@visa/cli 2.8.1 → 2.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +43 -43
- package/dist/mcp-server/index.js +15 -15
- package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var km=Object.create;var to=Object.defineProperty;var Cm=Object.getOwnPropertyDescriptor;var Tm=Object.getOwnPropertyNames;var Em=Object.getPrototypeOf,Am=Object.prototype.hasOwnProperty;var Rm=(e,t)=>()=>(e&&(t=e(e=0)),t);var Fa=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Is=(e,t)=>{for(var n in t)to(e,n,{get:t[n],enumerable:!0})},Va=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Tm(t))!Am.call(e,o)&&o!==n&&to(e,o,{get:()=>t[o],enumerable:!(r=Cm(t,o))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?km(Em(e)):{},Va(t||!e||!e.__esModule?to(n,"default",{value:e,enumerable:!0}):n,e)),Im=e=>Va(to({},"__esModule",{value:!0}),e);var lr=Fa((
|
|
1
|
+
"use strict";var km=Object.create;var to=Object.defineProperty;var Cm=Object.getOwnPropertyDescriptor;var Tm=Object.getOwnPropertyNames;var Em=Object.getPrototypeOf,Am=Object.prototype.hasOwnProperty;var Rm=(e,t)=>()=>(e&&(t=e(e=0)),t);var Fa=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Is=(e,t)=>{for(var n in t)to(e,n,{get:t[n],enumerable:!0})},Va=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Tm(t))!Am.call(e,o)&&o!==n&&to(e,o,{get:()=>t[o],enumerable:!(r=Cm(t,o))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?km(Em(e)):{},Va(t||!e||!e.__esModule?to(n,"default",{value:e,enumerable:!0}):n,e)),Im=e=>Va(to({},"__esModule",{value:!0}),e);var lr=Fa((Tv,Hm)=>{Hm.exports={name:"@visa/cli",version:"2.8.2",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.2","@typescript-eslint/eslint-plugin":"^8.61.0","@typescript-eslint/parser":"^8.61.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});var jr=Fa(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.micros=Vh;ce.fromCents=qh;ce.fromUsdc=Hh;ce.fromUsd=Bh;ce.toCents=Kh;ce.toCentsForAcquirer=Gh;ce.toUsdc=Wh;ce.toWire=zh;ce.fromWire=Jh;ce.toDisplay=Yh;ce.toUsdRounded2dp=Xh;ce.add=Zh;ce.sub=Qh;ce.clampNonNegative=ey;ce.isNonNegative=ty;ce.max=ny;ce.min=ry;var xt=10000n,Lu=1000000n;function Vh(e){return e}function qh(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 Hh(e){return e}function Bh(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Kh(e){if(e>=0n)return Number(e/xt);let t=e/xt,n=e%xt;return Number(n===0n?t:t-1n)}function Gh(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/xt)}function Wh(e){return e}function zh(e){return e.toString()}function Jh(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 Yh(e,t={}){let n=t.decimals??2,r=t.symbol??"$",o=e<0n,s=o?-e:e,i=s/Lu,a=s%Lu,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 Xh(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 Zh(e,t){return e+t}function Qh(e,t){return e-t}function ey(e){return e<0n?0n:e}function ty(e){return e>=0n}function ny(e,t){return e>t?e:t}function ry(e,t){return e<t?e:t}});var bs={};Is(bs,{initSentry:()=>Mb,isSentryConfigured:()=>Ob,reportFatal:()=>Nb});function Ob(){return!1}async function Mb(){return null}async function Nb(e,t){process.exit(t?.exitCode??1)}var vs=Rm(()=>{});var bv={};Is(bv,{printGroupHelpAndExit:()=>ze});module.exports=Im(bv);var nm=require("commander"),xs=T(require("crypto")),Y=T(require("fs")),J=T(require("os")),Ue=T(require("path")),rm=require("child_process"),Ea=require("node:readline/promises"),om=require("util");var oo=require("child_process"),Xa=require("util"),At=T(require("fs")),so=T(require("os")),Ls=T(require("path"));var Ka=T(require("crypto"));var dt="e9501a252b778bce5a3d77710667afdd9198a750d1d989d95fb32d80e485bf15";var Ga="VISA_ALLOW_INSECURE_MOCKS",qa,Ha,Ba;function $s(e){return`${e}-${Ka.randomBytes(24).toString("base64url")}`}function Wa(e=process.env){return e.NODE_ENV==="test"||e[Ga]==="true"}function Tt(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&Wa(e)}function Pn(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&Wa(e)}function Ps(){return`Set ${Ga}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function za(){return qa??=$s("mock-session"),qa}function Ja(e=process.env){return e.NODE_ENV==="test"?dt:(Ha??=$s("mock-rc"),Ha)}function Ya(){return Ba??=$s("mock-signature"),Ba}var Je=(0,Xa.promisify)(oo.execFile),Us=Ls.join(so.homedir(),".visa-mcp"),cr=Ls.join(Us,"session-token"),$e="visa-cli",Et="session-token",no="rc-access",$m=5e3,ro=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Pm(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
|
|
2
2
|
`)}function Za(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Pm(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function Om(){try{let{stdout:e}=await Je("security",["find-generic-password","-s",$e,"-a",Et,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Za(e))throw new ro("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 Mm(e){try{try{await Je("security",["delete-generic-password","-s",$e,"-a",Et],{timeout:5e3})}catch{}return await Je("security",["add-generic-password","-s",$e,"-a",Et,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Nm(){try{await Je("security",["delete-generic-password","-s",$e,"-a",Et],{timeout:5e3})}catch{}}async function Lm(){if(!Ds())return null;try{let{stdout:e}=await Je("secret-tool",["lookup","service",$e,"account",Et],{timeout:5e3});return e.trim()||null}catch{return null}}async function Um(e){if(!Ds())return!1;try{let t=(0,oo.execFile)("secret-tool",["store","--label",`${$e} ${Et}`,"service",$e,"account",Et]);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"))},$m))]),!0):!1}catch{return!1}}async function Dm(){if(Ds())try{await Je("secret-tool",["clear","service",$e,"account",Et],{timeout:5e3})}catch{}}function Ds(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function jm(){try{let{stdout:e}=await Je("security",["find-generic-password","-s",$e,"-a",no,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Fm(e){try{try{await Je("security",["delete-generic-password","-s",$e,"-a",no],{timeout:5e3})}catch{}await Je("security",["add-generic-password","-s",$e,"-a",no,"-w",e],{timeout:5e3})}catch{}}async function Vm(){try{await Je("security",["delete-generic-password","-s",$e,"-a",no],{timeout:5e3})}catch{}}function Ms(){try{return At.readFileSync(cr,"utf-8").trim()||null}catch(e){if(Za(e))throw new ro(`Unable to read Visa CLI credentials from ${cr}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Qa(e){At.mkdirSync(Us,{recursive:!0,mode:448}),At.writeFileSync(cr,e,{mode:384}),process.platform==="win32"&&qm(cr)}function Ns(){try{At.unlinkSync(cr)}catch{}}function qm(e){try{let t=so.userInfo().username;(0,oo.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 Os(){switch(process.platform){case"darwin":return{get:Om,store:Mm,delete:Nm};case"linux":return{get:Lm,store:Um,delete:Dm};default:return{get:async()=>Ms(),store:async e=>{try{return Qa(e),!0}catch{return!1}},delete:async()=>Ns(),storesInSessionFile:!0}}}var F=class{static async getSessionToken(){if(Tt())return Promise.resolve(za());let t=Os(),n=await t.get();if(n)return n;let r=Ms();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(Tt())return;let n=Os();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||Ns();return}await n.delete()}if(Qa(t),Ms()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Us} is writable.`))}static async getRcAccessToken(){return Tt()?Ja():jm()}static async saveRcAccessToken(t){Tt()||await Fm(t)}static async deleteSessionToken(){if(Tt())return;await Os().delete(),Ns()}static async clearAll(){await this.deleteSessionToken(),await Vm()}};var io=T(require("crypto")),ao=T(require("tty")),co=T(require("fs"));function Bm(e){return/-rc\.|-beta\./.test(e)}function js(e){return io.createHash("sha256").update(e.trim()).digest("hex")}function ec(e){return dt==="SKIP"?!0:io.timingSafeEqual(Buffer.from(js(e)),Buffer.from(dt))}function Km(){try{let e=co.openSync("/dev/tty","r+"),t=new ao.ReadStream(e),n=new ao.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{co.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 Gm(e){return new Promise((t,n)=>{let r;try{r=Km()}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 @@ ${_}`:m}function xp(e){let t=` ${W("\u2502",K.chrome)} `,n=[];if(typeof e.spentT
|
|
|
101
101
|
`)}catch{}}function Ic(){try{let e=vr();if(!e)return;let t={...e,renderedAt:0};Un(Pt(),JSON.stringify(t)+`
|
|
102
102
|
`)}catch{}}function en(){try{q.unlinkSync(kc())}catch{}}function vr(){let e=Pt();if(!q.existsSync(e))return null;try{let t=JSON.parse(q.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&wo(t.line)?null:t}catch{return null}}function wo(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 $c(){return vr()?.status??null}function Ip(){if(process.env.JEST_WORKER_ID)return;let e=kc();try{if(q.mkdirSync(B.dirname(e),{recursive:!0}),!Dp(e))return;let t=process.argv[1]?B.resolve(process.argv[1]):"";if(!t){en();return}let n=fo(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),o=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},s=(0,Sc.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...o,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});s.once("error",en),s.unref()}catch{en()}}function Ot(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 $p=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function Pp(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,Js.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,s=>{if(!$p.test(s))return"";let i=`${n}${t.length}__`;return t.push(s),i}),o=new RegExp(`${n}(\\d+)__`,"g");return Ot(r).replace(o,(s,i)=>t[Number(i)]??"")}function Op(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 Ln(e){return`$${e.toFixed(2)}`}function Mp(e){let t=e;if(t.startsWith("/")&&(t=t.replace(/^\/(?:api\/)?v\d+\/fal\//,""),t=t.replace(/^\/(?:api\/)?v\d+\/(?:shortcuts|openrouter)\//,""),t.startsWith("/"))){let o=t.split("/").filter(Boolean);t=o[o.length-1]||t}return t=t.replace(/^fal-ai\//,""),t=t.replace(/^fal-/,""),t=t.replace(/^or-/,""),t=t.split("/").filter(Boolean).map(o=>o.replace(/^v\d+(?:\.\d+)?-?/,"")||null).filter(o=>o!==null&&o.length>0).join(" "),t=t.replace(/_card$/,""),t.length>28&&(t=t.slice(0,28).trimEnd()),t||e}function Np(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",o=Ot(n.toUpperCase()),s=Ot(r);return`${t.isDefault?"default":"active"} ${o} ****${s}`}var K={get reset(){return ge().reset},get visaBlue(){return ge().visaBlue},get visaBlueSoft(){return ge().visaBlueSoft},get visaGold(){return ge().visaGold},get green(){return ge().green},get muted(){return ge().muted},get chrome(){return ge().chrome}};function W(e,t){return e.length===0||process.env.NO_COLOR||go()?e:`${t}${e}${K.reset}`}function wc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qs(){let e=tn.homedir();if(!e||!B.isAbsolute(e))throw new Error("unable to determine a valid home directory");return B.resolve(e)}function Lp(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Up(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Dp(e){for(let t=0;t<2;t+=1){let n;try{return n=q.openSync(e,"wx"),q.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=q.statSync(e);if(Date.now()-o.mtimeMs<=yp)return!1;q.unlinkSync(e)}catch{}}finally{n!==void 0&&q.closeSync(n)}}return!1}function zs(e){return e instanceof Error?e.message:"unknown file system error"}function Un(e,t){q.mkdirSync(B.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,Js.randomBytes)(8).toString("hex")}.tmp`;try{q.writeFileSync(n,t),q.renameSync(n,e)}catch(r){try{q.unlinkSync(n)}catch{}throw r}}var jp=1440*60*1e3;function xo(e,t){ue.mkdirSync(be.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Mc.randomBytes(8).toString("hex")}.tmp`;try{ue.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
104
|
-
`),ue.renameSync(n,e)}catch(r){try{ue.unlinkSync(n)}catch{}throw r}}function Pc(e){return`'${e.replace(/'/g,"'\\''")}'`}var ti="# visa-cli-hud-v1";function ko(e,t){if(!e&&!t&&Fp())return`visa-cli config statusline ${ti}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?be.resolve(r):"";return`${o?`${Pc(n)} ${Pc(o)} config statusline`:"visa-cli config statusline"} ${ti}`}function Fp(){try{return(0,Nc.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Mt(e){return typeof e!="string"?!1:e.includes(ti)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Vp(){return"2.8.
|
|
104
|
+
`),ue.renameSync(n,e)}catch(r){try{ue.unlinkSync(n)}catch{}throw r}}function Pc(e){return`'${e.replace(/'/g,"'\\''")}'`}var ti="# visa-cli-hud-v1";function ko(e,t){if(!e&&!t&&Fp())return`visa-cli config statusline ${ti}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?be.resolve(r):"";return`${o?`${Pc(n)} ${Pc(o)} config statusline`:"visa-cli config statusline"} ${ti}`}function Fp(){try{return(0,Nc.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Mt(e){return typeof e!="string"?!1:e.includes(ti)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Vp(){return"2.8.2"}function Co(e){let t=be.dirname(be.resolve(e));return be.basename(t)===".claude"?be.dirname(t):Lc.homedir()}function So(e,t){let n=be.relative(t,e);return!n.startsWith("..")&&!be.isAbsolute(n)?`~/${n}`:e}function qp(e){return be.join(Co(e),".visa-cli","hud-self-heal.json")}function Hp(e,t,n,r){try{if(!ue.existsSync(e))return!1;let o=JSON.parse(ue.readFileSync(e,"utf-8"));return o.version===t&&typeof o.checkedAt=="number"&&n-o.checkedAt<r}catch{return!1}}function ei(e,t,n){try{xo(e,{version:t,checkedAt:n})}catch{}}function Bp(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function ni(e,t={}){let n=t.now??Date.now(),r=t.version??Vp(),o=t.stampPath??qp(e),s=t.minIntervalMs??jp,i=[],a=!1,c=!1;if(!t.force&&Hp(o,r,n,s))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!ue.existsSync(e))return ei(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(ue.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!Mt(d))return ei(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let p=(t.getCommand??ko)();if(d!==p&&(l.statusLine=Bp(u,p),xo(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!To()){let m=Co(e);if(nn(m).length>0){let _=mt(null,m);if(_.removed&&_.rcPaths&&_.rcPaths.length>0){let x=_.rcPaths.map($=>So($,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${x}.`)}}}return ei(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 Kp(e,t){let n=Co(t),r=nn(n);if(r.length===0)return e;let o=r.map(s=>So(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 To(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 Oc(e,t){let n=Co(t),r=nn(n);if(r.length===0)return e;let o=r.map(i=>So(i,n)).join(", ");if(To())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=>So(a,n)).join(", ");return`${e}
|
|
@@ -119,7 +119,7 @@ ${a}`}function Qp(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)
|
|
|
119
119
|
`),{isActive:s}=zc(e,n,t?.transcript_path);return{schemaVersion:Gp,client:t?Qc(t):rn.UNKNOWN,rendered:o,lines:r.map(si),visa:{spendLine:si(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:s},context:t?tl(t):{}}}function ne(e){return e?e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function Ro(e){if(typeof e=="string")return ne(Ye.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return ne(t?Ye.basename(t):e.name)}function Xc(e){return ne(e.app_name??e.appName??e.app??e.client)}function Eo(e){return ne(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function Zc(e){return ne(e.cwd??e.current_dir??e.project_root)}function Hc(e){let t=ne(e.project);if(t)return t;let n=Zc(e);if(n)return ne(Ye.basename(n));let r=Ro(e.workspace);return r||""}function De(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function Qc(e){let t=Xc(e).toLowerCase();return t.includes("codex")?rn.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?rn.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||De(e.context_used)!==void 0?rn.CODEX:rn.UNKNOWN}function el(e){return Qc(e)===rn.CODEX}function tl(e){let t=Xc(e),n=Zc(e),r=Ro(e.workspace),o=De(e.context_used)??De(e.context_window?.used_percentage??void 0),s=De(e.context_remaining)??De(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...Eo(e)?{model:Eo(e)}:{},...Hc(e)?{project:Hc(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...ne(e.git_branch??e.branch)?{gitBranch:ne(e.git_branch??e.branch)}:{},...ne(e.status??e.run_state??e.runState)?{status:ne(e.status??e.run_state??e.runState)}:{},...ne(e.thread_title??e.threadTitle)?{threadTitle:ne(e.thread_title??e.threadTitle)}:{},...o!==void 0?{contextUsedPercent:o}:{},...s!==void 0?{contextRemainingPercent:s}:{},...De(e.used_tokens)!==void 0?{usedTokens:De(e.used_tokens)}:{},...De(e.total_input_tokens)!==void 0?{totalInputTokens:De(e.total_input_tokens)}:{},...De(e.total_output_tokens)!==void 0?{totalOutputTokens:De(e.total_output_tokens)}:{}}}function si(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var rl=T(require("path"));function nl(e){return e instanceof Error?e.message:String(e)}function ii(e,t){let n=[],r=[],o=e??"claude",s=Ao(o);if(o==="shell"||o==="prompt")try{let a=t.installShellHud();return a.installed?{ok:!0,messages:[a.message],errors:r}:{ok:!1,messages:n,errors:[a.message]}}catch(a){return{ok:!1,messages:n,errors:[`Failed to install shell HUD: ${nl(a)}`]}}if(!s)return{ok:!1,messages:n,errors:[`Unknown HUD surface: ${o}`,"Supported: claude (default), shell, all"]};let i=!0;if(s==="claude"||s==="claude-code"||s==="all"){let a=rl.join(t.homeDir,".claude","settings.json");try{let c=t.installVisaStatusLine(a);n.push(c.message),(c.installed==="error"||c.installed==="malformed-json")&&(i=!1)}catch(c){i=!1,r.push(`Failed to install Claude HUD: ${nl(c)}`)}}return{ok:i,messages:n,errors:r}}function ol(e){if(!e||typeof e!="object")return"";let t=e;return Array.isArray(t.enum)&&t.enum.length>0?"enum":typeof t.type=="string"?t.type:Array.isArray(t.type)?t.type.filter(n=>typeof n=="string").join("|"):""}var sl=T(require("os")),il=require("node:readline/promises"),kr={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function ai(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,o;try{r=(0,il.createInterface)({input:process.stdin,output:process.stdout});let s=new AbortController;o=()=>s.abort(),r.once("close",o);let i=(await r.question(`${e} ${n} `,{signal:s.signal})).trim();return i?/^y(es)?$/i.test(i):t}catch{return t}finally{r&&o&&r.off("close",o),r?.close()}}function cf(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function al(e=sl.hostname()){let t=lr().version,n=cf(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${kr.card}`,` ${kr.balance} | ${kr.spentToday} | ${kr.lastActivity}`,` [${kr.model}] | you`," Activity live"].join(`
|
|
120
120
|
`)}async function Xe(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 on=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},jn=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}},Ze=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}},re=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}},Qe=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 cl={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 Fn(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&&cl[n]?cl[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 Se=T(require("fs")),ui=T(require("path")),ll=T(require("os")),li=ui.join(ll.homedir(),".visa-mcp"),Cr=ui.join(li,"mcp-server.log"),lf=5*1024*1024,ci=null;function uf(){Se.existsSync(li)||Se.mkdirSync(li,{recursive:!0,mode:448})}function df(){if(!ci){if(uf(),Se.existsSync(Cr)&&Se.statSync(Cr).size>lf){let t=Cr+".1";Se.existsSync(t)&&Se.unlinkSync(t),Se.renameSync(Cr,t)}ci=Se.createWriteStream(Cr,{flags:"a"})}return ci}function mf(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function Io(e,...t){let n=new Date().toISOString(),r=t.map(s=>typeof s=="string"?s:JSON.stringify(s,null,2)).join(" "),o=`[${n}] [${e}] ${r}
|
|
121
121
|
`;mf(e)&&process.stderr.write(o),df().write(o)}var f={debug:(...e)=>Io("DEBUG",...e),info:(...e)=>Io("INFO",...e),warn:(...e)=>Io("WARN",...e),error:(...e)=>Io("ERROR",...e)};var pf=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function dl(e,t){let n=ul(e),r=ul(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:ff(n.pre,r.pre)>0}function ul(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(pf);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function ff(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 et(){return!!(ml(process.env.VISA_CLI_NO_UPDATE_CHECK)||ml(process.env.CI)||process.env.NODE_ENV==="test")}function ml(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Lt=T(require("fs")),fi=require("node:net"),hl=T(require("os")),yl=T(require("path"));var $o=T(require("fs")),pl=T(require("path")),fl=T(require("os"));var di=pl.join(fl.homedir(),".visa-mcp"),Tr=class{static ensureConfigDir(){$o.existsSync(di)||$o.mkdirSync(di,{recursive:!0,mode:448})}static getConfigDir(){return di}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 gl(e){let t=hl.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var gf="settings.json",hf="must use https unless it points at localhost/loopback for local development";function Er(){return yl.join(Tr.getConfigDir(),gf)}function _l(e){if((0,fi.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function yf(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 _l(o)}function _f(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,fi.isIP)(t);return n===4?_l(t):n===6?t==="::1"||yf(t):!1}function mi(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:"&&_f(n.hostname)))throw new Error(`${t} ${hf}`)}var Ut={"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");mi(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)")}}},gi=500,Po={"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 sn(){let e=Er();if(!Lt.existsSync(e))return{};try{let t=Lt.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(f.warn("settings:corrupt",{path:gl(e),reason:"not_object"}),{}):n}catch(t){return f.warn("settings:corrupt",{path:gl(e),error:t?.message||String(t)}),{}}}function pi(e){Tr.ensureConfigDir();let t=Er(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
|
|
122
|
-
`;Lt.writeFileSync(n,r,{mode:384}),Lt.renameSync(n,t)}function hi(e){let t=sn()[e];return typeof t=="string"?t:void 0}function Oo(e){let t=sn()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function yi(e){let t=sn()[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(Ut).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"}},Nt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+Po[t]),this.name="RetiredSettingKeyError"}},bl=["biometric.","spending.","account.","cards.","biometric"];function Mo(e,t){if(bl.some(s=>e.startsWith(s)))throw new yt(e);if(e in Po)throw new Nt(e);let n=Ut[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=sn();return o[e]=r,pi(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Er()}}function No(e){if(bl.some(s=>e.startsWith(s)))throw new yt(e);let t=Ut[e];if(e in Po){let s=sn(),i=e in s;return i&&(delete s[e],pi(s)),{key:e,removed:i,requiresRestart:!1,path:Er()}}if(!t)throw new ht(e);let r=sn(),o=e in r;return o&&(delete r[e],pi(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:Er()}}function vl(){let e=sn();return Object.entries(Po).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var bf="https://auth.visacli.sh",vf="https://auth-visa-code-preview.up.railway.app";function wf(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Sf(){try{let e=lr();return wf(e.version)}catch{return!1}}function xf(e){return e.envVar!==void 0&&e.envVar!==""?(mi(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(mi(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?vf:bf}function Te(){return xf({envVar:process.env.VISA_AUTH_URL,settingValue:hi("auth.serverUrl"),isPrerelease:Sf()})}function wl(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Oo("ui.suppressBrowser")??!1}function Sl(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Oo("ui.suppressFeed")??!1}function xl(){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=yi("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):gi}var kf="CARD_REENROLLMENT_REQUIRED",Cf="https://auth.visacli.sh/enroll-card";function Tf(){try{return new URL("/enroll-card",Te()).toString()}catch{return Cf}}function Ef(e){let t=Tf();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 Dt="2.8.
|
|
122
|
+
`;Lt.writeFileSync(n,r,{mode:384}),Lt.renameSync(n,t)}function hi(e){let t=sn()[e];return typeof t=="string"?t:void 0}function Oo(e){let t=sn()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function yi(e){let t=sn()[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(Ut).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"}},Nt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+Po[t]),this.name="RetiredSettingKeyError"}},bl=["biometric.","spending.","account.","cards.","biometric"];function Mo(e,t){if(bl.some(s=>e.startsWith(s)))throw new yt(e);if(e in Po)throw new Nt(e);let n=Ut[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=sn();return o[e]=r,pi(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Er()}}function No(e){if(bl.some(s=>e.startsWith(s)))throw new yt(e);let t=Ut[e];if(e in Po){let s=sn(),i=e in s;return i&&(delete s[e],pi(s)),{key:e,removed:i,requiresRestart:!1,path:Er()}}if(!t)throw new ht(e);let r=sn(),o=e in r;return o&&(delete r[e],pi(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:Er()}}function vl(){let e=sn();return Object.entries(Po).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var bf="https://auth.visacli.sh",vf="https://auth-visa-code-preview.up.railway.app";function wf(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Sf(){try{let e=lr();return wf(e.version)}catch{return!1}}function xf(e){return e.envVar!==void 0&&e.envVar!==""?(mi(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(mi(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?vf:bf}function Te(){return xf({envVar:process.env.VISA_AUTH_URL,settingValue:hi("auth.serverUrl"),isPrerelease:Sf()})}function wl(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Oo("ui.suppressBrowser")??!1}function Sl(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Oo("ui.suppressFeed")??!1}function xl(){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=yi("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):gi}var kf="CARD_REENROLLMENT_REQUIRED",Cf="https://auth.visacli.sh/enroll-card";function Tf(){try{return new URL("/enroll-card",Te()).toString()}catch{return Cf}}function Ef(e){let t=Tf();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 Dt="2.8.2",Af=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;function Rf(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 _i(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var If="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Vn(e){return typeof e=="string"?e.trim():""}function Ar(e){let t=e&&typeof e=="object"?e:{},n=Vn(t.error)||Vn(t.message);if(!n)return If;let r=Vn(t.error_code),o=[["surface",Vn(t.disabled_surface)],["flag",Vn(t.flag)],["correlation_id",Vn(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 Rr(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?Af.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(`
|
|
123
123
|
`)}var Ee=class{constructor(t){this.getSessionToken=t;this.baseUrl=Te()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!et()){let r=t.headers.get("X-Latest-Version");r&&dl(r,Dt)&&(this.lastSignals.updateAvailable={currentVersion:Dt,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return Dt}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new on(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(Ar(n))}async request(t,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error(Rr());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 Xe(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":Dt,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(Fn(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===kf){let p=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",g=Ef(u?.reenroll_url),_=p?`${m} ending in ${p}`:"your card";throw new Error(`Please re-add ${_} to keep payments running. Open: ${g}`)}let d=_i(u?.error_code);if(d)throw new Qe(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 re(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(Rr());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Dt,"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 Xe(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(g){throw new Error(Fn(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 x=Number(d.headers.get("Retry-After"))||1;throw new gt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",x,d.status)}throw new Error(Ar(m))}let g=Rf(m?.error_code);if(g||d.status===410){let x=g??"BUDGET_CLOSED";throw new jn(m?.message||m?.error||"Your session was invalidated by the server.",x,{budgetId:n.session_budget_id,status:d.status})}if(m?.declined){let x=Number(m.retryAfter??d.headers.get("Retry-After"));throw new re(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(x)&&x>0?x:void 0)}let _=_i(m?.error_code);throw _?new Qe(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",_,{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(Rr());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Dt,"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 Xe(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(g){throw new Error(Fn(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 Ze("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 Ze(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 x=Number(d.headers.get("Retry-After"))||1;throw new gt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",x,d.status)}throw new Error(Ar(m))}if(m?.declined){let x=Number(m.retryAfter??d.headers.get("Retry-After"));throw new re(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(x)&&x>0?x:void 0)}let _=_i(m?.error_code);throw _?new Qe(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",_,{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(Rr());let o={Authorization:`Bearer ${r}`,"X-Visa-CLI-Version":Dt,"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 Xe(`${this.baseUrl}${n}`,{method:"POST",headers:o,body:JSON.stringify(s),timeoutMs:void 0})}catch(u){throw new Error(Fn(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 Ze("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 Ze(a?.error||"Parentless batch is not enabled on this server.",{status:i.status,serverErrorCode:u});if(i.status===503)throw new Error(Ar(a));if(a?.declined){let d=Number(a.retryAfter??i.headers.get("Retry-After"));throw new re(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(Rr());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Dt,"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 Xe(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(g){throw new Error(Fn(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(Ar(m))}if(m?.declined){let g=Number(m.retryAfter??d.headers.get("Retry-After"));throw new re(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 Xe(`${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 Xe(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let o=r.toString(),s=o?`/v1/transactions?${o}`:"/v1/transactions";return this.request("GET",s,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,n){return this.request("POST","/v1/attestation-key",{publicKey:t,...n?{attestation:n}:{}})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};function Ir(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function Cl(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 kl(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function $f(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 Pf(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function Of(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function Mf(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 Tl(e){let t=Pf(e),n=7,r=Of(e),o=Mf(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)} ${Ir(s.priceCents,s.priceDisplay).padEnd(n)} ${kl(s.category||"other",r).padEnd(r)} ${kl(Cl(s),o)}`)}function El(e){console.log(`
|
|
124
124
|
Merchant tools
|
|
125
125
|
`),Tl(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 bi(e){console.log(`
|
|
@@ -129,10 +129,10 @@ Merchant tools
|
|
|
129
129
|
${e} tools
|
|
130
130
|
`),Tl(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>\`
|
|
131
131
|
`)}var h={};Is(h,{BRAND:()=>ig,DIRTY:()=>an,EMPTY_PATH:()=>Df,INVALID:()=>P,NEVER:()=>Bg,OK:()=>he,ParseStatus:()=>fe,Schema:()=>D,ZodAny:()=>Vt,ZodArray:()=>wt,ZodBigInt:()=>ln,ZodBoolean:()=>un,ZodBranded:()=>Pr,ZodCatch:()=>wn,ZodDate:()=>dn,ZodDefault:()=>vn,ZodDiscriminatedUnion:()=>Do,ZodEffects:()=>Me,ZodEnum:()=>_n,ZodError:()=>xe,ZodFirstPartyTypeKind:()=>O,ZodFunction:()=>Fo,ZodIntersection:()=>gn,ZodIssueCode:()=>b,ZodLazy:()=>hn,ZodLiteral:()=>yn,ZodMap:()=>Wn,ZodNaN:()=>Jn,ZodNativeEnum:()=>bn,ZodNever:()=>je,ZodNull:()=>pn,ZodNullable:()=>rt,ZodNumber:()=>cn,ZodObject:()=>ke,ZodOptional:()=>Pe,ZodParsedType:()=>C,ZodPipeline:()=>Or,ZodPromise:()=>qt,ZodReadonly:()=>Sn,ZodRecord:()=>jo,ZodSchema:()=>D,ZodSet:()=>zn,ZodString:()=>Ft,ZodSymbol:()=>Kn,ZodTransformer:()=>Me,ZodTuple:()=>nt,ZodType:()=>D,ZodUndefined:()=>mn,ZodUnion:()=>fn,ZodUnknown:()=>vt,ZodVoid:()=>Gn,addIssueToContext:()=>w,any:()=>gg,array:()=>bg,bigint:()=>ug,boolean:()=>jl,coerce:()=>Hg,custom:()=>Ll,date:()=>dg,datetimeRegex:()=>Ml,defaultErrorMap:()=>_t,discriminatedUnion:()=>xg,effect:()=>Ng,enum:()=>Pg,function:()=>Rg,getErrorMap:()=>qn,getParsedType:()=>tt,instanceof:()=>cg,intersection:()=>kg,isAborted:()=>Lo,isAsync:()=>Hn,isDirty:()=>Uo,isValid:()=>jt,late:()=>ag,lazy:()=>Ig,literal:()=>$g,makeIssue:()=>$r,map:()=>Eg,nan:()=>lg,nativeEnum:()=>Og,never:()=>yg,null:()=>fg,nullable:()=>Ug,number:()=>Dl,object:()=>vg,objectUtil:()=>vi,oboolean:()=>qg,onumber:()=>Vg,optional:()=>Lg,ostring:()=>Fg,pipeline:()=>jg,preprocess:()=>Dg,promise:()=>Mg,quotelessJson:()=>Nf,record:()=>Tg,set:()=>Ag,setErrorMap:()=>Uf,strictObject:()=>wg,string:()=>Ul,symbol:()=>mg,transformer:()=>Ng,tuple:()=>Cg,undefined:()=>pg,union:()=>Sg,unknown:()=>hg,util:()=>j,void:()=>_g});var j;(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})(j||(j={}));var vi;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(vi||(vi={}));var C=j.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),tt=e=>{switch(typeof e){case"undefined":return C.undefined;case"string":return C.string;case"number":return Number.isNaN(e)?C.nan:C.number;case"boolean":return C.boolean;case"function":return C.function;case"bigint":return C.bigint;case"symbol":return C.symbol;case"object":return Array.isArray(e)?C.array:e===null?C.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?C.promise:typeof Map<"u"&&e instanceof Map?C.map:typeof Set<"u"&&e instanceof Set?C.set:typeof Date<"u"&&e instanceof Date?C.date:C.object;default:return C.unknown}};var b=j.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"]),Nf=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),xe=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,j.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()}};xe.create=e=>new xe(e);var Lf=(e,t)=>{let n;switch(e.code){case b.invalid_type:e.received===C.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case b.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,j.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:n=`Unrecognized key(s) in object: ${j.joinValues(e.keys,", ")}`;break;case b.invalid_union:n="Invalid input";break;case b.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${j.joinValues(e.options)}`;break;case b.invalid_enum_value:n=`Invalid enum value. Expected ${j.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}"`:j.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,j.assertNever(e)}return{message:n}},_t=Lf;var Rl=_t;function Uf(e){Rl=e}function qn(){return Rl}var $r=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}},Df=[];function w(e,t){let n=qn(),r=$r({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 fe=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"}),an=e=>({status:"dirty",value:e}),he=e=>({status:"valid",value:e}),Lo=e=>e.status==="aborted",Uo=e=>e.status==="dirty",jt=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 Oe=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}},Il=(e,t)=>{if(jt(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 xe(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 D=class{get description(){return this._def.description}_getType(t){return tt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:tt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new fe,ctx:{common:t.parent.common,data:t.data,parsedType:tt(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:tt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Il(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:tt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return jt(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=>jt(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:tt(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Hn(o)?o:Promise.resolve(o));return Il(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 Me({schema:this,typeName:O.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 Pe.create(this,this._def)}nullable(){return rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return wt.create(this)}promise(){return qt.create(this,this._def)}or(t){return fn.create([this,t],this._def)}and(t){return gn.create(this,t,this._def)}transform(t){return new Me({...L(this._def),schema:this,typeName:O.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new vn({...L(this._def),innerType:this,defaultValue:n,typeName:O.ZodDefault})}brand(){return new Pr({typeName:O.ZodBranded,type:this,...L(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new wn({...L(this._def),innerType:this,catchValue:n,typeName:O.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Or.create(this,t)}readonly(){return Sn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},jf=/^c[^\s-]{8,}$/i,Ff=/^[0-9a-z]+$/,Vf=/^[0-9A-HJKMNP-TV-Z]{26}$/i,qf=/^[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,Hf=/^[a-z0-9_-]{21}$/i,Bf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Kf=/^[-+]?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)?)??$/,Gf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Wf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",wi,zf=/^(?:(?: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])$/,Jf=/^(?:(?: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])$/,Yf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Xf=/^(([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])$/,Zf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Qf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Pl="((\\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])))",eg=new RegExp(`^${Pl}$`);function Ol(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 tg(e){return new RegExp(`^${Ol(e)}$`)}function Ml(e){let t=`${Pl}T${Ol(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 ng(e,t){return!!((t==="v4"||!t)&&zf.test(e)||(t==="v6"||!t)&&Yf.test(e))}function rg(e,t){if(!Bf.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 og(e,t){return!!((t==="v4"||!t)&&Jf.test(e)||(t==="v6"||!t)&&Xf.test(e))}var Ft=class e extends D{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==C.string){let s=this._getOrReturnCtx(t);return w(s,{code:b.invalid_type,expected:C.string,received:s.parsedType}),P}let r=new fe,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),w(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),w(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?w(o,{code:b.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&w(o,{code:b.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Gf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"email",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")wi||(wi=new RegExp(Wf,"u")),wi.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"emoji",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")qf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"uuid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Hf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"nanoid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")jf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"cuid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Ff.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"cuid2",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Vf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(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),w(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),w(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),w(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),w(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),w(o,{code:b.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Ml(s).test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{code:b.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?eg.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{code:b.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?tg(s).test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{code:b.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Kf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"duration",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?ng(t.data,s.version)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"ip",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?rg(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"jwt",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?og(t.data,s.version)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"cidr",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Zf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"base64",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Qf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"base64url",code:b.invalid_string,message:s.message}),r.dirty()):j.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}};Ft.create=e=>new Ft({checks:[],typeName:O.ZodString,coerce:e?.coerce??!1,...L(e)});function sg(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 cn=class e extends D{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)!==C.number){let s=this._getOrReturnCtx(t);return w(s,{code:b.invalid_type,expected:C.number,received:s.parsedType}),P}let r,o=new fe;for(let s of this._def.checks)s.kind==="int"?j.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),w(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),w(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),w(r,{code:b.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?sg(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),w(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),w(r,{code:b.not_finite,message:s.message}),o.dirty()):j.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"&&j.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)}};cn.create=e=>new cn({checks:[],typeName:O.ZodNumber,coerce:e?.coerce||!1,...L(e)});var ln=class e extends D{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)!==C.bigint)return this._getInvalidInput(t);let r,o=new fe;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),w(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),w(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),w(r,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):j.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return w(n,{code:b.invalid_type,expected:C.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}};ln.create=e=>new ln({checks:[],typeName:O.ZodBigInt,coerce:e?.coerce??!1,...L(e)});var un=class extends D{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==C.boolean){let r=this._getOrReturnCtx(t);return w(r,{code:b.invalid_type,expected:C.boolean,received:r.parsedType}),P}return he(t.data)}};un.create=e=>new un({typeName:O.ZodBoolean,coerce:e?.coerce||!1,...L(e)});var dn=class e extends D{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==C.date){let s=this._getOrReturnCtx(t);return w(s,{code:b.invalid_type,expected:C.date,received:s.parsedType}),P}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return w(s,{code:b.invalid_date}),P}let r=new fe,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),w(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),w(o,{code:b.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):j.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}};dn.create=e=>new dn({checks:[],coerce:e?.coerce||!1,typeName:O.ZodDate,...L(e)});var Kn=class extends D{_parse(t){if(this._getType(t)!==C.symbol){let r=this._getOrReturnCtx(t);return w(r,{code:b.invalid_type,expected:C.symbol,received:r.parsedType}),P}return he(t.data)}};Kn.create=e=>new Kn({typeName:O.ZodSymbol,...L(e)});var mn=class extends D{_parse(t){if(this._getType(t)!==C.undefined){let r=this._getOrReturnCtx(t);return w(r,{code:b.invalid_type,expected:C.undefined,received:r.parsedType}),P}return he(t.data)}};mn.create=e=>new mn({typeName:O.ZodUndefined,...L(e)});var pn=class extends D{_parse(t){if(this._getType(t)!==C.null){let r=this._getOrReturnCtx(t);return w(r,{code:b.invalid_type,expected:C.null,received:r.parsedType}),P}return he(t.data)}};pn.create=e=>new pn({typeName:O.ZodNull,...L(e)});var Vt=class extends D{constructor(){super(...arguments),this._any=!0}_parse(t){return he(t.data)}};Vt.create=e=>new Vt({typeName:O.ZodAny,...L(e)});var vt=class extends D{constructor(){super(...arguments),this._unknown=!0}_parse(t){return he(t.data)}};vt.create=e=>new vt({typeName:O.ZodUnknown,...L(e)});var je=class extends D{_parse(t){let n=this._getOrReturnCtx(t);return w(n,{code:b.invalid_type,expected:C.never,received:n.parsedType}),P}};je.create=e=>new je({typeName:O.ZodNever,...L(e)});var Gn=class extends D{_parse(t){if(this._getType(t)!==C.undefined){let r=this._getOrReturnCtx(t);return w(r,{code:b.invalid_type,expected:C.void,received:r.parsedType}),P}return he(t.data)}};Gn.create=e=>new Gn({typeName:O.ZodVoid,...L(e)});var wt=class e extends D{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==C.array)return w(n,{code:b.invalid_type,expected:C.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)&&(w(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&&(w(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&&(w(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 Oe(n,i,n.path,a)))).then(i=>fe.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Oe(n,i,n.path,a)));return fe.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:O.ZodArray,...L(t)});function Bn(e){if(e instanceof ke){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Pe.create(Bn(r))}return new ke({...e._def,shape:()=>t})}else return e instanceof wt?new wt({...e._def,type:Bn(e.element)}):e instanceof Pe?Pe.create(Bn(e.unwrap())):e instanceof rt?rt.create(Bn(e.unwrap())):e instanceof nt?nt.create(e.items.map(t=>Bn(t))):e}var ke=class e extends D{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=j.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==C.object){let l=this._getOrReturnCtx(t);return w(l,{code:b.invalid_type,expected:C.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 je&&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 Oe(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof je){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&&(w(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 Oe(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=>fe.mergeObjectSync(r,l)):fe.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:O.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 j.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 j.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return Bn(this)}partial(t){let n={};for(let r of j.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 j.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Pe;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return Nl(j.objectKeys(this.shape))}};ke.create=(e,t)=>new ke({shape:()=>e,unknownKeys:"strip",catchall:je.create(),typeName:O.ZodObject,...L(t)});ke.strictCreate=(e,t)=>new ke({shape:()=>e,unknownKeys:"strict",catchall:je.create(),typeName:O.ZodObject,...L(t)});ke.lazycreate=(e,t)=>new ke({shape:e,unknownKeys:"strip",catchall:je.create(),typeName:O.ZodObject,...L(t)});var fn=class extends D{_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 xe(a.ctx.common.issues));return w(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 xe(c));return w(n,{code:b.invalid_union,unionErrors:a}),P}}get options(){return this._def.options}};fn.create=(e,t)=>new fn({options:e,typeName:O.ZodUnion,...L(t)});var bt=e=>e instanceof hn?bt(e.schema):e instanceof Me?bt(e.innerType()):e instanceof yn?[e.value]:e instanceof _n?e.options:e instanceof bn?j.objectValues(e.enum):e instanceof vn?bt(e._def.innerType):e instanceof mn?[void 0]:e instanceof pn?[null]:e instanceof Pe?[void 0,...bt(e.unwrap())]:e instanceof rt?[null,...bt(e.unwrap())]:e instanceof Pr||e instanceof Sn?bt(e.unwrap()):e instanceof wn?bt(e._def.innerType):[],Do=class e extends D{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.object)return w(n,{code:b.invalid_type,expected:C.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}):(w(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:O.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...L(r)})}};function Si(e,t){let n=tt(e),r=tt(t);if(e===t)return{valid:!0,data:e};if(n===C.object&&r===C.object){let o=j.objectKeys(t),s=j.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let c=Si(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===C.array&&r===C.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=Si(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===C.date&&r===C.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var gn=class extends D{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(Lo(s)||Lo(i))return P;let a=Si(s.value,i.value);return a.valid?((Uo(s)||Uo(i))&&n.dirty(),{status:n.value,value:a.data}):(w(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}))}};gn.create=(e,t,n)=>new gn({left:e,right:t,typeName:O.ZodIntersection,...L(n)});var nt=class e extends D{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.array)return w(r,{code:b.invalid_type,expected:C.array,received:r.parsedType}),P;if(r.data.length<this._def.items.length)return w(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&&(w(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 Oe(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>fe.mergeArray(n,i)):fe.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};nt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new nt({items:e,typeName:O.ZodTuple,rest:null,...L(t)})};var jo=class e extends D{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!==C.object)return w(r,{code:b.invalid_type,expected:C.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 Oe(r,a,r.path,a)),value:i._parse(new Oe(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?fe.mergeObjectAsync(n,o):fe.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof D?new e({keyType:t,valueType:n,typeName:O.ZodRecord,...L(r)}):new e({keyType:Ft.create(),valueType:t,typeName:O.ZodRecord,...L(n)})}},Wn=class extends D{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!==C.map)return w(r,{code:b.invalid_type,expected:C.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 Oe(r,a,r.path,[l,"key"])),value:s._parse(new Oe(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}}}};Wn.create=(e,t,n)=>new Wn({valueType:t,keyType:e,typeName:O.ZodMap,...L(n)});var zn=class e extends D{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.set)return w(r,{code:b.invalid_type,expected:C.set,received:r.parsedType}),P;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(w(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&&(w(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 Oe(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)}};zn.create=(e,t)=>new zn({valueType:e,minSize:null,maxSize:null,typeName:O.ZodSet,...L(t)});var Fo=class e extends D{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.function)return w(n,{code:b.invalid_type,expected:C.function,received:n.parsedType}),P;function r(a,c){return $r({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,qn(),_t].filter(l=>!!l),issueData:{code:b.invalid_arguments,argumentsError:c}})}function o(a,c){return $r({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,qn(),_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 qt){let a=this;return he(async function(...c){let l=new xe([]),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 he(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new xe([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new xe([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:nt.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||nt.create([]).rest(vt.create()),returns:n||vt.create(),typeName:O.ZodFunction,...L(r)})}},hn=class extends D{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})}};hn.create=(e,t)=>new hn({getter:e,typeName:O.ZodLazy,...L(t)});var yn=class extends D{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return w(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}};yn.create=(e,t)=>new yn({value:e,typeName:O.ZodLiteral,...L(t)});function Nl(e,t){return new _n({values:e,typeName:O.ZodEnum,...L(t)})}var _n=class e extends D{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return w(n,{expected:j.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 w(n,{received:n.data,code:b.invalid_enum_value,options:r}),P}return he(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})}};_n.create=Nl;var bn=class extends D{_parse(t){let n=j.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==C.string&&r.parsedType!==C.number){let o=j.objectValues(n);return w(r,{expected:j.joinValues(o),received:r.parsedType,code:b.invalid_type}),P}if(this._cache||(this._cache=new Set(j.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=j.objectValues(n);return w(r,{received:r.data,code:b.invalid_enum_value,options:o}),P}return he(t.data)}get enum(){return this._def.values}};bn.create=(e,t)=>new bn({values:e,typeName:O.ZodNativeEnum,...L(t)});var qt=class extends D{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.promise&&n.common.async===!1)return w(n,{code:b.invalid_type,expected:C.promise,received:n.parsedType}),P;let r=n.parsedType===C.promise?n.data:Promise.resolve(n.data);return he(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};qt.create=(e,t)=>new qt({type:e,typeName:O.ZodPromise,...L(t)});var Me=class extends D{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O.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=>{w(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"?an(c.value):n.value==="dirty"?an(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"?an(a.value):n.value==="dirty"?an(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(!jt(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=>jt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):P);j.assertNever(o)}};Me.create=(e,t,n)=>new Me({schema:e,typeName:O.ZodEffects,effect:t,...L(n)});Me.createWithPreprocess=(e,t,n)=>new Me({schema:t,effect:{type:"preprocess",transform:e},typeName:O.ZodEffects,...L(n)});var Pe=class extends D{_parse(t){return this._getType(t)===C.undefined?he(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Pe.create=(e,t)=>new Pe({innerType:e,typeName:O.ZodOptional,...L(t)});var rt=class extends D{_parse(t){return this._getType(t)===C.null?he(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};rt.create=(e,t)=>new rt({innerType:e,typeName:O.ZodNullable,...L(t)});var vn=class extends D{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===C.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};vn.create=(e,t)=>new vn({innerType:e,typeName:O.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...L(t)});var wn=class extends D{_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 xe(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new xe(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};wn.create=(e,t)=>new wn({innerType:e,typeName:O.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...L(t)});var Jn=class extends D{_parse(t){if(this._getType(t)!==C.nan){let r=this._getOrReturnCtx(t);return w(r,{code:b.invalid_type,expected:C.nan,received:r.parsedType}),P}return{status:"valid",value:t.data}}};Jn.create=e=>new Jn({typeName:O.ZodNaN,...L(e)});var ig=Symbol("zod_brand"),Pr=class extends D{_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}},Or=class e extends D{_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(),an(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:O.ZodPipeline})}},Sn=class extends D{_parse(t){let n=this._def.innerType._parse(t),r=o=>(jt(o)&&(o.value=Object.freeze(o.value)),o);return Hn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Sn.create=(e,t)=>new Sn({innerType:e,typeName:O.ZodReadonly,...L(t)});function $l(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Ll(e,t={},n){return e?Vt.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=$l(t,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=$l(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Vt.create()}var ag={object:ke.lazycreate},O;(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"})(O||(O={}));var cg=(e,t={message:`Input not instance of ${e.name}`})=>Ll(n=>n instanceof e,t),Ul=Ft.create,Dl=cn.create,lg=Jn.create,ug=ln.create,jl=un.create,dg=dn.create,mg=Kn.create,pg=mn.create,fg=pn.create,gg=Vt.create,hg=vt.create,yg=je.create,_g=Gn.create,bg=wt.create,vg=ke.create,wg=ke.strictCreate,Sg=fn.create,xg=Do.create,kg=gn.create,Cg=nt.create,Tg=jo.create,Eg=Wn.create,Ag=zn.create,Rg=Fo.create,Ig=hn.create,$g=yn.create,Pg=_n.create,Og=bn.create,Mg=qt.create,Ng=Me.create,Lg=Pe.create,Ug=rt.create,Dg=Me.createWithPreprocess,jg=Or.create,Fg=()=>Ul().optional(),Vg=()=>Dl().optional(),qg=()=>jl().optional(),Hg={string:(e=>Ft.create({...e,coerce:!0})),number:(e=>cn.create({...e,coerce:!0})),boolean:(e=>un.create({...e,coerce:!0})),bigint:(e=>ln.create({...e,coerce:!0})),date:(e=>dn.create({...e,coerce:!0}))};var Bg=P;var Kg=/^[A-Za-z0-9._-]+$/,Gg=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,Fl=new Set([".",".."]),ve=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function Wg(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 ve(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=n?e.slice(1,-2):e.slice(1,-1);if(!Gg.test(o))throw new ve(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=o.split("|");if(s.some(i=>Fl.has(i)))throw new ve(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:s}}if(Kg.test(e)){if(Fl.has(e))throw new ve(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new ve(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function zg(e){if(typeof e!="string"||e.length===0)throw new ve("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new ve("must start with '/'",e);if(e.slice(1).includes("//"))throw new ve("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new ve("must not end with '/'",e);let n=e.slice(1).split("/").map(s=>Wg(s,e));if(n.filter(s=>s.kind==="multi").length>1)throw new ve("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new ve("'**' 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 ve("optional alternation '(...)?' is only allowed as the final segment",e);return n}function xi(e){zg(e)}var Vl=["tempo","mpp_self","merchant_self"],ql=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],Hl=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],Bl=["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 Ci=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()}),Jg=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:Ci.optional()}).passthrough(),Ti=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")})]),Ei=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()}),Kl=h.object({attestation:h.boolean().optional(),rateLimitMs:h.number().positive().optional()}),Gl=h.object({displayName:h.string().optional(),feedbackEligible:h.boolean().optional(),suggestionEligible:h.boolean().optional(),batchable:h.boolean().optional()}),Wl=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(),Yg=h.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),Xg=120,Zg=120,Qg=1200,eh=/^[^\u0000-\u001F\u007F]+$/;function ki(e,t){return h.string().min(1).max(e).regex(eh,`${t} must not contain control characters`)}var Ai={id:h.string().min(1),name:ki(Xg,"name"),description:ki(Qg,"description"),provider:h.string().min(1),model:h.string().min(1),category:Yg,priceCents:h.number().nonnegative(),inputSchema:h.record(h.unknown()),gatewayUrl:h.string().min(1),merchantName:ki(Zg,"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:Ci.optional(),priceDisplay:h.string().optional(),pricingModel:h.enum(["per-call","per-token","band"]).optional(),pricingInfo:Jg.optional(),status:h.enum(["available","unavailable"]).optional(),handler:Ti.optional(),pricing:Ei.optional(),security:Kl.optional(),engagement:Gl.optional(),gatewayConfig:Wl.optional(),freeReadPathPattern:h.string().optional().superRefine((e,t)=>{if(e!==void 0)try{xi(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(Vl).optional(),executionKind:h.enum(ql).optional(),resultKind:h.enum(Hl).optional(),extractionMode:h.enum(Bl).optional(),pricingStrategy:h.enum(["flat","token","band"]).optional()},zl=h.object({...Ai,dispatch:h.literal("routed"),routedPath:h.string().min(1).startsWith("/")}).strict(),Jl=h.object({...Ai,dispatch:h.literal("enveloped")}).strict(),Yl=h.object({...Ai,handler:Ti,pricing:Ei}).strict(),Xl=h.union([h.discriminatedUnion("dispatch",[zl,Jl]),Yl]);var Ri=/^[a-z0-9][a-z0-9_-]*$/;var rh="https://fal.run",tu="https://openrouter.mpp.tempo.xyz",$i=1024,qo=8192,oh=4096,sh=10;function ih(e){return e>=sh?oh:qo}function nu(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):$i;return Math.min(n,t)}function ah(e){let{attestation:t,tool_id:n,...r}=e;return r}var Zl={"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 Vo(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:o,...s}=e,i={...s};return typeof o=="string"&&o.length>0?(i.image_size=o,i):(typeof r=="string"&&Zl[r]&&(i.image_size=Zl[r]),i)}function ch(e){let{attestation:t,tool_id:n,...r}=e;return r}function Ql(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 lh(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 uh(e,t,n,r,o,s,i,a){return lh(e,t,n,"suno-ai",r,o,s,i,{merchantName:"Suno AI",...a})}function oe(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:`${rh}/${r}`,merchantName:"fal.ai",buildBody:ah,tags:[],...a}}function ru(e,t=qo){return n=>{let{attestation:r,tool_id:o,model:s,prompt:i,system_prompt:a,max_tokens:c,max_completion_tokens:l,messages:u,temperature:d,...p}=n;return typeof s=="string"&&s.length>0&&s!==e&&console.warn("[catalog] openrouterBuildBody: caller model override ignored",{catalogModel:e,callerModel:s}),{messages:Array.isArray(u)?u:[...a?[{role:"system",content:a}]:[],{role:"user",content:i}],temperature:d??.7,...p,model:e,max_tokens:nu(c??l,t)}}}function ou(e,t=qo){return n=>{let{attestation:r,tool_id:o,prompt:s,image_url:i,aspect_ratio:a,max_tokens:c,max_completion_tokens:l,model:u,messages:d,image_config:p,temperature:m,...g}=n,_=[{type:"text",text:s}];return typeof i=="string"&&i.length>0&&_.push({type:"image_url",image_url:{url:i}}),{messages:Array.isArray(d)?d:[{role:"user",content:_}],temperature:m??.7,...g,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:nu(c??l,t)}}}function Q(e,t,n,r,o,s,i){let a=i?.maxOutputTokens??ih(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: ${$i}); 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:`${tu}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:ru(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s,...c>0?{perRequestFeeCents:c}:{}},...g}}function Ii(e,t,n,r,o,s){let i=s?.maxOutputTokens??qo,{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: ${$i}); 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:`${tu}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:ou(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var Pi=[oe("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"]}),oe("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:Vo}),oe("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:Vo}),oe("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:Vo}),oe("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"]}),Ii("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),Ii("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}}),Ii("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}}),oe("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"]}),oe("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"]}),oe("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"]}),oe("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"]}),oe("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"]}),oe("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"]}),oe("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"]}),oe("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"]}),oe("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"]}),uh("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}}}),oe("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"]}),oe("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"]}),oe("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"]}),oe("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:Ql,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:ch,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=>Vo({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"]},oe("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"}),oe("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:Ql,tags:["onchain","prices","allium","crypto","legacy"]}];function Mr(e){return Pi.find(t=>t.id===e)}var su=1,iu=["pick_one","fan_out"],au=["concat","dedupe_by_url","top_k_by_score"],ph=8,fh=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()}),gh=h.object({toolId:h.string().min(1),notes:h.string().min(1)}),hh=h.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),yh=h.object({providers:h.array(h.string().min(1)).min(1).max(ph),merge:h.enum(au),maxResults:h.number().int().positive().optional()}),cu=h.object({mode:h.enum(iu).default("pick_one"),intro:h.string().min(1),defaultTier:h.string().min(1),tiers:h.record(hh,gh).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:yh.optional(),guidance:h.string().min(1),inputProperties:h.record(h.string(),fh),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"]}),_h=h.object({version:h.literal(su),generatedAt:h.string().datetime(),tools:h.record(h.string().regex(Ri,"tool name must match MCP naming rules"),cu).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Go=require("child_process"),hu=require("util"),yu=T(require("crypto")),z=T(require("fs")),_u=T(require("os")),ye=T(require("path"));var Fe=(0,hu.promisify)(Go.execFile),wh=()=>process.platform==="darwin",Ht=()=>process.platform==="win32",Bt=ye.join(_u.homedir(),".visa-mcp","bin"),xn=ye.join(Bt,"Visa CLI"),St=ye.join(Bt,"visa-keychain-win.exe"),bu=ye.join(__dirname,"..","native"),lu="6",uu=ye.join(Bt,"visa-keychain.version"),du=ye.join(Bt,"visa-keychain.sha256"),mu="1",pu=ye.join(Bt,"visa-keychain-win.version"),fu=ye.join(Bt,"visa-keychain-win.sha256"),vu=[ye.join(bu,"bin","win32-x64","visa-keychain-win.exe"),ye.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),ye.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Ho(e){let t=z.readFileSync(e);return yu.createHash("sha256").update(t).digest("hex")}function Sh(e){let t=e.trim();if(t.startsWith("OK:"))return t.slice(3);if(t==="OK")return;let n=t.startsWith("ERROR:")?t.slice(6):"Unknown error";throw new Error(n)}async function Oi(){try{if(z.readFileSync(uu,"utf-8").trim()===lu&&z.existsSync(xn)){let r=z.readFileSync(du,"utf-8").trim();if(Ho(xn)!==r)f.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),z.unlinkSync(xn);else return xn}}catch{}let e=ye.join(bu,"visa-keychain.m");if(z.existsSync(e)||(e=ye.resolve(__dirname,"..","..","native","visa-keychain.m")),z.existsSync(e)||(e=ye.resolve(__dirname,"..","native","visa-keychain.m")),!z.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");z.mkdirSync(Bt,{recursive:!0,mode:448});try{await Fe("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",xn,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Ho(xn);return z.writeFileSync(du,t,{mode:384}),z.writeFileSync(uu,lu,{mode:384}),xn}function wu(){for(let e of vu)if(z.existsSync(e))return e;return null}async function Yn(){try{if(z.readFileSync(pu,"utf-8").trim()===mu&&z.existsSync(St)){let r=z.readFileSync(fu,"utf-8").trim();if(Ho(St)!==r)f.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),z.unlinkSync(St);else return St}}catch{}let e=wu();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
|
|
132
|
-
If building from source, run native/build-win.bat first.`);z.mkdirSync(Bt,{recursive:!0}),z.copyFileSync(e,St);let t=Ho(St);return z.writeFileSync(fu,t,{mode:384}),z.writeFileSync(pu,mu,{mode:384}),St}async function xh(){return Ht()?Yn():Oi()}var Bo="visa-cli",Ko="attestation-key";async function kh(e){try{await Fe("security",["delete-generic-password","-s",Bo,"-a",Ko],{timeout:5e3})}catch{}await Fe("security",["add-generic-password","-s",Bo,"-a",Ko,"-w",e],{timeout:5e3})}function Ch(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 Th(){try{let{stdout:e}=await Fe("security",["find-generic-password","-s",Bo,"-a",Ko,"-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:Ch(e)}}}async function Mi(){let e=await Th();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 Su(e){let t=await xh(),n;try{n=(await Fe(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 Sh(n)}var gu=!1;function Eh(){if(!Ht())return!1;try{return z.existsSync(St)||wu()!==null?!0:(gu||(gu=!0,f.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:St,searchedPrebuiltPaths:vu})),!1)}catch{return!1}}function se(){return Pn()||wh()?!0:Ht()?Eh():!1}async function Wo(){if(Ht()){let o=await Yn(),{stdout:s}=await Fe(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 Su(["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 kh(n),r}async function zo(){if(Ht())try{let e=await Yn(),{stdout:t}=await Fe(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await Mi()!==null}async function xu(){if(Pn())return"mock-public-key-spki";if(Ht()){let n=await Yn(),{stdout:r}=await Fe(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 Mi();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await Oi();return new Promise((n,r)=>{let o=(0,Go.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 kn(e,t){if(Pn())return Promise.resolve(Ya());if(Ht()){let s=await Yn(),i=["sign",e];t&&i.push(t);let{stdout:a}=await Fe(s,i,{timeout:6e4}),c=a.trim();if(c.startsWith("OK:"))return c.slice(3);throw new Error(c.startsWith("ERROR:")?c.slice(6):"Unknown error")}let n=await Mi();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Oi(),o=["sign",e];return t&&o.push(t),new Promise((s,i)=>{let a=(0,Go.execFile)(r,o,{timeout:6e4},(c,l)=>{let u=(l||"").trim();if(c){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}u.startsWith("OK:")?s(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function Jo(){if(Ht()){try{let e=await Yn();await Fe(e,["delete-key"],{timeout:1e4})}catch{}return}try{await Fe("security",["delete-generic-password","-s",Bo,"-a",Ko],{timeout:5e3})}catch{}try{await Su(["delete-key"])}catch{}}var Ah=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Rh=[...Ah.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 Li(e,t=Rh){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Ni(e.intentText);for(let r of t)if(r.match.kind==="intent"&&r.match.metaTool===e.metaTool&&!(r.match.tier&&r.match.tier!==e.tier)&&!(r.match.provider&&!n.includes(Ni(r.match.provider)))&&r.match.keywords.every(o=>n.includes(Ni(o))))return r.targetToolId;return null}function Ni(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var Lr={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 Kt(e,t,n){if(!Cu(e))return Oh(e,n);let r=ku[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=Mh(e,s,n);return i||Nh(e,r,s,o)}function Oh(e,t){return Li({requestedTool:e,intentText:t})??e}function Mh(e,t,n){return Li({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Nh(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 ku=Lr;function Cu(e){return e in ku}var Ur=Object.keys(Lr);function Ui(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Tu(e=process.env){return Ui(e)!==null}function Eu(e=process.env){let t=(e.VISA_CLI_PARENTLESS_SINGLE_CALL??"").trim().toLowerCase();return t==="true"||t==="1"}function Au(e=process.env){let t=(e.VISA_CLI_PARENTLESS_BATCH??"").trim().toLowerCase();return t==="true"||t==="1"}var md=require("child_process"),me=T(require("crypto")),Be=T(require("fs")),Br=T(require("os")),ms=T(require("path"));function ot(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"?On(o):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?On(i):null;if(!s&&!c)return e;let l=s??c,u=s?"content":"urls",d;try{d=ur(l,{tag:Lh(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 Lh(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 Ru=!1;async function Xn(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")||!se())throw r;if(f.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(Ru)throw f.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;Ru=!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 Wo();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 st(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Yo(e,t){if(!se())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 zo())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 st(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 Iu="2.8.1";function Di(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Xo(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=Oo(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Ae(e){return e==null?"\u2014":e?"yes":"no"}function Zo(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Uh(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Dh(){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=yi("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:gi,source:{kind:"default"}}}async function Dr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(N){n=N?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=hi("auth.serverUrl"),i=Te(),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:Ae(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:Ae(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:Ae(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:se(),formatted:Ae(se()),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:Zo(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Zo(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Zo(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Zo(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(N=>N.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=Dh();r.push({key:"credit.sessionCapCents",value:m.value,formatted:Uh(m.value),source:m.source});let g=vl();g.length>0&&r.push({key:"settings.retired",value:g.map(N=>N.key),formatted:g.map(N=>N.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${g.map(N=>`visa-cli config unset ${N.key}`).join(" && ")}`});let _=Xo("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:_.value,formatted:Ae(_.value),source:_.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let x=Xo("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:x.value,formatted:Ae(x.value),source:x.source});let $=et(),M;process.env.VISA_CLI_NO_UPDATE_CHECK?M={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?M={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?M={kind:"env",var:"NODE_ENV"}:M={kind:"default"},r.push({key:"ui.updateCheck",value:!$,formatted:Ae(!$),source:M});let S=Xo("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:S.value,formatted:Ae(S.value),source:S.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let k=Xo("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:k.value,formatted:Ae(k.value),source:k.source});let y=process.env.VISA_DRY_RUN,v=Tu();if(r.push({key:"tools.dryRun",value:v,formatted:Ae(v),source:y===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:Iu,formatted:Iu,source:{kind:"default"}}),e.includeDev){let N=process.env.VISA_MOCK_KEYCHAIN,we=Tt();r.push({key:"dev.mockKeychain",value:we,formatted:Ae(we),source:Di("VISA_MOCK_KEYCHAIN",!!N),hint:Ps()});let le=process.env.VISA_MOCK_TOUCHID,_e=Pn();r.push({key:"dev.mockTouchid",value:_e,formatted:Ae(_e),source:Di("VISA_MOCK_TOUCHID",!!le),hint:Ps()});let H=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!H,formatted:Ae(!!H),source:Di("VISA_CLI_DEBUG",!!H)})}return{entries:r,statusError:n}}function jh(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 $u(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}(${jh(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
|
|
132
|
+
If building from source, run native/build-win.bat first.`);z.mkdirSync(Bt,{recursive:!0}),z.copyFileSync(e,St);let t=Ho(St);return z.writeFileSync(fu,t,{mode:384}),z.writeFileSync(pu,mu,{mode:384}),St}async function xh(){return Ht()?Yn():Oi()}var Bo="visa-cli",Ko="attestation-key";async function kh(e){try{await Fe("security",["delete-generic-password","-s",Bo,"-a",Ko],{timeout:5e3})}catch{}await Fe("security",["add-generic-password","-s",Bo,"-a",Ko,"-w",e],{timeout:5e3})}function Ch(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 Th(){try{let{stdout:e}=await Fe("security",["find-generic-password","-s",Bo,"-a",Ko,"-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:Ch(e)}}}async function Mi(){let e=await Th();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 Su(e){let t=await xh(),n;try{n=(await Fe(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 Sh(n)}var gu=!1;function Eh(){if(!Ht())return!1;try{return z.existsSync(St)||wu()!==null?!0:(gu||(gu=!0,f.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:St,searchedPrebuiltPaths:vu})),!1)}catch{return!1}}function se(){return Pn()||wh()?!0:Ht()?Eh():!1}async function Wo(){if(Ht()){let o=await Yn(),{stdout:s}=await Fe(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 Su(["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 kh(n),r}async function zo(){if(Ht())try{let e=await Yn(),{stdout:t}=await Fe(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await Mi()!==null}async function xu(){if(Pn())return"mock-public-key-spki";if(Ht()){let n=await Yn(),{stdout:r}=await Fe(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 Mi();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await Oi();return new Promise((n,r)=>{let o=(0,Go.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 kn(e,t){if(Pn())return Promise.resolve(Ya());if(Ht()){let s=await Yn(),i=["sign",e];t&&i.push(t);let{stdout:a}=await Fe(s,i,{timeout:6e4}),c=a.trim();if(c.startsWith("OK:"))return c.slice(3);throw new Error(c.startsWith("ERROR:")?c.slice(6):"Unknown error")}let n=await Mi();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Oi(),o=["sign",e];return t&&o.push(t),new Promise((s,i)=>{let a=(0,Go.execFile)(r,o,{timeout:6e4},(c,l)=>{let u=(l||"").trim();if(c){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}u.startsWith("OK:")?s(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function Jo(){if(Ht()){try{let e=await Yn();await Fe(e,["delete-key"],{timeout:1e4})}catch{}return}try{await Fe("security",["delete-generic-password","-s",Bo,"-a",Ko],{timeout:5e3})}catch{}try{await Su(["delete-key"])}catch{}}var Ah=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Rh=[...Ah.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 Li(e,t=Rh){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Ni(e.intentText);for(let r of t)if(r.match.kind==="intent"&&r.match.metaTool===e.metaTool&&!(r.match.tier&&r.match.tier!==e.tier)&&!(r.match.provider&&!n.includes(Ni(r.match.provider)))&&r.match.keywords.every(o=>n.includes(Ni(o))))return r.targetToolId;return null}function Ni(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var Lr={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 Kt(e,t,n){if(!Cu(e))return Oh(e,n);let r=ku[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=Mh(e,s,n);return i||Nh(e,r,s,o)}function Oh(e,t){return Li({requestedTool:e,intentText:t})??e}function Mh(e,t,n){return Li({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Nh(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 ku=Lr;function Cu(e){return e in ku}var Ur=Object.keys(Lr);function Ui(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Tu(e=process.env){return Ui(e)!==null}function Eu(e=process.env){let t=(e.VISA_CLI_PARENTLESS_SINGLE_CALL??"").trim().toLowerCase();return t==="true"||t==="1"}function Au(e=process.env){let t=(e.VISA_CLI_PARENTLESS_BATCH??"").trim().toLowerCase();return t==="true"||t==="1"}var md=require("child_process"),me=T(require("crypto")),Be=T(require("fs")),Br=T(require("os")),ms=T(require("path"));function ot(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"?On(o):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?On(i):null;if(!s&&!c)return e;let l=s??c,u=s?"content":"urls",d;try{d=ur(l,{tag:Lh(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 Lh(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 Ru=!1;async function Xn(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")||!se())throw r;if(f.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(Ru)throw f.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;Ru=!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 Wo();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 st(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Yo(e,t){if(!se())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 zo())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 st(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 Iu="2.8.2";function Di(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Xo(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=Oo(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Ae(e){return e==null?"\u2014":e?"yes":"no"}function Zo(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Uh(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Dh(){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=yi("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:gi,source:{kind:"default"}}}async function Dr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(N){n=N?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=hi("auth.serverUrl"),i=Te(),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:Ae(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:Ae(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:Ae(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:se(),formatted:Ae(se()),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:Zo(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Zo(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Zo(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Zo(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(N=>N.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=Dh();r.push({key:"credit.sessionCapCents",value:m.value,formatted:Uh(m.value),source:m.source});let g=vl();g.length>0&&r.push({key:"settings.retired",value:g.map(N=>N.key),formatted:g.map(N=>N.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${g.map(N=>`visa-cli config unset ${N.key}`).join(" && ")}`});let _=Xo("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:_.value,formatted:Ae(_.value),source:_.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let x=Xo("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:x.value,formatted:Ae(x.value),source:x.source});let $=et(),M;process.env.VISA_CLI_NO_UPDATE_CHECK?M={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?M={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?M={kind:"env",var:"NODE_ENV"}:M={kind:"default"},r.push({key:"ui.updateCheck",value:!$,formatted:Ae(!$),source:M});let S=Xo("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:S.value,formatted:Ae(S.value),source:S.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let k=Xo("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:k.value,formatted:Ae(k.value),source:k.source});let y=process.env.VISA_DRY_RUN,v=Tu();if(r.push({key:"tools.dryRun",value:v,formatted:Ae(v),source:y===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:Iu,formatted:Iu,source:{kind:"default"}}),e.includeDev){let N=process.env.VISA_MOCK_KEYCHAIN,we=Tt();r.push({key:"dev.mockKeychain",value:we,formatted:Ae(we),source:Di("VISA_MOCK_KEYCHAIN",!!N),hint:Ps()});let le=process.env.VISA_MOCK_TOUCHID,_e=Pn();r.push({key:"dev.mockTouchid",value:_e,formatted:Ae(_e),source:Di("VISA_MOCK_TOUCHID",!!le),hint:Ps()});let H=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!H,formatted:Ae(!!H),source:Di("VISA_CLI_DEBUG",!!H)})}return{entries:r,statusError:n}}function jh(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 $u(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}(${jh(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
|
|
133
133
|
`)}function Pu(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 Ou(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 Gt=require("fs"),Nu=require("os"),ji=require("path"),Fh=(0,ji.join)((0,Nu.homedir)(),".visa-mcp"),Mu=(0,ji.join)(Fh,"mcp-session-budget.json");function Qo(){try{(0,Gt.existsSync)(Mu)&&(0,Gt.unlinkSync)(Mu)}catch{}}var Vi=require("crypto"),qe=T(jr()),Cn=null,Re=0,Zn=0,Ce=0,Wt=null,qi=null,Hi=null,ts=Promise.resolve();function oy(e){return Number((0,qe.fromCents)(e))}function Du(e){return(0,qe.toCents)((0,qe.micros)(BigInt(e)))}function Uu(e){return(0,qe.toWire)((0,qe.fromCents)(e))}function Fi(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function es(e){return typeof e=="string"&&/^\d+$/.test(e)}var sy=43,iy=new RegExp(`^[A-Za-z0-9_-]{${sy}}$`);function ay(e){return typeof e=="string"&&iy.test(e)}function cy(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||Cn&&e.session_id!==Cn||typeof e.nonce!="string"||e.nonce.length===0||!ay(e.server_signature)||!Fi(e.cumulative)||!Fi(e.remaining)||!Fi(e.delta)||e.cumulative<Re||Ce>0&&e.cumulative>Ce||Ce>0&&e.remaining>Ce||e.cumulative_micros!==void 0&&!es(e.cumulative_micros)||e.remaining_micros!==void 0&&!es(e.remaining_micros)||e.delta_micros!==void 0&&!es(e.delta_micros)||e.reserved_micros!==void 0&&!es(e.reserved_micros))}function kt(e){Cn=e,Re=0,Zn=0,Ce=0,Wt=null,qi=null,Hi=null,ts=Promise.resolve()}function Fr(e){Ce=Math.max(0,Math.floor(e))}function Bi(){return Cn}function Ki(e){if(!Cn)return null;let t=Re+Zn;return Ce>0&&t>Ce&&(t=Ce),{session_budget_id:Cn,cumulative_micros:oy(t),nonce:(0,Vi.randomUUID)(),idempotency_key:e||(0,Vi.randomUUID)()}}function Vr(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)?(Re=Math.max(Re,r.cumulative),Zn=0,Wt=r,r):null}function ju(){return Wt}function Gi(e){let t=Du(e.cumulative_micros);Re=Math.max(Re,t),Zn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Re,remaining:Math.max(0,Ce-Re),delta:0,cumulative_micros:Uu(Re),remaining_micros:Uu(Math.max(0,Ce-Re)),delta_micros:"0",nonce:e.nonce};return Wt=n,n}function qr(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,qe.toCents)((0,qe.micros)(n));if(!Number.isFinite(r)||r<0)return;qi=t;let o=e,s=typeof o.session_id=="string"?o.session_id:Cn??"";Wt?(typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)&&(Wt.remaining_micros=o.remaining_micros),typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)&&(Wt.delta_micros=o.charged_micros)):Wt={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 Fu(e){let t=e.receipt??null;Hi={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Du(e.voucher.cumulative_micros),estimatedCumulativeCents:ns(),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 Vu(){return Hi}function qu(){return Re}function Hu(){return qi}function ns(){let e=Re+Zn;return Ce>0&&e>Ce&&(e=Ce),e}function Bu(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return ts=ts.then(()=>{Zn+=t}),ts}var ly=10,uy=1,ee=null,Ku=Promise.resolve();function Wi(e){let t=Ku.catch(()=>{}).then(e);return Ku=t.then(()=>{},()=>{}),t}var de=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 zi(e,t,n){return Wi(()=>Gu(e,t,n))}async function Gu(e,t,n){if(Qo(),ee&&new Date(ee.expiresAt).getTime()>Date.now())return Bi()!==ee.budgetId&&(kt(ee.budgetId),Fr(ee.totalCents)),f.info("mcp-session:active-hit",{budgetId:ee.budgetId,tool:n.toolName,remainingEstimatedCents:ee.totalCents-ns()}),{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"?uy:ly,i=Math.max(s,Math.ceil(n.minRequiredCents??s));if(r.balanceCents<i)throw new de(r.balanceCents,i);let a=n.capCentsOverride??xl(),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),Fr(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 Wu(e,t,n){return Wi(async()=>{let o=zt()?await zu(e):null,s=await Gu(e,t,n);return{budgetId:s.budgetId,totalCents:s.totalCents,closedPrevious:o,requestedCapCents:s.requestedCapCents,appliedCapCents:s.appliedCapCents,clampedReason:s.clampedReason}})}async function zu(e){let n=zt()?.budgetId??Bi(),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 Qo(),ee=null,kt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:o,finalCumulativeMicros:s}}async function rs(e){return Wi(()=>zu(e))}function zt(){return Qo(),ee?new Date(ee.expiresAt).getTime()<=Date.now()?(ee=null,kt(null),null):{budgetId:ee.budgetId,totalCents:ee.totalCents,lastReceiptCumulative:qu(),lastReceiptCumulativeMicros:ju()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Hu(),estimatedCumulative:ns(),lastToolSpend:Vu(),expiresAt:ee.expiresAt}:null}var Yu=T(jr()),Ju=10000n;function dy(e){return e<=0n?0:Number((e+Ju-1n)/Ju)}function Xu(e){return dy((0,Yu.fromUsd)(e))}var os=T(jr()),my=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function ss(e){if(typeof e!="string"||!my.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,os.toDisplay)((0,os.fromCents)(o),{symbol:""})}}var is="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.",Zu="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 Qu=Promise.resolve(),ed=!1;function ps(e){let t=Qu.catch(()=>{}).then(e);return Qu=t.then(()=>{},()=>{}),t}async function pd(e){let t=await pe(()=>zi(I,Le,{toolName:e.toolId,userContext:e.userContext})),n=Ki(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await vy(),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 jn){if(f.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await rs(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 ed||(ed=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
|
|
134
|
-
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}),fd(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=Vr(s)??(n?Gi(n):null);if(qr(o?.receipt_v2),await Bu(e.estimatedAmountCents),Fu({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Qi(o))return ot(o);let c=await Zi();if(e.idempotencyKey&&ea(o,c,e.idempotencyKey))return ot(o);let l=c?Hr(c):null;return ot(ta(o,r,l))}function Ne(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function ls(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(ls).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${ls(r)}`).join(",")}}`}function Xi(e,t,n,r){let o=me.createHash("sha256").update(`${n}:${ls(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function py(e,t){return`${e}:${t}`}function fy(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 us(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=fy(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:py(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 fd(e){return pe(()=>hy(e))}async function gd(e,t,n){if(Qi(e))return ot(e);let r=await Zi();if(n&&ea(e,r,n))return ot(e);let o=r?Hr(r):null;return ot(ta(e,t,o))}async function gy(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 Le("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 Vr(i),qr(s?.receipt_v2),f.info("parentless-single-call:completed",{tool:e.toolId}),gd(s,e.beforeBalanceMicros,e.idempotencyKey)}async function hy(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 de(n.balanceCents,t);let r=t,o=Hr(n);if(Eu()){let l=e.idempotencyKey??me.randomUUID();try{return await gy({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 Ze)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 Le("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),Fr(a.budget.totalCents),f.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});try{let l=Ki(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(Vr(d)||Gi(l),qr(u?.receipt_v2),Qi(u))return ot(u);let p=await Zi();if(e.idempotencyKey&&ea(u,p,e.idempotencyKey))return ot(u);let m=p?Hr(p):null;return ot(ta(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 Yt(e){return ps(async()=>zt()?pd(e):fd(e))}function fs(){return Te()}var I=new Ee(()=>F.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 yy(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 _y(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 as(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function by(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 vy(){try{let e=await I.getBalance();return e.success?Hr(e):null}catch{return null}}async function Zi(){try{let e=await I.getBalance();return e.success?e:null}catch{return null}}function Qi(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 ea(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 ta(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 wy="2.8.
|
|
135
|
-
`);function Ke(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=gr(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(wl())return{opened:!1,url:t,blockedReason:"suppressed"};let n=Ks();if(n.headless)return f.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=dc(t,fs());if(!r)return f.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=pc(r);return o?((0,md.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 "${Br.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function pe(e){return Xn(I,e,xd)}var hd="get_cards",yd="set_default_card";function Sy(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 '${hd}' to see enrolled cards and '${yd}' to switch, then retry the original request.`}function xy(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 '${hd}' to see enrolled cards and '${yd}' to switch. Do not retry automatically.`}function Ge(e,t){let n=e.retryable?Sy(e.code,e.retryAfter):xy(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 ky(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 Qn=null,Cy=3e4;function _d(){Qn=null}var Jt=class extends Error{constructor(n){super(`${ds()} attestation is required for this action, but it is not available in this MCP process. `+na());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function gs(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. `+na()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function Ty(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:is,agent_guidance:Zu}}function ds(){return process.platform==="darwin"?"Touch ID":"local biometric"}function na(){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 Ey(e){let t=Date.now();if(Qn&&Qn.expiresAt>t)return{required:Qn.required,hasRegisteredKey:Qn.hasRegisteredKey};try{let n=await I.getStatus(e),r=n.attestationRequired!==!1,o=st(n);return Qn={required:r,hasRegisteredKey:o,expiresAt:t+Cy},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Le(e,t,n,r,o,s){if(!s?.forceRequired){let i=await Ey(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(!se())throw f.warn("attestation:unavailable",{context:e}),new Jt(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 kn(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 td="[dry-run] https://placeholder.visa-cli.dev/image.png",Ay=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"]),Ry=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 Iy(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||Ay.has(e)?"image":t==="generate_video"||Ry.has(e)?"video":null}function $y(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function Py(e){return e==="llm"?"OpenRouter":"fal.ai"}function er(e,t,n,r){let o={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:Py(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${$y(n)}`;return{...o,content:i,data:{content:i,model:t,dry_run:!0}}}return{...o,urls:[td],data:{[e==="video"?"videoUrl":"imageUrl"]:td,metadata:{dry_run:!0}}}}async function Ji(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:me.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(o){f.warn("dry_run:telemetry_failed",{tool:e.toolName,error:o?.message||String(o),mode:t})}}var Oy="https://openrouter.ai/api/v1/chat/completions",My="openrouter/free",Ny=50,Ly=15e3;function Uy(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 Dy(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:er("llm",e,t,n),degraded:!0,resolvedModel:null};let o=Uy(t),s;try{s=await Xe(Oy,{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:My,messages:[{role:"user",content:o}],max_tokens:Ny}),timeoutMs:Ly})}catch(u){return f.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:er("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:er("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:er("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 hs(e,t,n,r){let o=Ui();if(!o)return null;let s=Iy(e,r);if(!s)return null;let i=Date.now();if(o==="mock"){let l=er(s,e,t,r);return await Ji({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=er(s,e,t,r);return await Ji({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 Dy(e,t,r);return await Ji({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 it(e){return Xu(e.amount)}function jy(){return ms.join(Br.homedir(),".visa-mcp","allium-results")}var ex=16*1024,tx=50*1024*1024;function Fy(){let e=jy();try{if(!Be.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Be.readdirSync(e),n=0,r=0;for(let o of t)try{let s=Be.statSync(ms.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 nd=3600*1e3,Yi=0;function Vy(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Kr(e){if(!Sl()&&!(Date.now()<Yi))try{if(!await F.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(Vy(t)){let n=Yi===0;Yi=Date.now()+nd,n&&f.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:nd});return}f.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function qy(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 pe(async()=>{let l=await Le("get_visa_smi",a,i,c),u=await I.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:l,idempotencyKey:me.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 re)return f.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),Ge(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 Hy(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 hs("generate_image_card",e,t);if(n)return n;let r=await Ct("generate_image_card",void 0,t),o=me.randomUUID();f.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await pe(async()=>{let s;try{s=await Yt({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:it(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof de)return Ne(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=>Ke(i)),Kr({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 re)return f.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ge(s,r);throw f.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function By(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 hs("generate_image_fast_card",e,t);if(n)return n;let r=await Ct("generate_image_fast_card",void 0,t),o=me.randomUUID();f.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await pe(async()=>{let s;try{s=await Yt({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:it(r),userContext:t,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof de)return Ne(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=>Ke(i)),Kr({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 re)return f.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ge(s,r);throw f.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Ky(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 hs("generate_video_tempo_card",e,t);if(n)return n;let r=await Ct("generate_video_tempo_card",void 0,t),o=me.randomUUID();f.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await pe(async()=>{let s;try{s=await Yt({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:it(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof de)return Ne(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=>Ke(i)),Kr({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 re)return f.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ge(s,r);throw f.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Gy(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=me.randomUUID();f.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await pe(async()=>{let o;try{o=await Yt({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:it(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof de)return Ne(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=>Ke(s)),Kr({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 re)return f.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ge(o,n);throw f.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Wy(e,t){let n=await Ct("check_music_status_tempo_card",void 0,t),r=me.randomUUID();f.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await pe(async()=>{let o;try{o=await Yt({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:it(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof de)return Ne(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=>Ke(s)),o})}catch(o){if(o instanceof re)return f.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ge(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 zy(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=me.randomUUID();f.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await pe(async()=>{let o;try{o=await Yt({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:it(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof de)return Ne(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 re)return f.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ge(o,n);throw f.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var Jy=["generate_music_tempo_card"],rd=10,od=5,sd=new Map;function id(e){let t=sd.get(e);if(t!==void 0)return t;let r=Mr(e)?.isAsync===!0||Jy.includes(e);return sd.set(e,r),r}var Yy=36e4,Xy=18e4,Zy=15e3,Qy=12e4,e_=2e3;function ad(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function t_(e,t){return me.createHash("sha256").update(`${e}:${ls(t)}`).digest("hex")}function n_(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,...us(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=>Ke(d)),{deltaCharged:l,deltaMicros:u}}function r_(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($=>$?.success===!1).length,m=t.length-p,g=t.flatMap($=>Array.isArray($?.urls)?$.urls:[]),_=l>0n?Number(l)/1e6:Math.round((c+Number.EPSILON)*100)/100,x=m===0?"failure":p===0?"success":"partial";return f.info("payment:success",{tool:"batch",batchTool:s,count:n.length,totalAmount:a,totalCharged:_,merchant:i,successCount:m,failedCount:p,outcome:x,mode:d,batchId:u}),{success:m>0,outcome:x,batch_id:u,tool:o?r[0]:s,count:n.length,successCount:m,failedCount:p,totalCharged:_,...l>0n?{totalChargedMicros:l.toString(),amountMicros:l.toString(),amount_micros:l.toString()}:{},merchantName:i,results:t,...g.length?{urls:g}:{}}}async function o_(e){let{resolvedItems:t,previews:n,freeTools:r,catalogEntries:o,uniqueTools:s,isHomogeneous:i,primaryTool:a,merchantNames:c,totalAmount:l,timeoutMs:u,batchId:d,userContext:p}=e,m=Math.max(1,Math.ceil(l*100)),g=await I.getBalance();if(!g.success)throw new Error(`Could not read balance: ${g.error||"unknown error"}`);if(g.balanceCents<m)throw new de(g.balanceCents,m);let _=`batch-${d}`,x=`spend up to $${(m/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:$}=await pe(async()=>{let y=await Le("batch_open",m,_,x,p),v=y?.nonce??(await I.getAttestationChallenge()).nonce;f.info("parentless-batch:open-attempt",{batchTool:a,count:t.length,approvedTotalCents:m,attested:!!y});let{batch_parent_id:N}=await I.batchOpen({...y?{attestation:y}:{},nonce:v,approved_total_cents:m,batch_id:d});return{batchParentId:N}});f.info("parentless-batch:opened",{batchTool:a,count:t.length,batchParentId:$});let M=[],S=0,k=0n;try{for(let y=0;y<t.length;y+=1){let v=t[y],N=n[v.resolvedTool],we=r.has(v.resolvedTool);try{let le;if(we)le=await I.shortcut(v.resolvedTool,v.params,u,p,"batch");else{let{data:X,voucherReceiptHeader:$n}=await I.shortcutParentlessBatchItem(v.resolvedTool,{batch_parent_id:$,batch_id:d,batch_index:y,batch_request_hash:t_(v.resolvedTool,v.params),item_ceiling_cents:Math.max(1,it(N)),idempotency_key:Xi(d,y,v.resolvedTool,v.params)},v.params,u,p,"batch");Vr($n),qr(X?.receipt_v2),le=await gd(X,null,Xi(d,y,v.resolvedTool,v.params))}let{deltaCharged:_e,deltaMicros:H}=n_({results:M,batchId:d,index:y,item:v,itemResult:le,preview:N,isFree:we,catalogName:o[v.resolvedTool]?.name});S+=_e,k+=H}catch(le){if(le instanceof de&&M.length===0)return Ne(le);f.warn("payment:batch-item-failed",{tool:v.resolvedTool,index:y,error:le?.message||String(le)}),M.push({success:!1,tool:v.resolvedTool,...us(d,y),error:le?.message||String(le)})}}return r_({results:M,resolvedItems:t,uniqueTools:s,isHomogeneous:i,primaryTool:a,merchantNames:c,totalAmount:l,totalCharged:S,totalChargedMicros:k,batchId:d,mode:"parentless"})}catch(y){if(y instanceof re)return f.warn("payment:declined",{tool:"batch",batchTool:a,count:t.length,totalAmount:l,merchant:c,code:y.code,retryable:y.retryable}),Ge(y,{amount:l,merchantName:c});throw f.error("payment:failure",{tool:"batch",batchTool:a,count:t.length,totalAmount:l,merchant:c,error:y.message}),y}}async function s_(e,t){let n;if(e.requests?.some(y=>y.tool||y.tool_id)&&e.requests)n=e.requests.map(y=>{let v=y.tool||y.tool_id||e.tool;if(!v)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let N=Kt(v,y.tier||e.tier,y.prompt??t),{tool:we,tool_id:le,tier:_e,params:H,...X}=y,$n=H&&typeof H=="object"?{...H,...X}:X;return{resolvedTool:N,params:$n}});else if(e.tool){let y=Kt(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(N=>({resolvedTool:y,params:N}))}else return ad("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return ad("BATCH_EMPTY","Batch requires at least one item.");if(n.length>rd)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${rd} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(id)&&n.length>od)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${od} items. Please use multiple batches for more.`};let i=[...new Set(n.map(y=>y.resolvedTool))],a=i.length===1,c={};for(let y of i)c[y]=await kd(y);let l=new Set(i.filter(y=>c[y]&&Cd(c[y]))),u={};for(let y of i)l.has(y)||(u[y]=await Ct(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let p=[...new Set([...Object.values(u).map(y=>y.merchantName),...i.filter(y=>l.has(y)).map(y=>c[y]?.name??y)])].join(", "),m=a?i[0]:"mixed";f.info("payment:attempt",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:p,heterogeneous:!a});let g=n.some(y=>id(y.resolvedTool)),_=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),x=g?Yy:_?Xy+n.length*Zy:Qy+n.length*e_,$=me.randomUUID(),M=[],S=0,k=0n;return ps(async()=>{let y=!zt();if(Au()&&y&&d>0)try{return await o_({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,uniqueTools:i,isHomogeneous:a,primaryTool:m,merchantNames:p,totalAmount:d,timeoutMs:x,batchId:$,userContext:t})}catch(v){if(v instanceof Ze)f.info("parentless-batch:falling-back-to-session",{batchTool:m,count:n.length,status:v.status,serverErrorCode:v.serverErrorCode});else{if(v instanceof de)return Ne(v);throw v}}if(y&&d>0)try{let v=Math.max(1,Math.ceil(d*100));await pe(()=>zi(I,Le,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:v,capCentsOverride:v}))}catch(v){return v instanceof de?Ne(v):(f.warn("payment:batch-prewarm-failed",{batchTool:m,count:n.length,error:v?.message||String(v)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:v?.message||"Failed to authenticate batch session",tool:m,count:n.length,failedCount:n.length,results:[]})}try{for(let H=0;H<n.length;H+=1){let X=n[H],$n=u[X.resolvedTool];try{let Z=l.has(X.resolvedTool)?await I.shortcut(X.resolvedTool,X.params,x,t,"batch"):await pd({toolId:X.resolvedTool,toolParams:X.params,estimatedAmountCents:it($n),userContext:t,metaTool:"batch",timeoutMs:x,idempotencyKey:Xi($,H,X.resolvedTool,X.params)});if(l.has(X.resolvedTool)&&Z&&typeof Z=="object"&&!Array.isArray(Z)&&Z.merchantName==null&&(Z.merchantName=c[X.resolvedTool]?.name??X.resolvedTool),M.push({success:Z?.success!==!1,tool:X.resolvedTool,...Z,...us($,H,Z)}),Z?.success!==!1){let ar=He(Z?.amountMicros??Z?.amount_micros),ja=typeof Z?.amount=="number"?Z.amount:$n?.amount??0;ar!==null&&ar>0n?k+=ar:k+=BigInt(Math.round(ja*1e6)),S+=ja}Z?.urls&&Z.urls.forEach(ar=>Ke(ar))}catch(Z){if(Z instanceof de&&M.length===0)return Ne(Z);f.warn("payment:batch-item-failed",{tool:X.resolvedTool,index:H,error:Z?.message||String(Z)}),M.push({success:!1,tool:X.resolvedTool,...us($,H),error:Z?.message||String(Z)})}}let v=M.filter(H=>H?.success===!1).length,N=M.length-v,we=M.flatMap(H=>Array.isArray(H?.urls)?H.urls:[]),le=k>0n?Number(k)/1e6:Math.round((S+Number.EPSILON)*100)/100,_e=N===0?"failure":v===0?"success":"partial";return f.info("payment:success",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,totalCharged:le,merchant:p,successCount:N,failedCount:v,outcome:_e,mode:"session",batchId:$}),{success:N>0,outcome:_e,batch_id:$,tool:a?i[0]:m,count:n.length,successCount:N,failedCount:v,totalCharged:le,...k>0n?{totalChargedMicros:k.toString(),amountMicros:k.toString(),amount_micros:k.toString()}:{},merchantName:p,results:M,...we.length?{urls:we}:{}}}catch(v){if(v instanceof re)return f.warn("payment:declined",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:p,code:v.code,retryable:v.retryable}),Ge(v,{amount:d,merchantName:p});throw f.error("payment:failure",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:p,error:v.message}),v}finally{if(y){let v=await rs(I);f.info("batch-session:closed",{budgetId:v.budgetId,closedServerSide:v.closedServerSide})}}})}function i_(){let e=!1,t;try{let r=ms.join(Br.homedir(),".claude","settings.json");if(Be.existsSync(r)){let o=JSON.parse(Be.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";e=Mt(s)}}catch{}let n=_o();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function a_(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=Fy();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=i_(),!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=wy,Array.isArray(t.cards)&&(t.cards=t.cards.map(s=>({...s,displayName:ra(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=zt();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 ra(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 bd(e,t){try{let r=((await I.getStatus(t)).cards||[]).find(o=>o?.id===e);if(r)return ra(r)}catch(n){f.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function c_(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:ra(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 l_(e,t){return await I.getTransactions({limit:e.limit,offset:e.offset},t)}async function u_(e,t){return await I.feedback(e.message,e.transaction_id,t)}async function d_(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Tn("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=ss(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,o=r/100,s=me.randomUUID();f.info("buy_credits:attempt",{amountCents:r});try{return await pe(async()=>{let i=await Le("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 Jt)return Ty();if(i instanceof Qe)return f.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),ky(i);throw f.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function Tn(e,t){return{success:!1,error:t,code:e,message:t}}async function m_(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Tn("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 Tn("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 Tn("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return Tn("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");f.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await pe(async()=>{let n=await Le("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 Jt)return gs(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return Tn("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function p_(e){let t=await Dr({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 f_(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=Mo(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 Nt?"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(Ut).sort()}}}async function g_(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=No(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 Nt?"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(Ut).sort()}}}async function h_(e){let t=await I.getStatus(e),n=t.attestationRequired!==!1,r=st(t),o=se(),s=n?r?o?`${ds()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${ds()} is not available in this process. ${na()}`:"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 y_(e){f.info("biometric:on");let t=await Yo(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?(_d(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function __(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Tn("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 pe(async()=>{let n=await I.getStatus(t),r;if(st(n)&&(r=await Le("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${ds()} 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 _d(),{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 Jt)return gs(n,"biometric_off");throw n}}var cd=3e4,b_=3e5;async function vd(e,t,n="login"){let r=me.randomUUID(),o=`${e}${e.includes("?")?"&":"?"}state=${r}`,s=Ke(o);return!s.opened&&s.blockedReason!=="non_internal_host"&&s.blockedReason!=="invalid_url"?wd(o,s,n):s.opened?{...await Sd(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 wd(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 Sd(e,t,n="login"){let r=Date.now()+b_;for(;Date.now()<r;)try{let s=await fetch(`${fs()}/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 $t(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=Ou(a);if(n!=="enrollment"&&i.sessionToken){await F.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 $t(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 xd(e){let t=me.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=Ke(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?wd(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await Sd(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 v_(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 bd(n,t)}`;try{return await pe(async()=>{let s=await Le(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 Jt)return gs(s,"remove_card");throw s}}async function w_(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 bd(n,t)} as default`;try{return await pe(async()=>{let s=await Le(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 Jt)return gs(s,"set_default_card");throw s}}async function S_(e){return f.info("auth:login_attempt"),vd(`${fs()}/login`,e)}function x_(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 k_(e={},t){let n;try{n=x_(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return ps(async()=>{let r=await pe(()=>Wu(I,Le,{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 C_(){let e=zt();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 T_(){return ps(async()=>{let e=zt();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 rs(I);f.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=_y(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 ${yy(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 E_(e){if(f.info("auth:add_card_attempt"),!await F.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await I.createEnrollCode();return vd(`${fs()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function ld(){if(await F.clearAll(),se())try{await Jo()}catch{}}async function A_(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 ld(),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&&st(r)){let o=await xd(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 ld(),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 R_(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})
|
|
134
|
+
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}),fd(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=Vr(s)??(n?Gi(n):null);if(qr(o?.receipt_v2),await Bu(e.estimatedAmountCents),Fu({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Qi(o))return ot(o);let c=await Zi();if(e.idempotencyKey&&ea(o,c,e.idempotencyKey))return ot(o);let l=c?Hr(c):null;return ot(ta(o,r,l))}function Ne(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function ls(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(ls).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${ls(r)}`).join(",")}}`}function Xi(e,t,n,r){let o=me.createHash("sha256").update(`${n}:${ls(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function py(e,t){return`${e}:${t}`}function fy(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 us(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=fy(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:py(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 fd(e){return pe(()=>hy(e))}async function gd(e,t,n){if(Qi(e))return ot(e);let r=await Zi();if(n&&ea(e,r,n))return ot(e);let o=r?Hr(r):null;return ot(ta(e,t,o))}async function gy(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 Le("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 Vr(i),qr(s?.receipt_v2),f.info("parentless-single-call:completed",{tool:e.toolId}),gd(s,e.beforeBalanceMicros,e.idempotencyKey)}async function hy(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 de(n.balanceCents,t);let r=t,o=Hr(n);if(Eu()){let l=e.idempotencyKey??me.randomUUID();try{return await gy({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 Ze)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 Le("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),Fr(a.budget.totalCents),f.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});try{let l=Ki(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(Vr(d)||Gi(l),qr(u?.receipt_v2),Qi(u))return ot(u);let p=await Zi();if(e.idempotencyKey&&ea(u,p,e.idempotencyKey))return ot(u);let m=p?Hr(p):null;return ot(ta(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 Yt(e){return ps(async()=>zt()?pd(e):fd(e))}function fs(){return Te()}var I=new Ee(()=>F.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 yy(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 _y(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 as(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function by(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 vy(){try{let e=await I.getBalance();return e.success?Hr(e):null}catch{return null}}async function Zi(){try{let e=await I.getBalance();return e.success?e:null}catch{return null}}function Qi(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 ea(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 ta(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 wy="2.8.2",tx=["","","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(`
|
|
135
|
+
`);function Ke(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=gr(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(wl())return{opened:!1,url:t,blockedReason:"suppressed"};let n=Ks();if(n.headless)return f.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=dc(t,fs());if(!r)return f.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=pc(r);return o?((0,md.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 "${Br.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function pe(e){return Xn(I,e,xd)}var hd="get_cards",yd="set_default_card";function Sy(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 '${hd}' to see enrolled cards and '${yd}' to switch, then retry the original request.`}function xy(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 '${hd}' to see enrolled cards and '${yd}' to switch. Do not retry automatically.`}function Ge(e,t){let n=e.retryable?Sy(e.code,e.retryAfter):xy(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 ky(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 Qn=null,Cy=3e4;function _d(){Qn=null}var Jt=class extends Error{constructor(n){super(`${ds()} attestation is required for this action, but it is not available in this MCP process. `+na());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function gs(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. `+na()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function Ty(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:is,agent_guidance:Zu}}function ds(){return process.platform==="darwin"?"Touch ID":"local biometric"}function na(){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 Ey(e){let t=Date.now();if(Qn&&Qn.expiresAt>t)return{required:Qn.required,hasRegisteredKey:Qn.hasRegisteredKey};try{let n=await I.getStatus(e),r=n.attestationRequired!==!1,o=st(n);return Qn={required:r,hasRegisteredKey:o,expiresAt:t+Cy},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Le(e,t,n,r,o,s){if(!s?.forceRequired){let i=await Ey(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(!se())throw f.warn("attestation:unavailable",{context:e}),new Jt(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 kn(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 td="[dry-run] https://placeholder.visa-cli.dev/image.png",Ay=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"]),Ry=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 Iy(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||Ay.has(e)?"image":t==="generate_video"||Ry.has(e)?"video":null}function $y(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function Py(e){return e==="llm"?"OpenRouter":"fal.ai"}function er(e,t,n,r){let o={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:Py(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${$y(n)}`;return{...o,content:i,data:{content:i,model:t,dry_run:!0}}}return{...o,urls:[td],data:{[e==="video"?"videoUrl":"imageUrl"]:td,metadata:{dry_run:!0}}}}async function Ji(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:me.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(o){f.warn("dry_run:telemetry_failed",{tool:e.toolName,error:o?.message||String(o),mode:t})}}var Oy="https://openrouter.ai/api/v1/chat/completions",My="openrouter/free",Ny=50,Ly=15e3;function Uy(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 Dy(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:er("llm",e,t,n),degraded:!0,resolvedModel:null};let o=Uy(t),s;try{s=await Xe(Oy,{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:My,messages:[{role:"user",content:o}],max_tokens:Ny}),timeoutMs:Ly})}catch(u){return f.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:er("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:er("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:er("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 hs(e,t,n,r){let o=Ui();if(!o)return null;let s=Iy(e,r);if(!s)return null;let i=Date.now();if(o==="mock"){let l=er(s,e,t,r);return await Ji({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=er(s,e,t,r);return await Ji({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 Dy(e,t,r);return await Ji({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 it(e){return Xu(e.amount)}function jy(){return ms.join(Br.homedir(),".visa-mcp","allium-results")}var nx=16*1024,rx=50*1024*1024;function Fy(){let e=jy();try{if(!Be.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Be.readdirSync(e),n=0,r=0;for(let o of t)try{let s=Be.statSync(ms.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 nd=3600*1e3,Yi=0;function Vy(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Kr(e){if(!Sl()&&!(Date.now()<Yi))try{if(!await F.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(Vy(t)){let n=Yi===0;Yi=Date.now()+nd,n&&f.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:nd});return}f.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function qy(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 pe(async()=>{let l=await Le("get_visa_smi",a,i,c),u=await I.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:l,idempotencyKey:me.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 re)return f.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),Ge(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 Hy(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 hs("generate_image_card",e,t);if(n)return n;let r=await Ct("generate_image_card",void 0,t),o=me.randomUUID();f.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await pe(async()=>{let s;try{s=await Yt({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:it(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof de)return Ne(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=>Ke(i)),Kr({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 re)return f.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ge(s,r);throw f.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function By(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 hs("generate_image_fast_card",e,t);if(n)return n;let r=await Ct("generate_image_fast_card",void 0,t),o=me.randomUUID();f.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await pe(async()=>{let s;try{s=await Yt({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:it(r),userContext:t,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof de)return Ne(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=>Ke(i)),Kr({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 re)return f.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ge(s,r);throw f.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Ky(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 hs("generate_video_tempo_card",e,t);if(n)return n;let r=await Ct("generate_video_tempo_card",void 0,t),o=me.randomUUID();f.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await pe(async()=>{let s;try{s=await Yt({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:it(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof de)return Ne(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=>Ke(i)),Kr({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 re)return f.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ge(s,r);throw f.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Gy(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=me.randomUUID();f.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await pe(async()=>{let o;try{o=await Yt({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:it(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof de)return Ne(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=>Ke(s)),Kr({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 re)return f.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ge(o,n);throw f.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Wy(e,t){let n=await Ct("check_music_status_tempo_card",void 0,t),r=me.randomUUID();f.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await pe(async()=>{let o;try{o=await Yt({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:it(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof de)return Ne(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=>Ke(s)),o})}catch(o){if(o instanceof re)return f.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ge(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 zy(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=me.randomUUID();f.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await pe(async()=>{let o;try{o=await Yt({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:it(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof de)return Ne(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 re)return f.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ge(o,n);throw f.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var Jy=["generate_music_tempo_card"],rd=10,od=5,sd=new Map;function id(e){let t=sd.get(e);if(t!==void 0)return t;let r=Mr(e)?.isAsync===!0||Jy.includes(e);return sd.set(e,r),r}var Yy=36e4,Xy=18e4,Zy=15e3,Qy=12e4,e_=2e3;function ad(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function t_(e,t){return me.createHash("sha256").update(`${e}:${ls(t)}`).digest("hex")}function n_(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,...us(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=>Ke(d)),{deltaCharged:l,deltaMicros:u}}function r_(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($=>$?.success===!1).length,m=t.length-p,g=t.flatMap($=>Array.isArray($?.urls)?$.urls:[]),_=l>0n?Number(l)/1e6:Math.round((c+Number.EPSILON)*100)/100,x=m===0?"failure":p===0?"success":"partial";return f.info("payment:success",{tool:"batch",batchTool:s,count:n.length,totalAmount:a,totalCharged:_,merchant:i,successCount:m,failedCount:p,outcome:x,mode:d,batchId:u}),{success:m>0,outcome:x,batch_id:u,tool:o?r[0]:s,count:n.length,successCount:m,failedCount:p,totalCharged:_,...l>0n?{totalChargedMicros:l.toString(),amountMicros:l.toString(),amount_micros:l.toString()}:{},merchantName:i,results:t,...g.length?{urls:g}:{}}}async function o_(e){let{resolvedItems:t,previews:n,freeTools:r,catalogEntries:o,uniqueTools:s,isHomogeneous:i,primaryTool:a,merchantNames:c,totalAmount:l,timeoutMs:u,batchId:d,userContext:p}=e,m=Math.max(1,Math.ceil(l*100)),g=await I.getBalance();if(!g.success)throw new Error(`Could not read balance: ${g.error||"unknown error"}`);if(g.balanceCents<m)throw new de(g.balanceCents,m);let _=`batch-${d}`,x=`spend up to $${(m/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:$}=await pe(async()=>{let y=await Le("batch_open",m,_,x,p),v=y?.nonce??(await I.getAttestationChallenge()).nonce;f.info("parentless-batch:open-attempt",{batchTool:a,count:t.length,approvedTotalCents:m,attested:!!y});let{batch_parent_id:N}=await I.batchOpen({...y?{attestation:y}:{},nonce:v,approved_total_cents:m,batch_id:d});return{batchParentId:N}});f.info("parentless-batch:opened",{batchTool:a,count:t.length,batchParentId:$});let M=[],S=0,k=0n;try{for(let y=0;y<t.length;y+=1){let v=t[y],N=n[v.resolvedTool],we=r.has(v.resolvedTool);try{let le;if(we)le=await I.shortcut(v.resolvedTool,v.params,u,p,"batch");else{let{data:X,voucherReceiptHeader:$n}=await I.shortcutParentlessBatchItem(v.resolvedTool,{batch_parent_id:$,batch_id:d,batch_index:y,batch_request_hash:t_(v.resolvedTool,v.params),item_ceiling_cents:Math.max(1,it(N)),idempotency_key:Xi(d,y,v.resolvedTool,v.params)},v.params,u,p,"batch");Vr($n),qr(X?.receipt_v2),le=await gd(X,null,Xi(d,y,v.resolvedTool,v.params))}let{deltaCharged:_e,deltaMicros:H}=n_({results:M,batchId:d,index:y,item:v,itemResult:le,preview:N,isFree:we,catalogName:o[v.resolvedTool]?.name});S+=_e,k+=H}catch(le){if(le instanceof de&&M.length===0)return Ne(le);f.warn("payment:batch-item-failed",{tool:v.resolvedTool,index:y,error:le?.message||String(le)}),M.push({success:!1,tool:v.resolvedTool,...us(d,y),error:le?.message||String(le)})}}return r_({results:M,resolvedItems:t,uniqueTools:s,isHomogeneous:i,primaryTool:a,merchantNames:c,totalAmount:l,totalCharged:S,totalChargedMicros:k,batchId:d,mode:"parentless"})}catch(y){if(y instanceof re)return f.warn("payment:declined",{tool:"batch",batchTool:a,count:t.length,totalAmount:l,merchant:c,code:y.code,retryable:y.retryable}),Ge(y,{amount:l,merchantName:c});throw f.error("payment:failure",{tool:"batch",batchTool:a,count:t.length,totalAmount:l,merchant:c,error:y.message}),y}}async function s_(e,t){let n;if(e.requests?.some(y=>y.tool||y.tool_id)&&e.requests)n=e.requests.map(y=>{let v=y.tool||y.tool_id||e.tool;if(!v)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let N=Kt(v,y.tier||e.tier,y.prompt??t),{tool:we,tool_id:le,tier:_e,params:H,...X}=y,$n=H&&typeof H=="object"?{...H,...X}:X;return{resolvedTool:N,params:$n}});else if(e.tool){let y=Kt(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(N=>({resolvedTool:y,params:N}))}else return ad("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return ad("BATCH_EMPTY","Batch requires at least one item.");if(n.length>rd)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${rd} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(id)&&n.length>od)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${od} items. Please use multiple batches for more.`};let i=[...new Set(n.map(y=>y.resolvedTool))],a=i.length===1,c={};for(let y of i)c[y]=await kd(y);let l=new Set(i.filter(y=>c[y]&&Cd(c[y]))),u={};for(let y of i)l.has(y)||(u[y]=await Ct(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let p=[...new Set([...Object.values(u).map(y=>y.merchantName),...i.filter(y=>l.has(y)).map(y=>c[y]?.name??y)])].join(", "),m=a?i[0]:"mixed";f.info("payment:attempt",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:p,heterogeneous:!a});let g=n.some(y=>id(y.resolvedTool)),_=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),x=g?Yy:_?Xy+n.length*Zy:Qy+n.length*e_,$=me.randomUUID(),M=[],S=0,k=0n;return ps(async()=>{let y=!zt();if(Au()&&y&&d>0)try{return await o_({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,uniqueTools:i,isHomogeneous:a,primaryTool:m,merchantNames:p,totalAmount:d,timeoutMs:x,batchId:$,userContext:t})}catch(v){if(v instanceof Ze)f.info("parentless-batch:falling-back-to-session",{batchTool:m,count:n.length,status:v.status,serverErrorCode:v.serverErrorCode});else{if(v instanceof de)return Ne(v);throw v}}if(y&&d>0)try{let v=Math.max(1,Math.ceil(d*100));await pe(()=>zi(I,Le,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:v,capCentsOverride:v}))}catch(v){return v instanceof de?Ne(v):(f.warn("payment:batch-prewarm-failed",{batchTool:m,count:n.length,error:v?.message||String(v)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:v?.message||"Failed to authenticate batch session",tool:m,count:n.length,failedCount:n.length,results:[]})}try{for(let H=0;H<n.length;H+=1){let X=n[H],$n=u[X.resolvedTool];try{let Z=l.has(X.resolvedTool)?await I.shortcut(X.resolvedTool,X.params,x,t,"batch"):await pd({toolId:X.resolvedTool,toolParams:X.params,estimatedAmountCents:it($n),userContext:t,metaTool:"batch",timeoutMs:x,idempotencyKey:Xi($,H,X.resolvedTool,X.params)});if(l.has(X.resolvedTool)&&Z&&typeof Z=="object"&&!Array.isArray(Z)&&Z.merchantName==null&&(Z.merchantName=c[X.resolvedTool]?.name??X.resolvedTool),M.push({success:Z?.success!==!1,tool:X.resolvedTool,...Z,...us($,H,Z)}),Z?.success!==!1){let ar=He(Z?.amountMicros??Z?.amount_micros),ja=typeof Z?.amount=="number"?Z.amount:$n?.amount??0;ar!==null&&ar>0n?k+=ar:k+=BigInt(Math.round(ja*1e6)),S+=ja}Z?.urls&&Z.urls.forEach(ar=>Ke(ar))}catch(Z){if(Z instanceof de&&M.length===0)return Ne(Z);f.warn("payment:batch-item-failed",{tool:X.resolvedTool,index:H,error:Z?.message||String(Z)}),M.push({success:!1,tool:X.resolvedTool,...us($,H),error:Z?.message||String(Z)})}}let v=M.filter(H=>H?.success===!1).length,N=M.length-v,we=M.flatMap(H=>Array.isArray(H?.urls)?H.urls:[]),le=k>0n?Number(k)/1e6:Math.round((S+Number.EPSILON)*100)/100,_e=N===0?"failure":v===0?"success":"partial";return f.info("payment:success",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,totalCharged:le,merchant:p,successCount:N,failedCount:v,outcome:_e,mode:"session",batchId:$}),{success:N>0,outcome:_e,batch_id:$,tool:a?i[0]:m,count:n.length,successCount:N,failedCount:v,totalCharged:le,...k>0n?{totalChargedMicros:k.toString(),amountMicros:k.toString(),amount_micros:k.toString()}:{},merchantName:p,results:M,...we.length?{urls:we}:{}}}catch(v){if(v instanceof re)return f.warn("payment:declined",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:p,code:v.code,retryable:v.retryable}),Ge(v,{amount:d,merchantName:p});throw f.error("payment:failure",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:p,error:v.message}),v}finally{if(y){let v=await rs(I);f.info("batch-session:closed",{budgetId:v.budgetId,closedServerSide:v.closedServerSide})}}})}function i_(){let e=!1,t;try{let r=ms.join(Br.homedir(),".claude","settings.json");if(Be.existsSync(r)){let o=JSON.parse(Be.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";e=Mt(s)}}catch{}let n=_o();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function a_(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=Fy();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=i_(),!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=wy,Array.isArray(t.cards)&&(t.cards=t.cards.map(s=>({...s,displayName:ra(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=zt();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 ra(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 bd(e,t){try{let r=((await I.getStatus(t)).cards||[]).find(o=>o?.id===e);if(r)return ra(r)}catch(n){f.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function c_(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:ra(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 l_(e,t){return await I.getTransactions({limit:e.limit,offset:e.offset},t)}async function u_(e,t){return await I.feedback(e.message,e.transaction_id,t)}async function d_(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Tn("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=ss(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,o=r/100,s=me.randomUUID();f.info("buy_credits:attempt",{amountCents:r});try{return await pe(async()=>{let i=await Le("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 Jt)return Ty();if(i instanceof Qe)return f.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),ky(i);throw f.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function Tn(e,t){return{success:!1,error:t,code:e,message:t}}async function m_(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Tn("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 Tn("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 Tn("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return Tn("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");f.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await pe(async()=>{let n=await Le("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 Jt)return gs(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return Tn("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function p_(e){let t=await Dr({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 f_(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=Mo(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 Nt?"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(Ut).sort()}}}async function g_(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=No(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 Nt?"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(Ut).sort()}}}async function h_(e){let t=await I.getStatus(e),n=t.attestationRequired!==!1,r=st(t),o=se(),s=n?r?o?`${ds()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${ds()} is not available in this process. ${na()}`:"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 y_(e){f.info("biometric:on");let t=await Yo(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?(_d(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function __(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Tn("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 pe(async()=>{let n=await I.getStatus(t),r;if(st(n)&&(r=await Le("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${ds()} 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 _d(),{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 Jt)return gs(n,"biometric_off");throw n}}var cd=3e4,b_=3e5;async function vd(e,t,n="login"){let r=me.randomUUID(),o=`${e}${e.includes("?")?"&":"?"}state=${r}`,s=Ke(o);return!s.opened&&s.blockedReason!=="non_internal_host"&&s.blockedReason!=="invalid_url"?wd(o,s,n):s.opened?{...await Sd(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 wd(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 Sd(e,t,n="login"){let r=Date.now()+b_;for(;Date.now()<r;)try{let s=await fetch(`${fs()}/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 $t(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=Ou(a);if(n!=="enrollment"&&i.sessionToken){await F.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 $t(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 xd(e){let t=me.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=Ke(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?wd(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await Sd(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 v_(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 bd(n,t)}`;try{return await pe(async()=>{let s=await Le(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 Jt)return gs(s,"remove_card");throw s}}async function w_(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 bd(n,t)} as default`;try{return await pe(async()=>{let s=await Le(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 Jt)return gs(s,"set_default_card");throw s}}async function S_(e){return f.info("auth:login_attempt"),vd(`${fs()}/login`,e)}function x_(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 k_(e={},t){let n;try{n=x_(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return ps(async()=>{let r=await pe(()=>Wu(I,Le,{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 C_(){let e=zt();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 T_(){return ps(async()=>{let e=zt();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 rs(I);f.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=_y(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 ${yy(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 E_(e){if(f.info("auth:add_card_attempt"),!await F.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await I.createEnrollCode();return vd(`${fs()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function ld(){if(await F.clearAll(),se())try{await Jo()}catch{}}async function A_(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 ld(),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&&st(r)){let o=await xd(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 ld(),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 R_(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})
|
|
136
136
|
${p.description}
|
|
137
137
|
Provider: ${p.provider} | Price: ${ud(p)}${dd(p)}
|
|
138
138
|
Params: ${Object.keys(p.inputSchema?.properties||p.inputSchema||{}).join(", ")||"none"}`).join(`
|
|
@@ -154,30 +154,30 @@ Use execute_tool with the tool id and required params to run any of these.`}],_t
|
|
|
154
154
|
|
|
155
155
|
${i}
|
|
156
156
|
|
|
157
|
-
Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}catch(o){throw f.error("catalog:discover:error",{error:o.message}),new Error(`Failed to search tool catalog: ${o.message}`)}}function ud(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function dd(e){let t=e.protocol;return t==="mpp"||t==="x402"?" | Paid from your prepaid balance":""}function I_(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function cs(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function $_(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let o=r.properties??{},s=n??e.id;for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(o,a)){let c=Object.keys(o),l=c.length>0?` Expected: ${c.join(", ")}.`:"";return`Unknown parameter "${a}" for ${s}.${l}`}let i=(r.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0);if(i.length>1)return`${i.join(", ")} are required for ${s}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${s}.`;if(t[a]===null)return`${a} cannot be null.`;if(typeof t[a]=="string"&&t[a].trim()==="")return`${a} cannot be empty.`}for(let[a,c]of Object.entries(t)){let l=o[a];if(!(!l||c===void 0||c===null)){if(l.enum&&!l.enum.includes(c))return`${a} must be one of: ${l.enum.map(String).join(", ")}.`;if(cs(l,"integer")){if(typeof c!="number"||!Number.isInteger(c))return`${a} must be an integer.`}else if(cs(l,"number")){if(typeof c!="number"||!Number.isFinite(c))return`${a} must be a number.`}else if(cs(l,"string")){if(typeof c!="string")return`${a} must be a string.`;if(c.trim()==="")return`${a} cannot be empty.`;if(l.minLength!==void 0&&c.length<l.minLength)return`${a} is too short.`;if(l.maxLength!==void 0&&c.length>l.maxLength)return`${a} is too long.`}else if(cs(l,"boolean")&&typeof c!="boolean")return`${a} must be a boolean.`;if(typeof c=="number"){if(l.minimum!==void 0&&c<l.minimum)return`${a} must be at least ${l.minimum}.`;if(l.maximum!==void 0&&c>l.maximum)return`${a} must be at most ${l.maximum}.`}}}return null}async function kd(e){let t=Mr(e);if(t)return t;try{return await I.catalogTool(e)}catch(n){return f.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}function Cd(e){let t=e.priceCents,n=e.pricing;return e.executionMode==="free_authenticated"||e.accessMode==="free"||n?.free===!0||t===0||n?.amount===0}async function P_(e,t,n="execute_tool"){let{tool_id:r,params:o,...s}=e,i=o||s;if(!r)return as("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");f.info("catalog:execute",{tool:r,metaTool:n});let a=await kd(r);if(!a)return as(`Unknown tool: '${r}'
|
|
157
|
+
Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}catch(o){throw f.error("catalog:discover:error",{error:o.message}),new Error(`Failed to search tool catalog: ${o.message}`)}}function ud(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function dd(e){let t=e.protocol;return t==="mpp"||t==="x402"?" | Paid from your prepaid balance":""}function I_(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function cs(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function $_(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let o=r.properties??{},s=n??e.id;for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(o,a)){let c=Object.keys(o),l=c.length>0?` Expected: ${c.join(", ")}.`:"";return`Unknown parameter "${a}" for ${s}.${l}`}let i=(r.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0);if(i.length>1)return`${i.join(", ")} are required for ${s}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${s}.`;if(t[a]===null)return`${a} cannot be null.`;if(typeof t[a]=="string"&&t[a].trim()==="")return`${a} cannot be empty.`}for(let[a,c]of Object.entries(t)){let l=o[a];if(!(!l||c===void 0||c===null)){if(l.enum&&!l.enum.includes(c))return`${a} must be one of: ${l.enum.map(String).join(", ")}.`;if(cs(l,"integer")){if(typeof c!="number"||!Number.isInteger(c))return`${a} must be an integer.`}else if(cs(l,"number")){if(typeof c!="number"||!Number.isFinite(c))return`${a} must be a number.`}else if(cs(l,"string")){if(typeof c!="string")return`${a} must be a string.`;if(c.trim()==="")return`${a} cannot be empty.`;if(l.minLength!==void 0&&c.length<l.minLength)return`${a} is too short.`;if(l.maxLength!==void 0&&c.length>l.maxLength)return`${a} is too long.`}else if(cs(l,"boolean")&&typeof c!="boolean")return`${a} must be a boolean.`;if(typeof c=="number"){if(l.minimum!==void 0&&c<l.minimum)return`${a} must be at least ${l.minimum}.`;if(l.maximum!==void 0&&c>l.maximum)return`${a} must be at most ${l.maximum}.`}}}return null}async function kd(e){let t=Mr(e);if(t)return t;try{return await I.catalogTool(e)}catch(n){return f.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}function Cd(e){let t=e.priceCents,n=e.pricing;return e.executionMode==="free_authenticated"||e.accessMode==="free"||n?.free===!0||t===0||n?.amount===0}function P_(e){return e.split(/[-_]/).filter(t=>t.length>0&&!/^[0-9a-f]{8,}$/i.test(t)).join(" ").trim()}async function O_(e){let t=P_(e);if(!t)return[];try{return((await I.catalogSearch(t,void 0)).tools||[]).filter(r=>r.id!==e).slice(0,3).map(r=>({tool_id:r.id,name:r.name}))}catch(n){return f.warn("catalog:suggest:error",{tool:e,error:n?.message||String(n)}),[]}}async function M_(e,t,n="execute_tool"){let{tool_id:r,params:o,...s}=e,i=o||s;if(!r)return as("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");f.info("catalog:execute",{tool:r,metaTool:n});let a=await kd(r);if(!a){let m=await O_(r),g=m.length?` Did you mean: ${m.map(_=>_.tool_id).join(", ")}?`:"";return as(`Unknown tool: '${r}'.${g} Use discover_tools first to find available tools.`,"UNKNOWN_TOOL",m.length?{suggestions:m}:void 0)}if(a.deprecated){let m=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return as(`Tool '${r}' is deprecated and is no longer available for new paid calls.${m}`,"DEPRECATED_TOOL")}let l=$_(a,i,n&&n!=="execute_tool"?n:void 0);if(l)return f.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:l}),as(l);let u=await hs(r,i,t,n);if(u)return u;if(Cd(a)){f.info("catalog:execute:free",{tool:r,metaTool:n});let m=await I.shortcut(r,i,6e4,t,n);return m&&typeof m=="object"&&!Array.isArray(m)&&m.merchantName==null&&(m.merchantName=a.name??r),m}let d=await Ct(r,void 0,t),p=me.randomUUID();f.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await pe(async()=>{let m;try{m=await Yt({toolId:r,toolParams:i,estimatedAmountCents:it(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:p})}catch(g){if(g instanceof de)return Ne(g);throw g}if(f.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),m&&typeof m=="object"&&!Array.isArray(m)&&m.merchantName==null&&(m.merchantName=a?.name??r),m.urls?.length){m.urls.forEach(_=>Ke(_));let g=I_(m.urls[0],m.mediaType);Kr({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:m.urls[0],mediaType:g,cost:m.amount??d.amount,transactionId:m.transactionId,userContext:t})}return m})}catch(m){return m instanceof re?(f.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:m.code,retryable:m.retryable}),Ge(m,d)):(N_(m?.message)?f.warn("payment:ambiguous",{tool:r,amount:d.amount,merchant:d.merchantName,error:m.message,note:"Polling/timeout error on async tool \u2014 call may have succeeded. Verify via `visa-cli transactions list`."}):f.error("payment:failure",{tool:r,amount:d.amount,merchant:d.merchantName,error:m.message}),by({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:m?.message||"Tool execution failed."}))}}function N_(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}var Ve=class{static async getStatus(t){return a_(t)}static async getVisaSmi(t,n){return qy(t,n)}static async getCards(t){return c_(t)}static async transactionHistory(t,n){return l_(t||{},n)}static async feedback(t,n){return u_(t,n)}static async updateSpendingControls(t,n){return m_(t,n)}static async configList(t){return p_(t||{})}static async configSet(t){return f_(t||{})}static async configUnset(t){return g_(t||{})}static async biometricStatus(t){return h_(t)}static async biometricOn(t){return y_(t)}static async biometricOff(t,n){return __(t,n)}static async reset(t,n){return A_(t,n)}static async login(t){return S_(t)}static async closeSession(t){return T_()}static async startSession(t,n){return k_(t||{},n)}static async getSessionStatus(t){return C_()}static async addCard(t){return E_(t)}static async removeCard(t,n){return v_(t,n)}static async setDefaultCard(t,n){return w_(t,n)}static async buyCredits(t,n){return d_(t,n)}static async batch(t,n){return s_(t,n)}static async discoverTools(t){return R_(t)}static async executeTool(t,n,r="execute_tool"){return M_(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return Hy(n,r);case"generate_image_fast_card":return By(n,r);case"generate_video_tempo_card":return Ky(n,r);case"generate_music_tempo_card":return Gy(n,r);case"check_music_status_tempo_card":return Wy(n,r);case"query_onchain_prices_card":return zy(n,r);default:{let o=await Ct(t,void 0,r);f.info("payment:attempt",{tool:t});try{let s=await Yt({toolId:t,toolParams:n,estimatedAmountCents:it(o),userContext:r,timeoutMs:6e4});return f.info("payment:success",{tool:t,mode:"session"}),s.urls?.length&&s.urls.forEach(i=>Ke(i)),s}catch(s){if(s instanceof de)return Ne(s);if(s instanceof re)return f.warn("payment:declined",{tool:t,code:s.code,retryable:s.retryable}),Ge(s,o);throw f.error("payment:failure",{tool:t,error:s.message}),s}}}}static async submitFeedback(t,n,r){f.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let o=await I.submitFeedback(t,n,r);return f.info("feedback:submitted",{transactionId:n}),o}catch(o){let s=o instanceof Error?o.message:"Unknown error";throw f.error("feedback:error",{error:s,transactionId:n}),o}}static async getFeedback(t,n){f.info("feedback:list",{limit:t||20});try{let r=await I.getFeedback(t,n);return f.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let o=r instanceof Error?r.message:"Unknown error";throw f.error("feedback:error",{error:o}),r}}};function Td(e,t=process.stderr){if(et()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: visa-cli update`;return t.write(`
|
|
158
158
|
\x1B[33m\u2191 ${r}\x1B[0m
|
|
159
|
-
`),!0}function Ed(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]=
|
|
159
|
+
`),!0}function Ed(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]=L_(o,n[o]?.description);return r}function L_(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 U_(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 D_=20;function Rd(e,t,n,r){let o=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=K_(e.spendingControls).dailyLimit,a=Math.max(0,Gr(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,Gr(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(V_),p=d.slice(0,3),m=q_(d,3),g=(e.cards??[]).slice(0,3),_=r.latestVersion?En(r.latestVersion):"",x=r.updateCheckDisabled?"update checks disabled":_?`update ready: v${_}`:"up to date",$=Math.round(l*100),M=at(e.status,e.enrolled?"approved":"not enrolled"),k=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${M} | touch id: ${n?"ready":"unavailable"}`,`Version: v${o} | ${x}`,`Top-up meter: ${Ad(l)} ${String($).padStart(3," ")}% | remaining ${tr(c)}/day | daily top-up cap ${tr(i)}`,"","Card top-ups",` Remaining ${tr(c)} / ${tr(i)}`,` Usage ${Ad(l)} ${$}%`,` Top-ups today ${tr(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...g.length>0?g.map(v=>` ${B_(v)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((v,N)=>` ${N+1}. ${v}`):[" No paid services yet"],"","Recent receipts",...p.length>0?p.map(v=>` ${H_(v)}`):[" No receipts yet"]],y=U_(e);return y.length>0&&k.push("",...y),_&&!r.updateCheckDisabled?(k.push("",`Update: v${_} ready \u2014 run \`visa-cli update\``),r.updateMessage&&k.push(` ${En(r.updateMessage)}`)):r.updateMessage&&k.push("",`Update: ${En(r.updateMessage)}`),`${k.join(`
|
|
160
160
|
`)}
|
|
161
|
-
`}function
|
|
162
|
-
`)}var ks=T(jr());function
|
|
163
|
-
`)}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 _=g;if(typeof _.merchant!="string"||typeof _.amount!="number"||typeof _.currency!="string"||typeof _.idem_key!="string"){i(p,-32602,"visa_authorize_payment: missing or wrong-typed required fields");return}try{let{jwt:x,jti:$,expiresAt:M}=
|
|
164
|
-
`)},{type:"text",text:JSON.stringify({visa_payment_id:x,jti:$,agent_id:e.agent_id,amount:_.amount,currency:_.currency.toUpperCase(),merchant:_.merchant,expires_at:M})}]}})}catch(x){i(p,-32603,`failed to sign visa_payment_id: ${x instanceof Error?x.message:String(x)}`)}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"&&
|
|
161
|
+
`}function j_(e){return e.tool_name!=null}function F_(e){return Gr(e.amount)===0&&e.status==="failed"}function V_(e){return j_(e)&&!F_(e)}function q_(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 H_(e){let t=at(e.merchant_name,"Unknown merchant"),n=at(e.tool_name,"unknown_tool"),r=tr(Gr(e.amount)),o=at(e.status,"unknown"),s=G_(e.created_at);return`${r} ${o.padEnd(9)} ${t} [${n}] ${s}`}function B_(e){let t=at(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function K_(e){return{dailyLimit:Gr(e?.daily_limit??e?.dailyLimit??0)}}function Gr(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function tr(e){return`$${e.toFixed(2)}`}function Ad(e,t=D_){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=En(e??"").trim();return n.length>0?n:t}function G_(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 En(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 W_=/^[1-9]\d{0,9}$/;function oa(e){if(!W_.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 Id(e){let t=En(e.brand||"Visa"),n=En(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")),ie=T(require("path")),z_=["npm","pnpm","yarn","bun"],J_=/\s+/,Y_=process.platform==="win32"?"visa-cli.cmd":"visa-cli",sa=["node_modules","@visa","cli"];function X_(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(J_)[0]??"",r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);return z_.includes(o)?o:void 0}function ia(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 Z_(e=process.argv[1]){return X_()??ia(process.env.npm_execpath)??ia(process.env.npm_node_execpath)??ia(e)}function Q_(e=process.env.PATH??""){let t=[];for(let n of e.split(ie.delimiter))n&&t.push(n);return t}function eb(e=process.env.PATH??""){let t=new Set,n=[];for(let r of Q_(e))try{let o=ie.join(r,Y_);ct.accessSync(o,ct.constants.X_OK);let s=ie.resolve(o);t.has(s)||(t.add(s),n.push(o))}catch{}return n}function $d(e){try{let t=ct.readFileSync(ie.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function tb(e){let t=ie.resolve(e).split(ie.sep);for(let n=t.length-sa.length;n>=0;n--)if(sa.every((r,o)=>t[n+o]===r)){let r=t.slice(0,n+sa.length).join(ie.sep)||ie.sep;if($d(r))return r}}function nb(e){if(!e)return;let t=ie.normalize(e),n=t.split(ie.sep),r=s=>s.every((a,c)=>n[n.length-s.length+c]===a)?n.slice(0,-s.length).join(ie.sep)||ie.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 rb(e,t){let n=ie.resolve(e);try{n=ct.realpathSync(e)}catch{}let r=tb(n);return{binPath:e,realPath:n,packageRoot:r,version:r?$d(r):void 0,prefix:nb(r),isActive:n===t}}function ob(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?ie.resolve(n):"";try{n&&(r=ct.realpathSync(n))}catch{}let o=e?[e]:[n,...eb(t)].filter(Boolean),s=new Map;for(let d of o){let p=rb(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 sb(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function aa(e,t,n,r={}){let o=t??Z_(n)??"npm",s=r.withDiagnostics?ob(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 ${sb(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 ib(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 ca(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(ib)];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(`
|
|
162
|
+
`)}var ks=T(jr());function ab(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function Pd(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=ab(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 Od(){await F.deleteSessionToken()}var lt=T(require("crypto")),Ie=T(require("fs")),ys=T(require("os")),nr=T(require("path")),Ld=T(require("node:readline")),la="2.8.2",cb=process.env.PORTER_API_URL??"https://porter-travel.up.railway.app",lb=process.env.TAP_REGISTRY_URL??"https://tap-production-eff9.up.railway.app",Wr=nr.join(ys.homedir(),".visa-cli","agents");function ub(){return!!(process.env.VISA_DEV==="1"||la==="0.0.0"||la.startsWith("0.0.")||/-rc\.|-beta\./.test(la))}function db(){Ie.mkdirSync(Wr,{recursive:!0,mode:448})}function ma(e){return nr.join(Wr,`${e}.json`)}function ua(){return Ie.existsSync(Wr)?Ie.readdirSync(Wr).filter(e=>e.endsWith(".json")).map(e=>nr.join(Wr,e)):[]}function mb(e){let t=ma(e);return Ie.existsSync(t)?JSON.parse(Ie.readFileSync(t,"utf8")):null}function pb(e){db();let t=ma(e.agent_id);Ie.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}async function da(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 Md=da;function fb(){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 Ud(e,t){let n=lt.createPrivateKey({key:t,format:"jwk"});return lt.sign(null,Buffer.from(e,"utf8"),n).toString("base64url")}async function gb(e){let{publicKeyB64url:t,privateJwk:n}=fb(),r=new Date().toISOString(),o=`tap:register:v1:${e.name}:${r}`,s=Ud(o,n),i=await da(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 da(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 Dd(e){let t=await Md(e.porter_url,"GET",`/api/v1/tap/challenge?public_key=${encodeURIComponent(e.public_key_b64url)}`),n=Ud(t.challenge,e.private_key_jwk),r=await Md(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 hb(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 yb=["visa_authorize_payment"],_b={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 bb(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:hb(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 vb(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 Dd(e);return n=m,r=Date.now()+g*1e3,m}function s(p){process.stdout.write(JSON.stringify(p)+`
|
|
163
|
+
`)}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 _=g;if(typeof _.merchant!="string"||typeof _.amount!="number"||typeof _.currency!="string"||typeof _.idem_key!="string"){i(p,-32602,"visa_authorize_payment: missing or wrong-typed required fields");return}try{let{jwt:x,jti:$,expiresAt:M}=bb(e,_);s({jsonrpc:"2.0",id:p,result:{content:[{type:"text",text:["\u2713 Payment authorized \u2014 pass this JWT as visa_payment_id at checkout:","",x,"",` agent: ${e.agent_id}`,` merchant: ${_.merchant}`,` amount: ${_.amount} ${_.currency.toUpperCase()}`,` jti: ${$}`,` expires: ${new Date(M*1e3).toISOString()}`].join(`
|
|
164
|
+
`)},{type:"text",text:JSON.stringify({visa_payment_id:x,jti:$,agent_id:e.agent_id,amount:_.amount,currency:_.currency.toUpperCase(),merchant:_.merchant,expires_at:M})}]}})}catch(x){i(p,-32603,`failed to sign visa_payment_id: ${x instanceof Error?x.message:String(x)}`)}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"&&yb.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),_;try{_=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($){i(p.id,-32e3,`network error talking to porter: ${$ instanceof Error?$.message:String($)}`);return}if(_.status===401&&m===1){n=null;continue}if(!_.ok){let $=await _.text().catch(()=>"");i(p.id,-32e3,`porter returned ${_.status}: ${$.slice(0,400)}`);return}if((_.headers.get("content-type")??"").includes("text/event-stream"))await u(_,p);else{let $=await _.text();if($.trim()){let M=JSON.parse($);l(p,M),s(M)}}return}}function l(p,m){if(p.method!=="tools/list")return;let g=m.result;!g||!Array.isArray(g.tools)||g.tools.some(_=>_.name==="visa_authorize_payment")||g.tools.push(_b)}async function u(p,m){let g=p.body?.getReader();if(!g)return;let _=new TextDecoder,x="";for(;;){let{done:$,value:M}=await g.read();if($)break;x+=_.decode(M,{stream:!0});let S;for(;(S=x.indexOf(`
|
|
165
165
|
|
|
166
166
|
`))>=0;){let k=x.slice(0,S);x=x.slice(S+2);for(let y of k.split(`
|
|
167
|
-
`))if(y.startsWith("data: ")){let v=y.slice(6).trim();if(!v)continue;try{let N=JSON.parse(v);l(m,N),s(N)}catch{}}}}}await o().catch(()=>{});let d=Ld.createInterface({input:process.stdin,terminal:!1});for await(let p of d){let m=p.trim();if(!m)continue;let g;try{g=JSON.parse(m)}catch{continue}c(g)}}function Nd(e){let t=ua();if(t.length===0)throw new Error("No agents registered. Run `visa-cli agent register` first.");if(e){let n=
|
|
167
|
+
`))if(y.startsWith("data: ")){let v=y.slice(6).trim();if(!v)continue;try{let N=JSON.parse(v);l(m,N),s(N)}catch{}}}}}await o().catch(()=>{});let d=Ld.createInterface({input:process.stdin,terminal:!1});for await(let p of d){let m=p.trim();if(!m)continue;let g;try{g=JSON.parse(m)}catch{continue}c(g)}}function Nd(e){let t=ua();if(t.length===0)throw new Error("No agents registered. Run `visa-cli agent register` first.");if(e){let n=mb(e);if(!n)throw new Error(`Agent not found: ${e}`);return n}if(t.length>1){let n=t.map(r=>nr.basename(r,".json")).map(r=>` - ${r}`).join(`
|
|
168
168
|
`);throw new Error(`Multiple agents registered \u2014 pass --agent <id>:
|
|
169
|
-
${n}`)}return JSON.parse(Ie.readFileSync(t[0],"utf8"))}function jd(e){if(!
|
|
169
|
+
${n}`)}return JSON.parse(Ie.readFileSync(t[0],"utf8"))}function jd(e){if(!ub())return;let t=e.command("agent").description("(dev/rc) Manage agent identities for AI clients. Pre-kernel fallback \u2014 graduates to kernel signing once available.");t.command("register").description("Provision an Ed25519 keypair, publish in the tap-stack registry, and authorize with porter.").option("--porter <url>","Porter merchant URL",cb).option("--registry <url>","TAP registry URL (publishes the JWKS)",lb).option("--name <name>","Human-readable name for this agent",`${process.env.USER??"user"}@${ys.hostname()}`).action(async n=>{try{let r=await gb({registryUrl:n.registry,porterUrl:n.porter,name:n.name}),o=ua().length>1?` --agent ${r.agent_id}`:"";process.stdout.write(["\u2713 Agent registered",` agent_id: ${r.agent_id} (kid for visa_payment_id JWTs)`,` tap registry: ${r.tap_registry_url}`,` porter: ${r.porter_url}`,` tap_account: ${r.tap_account_id} (porter x-tap-token)`,` name: ${r.name}`,` key file: ${ma(r.agent_id)}`,"","Next \u2014 add porter to your AI client (visa-cli will inject the TAP token automatically):","",` claude mcp add porter -- visa-cli agent proxy${o}`,"",'Now ask Claude: "search flights from JFK to CDG on 2026-09-15."',""].join(`
|
|
170
170
|
`))}catch(r){process.stderr.write(`agent register failed: ${r instanceof Error?r.message:String(r)}
|
|
171
171
|
`),process.exit(1)}}),t.command("token").description("Mint a fresh 24h TAP token for the registered agent.").option("--agent <id>","Specific agent_id (required if more than one is registered)").option("--export","Print as `export X_TAP_TOKEN=\u2026` for shell sourcing",!1).action(async n=>{try{let r=Nd(n.agent),{token:o,expiresInSeconds:s}=await Dd(r);n.export?process.stdout.write(`export X_TAP_TOKEN='${o}'
|
|
172
172
|
`):process.stdout.write(`${o}
|
|
173
173
|
`),process.stderr.write(`# expires in ${Math.round(s/3600)}h \xB7 agent ${r.agent_id}
|
|
174
174
|
`)}catch(r){process.stderr.write(`agent token failed: ${r instanceof Error?r.message:String(r)}
|
|
175
|
-
`),process.exit(1)}}),t.command("proxy").description("Run as a stdio MCP server that proxies to porter. Inject X-TAP-Token automatically. Used by AI clients (claude mcp add porter -- visa-cli agent proxy).").option("--agent <id>","Specific agent_id (required if more than one is registered)").action(async n=>{try{let r=Nd(n.agent);await
|
|
175
|
+
`),process.exit(1)}}),t.command("proxy").description("Run as a stdio MCP server that proxies to porter. Inject X-TAP-Token automatically. Used by AI clients (claude mcp add porter -- visa-cli agent proxy).").option("--agent <id>","Specific agent_id (required if more than one is registered)").action(async n=>{try{let r=Nd(n.agent);await vb(r)}catch(r){process.stderr.write(`agent proxy failed: ${r instanceof Error?r.message:String(r)}
|
|
176
176
|
`),process.exit(1)}}),t.command("list").description("List registered agents.").action(()=>{let n=ua();if(n.length===0){process.stdout.write("No agents registered. Run `visa-cli agent register` to add one.\n");return}for(let r of n){let o=JSON.parse(Ie.readFileSync(r,"utf8"));process.stdout.write(`${o.agent_id} ${o.porter_url} ${o.name}
|
|
177
|
-
`)}})}var
|
|
178
|
-
`)}function
|
|
179
|
-
`).find(Boolean),s=o?` (${o})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${s}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${s}.`}function zr(){return process.env.APPDATA||U.join(te,"AppData","Roaming")}function
|
|
180
|
-
`),r=ya(n,t);if(!r)return;let o={};for(let s=r.start+1;s<r.end;s++){let i=n[s].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(o[i[1]]=
|
|
177
|
+
`)}})}var wb=["get_status","add_card","pay","get_visa_smi","get_cards","remove_card","set_default_card","buy_credits","transaction_history","update_spending_controls","config_list","config_set","config_unset","biometric_status","biometric_on","biometric_off","reset","login","start_session","close_session","get_session_status","set_session_mode","generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card","feedback","suggest_meme_templates","batch","discover_tools","execute_tool"];function Sb(){let e=new Set;for(let t of wb)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of Ur)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var Cx=Sb();var pa=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"]);var Ix=new Set(Ur),$x=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...pa,...Ur]);var V=T(require("fs")),U=T(require("path")),Fd=T(require("os")),te=Fd.homedir(),xb=["Claude_","Anthropic.ClaudeDesktop_"],rr=class extends Error{constructor(n,r,o){super(Cb(n,r,o));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function Vd(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
|
|
178
|
+
`)}function kb(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Vd(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function Cb(e,t,n){let r=t.replace(te,"~"),o=Vd(n).split(`
|
|
179
|
+
`).find(Boolean),s=o?` (${o})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${s}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${s}.`}function zr(){return process.env.APPDATA||U.join(te,"AppData","Roaming")}function Tb(){return process.env.LOCALAPPDATA||U.join(te,"AppData","Local")}function fa(e){return process.platform==="win32"?e.win32:e.posix}function qd(){if(process.platform!=="win32")return;let e=U.join(Tb(),"Packages");if(V.existsSync(e))try{let t=V.readdirSync(e,"utf-8");for(let n of xb){let r=t.filter(o=>o.startsWith(n)).sort()[0];if(r)return U.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function Hd(){if(process.platform==="win32"){let e=qd();return e?U.join(e,"claude_desktop_config.json"):U.join(zr(),"Claude","claude_desktop_config.json")}return U.join(te,"Library","Application Support","Claude","claude_desktop_config.json")}function Bd(){if(process.platform!=="win32")return[U.join(te,"Library","Application Support","Claude")];let e=[U.join(zr(),"Claude")],t=qd();return t&&e.push(t),e}function _s(e){return e.id==="claude-desktop"?Hd():e.globalConfigPath}function Eb(e){return e.id==="claude-desktop"?Bd():e.detectPaths}var We=[{id:"claude",displayName:"Claude Code",globalConfigPath:U.join(te,".claude.json"),configKey:"mcpServers",detectPaths:[U.join(te,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:Hd(),configKey:"mcpServers",detectPaths:Bd(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:U.join(te,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[U.join(te,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:U.join(te,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[U.join(te,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:U.join(te,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[U.join(te,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:fa({win32:U.join(zr(),"Roo","mcp_settings.json"),posix:U.join(te,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[U.join(te,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:U.join(te,".vscode","mcp.json"),configKey:"servers",detectPaths:[U.join(te,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:fa({win32:U.join(zr(),"Zed","settings.json"),posix:U.join(te,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:fa({win32:[U.join(zr(),"Zed")],posix:[U.join(te,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:U.join(te,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[U.join(te,".codex")],postInstallHint:"Restart Codex to connect."}];function ga(e){return We.find(t=>t.id===e)}function Jr(e){return Eb(e).some(t=>{if(t.includes("*")){let n=U.dirname(t),r=U.basename(t).replaceAll("*","");if(!V.existsSync(n))return!1;try{return V.readdirSync(n).some(o=>o.startsWith(r))}catch{return!1}}return V.existsSync(t)})}function Kd(){return{command:"node",args:[U.resolve(__dirname,"mcp-server/index.js")]}}function ha(e,t){return t==="project"?"json":e.configFormat??"json"}function Ab(e){if(e=e.trim(),e==="true")return!0;if(e==="false")return!1;if(e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);if(e.startsWith("[")&&e.endsWith("]")){let n=e.slice(1,-1).trim();return n.length===0?[]:n.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r)}let t=Number(e);return isNaN(t)?e:t}function ya(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(s=>s.trim()===n);if(r===-1)return;let o=r+1;for(;o<e.length&&!e[o].trim().startsWith("[");)o++;return{start:r,end:o}}function _a(e,t){let n=e.split(`
|
|
180
|
+
`),r=ya(n,t);if(!r)return;let o={};for(let s=r.start+1;s<r.end;s++){let i=n[s].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(o[i[1]]=Ab(i[2]))}return Object.keys(o).length>0?o:void 0}function Rb(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,o=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],s=e.split(`
|
|
181
181
|
`),i=ya(s,t);if(i){s.splice(i.start,i.end-i.start,...o);let c=s.join(`
|
|
182
182
|
`);return c.endsWith(`
|
|
183
183
|
`)?c:c+`
|
|
@@ -185,20 +185,20 @@ ${n}`)}return JSON.parse(Ie.readFileSync(t[0],"utf8"))}function jd(e){if(!cb())r
|
|
|
185
185
|
|
|
186
186
|
`:"")+o.join(`
|
|
187
187
|
`)+`
|
|
188
|
-
`}function
|
|
188
|
+
`}function Ib(e,t){let n=e.split(`
|
|
189
189
|
`),r=ya(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
|
|
190
190
|
`).replace(/\n{3,}/g,`
|
|
191
191
|
|
|
192
|
-
`)):e}function Yr(e,t="global"){let n=t==="project"?U.join(process.cwd(),".mcp.json"):_s(e);try{let r=U.dirname(n);V.existsSync(r)||V.mkdirSync(r,{recursive:!0});let o=ha(e,t),s=Kd();if(o==="toml"){let i=V.existsSync(n)?V.readFileSync(n,"utf-8"):"",a=
|
|
193
|
-
`)}}catch(r){throw
|
|
194
|
-
`),{removed:!0,configPath:n})}function Gd(e,t="global"){let n=t==="project"?U.join(process.cwd(),".mcp.json"):_s(e);if(!V.existsSync(n))return!1;if(ha(e,t)==="toml")try{let o=V.readFileSync(n,"utf-8");return!!_a(o,"visa-cli")}catch{return!1}try{return!!JSON.parse(V.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function
|
|
195
|
-
${r}: ${n(e.currentPath)}`}function sm(e,t){if(e.length===0){console.log(`${t} \u2713 All MCP client configs are up to date.`);return}console.log(`${t} Found ${e.length} stale MCP config ${e.length===1?"entry":"entries"}:`);for(let n of e)console.log(
|
|
192
|
+
`)):e}function Yr(e,t="global"){let n=t==="project"?U.join(process.cwd(),".mcp.json"):_s(e);try{let r=U.dirname(n);V.existsSync(r)||V.mkdirSync(r,{recursive:!0});let o=ha(e,t),s=Kd();if(o==="toml"){let i=V.existsSync(n)?V.readFileSync(n,"utf-8"):"",a=Rb(i,"visa-cli",s);V.writeFileSync(n,a)}else{let i={};if(V.existsSync(n))try{i=JSON.parse(V.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(s):s,V.writeFileSync(n,JSON.stringify(i,null,2)+`
|
|
193
|
+
`)}}catch(r){throw kb(r)?new rr(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function ba(e,t="global"){let n=t==="project"?U.join(process.cwd(),".mcp.json"):_s(e);if(!V.existsSync(n))return{removed:!1,configPath:n};if(ha(e,t)==="toml"){let i=V.readFileSync(n,"utf-8");return _a(i,"visa-cli")?(V.writeFileSync(n,Ib(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let o;try{o=JSON.parse(V.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let s=o[e.configKey];return!s||!s["visa-cli"]?{removed:!1,configPath:n}:(delete s["visa-cli"],V.writeFileSync(n,JSON.stringify(o,null,2)+`
|
|
194
|
+
`),{removed:!0,configPath:n})}function Gd(e,t="global"){let n=t==="project"?U.join(process.cwd(),".mcp.json"):_s(e);if(!V.existsSync(n))return!1;if(ha(e,t)==="toml")try{let o=V.readFileSync(n,"utf-8");return!!_a(o,"visa-cli")}catch{return!1}try{return!!JSON.parse(V.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function $b(e){if(!e||typeof e!="object")return;let t=e;if(t.command!=="node"||!Array.isArray(t.args)||t.args.length===0)return;let n=t.args[t.args.length-1];if(!(typeof n!="string"||n.length===0))return n}function Pb(e,t){if(e===t)return!0;let n=U.resolve(e),r=U.resolve(t);if(n===r)return!0;try{let o=V.realpathSync(n),s=V.realpathSync(r);return o===s}catch{return!1}}function Xr(){let e=Kd(),t=e.args[e.args.length-1],n=[];for(let r of We){let o=_s(r);if(!V.existsSync(o))continue;let s=r.configFormat??"json",i;if(s==="toml")try{let l=V.readFileSync(o,"utf-8");i=_a(l,"visa-cli")}catch{continue}else{let l;try{l=JSON.parse(V.readFileSync(o,"utf-8"))}catch{continue}i=l?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=$b(i);if(!a||Pb(a,t))continue;let c=V.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:o,currentPath:a,expectedPath:t,staleReason:c})}return n}function va(e){return{configPath:Yr(e.client,"global").configPath}}var ka=(0,om.promisify)(rm.execFile);function wa(){let e=pt();setImmediate(()=>{ni(e,{getCommand:()=>ko(process.execPath,process.argv[1])})})}process.stdout.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});process.stderr.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});function Lb(e){let t=J.homedir(),n=o=>o.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
|
|
195
|
+
${r}: ${n(e.currentPath)}`}function sm(e,t){if(e.length===0){console.log(`${t} \u2713 All MCP client configs are up to date.`);return}console.log(`${t} Found ${e.length} stale MCP config ${e.length===1?"entry":"entries"}:`);for(let n of e)console.log(Lb(n))}function Wd(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function ze(){this.help({error:!1})}var G=new nm.Command,Ub=new Set(["pay",...pa]),ws=null,Zr=!1;function ae(){return ws=new Ee(()=>F.getSessionToken()),ws}function zd(e){if(e instanceof on)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var Jd=0,Yd="",Db="attestation-key-rotation",jb="api-keys-create",Xd=0,Zd="";async function Fb(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Jd,merchant:Yd,context:Db})).toString("base64");return{signature:await kn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:Jd,merchant:Yd}}async function Vb(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Xd,merchant:Zd,context:jb})).toString("base64");return{signature:await kn(n,"create a Visa Key"),nonce:t,amount:Xd,merchant:Zd}}async function qb(e){let t=await e.getStatus();return t.attestationRequired!==!1||st(t)}async function Hb(e){let t=await xu(),n=await Fb(e);await e.registerAttestationKey(t,n)}async function im(e,t,n=!1){let r=await Wo();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&f.info("attestation:requirement-restored-after-recovery",{surface:"setup"}),console.log(n?" Touch ID requirement re-enabled after biometric recovery.":" Touch ID requirement enabled."))}async function Sa(e){if(!await Ra(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await im(e,!0,!0)}function Aa(e){return async()=>{let t=await Ra(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function Bb(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let o=await globalThis.fetch(`${Te()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!o.ok){await $t(o,i=>{f.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:i})});continue}let s=await o.json();if(s.status==="pending")continue;if(s.status==="complete"&&s.attestationCleared)return;if(s.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(s.status==="error")throw new Error(s.error||"Biometric reset failed. Please try again.")}catch(o){if(o?.message&&!/fetch failed|network|abort/i.test(o.message))throw o;await $t(void 0,s=>{f.warn("auth_status:retry_after_network_error",{delayMs:s})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function Ra(e){let t;try{t=await e.getStatus()}catch(o){let s=o?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(s))return!1;throw new Error(`Could not check server biometric state: ${s||"unknown error"}`)}if(!st(t))return!1;let n=xs.randomUUID(),r=await e.startAttestationRecovery(n);if(!r.success||!r.recoveryUrl)throw new Error(r.error||"Could not start biometric reset.");return console.log(" Server biometric key found. Opening GitHub to confirm reset..."),await Gs(r.recoveryUrl),await Bb(n),console.log(" Server biometric state cleared."),!0}function or(e){return`$${(e/100).toFixed(2)}`}function am(e){return typeof e=="number"?or(e):"no cap"}function Ca(e,t,n=!1){if(!e){let i=or(t);return n&&t>=0?`+${i}`:i}let r=(0,ks.fromWire)(e),o=r%10000n===0n?2:6,s=(0,ks.toDisplay)(r,{decimals:o});return n&&r>=0n?`+${s}`:s}function Kb(e){return Ca(e,0)}function Gb(e){let t=`visa-cli-${J.hostname()||"local"}`,n=(e?.trim()||t).trim();if(!n)throw new Error("Visa Key label is required.");if(n.length>128)throw new Error("Visa Key label must be 128 characters or fewer.");return n}function Wb(e){if(!e)return;let t=e.split(",").map(s=>s.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(s=>s.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let o=n.find(s=>Ub.has(s));if(o)throw new Error(`Tool id "${o}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}function Qd(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 em(e){if(e===!1)return null;if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--total-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e6)throw new Error("--total-cap must be between 1 and 10000 USD.");return n}var Ta=!1;async function cm(e){let t=(0,Ea.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function zb(e,t=!1){let n=Qd(e);if(n!==void 0||t||!process.stdin.isTTY)return n;if(await ai("Use recommended Visa Key caps ($5/day and $25 total)? Without caps, leaked keys can spend from prepaid balance until revoked.",!0))return Ta=!0,500;let o=await cm("Daily cap USD (1-100): ");if(!o)throw new Error("--daily-cap is required when declining the recommended daily cap.");return Qd(o)}async function Jb(e,t=!1){let n=em(e);if(n!==void 0||t||!process.stdin.isTTY)return n;if(Ta)return Ta=!1,2500;let r=await cm("Cumulative cap USD (1-10000, default 25): ");return em(r||"25")}function lm(e){return e&&e.length>0?e.join(", "):"all tools"}function um(e,t){if(!e)return{};try{let n=JSON.parse(e);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${t} must be a JSON object.`);return n}catch(n){throw new Error(`${t} must be valid JSON: ${n.message}`)}}function Cs(e,t={}){let n=t.format&&mo(t.format)?t.format:void 0;if(t.json||n!==void 0){let i=t.command??"tool.run",a=n??"json",c,l=e?.content?.[0]?.text;typeof l=="string"&&(c=l);let u=Array.isArray(e?.urls)&&typeof e.urls[0]=="string"?e.urls[0]:void 0;if(!c&&u&&u.startsWith("data:")&&(c=u),c)try{let d=On(c);if(d){let p=typeof e?.merchantName=="string"?e.merchantName:"media",m=typeof e?.transactionId=="string"?`${p}-${e.transactionId}`:p,g=ur(d,{tag:m}),_=Vs(i,e);_.success&&(_.filePath=g.filePath,_.mime=g.mime,_.bytes=g.bytes,u&&u.startsWith("data:")&&(_.urls=void 0)),fr(_,a);return}}catch(d){fr(dr(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=mm;return}fr(Vs(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=On(e.content[0].text);if(i){let a=typeof e?.merchantName=="string"?e.merchantName:"media",c=typeof e?.transactionId=="string"?`${a}-${e.transactionId}`:a,l=ur(i,{tag:c});console.log("Saved inline image to file:"),console.log(` ${l.filePath}`),console.log(` (${l.mime}, ${(l.bytes/1024).toFixed(1)} KB)`),console.log(` Open with: open "${l.filePath}"`);return}}catch(i){console.error(`(warning: could not save inline image to disk: ${i instanceof Error?i.message:String(i)})`)}console.log(e.content[0].text);return}let o=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];if(e?.success===!1){let i=JSON.stringify(e,null,2);console.log("Result:"),console.log(i);return}if(console.log("Done"),typeof e?.merchantName=="string"&&console.log(`Merchant: ${e.merchantName}`),typeof e?.amount=="number"&&console.log(`Cost: $${e.amount.toFixed(2)}`),typeof e?.transactionId=="string"&&console.log(`Transaction: ${e.transactionId}`),o.length>0){console.log(`
|
|
196
196
|
Result URLs:`);for(let i of o)console.log(` ${i}`);return}let s=JSON.stringify(e,null,2);s&&s!=="{}"&&(console.log(`
|
|
197
|
-
Result:`),console.log(s))}var
|
|
197
|
+
Result:`),console.log(s))}var Yb=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),dm=0,mm=1,Xb=2;function Zb(e){if(e?.success!==!1)return dm;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return Yb.has(n)?Xb:mm}function Ts(e){let t=Zb(e);t!==dm&&(process.exitCode=t)}function sr(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,o=t instanceof Error?t.message:String(t),s=r.format&&mo(r.format)?r.format:void 0;if(r.json||s!==void 0){let i=s??"json";fr(dr(e,o),i)}else console.error("Error:",o);process.exit(1)}async function Qb(e,t={}){let n=await e.catalogSearch(t.query,t.category,"discover_tools",{limit:t.limit,offset:t.offset});return Array.isArray(n.tools)?n.tools:[]}var Ia=100,$a=200;function Ss(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function ev(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,$a)):Ia,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function tv(e){let t=`
|
|
198
198
|
Options:
|
|
199
199
|
`,n=`
|
|
200
200
|
Commands:
|
|
201
|
-
`,r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1||r>o)return e;let s=p=>{let g=e.slice(p+1).search(/\n[A-Z][A-Za-z ]+:\n/);return g===-1?e.length:p+1+g},i=s(r),a=s(o),c=e.slice(0,r),l=e.slice(r,i),u=e.slice(o,a),d=e.slice(a);return`${c}${u}${l}${d}`}function
|
|
201
|
+
`,r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1||r>o)return e;let s=p=>{let g=e.slice(p+1).search(/\n[A-Z][A-Za-z ]+:\n/);return g===-1?e.length:p+1+g},i=s(r),a=s(o),c=e.slice(0,r),l=e.slice(r,i),u=e.slice(o,a),d=e.slice(a);return`${c}${u}${l}${d}`}function nv(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
|
|
202
202
|
|
|
203
203
|
`);if(t===-1)return e;let n=e.slice(0,t),r=e.slice(t+2),o=r.indexOf(`
|
|
204
204
|
|
|
@@ -206,13 +206,13 @@ Commands:
|
|
|
206
206
|
|
|
207
207
|
${n}
|
|
208
208
|
|
|
209
|
-
${i}`:e}function
|
|
210
|
-
`).map(
|
|
211
|
-
`);return`${n}${r}${s}`})}function
|
|
209
|
+
${i}`:e}function rv(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,o)=>{let s=o.split(`
|
|
210
|
+
`).map(ov).join(`
|
|
211
|
+
`);return`${n}${r}${s}`})}function ov(e){if(!e.startsWith(" "))return e;let n=2,r=n;for(;r<e.length&&e[r]!==" "&&e[r]!==" ";)r+=1;if(r===n)return e;let o=-1;for(let c=r;c<e.length-1;c+=1){if(e[c]!==" "||e[c+1]!==" ")continue;let l=c+2;for(;l<e.length&&e[l]===" ";)l+=1;if(l<e.length){o=l;break}}if(o===-1)return e;let s=e.slice(n,r),i=e.slice(o),a=Math.max(2,o-2-s.length);return` ${s}${" ".repeat(a)}${i}`}function sv(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function iv(e){return e.replace(/^Options:$/gm,"Flags:")}function pm(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>iv(sv(rv(tv(nv(t())))));for(let n of e.commands)pm(n)}function av(e){let t=new Map(e.map((r,o)=>[r,o]));G.commands.sort((r,o)=>{let s=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(o.name())??Number.MAX_SAFE_INTEGER;return s-i})}G.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(lr().version).addHelpCommand(!1).action(ze);G.hook("preAction",async()=>{await tc()});G.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking for unattended setup").option("--hud","Install the Visa HUD during setup without prompting").option("--no-hud","Skip installing the Visa HUD during setup").action(async e=>{let t=!1,n=()=>{t||(t=!0,console.log(`
|
|
212
212
|
|
|
213
213
|
Setup interrupted.`),console.log(" If you signed in via the browser but did not finish card enrollment, the"),console.log(" server-side enrollment may have expired. Re-run `visa-cli setup` \u2014 it will"),console.log(" resume from your current state or restart cleanly."),console.log(""),process.exit(130))};process.on("SIGINT",n);let r=()=>{process.removeListener("SIGINT",n)};try{if(e.check){let S=Xr();sm(S,"MCP config check:"),S.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),r(),process.exit(1)),r();return}console.log("Step 1: Registering MCP server...");let o=Xr(),s=new Map(o.map(S=>[S.client.id,S])),i=new Set,a=new Set,c=new Set;for(let S of We)if(Jr(S)){let k;try{k=Yr(S)}catch(N){if(N instanceof rr){Wd(N),a.add(S.displayName),c.add(S.id);continue}throw N}let y=s.get(S.id),v=y?` \u2014 repaired stale ${y.staleReason} entry`:"";console.log(` \u2713 ${S.displayName} (${k.configPath.replace(J.homedir(),"~")})${v}`),y&&i.add(S.id)}let l=o.filter(S=>!i.has(S.client.id)&&!c.has(S.client.id)),u=0;for(let S of l){try{va(S)}catch(k){if(k instanceof rr){Wd(k),a.add(S.client.displayName),c.add(S.client.id);continue}throw k}console.log(` \u2713 ${S.client.displayName} (${S.configPath.replace(J.homedir(),"~")}) \u2014 repaired stale ${S.staleReason} entry`),u++}let d=i.size+u;d===0&&a.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):d>0&&console.log(` \u2713 Repaired ${d} stale MCP config ${d===1?"entry":"entries"}.`),a.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(a).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
|
|
214
214
|
Step 2: Checking authentication...`);let p=await F.getSessionToken();if(p)try{await new Ee(()=>Promise.resolve(p)).getStatus(),console.log(" Already authenticated.")}catch(S){let k=S instanceof Error?S.message:"";k.includes("session has expired")||k.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await Od(),p=null):console.log(` Couldn't verify session (${k||"unknown error"}) \u2014 continuing with existing token.`)}if(!p){let S=null;try{let{stdout:k}=await ka("gh",["auth","token"],{timeout:5e3});S=k.trim()}catch{}if(S||(S=process.env.GITHUB_TOKEN||null),S)try{console.log(" Found GitHub token \u2014 attempting headless login...");let k=await globalThis.fetch(`${Te()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:S}),signal:AbortSignal.timeout(1e4)});if(k.ok){let y=await k.json();if(y.success&&y.sessionToken){let v=y.sessionToken;p=v,await F.saveSessionToken(v),console.log(` Signed in as ${y.user} (headless).`)}}else(await k.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser to finish onboarding...")}catch{}}if(p||(console.log(" No session found. Opening browser for GitHub login..."),p=await new Promise(async(S,k)=>{let y=xs.randomUUID(),v=`${Te()}/login?state=${y}`;await Gs(v);let N=3e4,we=300*1e3,le=Date.now()+we;for(;Date.now()<le;)try{let _e=await globalThis.fetch(`${Te()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:y,timeout:N}),signal:AbortSignal.timeout(N+5e3)});if(!_e.ok){await $t(_e,X=>{f.warn("auth_status:retry_after_http_error",{status:_e.status,delayMs:X})});continue}let H=await _e.json();if(H.status==="pending")continue;if(H.status==="expired"){k(new Error("Session expired. Please run setup again."));return}if(H.status==="complete"&&H.sessionToken){console.log(` Signed in as ${H.user}.`),S(H.sessionToken);return}}catch{await $t(void 0,_e=>{f.warn("auth_status:retry_after_network_error",{delayMs:_e})})}k(new Error("Login timed out after 5 minutes. Please run setup again."))}),await F.saveSessionToken(p),console.log(" Session token saved.")),console.log(`
|
|
215
|
-
Step 3: Setting up authentication...`),se()){try{await ka("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}let S=ae();try{let k=await S.getStatus(),y=!0;if(st(k))if(await zo())try{await
|
|
215
|
+
Step 3: Setting up authentication...`),se()){try{await ka("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}let S=ae();try{let k=await S.getStatus(),y=!0;if(st(k))if(await zo())try{await Hb(S),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),y=!1}catch(v){if(!zd(v))throw v;console.log(" Existing local Touch ID key does not match server biometric state."),await Sa(S),y=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await Sa(S),y=!1;y&&await im(S,k.attestationRequired===!1)}catch(k){let y=k?.message||"unknown error";if(zd(k)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let v=!1;try{await Sa(S),v=!0}catch(N){console.error(` Biometric recovery failed: ${N?.message||"unknown error"}`)}if(!v){let N=k instanceof on&&k.hint?k.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${N}`),process.exit(1)}}else console.error(` Biometric setup failed: ${y}`),process.exit(1)}}else{let S=ae(),k;try{k=await S.getStatus()}catch(v){console.error(" Biometric attestation (Touch ID or Windows Hello) is unavailable in this process."),console.error(` Could not verify server biometric policy: ${v?.message||"unknown error"}`),console.error(" Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC) before using payment commands."),process.exit(1)}let y=Pd(k);y.canContinue||(console.error(` ${y.message}`),y.hint&&console.error(` ${y.hint}`),process.exit(1)),console.log(` ${y.message}`)}let m=pt(),g=Y.existsSync(Ue.join(J.homedir(),".claude.json")),_=e.hud===!0;if(e.hud===void 0&&g&&!e.yes&&process.stdin.isTTY&&(console.log(`
|
|
216
216
|
Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(al()),_=await ai(" Install the Visa HUD now?",!1)),_)if(!g)console.log(`
|
|
217
217
|
Step 4: HUD requested, but Claude Code config was not detected.`),console.log(" Skipped. Enable later with: visa-cli config hud enable");else{console.log(`
|
|
218
218
|
Step 4: Enabling the Visa spend HUD...`);let S=wr(m),k=S.installed==="new"||S.installed==="already-visa"||S.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${k}${S.message}`);try{let y=ae(),v=await y.getStatus(),N={currentVersion:y.getClientVersion(),latestVersion:y.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:et()},we=Xs(v,N);Zs(we,v),console.log(` Preview: ${we.split(`
|
|
@@ -250,28 +250,28 @@ Repaired ${s.length} stale MCP config ${s.length===1?"entry":"entries"}.`);retur
|
|
|
250
250
|
\x1B[1mSupported MCP Clients\x1B[0m
|
|
251
251
|
`),console.log(` ${"Client".padEnd(18)} ${"Detected".padEnd(10)} ${"Installed".padEnd(11)} Config Path`),console.log(` ${"\u2500".repeat(18)} ${"\u2500".repeat(10)} ${"\u2500".repeat(11)} ${"\u2500".repeat(40)}`);for(let a of We){let c=Jr(a),l=Gd(a),u=c?"Yes":"No",d=l?"Yes":"No",p=a.globalConfigPath.replace(J.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${p}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let s=[],i=[];for(let a of We){if(!Jr(a)){i.push(a.displayName);continue}Yr(a,n),s.push(a.displayName)}s.length>0&&console.log(`Installed for: ${s.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),s.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
|
|
252
252
|
Supported clients: ${We.map(s=>s.id).join(", ")}`),process.exit(1));let r=ga(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${We.map(s=>s.id).join(", ")}`),process.exit(1)),n==="global"&&!Jr(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let o=Yr(r,n);console.log(`Registered visa-cli MCP server in ${o.configPath}`),console.log(o.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Zr=!1;try{let e=ae(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(o=>{if(process.env.VISA_CLI_DEBUG){let s=o instanceof Error?o.message:String(o);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${s}
|
|
253
|
-
`)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:et()};process.stdout.write(Rd(t,Array.isArray(n?.transactions)?n.transactions:[],se(),r)),Zr=!0}catch(e){Zr=!1,console.error("Error:",e.message),process.exit(1)}});function
|
|
253
|
+
`)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:et()};process.stdout.write(Rd(t,Array.isArray(n?.transactions)?n.transactions:[],se(),r)),Zr=!0}catch(e){Zr=!1,console.error("Error:",e.message),process.exit(1)}});function cv(e){let t=e.map(Id),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),o=Math.max(4,...t.map(i=>i.card.length)),s=7;console.log(`
|
|
254
254
|
Cards
|
|
255
255
|
`),console.log(` ${"ID".padEnd(n)} ${"Brand".padEnd(r)} ${"Card".padEnd(o)} Default`),console.log(` ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(o)} ${"\u2500".repeat(s)}`);for(let i of t)console.log(` ${i.id.padEnd(n)} ${i.brand.padEnd(r)} ${i.card.padEnd(o)} ${i.default}`);console.log(`
|
|
256
256
|
Use:`),console.log(" visa-cli cards default <id>"),console.log(` visa-cli cards remove <id>
|
|
257
|
-
`)}async function fm(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,Ea.createInterface)({input:process.stdin,output:process.stdout});try{let r=(await n.question(`${e} [y/N] `)).trim();return/^y(es)?$/i.test(r)?"confirmed":"declined"}finally{n.close()}}var Es=G.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(ze);Es.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await Ve.getCards("visa-cli cards list"),t=Array.isArray(e.cards)?e.cards:[];if(t.length===0){console.log(e.message||"No cards enrolled. Add one with: visa-cli cards add");return}
|
|
258
|
-
`),e.localOnly)console.log(" Local-only reset: skipping server logout and biometric recovery.");else{let t=ae();await Ra(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}}await
|
|
257
|
+
`)}async function fm(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,Ea.createInterface)({input:process.stdin,output:process.stdout});try{let r=(await n.question(`${e} [y/N] `)).trim();return/^y(es)?$/i.test(r)?"confirmed":"declined"}finally{n.close()}}var Es=G.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(ze);Es.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await Ve.getCards("visa-cli cards list"),t=Array.isArray(e.cards)?e.cards:[];if(t.length===0){console.log(e.message||"No cards enrolled. Add one with: visa-cli cards add");return}cv(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});Es.command("add").description("Add a new Visa card").action(async()=>{try{let e=await Ve.addCard("visa-cli cards add");if(e?.message){console.log(e.message);return}let t=e?.card?.last4;console.log(t?`Card ending in ****${t} enrolled.`:"Card enrollment complete.")}catch(e){console.error("Error:",e.message),process.exit(1)}});Es.command("remove <card-id>").alias("rm").description("Remove an enrolled card").option("-y, --yes","Skip the interactive confirmation prompt").action(async(e,t)=>{try{let n=oa(e),r=await fm(`Remove card ${n}? This cannot be undone.`,t);if(r==="refused-non-tty"&&(console.error("Refusing to remove card without --yes in a non-interactive shell."),process.exit(1)),r==="declined"){console.log("Aborted.");return}let o=await Ve.removeCard({cardId:n,confirm:!0},"visa-cli cards remove");o?.success===!1&&(console.error(o.error||o.message||"Failed to remove card."),process.exit(1)),console.log(o?.message||`Removed card ${n}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});Es.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=oa(e),n=await Ve.setDefaultCard({cardId:t},"visa-cli cards default");n?.success===!1&&(console.error(n.error||n.message||"Failed to set default card."),process.exit(1)),console.log(n?.message||`Set card ${t} as default.`)}catch(t){console.error("Error:",t.message),process.exit(1)}});function Pa(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),t.includes("Not logged in")&&(console.error(""),console.error("Hint: if `visa-cli status` or `visa-cli setup` says you are authenticated, this process may not have access to your macOS Keychain."),console.error("In sandboxed agents such as Codex, rerun the keys command with keychain access or run it from a normal terminal.")),process.exit(1)}function lv(e){let t=e instanceof Error?e.message:String(e);return t.includes("EMPLOYEE_ONLY_FEATURE")||t.includes("Visa Key management is limited to approved rollout users")}async function Oa(e){let t=Object.prototype.hasOwnProperty.call(process.env,"VISA_CLI_API_KEY"),n=process.env.VISA_CLI_API_KEY;delete process.env.VISA_CLI_API_KEY;try{return await e()}finally{t&&(process.env.VISA_CLI_API_KEY=n)}}var Ma=G.command("keys").description("Create and manage Visa Keys for apps and agents").addHelpCommand(!1).action(ze);Ma.command("create [label]").description("Create a Visa Key for the authenticated approved user").option("--tools <ids>","Comma-separated allowed tool ids (default: all tools)").option("--daily-cap <usd>","Daily cap in USD, between 1 and 100").option("--total-cap <usd>","Cumulative cap in USD, between 1 and 10000").option("--no-total-cap","Create without a cumulative cap (higher risk; daily cap still applies)").option("--json","Output raw JSON").action(async(e,t)=>{try{let n=await zb(t.dailyCap,t.json),r=await Jb(t.totalCap,t.json),o=await Oa(async()=>{let s=ae(),i={label:Gb(e),allowed_tools:Wb(t.tools),daily_cap_cents:n,total_cap_cents:r};return await qb(s)?await Xn(s,async()=>{let a=await Vb(s);return s.createAppApiKey({...i,attestation:a})},Aa(s)):await s.createAppApiKey(i)});if(t.json){console.log(JSON.stringify(o,null,2));return}console.log("Visa Key created."),console.log(""),console.log(`Key: ${o.key}`),console.log(`Label: ${o.label}`),console.log(`Owner: ${o.owner}`),console.log(`Allowed tools: ${lm(o.allowed_tools)}`),console.log(`Daily cap: ${or(o.daily_cap_cents)}/day`),console.log(`Total cap: ${am(o.total_cap_cents)}`),console.log(""),console.log("Store this key now. It will not be shown again."),console.log(""),o.biometric_enabled?(console.log("---------------------------------------------------------------"),console.log("Biometric (Touch ID) is currently ON for this account."),console.log("This Visa Key can still be used headlessly. Per-call Touch ID is"),console.log("not required; spending is bounded by the key daily cap and tools."),console.log("---------------------------------------------------------------"),console.log("")):o.biometric_warning&&(console.log("Note: Visa Keys bypass per-call biometric verification."),console.log("Keep daily caps and allowed tools scoped for headless use."),console.log("")),console.log("Direct execution flow:"),console.log(" idem=$(uuidgen | tr '[:upper:]' '[:lower:]') # reuse on retry"),console.log(` curl -X POST ${Te()}/v1/api/tools/or-gpt-4o-mini/execute \\`),console.log(` -H "X-Api-Key: ${o.key}" \\`),console.log(' -H "Idempotency-Key: $idem" \\'),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"input":{"messages":[{"role":"user","content":"Say hello in one sentence."}]}}'`),console.log(""),console.log("This key spends from your prepaid balance directly. Account/key caps"),console.log("enforce limits; there is no public session to open, track, or close.")}catch(n){Pa(n)}});Ma.command("list").description("List Visa Keys for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await Oa(async()=>await ae().listAppApiKeys());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.keys||[];if(n.length===0){console.log("No Visa Keys found. Create one with: visa-cli keys create");return}console.log("Visa Keys"),console.log("");for(let r of n)console.log(`${r.id}. ${r.label} (${r.key_prefix})`),console.log(` Status: ${r.status}`),console.log(` Owner: ${r.owner}`),console.log(` Allowed tools: ${lm(r.allowed_tools)}`),console.log(` Daily cap: ${or(r.daily_cap_cents)}/day`),console.log(` Total cap: ${am(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){Pa(t)}});Ma.command("revoke <id>").alias("delete").description("Revoke (or delete) a Visa Key by id").action(async e=>{try{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("Visa Key id must be a positive integer. Run `visa-cli keys list` first.");let n=await Oa(async()=>await ae().revokeAppApiKey(t));console.log(`Revoked Visa Key ${n.revoked}.`)}catch(t){Pa(t)}});async function uv(){if(await F.clearAll(),console.log(" Keychain credentials cleared."),se())try{await Jo(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}}async function gm(e={}){try{if(console.log(`Resetting Visa CLI...
|
|
258
|
+
`),e.localOnly)console.log(" Local-only reset: skipping server logout and biometric recovery.");else{let t=ae();await Ra(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}}await uv(),console.log(`
|
|
259
259
|
Reset complete.`),e.localOnly&&console.log("Run `visa-cli setup` to sign in with the GitHub account you want to use.")}catch(t){console.error("Error:",t.message),process.exit(1)}}G.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").option("--local-only","Only clear local credentials and the local biometric key; skip server-side biometric recovery").action(gm);var Na=G.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(ze);Na.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new Ee(()=>F.getSessionToken()).getBalance();if(console.log(`
|
|
260
260
|
Balance: ${Ca(t.balanceMicros,t.balanceCents)}
|
|
261
261
|
`),t.ledger.length===0){console.log(` (no ledger entries \u2014 top up to begin: visa-cli balance topup --amount 5)
|
|
262
|
-
`);return}let n=t.ledger.slice(0,20),r=[],o=t.balanceCents,s=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(s!=null?s.toString():String(o*1e4)),s!=null&&u.deltaMicros?s-=BigInt(u.deltaMicros):(s=null,o-=u.deltaCents);let i=19,a=11,c=13,l=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(c)} ${"REASON".padEnd(l)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(c)} ${"\u2500".repeat(l)} ${"\u2500".repeat(20)}`),n.forEach((u,d)=>{let p=(u.createdAt||"").slice(0,19),m=Ca(u.deltaMicros,u.deltaCents,!0),g=
|
|
262
|
+
`);return}let n=t.ledger.slice(0,20),r=[],o=t.balanceCents,s=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(s!=null?s.toString():String(o*1e4)),s!=null&&u.deltaMicros?s-=BigInt(u.deltaMicros):(s=null,o-=u.deltaCents);let i=19,a=11,c=13,l=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(c)} ${"REASON".padEnd(l)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(c)} ${"\u2500".repeat(l)} ${"\u2500".repeat(20)}`),n.forEach((u,d)=>{let p=(u.createdAt||"").slice(0,19),m=Ca(u.deltaMicros,u.deltaCents,!0),g=Kb(r[d]),_=(u.reason??"").slice(0,l),x=u.toolName??"";console.log(` ${p.padEnd(i)} ${m.padStart(a)} ${g.padStart(c)} ${_.padEnd(l)} ${x}`)}),console.log()}catch(e){e instanceof Qe&&(console.error(`Top-up pending reconciliation [${e.code}]: ${e.message}`),e.transactionId&&console.error(`Transaction: ${e.transactionId}`),process.exit(1)),console.error("Error:",e.message),process.exit(1)}});Na.command("topup").description("Top up prepaid balance from your default card (same path as MCP buy_credits; Touch ID required)").requiredOption("-a, --amount <usd>","Amount in USD (e.g. 5 or 1.50)").action(async e=>{try{let t=ss(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,o=new Ee(()=>F.getSessionToken());if(!se())throw new Error(is);let s=xs.randomUUID(),i=await Xn(o,async()=>{let a;if(se()){let{nonce:c}=await o.getAttestationChallenge(),l=Buffer.from(JSON.stringify({nonce:c,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await kn(l,`top up balance with $${t.displayUsd}`),nonce:c,amount:r,merchant:"Visa CLI Balance"}}return o.topupBalance({amount_cents:n,idempotency_key:s,attestation:a})},Aa(o));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now $${((i.balanceCents??0)/100).toFixed(2)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),Ic();else{let a=i.error_code?` [${i.error_code}]`:"";console.error(`Top-up failed${a}: ${i.error||"Unknown error"}`),process.exit(1)}}catch(t){console.error("Error:",t.message),process.exit(1)}});var hm=Na.command("auto-topup").description("Show or disable automatic balance top-ups (read/disable only \u2014 re-enabling is retired pending mandate model)").addHelpCommand(!1).action(ze);hm.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new Ee(()=>F.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
|
|
263
263
|
Auto-topup: disabled
|
|
264
|
-
`);return}let n=or(t.targetCents),r=or(t.thresholdCents),o=12,s=13;console.log(),console.log(` ${"STATE".padEnd(o)} enabled`),console.log(` ${"TARGET".padEnd(o)} ${n.padStart(s)} (refill balance to this amount)`),console.log(` ${"THRESHOLD".padEnd(o)} ${r.padStart(s)} (trigger refill when balance drops below this)`),console.log(),console.log(" Disable with: visa-cli balance auto-topup disable"),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});hm.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new Ee(()=>F.getSessionToken()).disableAutoTopup();t.success||(console.error(`Auto-topup disable failed: ${t.error||"Unknown error"}`),process.exit(1)),console.log("Auto-topup disabled. Your balance will no longer refill automatically.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var
|
|
264
|
+
`);return}let n=or(t.targetCents),r=or(t.thresholdCents),o=12,s=13;console.log(),console.log(` ${"STATE".padEnd(o)} enabled`),console.log(` ${"TARGET".padEnd(o)} ${n.padStart(s)} (refill balance to this amount)`),console.log(` ${"THRESHOLD".padEnd(o)} ${r.padStart(s)} (trigger refill when balance drops below this)`),console.log(),console.log(" Disable with: visa-cli balance auto-topup disable"),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});hm.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new Ee(()=>F.getSessionToken()).disableAutoTopup();t.success||(console.error(`Auto-topup disable failed: ${t.error||"Unknown error"}`),process.exit(1)),console.log("Auto-topup disabled. Your balance will no longer refill automatically.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var dv=G.command("session",{hidden:!0}).description("Inspect session budgets");dv.command("inspect <id>").description("Show a session-budget by id (e.g. sb_abc123)").action(async e=>{try{if(!e||e.length===0)throw new Error("session id required");let t=new Ee(()=>F.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),o=n.status==="fulfilled"?n.value.budget:void 0,s=r.status==="fulfilled"?r.value:void 0;if(!o&&!s?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
|
|
265
265
|
Session: ${e}`),o){let i=(o.totalCents/100).toFixed(2),a=(o.cumulativeCents/100).toFixed(2),c=(o.remainingCents/100).toFixed(2);console.log(` Status: ${o.status}${o.expired?" (expired)":""}`),console.log(` Budget: $${i} \xB7 spent $${a} \xB7 remaining $${c}`),console.log(` Created: ${o.createdAt}`),console.log(` Expires: ${o.expiresAt}`)}if(s?.ledger?.length){console.log(`
|
|
266
266
|
PSP References (CyberSource activity):`);let i=8,a=9,c=36;console.log(` ${"TYPE".padEnd(i)} ${"AMOUNT".padStart(a)} ${"CYBERSOURCE TX ID".padEnd(c)} CREATED`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(c)} ${"\u2500".repeat(19)}`);for(let l of s.ledger){let u=`$${(l.amountCents/100).toFixed(2)}`;console.log(` ${l.type.padEnd(i)} ${u.padStart(a)} ${(l.transactionId||"").padEnd(c)} ${(l.createdAt||"").slice(0,19)}`)}}else o&&console.log(`
|
|
267
|
-
(no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function ym(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await ae().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}G.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(ym);G.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=aa(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?ca(e.diagnostics,e.display):null;try{t&&console.warn(`Warning: ${t}`),console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:n,stderr:r}=await ka(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});n.trim()&&process.stdout.write(n),r.trim()&&process.stderr.write(r);let o=ni(pt(),{force:!0});for(let s of o.messages)console.log(s);console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(n){console.error(`Update failed while running: ${e.display}`),console.error(n?.message??String(n)),process.exit(1)}});var ut=G.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(ze);function _m(e){return[Ue.join(e,".zshrc"),Ue.join(e,".bashrc"),Ue.join(e,".bash_profile"),Ue.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),Ue.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),Ue.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),Ue.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),Ue.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function
|
|
267
|
+
(no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function ym(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await ae().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}G.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(ym);G.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=aa(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?ca(e.diagnostics,e.display):null;try{t&&console.warn(`Warning: ${t}`),console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:n,stderr:r}=await ka(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});n.trim()&&process.stdout.write(n),r.trim()&&process.stderr.write(r);let o=ni(pt(),{force:!0});for(let s of o.messages)console.log(s);console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(n){console.error(`Update failed while running: ${e.display}`),console.error(n?.message??String(n)),process.exit(1)}});var ut=G.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(ze);function _m(e){return[Ue.join(e,".zshrc"),Ue.join(e,".bashrc"),Ue.join(e,".bash_profile"),Ue.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),Ue.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),Ue.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),Ue.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),Ue.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function mv(e){let t=new Map;for(let n of _m(e))try{Y.existsSync(n)&&t.set(n,Y.readFileSync(n,"utf-8"))}catch{}return t}function pv(e){let t=[];for(let[n,r]of e)try{(Y.existsSync(n)?Y.readFileSync(n,"utf-8"):"")!==r&&t.push(n)}catch{}return t}function fv(e){let t=[];for(let n of _m(e))try{if(!Y.existsSync(n))continue;let r=Y.readFileSync(n,"utf-8");br(r)!==r.trimEnd()&&t.push(n)}catch{}return t}ut.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(ym);ut.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=ae(),n=await Dr({api:t,includeDev:!!e.dev});if(e.json){console.log(Pu(n));return}n.statusError&&(console.error(`Warning: could not reach auth server (${n.statusError}).`),console.error("Server-sourced entries show '\u2014'. Log in with `visa-cli setup` if you expected values here."),console.error("")),console.log($u(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});ut.command("get <key>").description("Print the resolved value of a single config key (pipe-friendly)").option("--raw","Print the underlying value as JSON instead of the formatted display string").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").action(async(e,t)=>{try{let n=ae(),o=(await Dr({api:n,includeDev:!!t.dev})).entries.find(s=>s.key===e);o||(console.error(`Error: unknown config key '${e}'. Run 'visa-cli config list' to see available keys.`),process.exit(1)),t.raw?console.log(JSON.stringify(o.value)):console.log(o.formatted)}catch(n){console.error("Error:",n.message),process.exit(1)}});function gv(){return Object.entries(Ut).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
|
|
268
268
|
`)}ut.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
|
|
269
269
|
Settable keys:
|
|
270
|
-
${
|
|
270
|
+
${gv()}`).action((e,t)=>{try{let n=Mo(e,t);console.log(`Saved ${n.key}=${JSON.stringify(n.value)} \u2192 ${n.path}`),n.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")}catch(n){n instanceof ht||n instanceof yt||n instanceof Nt?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});ut.command("unset <key>").description("Remove a CLI setting from ~/.visa-mcp/settings.json (falls back to env var or default)").action(e=>{try{let t=No(e);t.removed?(console.log(`Removed ${t.key} from ${t.path}`),t.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")):console.log(`No-op: ${t.key} was not set in ${t.path}.`)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}});ut.command("reset").description("Log out and clear all credentials").option("--local-only","Only clear local credentials and the local biometric key; skip server-side biometric recovery").action(gm);var La=ut.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(ze);La.command("status").description("Show current biometric enforcement state").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await ae().getStatus(),r=n.attestationRequired!==!1,o=!!n.hasAttestationKey,s=se();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${o?"yes":"no"}`),console.log(`Touch ID available on this device: ${s?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});La.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ae(),n=await Yo(t);n.ok||(console.error(`Error: ${n.message}`),process.exit(1));let r=await t.setBiometricPreference({required:!0});r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});La.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ae(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!se()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await Xn(t,async()=>{let o;if(n.hasAttestationKey&&se())try{let{nonce:s}=await t.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:s,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");o={signature:await kn(c,"disable Touch ID requirement"),nonce:s,amount:i,merchant:a}}catch(s){throw new Error(`Touch ID confirmation failed: ${s?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:o})},Aa(t));r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var Rn=ut.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(ze);function bm(){let e=bo();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function vm(e){for(let t of e.messages)console.log(t);for(let t of e.errors)console.error(t);e.ok||process.exit(1)}function hv(){vm(ii(void 0,{homeDir:J.homedir(),installVisaStatusLine:wr,installShellHud:bo}))}function wm(){console.log("Note: `config shell-hud enable` now installs the Claude Code statusLine HUD."),console.log(" For the explicit shell-prompt HUD, run: visa-cli config hud enable shell"),hv()}function As(){let e=mt();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}Rn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(bm);Rn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(wm);Rn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(As);Rn.command("disable").description("Disable the persistent shell HUD").action(As);Rn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${vo()}
|
|
271
271
|
`)});Rn.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,p,m)=>{console.log(` ${p?"\u2713":"\u2717"} ${d}: ${m}`),p||(n=!1)};console.log(`Shell HUD Doctor
|
|
272
272
|
`);let o=Dn();if(r("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let d=_r(o),p=e(d);if(r("RC file exists",p,d.replace(J.homedir(),"~")),p){let g=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!g,g?"found in rc file":"missing \u2014 run: visa-cli config hud enable shell")}}let s=Pt(),i=e(s);if(r("Cache file",i,i?s.replace(J.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(s,"utf-8")),p=Date.now()-(d.renderedAt??0),m=Math.round(p/1e3),g=m<=30;console.log(` ${g?"\u2713":"\u26A0"} Cache freshness: ${m}s old${g?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=yr(),c=e(a),l="missing";if(c)try{l=t(a,"utf-8").trim().slice(0,80)}catch{l="unreadable"}r("Line file",c,l);let u=!1;try{u=!!await F.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await ae().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let p=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,p)}console.log(n?`
|
|
273
273
|
All checks passed.`:`
|
|
274
|
-
Some checks failed \u2014 see above.`),n||process.exit(1)});async function Sm(e){if(!(!e.force&&Ac()))try{await Ws();let t=ae(),[n,r,o,s]=await Promise.allSettled([t.getStatus(),t.getBalance(),t.listAppApiKeys(),t.getTransactions({limit:1})]);if(n.status==="rejected")throw n.reason;let i=n.value,a=i.prepaidBalance?.cents;if(typeof a=="number"){i.balanceCents=a;let u=i.prepaidBalance?.amountUsd;i.amountUsd=typeof u=="number"?u:a/100}if(r.status==="fulfilled"&&r.value.success&&(i.balanceCents=r.value.balanceCents,i.amountUsd=r.value.amountUsd),o.status==="fulfilled"&&o.value.success?i.apiKeyCount=Array.isArray(o.value.keys)?o.value.keys.length:0:o.status==="rejected"&&
|
|
274
|
+
Some checks failed \u2014 see above.`),n||process.exit(1)});async function Sm(e){if(!(!e.force&&Ac()))try{await Ws();let t=ae(),[n,r,o,s]=await Promise.allSettled([t.getStatus(),t.getBalance(),t.listAppApiKeys(),t.getTransactions({limit:1})]);if(n.status==="rejected")throw n.reason;let i=n.value,a=i.prepaidBalance?.cents;if(typeof a=="number"){i.balanceCents=a;let u=i.prepaidBalance?.amountUsd;i.amountUsd=typeof u=="number"?u:a/100}if(r.status==="fulfilled"&&r.value.success&&(i.balanceCents=r.value.balanceCents,i.amountUsd=r.value.amountUsd),o.status==="fulfilled"&&o.value.success?i.apiKeyCount=Array.isArray(o.value.keys)?o.value.keys.length:0:o.status==="rejected"&&lv(o.reason)&&(i.apiKeyStatus="rollout_locked"),s.status==="fulfilled"){let u=s.value,p=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(m=>m&&typeof m.tool_name=="string"&&m.tool_name.length>0);p&&p.created_at&&(i.lastService={toolName:p.tool_name,createdAt:p.created_at})}let c={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:et()},l=Xs(i,c);Zs(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";Rc(n)}finally{en()}}Rn.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(Sm);var In=G.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");In.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(bm);In.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(wm);In.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(As);In.command("disable").description("Disable the persistent shell HUD").action(As);In.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${vo()}
|
|
275
275
|
`)});In.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});In.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(Sm);async function xm(e){try{await Ws();let t=await Bc(),n=vo(),r=n,o=n.split(`
|
|
276
276
|
`)[0],s=$c();if(!t&&o.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
|
|
277
277
|
`),wa();return}if(e.json){let a=await Yc(r,t,s);process.stdout.write(`${JSON.stringify(a,null,2)}
|
|
@@ -280,7 +280,7 @@ Some checks failed \u2014 see above.`),n||process.exit(1)});async function Sm(e)
|
|
|
280
280
|
${e}Visa HUD Status${o}
|
|
281
281
|
`);let s=pt(),i=!1,a=!1;try{if(Y.existsSync(s)){let g=JSON.parse(Y.readFileSync(s,"utf-8")),_=typeof g.statusLine=="object"?g.statusLine.command:"";i=Mt(_),a=!!g.statusLine&&!i}}catch{}let c=i?`${n}\u2713${o}`:`${t}\u2717${o}`,l=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${o} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${c} ${e}Claude Code${o} (statusLine) ${l}`);let u=nn(J.homedir()),d=u.length>0||_o(),p=d?`${n}\u2713${o}`:`${t}\u2717${o}`,m=d?`installed in shell rc file${u.length>0?` (${u.map(g=>g.replace(J.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${p} ${e}Shell prompt${o} ${m}`),i&&d&&console.log(` ${r}!${o} ${e}Overlap${o} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
|
|
282
282
|
${e}Quick start:${o}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${o}`),d||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${o}`),i&&d&&console.log(` ${n}All surfaces enabled.${o}`),(i||d)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${o}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${o}`),console.log()});ir.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{vm(ii(e,{homeDir:J.homedir(),installVisaStatusLine:wr,installShellHud:bo}))});ir.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let s=mt();s.removed||(console.error(s.message),process.exit(1)),console.log(s.message);return}let n=Ao(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, all"),process.exit(1));let r=!1,o=!1;if(n==="claude"||n==="claude-code"||n==="all"){let s=pt(),i=ri(s);console.log(i.message),i.removed&&(o=!0),!i.removed&&n!=="all"&&(r=!0);let a=i.status==="removed"||i.status==="missing-settings"||i.status==="missing-statusline";if(n!=="all"&&!e&&a&&!To()&&nn(J.homedir()).length>0){let l=mt();l.removed&&l.rcPaths&&l.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${l.rcPaths.map(u=>u.replace(J.homedir(),"~")).join(", ")} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=1 (or true / yes / on) if you want the shell surface to stay.`),o=!0,(i.status==="missing-settings"||i.status==="missing-statusline")&&(r=!1))}}if(n==="all"){let s=mt();console.log(s.message),s.removed&&(o=!0),!s.removed&&n!=="all"&&(r=!0)}n==="all"&&!o&&(r=!0),r&&process.exit(1)});ir.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").option("--fix","Self-heal locally fixable issues (stale cache, legacy placeholder, orphan precmd block)").option("-y, --yes","Allow --fix to remove overlapping shell HUD blocks without an interactive prompt").action(async e=>{let t=!0,n=(m,g,_)=>{console.log(` ${g?"\u2713":"\u2717"} ${m}: ${_}`),g||(t=!1)};console.log(`Visa HUD Doctor
|
|
283
|
-
`);let r=[],o=aa(void 0,void 0,void 0,{withDiagnostics:!0}),s=o.diagnostics?ca(o.diagnostics,o.display):null;s&&(console.log(`\u26A0 ${s}`),console.log(""));let i=pt(),a=!1;try{if(Y.existsSync(i)){let m=JSON.parse(Y.readFileSync(i,"utf-8")),g=typeof m.statusLine=="object"?m.statusLine.command:"";a=Mt(g)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let c=
|
|
283
|
+
`);let r=[],o=aa(void 0,void 0,void 0,{withDiagnostics:!0}),s=o.diagnostics?ca(o.diagnostics,o.display):null;s&&(console.log(`\u26A0 ${s}`),console.log(""));let i=pt(),a=!1;try{if(Y.existsSync(i)){let m=JSON.parse(Y.readFileSync(i,"utf-8")),g=typeof m.statusLine=="object"?m.statusLine.command:"";a=Mt(g)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let c=fv(J.homedir()),l=Dn();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let m=_r(l),g=Y.existsSync(m);if(n("RC file exists",g,m.replace(J.homedir(),"~")),g){let x=Y.readFileSync(m,"utf-8").includes("visa-cli shell hud v2");console.log(` ${x?"\u2713":"\u2013"} Shell HUD block: ${x?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}if(c.length>0&&console.log(` \u2713 Shell HUD rc scan: installed in ${c.map(m=>m.replace(J.homedir(),"~")).join(", ")}`),a&&c.length>0&&e.fix){let m=c.map(_=>_.replace(J.homedir(),"~")).join(", "),g=e.yes===!0;if(!g&&process.stdin.isTTY&&(g=await fm(`Remove shell prompt HUD block from ${m}?`,{})==="confirmed"),g){let _=mv(J.homedir());mt();let x=pv(_);if(x.length>0){let $=x.map(M=>M.replace(J.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${$}`),r.push(`removed shell precmd block from ${$}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${m}; rerun with --yes or remove it explicitly with: visa-cli config hud disable shell`)}else a&&c.length>0&&console.log(" ! Overlap notice: Claude Code statusLine and shell prompt HUD are both installed. If the prompt output is unintended, run: visa-cli config hud disable shell \u2014 or rerun with: visa-cli config hud doctor --fix --yes");let u=Pt(),d=Y.existsSync(u);if(n("HUD cache file",d,d?u.replace(J.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),d)try{let m=JSON.parse(Y.readFileSync(u,"utf-8")),g=Date.now()-(m.renderedAt??0),_=Math.round(g/1e3),x=_<=30,$=typeof m.line=="string"?m.line:"",M=$.length>0&&wo($);if(console.log(` ${x?"\u2713":"\u26A0"} Cache freshness: ${_}s old${x?"":" (stale \u2014 will refresh on next prompt)"}`),M&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!x||M)){let S=!1;try{Y.rmSync(u,{force:!0}),S=!0}catch{}try{let k=yr();Y.existsSync(k)&&(Y.rmSync(k,{force:!0}),S=!0)}catch{}if(S){let k=M?"cache held legacy placeholder":`cache was ${_}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${k}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let y=Ue.join(J.homedir(),".visa-cli","shell-hud.lock");Y.existsSync(y)&&(en(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}}}catch{if(console.log(" \u2717 Cache readable: corrupt JSON"),e.fix)try{Y.rmSync(u,{force:!0}),console.log(" \u2713 --fix: removed corrupt cache file; next prompt will trigger a fresh refresh"),r.push("removed corrupt cache");let m=Ue.join(J.homedir(),".visa-cli","shell-hud.lock");Y.existsSync(m)&&(en(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}catch{t=!1}else t=!1}let p=!1;try{p=!!await F.getSessionToken()}catch{}if(n("Auth token",p,p?"found in keychain":"missing \u2014 run: visa-cli setup"),p)try{await ae().getStatus(),n("API connectivity",!0,"GET /v1/status OK")}catch(m){let g=m instanceof Error?m.message:"unknown error";n("API connectivity",!1,g)}e.fix&&(r.length===0?console.log(`
|
|
284
284
|
--fix: no locally fixable issues found.`):console.log(`
|
|
285
285
|
--fix: applied ${r.length} change${r.length===1?"":"s"} \u2014 ${r.join("; ")}.`)),console.log(t?`
|
|
286
286
|
All checks passed.`:`
|
|
@@ -288,15 +288,15 @@ Some checks failed \u2014 see above.`),t||process.exit(1)});ir.command("enable-c
|
|
|
288
288
|
No live platform merchants on this auth server.
|
|
289
289
|
`);return}if(e.json){console.log(JSON.stringify({merchants:n},null,2));return}let r="\x1B[1m",o="\x1B[2m",s="\x1B[0m";console.log();for(let i of n)console.log(` ${r}${i.display_name}${s} ${o}\u2014 slug: ${i.slug}${s}`);console.log(`
|
|
290
290
|
${o}Run 'visa-cli merchants tools' to browse tools by merchant.${s}
|
|
291
|
-
`)}catch(t){console.error("Error:",t.message),process.exit(1)}});var
|
|
291
|
+
`)}catch(t){console.error("Error:",t.message),process.exit(1)}});var yv=new Set(["list","tools","describe","run","refresh"]);async function Ua(e){try{let n=await ae().catalogTool(e,"discover_tools");n||(console.error(`Tool not found: ${e}`),console.error('Search with: visa-cli tools --query "what you want to do"'),process.exit(1)),console.log(`
|
|
292
292
|
${n.id}
|
|
293
293
|
`),console.log(n.description),console.log(`
|
|
294
294
|
Price`),console.log(` ${Ir(n.priceCents,n.priceDisplay)}`),console.log(`
|
|
295
295
|
Provider`),console.log(` ${n.provider} \xB7 ${n.category}`),console.log(`
|
|
296
296
|
Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set,i=Object.entries(r),a=Math.max(12,...i.map(([c])=>c.length));for(let[c,l]of i){let u=s.has(c)?"required":"optional",d=ol(l),p=d?` ${d.padEnd(8)}`:" ",m=l?.description?` - ${l.description}`:"";console.log(` ${c.padEnd(a)} ${u}${p}${m}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
|
|
297
|
-
Examples`);let o=Ed(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(o)}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}}async function Da(e){try{let t=ae();if(e.merchant){let s=e.merchant,i=await t.getPublicMerchantDiscover(s);i||(console.error(`Merchant not found: ${s}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1));let a=i.routes.filter(l=>l.tool_id).map(l=>({id:l.tool_id,name:l.tool_id,description:l.description||"",provider:i.upstream_display??i.title,model:l.tool_id,category:l.category||"utility",priceCents:l.price_cents??0,inputSchema:l.request?.body_schema??{}})),c=e.category?a.filter(l=>l.category===e.category):a;if(e.json){console.log(JSON.stringify({merchant:s,tools:c},null,2));return}if(c.length===0){console.log(`No tools found for merchant "${s}".`);return}e.verbose?bi(c):Al(s,c);return}let{limit:n,offset:r}=
|
|
297
|
+
Examples`);let o=Ed(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(o)}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}}async function Da(e){try{let t=ae();if(e.merchant){let s=e.merchant,i=await t.getPublicMerchantDiscover(s);i||(console.error(`Merchant not found: ${s}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1));let a=i.routes.filter(l=>l.tool_id).map(l=>({id:l.tool_id,name:l.tool_id,description:l.description||"",provider:i.upstream_display??i.title,model:l.tool_id,category:l.category||"utility",priceCents:l.price_cents??0,inputSchema:l.request?.body_schema??{}})),c=e.category?a.filter(l=>l.category===e.category):a;if(e.json){console.log(JSON.stringify({merchant:s,tools:c},null,2));return}if(c.length===0){console.log(`No tools found for merchant "${s}".`);return}e.verbose?bi(c):Al(s,c);return}let{limit:n,offset:r}=ev(e),o=await Qb(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:o},null,2));return}if(o.length===0){console.log("No merchant tools found. Try: visa-cli tools --category image");return}e.verbose?bi(o):El(o)}catch(t){console.error("Error:",t.message),process.exit(1)}}An.command("tools").description("List available merchant tools").option("--category <category>","Filter by category (image, video, audio, 3d, llm)").option("--query <query>","Search by intent or keyword").option("--merchant <slug>","Scope to a single merchant (e.g. fal, openrouter)").option("--verbose","Show grouped cards with descriptions").option("--json","Print machine-readable JSON").option("--limit <n>",`Maximum tools to return (default ${Ia}, max ${$a})`,Ss).option("--offset <n>","Pagination offset (default 0)",Ss).action(Da);An.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{await Ua(e)});function _v(e){return["fal-flux-pro-ultra","fal-flux-pro","fal-flux-schnell","fal-recraft-v3","fal-ideogram-v2","fal-minimax-video","fal-wan-video","fal-kling-video","fal-ace-step-music","query_onchain_prices"].includes(e)}async function Rs(e,t,n){return _v(e)?Ve.shortcut(e,t,n):Ve.executeTool({tool_id:e,params:t},n,"execute_tool")}An.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=um(t.json,"--json");t.prompt&&(n.prompt=t.prompt),mr({yes:t.yes}),console.log(`Running ${e}`);let r=await Rs(e,n,`visa-cli merchants run ${e}`);Cs(r),Ts(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});An.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
|
|
298
298
|
Platform-merchant tool discovery is cached in-process by the MCP server.`),console.log(" Cache TTL: VISA_MERCHANT_DISCOVER_TTL_MS (default 300000ms = 5min)."),console.log(` To force-refresh now, restart Claude / Cursor \u2014 the next tools/list will re-fetch.
|
|
299
|
-
`)});An.on("command:*",async function(e){let t=e[0],n=e[1],r=e.slice(2);if(!t||
|
|
299
|
+
`)});An.on("command:*",async function(e){let t=e[0],n=e[1],r=e.slice(2);if(!t||yv.has(t)){console.error(`Unknown merchants subcommand: ${t}`),An.help({error:!0});return}if(!n||n==="tools"){let o=r.indexOf("--category"),s=o!==-1?r[o+1]:void 0,i=r.includes("--verbose"),a=r.includes("--json");await Da({category:s,verbose:i,json:a,merchant:t});return}if(n==="describe"){let o=r[0];o||(console.error(`Usage: visa-cli merchants ${t} describe <tool>`),process.exit(1));try{let s=ae(),i=await s.getPublicMerchantDiscover(t);if(i||(console.error(`Merchant not found: ${t}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1)),!await s.catalogTool(o,"discover_tools")){let c=i.routes.find(l=>l.tool_id===o);c||(console.error(`Tool "${o}" not found for merchant "${t}"`),console.error(`Browse with: visa-cli merchants ${t} tools`),process.exit(1)),console.log(`
|
|
300
300
|
${o}
|
|
301
301
|
`),c.description&&console.log(c.description),console.log(`
|
|
302
302
|
Price`),console.log(` ${Ir(c.price_cents)}`),console.log(`
|
|
@@ -308,4 +308,4 @@ ${e.kind}
|
|
|
308
308
|
LLM completion
|
|
309
309
|
`),console.log(`Using: ${a}`);let l=r.length>200?`${r.slice(0,200)}\u2026`:r;console.log(`Prompt: ${l}
|
|
310
310
|
`)}let c=await Rs(a,o,"visa-cli run-llm");Cs(c,{json:t.json,format:t.format,command:"run-llm"}),Ts(c)}catch(n){sr("run-llm",n,{json:t.json,format:t.format})}});G.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let s=[];for(let i of We)ba(i,n).removed&&s.push(i.displayName);s.length>0?console.log(`Removed visa-cli from: ${s.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
|
|
311
|
-
Supported clients: ${We.map(s=>s.id).join(", ")}`),process.exit(1));let r=ga(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${We.map(s=>s.id).join(", ")}`),process.exit(1));let o=ba(r,n);o.removed?console.log(`Removed visa-cli from ${o.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.hook("postAction",()=>{if(Zr){Zr=!1;return}ws&&Td(ws.lastSignals)});jd(G);
|
|
311
|
+
Supported clients: ${We.map(s=>s.id).join(", ")}`),process.exit(1));let r=ga(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${We.map(s=>s.id).join(", ")}`),process.exit(1));let o=ba(r,n);o.removed?console.log(`Removed visa-cli from ${o.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.hook("postAction",()=>{if(Zr){Zr=!1;return}ws&&Td(ws.lastSignals)});jd(G);av(["setup","install","status","cards","keys","balance","tools","describe","merchants","generate","run-llm","config","feedback","update","uninstall"]);pm(G);G.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(vs(),bs));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(vs(),bs));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(vs(),bs));await t(e)});0&&(module.exports={printGroupHelpAndExit});
|