@visa/cli 3.0.0-rc.0 → 3.0.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
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Lm=Object.create;var oo=Object.defineProperty;var Um=Object.getOwnPropertyDescriptor;var Dm=Object.getOwnPropertyNames;var jm=Object.getPrototypeOf,Fm=Object.prototype.hasOwnProperty;var Vm=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var za=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Os=(e,t)=>{for(var n in t)oo(e,n,{get:t[n],enumerable:!0})},Ja=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Dm(t))!Fm.call(e,o)&&o!==n&&oo(e,o,{get:()=>t[o],enumerable:!(r=Um(t,o))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?Lm(jm(e)):{},Ja(t||!e||!e.__esModule?oo(n,"default",{value:e,enumerable:!0}):n,e)),qm=e=>Ja(oo({},"__esModule",{value:!0}),e);var dr=za((Yv,tp)=>{tp.exports={name:"@visa/cli",version:"3.0.0
|
|
1
|
+
"use strict";var Lm=Object.create;var oo=Object.defineProperty;var Um=Object.getOwnPropertyDescriptor;var Dm=Object.getOwnPropertyNames;var jm=Object.getPrototypeOf,Fm=Object.prototype.hasOwnProperty;var Vm=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var za=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Os=(e,t)=>{for(var n in t)oo(e,n,{get:t[n],enumerable:!0})},Ja=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Dm(t))!Fm.call(e,o)&&o!==n&&oo(e,o,{get:()=>t[o],enumerable:!(r=Um(t,o))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?Lm(jm(e)):{},Ja(t||!e||!e.__esModule?oo(n,"default",{value:e,enumerable:!0}):n,e)),qm=e=>Ja(oo({},"__esModule",{value:!0}),e);var dr=za((Yv,tp)=>{tp.exports={name:"@visa/cli",version:"3.0.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.3","@typescript-eslint/eslint-plugin":"^8.61.1","@typescript-eslint/parser":"^8.61.1","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.4","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});var Fr=za(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.micros=oy;ue.fromCents=sy;ue.fromUsdc=iy;ue.fromUsd=ay;ue.toCents=cy;ue.toCentsForAcquirer=ly;ue.toUsdc=uy;ue.toWire=dy;ue.fromWire=my;ue.toDisplay=py;ue.toUsdRounded2dp=fy;ue.add=gy;ue.sub=hy;ue.clampNonNegative=yy;ue.isNonNegative=_y;ue.max=by;ue.min=vy;var xt=10000n,td=1000000n;function oy(e){return e}function sy(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*xt}function iy(e){return e}function ay(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function cy(e){if(e>=0n)return Number(e/xt);let t=e/xt,n=e%xt;return Number(n===0n?t:t-1n)}function ly(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/xt)}function uy(e){return e}function dy(e){return e.toString()}function my(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 py(e,t={}){let n=t.decimals??2,r=t.symbol??"$",o=e<0n,s=o?-e:e,i=s/td,a=s%td,c=o?"-":"";if(n===0)return`${c}${r}${i.toString()}`;let l=a.toString().padStart(6,"0").slice(0,n);return`${c}${r}${i.toString()}.${l}`}function fy(e){let t=e<0n,n=t?-e:e,r=n/xt,s=n%xt*2n,i;s<xt?i=r:s>xt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function gy(e,t){return e+t}function hy(e,t){return e-t}function yy(e){return e<0n?0n:e}function _y(e){return e>=0n}function by(e,t){return e>t?e:t}function vy(e,t){return e<t?e:t}});var Ss={};Os(Ss,{initSentry:()=>Qb,isSentryConfigured:()=>Zb,reportFatal:()=>ev});function Zb(){return!1}async function Qb(){return null}async function ev(e,t){process.exit(t?.exitCode??1)}var xs=Vm(()=>{});var Bv={};Os(Bv,{printGroupHelpAndExit:()=>Je});module.exports=qm(Bv);var hm=require("commander"),Ts=T(require("crypto")),X=T(require("fs")),J=T(require("os")),De=T(require("path")),ym=require("child_process"),Na=require("node:readline/promises"),_m=require("util");var ao=require("child_process"),sc=require("util"),Rt=T(require("fs")),co=T(require("os")),js=T(require("path"));var Qa=T(require("crypto"));var dt="e9501a252b778bce5a3d77710667afdd9198a750d1d989d95fb32d80e485bf15";var ec="VISA_ALLOW_INSECURE_MOCKS",Ya,Xa,Za;function Ms(e){return`${e}-${Qa.randomBytes(24).toString("base64url")}`}function tc(e=process.env){return e.NODE_ENV==="test"||e[ec]==="true"}function Et(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&tc(e)}function On(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&tc(e)}function Ns(){return`Set ${ec}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function nc(){return Ya??=Ms("mock-session"),Ya}function rc(e=process.env){return e.NODE_ENV==="test"?dt:(Xa??=Ms("mock-rc"),Xa)}function oc(){return Za??=Ms("mock-signature"),Za}var Ye=(0,sc.promisify)(ao.execFile),Fs=js.join(co.homedir(),".visa-mcp"),ur=js.join(Fs,"session-token"),Pe="visa-cli",At="session-token",so="rc-access",Bm=5e3,io=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Hm(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
|
|
2
2
|
`)}function ic(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Hm(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function Km(){try{let{stdout:e}=await Ye("security",["find-generic-password","-s",Pe,"-a",At,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(ic(e))throw new io("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 Gm(e){try{try{await Ye("security",["delete-generic-password","-s",Pe,"-a",At],{timeout:5e3})}catch{}return await Ye("security",["add-generic-password","-s",Pe,"-a",At,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Wm(){try{await Ye("security",["delete-generic-password","-s",Pe,"-a",At],{timeout:5e3})}catch{}}async function zm(){if(!Vs())return null;try{let{stdout:e}=await Ye("secret-tool",["lookup","service",Pe,"account",At],{timeout:5e3});return e.trim()||null}catch{return null}}async function Jm(e){if(!Vs())return!1;try{let t=(0,ao.execFile)("secret-tool",["store","--label",`${Pe} ${At}`,"service",Pe,"account",At]);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"))},Bm))]),!0):!1}catch{return!1}}async function Ym(){if(Vs())try{await Ye("secret-tool",["clear","service",Pe,"account",At],{timeout:5e3})}catch{}}function Vs(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Xm(){try{let{stdout:e}=await Ye("security",["find-generic-password","-s",Pe,"-a",so,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Zm(e){try{try{await Ye("security",["delete-generic-password","-s",Pe,"-a",so],{timeout:5e3})}catch{}await Ye("security",["add-generic-password","-s",Pe,"-a",so,"-w",e],{timeout:5e3})}catch{}}async function Qm(){try{await Ye("security",["delete-generic-password","-s",Pe,"-a",so],{timeout:5e3})}catch{}}function Us(){try{return Rt.readFileSync(ur,"utf-8").trim()||null}catch(e){if(ic(e))throw new io(`Unable to read Visa CLI credentials from ${ur}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function ac(e){Rt.mkdirSync(Fs,{recursive:!0,mode:448}),Rt.writeFileSync(ur,e,{mode:384}),process.platform==="win32"&&ep(ur)}function Ds(){try{Rt.unlinkSync(ur)}catch{}}function ep(e){try{let t=co.userInfo().username;(0,ao.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},n=>{n&&console.error(`[visa-cli] icacls ACL restriction failed: ${n.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function Ls(){switch(process.platform){case"darwin":return{get:Km,store:Gm,delete:Wm};case"linux":return{get:zm,store:Jm,delete:Ym};default:return{get:async()=>Us(),store:async e=>{try{return ac(e),!0}catch{return!1}},delete:async()=>Ds(),storesInSessionFile:!0}}}var V=class{static async getSessionToken(){if(Et())return Promise.resolve(nc());let t=Ls(),n=await t.get();if(n)return n;let r=Us();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(Et())return;let n=Ls();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||Ds();return}await n.delete()}if(ac(t),Us()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Fs} is writable.`))}static async getRcAccessToken(){return Et()?rc():Xm()}static async saveRcAccessToken(t){Et()||await Zm(t)}static async deleteSessionToken(){if(Et())return;await Ls().delete(),Ds()}static async clearAll(){await this.deleteSessionToken(),await Qm()}};var lo=T(require("crypto")),uo=T(require("tty")),mo=T(require("fs"));function np(e){return/-rc\.|-beta\./.test(e)}function qs(e){return lo.createHash("sha256").update(e.trim()).digest("hex")}function cc(e){return dt==="SKIP"?!0:lo.timingSafeEqual(Buffer.from(qs(e)),Buffer.from(dt))}function rp(){try{let e=mo.openSync("/dev/tty","r+"),t=new uo.ReadStream(e),n=new uo.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{mo.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 op(e){return new Promise((t,n)=>{let r;try{r=rp()}catch(u){n(u);return}let{input:o,output:s,cleanupStreams:i}=r,a=()=>{o.off("data",l);try{o.setRawMode?.(!1)}catch{}i()};s.write(e),o.setRawMode?.(!0),o.resume(),o.setEncoding("utf8");let c="",l=u=>{u==="\r"||u===`
|
|
3
3
|
`?(s.write(`
|
|
4
4
|
`),a(),t(c)):u===""?(s.write(`
|
|
@@ -101,7 +101,7 @@ ${y}`:m}function Np(e){let t=` ${W("\u2502",K.chrome)} `,n=[];if(typeof e.spentT
|
|
|
101
101
|
`)}catch{}}function Dc(){try{let e=Sr();if(!e)return;let t={...e,renderedAt:0};Dn(Ot(),JSON.stringify(t)+`
|
|
102
102
|
`)}catch{}}function nn(){try{B.unlinkSync(Pc())}catch{}}function Sr(){let e=Ot();if(!B.existsSync(e))return null;try{let t=JSON.parse(B.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&ko(t.line)?null:t}catch{return null}}function ko(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 jc(){return Sr()?.status??null}function qp(){if(process.env.JEST_WORKER_ID)return;let e=Pc();try{if(B.mkdirSync(H.dirname(e),{recursive:!0}),!Yp(e))return;let t=process.argv[1]?H.resolve(process.argv[1]):"";if(!t){nn();return}let n=yo(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),o=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},s=(0,Ic.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...o,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});s.once("error",nn),s.unref()}catch{nn()}}function Mt(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}var Bp=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function Hp(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,Zs.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,s=>{if(!Bp.test(s))return"";let i=`${n}${t.length}__`;return t.push(s),i}),o=new RegExp(`${n}(\\d+)__`,"g");return Mt(r).replace(o,(s,i)=>t[Number(i)]??"")}function Kp(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${W(r||"",K.green)}${W(o||"",K.chrome)}`}function Un(e){return`$${e.toFixed(2)}`}function Gp(e){let t=e;if(t.startsWith("/")&&(t=t.replace(/^\/(?:api\/)?v\d+\/fal\//,""),t=t.replace(/^\/(?:api\/)?v\d+\/(?:shortcuts|openrouter)\//,""),t.startsWith("/"))){let o=t.split("/").filter(Boolean);t=o[o.length-1]||t}return t=t.replace(/^fal-ai\//,""),t=t.replace(/^fal-/,""),t=t.replace(/^or-/,""),t=t.split("/").filter(Boolean).map(o=>o.replace(/^v\d+(?:\.\d+)?-?/,"")||null).filter(o=>o!==null&&o.length>0).join(" "),t=t.replace(/_card$/,""),t.length>28&&(t=t.slice(0,28).trimEnd()),t||e}function Wp(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=Mt(n.toUpperCase()),s=Mt(r);return`${t.isDefault?"default":"active"} ${o} ****${s}`}var K={get reset(){return _e().reset},get visaBlue(){return _e().visaBlue},get visaBlueSoft(){return _e().visaBlueSoft},get visaGold(){return _e().visaGold},get green(){return _e().green},get muted(){return _e().muted},get chrome(){return _e().chrome}};function W(e,t){return e.length===0||process.env.NO_COLOR||_o()?e:`${t}${e}${K.reset}`}function Rc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ni(){let e=rn.homedir();if(!e||!H.isAbsolute(e))throw new Error("unable to determine a valid home directory");return H.resolve(e)}function zp(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Jp(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Yp(e){for(let t=0;t<2;t+=1){let n;try{return n=B.openSync(e,"wx"),B.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=B.statSync(e);if(Date.now()-o.mtimeMs<=Rp)return!1;B.unlinkSync(e)}catch{}}finally{n!==void 0&&B.closeSync(n)}}return!1}function Xs(e){return e instanceof Error?e.message:"unknown file system error"}function Dn(e,t){B.mkdirSync(H.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,Zs.randomBytes)(8).toString("hex")}.tmp`;try{B.writeFileSync(n,t),B.renameSync(n,e)}catch(r){try{B.unlinkSync(n)}catch{}throw r}}var Xp=1440*60*1e3;function To(e,t){de.mkdirSync(we.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${qc.randomBytes(8).toString("hex")}.tmp`;try{de.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
104
|
-
`),de.renameSync(n,e)}catch(r){try{de.unlinkSync(n)}catch{}throw r}}function Fc(e){return`'${e.replace(/'/g,"'\\''")}'`}var oi="# visa-cli-hud-v1";function Eo(e,t){if(!e&&!t&&Zp())return`visa-cli config statusline ${oi}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?we.resolve(r):"";return`${o?`${Fc(n)} ${Fc(o)} config statusline`:"visa-cli config statusline"} ${oi}`}function Zp(){try{return(0,Bc.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Nt(e){return typeof e!="string"?!1:e.includes(oi)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Qp(){return"3.0.0
|
|
104
|
+
`),de.renameSync(n,e)}catch(r){try{de.unlinkSync(n)}catch{}throw r}}function Fc(e){return`'${e.replace(/'/g,"'\\''")}'`}var oi="# visa-cli-hud-v1";function Eo(e,t){if(!e&&!t&&Zp())return`visa-cli config statusline ${oi}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?we.resolve(r):"";return`${o?`${Fc(n)} ${Fc(o)} config statusline`:"visa-cli config statusline"} ${oi}`}function Zp(){try{return(0,Bc.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Nt(e){return typeof e!="string"?!1:e.includes(oi)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Qp(){return"3.0.0"}function Ao(e){let t=we.dirname(we.resolve(e));return we.basename(t)===".claude"?we.dirname(t):Hc.homedir()}function Co(e,t){let n=we.relative(t,e);return!n.startsWith("..")&&!we.isAbsolute(n)?`~/${n}`:e}function ef(e){return we.join(Ao(e),".visa-cli","hud-self-heal.json")}function tf(e,t,n,r){try{if(!de.existsSync(e))return!1;let o=JSON.parse(de.readFileSync(e,"utf-8"));return o.version===t&&typeof o.checkedAt=="number"&&n-o.checkedAt<r}catch{return!1}}function ri(e,t,n){try{To(e,{version:t,checkedAt:n})}catch{}}function nf(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function si(e,t={}){let n=t.now??Date.now(),r=t.version??Qp(),o=t.stampPath??ef(e),s=t.minIntervalMs??Xp,i=[],a=!1,c=!1;if(!t.force&&tf(o,r,n,s))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!de.existsSync(e))return ri(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(de.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!Nt(d))return ri(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let p=(t.getCommand??Eo)();if(d!==p&&(l.statusLine=nf(u,p),To(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!Ro()){let m=Ao(e);if(on(m).length>0){let y=mt(null,m);if(y.removed&&y.rcPaths&&y.rcPaths.length>0){let w=y.rcPaths.map(N=>Co(N,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${w}.`)}}}return ri(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}catch(l){if(t.force){let u=l instanceof Error?l.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${u}. Run: visa-cli config hud doctor
|
|
105
105
|
`)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function rf(e,t){let n=Ao(t),r=on(n);if(r.length===0)return e;let o=r.map(s=>Co(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 Ro(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 Vc(e,t){let n=Ao(t),r=on(n);if(r.length===0)return e;let o=r.map(i=>Co(i,n)).join(", ");if(Ro())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=mt(null,n);if(s.removed&&s.rcPaths&&s.rcPaths.length>0){let i=s.rcPaths.map(a=>Co(a,n)).join(", ");return`${e}
|
|
@@ -123,7 +123,7 @@ ${a}`}function mf(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)
|
|
|
123
123
|
`)}
|
|
124
124
|
`}function wl(e){return e.json===!0||e.isTTY!==!0}function mi(e){if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--daily-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e4)throw new Error("--daily-cap must be between 1 and 100 USD.");return n}function pi(e){if(e===!1)return null;if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--total-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e6)throw new Error("--total-cap must be between 1 and 10000 USD.");return n}function Sl(e,t){let n=mi(e);if(n!==void 0)return n;if(wl(t))return 500}function xl(e,t){let n=pi(e);if(n!==void 0)return n;if(wl(t)||t.recommendedCapsAccepted===!0)return 2500}async function Ze(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 an=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Fn=class extends Error{code;budgetId;status;constructor(t,n,r={}){super(t),this.name="SessionInvalidError",this.code=n,this.budgetId=r.budgetId,this.status=r.status}},gt=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,n=1,r){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=n,this.status=r}},Qe=class extends Error{code="PARENTLESS_NOT_ENABLED";status;serverErrorCode;constructor(t,n={}){super(t),this.name="ParentlessNotEnabledError",this.status=n.status,this.serverErrorCode=n.serverErrorCode}},oe=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,o,s,i,a,c){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=o,this.paymentErrorClass=s,this.correlationId=i,this.transactionId=a,this.retryAfter=c}},et=class extends Error{code;transactionId;retryable;reconciliationRequired;constructor(t,n,r={}){super(t),this.name="TopupAmbiguousError",this.code=n,this.transactionId=r.transactionId,this.retryable=r.retryable??!1,this.reconciliationRequired=r.reconciliationRequired??!0}};var kl={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 Vn(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&&kl[n]?kl[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 xe=T(require("fs")),hi=T(require("path")),Cl=T(require("os")),gi=hi.join(Cl.homedir(),".visa-mcp"),Er=hi.join(gi,"mcp-server.log"),kf=5*1024*1024,fi=null;function Cf(){xe.existsSync(gi)||xe.mkdirSync(gi,{recursive:!0,mode:448})}function Tf(){if(!fi){if(Cf(),xe.existsSync(Er)&&xe.statSync(Er).size>kf){let t=Er+".1";xe.existsSync(t)&&xe.unlinkSync(t),xe.renameSync(Er,t)}fi=xe.createWriteStream(Er,{flags:"a"})}return fi}function Ef(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function Oo(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}
|
|
125
125
|
`;Ef(e)&&process.stderr.write(o),Tf().write(o)}var f={debug:(...e)=>Oo("DEBUG",...e),info:(...e)=>Oo("INFO",...e),warn:(...e)=>Oo("WARN",...e),error:(...e)=>Oo("ERROR",...e)};var Af=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function El(e,t){let n=Tl(e),r=Tl(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:Rf(n.pre,r.pre)>0}function Tl(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Af);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Rf(e,t){let n=e.split("."),r=t.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let i=n[s],a=r[s],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function tt(){return!!(Al(process.env.VISA_CLI_NO_UPDATE_CHECK)||Al(process.env.CI)||process.env.NODE_ENV==="test")}function Al(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Ut=T(require("fs")),vi=require("node:net"),Pl=T(require("os")),Ol=T(require("path"));var Mo=T(require("fs")),Rl=T(require("path")),Il=T(require("os"));var yi=Rl.join(Il.homedir(),".visa-mcp"),Ar=class{static ensureConfigDir(){Mo.existsSync(yi)||Mo.mkdirSync(yi,{recursive:!0,mode:448})}static getConfigDir(){return yi}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 $l(e){let t=Pl.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var If="settings.json",$f="must use https unless it points at localhost/loopback for local development";function Rr(){return Ol.join(Ar.getConfigDir(),If)}function Ml(e){if((0,vi.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Pf(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 Ml(o)}function Of(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,vi.isIP)(t);return n===4?Ml(t):n===6?t==="::1"||Pf(t):!1}function _i(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:"&&Of(n.hostname)))throw new Error(`${t} ${$f}`)}var Dt={"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");_i(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)")}}},wi=500,No={"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 cn(){let e=Rr();if(!Ut.existsSync(e))return{};try{let t=Ut.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(f.warn("settings:corrupt",{path:$l(e),reason:"not_object"}),{}):n}catch(t){return f.warn("settings:corrupt",{path:$l(e),error:t?.message||String(t)}),{}}}function bi(e){Ar.ensureConfigDir();let t=Rr(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
|
|
126
|
-
`;Ut.writeFileSync(n,r,{mode:384}),Ut.renameSync(n,t)}function Si(e){let t=cn()[e];return typeof t=="string"?t:void 0}function Lo(e){let t=cn()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function xi(e){let t=cn()[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 ht=class extends Error{constructor(t){let n=Object.keys(Dt).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"}},yt=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"}},Lt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+No[t]),this.name="RetiredSettingKeyError"}},Nl=["biometric.","spending.","account.","cards.","biometric"];function Uo(e,t){if(Nl.some(s=>e.startsWith(s)))throw new yt(e);if(e in No)throw new Lt(e);let n=Dt[e];if(!n)throw new ht(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=cn();return o[e]=r,bi(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Rr()}}function Do(e){if(Nl.some(s=>e.startsWith(s)))throw new yt(e);let t=Dt[e];if(e in No){let s=cn(),i=e in s;return i&&(delete s[e],bi(s)),{key:e,removed:i,requiresRestart:!1,path:Rr()}}if(!t)throw new ht(e);let r=cn(),o=e in r;return o&&(delete r[e],bi(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:Rr()}}function Ll(){let e=cn();return Object.entries(No).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var Mf="https://auth.visacli.sh",Nf="https://auth-visa-code-preview.up.railway.app";function Lf(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Uf(){try{let e=dr();return Lf(e.version)}catch{return!1}}function Df(e){return e.envVar!==void 0&&e.envVar!==""?(_i(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(_i(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Nf:Mf}function Ee(){return Df({envVar:process.env.VISA_AUTH_URL,settingValue:Si("auth.serverUrl"),isPrerelease:Uf()})}function Ul(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Lo("ui.suppressBrowser")??!1}function Dl(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Lo("ui.suppressFeed")??!1}function jl(){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=xi("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):wi}var jf="CARD_REENROLLMENT_REQUIRED",Ff="https://auth.visacli.sh/enroll-card";function Vf(){try{return new URL("/enroll-card",Ee()).toString()}catch{return Ff}}function qf(e){let t=Vf();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 f.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var jt="3.0.0
|
|
126
|
+
`;Ut.writeFileSync(n,r,{mode:384}),Ut.renameSync(n,t)}function Si(e){let t=cn()[e];return typeof t=="string"?t:void 0}function Lo(e){let t=cn()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function xi(e){let t=cn()[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 ht=class extends Error{constructor(t){let n=Object.keys(Dt).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"}},yt=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"}},Lt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+No[t]),this.name="RetiredSettingKeyError"}},Nl=["biometric.","spending.","account.","cards.","biometric"];function Uo(e,t){if(Nl.some(s=>e.startsWith(s)))throw new yt(e);if(e in No)throw new Lt(e);let n=Dt[e];if(!n)throw new ht(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=cn();return o[e]=r,bi(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Rr()}}function Do(e){if(Nl.some(s=>e.startsWith(s)))throw new yt(e);let t=Dt[e];if(e in No){let s=cn(),i=e in s;return i&&(delete s[e],bi(s)),{key:e,removed:i,requiresRestart:!1,path:Rr()}}if(!t)throw new ht(e);let r=cn(),o=e in r;return o&&(delete r[e],bi(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:Rr()}}function Ll(){let e=cn();return Object.entries(No).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var Mf="https://auth.visacli.sh",Nf="https://auth-visa-code-preview.up.railway.app";function Lf(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Uf(){try{let e=dr();return Lf(e.version)}catch{return!1}}function Df(e){return e.envVar!==void 0&&e.envVar!==""?(_i(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(_i(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Nf:Mf}function Ee(){return Df({envVar:process.env.VISA_AUTH_URL,settingValue:Si("auth.serverUrl"),isPrerelease:Uf()})}function Ul(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Lo("ui.suppressBrowser")??!1}function Dl(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Lo("ui.suppressFeed")??!1}function jl(){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=xi("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):wi}var jf="CARD_REENROLLMENT_REQUIRED",Ff="https://auth.visacli.sh/enroll-card";function Vf(){try{return new URL("/enroll-card",Ee()).toString()}catch{return Ff}}function qf(e){let t=Vf();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 f.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var jt="3.0.0",Bf=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;function Hf(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}function ki(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var Kf="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function qn(e){return typeof e=="string"?e.trim():""}function Ir(e){let t=e&&typeof e=="object"?e:{},n=qn(t.error)||qn(t.message);if(!n)return Kf;let r=qn(t.error_code),o=[["surface",qn(t.disabled_surface)],["flag",qn(t.flag)],["correlation_id",qn(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 $r(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?Bf.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected VisaKey_<...> or legacy vk_<...>)."),n.push("Create a new Visa Key with: visa-cli keys 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(`
|
|
127
127
|
`)}var Ae=class{constructor(t){this.getSessionToken=t;this.baseUrl=Ee()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!tt()){let r=t.headers.get("X-Latest-Version");r&&El(r,jt)&&(this.lastSignals.updateAvailable={currentVersion:jt,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return jt}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new an(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(Ir(n))}async request(t,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error($r());let c={Authorization:`Bearer ${a}`};s&&(t==="GET"?c["X-User-Context"]=encodeURIComponent(s.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:s}),i&&(c["X-Visa-Meta-Tool"]=i),r&&(c["Content-Type"]="application/json");let l;try{l=await Ze(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":jt,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(Vn(d))}if(this.parseServerSignals(l),l.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(l.status===429){let d=l.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}l.status===503&&await this.throwServerUnavailable(l);let u;try{u=await l.json()}catch{throw l.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!l.ok){if(l.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(u),typeof u?.error_code=="string"&&u.error_code===jf){let p=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",g=qf(u?.reenroll_url),y=p?`${m} ending in ${p}`:"your card";throw new Error(`Please re-add ${y} to keep payments running. Open: ${g}`)}let d=ki(u?.error_code);if(d)throw new et(u?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",d,{transactionId:typeof u?.transactionId=="string"?u.transactionId:void 0,retryable:!!u?.retryable,reconciliationRequired:u?.reconciliation_required!==!1});if(u?.declined){let p=Number(u.retryAfter??l.headers.get("Retry-After"));throw new oe(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(p)&&p>0?p:void 0)}if(l.status===402){let p=u?.error||"Gateway returned 402",m=typeof u?.error_code=="string"?u.error_code:"";throw m==="SPENDING_LIMIT_EXCEEDED"||m==="DAILY_LIMIT_EXCEEDED"||m==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${p}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(p)}throw new Error(u?.error||`Request failed (${l.status}). Try again.`)}return u}async shortcut(t,n,r,o,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,o,s)}async shortcutWithSession(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error($r());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":jt,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...n,...r};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Ze(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(g){throw new Error(Vn(g))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let g=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${g}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let w=Number(d.headers.get("Retry-After"))||1;throw new gt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",w,d.status)}throw new Error(Ir(m))}let g=Hf(m?.error_code);if(g||d.status===410){let w=g??"BUDGET_CLOSED";throw new Fn(m?.message||m?.error||"Your session was invalidated by the server.",w,{budgetId:n.session_budget_id,status:d.status})}if(m?.declined){let w=Number(m.retryAfter??d.headers.get("Retry-After"));throw new oe(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(w)&&w>0?w:void 0)}let y=ki(m?.error_code);throw y?new et(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",y,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:p}}async shortcutParentless(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error($r());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":jt,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...r,...n.attestation?{attestation:n.attestation}:{},nonce:n.nonce,approved_max_cents:n.approved_max_cents,idempotency_key:n.idempotency_key,...n.stream===!0?{stream:!0}:{}};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Ze(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(g){throw new Error(Vn(g))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let g=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${g}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):d.status===404?new Qe("Parentless single-call is not available on this server.",{status:404}):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.`);this.throwIfAttestationDrift(m);let g=typeof m?.error_code=="string"?m.error_code:void 0;if(d.status===404||d.status===410&&g==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new Qe(m?.error||"Parentless single-call is not enabled on this server.",{status:d.status,serverErrorCode:g});if(d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let w=Number(d.headers.get("Retry-After"))||1;throw new gt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",w,d.status)}throw new Error(Ir(m))}if(m?.declined){let w=Number(m.retryAfter??d.headers.get("Retry-After"));throw new oe(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(w)&&w>0?w:void 0)}let y=ki(m?.error_code);throw y?new et(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",y,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:p}}async batchOpen(t){let n="/v1/batch/open",r=await this.getSessionToken();if(!r)throw new Error($r());let o={Authorization:`Bearer ${r}`,"X-Visa-CLI-Version":jt,"X-Source":"cli","Content-Type":"application/json"},s={...t.attestation?{attestation:t.attestation}:{},nonce:t.nonce,approved_total_cents:t.approved_total_cents,batch_id:t.batch_id},i;try{i=await Ze(`${this.baseUrl}${n}`,{method:"POST",headers:o,body:JSON.stringify(s),timeoutMs:void 0})}catch(u){throw new Error(Vn(u))}if(this.parseServerSignals(i),i.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(i.status===429){let u=i.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${u}s before opening another batch.`)}let a;try{a=await i.json()}catch{throw i.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):i.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):i.status===404?new Qe("Parentless batch is not available on this server.",{status:404}):new Error(`Unexpected response from ${n}. Try again.`)}if(!i.ok){if(i.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);this.throwIfAttestationDrift(a);let u=typeof a?.error_code=="string"?a.error_code:void 0;if(i.status===404||i.status===410&&u==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new Qe(a?.error||"Parentless batch is not enabled on this server.",{status:i.status,serverErrorCode:u});if(i.status===503)throw new Error(Ir(a));if(a?.declined){let d=Number(a.retryAfter??i.headers.get("Retry-After"));throw new oe(a.error||"Your card was declined.",!!a.retryable,a.code,a.reason,a.payment_error_class,a.correlation_id,a.transactionId,Number.isFinite(d)&&d>0?d:void 0)}throw new Error(a?.error||`Request failed (${i.status}). Try again.`)}let c=a?.parent_spend_execution_id??a?.batch_parent_id??a?.parent_id??a?.spend_execution_id,l=a?.idempotency_scope??a?.idempotency_key_scope??t.batch_id;if(typeof c!="string"||c.length===0)throw new Error(`Batch open returned no parent id from ${n}. Try again.`);return{batch_parent_id:c,idempotency_scope:String(l)}}async shortcutParentlessBatchItem(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error($r());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":jt,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...r,batch_parent_id:n.batch_parent_id,batch_id:n.batch_id,batch_index:n.batch_index,batch_request_hash:n.batch_request_hash,item_ceiling_cents:n.item_ceiling_cents,idempotency_key:n.idempotency_key,...n.stream===!0?{stream:!0}:{}};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Ze(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(g){throw new Error(Vn(g))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let g=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${g}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let g=Number(d.headers.get("Retry-After"))||1;throw new gt(m?.message||m?.error||"Batch parent is being modified by another request. Retry shortly.",g,d.status)}throw new Error(Ir(m))}if(m?.declined){let g=Number(m.retryAfter??d.headers.get("Retry-After"));throw new oe(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(g)&&g>0?g:void 0)}throw new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:p}}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 Ze(`${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 Ze(`${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(t){let n=new URLSearchParams;t?.limit!=null&&n.set("limit",String(t.limit)),t?.startingAfter!=null&&n.set("starting_after",String(t.startingAfter)),t?.endingBefore!=null&&n.set("ending_before",String(t.endingBefore));let r=n.toString();return this.request("GET",r?`/v1/api/keys?${r}`:"/v1/api/keys")}async listAllAppApiKeys(){let t=[],n=new Set,r,o=null,s=0;for(;;){let i=await this.listAppApiKeys({limit:100,...r!==void 0?{startingAfter:r}:{}});if(s+=1,o=i,t.push(...i.keys??[]),!i.has_more)break;if(i.next_cursor==null)throw new Error("API key pagination response did not include next_cursor.");if(n.has(i.next_cursor))throw new Error("API key pagination cursor did not advance.");n.add(i.next_cursor),r=i.next_cursor}return{...o??{success:!0,keys:[]},keys:t,limit:100,has_more:!1,next_cursor:null,previous_cursor:null,pages:s}}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)}};function Pr(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function Vl(e){let t=e.inputSchema?.properties;return t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).join(", ")||"none":Object.keys(e.inputSchema||{}).join(", ")||"none"}function Fl(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function Gf(e){let t=new Map;for(let n of e){let r=n.category||"other",o=t.get(r)??[];o.push(n),t.set(r,o)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function Wf(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function zf(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function Jf(e,t,n){let r=typeof process.stdout.columns=="number"&&process.stdout.columns>0?process.stdout.columns:100;return Math.max(16,r-(e+t+n+10))}function ql(e){let t=Wf(e),n=7,r=zf(e),o=Jf(t,n,r);console.log(` ${"Tool".padEnd(t)} ${"Price".padEnd(n)} ${"Category".padEnd(r)} Params`),console.log(` ${"\u2500".repeat(t)} ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(Math.min(o,32))}`);for(let s of e)console.log(` ${s.id.padEnd(t)} ${Pr(s.priceCents,s.priceDisplay).padEnd(n)} ${Fl(s.category||"other",r).padEnd(r)} ${Fl(Vl(s),o)}`)}function Bl(e){console.log(`
|
|
128
128
|
Merchant tools
|
|
129
129
|
`),ql(e),console.log("\nUse `visa-cli describe <tool>` for full details (incl. parameter types)."),console.log('Shortcut: `visa-cli generate image "a lobster"`\n')}function Ci(e){console.log(`
|
|
@@ -133,9 +133,9 @@ Merchant tools
|
|
|
133
133
|
${e} tools
|
|
134
134
|
`),ql(t),console.log("\nUse `visa-cli describe <tool>` for full details (incl. parameter types)."),console.log(`Or scope it: \`visa-cli merchants ${e} describe <tool>\`
|
|
135
135
|
`)}var h={};Os(h,{BRAND:()=>wg,DIRTY:()=>ln,EMPTY_PATH:()=>Qf,INVALID:()=>P,NEVER:()=>sh,OK:()=>be,ParseStatus:()=>ge,Schema:()=>j,ZodAny:()=>qt,ZodArray:()=>wt,ZodBigInt:()=>dn,ZodBoolean:()=>mn,ZodBranded:()=>Mr,ZodCatch:()=>xn,ZodDate:()=>pn,ZodDefault:()=>Sn,ZodDiscriminatedUnion:()=>Vo,ZodEffects:()=>Ne,ZodEnum:()=>vn,ZodError:()=>ke,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>Bo,ZodIntersection:()=>yn,ZodIssueCode:()=>b,ZodLazy:()=>_n,ZodLiteral:()=>bn,ZodMap:()=>zn,ZodNaN:()=>Yn,ZodNativeEnum:()=>wn,ZodNever:()=>Fe,ZodNull:()=>gn,ZodNullable:()=>ot,ZodNumber:()=>un,ZodObject:()=>Ce,ZodOptional:()=>Oe,ZodParsedType:()=>k,ZodPipeline:()=>Nr,ZodPromise:()=>Bt,ZodReadonly:()=>kn,ZodRecord:()=>qo,ZodSchema:()=>j,ZodSet:()=>Jn,ZodString:()=>Vt,ZodSymbol:()=>Gn,ZodTransformer:()=>Ne,ZodTuple:()=>rt,ZodType:()=>j,ZodUndefined:()=>fn,ZodUnion:()=>hn,ZodUnknown:()=>vt,ZodVoid:()=>Wn,addIssueToContext:()=>S,any:()=>Ig,array:()=>Mg,bigint:()=>Cg,boolean:()=>tu,coerce:()=>oh,custom:()=>Zl,date:()=>Tg,datetimeRegex:()=>Yl,defaultErrorMap:()=>_t,discriminatedUnion:()=>Dg,effect:()=>Yg,enum:()=>Wg,function:()=>Hg,getErrorMap:()=>Bn,getParsedType:()=>nt,instanceof:()=>xg,intersection:()=>jg,isAborted:()=>jo,isAsync:()=>Hn,isDirty:()=>Fo,isValid:()=>Ft,late:()=>Sg,lazy:()=>Kg,literal:()=>Gg,makeIssue:()=>Or,map:()=>qg,nan:()=>kg,nativeEnum:()=>zg,never:()=>Pg,null:()=>Rg,nullable:()=>Zg,number:()=>eu,object:()=>Ng,objectUtil:()=>Ti,oboolean:()=>rh,onumber:()=>nh,optional:()=>Xg,ostring:()=>th,pipeline:()=>eh,preprocess:()=>Qg,promise:()=>Jg,quotelessJson:()=>Yf,record:()=>Vg,set:()=>Bg,setErrorMap:()=>Zf,strictObject:()=>Lg,string:()=>Ql,symbol:()=>Eg,transformer:()=>Yg,tuple:()=>Fg,undefined:()=>Ag,union:()=>Ug,unknown:()=>$g,util:()=>F,void:()=>Og});var F;(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})(F||(F={}));var Ti;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ti||(Ti={}));var k=F.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),nt=e=>{switch(typeof e){case"undefined":return k.undefined;case"string":return k.string;case"number":return Number.isNaN(e)?k.nan:k.number;case"boolean":return k.boolean;case"function":return k.function;case"bigint":return k.bigint;case"symbol":return k.symbol;case"object":return Array.isArray(e)?k.array:e===null?k.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?k.promise:typeof Map<"u"&&e instanceof Map?k.map:typeof Set<"u"&&e instanceof Set?k.set:typeof Date<"u"&&e instanceof Date?k.date:k.object;default:return k.unknown}};var b=F.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"]),Yf=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ke=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,F.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()}};ke.create=e=>new ke(e);var Xf=(e,t)=>{let n;switch(e.code){case b.invalid_type:e.received===k.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case b.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,F.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:n=`Unrecognized key(s) in object: ${F.joinValues(e.keys,", ")}`;break;case b.invalid_union:n="Invalid input";break;case b.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${F.joinValues(e.options)}`;break;case b.invalid_enum_value:n=`Invalid enum value. Expected ${F.joinValues(e.options)}, received '${e.received}'`;break;case b.invalid_arguments:n="Invalid function arguments";break;case b.invalid_return_type:n="Invalid function return type";break;case b.invalid_date:n="Invalid date";break;case b.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}"`:F.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case b.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 b.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 b.custom:n="Invalid input";break;case b.invalid_intersection_types:n="Intersection results could not be merged";break;case b.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case b.not_finite:n="Number must be finite";break;default:n=t.defaultError,F.assertNever(e)}return{message:n}},_t=Xf;var Kl=_t;function Zf(e){Kl=e}function Bn(){return Kl}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="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},Qf=[];function S(e,t){let n=Bn(),r=Or({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===_t?void 0:_t].filter(o=>!!o)});e.common.issues.push(r)}var ge=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 P;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 P;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}}},P=Object.freeze({status:"aborted"}),ln=e=>({status:"dirty",value:e}),be=e=>({status:"valid",value:e}),jo=e=>e.status==="aborted",Fo=e=>e.status==="dirty",Ft=e=>e.status==="valid",Hn=e=>typeof Promise<"u"&&e instanceof Promise;var E;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(E||(E={}));var Me=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}},Gl=(e,t)=>{if(Ft(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 ke(e.common.issues);return this._error=n,this._error}}};function L(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{let{message:c}=e;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}var j=class{get description(){return this._def.description}_getType(t){return nt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:nt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ge,ctx:{common:t.parent.common,data:t.data,parsedType:nt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Hn(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:nt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Gl(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:nt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return Ft(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=>Ft(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:nt(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Hn(o)?o:Promise.resolve(o));return Gl(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:b.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Ne({schema:this,typeName:M.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 Oe.create(this,this._def)}nullable(){return ot.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return wt.create(this)}promise(){return Bt.create(this,this._def)}or(t){return hn.create([this,t],this._def)}and(t){return yn.create(this,t,this._def)}transform(t){return new Ne({...L(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Sn({...L(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new Mr({typeName:M.ZodBranded,type:this,...L(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new xn({...L(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Nr.create(this,t)}readonly(){return kn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},eg=/^c[^\s-]{8,}$/i,tg=/^[0-9a-z]+$/,ng=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rg=/^[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,og=/^[a-z0-9_-]{21}$/i,sg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ig=/^[-+]?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)?)??$/,ag=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ei,lg=/^(?:(?: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])$/,ug=/^(?:(?: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])$/,dg=/^(([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]))$/,mg=/^(([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])$/,pg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zl="((\\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])))",gg=new RegExp(`^${zl}$`);function Jl(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 hg(e){return new RegExp(`^${Jl(e)}$`)}function Yl(e){let t=`${zl}T${Jl(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 yg(e,t){return!!((t==="v4"||!t)&&lg.test(e)||(t==="v6"||!t)&&dg.test(e))}function _g(e,t){if(!sg.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 bg(e,t){return!!((t==="v4"||!t)&&ug.test(e)||(t==="v6"||!t)&&mg.test(e))}var Vt=class e extends j{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==k.string){let s=this._getOrReturnCtx(t);return S(s,{code:b.invalid_type,expected:k.string,received:s.parsedType}),P}let r=new ge,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),S(o,{code:b.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),S(o,{code:b.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?S(o,{code:b.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&S(o,{code:b.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")ag.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"email",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Ei||(Ei=new RegExp(cg,"u")),Ei.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"emoji",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")rg.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"uuid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")og.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"nanoid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")eg.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"cuid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")tg.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"cuid2",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")ng.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"ulid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),S(o,{validation:"url",code:b.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),S(o,{validation:"regex",code:b.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),S(o,{code:b.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),S(o,{code:b.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),S(o,{code:b.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Yl(s).test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{code:b.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?gg.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{code:b.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?hg(s).test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{code:b.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?ig.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"duration",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?yg(t.data,s.version)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"ip",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?_g(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"jwt",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?bg(t.data,s.version)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"cidr",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?pg.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"base64",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?fg.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"base64url",code:b.invalid_string,message:s.message}),r.dirty()):F.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:b.invalid_string,...E.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...E.errToObj(t)})}url(t){return this._addCheck({kind:"url",...E.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...E.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...E.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...E.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...E.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...E.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...E.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...E.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...E.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...E.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...E.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...E.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,...E.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,...E.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...E.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...E.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...E.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...E.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...E.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...E.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...E.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...E.errToObj(n)})}nonempty(t){return this.min(1,E.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}};Vt.create=e=>new Vt({checks:[],typeName:M.ZodString,coerce:e?.coerce??!1,...L(e)});function vg(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 un=class e extends j{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)!==k.number){let s=this._getOrReturnCtx(t);return S(s,{code:b.invalid_type,expected:k.number,received:s.parsedType}),P}let r,o=new ge;for(let s of this._def.checks)s.kind==="int"?F.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),S(r,{code:b.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),S(r,{code:b.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),S(r,{code:b.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?vg(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),S(r,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),S(r,{code:b.not_finite,message:s.message}),o.dirty()):F.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,E.toString(n))}gt(t,n){return this.setLimit("min",t,!1,E.toString(n))}lte(t,n){return this.setLimit("max",t,!0,E.toString(n))}lt(t,n){return this.setLimit("max",t,!1,E.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:E.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:E.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:E.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:E.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:E.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:E.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:E.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:E.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:E.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:E.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"&&F.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)}};un.create=e=>new un({checks:[],typeName:M.ZodNumber,coerce:e?.coerce||!1,...L(e)});var dn=class e extends j{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)!==k.bigint)return this._getInvalidInput(t);let r,o=new ge;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),S(r,{code:b.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),S(r,{code:b.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),S(r,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):F.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return S(n,{code:b.invalid_type,expected:k.bigint,received:n.parsedType}),P}gte(t,n){return this.setLimit("min",t,!0,E.toString(n))}gt(t,n){return this.setLimit("min",t,!1,E.toString(n))}lte(t,n){return this.setLimit("max",t,!0,E.toString(n))}lt(t,n){return this.setLimit("max",t,!1,E.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:E.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:E.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:E.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:E.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:E.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:E.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}};dn.create=e=>new dn({checks:[],typeName:M.ZodBigInt,coerce:e?.coerce??!1,...L(e)});var mn=class extends j{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==k.boolean){let r=this._getOrReturnCtx(t);return S(r,{code:b.invalid_type,expected:k.boolean,received:r.parsedType}),P}return be(t.data)}};mn.create=e=>new mn({typeName:M.ZodBoolean,coerce:e?.coerce||!1,...L(e)});var pn=class e extends j{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==k.date){let s=this._getOrReturnCtx(t);return S(s,{code:b.invalid_type,expected:k.date,received:s.parsedType}),P}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return S(s,{code:b.invalid_date}),P}let r=new ge,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),S(o,{code:b.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),S(o,{code:b.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):F.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:E.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:E.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}};pn.create=e=>new pn({checks:[],coerce:e?.coerce||!1,typeName:M.ZodDate,...L(e)});var Gn=class extends j{_parse(t){if(this._getType(t)!==k.symbol){let r=this._getOrReturnCtx(t);return S(r,{code:b.invalid_type,expected:k.symbol,received:r.parsedType}),P}return be(t.data)}};Gn.create=e=>new Gn({typeName:M.ZodSymbol,...L(e)});var fn=class extends j{_parse(t){if(this._getType(t)!==k.undefined){let r=this._getOrReturnCtx(t);return S(r,{code:b.invalid_type,expected:k.undefined,received:r.parsedType}),P}return be(t.data)}};fn.create=e=>new fn({typeName:M.ZodUndefined,...L(e)});var gn=class extends j{_parse(t){if(this._getType(t)!==k.null){let r=this._getOrReturnCtx(t);return S(r,{code:b.invalid_type,expected:k.null,received:r.parsedType}),P}return be(t.data)}};gn.create=e=>new gn({typeName:M.ZodNull,...L(e)});var qt=class extends j{constructor(){super(...arguments),this._any=!0}_parse(t){return be(t.data)}};qt.create=e=>new qt({typeName:M.ZodAny,...L(e)});var vt=class extends j{constructor(){super(...arguments),this._unknown=!0}_parse(t){return be(t.data)}};vt.create=e=>new vt({typeName:M.ZodUnknown,...L(e)});var Fe=class extends j{_parse(t){let n=this._getOrReturnCtx(t);return S(n,{code:b.invalid_type,expected:k.never,received:n.parsedType}),P}};Fe.create=e=>new Fe({typeName:M.ZodNever,...L(e)});var Wn=class extends j{_parse(t){if(this._getType(t)!==k.undefined){let r=this._getOrReturnCtx(t);return S(r,{code:b.invalid_type,expected:k.void,received:r.parsedType}),P}return be(t.data)}};Wn.create=e=>new Wn({typeName:M.ZodVoid,...L(e)});var wt=class e extends j{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==k.array)return S(n,{code:b.invalid_type,expected:k.array,received:n.parsedType}),P;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(S(n,{code:i?b.too_big:b.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&&(S(n,{code:b.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&&(S(n,{code:b.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 Me(n,i,n.path,a)))).then(i=>ge.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Me(n,i,n.path,a)));return ge.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:E.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:E.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:E.toString(n)}})}nonempty(t){return this.min(1,t)}};wt.create=(e,t)=>new wt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...L(t)});function Kn(e){if(e instanceof Ce){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Oe.create(Kn(r))}return new Ce({...e._def,shape:()=>t})}else return e instanceof wt?new wt({...e._def,type:Kn(e.element)}):e instanceof Oe?Oe.create(Kn(e.unwrap())):e instanceof ot?ot.create(Kn(e.unwrap())):e instanceof rt?rt.create(e.items.map(t=>Kn(t))):e}var Ce=class e extends j{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=F.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==k.object){let l=this._getOrReturnCtx(t);return S(l,{code:b.invalid_type,expected:k.object,received:l.parsedType}),P}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Fe&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Me(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Fe){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(S(o,{code:b.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Me(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,p=await u.value;l.push({key:d,value:p,alwaysSet:u.alwaysSet})}return l}).then(l=>ge.mergeObjectSync(r,l)):ge.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return E.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:E.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:M.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 F.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 F.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return Kn(this)}partial(t){let n={};for(let r of F.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 F.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Oe;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return Xl(F.objectKeys(this.shape))}};Ce.create=(e,t)=>new Ce({shape:()=>e,unknownKeys:"strip",catchall:Fe.create(),typeName:M.ZodObject,...L(t)});Ce.strictCreate=(e,t)=>new Ce({shape:()=>e,unknownKeys:"strict",catchall:Fe.create(),typeName:M.ZodObject,...L(t)});Ce.lazycreate=(e,t)=>new Ce({shape:e,unknownKeys:"strip",catchall:Fe.create(),typeName:M.ZodObject,...L(t)});var hn=class extends j{_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 ke(a.ctx.common.issues));return S(n,{code:b.invalid_union,unionErrors:i}),P}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let l={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new ke(c));return S(n,{code:b.invalid_union,unionErrors:a}),P}}get options(){return this._def.options}};hn.create=(e,t)=>new hn({options:e,typeName:M.ZodUnion,...L(t)});var bt=e=>e instanceof _n?bt(e.schema):e instanceof Ne?bt(e.innerType()):e instanceof bn?[e.value]:e instanceof vn?e.options:e instanceof wn?F.objectValues(e.enum):e instanceof Sn?bt(e._def.innerType):e instanceof fn?[void 0]:e instanceof gn?[null]:e instanceof Oe?[void 0,...bt(e.unwrap())]:e instanceof ot?[null,...bt(e.unwrap())]:e instanceof Mr||e instanceof kn?bt(e.unwrap()):e instanceof xn?bt(e._def.innerType):[],Vo=class e extends j{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==k.object)return S(n,{code:b.invalid_type,expected:k.object,received:n.parsedType}),P;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}):(S(n,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),P)}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=bt(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:M.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...L(r)})}};function Ai(e,t){let n=nt(e),r=nt(t);if(e===t)return{valid:!0,data:e};if(n===k.object&&r===k.object){let o=F.objectKeys(t),s=F.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let c=Ai(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===k.array&&r===k.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],c=Ai(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===k.date&&r===k.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var yn=class extends j{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(jo(s)||jo(i))return P;let a=Ai(s.value,i.value);return a.valid?((Fo(s)||Fo(i))&&n.dirty(),{status:n.value,value:a.data}):(S(r,{code:b.invalid_intersection_types}),P)};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}))}};yn.create=(e,t,n)=>new yn({left:e,right:t,typeName:M.ZodIntersection,...L(n)});var rt=class e extends j{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==k.array)return S(r,{code:b.invalid_type,expected:k.array,received:r.parsedType}),P;if(r.data.length<this._def.items.length)return S(r,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;!this._def.rest&&r.data.length>this._def.items.length&&(S(r,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Me(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ge.mergeArray(n,i)):ge.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};rt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new rt({items:e,typeName:M.ZodTuple,rest:null,...L(t)})};var qo=class e extends j{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!==k.object)return S(r,{code:b.invalid_type,expected:k.object,received:r.parsedType}),P;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Me(r,a,r.path,a)),value:i._parse(new Me(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ge.mergeObjectAsync(n,o):ge.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof j?new e({keyType:t,valueType:n,typeName:M.ZodRecord,...L(r)}):new e({keyType:Vt.create(),valueType:t,typeName:M.ZodRecord,...L(n)})}},zn=class extends j{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!==k.map)return S(r,{code:b.invalid_type,expected:k.map,received:r.parsedType}),P;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:o._parse(new Me(r,a,r.path,[l,"key"])),value:s._parse(new Me(r,c,r.path,[l,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return P;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return P;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};zn.create=(e,t,n)=>new zn({valueType:t,keyType:e,typeName:M.ZodMap,...L(n)});var Jn=class e extends j{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==k.set)return S(r,{code:b.invalid_type,expected:k.set,received:r.parsedType}),P;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(S(r,{code:b.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&&(S(r,{code:b.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return P;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>s._parse(new Me(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:E.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:E.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Jn.create=(e,t)=>new Jn({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...L(t)});var Bo=class e extends j{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==k.function)return S(n,{code:b.invalid_type,expected:k.function,received:n.parsedType}),P;function r(a,c){return Or({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Bn(),_t].filter(l=>!!l),issueData:{code:b.invalid_arguments,argumentsError:c}})}function o(a,c){return Or({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Bn(),_t].filter(l=>!!l),issueData:{code:b.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Bt){let a=this;return be(async function(...c){let l=new ke([]),u=await a._def.args.parseAsync(c,s).catch(m=>{throw l.addIssue(r(c,m)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw l.addIssue(o(d,m)),l})})}else{let a=this;return be(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new ke([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new ke([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:rt.create(t).rest(vt.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||rt.create([]).rest(vt.create()),returns:n||vt.create(),typeName:M.ZodFunction,...L(r)})}},_n=class extends j{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})}};_n.create=(e,t)=>new _n({getter:e,typeName:M.ZodLazy,...L(t)});var bn=class extends j{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return S(n,{received:n.data,code:b.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:t.data}}get value(){return this._def.value}};bn.create=(e,t)=>new bn({value:e,typeName:M.ZodLiteral,...L(t)});function Xl(e,t){return new vn({values:e,typeName:M.ZodEnum,...L(t)})}var vn=class e extends j{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return S(n,{expected:F.joinValues(r),received:n.parsedType,code:b.invalid_type}),P}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 S(n,{received:n.data,code:b.invalid_enum_value,options:r}),P}return be(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})}};vn.create=Xl;var wn=class extends j{_parse(t){let n=F.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==k.string&&r.parsedType!==k.number){let o=F.objectValues(n);return S(r,{expected:F.joinValues(o),received:r.parsedType,code:b.invalid_type}),P}if(this._cache||(this._cache=new Set(F.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=F.objectValues(n);return S(r,{received:r.data,code:b.invalid_enum_value,options:o}),P}return be(t.data)}get enum(){return this._def.values}};wn.create=(e,t)=>new wn({values:e,typeName:M.ZodNativeEnum,...L(t)});var Bt=class extends j{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==k.promise&&n.common.async===!1)return S(n,{code:b.invalid_type,expected:k.promise,received:n.parsedType}),P;let r=n.parsedType===k.promise?n.data:Promise.resolve(n.data);return be(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Bt.create=(e,t)=>new Bt({type:e,typeName:M.ZodPromise,...L(t)});var Ne=class extends j{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.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=>{S(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 P;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?P:c.status==="dirty"?ln(c.value):n.value==="dirty"?ln(c.value):c});{if(n.value==="aborted")return P;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?P:a.status==="dirty"?ln(a.value):n.value==="dirty"?ln(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?P:(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"?P:(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(!Ft(i))return P;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=>Ft(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):P);F.assertNever(o)}};Ne.create=(e,t,n)=>new Ne({schema:e,typeName:M.ZodEffects,effect:t,...L(n)});Ne.createWithPreprocess=(e,t,n)=>new Ne({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...L(n)});var Oe=class extends j{_parse(t){return this._getType(t)===k.undefined?be(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Oe.create=(e,t)=>new Oe({innerType:e,typeName:M.ZodOptional,...L(t)});var ot=class extends j{_parse(t){return this._getType(t)===k.null?be(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ot.create=(e,t)=>new ot({innerType:e,typeName:M.ZodNullable,...L(t)});var Sn=class extends j{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===k.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Sn.create=(e,t)=>new Sn({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...L(t)});var xn=class extends j{_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 Hn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};xn.create=(e,t)=>new xn({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...L(t)});var Yn=class extends j{_parse(t){if(this._getType(t)!==k.nan){let r=this._getOrReturnCtx(t);return S(r,{code:b.invalid_type,expected:k.nan,received:r.parsedType}),P}return{status:"valid",value:t.data}}};Yn.create=e=>new Yn({typeName:M.ZodNaN,...L(e)});var wg=Symbol("zod_brand"),Mr=class extends j{_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}},Nr=class e extends j{_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"?P:s.status==="dirty"?(n.dirty(),ln(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"?P: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:M.ZodPipeline})}},kn=class extends j{_parse(t){let n=this._def.innerType._parse(t),r=o=>(Ft(o)&&(o.value=Object.freeze(o.value)),o);return Hn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};kn.create=(e,t)=>new kn({innerType:e,typeName:M.ZodReadonly,...L(t)});function Wl(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Zl(e,t={},n){return e?qt.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Wl(t,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Wl(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):qt.create()}var Sg={object:Ce.lazycreate},M;(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"})(M||(M={}));var xg=(e,t={message:`Input not instance of ${e.name}`})=>Zl(n=>n instanceof e,t),Ql=Vt.create,eu=un.create,kg=Yn.create,Cg=dn.create,tu=mn.create,Tg=pn.create,Eg=Gn.create,Ag=fn.create,Rg=gn.create,Ig=qt.create,$g=vt.create,Pg=Fe.create,Og=Wn.create,Mg=wt.create,Ng=Ce.create,Lg=Ce.strictCreate,Ug=hn.create,Dg=Vo.create,jg=yn.create,Fg=rt.create,Vg=qo.create,qg=zn.create,Bg=Jn.create,Hg=Bo.create,Kg=_n.create,Gg=bn.create,Wg=vn.create,zg=wn.create,Jg=Bt.create,Yg=Ne.create,Xg=Oe.create,Zg=ot.create,Qg=Ne.createWithPreprocess,eh=Nr.create,th=()=>Ql().optional(),nh=()=>eu().optional(),rh=()=>tu().optional(),oh={string:(e=>Vt.create({...e,coerce:!0})),number:(e=>un.create({...e,coerce:!0})),boolean:(e=>mn.create({...e,coerce:!0})),bigint:(e=>dn.create({...e,coerce:!0})),date:(e=>pn.create({...e,coerce:!0}))};var sh=P;var ih=/^[A-Za-z0-9._-]+$/,ah=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,nu=new Set([".",".."]),Se=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function ch(e,t){if(e==="*")return{raw:e,kind:"single"};if(e==="**")return{raw:e,kind:"multi"};if(e.startsWith("(")){let n=e.endsWith(")?"),r=e.endsWith(")");if(!n&&!r)throw new Se(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=n?e.slice(1,-2):e.slice(1,-1);if(!ah.test(o))throw new Se(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=o.split("|");if(s.some(i=>nu.has(i)))throw new Se(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:s}}if(ih.test(e)){if(nu.has(e))throw new Se(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new Se(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function lh(e){if(typeof e!="string"||e.length===0)throw new Se("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new Se("must start with '/'",e);if(e.slice(1).includes("//"))throw new Se("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new Se("must not end with '/'",e);let n=e.slice(1).split("/").map(s=>ch(s,e));if(n.filter(s=>s.kind==="multi").length>1)throw new Se("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new Se("'**' may not be the first segment (a literal prefix anchor is required)",e);let o=n.findIndex(s=>s.kind==="alt-optional");if(o!==-1&&o!==n.length-1)throw new Se("optional alternation '(...)?' is only allowed as the final segment",e);return n}function Ri(e){lh(e)}var ru=["tempo","mpp_self","merchant_self"],ou=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],su=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],iu=["images[0].url","image.url","audio.url","audio_file.url","audio_url","video.url","model_mesh.url","text","choices[0].message.content","choices[0].message.images[0].image_url.url","request_id"];var $i=h.object({inputPerMillion:h.number().positive(),outputPerMillion:h.number().positive(),contextWindow:h.number().int().positive().optional(),maxOutput:h.number().int().positive().optional(),perRequestFeeCents:h.number().nonnegative().optional()}),uh=h.object({strategy:h.enum(["flat","token","band"]).optional(),pricingModel:h.enum(["per-call","per-token","band"]).optional(),priceCents:h.number().nonnegative().optional(),currency:h.string().optional(),display:h.string().optional(),estimate:h.boolean().optional(),source:h.string().optional(),priceBand:h.record(h.unknown()).optional(),tokenPricing:$i.optional()}).passthrough(),Pi=h.discriminatedUnion("type",[h.object({type:h.literal("shortcut"),routedPath:h.string().min(1).startsWith("/")}),h.object({type:h.literal("custom"),merchantSlug:h.string().min(1),subPath:h.string().optional()}),h.object({type:h.literal("local"),fn:h.string().min(1)}),h.object({type:h.literal("read")})]),Oi=h.object({amount:h.number().nonnegative(),currency:h.string().length(3).optional(),display:h.string().optional(),free:h.boolean().optional(),batchDiscount:h.number().min(0).max(100).optional()}),au=h.object({attestation:h.boolean().optional(),rateLimitMs:h.number().positive().optional()}),cu=h.object({displayName:h.string().optional(),feedbackEligible:h.boolean().optional(),suggestionEligible:h.boolean().optional(),batchable:h.boolean().optional()}),lu=h.object({enabled:h.boolean().optional(),gatewayPath:h.string().min(1).startsWith("/").optional(),method:h.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:h.number().int().positive().max(12e4).optional()}).strict(),dh=h.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),mh=120,ph=120,fh=1200,gh=/^[^\u0000-\u001F\u007F]+$/;function Ii(e,t){return h.string().min(1).max(e).regex(gh,`${t} must not contain control characters`)}var Mi={id:h.string().min(1),name:Ii(mh,"name"),description:Ii(fh,"description"),provider:h.string().min(1),model:h.string().min(1),category:dh,priceCents:h.number().nonnegative(),inputSchema:h.record(h.unknown()),gatewayUrl:h.string().min(1),merchantName:Ii(ph,"merchantName"),isAsync:h.boolean().optional(),pollUrl:h.string().optional(),pollInterval:h.number().positive().optional(),pollTimeout:h.number().positive().optional(),tags:h.array(h.string()).optional(),tokenPricing:$i.optional(),priceDisplay:h.string().optional(),pricingModel:h.enum(["per-call","per-token","band"]).optional(),pricingInfo:uh.optional(),status:h.enum(["available","unavailable"]).optional(),handler:Pi.optional(),pricing:Oi.optional(),security:au.optional(),engagement:cu.optional(),gatewayConfig:lu.optional(),freeReadPathPattern:h.string().optional().superRefine((e,t)=>{if(e!==void 0)try{Ri(e)}catch(n){t.addIssue({code:h.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:h.boolean().optional(),beta:h.boolean().optional(),deprecated:h.boolean().optional(),internal:h.boolean().optional(),replacementTool:h.string().optional(),minCliVersion:h.string().optional(),sunsetAt:h.string().optional(),rail:h.enum(ru).optional(),executionKind:h.enum(ou).optional(),resultKind:h.enum(su).optional(),extractionMode:h.enum(iu).optional(),pricingStrategy:h.enum(["flat","token","band"]).optional()},uu=h.object({...Mi,dispatch:h.literal("routed"),routedPath:h.string().min(1).startsWith("/")}).strict(),du=h.object({...Mi,dispatch:h.literal("enveloped")}).strict(),mu=h.object({...Mi,handler:Pi,pricing:Oi}).strict(),pu=h.union([h.discriminatedUnion("dispatch",[uu,du]),mu]);var Ni=/^[a-z0-9][a-z0-9_-]*$/;var _h="https://fal.run",yu="https://openrouter.mpp.tempo.xyz",Ui=1024,Ko=8192,bh=4096,vh=10;function wh(e){return e>=vh?bh:Ko}function _u(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):Ui;return Math.min(n,t)}var Sh=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function bu(e){for(let t of Sh)delete e[t];return e}function xh(e){let{attestation:t,tool_id:n,...r}=e;return bu(r)}var fu={"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 Ho(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:o,...s}=e,i=bu({...s});return typeof o=="string"&&o.length>0?(i.image_size=o,i):(typeof r=="string"&&fu[r]&&(i.image_size=fu[r]),i)}function kh(e){let{attestation:t,tool_id:n,...r}=e;return r}function gu(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 Ch(e,t,n,r,o,s,i,a,c){return{id:e,name:t,description:n,provider:r,model:o.replace(/^\//,""),category:s,gatewayUrl:`https://${r}${o}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:o},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...c}}function Th(e,t,n,r,o,s,i,a){return Ch(e,t,n,"suno-ai",r,o,s,i,{merchantName:"Suno AI",...a})}function se(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:`${_h}/${r}`,merchantName:"fal.ai",buildBody:xh,tags:[],...a}}function vu(e,t=Ko){return n=>{let{attestation:r,tool_id:o,model:s,prompt:i,system_prompt:a,max_tokens:c,max_completion_tokens:l,n:u,messages:d,temperature:p,...m}=n;return typeof s=="string"&&s.length>0&&s!==e&&console.warn("[catalog] openrouterBuildBody: caller model override ignored",{catalogModel:e,callerModel:s}),{messages:Array.isArray(d)?d:[...a?[{role:"system",content:a}]:[],{role:"user",content:i}],temperature:p??.7,...m,model:e,max_tokens:_u(c??l,t)}}}function wu(e,t=Ko){return n=>{let{attestation:r,tool_id:o,prompt:s,image_url:i,aspect_ratio:a,max_tokens:c,max_completion_tokens:l,n:u,model:d,messages:p,image_config:m,temperature:g,...y}=n,w=[{type:"text",text:s}];return typeof i=="string"&&i.length>0&&w.push({type:"image_url",image_url:{url:i}}),{messages:Array.isArray(p)?p:[{role:"user",content:w}],temperature:g??.7,...y,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:_u(c??l,t)}}}function Q(e,t,n,r,o,s,i){let a=i?.maxOutputTokens??wh(s),c=i?.perRequestFeeCents??0,l=500/1e6*o*100,u=500/1e6*s*100,d=Math.max(1,Math.ceil(l+u+c)),{perRequestFeeCents:p,maxOutputTokens:m,...g}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:d,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:`Maximum tokens in response (default: ${Ui}); values above ${a} are clamped to ${a}`,minimum:1,maximum:a},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${yu}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:vu(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s,...c>0?{perRequestFeeCents:c}:{}},...g}}function Li(e,t,n,r,o,s){let i=s?.maxOutputTokens??Ko,{maxOutputTokens:a,...c}=s??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",pricingStrategy:"band",priceCents:o,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:`Maximum text tokens in response metadata (default: ${Ui}); values above ${i} are clamped to ${i}`,minimum:1,maximum:i},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${yu}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:wu(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var Di=[se("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"]}),se("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:Ho}),se("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:Ho}),se("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:Ho}),se("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"]}),Li("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),Li("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}}),Li("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}}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),Th("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}}}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),Q("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"]}),Q("or-gpt-55","GPT-5.5","OpenAI frontier model for complex professional reasoning, coding, and long-context analysis.","openai/gpt-5.5",5,30,{tags:["llm","gpt","openai","frontier","reasoning","coding","long-context"]}),Q("or-gpt-55-pro","GPT-5.5 Pro","OpenAI high-capability frontier model optimized for deep reasoning and high-stakes workloads.","openai/gpt-5.5-pro",30,180,{tags:["llm","gpt","openai","frontier","pro","deep-reasoning","coding","long-context"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("or-gemini-35-flash","Gemini 3.5 Flash","Google frontier Flash model for multimodal reasoning, coding, and parallel agentic workflows.","google/gemini-3.5-flash",1.5,9,{tags:["llm","gemini","google","frontier","multimodal","reasoning","coding","fast"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",internal:!0,executionKind:"x402_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:gu,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"parallel-search-tempo",name:"Parallel Search (Tempo)",description:"Internal Tempo gateway route for Parallel's paid search endpoint.",provider:"parallel",model:"search",category:"utility",priceCents:1,inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query. Mapped by Parallel to objective when provided."},objective:{type:"string",description:"Search objective. Use with search_queries for advanced requests."},search_queries:{type:"array",items:{type:"string"},description:"Optional explicit search query list."},mode:{type:"string",enum:["one-shot","fast"],description:"Parallel search mode.",default:"one-shot"}},anyOf:[{required:["query"]},{required:["objective"]}]},gatewayUrl:"https://parallelmpp.dev/api/search",merchantName:"Parallel",internal:!0,rail:"tempo",executionKind:"tempo_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildBody:kh,tags:["search","parallel","tempo","internal"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>Ho({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"]},se("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"}),se("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{id:"check_fal_status",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion. Free.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",handler:{type:"local",fn:"check_fal_status"},pricing:{amount:0,currency:"USD",display:"$0.00",free:!0},freeReadPathPattern:"/api/v1/fal/**/requests/*/(status)?",tags:["status","fal","async"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno) \u2014 retired",description:"[Retired] Suno music generation. Use `generate_music` (ACE-Step) instead.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status (Suno) \u2014 retired",description:"[Retired] Suno status poll. No replacement; ACE-Step jobs poll via `check_fal_status`.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:gu,tags:["onchain","prices","allium","crypto","legacy"]}];function Xn(e){return Di.find(t=>t.id===e)}var Su=1,xu=["pick_one","fan_out"],ku=["concat","dedupe_by_url","top_k_by_score"],Rh=8,Ih=h.object({type:h.string().min(1),description:h.string().min(1),enum:h.array(h.string()).optional(),default:h.unknown().optional(),minimum:h.number().optional(),maximum:h.number().optional()}),$h=h.object({toolId:h.string().min(1),notes:h.string().min(1)}),Ph=h.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),Oh=h.object({providers:h.array(h.string().min(1)).min(1).max(Rh),merge:h.enum(ku),maxResults:h.number().int().positive().optional()}),Cu=h.object({mode:h.enum(xu).default("pick_one"),intro:h.string().min(1),defaultTier:h.string().min(1),tiers:h.record(Ph,$h).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Oh.optional(),guidance:h.string().min(1),inputProperties:h.record(h.string(),Ih),required:h.array(h.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"]}),Mh=h.object({version:h.literal(Su),generatedAt:h.string().datetime(),tools:h.record(h.string().regex(Ni,"tool name must match MCP naming rules"),Cu).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Jo=require("child_process"),Nu=require("util"),Lu=T(require("crypto")),z=T(require("fs")),Uu=T(require("os")),ve=T(require("path"));var Ve=(0,Nu.promisify)(Jo.execFile),Uh=6e4,Dh=()=>process.platform==="darwin",Ht=()=>process.platform==="win32",Kt=ve.join(Uu.homedir(),".visa-mcp","bin"),Cn=ve.join(Kt,"Visa CLI"),St=ve.join(Kt,"visa-keychain-win.exe"),Du=ve.join(__dirname,"..","native"),Tu="6",Eu=ve.join(Kt,"visa-keychain.version"),Au=ve.join(Kt,"visa-keychain.sha256"),Ru="1",Iu=ve.join(Kt,"visa-keychain-win.version"),$u=ve.join(Kt,"visa-keychain-win.sha256"),ju=[ve.join(Du,"bin","win32-x64","visa-keychain-win.exe"),ve.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),ve.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Go(e){let t=z.readFileSync(e);return Lu.createHash("sha256").update(t).digest("hex")}function jh(e){let t=e.trim();if(t.startsWith("OK:"))return t.slice(3);if(t==="OK")return;let n=t.startsWith("ERROR:")?t.slice(6):"Unknown error";throw new Error(n)}function Pu(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function Ou(e){let t=Math.max(1,Math.round(e/1e3));return new Error(`Timed out waiting for Touch ID/device approval after ${t}s.`)}async function ji(){try{if(z.readFileSync(Eu,"utf-8").trim()===Tu&&z.existsSync(Cn)){let r=z.readFileSync(Au,"utf-8").trim();if(Go(Cn)!==r)f.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),z.unlinkSync(Cn);else return Cn}}catch{}let e=ve.join(Du,"visa-keychain.m");if(z.existsSync(e)||(e=ve.resolve(__dirname,"..","..","native","visa-keychain.m")),z.existsSync(e)||(e=ve.resolve(__dirname,"..","native","visa-keychain.m")),!z.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");z.mkdirSync(Kt,{recursive:!0,mode:448});try{await Ve("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=Go(Cn);return z.writeFileSync(Au,t,{mode:384}),z.writeFileSync(Eu,Tu,{mode:384}),Cn}function Fu(){for(let e of ju)if(z.existsSync(e))return e;return null}async function Zn(){try{if(z.readFileSync(Iu,"utf-8").trim()===Ru&&z.existsSync(St)){let r=z.readFileSync($u,"utf-8").trim();if(Go(St)!==r)f.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),z.unlinkSync(St);else return St}}catch{}let e=Fu();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
|
|
136
|
-
If building from source, run native/build-win.bat first.`);z.mkdirSync(Kt,{recursive:!0}),z.copyFileSync(e,St);let t=Go(St);return z.writeFileSync($u,t,{mode:384}),z.writeFileSync(Iu,Ru,{mode:384}),St}async function Fh(){return Ht()?Zn():ji()}var Wo="visa-cli",zo="attestation-key";async function Vh(e){try{await Ve("security",["delete-generic-password","-s",Wo,"-a",zo],{timeout:5e3})}catch{}await Ve("security",["add-generic-password","-s",Wo,"-a",zo,"-w",e],{timeout:5e3})}function qh(e){let t=typeof e?.code=="number"?e.code:void 0,n=typeof e?.stderr=="string"?e.stderr:"",r=typeof e?.stdout=="string"?e.stdout:"",o=[n,r,e?.message].filter(Boolean).join(" ").trim();return t===44||/could not be found|item(?: was)? not found|no such keychain item|not found/i.test(o)?{state:"absent",usable:!1,message:"No local attestation key was found."}:/user interaction is not allowed|user canceled|user cancelled|authorization failed|interaction not allowed|keychain.*locked|denied|not authorized/i.test(o)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:o||"Could not read the local attestation key from Keychain."}}async function Bh(){try{let{stdout:e}=await Ve("security",["find-generic-password","-s",Wo,"-a",zo,"-w"],{timeout:5e3}),t=e.trim();return t?{key:t,status:{state:"present",usable:!0}}:{key:null,status:{state:"absent",usable:!1,message:"No local attestation key was found."}}}catch(e){return{key:null,status:qh(e)}}}async function Fi(){let e=await Bh();if(e.key)return e.key;if(e.status.state==="absent")return null;throw new Error(e.status.message||"Could not read the local attestation key from Keychain.")}async function Vu(e){let t=await Fh(),n;try{n=(await Ve(t,e,{timeout:6e4})).stdout}catch(r){n=r.stdout||"";let o=n.trim();throw o.startsWith("ERROR:")?new Error(o.slice(6)):new Error(r.stderr?.trim()||r.message||"Unknown error")}return jh(n)}var Mu=!1;function Hh(){if(!Ht())return!1;try{return z.existsSync(St)||Fu()!==null?!0:(Mu||(Mu=!0,f.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:St,searchedPrebuiltPaths:ju})),!1)}catch{return!1}}function ie(){return On()||Dh()?!0:Ht()?Hh():!1}async function Yo(){if(Ht()){let o=await Zn(),{stdout:s}=await Ve(o,["generate-key"],{timeout:3e4}),i=s.trim();if(i.startsWith("OK:"))return i.slice(3);throw new Error(i.startsWith("ERROR:")?i.slice(6):"Key generation failed")}let e=await Vu(["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 Vh(n),r}async function Xo(){if(Ht())try{let e=await Zn(),{stdout:t}=await Ve(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await Fi()!==null}async function qu(){if(On())return"mock-public-key-spki";if(Ht()){let n=await Zn(),{stdout:r}=await Ve(n,["public-key"],{timeout:6e4}),o=r.trim();if(o.startsWith("OK:"))return o.slice(3);throw new Error(o.startsWith("ERROR:")?o.slice(6):"Attestation key not found. Run setup to generate a new key.")}let e=await Fi();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await ji();return new Promise((n,r)=>{let o=(0,Jo.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 Tn(e,t,n={}){if(On())return Promise.resolve(oc());let r=n.timeoutMs??Uh;if(Ht()){let a=await Zn(),c=["sign",e];t&&c.push(t);let l;try{l=(await Ve(a,c,{timeout:r})).stdout}catch(d){throw Pu(d)?Ou(r):d}let u=l.trim();if(u.startsWith("OK:"))return u.slice(3);throw new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error")}let o=await Fi();if(!o)throw new Error("Attestation key not found. Run setup to generate a new key.");let s=await ji(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Jo.execFile)(s,i,{timeout:r},(u,d)=>{let p=(d||"").trim();if(u){p.startsWith("ERROR:")?c(new Error(p.slice(6))):Pu(u)?c(Ou(r)):c(new Error(u.stderr?.trim()||u.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):c(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});l.stdin.write(o),l.stdin.end()})}async function Zo(){if(Ht()){try{let e=await Zn();await Ve(e,["delete-key"],{timeout:1e4})}catch{}return}try{await Ve("security",["delete-generic-password","-s",Wo,"-a",zo],{timeout:5e3})}catch{}try{await Vu(["delete-key"])}catch{}}var Kh=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Gh=[...Kh.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 qi(e,t=Gh){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Vi(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(Vi(r.match.provider)))&&r.match.keywords.every(o=>n.includes(Vi(o))))return r.targetToolId;return null}function Vi(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var Ur={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status" and the exact request_id/model_path returned by the async response. Do not substitute the catalog model path manually. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},frontier_openai:{toolId:"or-gpt-55",notes:"GPT-5.5. OpenAI frontier model for complex professional reasoning."},frontier_openai_pro:{toolId:"or-gpt-55-pro",notes:"GPT-5.5 Pro. Highest-capability OpenAI frontier tier; materially more expensive."},frontier_anthropic:{toolId:"or-claude-opus",notes:"Claude Opus 4.7. Anthropic frontier model for complex tasks."},frontier_google:{toolId:"or-gemini-35-flash",notes:"Gemini 3.5 Flash. Google frontier Flash model for multimodal reasoning and coding."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), frontier_* (top-model council / highest quality; warn user these are materially pricier), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function Gt(e,t,n){if(!Hu(e))return Yh(e,n);let r=Bu[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=Xh(e,s,n);return i||Zh(e,r,s,o)}function Yh(e,t){return qi({requestedTool:e,intentText:t})??e}function Xh(e,t,n){return qi({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Zh(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 Bu=Ur;function Hu(e){return e in Bu}var Dr=Object.keys(Ur);function Bi(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Ku(e=process.env){return Bi(e)!==null}function Gu(e=process.env){let t=(e.VISA_CLI_PARENTLESS_SINGLE_CALL??"").trim().toLowerCase();return t==="true"||t==="1"}function Wu(e=process.env){let t=(e.VISA_CLI_PARENTLESS_BATCH??"").trim().toLowerCase();return t==="true"||t==="1"}var Rd=require("child_process"),pe=T(require("crypto")),Ke=T(require("fs")),Kr=T(require("os")),hs=T(require("path"));function st(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),o=n.content?.[0]?.text,s=typeof o=="string"?Mn(o):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Mn(i):null;if(!s&&!c)return e;let l=s??c,u=s?"content":"urls",d;try{d=mr(l,{tag:Qh(r,n)})}catch(m){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${m instanceof Error?m.message:String(m)}`}}let p={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?p.urls=void 0:(p.content=Array.isArray(n.content)?[...n.content]:[{}],p.content[0]={...p.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),p}function Qh(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}var zu=!1;async function Qn(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!ie())throw r;if(f.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(zu)throw f.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;zu=!0,f.info("attestation:starting-browser-recovery");try{let s=await n();if(!s.success)throw f.error("attestation:browser-recovery-failed",{message:s.message}),r;let i=await Yo();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),f.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),f.info("attestation:key-reregistered-after-recovery"),await t()}catch(s){throw f.error("attestation:recovery-failure",{error:s.message}),r}}throw r}}function it(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Qo(e,t){if(!ie())return{ok:!1,code:"TOUCH_ID_UNAVAILABLE",message:"Touch ID is not available in this process. Run `visa-cli setup` from an interactive macOS terminal before enabling Touch ID."};if(!await Xo())return{ok:!1,code:"LOCAL_ATTESTATION_KEY_MISSING",message:"No local attestation key found on this device. Run `visa-cli setup` before enabling Touch ID; otherwise payments and biometric off can require a key this device cannot produce."};let n=await e.getStatus(t);return it(n)?{ok:!0,status:n}:{ok:!1,code:"SERVER_ATTESTATION_KEY_MISSING",message:"No server attestation key is registered for this account. Run `visa-cli setup` before enabling Touch ID."}}var Ju="3.0.0-rc.0";function Hi(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function es(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=Lo(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Re(e){return e==null?"\u2014":e?"yes":"no"}function ts(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function ey(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function ty(){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=xi("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:wi,source:{kind:"default"}}}async function jr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(_){n=_?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=Si("auth.serverUrl"),i=Ee(),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:Re(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}}),t?.userId&&r.push({key:"account.userId",value:t.userId,formatted:t.userId,source:{kind:"server"},hint:"Opaque stable account id used for account-scoped local credentials."});let c=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:c,formatted:Re(c),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:c===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:Re(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:ie(),formatted:Re(ie()),source:{kind:"device"}});let l=t?.spendingControls,u=l?l.max_transaction_amount??l.maxTransactionAmount??null:null,d=l?l.daily_limit??l.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:ts(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:ts(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:ts(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:ts(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 p=t?.cards?.find(_=>_.isDefault)??t?.cards?.[0];p&&r.push({key:"cards.default",value:{brand:p.brand??null,last4:p.last4},formatted:`${p.brand||"card"} \u2022\u2022\u2022\u2022 ${p.last4}`,source:{kind:"server"}});let m=ty();r.push({key:"credit.sessionCapCents",value:m.value,formatted:ey(m.value),source:m.source});let g=Ll();g.length>0&&r.push({key:"settings.retired",value:g.map(_=>_.key),formatted:g.map(_=>_.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${g.map(_=>`visa-cli config unset ${_.key}`).join(" && ")}`});let y=es("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:y.value,formatted:Re(y.value),source:y.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let w=es("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:w.value,formatted:Re(w.value),source:w.source});let N=tt(),U;process.env.VISA_CLI_NO_UPDATE_CHECK?U={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?U={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?U={kind:"env",var:"NODE_ENV"}:U={kind:"default"},r.push({key:"ui.updateCheck",value:!N,formatted:Re(!N),source:U});let v=es("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:v.value,formatted:Re(v.value),source:v.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let x=es("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:x.value,formatted:Re(x.value),source:x.source});let $=process.env.VISA_DRY_RUN,O=Ku();if(r.push({key:"tools.dryRun",value:O,formatted:Re(O),source:$===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:Ju,formatted:Ju,source:{kind:"default"}}),e.includeDev){let _=process.env.VISA_MOCK_KEYCHAIN,C=Et();r.push({key:"dev.mockKeychain",value:C,formatted:Re(C),source:Hi("VISA_MOCK_KEYCHAIN",!!_),hint:Ns()});let he=process.env.VISA_MOCK_TOUCHID,ye=On();r.push({key:"dev.mockTouchid",value:ye,formatted:Re(ye),source:Hi("VISA_MOCK_TOUCHID",!!he),hint:Ns()});let Y=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!Y,formatted:Re(!!Y),source:Hi("VISA_CLI_DEBUG",!!Y)})}return{entries:r,statusError:n}}function ny(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 Yu(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}(${ny(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
|
|
136
|
+
If building from source, run native/build-win.bat first.`);z.mkdirSync(Kt,{recursive:!0}),z.copyFileSync(e,St);let t=Go(St);return z.writeFileSync($u,t,{mode:384}),z.writeFileSync(Iu,Ru,{mode:384}),St}async function Fh(){return Ht()?Zn():ji()}var Wo="visa-cli",zo="attestation-key";async function Vh(e){try{await Ve("security",["delete-generic-password","-s",Wo,"-a",zo],{timeout:5e3})}catch{}await Ve("security",["add-generic-password","-s",Wo,"-a",zo,"-w",e],{timeout:5e3})}function qh(e){let t=typeof e?.code=="number"?e.code:void 0,n=typeof e?.stderr=="string"?e.stderr:"",r=typeof e?.stdout=="string"?e.stdout:"",o=[n,r,e?.message].filter(Boolean).join(" ").trim();return t===44||/could not be found|item(?: was)? not found|no such keychain item|not found/i.test(o)?{state:"absent",usable:!1,message:"No local attestation key was found."}:/user interaction is not allowed|user canceled|user cancelled|authorization failed|interaction not allowed|keychain.*locked|denied|not authorized/i.test(o)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:o||"Could not read the local attestation key from Keychain."}}async function Bh(){try{let{stdout:e}=await Ve("security",["find-generic-password","-s",Wo,"-a",zo,"-w"],{timeout:5e3}),t=e.trim();return t?{key:t,status:{state:"present",usable:!0}}:{key:null,status:{state:"absent",usable:!1,message:"No local attestation key was found."}}}catch(e){return{key:null,status:qh(e)}}}async function Fi(){let e=await Bh();if(e.key)return e.key;if(e.status.state==="absent")return null;throw new Error(e.status.message||"Could not read the local attestation key from Keychain.")}async function Vu(e){let t=await Fh(),n;try{n=(await Ve(t,e,{timeout:6e4})).stdout}catch(r){n=r.stdout||"";let o=n.trim();throw o.startsWith("ERROR:")?new Error(o.slice(6)):new Error(r.stderr?.trim()||r.message||"Unknown error")}return jh(n)}var Mu=!1;function Hh(){if(!Ht())return!1;try{return z.existsSync(St)||Fu()!==null?!0:(Mu||(Mu=!0,f.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:St,searchedPrebuiltPaths:ju})),!1)}catch{return!1}}function ie(){return On()||Dh()?!0:Ht()?Hh():!1}async function Yo(){if(Ht()){let o=await Zn(),{stdout:s}=await Ve(o,["generate-key"],{timeout:3e4}),i=s.trim();if(i.startsWith("OK:"))return i.slice(3);throw new Error(i.startsWith("ERROR:")?i.slice(6):"Key generation failed")}let e=await Vu(["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 Vh(n),r}async function Xo(){if(Ht())try{let e=await Zn(),{stdout:t}=await Ve(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await Fi()!==null}async function qu(){if(On())return"mock-public-key-spki";if(Ht()){let n=await Zn(),{stdout:r}=await Ve(n,["public-key"],{timeout:6e4}),o=r.trim();if(o.startsWith("OK:"))return o.slice(3);throw new Error(o.startsWith("ERROR:")?o.slice(6):"Attestation key not found. Run setup to generate a new key.")}let e=await Fi();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await ji();return new Promise((n,r)=>{let o=(0,Jo.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 Tn(e,t,n={}){if(On())return Promise.resolve(oc());let r=n.timeoutMs??Uh;if(Ht()){let a=await Zn(),c=["sign",e];t&&c.push(t);let l;try{l=(await Ve(a,c,{timeout:r})).stdout}catch(d){throw Pu(d)?Ou(r):d}let u=l.trim();if(u.startsWith("OK:"))return u.slice(3);throw new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error")}let o=await Fi();if(!o)throw new Error("Attestation key not found. Run setup to generate a new key.");let s=await ji(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Jo.execFile)(s,i,{timeout:r},(u,d)=>{let p=(d||"").trim();if(u){p.startsWith("ERROR:")?c(new Error(p.slice(6))):Pu(u)?c(Ou(r)):c(new Error(u.stderr?.trim()||u.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):c(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});l.stdin.write(o),l.stdin.end()})}async function Zo(){if(Ht()){try{let e=await Zn();await Ve(e,["delete-key"],{timeout:1e4})}catch{}return}try{await Ve("security",["delete-generic-password","-s",Wo,"-a",zo],{timeout:5e3})}catch{}try{await Vu(["delete-key"])}catch{}}var Kh=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Gh=[...Kh.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 qi(e,t=Gh){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Vi(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(Vi(r.match.provider)))&&r.match.keywords.every(o=>n.includes(Vi(o))))return r.targetToolId;return null}function Vi(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var Ur={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status" and the exact request_id/model_path returned by the async response. Do not substitute the catalog model path manually. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},frontier_openai:{toolId:"or-gpt-55",notes:"GPT-5.5. OpenAI frontier model for complex professional reasoning."},frontier_openai_pro:{toolId:"or-gpt-55-pro",notes:"GPT-5.5 Pro. Highest-capability OpenAI frontier tier; materially more expensive."},frontier_anthropic:{toolId:"or-claude-opus",notes:"Claude Opus 4.7. Anthropic frontier model for complex tasks."},frontier_google:{toolId:"or-gemini-35-flash",notes:"Gemini 3.5 Flash. Google frontier Flash model for multimodal reasoning and coding."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), frontier_* (top-model council / highest quality; warn user these are materially pricier), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function Gt(e,t,n){if(!Hu(e))return Yh(e,n);let r=Bu[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=Xh(e,s,n);return i||Zh(e,r,s,o)}function Yh(e,t){return qi({requestedTool:e,intentText:t})??e}function Xh(e,t,n){return qi({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Zh(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 Bu=Ur;function Hu(e){return e in Bu}var Dr=Object.keys(Ur);function Bi(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Ku(e=process.env){return Bi(e)!==null}function Gu(e=process.env){let t=(e.VISA_CLI_PARENTLESS_SINGLE_CALL??"").trim().toLowerCase();return t==="true"||t==="1"}function Wu(e=process.env){let t=(e.VISA_CLI_PARENTLESS_BATCH??"").trim().toLowerCase();return t==="true"||t==="1"}var Rd=require("child_process"),pe=T(require("crypto")),Ke=T(require("fs")),Kr=T(require("os")),hs=T(require("path"));function st(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),o=n.content?.[0]?.text,s=typeof o=="string"?Mn(o):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Mn(i):null;if(!s&&!c)return e;let l=s??c,u=s?"content":"urls",d;try{d=mr(l,{tag:Qh(r,n)})}catch(m){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${m instanceof Error?m.message:String(m)}`}}let p={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?p.urls=void 0:(p.content=Array.isArray(n.content)?[...n.content]:[{}],p.content[0]={...p.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),p}function Qh(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}var zu=!1;async function Qn(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!ie())throw r;if(f.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(zu)throw f.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;zu=!0,f.info("attestation:starting-browser-recovery");try{let s=await n();if(!s.success)throw f.error("attestation:browser-recovery-failed",{message:s.message}),r;let i=await Yo();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),f.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),f.info("attestation:key-reregistered-after-recovery"),await t()}catch(s){throw f.error("attestation:recovery-failure",{error:s.message}),r}}throw r}}function it(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Qo(e,t){if(!ie())return{ok:!1,code:"TOUCH_ID_UNAVAILABLE",message:"Touch ID is not available in this process. Run `visa-cli setup` from an interactive macOS terminal before enabling Touch ID."};if(!await Xo())return{ok:!1,code:"LOCAL_ATTESTATION_KEY_MISSING",message:"No local attestation key found on this device. Run `visa-cli setup` before enabling Touch ID; otherwise payments and biometric off can require a key this device cannot produce."};let n=await e.getStatus(t);return it(n)?{ok:!0,status:n}:{ok:!1,code:"SERVER_ATTESTATION_KEY_MISSING",message:"No server attestation key is registered for this account. Run `visa-cli setup` before enabling Touch ID."}}var Ju="3.0.0";function Hi(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function es(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=Lo(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Re(e){return e==null?"\u2014":e?"yes":"no"}function ts(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function ey(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function ty(){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=xi("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:wi,source:{kind:"default"}}}async function jr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(_){n=_?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=Si("auth.serverUrl"),i=Ee(),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:Re(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}}),t?.userId&&r.push({key:"account.userId",value:t.userId,formatted:t.userId,source:{kind:"server"},hint:"Opaque stable account id used for account-scoped local credentials."});let c=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:c,formatted:Re(c),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:c===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:Re(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:ie(),formatted:Re(ie()),source:{kind:"device"}});let l=t?.spendingControls,u=l?l.max_transaction_amount??l.maxTransactionAmount??null:null,d=l?l.daily_limit??l.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:ts(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:ts(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:ts(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:ts(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 p=t?.cards?.find(_=>_.isDefault)??t?.cards?.[0];p&&r.push({key:"cards.default",value:{brand:p.brand??null,last4:p.last4},formatted:`${p.brand||"card"} \u2022\u2022\u2022\u2022 ${p.last4}`,source:{kind:"server"}});let m=ty();r.push({key:"credit.sessionCapCents",value:m.value,formatted:ey(m.value),source:m.source});let g=Ll();g.length>0&&r.push({key:"settings.retired",value:g.map(_=>_.key),formatted:g.map(_=>_.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${g.map(_=>`visa-cli config unset ${_.key}`).join(" && ")}`});let y=es("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:y.value,formatted:Re(y.value),source:y.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let w=es("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:w.value,formatted:Re(w.value),source:w.source});let N=tt(),U;process.env.VISA_CLI_NO_UPDATE_CHECK?U={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?U={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?U={kind:"env",var:"NODE_ENV"}:U={kind:"default"},r.push({key:"ui.updateCheck",value:!N,formatted:Re(!N),source:U});let v=es("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:v.value,formatted:Re(v.value),source:v.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let x=es("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:x.value,formatted:Re(x.value),source:x.source});let $=process.env.VISA_DRY_RUN,O=Ku();if(r.push({key:"tools.dryRun",value:O,formatted:Re(O),source:$===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:Ju,formatted:Ju,source:{kind:"default"}}),e.includeDev){let _=process.env.VISA_MOCK_KEYCHAIN,C=Et();r.push({key:"dev.mockKeychain",value:C,formatted:Re(C),source:Hi("VISA_MOCK_KEYCHAIN",!!_),hint:Ns()});let he=process.env.VISA_MOCK_TOUCHID,ye=On();r.push({key:"dev.mockTouchid",value:ye,formatted:Re(ye),source:Hi("VISA_MOCK_TOUCHID",!!he),hint:Ns()});let Y=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!Y,formatted:Re(!!Y),source:Hi("VISA_CLI_DEBUG",!!Y)})}return{entries:r,statusError:n}}function ny(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 Yu(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}(${ny(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
|
|
137
137
|
`)}function Xu(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 Zu(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 Wt=require("fs"),ed=require("os"),Ki=require("path"),ry=(0,Ki.join)((0,ed.homedir)(),".visa-mcp"),Qu=(0,Ki.join)(ry,"mcp-session-budget.json");function ns(){try{(0,Wt.existsSync)(Qu)&&(0,Wt.unlinkSync)(Qu)}catch{}}var Wi=require("crypto"),Be=T(Fr()),En=null,Ie=0,er=0,Te=0,zt=null,zi=null,Ji=null,os=Promise.resolve();function wy(e){return Number((0,Be.fromCents)(e))}function rd(e){return(0,Be.toCents)((0,Be.micros)(BigInt(e)))}function nd(e){return(0,Be.toWire)((0,Be.fromCents)(e))}function Gi(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function rs(e){return typeof e=="string"&&/^\d+$/.test(e)}var Sy=43,xy=new RegExp(`^[A-Za-z0-9_-]{${Sy}}$`);function ky(e){return typeof e=="string"&&xy.test(e)}function Cy(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||En&&e.session_id!==En||typeof e.nonce!="string"||e.nonce.length===0||!ky(e.server_signature)||!Gi(e.cumulative)||!Gi(e.remaining)||!Gi(e.delta)||e.cumulative<Ie||Te>0&&e.cumulative>Te||Te>0&&e.remaining>Te||e.cumulative_micros!==void 0&&!rs(e.cumulative_micros)||e.remaining_micros!==void 0&&!rs(e.remaining_micros)||e.delta_micros!==void 0&&!rs(e.delta_micros)||e.reserved_micros!==void 0&&!rs(e.reserved_micros))}function kt(e){En=e,Ie=0,er=0,Te=0,zt=null,zi=null,Ji=null,os=Promise.resolve()}function Vr(e){Te=Math.max(0,Math.floor(e))}function Yi(){return En}function Xi(e){if(!En)return null;let t=Ie+er;return Te>0&&t>Te&&(t=Te),{session_budget_id:En,cumulative_micros:wy(t),nonce:(0,Wi.randomUUID)(),idempotency_key:e||(0,Wi.randomUUID)()}}function qr(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 Cy(r)?(Ie=Math.max(Ie,r.cumulative),er=0,zt=r,r):null}function od(){return zt}function Zi(e){let t=rd(e.cumulative_micros);Ie=Math.max(Ie,t),er=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ie,remaining:Math.max(0,Te-Ie),delta:0,cumulative_micros:nd(Ie),remaining_micros:nd(Math.max(0,Te-Ie)),delta_micros:"0",nonce:e.nonce};return zt=n,n}function Br(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,Be.toCents)((0,Be.micros)(n));if(!Number.isFinite(r)||r<0)return;zi=t;let o=e,s=typeof o.session_id=="string"?o.session_id:En??"";zt?(typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)&&(zt.remaining_micros=o.remaining_micros),typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)&&(zt.delta_micros=o.charged_micros)):zt={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 sd(e){let t=e.receipt??null;Ji={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:rd(e.voucher.cumulative_micros),estimatedCumulativeCents:ss(),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 id(){return Ji}function ad(){return Ie}function cd(){return zi}function ss(){let e=Ie+er;return Te>0&&e>Te&&(e=Te),e}function ld(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return os=os.then(()=>{er+=t}),os}var Ty=10,Ey=1,ee=null,ud=Promise.resolve();function Qi(e){let t=ud.catch(()=>{}).then(e);return ud=t.then(()=>{},()=>{}),t}var me=class extends Error{balanceCents;minRequiredCents;constructor(t,n){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(n/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first.`),this.name="InsufficientBalanceError"}};async function ea(e,t,n){return Qi(()=>dd(e,t,n))}async function dd(e,t,n){if(ns(),ee&&new Date(ee.expiresAt).getTime()>Date.now())return Yi()!==ee.budgetId&&(kt(ee.budgetId),Vr(ee.totalCents)),f.info("mcp-session:active-hit",{budgetId:ee.budgetId,tool:n.toolName,remainingEstimatedCents:ee.totalCents-ss()}),{budgetId:ee.budgetId,isFresh:!1,totalCents:ee.totalCents,requestedCapCents:ee.totalCents,appliedCapCents:ee.totalCents,clampedReason:null};ee&&(ee=null,kt(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"?Ey:Ty,i=Math.max(s,Math.ceil(n.minRequiredCents??s));if(r.balanceCents<i)throw new me(r.balanceCents,i);let a=n.capCentsOverride??jl(),c=Math.min(a,r.balanceCents),l=c<a?"balance":null,u=await t("session_create",c,"Visa CLI Session",`open credit-model session with $${(c/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:c,session_kind:o,...u?{attestation:u}:{}});if(!d.success||!d.budget){let m=d.error||"unknown error";throw new Error(`Failed to open credit session: ${m}`)}let p={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return ee=p,kt(p.budgetId),Vr(p.totalCents),f.info("mcp-session:opened",{budgetId:p.budgetId,capCents:p.totalCents,requestedCapCents:a,clampedReason:l,sessionKind:o,expiresAt:p.expiresAt,tool:n.toolName}),{budgetId:p.budgetId,isFresh:!0,totalCents:p.totalCents,requestedCapCents:a,appliedCapCents:p.totalCents,clampedReason:l}}async function md(e,t,n){return Qi(async()=>{let o=Jt()?await pd(e):null,s=await dd(e,t,n);return{budgetId:s.budgetId,totalCents:s.totalCents,closedPrevious:o,requestedCapCents:s.requestedCapCents,appliedCapCents:s.appliedCapCents,clampedReason:s.clampedReason}})}async function pd(e){let n=Jt()?.budgetId??Yi(),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){f.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return ns(),ee=null,kt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:o,finalCumulativeMicros:s}}async function is(e){return Qi(()=>pd(e))}function Jt(){return ns(),ee?new Date(ee.expiresAt).getTime()<=Date.now()?(ee=null,kt(null),null):{budgetId:ee.budgetId,totalCents:ee.totalCents,lastReceiptCumulative:ad(),lastReceiptCumulativeMicros:od()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:cd(),estimatedCumulative:ss(),lastToolSpend:id(),expiresAt:ee.expiresAt}:null}var gd=T(Fr()),fd=10000n;function Ay(e){return e<=0n?0:Number((e+fd-1n)/fd)}function hd(e){return Ay((0,gd.fromUsd)(e))}var as=T(Fr()),Ry=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function cs(e){if(typeof e!="string"||!Ry.test(e))return{ok:!1,error:"amount must be a USD amount with at most two decimal places"};let[t,n=""]=e.split("."),r=BigInt(t)*100n+BigInt(n.padEnd(2,"0"));if(r>BigInt(Number.MAX_SAFE_INTEGER))return{ok:!1,error:"amount is too large"};let o=Number(r);return o<=0?{ok:!1,error:"amount must be greater than $0.00"}:{ok:!0,cents:o,displayUsd:(0,as.toDisplay)((0,as.fromCents)(o),{symbol:""})}}var ls="Buying credits requires local biometric attestation from a Touch ID-capable Mac or a Windows Hello-capable PC running the Visa CLI. This device cannot create the required attestation, so no card charge was attempted. Credits are account-level, so you can top up this account from any interactive biometric-capable CLI, then use the balance from this remote server.",yd="Tell the user that buying credits requires a local CLI/MCP process with Touch ID (Mac) or Windows Hello (PC) today. Credits are account-level: suggest topping up the same account from any interactive biometric-capable CLI, then continuing on this remote server. Do not retry buy_credits from this process; it cannot produce the required card-charge attestation.";var _d=Promise.resolve(),bd=!1;function ys(e){let t=_d.catch(()=>{}).then(e);return _d=t.then(()=>{},()=>{}),t}async function Id(e){let t=await fe(()=>ea(I,Ue,{toolName:e.toolId,userContext:e.userContext})),n=Xi(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await Uy(),o,s,i=async()=>I.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:o,voucherReceiptHeader:s}=await i())}catch(u){if(u instanceof gt){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;f.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(p=>setTimeout(p,d)),{data:o,voucherReceiptHeader:s}=await i()}else throw u}}catch(u){if(u instanceof Fn){if(f.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await is(I),process.env.VISA_REQUIRE_EXPLICIT_SESSION==="true")throw new Error(`Your session was closed by another process (${u.code}). Restart MCP or run start_session again.`);return bd||(bd=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
|
|
138
|
-
To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),f.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),$d(e)}throw u instanceof gt?(f.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=qr(s)??(n?Zi(n):null);if(Br(o?.receipt_v2),await ld(e.estimatedAmountCents),sd({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),ia(o))return st(o);let c=await sa();if(e.idempotencyKey&&aa(o,c,e.idempotencyKey))return st(o);let l=c?Hr(c):null;return st(ca(o,r,l))}function Le(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function ps(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(ps).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${ps(r)}`).join(",")}}`}function oa(e,t,n,r){let o=pe.createHash("sha256").update(`${n}:${ps(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function Iy(e,t){return`${e}:${t}`}function $y(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 fs(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=He(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=$y(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:Iy(e,t),index:t,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...s?{amountMicros:s,amount_micros:s,cost_micros:s}:{}}}async function $d(e){return fe(()=>Oy(e))}async function Pd(e,t,n){if(ia(e))return st(e);let r=await sa();if(n&&aa(e,r,n))return st(e);let o=r?Hr(r):null;return st(ca(e,t,o))}async function Py(e){let t=e.cap,n=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (call cap $${(t/100).toFixed(2)})`,r=await Ue("shortcut_call",t,e.toolId,n,e.userContext);f.info("parentless-single-call:attempt",{tool:e.toolId,approvedMaxCents:t,attested:!!r});let o=r?.nonce??(await I.getAttestationChallenge()).nonce,{data:s,voucherReceiptHeader:i}=await I.shortcutParentless(e.toolId,{...r?{attestation:r}:{},nonce:o,approved_max_cents:t,idempotency_key:e.idempotencyKey},e.toolParams,e.timeoutMs,e.userContext,e.metaTool);return qr(i),Br(s?.receipt_v2),f.info("parentless-single-call:completed",{tool:e.toolId}),Pd(s,e.beforeBalanceMicros,e.idempotencyKey)}async function Oy(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await I.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new me(n.balanceCents,t);let r=t,o=Hr(n);if(Gu()){let l=e.idempotencyKey??pe.randomUUID();try{return await Py({toolId:e.toolId,toolParams:e.toolParams,estimatedAmountCents:e.estimatedAmountCents,cap:r,beforeBalanceMicros:o,userContext:e.userContext,metaTool:e.metaTool,timeoutMs:e.timeoutMs,idempotencyKey:l})}catch(u){if(u instanceof Qe)f.info("parentless-single-call:falling-back-to-session",{tool:e.toolId,status:u.status,serverErrorCode:u.serverErrorCode});else throw u}}let s=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Ue("session_create",r,"Visa CLI Session",s,e.userContext),a=await I.createSessionBudget({total_cents:r,session_kind:"one_shot",...i?{attestation:i}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let c=a.budget.id;kt(c),Vr(a.budget.totalCents),f.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});try{let l=Xi(e.idempotencyKey);if(!l)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:u,voucherReceiptHeader:d}=await I.shortcutWithSession(e.toolId,l,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(qr(d)||Zi(l),Br(u?.receipt_v2),ia(u))return st(u);let p=await sa();if(e.idempotencyKey&&aa(u,p,e.idempotencyKey))return st(u);let m=p?Hr(p):null;return st(ca(u,o,m))}finally{try{await I.closeSession(c)}catch(l){f.warn("on-demand-session:close-failed",{budgetId:c,error:l?.message||String(l)})}kt(null),f.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Xt(e){return ys(async()=>Jt()?Id(e):$d(e))}function _s(){return Ee()}var I=new Ae(()=>V.getSessionToken());function He(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Hr(e){return He(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function My(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 Ny(e){let t=He(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=He(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=He(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function us(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function Ly(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 Uy(){try{let e=await I.getBalance();return e.success?Hr(e):null}catch{return null}}async function sa(){try{let e=await I.getBalance();return e.success?e:null}catch{return null}}function ia(e){if(!e||e.success===!1)return!1;let t=He(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=He(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,e.charged_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function aa(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let o=He(r.deltaMicros)??BigInt(r.deltaCents)*10000n,s=o<0n?-o:o;if(s<=0n)return!1;let i=s.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(s)/1e6),!0}function ca(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 Dy="3.0.0
|
|
138
|
+
To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),f.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),$d(e)}throw u instanceof gt?(f.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=qr(s)??(n?Zi(n):null);if(Br(o?.receipt_v2),await ld(e.estimatedAmountCents),sd({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),ia(o))return st(o);let c=await sa();if(e.idempotencyKey&&aa(o,c,e.idempotencyKey))return st(o);let l=c?Hr(c):null;return st(ca(o,r,l))}function Le(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function ps(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(ps).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${ps(r)}`).join(",")}}`}function oa(e,t,n,r){let o=pe.createHash("sha256").update(`${n}:${ps(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function Iy(e,t){return`${e}:${t}`}function $y(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 fs(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=He(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=$y(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:Iy(e,t),index:t,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...s?{amountMicros:s,amount_micros:s,cost_micros:s}:{}}}async function $d(e){return fe(()=>Oy(e))}async function Pd(e,t,n){if(ia(e))return st(e);let r=await sa();if(n&&aa(e,r,n))return st(e);let o=r?Hr(r):null;return st(ca(e,t,o))}async function Py(e){let t=e.cap,n=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (call cap $${(t/100).toFixed(2)})`,r=await Ue("shortcut_call",t,e.toolId,n,e.userContext);f.info("parentless-single-call:attempt",{tool:e.toolId,approvedMaxCents:t,attested:!!r});let o=r?.nonce??(await I.getAttestationChallenge()).nonce,{data:s,voucherReceiptHeader:i}=await I.shortcutParentless(e.toolId,{...r?{attestation:r}:{},nonce:o,approved_max_cents:t,idempotency_key:e.idempotencyKey},e.toolParams,e.timeoutMs,e.userContext,e.metaTool);return qr(i),Br(s?.receipt_v2),f.info("parentless-single-call:completed",{tool:e.toolId}),Pd(s,e.beforeBalanceMicros,e.idempotencyKey)}async function Oy(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await I.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new me(n.balanceCents,t);let r=t,o=Hr(n);if(Gu()){let l=e.idempotencyKey??pe.randomUUID();try{return await Py({toolId:e.toolId,toolParams:e.toolParams,estimatedAmountCents:e.estimatedAmountCents,cap:r,beforeBalanceMicros:o,userContext:e.userContext,metaTool:e.metaTool,timeoutMs:e.timeoutMs,idempotencyKey:l})}catch(u){if(u instanceof Qe)f.info("parentless-single-call:falling-back-to-session",{tool:e.toolId,status:u.status,serverErrorCode:u.serverErrorCode});else throw u}}let s=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Ue("session_create",r,"Visa CLI Session",s,e.userContext),a=await I.createSessionBudget({total_cents:r,session_kind:"one_shot",...i?{attestation:i}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let c=a.budget.id;kt(c),Vr(a.budget.totalCents),f.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});try{let l=Xi(e.idempotencyKey);if(!l)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:u,voucherReceiptHeader:d}=await I.shortcutWithSession(e.toolId,l,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(qr(d)||Zi(l),Br(u?.receipt_v2),ia(u))return st(u);let p=await sa();if(e.idempotencyKey&&aa(u,p,e.idempotencyKey))return st(u);let m=p?Hr(p):null;return st(ca(u,o,m))}finally{try{await I.closeSession(c)}catch(l){f.warn("on-demand-session:close-failed",{budgetId:c,error:l?.message||String(l)})}kt(null),f.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Xt(e){return ys(async()=>Jt()?Id(e):$d(e))}function _s(){return Ee()}var I=new Ae(()=>V.getSessionToken());function He(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Hr(e){return He(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function My(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 Ny(e){let t=He(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=He(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=He(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function us(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function Ly(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 Uy(){try{let e=await I.getBalance();return e.success?Hr(e):null}catch{return null}}async function sa(){try{let e=await I.getBalance();return e.success?e:null}catch{return null}}function ia(e){if(!e||e.success===!1)return!1;let t=He(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=He(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,e.charged_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function aa(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let o=He(r.deltaMicros)??BigInt(r.deltaCents)*10000n,s=o<0n?-o:o;if(s<=0n)return!1;let i=s.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(s)/1e6),!0}function ca(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 Dy="3.0.0",Ix=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily top-up limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
|
|
139
139
|
`);function Ge(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=yr(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(Ul())return{opened:!1,url:t,blockedReason:"suppressed"};let n=zs();if(n.headless)return f.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=bc(t,_s());if(!r)return f.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=wc(r);return o?((0,Rd.execFile)(o.cmd,o.args,s=>{s&&f.warn(`Browser open failed: ${s.message}. URL: ${r}`)}),{opened:!0,url:r}):(f.info(`No browser command for platform "${Kr.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function fe(e){return Qn(I,e,Fd)}var Od="get_cards",Md="set_default_card";function jy(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 '${Od}' to see enrolled cards and '${Md}' to switch, then retry the original request.`}function Fy(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 '${Od}' to see enrolled cards and '${Md}' to switch. Do not retry automatically.`}function We(e,t){let n=e.retryable?jy(e.code,e.retryAfter):Fy(e.code,t.merchantName);return{success:!1,declined:!0,retryable:e.retryable,code:e.code,reason:e.reason,payment_error_class:e.paymentErrorClass,correlation_id:e.correlationId,transactionId:e.transactionId,retryAfter:e.retryAfter,merchantName:t.merchantName,amount:t.amount,message:e.message,agent_guidance:n}}function Vy(e){return{success:!1,error:e.message,error_code:e.code,transactionId:e.transactionId,reconciliation_required:e.reconciliationRequired,retryable:e.retryable,agent_guidance:"The top-up charge outcome is ambiguous. Tell the user not to retry with a new idempotency key or start another top-up. They should check transaction_history in a few minutes or contact support with the transactionId."}}var tr=null,qy=3e4;function Nd(){tr=null}var Yt=class extends Error{constructor(n){super(`${gs()} attestation is required for this action, but it is not available in this MCP process. `+la());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function bs(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. `+la()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function By(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:ls,agent_guidance:yd}}function gs(){return process.platform==="darwin"?"Touch ID":"local biometric"}function la(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}async function Hy(e){let t=Date.now();if(tr&&tr.expiresAt>t)return{required:tr.required,hasRegisteredKey:tr.hasRegisteredKey};try{let n=await I.getStatus(e),r=n.attestationRequired!==!1,o=it(n);return tr={required:r,hasRegisteredKey:o,expiresAt:t+qy},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Ue(e,t,n,r,o,s){if(!s?.forceRequired){let i=await Hy(o);if(!i.required){f.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){f.info("attestation:skipped-no-registered-key",{context:e});return}}if(!ie())throw f.warn("attestation:unavailable",{context:e}),new Yt(e);f.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await I.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");f.info("touchid:prompt",{context:e,amount:t,merchant:n});let c=await Tn(a,r);return f.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:c,nonce:i,amount:t,merchant:n}}catch(i){throw f.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var vd="[dry-run] https://placeholder.visa-cli.dev/image.png",Ky=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"]),Gy=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 Wy(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||Ky.has(e)?"image":t==="generate_video"||Gy.has(e)?"video":zy(e)?"media":null}function zy(e){let t=Xn(e);return t?!da(t):!1}function Jy(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function Yy(e){return e==="llm"?"OpenRouter":"fal.ai"}function nr(e,t,n,r){let o={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:Yy(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${Jy(n)}`;return{...o,content:i,data:{content:i,model:t,dry_run:!0}}}return{...o,urls:[vd],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:vd,metadata:{dry_run:!0}}}}async function ta(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await I.emitTelemetry([{id:pe.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(o){f.warn("dry_run:telemetry_failed",{tool:e.toolName,error:o?.message||String(o),mode:t})}}var Xy="https://openrouter.ai/api/v1/chat/completions",Zy="openrouter/free",Qy=50,e_=15e3;function t_(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 n_(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return f.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:nr("llm",e,t,n),degraded:!0,resolvedModel:null};let o=t_(t),s;try{s=await Ze(Xy,{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:Zy,messages:[{role:"user",content:o}],max_tokens:Qy}),timeoutMs:e_})}catch(u){return f.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:nr("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!s.ok){let u=await s.text().catch(()=>"");return f.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:s.status,bodyExcerpt:u.slice(0,200)}),{result:nr("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await s.json()}catch(u){return f.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:nr("llm",e,t,n),degraded:!0,resolvedModel:null}}let a=typeof i?.choices?.[0]?.message?.content=="string"?i.choices[0].message.content:"",c=typeof i?.model=="string"?i.model:null;return{result:{success:!0,transactionId:`preflight:${n??e}`,amount:0,rail:"preflight",merchantName:"OpenRouter",dry_run:!0,preflight:!0,metadata:{dry_run:!0,preflight:!0,model_used:c},content:a,data:{content:a,model:c??e,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:c}}async function Gr(e,t,n,r){let o=Bi();if(!o)return null;let s=Wy(e,r);if(!s)return null;let i=Date.now();if(o==="mock"){let l=nr(s,e,t,r);return await ta({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"mock"}),f.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),l}if(s!=="llm"){f.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:s});let l=nr(s,e,t,r);return await ta({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"preflight"}),l}let{result:a,resolvedModel:c}=await n_(e,t,r);return await ta({toolName:r??e,resolvedModel:c??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),f.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),a}async function Ct(e,t,n){let r=await I.paymentPreview({tool:e,url:t},n);if(!r||!r.merchantName||r.amount===void 0||r.amount===null||r.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(r.amount)||r.amount<0||r.amount>999999)throw new Error(`Invalid payment amount: ${r.amount}. Payment rejected for safety.`);return r}function Tt(e){return hd(e.amount)}function r_(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,Tt(t[e.resolvedTool]))}function o_(){return hs.join(Kr.homedir(),".visa-mcp","allium-results")}var $x=16*1024,Px=50*1024*1024;function s_(){let e=o_();try{if(!Ke.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Ke.readdirSync(e),n=0,r=0;for(let o of t)try{let s=Ke.statSync(hs.join(e,o));s.isFile()&&(n+=s.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return f.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var wd=3600*1e3,na=0;function i_(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Wr(e){if(!Dl()&&!(Date.now()<na))try{if(!await V.getSessionToken())return;await I.feedSubmit({prompt:e.prompt,tool:e.tool,media_url:e.mediaUrl,media_type:e.mediaType,cost:e.cost,transaction_id:e.transactionId,auto:!0,...e.userContext&&{user_context:e.userContext}}),f.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(i_(t)){let n=na===0;na=Date.now()+wd,n&&f.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:wd});return}f.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function a_(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),o=(e.start_date||"").trim(),s=(e.end_date||o).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(o))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(s&&!/^\d{4}-\d{2}$/.test(s))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,c=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;f.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await fe(async()=>{let l=await Ue("get_visa_smi",a,i,c),u=await I.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:l,idempotencyKey:pe.randomUUID()},t);return u.success?f.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):f.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(l){if(l instanceof oe)return f.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),We(l,{amount:a,merchantName:i,description:"Visa SMI data"});throw f.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:l.message}),l}}async function c_(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 Gr("generate_image_card",e,t);if(n)return n;let r=await Ct("generate_image_card",void 0,t),o=pe.randomUUID();f.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let s;try{s=await Xt({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:Tt(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof me)return Le(i);throw i}return f.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ge(i)),Wr({prompt:e.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):f.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof oe)return f.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),We(s,r);throw f.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function l_(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 Gr("generate_image_fast_card",e,t);if(n)return n;let r=await Ct("generate_image_fast_card",void 0,t),o=pe.randomUUID();f.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let s;try{s=await Xt({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:Tt(r),userContext:t,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof me)return Le(i);throw i}return f.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)),Wr({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):f.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof oe)return f.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),We(s,r);throw f.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function u_(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 Gr("generate_video_tempo_card",e,t);if(n)return n;let r=await Ct("generate_video_tempo_card",void 0,t),o=pe.randomUUID();f.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let s;try{s=await Xt({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:Tt(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof me)return Le(i);throw i}return f.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)),Wr({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"video",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):f.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof oe)return f.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),We(s,r);throw f.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function d_(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 Ct("generate_music_tempo_card",void 0,t),r=pe.randomUUID();f.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let o;try{o=await Xt({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:Tt(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof me)return Le(s);throw s}return f.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)),Wr({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,f.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):f.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof oe)return f.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),We(o,n);throw f.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function m_(e,t){let n=await Ct("check_music_status_tempo_card",void 0,t),r=pe.randomUUID();f.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let o;try{o=await Xt({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:Tt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof me)return Le(s);throw s}return f.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 oe)return f.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),We(o,n);throw f.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function p_(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 Ct("query_onchain_prices",void 0,t),r=pe.randomUUID();f.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let o;try{o=await Xt({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:Tt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof me)return Le(s);throw s}if(f.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 oe)return f.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),We(o,n);throw f.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var f_=["generate_music_tempo_card"],ds=10,Sd=5,xd=new Map;function kd(e){let t=xd.get(e);if(t!==void 0)return t;let r=Xn(e)?.isAsync===!0||f_.includes(e);return xd.set(e,r),r}var g_=36e4,h_=18e4,y_=15e3,__=12e4,b_=2e3;function ra(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function v_(e,t){return pe.createHash("sha256").update(`${e}:${ps(t)}`).digest("hex")}function w_(e){let{results:t,batchId:n,index:r,item:o,itemResult:s,preview:i,isFree:a,catalogName:c}=e;a&&s&&typeof s=="object"&&!Array.isArray(s)&&s.merchantName==null&&(s.merchantName=c??o.resolvedTool),t.push({success:s?.success!==!1,tool:o.resolvedTool,...s,...fs(n,r,s)});let l=0,u=0n;if(s?.success!==!1){let d=He(s?.amountMicros??s?.amount_micros),p=typeof s?.amount=="number"?s.amount:i?.amount??0;d!==null&&d>0n?u+=d:u+=BigInt(Math.round(p*1e6)),l+=p}return s?.urls&&s.urls.forEach(d=>Ge(d)),{deltaCharged:l,deltaMicros:u}}function S_(e){let{results:t,resolvedItems:n,uniqueTools:r,isHomogeneous:o,primaryTool:s,merchantNames:i,totalAmount:a,totalCharged:c,totalChargedMicros:l,batchId:u,mode:d}=e,p=t.filter(N=>N?.success===!1).length,m=t.length-p,g=t.flatMap(N=>Array.isArray(N?.urls)?N.urls:[]),y=l>0n?Number(l)/1e6:Math.round((c+Number.EPSILON)*100)/100,w=m===0?"failure":p===0?"success":"partial";return f.info("payment:success",{tool:"batch",batchTool:s,count:n.length,totalAmount:a,totalCharged:y,merchant:i,successCount:m,failedCount:p,outcome:w,mode:d,batchId:u}),{success:m>0,outcome:w,batch_id:u,tool:o?r[0]:s,count:n.length,successCount:m,failedCount:p,totalCharged:y,...l>0n?{totalChargedMicros:l.toString(),amountMicros:l.toString(),amount_micros:l.toString()}:{},merchantName:i,results:t,...g.length?{urls:g}:{}}}async function x_(e){let{resolvedItems:t,previews:n,freeTools:r,catalogEntries:o,itemCeilingCents:s,batchCeilingCents:i,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,timeoutMs:p,batchId:m,userContext:g}=e,y=i,w=await I.getBalance();if(!w.success)throw new Error(`Could not read balance: ${w.error||"unknown error"}`);if(w.balanceCents<y)throw new me(w.balanceCents,y);let N=`batch-${m}`,U=`spend up to $${(y/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:v}=await fe(async()=>{let _=await Ue("batch_open",y,N,U,g,{forceRequired:!0}),C=_?.nonce??(await I.getAttestationChallenge()).nonce;f.info("parentless-batch:open-attempt",{batchTool:l,count:t.length,approvedTotalCents:y,attested:!!_});let{batch_parent_id:he}=await I.batchOpen({..._?{attestation:_}:{},nonce:C,approved_total_cents:y,batch_id:m});return{batchParentId:he}});f.info("parentless-batch:opened",{batchTool:l,count:t.length,batchParentId:v});let x=[],$=0,O=0n;try{for(let _=0;_<t.length;_+=1){let C=t[_],he=n[C.resolvedTool],ye=r.has(C.resolvedTool);try{let Y;if(ye)Y=await I.shortcut(C.resolvedTool,C.params,p,g,"batch");else{let{data:ne,voucherReceiptHeader:cr}=await I.shortcutParentlessBatchItem(C.resolvedTool,{batch_parent_id:v,batch_id:m,batch_index:_,batch_request_hash:v_(C.resolvedTool,C.params),item_ceiling_cents:s[_],idempotency_key:oa(m,_,C.resolvedTool,C.params)},C.params,p,g,"batch");qr(cr),Br(ne?.receipt_v2),Y=await Pd(ne,null,oa(m,_,C.resolvedTool,C.params))}let{deltaCharged:Qt,deltaMicros:le}=w_({results:x,batchId:m,index:_,item:C,itemResult:Y,preview:he,isFree:ye,catalogName:o[C.resolvedTool]?.name});$+=Qt,O+=le}catch(Y){if(Y instanceof me&&x.length===0)return Le(Y);f.warn("payment:batch-item-failed",{tool:C.resolvedTool,index:_,error:Y?.message||String(Y)}),x.push({success:!1,tool:C.resolvedTool,...fs(m,_),error:Y?.message||String(Y)})}}return S_({results:x,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:$,totalChargedMicros:O,batchId:m,mode:"parentless"})}catch(_){if(_ instanceof oe)return f.warn("payment:declined",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,code:_.code,retryable:_.retryable}),We(_,{amount:d,merchantName:u});throw f.error("payment:failure",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,error:_.message}),_}}async function k_(e,t){let n;if(e.requests?.some(_=>_.tool||_.tool_id)&&e.requests)n=e.requests.map(_=>{let C=_.tool||_.tool_id||e.tool;if(!C)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let he=Gt(C,_.tier||e.tier,_.prompt??t),{tool:ye,tool_id:Y,tier:Qt,params:le,...ne}=_,cr=le&&typeof le=="object"?{...le,...ne}:ne;return{resolvedTool:he,params:cr}});else if(e.tool){let _=Gt(e.tool,e.tier,e.params?.prompt??t);if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return ra("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>ds)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ds} items. Please split into smaller batches.`}}n=(e.requests||(e.count!==void 0&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(he=>({resolvedTool:_,params:he}))}else return ra("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return ra("BATCH_EMPTY","Batch requires at least one item.");if(n.length>ds)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ds} items. Please split into smaller batches.`};if([...new Set(n.map(_=>_.resolvedTool))].some(kd)&&n.length>Sd)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Sd} items. Please use multiple batches for more.`};let i=[...new Set(n.map(_=>_.resolvedTool))],a=i.length===1,c={};for(let _ of i)c[_]=await Vd(_);let l=new Set(i.filter(_=>c[_]&&da(c[_]))),u={};for(let _ of i)l.has(_)||(u[_]=await Ct(_,void 0,t));let d=0;for(let _ of n)d+=u[_.resolvedTool]?.amount??0;let p=n.map(_=>r_(_,u,l)),m=p.reduce((_,C)=>_+C,0),g=[...new Set([...Object.values(u).map(_=>_.merchantName),...i.filter(_=>l.has(_)).map(_=>c[_]?.name??_)])].join(", "),y=a?i[0]:"mixed";f.info("payment:attempt",{tool:"batch",batchTool:y,count:n.length,totalAmount:d,merchant:g,heterogeneous:!a});let w=n.some(_=>kd(_.resolvedTool)),N=n.some(_=>_.resolvedTool.startsWith("or-")||_.resolvedTool==="run_llm"||_.resolvedTool==="execute_tool"),U=w?g_:N?h_+n.length*y_:__+n.length*b_,v=pe.randomUUID(),x=[],$=0,O=0n;return ys(async()=>{let _=!Jt();if(Wu()&&_&&m>0)try{return await x_({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:p,batchCeilingCents:m,uniqueTools:i,isHomogeneous:a,primaryTool:y,merchantNames:g,totalAmount:d,timeoutMs:U,batchId:v,userContext:t})}catch(C){if(C instanceof Qe)f.info("parentless-batch:falling-back-to-session",{batchTool:y,count:n.length,status:C.status,serverErrorCode:C.serverErrorCode});else{if(C instanceof me)return Le(C);throw C}}if(_&&m>0)try{let C=m;await fe(()=>ea(I,Ue,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:C,capCentsOverride:C}))}catch(C){return C instanceof me?Le(C):(f.warn("payment:batch-prewarm-failed",{batchTool:y,count:n.length,error:C?.message||String(C)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:C?.message||"Failed to authenticate batch session",tool:y,count:n.length,failedCount:n.length,results:[]})}try{for(let le=0;le<n.length;le+=1){let ne=n[le],cr=u[ne.resolvedTool];try{let Z=l.has(ne.resolvedTool)?await I.shortcut(ne.resolvedTool,ne.params,U,t,"batch"):await Id({toolId:ne.resolvedTool,toolParams:ne.params,estimatedAmountCents:p[le],userContext:t,metaTool:"batch",timeoutMs:U,idempotencyKey:oa(v,le,ne.resolvedTool,ne.params)});if(l.has(ne.resolvedTool)&&Z&&typeof Z=="object"&&!Array.isArray(Z)&&Z.merchantName==null&&(Z.merchantName=c[ne.resolvedTool]?.name??ne.resolvedTool),x.push({success:Z?.success!==!1,tool:ne.resolvedTool,...Z,...fs(v,le,Z)}),Z?.success!==!1){let lr=He(Z?.amountMicros??Z?.amount_micros),Wa=typeof Z?.amount=="number"?Z.amount:cr?.amount??0;lr!==null&&lr>0n?O+=lr:O+=BigInt(Math.round(Wa*1e6)),$+=Wa}Z?.urls&&Z.urls.forEach(lr=>Ge(lr))}catch(Z){if(Z instanceof me&&x.length===0)return Le(Z);f.warn("payment:batch-item-failed",{tool:ne.resolvedTool,index:le,error:Z?.message||String(Z)}),x.push({success:!1,tool:ne.resolvedTool,...fs(v,le),error:Z?.message||String(Z)})}}let C=x.filter(le=>le?.success===!1).length,he=x.length-C,ye=x.flatMap(le=>Array.isArray(le?.urls)?le.urls:[]),Y=O>0n?Number(O)/1e6:Math.round(($+Number.EPSILON)*100)/100,Qt=he===0?"failure":C===0?"success":"partial";return f.info("payment:success",{tool:"batch",batchTool:y,count:n.length,totalAmount:d,totalCharged:Y,merchant:g,successCount:he,failedCount:C,outcome:Qt,mode:"session",batchId:v}),{success:he>0,outcome:Qt,batch_id:v,tool:a?i[0]:y,count:n.length,successCount:he,failedCount:C,totalCharged:Y,...O>0n?{totalChargedMicros:O.toString(),amountMicros:O.toString(),amount_micros:O.toString()}:{},merchantName:g,results:x,...ye.length?{urls:ye}:{}}}catch(C){if(C instanceof oe)return f.warn("payment:declined",{tool:"batch",batchTool:y,count:n.length,totalAmount:d,merchant:g,code:C.code,retryable:C.retryable}),We(C,{amount:d,merchantName:g});throw f.error("payment:failure",{tool:"batch",batchTool:y,count:n.length,totalAmount:d,merchant:g,error:C.message}),C}finally{if(_){let C=await is(I);f.info("batch-session:closed",{budgetId:C.budgetId,closedServerSide:C.closedServerSide})}}})}function C_(){let e=!1,t;try{let r=hs.join(Kr.homedir(),".claude","settings.json");if(Ke.existsSync(r)){let o=JSON.parse(Ke.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";e=Nt(s)}}catch{}let n=wo();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function T_(e){let[t,n]=await Promise.all([I.getStatus(e),I.getBalance().catch(s=>(f.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=s_();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=C_(),!t.hud.statusLine&&!t.hud.shellHud&&(t._hud_nudge="The user has no HUD surfaces enabled. Mention once, naturally, that they can enable a live spend dashboard with `visa-cli config hud enable` \u2014 it shows balance, active tools, and spend on every prompt."),t.version=Dy,Array.isArray(t.cards)&&(t.cards=t.cards.map(s=>({...s,displayName:ua(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=Jt();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 ua(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 Ld(e,t){try{let r=((await I.getStatus(t)).cards||[]).find(o=>o?.id===e);if(r)return ua(r)}catch(n){f.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function E_(e){let n=(await I.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(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:ua(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 A_(e,t){return await I.getTransactions({limit:e.limit,offset:e.offset},t)}async function R_(e,t){return await I.feedback(e.message,e.transaction_id,t)}async function I_(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return An("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=cs(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,o=r/100,s=pe.randomUUID();f.info("buy_credits:attempt",{amountCents:r});try{return await fe(async()=>{let i=await Ue("balance-topup",o,"Visa CLI Balance",`top up balance with $${n.displayUsd}`,t,{forceRequired:!0}),a=await I.topupBalance({amount_cents:r,idempotency_key:s,attestation:i});if(a.success){f.info("buy_credits:success",{amountCents:r,balanceCents:a.balanceCents});let c=((a.balanceCents??0)/100).toFixed(2),l=(r/100).toFixed(2);return{...a,amount:r/100,amountMicros:String(r*1e4),merchantName:"Visa CLI Balance",message:`Added $${l} \u2014 balance is now $${c}`}}return f.warn("buy_credits:failed",{amountCents:r,error:a.error}),a})}catch(i){if(i instanceof Yt)return By();if(i instanceof et)return f.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),Vy(i);throw f.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function An(e,t){return{success:!1,error:t,code:e,message:t}}async function $_(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return An("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01))return An("INVALID_VALUE","maxTransactionAmount must be at least $0.01");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1))return An("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return An("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");f.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await fe(async()=>{let n=await Ue("spending-controls",0,"","update spending controls"),r=await I.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return f.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(f.error("spending_controls:failure",{error:n.message}),n instanceof Yt)return bs(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return An("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function P_(e){let t=await jr({api:I,includeDev:!!e.includeDev});return{config:t.entries.map(n=>({key:n.key,value:n.value,source:n.source,hint:n.hint})),statusError:t.statusError}}async function O_(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."};f.info("config:set",{key:e.key});try{let t=Uo(e.key,e.value);return f.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 ht?"UNKNOWN_KEY":t instanceof yt?"SERVER_CONTROLLED":t instanceof Lt?"RETIRED_KEY":"INVALID_VALUE";return f.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(Dt).sort()}}}async function M_(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."};f.info("config:unset",{key:e.key});try{let t=Do(e.key);return f.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 ht?"UNKNOWN_KEY":t instanceof yt?"SERVER_CONTROLLED":t instanceof Lt?"RETIRED_KEY":"INVALID_VALUE";return f.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(Dt).sort()}}}async function N_(e){let t=await I.getStatus(e),n=t.attestationRequired!==!1,r=it(t),o=ie(),s=n?r?o?`${gs()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${gs()} is not available in this process. ${la()}`:"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 L_(e){f.info("biometric:on");let t=await Qo(I,e);if(t.ok===!1)return{success:!1,error:t.code,error_code:t.code,message:t.message,agent_guidance:`${t.message} Do not call biometric_on again until the user has completed setup in an interactive terminal.`};let n=await I.setBiometricPreference({required:!0},e);return n.success?(Nd(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function U_(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return An("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.");f.info("biometric:off");try{return await fe(async()=>{let n=await I.getStatus(t),r;if(it(n)&&(r=await Ue("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${gs()} confirmation required to disable \u2014 not available on this device.`);let o=await I.setBiometricPreference({required:!1,attestation:r},t);if(!o.success)throw new Error(o.error||"unknown error");return Nd(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(f.error("biometric:off:failure",{error:n.message}),n instanceof Yt)return bs(n,"biometric_off");throw n}}var Cd=3e4,D_=3e5;async function Ud(e,t,n="login"){let r=pe.randomUUID(),o=`${e}${e.includes("?")?"&":"?"}state=${r}`,s=Ge(o);return!s.opened&&s.blockedReason!=="non_internal_host"&&s.blockedReason!=="invalid_url"?Dd(o,s,n):s.opened?{...await jd(r,t,n),browserUrl:o}:{success:!1,browserUrl:o,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${o}`}}function Dd(e,t,n){let r=n==="enrollment"?"card enrollment":n==="attestation-recovery"?"biometric reset":"login",o=t.blockedReason==="suppressed"?"browser auto-open is suppressed":t.blockedReason==="headless"?"this process appears to be headless":t.blockedReason==="unsupported_platform"?"this platform has no configured browser opener":"browser auto-open is unavailable";return{success:!1,requiresBrowser:!0,browserUrl:e,message:`Browser auto-open was skipped because ${o}. Open this URL to continue ${r}: ${e}`}}async function jd(e,t,n="login"){let r=Date.now()+D_;for(;Date.now()<r;)try{let s=await fetch(`${_s()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Cd,...t&&{user_context:t}}),signal:AbortSignal.timeout(Cd+5e3)});if(!s.ok){await Pt(s,a=>{f.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 f.info("auth:attestation_recovery_complete",{user:i.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=i.welcomeBonusCents??0,c=Zu(a);if(n!=="enrollment"&&i.sessionToken){await V.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return f.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...c||{}}}let l=i.last4||"****";return f.info("auth:card_added",{last4:l,bonusCents:a}),{success:!0,message:`Card ending in ${l} enrolled and ready for payments.`,...c||{}}}}catch{await Pt(void 0,s=>{f.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 Fd(e){let t=pe.randomUUID(),n;try{n=await I.startAttestationRecovery(t,e)}catch(s){return{success:!1,message:`Could not start biometric reset: ${s?.message||"unknown error"}`}}if(!n.success||!n.recoveryUrl)return{success:!1,message:n.error||"Could not start biometric reset. Please try again."};let r=Ge(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?Dd(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await jd(t,e,"attestation-recovery"),browserUrl:n.recoveryUrl}:{success:!1,browserUrl:n.recoveryUrl,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${n.recoveryUrl}`}}async function j_(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."};f.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,o=`remove ${await Ld(n,t)}`;try{return await fe(async()=>{let s=await Ue(r,0,"",o,t,{forceRequired:!0}),i=await I.removeCard(n,{attestation:s},t);return f.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(s){if(f.error("cards:remove_failure",{cardId:n,error:s.message}),s instanceof Yt)return bs(s,"remove_card");throw s}}async function F_(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."};f.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,o=`set ${await Ld(n,t)} as default`;try{return await fe(async()=>{let s=await Ue(r,0,"",o,t,{forceRequired:!0}),i=await I.setDefaultCard(n,{attestation:s},t);return f.info("cards:set_default_success",{cardId:n}),i})}catch(s){if(f.error("cards:set_default_failure",{cardId:n,error:s.message}),s instanceof Yt)return bs(s,"set_default_card");throw s}}async function V_(e){return f.info("auth:login_attempt"),Ud(`${_s()}/login`,e)}function q_(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 B_(e={},t){let n;try{n=q_(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return ys(async()=>{let r=await fe(()=>md(I,Ue,{toolName:"start_session",userContext:t,capCentsOverride:n}));f.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 H_(){let e=Jt();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 K_(){return ys(async()=>{let e=Jt();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 is(I);f.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=Ny(e),r=He(t.finalCumulativeMicros),o=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),s=Number(o/10000n);return f.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 ${My(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 G_(e){if(f.info("auth:add_card_attempt"),!await V.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await I.createEnrollCode();return Ud(`${_s()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function Td(){if(await V.clearAll(),ie())try{await Zo()}catch{}}async function W_(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(f.info("reset:attempt"),e.localOnly)return await Td(),f.info("reset:success",{localOnly:!0}),{success:!0,message:"Device reset locally. Local credentials and keys have been removed; server-side session and biometric state were not changed. Use the login tool or visa-cli setup to sign in with the GitHub account you want to use."};let n=!1;try{let r=await I.getStatus(t);if(r&&it(r)){let o=await Fd(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}`};f.warn("reset:server_attestation_status_unavailable",{error:o})}try{await I.logout(void 0,t)}catch{}return await Td(),f.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 z_(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;f.info("catalog:discover",{query:t,category:n,browseAll:r});try{let s=(await I.catalogSearch(t,n)).tools||[];if(s.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let l of s){let u=l.category||"other";(a[u]??=[]).push(l)}let c=Object.keys(a).sort().map(l=>{let u=a[l].map((p,m)=>`${m+1}. **${p.name}** (${p.id})
|
|
140
140
|
${p.description}
|
|
141
141
|
Provider: ${p.provider} | Price: ${Ed(p)}${Ad(p)}
|
|
@@ -163,7 +163,7 @@ Use execute_tool with the tool id and required params to run any of these.`}],_t
|
|
|
163
163
|
`),!0}function Bd(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(o=>typeof o=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length===0)return{prompt:"a lobster"};let r={};for(let o of t)r[o]=tb(o,n[o]?.description);return r}function tb(e,t){let n=e.toLowerCase();return n==="prompt"?"a lobster":n==="text"?"Hello from Visa CLI.":n.endsWith("image_url")||n==="image_url"?"https://example.com/sample.jpg":n.endsWith("audio_url")||n==="audio_url"?"https://example.com/sample.wav":n.endsWith("video_url")||n==="video_url"?"https://example.com/sample.mp4":n==="taskid"||n==="task_id"?"task_abc123":n==="request_id"||n==="requestid"?"req_abc123":n==="model_path"||n==="model"?"fal-ai/flux/schnell":n==="language"?"en":t&&/\bUR?L\b|https?:\/\//i.test(t)?"https://example.com/sample":"example"}function nb(e){let t=at(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=at(e.referralLink,"");if(r&&n.push(` Your link ${r}`),typeof e.referralCount=="number"&&Number.isFinite(e.referralCount)){let o=Math.max(0,Math.trunc(e.referralCount));n.push(` Joined ${o} ${o===1?"person":"people"} via your link`)}return n}var rb=20;function Kd(e,t,n,r){let o=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=ub(e.spendingControls).dailyLimit,a=Math.max(0,zr(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,zr(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(ib),p=d.slice(0,3),m=ab(d,3),g=(e.cards??[]).slice(0,3),y=r.latestVersion?Rn(r.latestVersion):"",w=r.updateCheckDisabled?"update checks disabled":y?`update ready: v${y}`:"up to date",N=Math.round(l*100),U=at(e.status,e.enrolled?"approved":"not enrolled"),x=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${U} | touch id: ${n?"ready":"unavailable"}`,`Version: v${o} | ${w}`,`Top-up meter: ${Hd(l)} ${String(N).padStart(3," ")}% | remaining ${rr(c)}/day | daily top-up cap ${rr(i)}`,"","Card top-ups",` Remaining ${rr(c)} / ${rr(i)}`,` Usage ${Hd(l)} ${N}%`,` Top-ups today ${rr(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...g.length>0?g.map(O=>` ${lb(O)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((O,_)=>` ${_+1}. ${O}`):[" No paid services yet"],"","Recent receipts",...p.length>0?p.map(O=>` ${cb(O)}`):[" No receipts yet"]],$=nb(e);return $.length>0&&x.push("",...$),y&&!r.updateCheckDisabled?(x.push("",`Update: v${y} ready \u2014 run \`visa-cli update\``),r.updateMessage&&x.push(` ${Rn(r.updateMessage)}`)):r.updateMessage&&x.push("",`Update: ${Rn(r.updateMessage)}`),`${x.join(`
|
|
164
164
|
`)}
|
|
165
165
|
`}function ob(e){return e.tool_name!=null}function sb(e){return zr(e.amount)===0&&e.status==="failed"}function ib(e){return ob(e)&&!sb(e)}function ab(e,t=1/0){let n=new Set,r=[];for(let o of e){if(r.length>=t)break;let s=at(o.merchant_name,"Unknown merchant"),i=at(o.tool_name,"unknown_tool"),a=`${s} :: ${i}`;n.has(a)||(n.add(a),r.push(`${s} [${i}]`))}return r}function cb(e){let t=at(e.merchant_name,"Unknown merchant"),n=at(e.tool_name,"unknown_tool"),r=rr(zr(e.amount)),o=at(e.status,"unknown"),s=db(e.created_at);return`${r} ${o.padEnd(9)} ${t} [${n}] ${s}`}function lb(e){let t=at(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function ub(e){return{dailyLimit:zr(e?.daily_limit??e?.dailyLimit??0)}}function zr(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function rr(e){return`$${e.toFixed(2)}`}function Hd(e,t=rb){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function at(e,t){let n=Rn(e??"").trim();return n.length>0?n:t}function db(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?at(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function Rn(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ")}var mb=/^[1-9]\d{0,9}$/;function ma(e){if(!mb.test(e))throw new Error("card id must be a positive integer with up to 10 digits. Run `visa-cli cards list` first.");return Number(e)}function Gd(e){let t=Rn(e.brand||"Visa"),n=Rn(e.last4||"unknown");return{id:Number.isInteger(e.id)?String(e.id):"-",brand:t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),card:`****${n}`,default:e.isDefault?"yes":""}}var ct=T(require("fs")),ae=T(require("path")),pb=["npm","pnpm","yarn","bun"],fb=/\s+/,gb=process.platform==="win32"?"visa-cli.cmd":"visa-cli",pa=["node_modules","@visa","cli"];function hb(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(fb)[0]??"",r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);return pb.includes(o)?o:void 0}function fa(e){if(!e)return;let t=e;try{t=ct.realpathSync(e)}catch{}let n=t.replace(/\\/g,"/").toLowerCase();if(n.includes("/pnpm/")||n.includes("/.pnpm/"))return"pnpm";if(n.includes("/yarn/")||n.includes("/.yarn/"))return"yarn";if(n.includes("/bun/")||n.includes("/.bun/"))return"bun";if(n.includes("/npm/")||n.includes("/node_modules/@visa/cli/"))return"npm"}function yb(e=process.argv[1]){return hb()??fa(process.env.npm_execpath)??fa(process.env.npm_node_execpath)??fa(e)}function _b(e=process.env.PATH??""){let t=[];for(let n of e.split(ae.delimiter))n&&t.push(n);return t}function bb(e=process.env.PATH??""){let t=new Set,n=[];for(let r of _b(e))try{let o=ae.join(r,gb);ct.accessSync(o,ct.constants.X_OK);let s=ae.resolve(o);t.has(s)||(t.add(s),n.push(o))}catch{}return n}function Wd(e){try{let t=ct.readFileSync(ae.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function vb(e){let t=ae.resolve(e).split(ae.sep);for(let n=t.length-pa.length;n>=0;n--)if(pa.every((r,o)=>t[n+o]===r)){let r=t.slice(0,n+pa.length).join(ae.sep)||ae.sep;if(Wd(r))return r}}function wb(e){if(!e)return;let t=ae.normalize(e),n=t.split(ae.sep),r=s=>s.every((a,c)=>n[n.length-s.length+c]===a)?n.slice(0,-s.length).join(ae.sep)||ae.parse(t).root:void 0,o=r(["lib","node_modules","@visa","cli"]);if(o)return o;if(process.platform==="win32")return r(["node_modules","@visa","cli"])}function Sb(e,t){let n=ae.resolve(e);try{n=ct.realpathSync(e)}catch{}let r=vb(n);return{binPath:e,realPath:n,packageRoot:r,version:r?Wd(r):void 0,prefix:wb(r),isActive:n===t}}function xb(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?ae.resolve(n):"";try{n&&(r=ct.realpathSync(n))}catch{}let o=e?[e]:[n,...bb(t)].filter(Boolean),s=new Map;for(let d of o){let p=Sb(d,r),m=s.get(p.realPath);s.set(p.realPath,m?{...p,binPath:m.binPath}:p)}let i=[...s.values()],a=i.find(d=>d.isActive);!a&&i.length>0&&!e&&(a={...i[0],isActive:!0},i[0]=a);let c=new Set(i.map(d=>d.packageRoot).filter(Boolean)),l=!!a?.packageRoot&&c.size>1,u=a?.prefix;return{active:a,installs:i,hasConflictingInstalls:l,recommendedPrefix:u}}function kb(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function ga(e,t,n,r={}){let o=t??yb(n)??"npm",s=r.withDiagnostics?xb(n):void 0,a=`@visa/cli@${e??"latest"}`;switch(o){case"npm":if(s?.hasConflictingInstalls&&s.recommendedPrefix){let c=s.recommendedPrefix;return{packageManager:o,command:"npm",args:["install","-g","--prefix",c,a],display:`npm install -g --prefix ${kb(c)} ${a}`,diagnostics:s}}return{packageManager:o,command:"npm",args:["install","-g",a],display:`npm install -g ${a}`,diagnostics:s};case"pnpm":return{packageManager:o,command:"pnpm",args:["add","-g",a],display:`pnpm add -g ${a}`,diagnostics:s};case"yarn":return{packageManager:o,command:"yarn",args:["global","add",a],display:`yarn global add ${a}`,diagnostics:s};case"bun":return{packageManager:o,command:"bun",args:["add","-g",a],display:`bun add -g ${a}`,diagnostics:s}}}function Cb(e){let t=e.isActive?" (active)":"",n=e.version?` v${e.version}`:" version unknown",r=e.prefix?` via ${e.prefix}`:"";return` - ${e.binPath}${t}: ${n}${r}`}function ha(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(Cb)];return t&&(e.recommendedPrefix?n.push("The update command below targets the active install so your shell actually picks up the new version."):n.push("The update command is shown below; remove duplicate installs if your shell still picks up an older version."),n.push(` ${t}`)),n.join(`
|
|
166
|
-
`)}var Es=T(Fr());function Tb(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function zd(e){if(!e)return{canContinue:!1,message:"Biometric attestation is unavailable and Visa CLI could not verify server attestation policy.",hint:"Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC) before using payment commands."};let t=Tb(e);return e.attestationRequired!==!1||t?{canContinue:!1,message:"Biometric attestation is unavailable, but this account requires a registered local attestation key.",hint:"Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC), or use an already-registered device to recover or change biometric policy."}:{canContinue:!0,message:"Biometric attestation is unavailable; continuing only because server biometric policy is disabled and no attestation key is registered."}}async function Jd(){await V.deleteSessionToken()}var lt=T(require("crypto")),$e=T(require("fs")),vs=T(require("os")),or=T(require("path")),Zd=T(require("node:readline")),ya="3.0.0
|
|
166
|
+
`)}var Es=T(Fr());function Tb(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function zd(e){if(!e)return{canContinue:!1,message:"Biometric attestation is unavailable and Visa CLI could not verify server attestation policy.",hint:"Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC) before using payment commands."};let t=Tb(e);return e.attestationRequired!==!1||t?{canContinue:!1,message:"Biometric attestation is unavailable, but this account requires a registered local attestation key.",hint:"Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC), or use an already-registered device to recover or change biometric policy."}:{canContinue:!0,message:"Biometric attestation is unavailable; continuing only because server biometric policy is disabled and no attestation key is registered."}}async function Jd(){await V.deleteSessionToken()}var lt=T(require("crypto")),$e=T(require("fs")),vs=T(require("os")),or=T(require("path")),Zd=T(require("node:readline")),ya="3.0.0",Eb=process.env.PORTER_API_URL??"https://porter-travel.up.railway.app",Ab=process.env.TAP_REGISTRY_URL??"https://tap-production-eff9.up.railway.app",Jr=or.join(vs.homedir(),".visa-cli","agents");function Rb(){return!!(process.env.VISA_DEV==="1"||ya==="0.0.0"||ya.startsWith("0.0.")||/-rc\.|-beta\./.test(ya))}function Ib(){$e.mkdirSync(Jr,{recursive:!0,mode:448})}function va(e){return or.join(Jr,`${e}.json`)}function _a(){return $e.existsSync(Jr)?$e.readdirSync(Jr).filter(e=>e.endsWith(".json")).map(e=>or.join(Jr,e)):[]}function $b(e){let t=va(e);return $e.existsSync(t)?JSON.parse($e.readFileSync(t,"utf8")):null}function Pb(e){Ib();let t=va(e.agent_id);$e.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}async function ba(e,t,n,r){let o=`${e.replace(/\/+$/,"")}${n}`,s=await fetch(o,{method:t,headers:{"Content-Type":"application/json"},body:r!==void 0?JSON.stringify(r):void 0}),i=await s.json().catch(()=>({}));if(!s.ok||i.errors?.length){let a=i.errors?.[0];throw new Error(`${t} ${o} failed (${s.status}): ${a?.code??"unknown"} \u2014 ${a?.message??"no message"}`)}if(i.data===void 0)throw new Error(`${t} ${o}: empty response data`);return i.data}var Yd=ba;function Ob(){let{publicKey:e,privateKey:t}=lt.generateKeyPairSync("ed25519"),n=e.export({format:"jwk"}),r=t.export({format:"jwk"});return{publicKeyB64url:n.x,privateJwk:r}}function Qd(e,t){let n=lt.createPrivateKey({key:t,format:"jwk"});return lt.sign(null,Buffer.from(e,"utf8"),n).toString("base64url")}async function Mb(e){let{publicKeyB64url:t,privateJwk:n}=Ob(),r=new Date().toISOString(),o=`tap:register:v1:${e.name}:${r}`,s=Qd(o,n),i=await ba(e.registryUrl,"POST","/api/v1/agents",{name:e.name,public_key:t,signed_at:r,signature:s,visibility:"public",capabilities:["porter:book","visa:authorize_payment"]}),a=await ba(e.porterUrl,"POST","/api/v1/tap/accounts",{public_key:t,name:e.name}),c={agent_id:i.agent_id,tap_registry_url:e.registryUrl,porter_url:e.porterUrl,tap_account_id:a.id,public_key_b64url:t,private_key_jwk:n,name:e.name,created_at:new Date().toISOString()};return Pb(c),c}async function em(e){let t=await Yd(e.porter_url,"GET",`/api/v1/tap/challenge?public_key=${encodeURIComponent(e.public_key_b64url)}`),n=Qd(t.challenge,e.private_key_jwk),r=await Yd(e.porter_url,"POST","/api/v1/tap/verify",{public_key:e.public_key_b64url,challenge:t.challenge,signature:n});return{token:r.token,expiresInSeconds:r.expires_in}}function Nb(e,t,n){let r=JSON.stringify(t),o=JSON.stringify(n),s=Buffer.from(r).toString("base64url"),i=Buffer.from(o).toString("base64url"),a=`${s}.${i}`,c=lt.createPrivateKey({key:e,format:"jwk"}),l=lt.sign(null,Buffer.from(a,"utf8"),c);return`${a}.${l.toString("base64url")}`}var Lb=["visa_authorize_payment"],Ub={name:"visa_authorize_payment",description:["Mint a signed payment-authorization JWT (visa_payment_id) for a merchant.","Pass the returned JWT into the merchant's checkout/booking call (e.g. porter_checkout).","The signing key is the agent's Ed25519 keypair held by visa-cli (kernel-sealed in production).","No money is moved here \u2014 the JWT only authorizes the merchant to settle later for up to `amount`."].join(" "),inputSchema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",additionalProperties:!1,properties:{merchant:{type:"string",description:'Merchant identifier \u2014 must match the merchant\'s `aud` claim. Today: "porter".'},amount:{type:"integer",minimum:1,description:"Amount in minor units (cents for USD). MUST equal or exceed the merchant transaction total."},currency:{type:"string",minLength:3,maxLength:3,description:'ISO 4217 currency code, e.g. "USD".'},idem_key:{type:"string",description:"Merchant-stable transaction binding. For porter: the cart_id from porter_add_to_cart."},description:{type:"string",description:'Human-readable purpose of the payment, e.g. "JFK\u2192CDG business 2026-09-15".'}},required:["merchant","amount","currency","idem_key"]}};function Db(e,t){let n=Math.floor(Date.now()/1e3),r=n+300,o=`vpid_${lt.randomBytes(16).toString("hex")}`,s=process.env.VISACLI_ISSUER??e.tap_registry_url??e.porter_url;return{jwt:Nb(e.private_key_jwk,{alg:"EdDSA",typ:"JWT",kid:e.agent_id},{iss:s,aud:t.merchant,sub:e.agent_id,amount:t.amount,currency:t.currency.toUpperCase(),idem_key:t.idem_key,iat:n,nbf:n,exp:r,jti:o}),jti:o,expiresAt:r}}async function jb(e){let t=`${e.porter_url.replace(/\/+$/,"")}/api/mcp`,n=null,r=0;async function o(p=!1){if(!p&&n&&Date.now()<r-6e4)return n;let{token:m,expiresInSeconds:g}=await em(e);return n=m,r=Date.now()+g*1e3,m}function s(p){process.stdout.write(JSON.stringify(p)+`
|
|
167
167
|
`)}function i(p,m,g){s({jsonrpc:"2.0",id:p??null,error:{code:m,message:g}})}function a(p,m,g){if(m==="visa_authorize_payment"){let y=g;if(typeof y.merchant!="string"||typeof y.amount!="number"||typeof y.currency!="string"||typeof y.idem_key!="string"){i(p,-32602,"visa_authorize_payment: missing or wrong-typed required fields");return}try{let{jwt:w,jti:N,expiresAt:U}=Db(e,y);s({jsonrpc:"2.0",id:p,result:{content:[{type:"text",text:["\u2713 Payment authorized \u2014 pass this JWT as visa_payment_id at checkout:","",w,"",` agent: ${e.agent_id}`,` merchant: ${y.merchant}`,` amount: ${y.amount} ${y.currency.toUpperCase()}`,` jti: ${N}`,` expires: ${new Date(U*1e3).toISOString()}`].join(`
|
|
168
168
|
`)},{type:"text",text:JSON.stringify({visa_payment_id:w,jti:N,agent_id:e.agent_id,amount:y.amount,currency:y.currency.toUpperCase(),merchant:y.merchant,expires_at:U})}]}})}catch(w){i(p,-32603,`failed to sign visa_payment_id: ${w instanceof Error?w.message:String(w)}`)}return}i(p,-32601,`unknown synthetic tool: ${m}`)}async function c(p){if(p.method==="tools/call"){let g=p.params??{};if(typeof g.name=="string"&&Lb.includes(g.name)){a(p.id,g.name,g.arguments??{});return}}let m=0;for(;m<2;){m+=1;let g=await o(m>1),y;try{y=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","X-TAP-Token":g},body:JSON.stringify(p)})}catch(N){i(p.id,-32e3,`network error talking to porter: ${N instanceof Error?N.message:String(N)}`);return}if(y.status===401&&m===1){n=null;continue}if(!y.ok){let N=await y.text().catch(()=>"");i(p.id,-32e3,`porter returned ${y.status}: ${N.slice(0,400)}`);return}if((y.headers.get("content-type")??"").includes("text/event-stream"))await u(y,p);else{let N=await y.text();if(N.trim()){let U=JSON.parse(N);l(p,U),s(U)}}return}}function l(p,m){if(p.method!=="tools/list")return;let g=m.result;!g||!Array.isArray(g.tools)||g.tools.some(y=>y.name==="visa_authorize_payment")||g.tools.push(Ub)}async function u(p,m){let g=p.body?.getReader();if(!g)return;let y=new TextDecoder,w="";for(;;){let{done:N,value:U}=await g.read();if(N)break;w+=y.decode(U,{stream:!0});let v;for(;(v=w.indexOf(`
|
|
169
169
|
|