@visa/cli 4.0.0-rc.16 → 4.0.0-rc.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var A_=Object.create;var Ko=Object.defineProperty;var k_=Object.getOwnPropertyDescriptor;var T_=Object.getOwnPropertyNames;var R_=Object.getPrototypeOf,I_=Object.prototype.hasOwnProperty;var st=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var ec=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Fr=(e,t)=>{for(var n in t)Ko(e,n,{get:t[n],enumerable:!0})},xd=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of T_(t))!I_.call(e,s)&&s!==n&&Ko(e,s,{get:()=>t[s],enumerable:!(r=k_(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?A_(R_(e)):{},xd(t||!e||!e.__esModule?Ko(n,"default",{value:e,enumerable:!0}):n,e)),$_=e=>xd(Ko({},"__esModule",{value:!0}),e);var Ls=ec((Hk,q_)=>{q_.exports={name:"@visa/cli",version:"4.0.0-rc.16",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js",visa:"./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/crypto build && pnpm --filter subway-sdk build && pnpm --filter @visa-cli/tools build && pnpm --filter @visa/identity build && pnpm --filter @visa/wallet build && pnpm --filter @visa/wallet-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"},optionalDependencies:{libp2p:"^3.3.4","@libp2p/tcp":"^11.0.22","@libp2p/crypto":"^5.1.20","@chainsafe/libp2p-noise":"^17.0.0","@chainsafe/libp2p-yamux":"^8.0.1","@multiformats/multiaddr":"^13.0.3",uint8arrays:"^6.1.1"},devDependencies:{"@visa/crypto":"workspace:*","subway-sdk":"workspace:*","@visa/money":"workspace:*","@visa/wallet":"workspace:*","@visa/wallet-tools":"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":"^26.1.0","@typescript-eslint/eslint-plugin":"^8.63.0","@typescript-eslint/parser":"^8.63.0","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.9.4","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});function m0(){Fe.existsSync(Uc)||Fe.mkdirSync(Uc,{recursive:!0,mode:448})}function p0(){if(!Lc){if(m0(),Fe.existsSync(Zs)&&Fe.statSync(Zs).size>f0){let t=Zs+".1";Fe.existsSync(t)&&Fe.unlinkSync(t),Fe.renameSync(Zs,t)}Lc=Fe.createWriteStream(Zs,{flags:"a"})}return Lc}function g0(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function bi(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
1
+ "use strict";var A_=Object.create;var Ko=Object.defineProperty;var k_=Object.getOwnPropertyDescriptor;var T_=Object.getOwnPropertyNames;var R_=Object.getPrototypeOf,I_=Object.prototype.hasOwnProperty;var st=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var ec=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Fr=(e,t)=>{for(var n in t)Ko(e,n,{get:t[n],enumerable:!0})},xd=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of T_(t))!I_.call(e,s)&&s!==n&&Ko(e,s,{get:()=>t[s],enumerable:!(r=k_(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?A_(R_(e)):{},xd(t||!e||!e.__esModule?Ko(n,"default",{value:e,enumerable:!0}):n,e)),$_=e=>xd(Ko({},"__esModule",{value:!0}),e);var Ls=ec((Hk,q_)=>{q_.exports={name:"@visa/cli",version:"4.0.0-rc.17",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js",visa:"./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/crypto build && pnpm --filter subway-sdk build && pnpm --filter @visa-cli/tools build && pnpm --filter @visa/identity build && pnpm --filter @visa/wallet build && pnpm --filter @visa/wallet-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"},optionalDependencies:{libp2p:"^3.3.4","@libp2p/tcp":"^11.0.22","@libp2p/crypto":"^5.1.20","@chainsafe/libp2p-noise":"^17.0.0","@chainsafe/libp2p-yamux":"^8.0.1","@multiformats/multiaddr":"^13.0.3",uint8arrays:"^6.1.1"},devDependencies:{"@visa/crypto":"workspace:*","subway-sdk":"workspace:*","@visa/money":"workspace:*","@visa/wallet":"workspace:*","@visa/wallet-tools":"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":"^26.1.0","@typescript-eslint/eslint-plugin":"^8.63.0","@typescript-eslint/parser":"^8.63.0","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.9.4","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});function m0(){Fe.existsSync(Uc)||Fe.mkdirSync(Uc,{recursive:!0,mode:448})}function p0(){if(!Lc){if(m0(),Fe.existsSync(Zs)&&Fe.statSync(Zs).size>f0){let t=Zs+".1";Fe.existsSync(t)&&Fe.unlinkSync(t),Fe.renameSync(Zs,t)}Lc=Fe.createWriteStream(Zs,{flags:"a"})}return Lc}function g0(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function bi(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
2
2
  `;g0(e)&&process.stderr.write(s),p0().write(s)}var Fe,Dc,tm,Uc,Zs,f0,Lc,g,qt=st(()=>{"use strict";Fe=R(require("fs")),Dc=R(require("path")),tm=R(require("os")),Uc=Dc.join(tm.homedir(),".visa-mcp"),Zs=Dc.join(Uc,"mcp-server.log"),f0=5*1024*1024,Lc=null;g={debug:(...e)=>bi("DEBUG",...e),info:(...e)=>bi("INFO",...e),warn:(...e)=>bi("WARN",...e),error:(...e)=>bi("ERROR",...e)}});var vi,om,im,jc,Qs,am=st(()=>{"use strict";vi=R(require("fs")),om=R(require("path")),im=R(require("os")),jc=om.join(im.homedir(),".visa-mcp"),Qs=class{static ensureConfigDir(){vi.existsSync(jc)||vi.mkdirSync(jc,{recursive:!0,mode:448})}static getConfigDir(){return jc}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 cm(e){let t=lm.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function eo(){return um.join(Qs.getConfigDir(),_0)}function dm(e){if((0,Hc.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function v0(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);if(!Number.isFinite(n)||!Number.isFinite(r))return!1;let s=[n>>8&255,n&255,r>>8&255,r&255].join(".");return dm(s)}function w0(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Hc.isIP)(t);return n===4?dm(t):n===6?t==="::1"||v0(t):!1}function Bc(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:"&&w0(n.hostname)))throw new Error(`${t} ${b0}`)}function er(){let e=eo();if(!wn.existsSync(e))return{};try{let t=wn.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(g.warn("settings:corrupt",{path:cm(e),reason:"not_object"}),{}):n}catch(t){return g.warn("settings:corrupt",{path:cm(e),error:t?.message||String(t)}),{}}}function Fc(e){Qs.ensureConfigDir();let t=eo(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
3
3
  `;wn.writeFileSync(n,r,{mode:384}),wn.renameSync(n,t)}function qc(e){let t=er()[e];return typeof t=="string"?t:void 0}function Si(e){let t=er()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function Kc(e){let t=er()[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}}function xi(e,t){if(fm.some(o=>e.startsWith(o)))throw new Kt(e);if(e in wi)throw new vn(e);let n=tr[e];if(!n)throw new at(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")r=!0;else if(o==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let o=Number(t);if(!Number.isFinite(o))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=o}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let s=er();return s[e]=r,Fc(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:eo()}}function Ci(e){if(fm.some(o=>e.startsWith(o)))throw new Kt(e);let t=tr[e];if(e in wi){let o=er(),i=e in o;return i&&(delete o[e],Fc(o)),{key:e,removed:i,requiresRestart:!1,path:eo()}}if(!t)throw new at(e);let r=er(),s=e in r;return s&&(delete r[e],Fc(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:eo()}}function mm(){let e=er();return Object.entries(wi).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}function C0(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function E0(){try{let e=Ls();return C0(e.version)}catch{return!1}}function A0(e){return e.envVar!==void 0&&e.envVar!==""?(Bc(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Bc(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?x0:S0}function Se(){return A0({envVar:process.env.VISA_AUTH_URL,settingValue:qc("auth.serverUrl"),isPrerelease:E0()})}function pm(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Si("ui.suppressBrowser")??!1}function gm(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Si("ui.suppressFeed")??!1}function hm(){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=Kc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Vc}var wn,Hc,lm,um,_0,b0,tr,Vc,wi,at,Kt,vn,fm,S0,x0,St=st(()=>{"use strict";wn=R(require("fs")),Hc=require("node:net"),lm=R(require("os")),um=R(require("path"));am();qt();_0="settings.json",b0="must use https unless it points at localhost/loopback for local development";tr={"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");Bc(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.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(s=>s.trim()).filter(Boolean);for(let s of r)if(!n.test(s))throw new Error(`merchants.discover: "${s}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [10, 10000] = $0.10\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<10||e>1e4)throw new Error("credit.sessionCapCents must be between 10 ($0.10) and 10000 ($100)")}}},Vc=500,wi={"tools.specific":"Legacy direct _card MCP tools are retired. Use discover_tools/execute_tool.","tools.meta":"Category meta-tools (generate_image, run_llm, ...) are removed. Use discover_tools/execute_tool.","credit.sessionMode":"The session-mode toggle is retired. Use start_session, close_session, and get_session_status."};at=class extends Error{constructor(t){let n=Object.keys(tr).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"}},Kt=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"}},vn=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+wi[t]),this.name="RetiredSettingKeyError"}},fm=["biometric.","spending.","account.","cards.","biometric"];S0="https://auth.visacli.sh",x0="https://auth-visa-code-preview.up.railway.app"});var tp=ec(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.formatCents=ep;lt.formatUsd=vw;lt.formatMicros=Pi;lt.formatMicrosWire=ww;lt.formatTxAmount=Sw;lt.formatDate=xw;lt.formatRelativeTime=Cw;lt.formatTime=Ew;lt.formatAge=Aw;var Qm=1e6,bw=100;function ep(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let s=(e/bw).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${s}`:s}function vw(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let r=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${r}`:r}function Pi(e,t={}){let n=t.fallback??"\u2014",r=typeof e=="string"?e===""?null:Number(e):e;if(r==null||!Number.isFinite(r))return n;let o=(r/Qm).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&r>0?`+${o}`:o}function ww(e,t,n={}){return e&&/^-?\d+$/.test(e)?Pi(e,n):t!=null&&Number.isFinite(t)?ep(t,n):n.fallback??"\u2014"}function Sw(e,t={}){let n=Number(e.amount_micros);if(Number.isFinite(n)&&e.amount_micros!=null&&e.amount_micros!=="")return Pi(n,t);let r=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(r)?Pi(r*Qm,t):t.fallback??"\u2014"}function xw(e,t={}){let n=t.fallback??"\u2014";if(!e)return n;let r=new Date(e);return Number.isNaN(r.getTime())?n:r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function Cw(e,t=Date.now()){if(!e)return"\u2014";let n=Date.parse(e);if(Number.isNaN(n))return"\u2014";let r=t-n,s=r>=0,o=Math.abs(r),i=Math.floor(o/1e3),a=Math.floor(i/60),c=Math.floor(a/60),l=Math.floor(c/24),u=Math.floor(l/7),d=Math.floor(l/30),f=Math.floor(l/365);return i<45?"just now":a<1?s?"a minute ago":"in a minute":a<60?is(r,s,a,"minute"):c<24?is(r,s,c,"hour"):l===1?s?"yesterday":"tomorrow":l<7?is(r,s,l,"day"):u<4?is(r,s,u,"week"):d<12?is(r,s,d,"month"):is(r,s,f,"year")}function is(e,t,n,r){let s=n!==1?"s":"";return t?`${n} ${r}${s} ago`:`in ${n} ${r}${s}`}function Ew(e,t={}){let n=t.fallback??"\u2014";if(!e)return n;let r=new Date(e);return Number.isNaN(r.getTime())?n:r.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}function Aw(e,t){if(!e)return"";let n=Date.parse(e);if(Number.isNaN(n))return"";let r=Math.max(0,t-n),s=Math.floor(r/1e3);if(s<45)return"just now";let o=Math.floor(s/60);if(o<60)return`${o}m ago`;let i=Math.floor(o/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<30)return`${a}d ago`;let c=Math.floor(a/30);return c<12?`${c}mo ago`:`${Math.floor(a/365)}y ago`}});var as=ec(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.formatAge=q.formatTime=q.formatRelativeTime=q.formatDate=q.formatTxAmount=q.formatMicrosWire=q.formatMicros=q.formatUsd=q.formatCents=void 0;q.micros=kw;q.fromCents=Tw;q.fromUsdc=Rw;q.fromUsd=Iw;q.toCents=$w;q.toCentsForAcquirer=Pw;q.toUsdc=Ow;q.toWire=Nw;q.fromWire=Mw;q.toDisplay=Lw;q.toUsdRounded2dp=Uw;q.add=Dw;q.sub=jw;q.clampNonNegative=Bw;q.isNonNegative=Fw;q.max=Hw;q.min=Vw;var Jt=10000n,np=1000000n;function kw(e){return e}function Tw(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Jt}function Rw(e){return e}function Iw(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function $w(e){if(e>=0n)return Number(e/Jt);let t=e/Jt,n=e%Jt;return Number(n===0n?t:t-1n)}function Pw(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Jt)}function Ow(e){return e}function Nw(e){return e.toString()}function Mw(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 Lw(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/np,a=o%np,c=s?"-":"";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 Uw(e){let t=e<0n,n=t?-e:e,r=n/Jt,o=n%Jt*2n,i;o<Jt?i=r:o>Jt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function Dw(e,t){return e+t}function jw(e,t){return e-t}function Bw(e){return e<0n?0n:e}function Fw(e){return e>=0n}function Hw(e,t){return e>t?e:t}function Vw(e,t){return e<t?e:t}var Xt=tp();Object.defineProperty(q,"formatCents",{enumerable:!0,get:function(){return Xt.formatCents}});Object.defineProperty(q,"formatUsd",{enumerable:!0,get:function(){return Xt.formatUsd}});Object.defineProperty(q,"formatMicros",{enumerable:!0,get:function(){return Xt.formatMicros}});Object.defineProperty(q,"formatMicrosWire",{enumerable:!0,get:function(){return Xt.formatMicrosWire}});Object.defineProperty(q,"formatTxAmount",{enumerable:!0,get:function(){return Xt.formatTxAmount}});Object.defineProperty(q,"formatDate",{enumerable:!0,get:function(){return Xt.formatDate}});Object.defineProperty(q,"formatRelativeTime",{enumerable:!0,get:function(){return Xt.formatRelativeTime}});Object.defineProperty(q,"formatTime",{enumerable:!0,get:function(){return Xt.formatTime}});Object.defineProperty(q,"formatAge",{enumerable:!0,get:function(){return Xt.formatAge}})});function Al(e,t){switch(e){case"name_not_found":return new Kp(t);case"delivery_failed":return new Gp(t);case"timeout":return new yo(t);case"not_registered":return new Wp;case"register_failed":return new zi(t);case"invalid_message":return new Yp(t);case"rate_limited":return new zp(t);default:return new Tt(e,t)}}var Tt,Kp,Gp,yo,Wp,Ne,Yp,zi,zp,kl=st(()=>{"use strict";Tt=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},Kp=class extends Tt{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},Gp=class extends Tt{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},yo=class extends Tt{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},Wp=class extends Tt{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},Ne=class extends Tt{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},Yp=class extends Tt{constructor(e){super("invalid_message",e),this.name="InvalidMessageError"}},zi=class extends Tt{constructor(e){super("register_failed",e),this.name="RegisterFailedError"}},zp=class extends Tt{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});var Jp,Tl=st(()=>{"use strict";Jp=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')})});function Ar(e){return e.includes(".")?e:`${e}.relay`}function Rl(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function hS(){if(typeof WebSocket<"u")return WebSocket;try{let e=Jp("ws");return e.default??e}catch{return}}function yS(e,t,n){return Math.min(Math.max(e,t),n)}function HS(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Mg(e,t,n=""){let r=HS(e),s=e?.length;if(!r||t!==void 0){let i=n&&`"${n}" `,a="",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e}function sg(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function VS(e,t){Mg(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function _o(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ol(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function It(e,t){return e<<32-t|e>>>t}function Lg(e,t={}){let n=(s,o)=>e(o).update(s).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>e(s),Object.assign(n,t),Object.freeze(n)}function qS(e,t,n){return e&t^~e&n}function KS(e,t,n){return e&t^e&n^t&n}function GS(e,t=!1){return t?{h:Number(e&Ji),l:Number(e>>og&Ji)}:{h:Number(e>>og&Ji)|0,l:Number(e&Ji)|0}}function WS(e,t=!1){let n=e.length,r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){let{h:i,l:a}=GS(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function tn(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function lx(e){return MS(e)}function ux(e,t){return DS(t,e)}function fx(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function gx(e){let t=dx(ax(e.payload)),n=`${e.messageId}
4
4
  ${e.senderPeerId}
@@ -109,7 +109,7 @@ ${h}`:m}function Cb(e){let t=` ${te("\u2502",ee.chrome)} `,n=[];if(typeof e.spen
109
109
  `)}catch{}}function pf(){try{let e=Ws();if(!e)return;let t={...e,renderedAt:0};Wr(yn(),JSON.stringify(t)+`
110
110
  `)}catch{}}function zn(){try{z.unlinkSync(cf())}catch{}}function Ws(){let e=yn();if(!z.existsSync(e))return null;try{let t=JSON.parse(z.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&ui(t.line)?null:t}catch{return null}}function ui(e){for(let t of e.split(`
111
111
  `)){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 gf(){return Ws()?.status??null}function $b(){if(process.env.JEST_WORKER_ID)return;let e=cf();try{if(z.mkdirSync(Q.dirname(e),{recursive:!0}),!jb(e))return;let t=process.argv[1]?Q.resolve(process.argv[1]):"";if(!t){zn();return}let n=ri(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),s=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},o=(0,of.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...s,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});o.once("error",zn),o.unref()}catch{zn()}}function _n(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 Pb=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function Ob(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,vc.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!Pb.test(o))return"";let i=`${n}${t.length}__`;return t.push(o),i}),s=new RegExp(`${n}(\\d+)__`,"g");return _n(r).replace(s,(o,i)=>t[Number(i)]??"")}function Nb(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${te(r||"",ee.green)}${te(s||"",ee.chrome)}`}function Gr(e){return`$${e.toFixed(2)}`}function Mb(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 s=t.split("/").filter(Boolean);t=s[s.length-1]||t}return t=t.replace(/^fal-ai\//,""),t=t.replace(/^fal-/,""),t=t.replace(/^or-/,""),t=t.split("/").filter(Boolean).map(s=>s.replace(/^v\d+(?:\.\d+)?-?/,"")||null).filter(s=>s!==null&&s.length>0).join(" "),t=t.replace(/_card$/,""),t.length>28&&(t=t.slice(0,28).trimEnd()),t||e}function Lb(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=_n(n.toUpperCase()),o=_n(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}var ee={get reset(){return $e().reset},get visaBlue(){return $e().visaBlue},get visaBlueSoft(){return $e().visaBlueSoft},get visaGold(){return $e().visaGold},get green(){return $e().green},get muted(){return $e().muted},get chrome(){return $e().chrome}};function te(e,t){return e.length===0||process.env.NO_COLOR||si()?e:`${t}${e}${ee.reset}`}function sf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cc(){let e=Jn.homedir();if(!e||!Q.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Q.resolve(e)}function Ub(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Db(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function jb(e){for(let t=0;t<2;t+=1){let n;try{return n=z.openSync(e,"wx"),z.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=z.statSync(e);if(Date.now()-s.mtimeMs<=_b)return!1;z.unlinkSync(e)}catch{}}finally{n!==void 0&&z.closeSync(n)}}return!1}function bc(e){return e instanceof Error?e.message:"unknown file system error"}function Wr(e,t){z.mkdirSync(Q.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,vc.randomBytes)(8).toString("hex")}.tmp`;try{z.writeFileSync(n,t),z.renameSync(n,e)}catch(r){try{z.unlinkSync(n)}catch{}throw r}}var Bb=1440*60*1e3;function fi(e,t){we.mkdirSync(De.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${_f.randomBytes(8).toString("hex")}.tmp`;try{we.writeFileSync(n,JSON.stringify(t,null,2)+`
112
- `),we.renameSync(n,e)}catch(r){try{we.unlinkSync(n)}catch{}throw r}}function hf(e){return`'${e.replace(/'/g,"'\\''")}'`}var Ac="# visa-cli-hud-v1";function mi(e,t){if(!e&&!t&&Fb())return`visa-cli config statusline ${Ac}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?De.resolve(r):"";return`${s?`${hf(n)} ${hf(s)} config statusline`:"visa-cli config statusline"} ${Ac}`}function Fb(){try{return(0,bf.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function bn(e){return typeof e!="string"?!1:e.includes(Ac)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Hb(){return"4.0.0-rc.16"}function pi(e){let t=De.dirname(De.resolve(e));return De.basename(t)===".claude"?De.dirname(t):vf.homedir()}function di(e,t){let n=De.relative(t,e);return!n.startsWith("..")&&!De.isAbsolute(n)?`~/${n}`:e}function Vb(e){return De.join(pi(e),".visa-cli","hud-self-heal.json")}function qb(e,t,n,r){try{if(!we.existsSync(e))return!1;let s=JSON.parse(we.readFileSync(e,"utf-8"));return s.version===t&&typeof s.checkedAt=="number"&&n-s.checkedAt<r}catch{return!1}}function Ec(e,t,n){try{fi(e,{version:t,checkedAt:n})}catch{}}function Kb(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function kc(e,t={}){let n=t.now??Date.now(),r=t.version??Hb(),s=t.stampPath??Vb(e),o=t.minIntervalMs??Bb,i=[],a=!1,c=!1;if(!t.force&&qb(s,r,n,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!we.existsSync(e))return Ec(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(we.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!bn(d))return Ec(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let f=(t.getCommand??mi)();if(d!==f&&(l.statusLine=Kb(u,f),fi(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!gi()){let m=pi(e);if(Xn(m).length>0){let h=Bt(null,m);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let v=h.rcPaths.map(I=>di(I,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${v}.`)}}}return Ec(s,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
112
+ `),we.renameSync(n,e)}catch(r){try{we.unlinkSync(n)}catch{}throw r}}function hf(e){return`'${e.replace(/'/g,"'\\''")}'`}var Ac="# visa-cli-hud-v1";function mi(e,t){if(!e&&!t&&Fb())return`visa-cli config statusline ${Ac}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?De.resolve(r):"";return`${s?`${hf(n)} ${hf(s)} config statusline`:"visa-cli config statusline"} ${Ac}`}function Fb(){try{return(0,bf.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function bn(e){return typeof e!="string"?!1:e.includes(Ac)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Hb(){return"4.0.0-rc.17"}function pi(e){let t=De.dirname(De.resolve(e));return De.basename(t)===".claude"?De.dirname(t):vf.homedir()}function di(e,t){let n=De.relative(t,e);return!n.startsWith("..")&&!De.isAbsolute(n)?`~/${n}`:e}function Vb(e){return De.join(pi(e),".visa-cli","hud-self-heal.json")}function qb(e,t,n,r){try{if(!we.existsSync(e))return!1;let s=JSON.parse(we.readFileSync(e,"utf-8"));return s.version===t&&typeof s.checkedAt=="number"&&n-s.checkedAt<r}catch{return!1}}function Ec(e,t,n){try{fi(e,{version:t,checkedAt:n})}catch{}}function Kb(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function kc(e,t={}){let n=t.now??Date.now(),r=t.version??Hb(),s=t.stampPath??Vb(e),o=t.minIntervalMs??Bb,i=[],a=!1,c=!1;if(!t.force&&qb(s,r,n,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!we.existsSync(e))return Ec(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(we.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!bn(d))return Ec(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let f=(t.getCommand??mi)();if(d!==f&&(l.statusLine=Kb(u,f),fi(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!gi()){let m=pi(e);if(Xn(m).length>0){let h=Bt(null,m);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let v=h.rcPaths.map(I=>di(I,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${v}.`)}}}return Ec(s,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
113
113
  `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function Gb(e,t){let n=pi(t),r=Xn(n);if(r.length===0)return e;let s=r.map(o=>di(o,n)).join(", ");return`${e}
114
114
  Note: a shell-prompt HUD block was detected in ${s}. If it is unintended, remove it with: visa-cli config hud disable shell`}function gi(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 yf(e,t){let n=pi(t),r=Xn(n);if(r.length===0)return e;let s=r.map(i=>di(i,n)).join(", ");if(gi())return`${e}
115
115
  Note: a legacy shell-prompt HUD block was detected in ${s}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let o=Bt(null,n);if(o.removed&&o.rcPaths&&o.rcPaths.length>0){let i=o.rcPaths.map(a=>di(a,n)).join(", ");return`${e}
@@ -129,7 +129,7 @@ ${a}`}function e0(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)
129
129
  `)}var zf="WARNING: This Visa Key is a bearer secret for headless API use. Touch ID will not be prompted when the key is used; anyone with the key can spend prepaid balance within the caps above until it expires or is revoked. Store it like a password and revoke it immediately if exposed.";function d0(e){let t=Math.max(5,...e.map(([o])=>o.length)),n=Math.max(5,...e.map(([,o])=>o.length)),r=`+-${"-".repeat(t)}-+-${"-".repeat(n)}-+`,s=(o,i)=>`| ${o.padEnd(t)} | ${i.padEnd(n)} |`;return[r,s("Field","Value"),r,...e.map(([o,i])=>s(o,i)),r]}function Jf(e,t={}){let n=t.authUrl??"https://auth.visacli.sh",r=[...u0().split(`
130
130
  `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...d0([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${Oc(e.daily_cap_cents)}/day`],["Total cap",Wf(e.total_cap_cents)],["Allowed tools",Yf(e.allowed_tools)]]),"","Guardrails",`- Spend: ${Oc(e.daily_cap_cents)}/day, ${Wf(e.total_cap_cents)} total`,`- Tools: ${Yf(e.allowed_tools)}`,"- Auth: X-Api-Key header; no OAuth handoff or per-call Touch ID","","Use it","Save this key now - it won't be shown again.","",`export VISAKEY_API_KEY=${e.key}`,"",`POST ${n}/v1/api/tools/{tool_name}/execute`,"Headers: X-Api-Key, Idempotency-Key, Content-Type: application/json"];return e.biometric_warning?r.push("",zf,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",zf),`${r.join(`
131
131
  `)}
132
- `}function Xf(e){return e.json===!0||e.isTTY!==!0}function Nc(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 Mc(e){if(e===!1)return null;if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--total-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e6)throw new Error("--total-cap must be between 1 and 10000 USD.");return n}function Zf(e,t){let n=Nc(e);if(n!==void 0)return n;if(Xf(t))return 500}function Qf(e,t){let n=Mc(e);if(n!==void 0)return n;if(Xf(t)||t.recommendedCapsAccepted===!0)return 2500}async function bt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var Qn=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},zr=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}},Vt=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}},vt=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}},he=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,s,o,i,a,c){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=s,this.paymentErrorClass=o,this.correlationId=i,this.transactionId=a,this.retryAfter=c}},it=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 em={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 Jr(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&&em[n]?em[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.`}qt();var h0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function rm(e,t){let n=nm(e),r=nm(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:y0(n.pre,r.pre)>0}function nm(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(h0);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function y0(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],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 wt(){return!!(sm(process.env.VISA_CLI_NO_UPDATE_CHECK)||sm(process.env.CI)||process.env.NODE_ENV==="test")}function sm(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}St();var k0="CARD_REENROLLMENT_REQUIRED",T0="https://auth.visacli.sh/enroll-card";function R0(){try{return new URL("/enroll-card",Se()).toString()}catch{return T0}}function I0(e){let t=R0();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 g.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var Sn="4.0.0-rc.16",$0=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;async function to(e){let t=null;try{t=await e.json()}catch{}return t&&(t.error_code==="TOOL_UPSTREAM_AUTH_FAILED"||typeof t.upstream_status=="number")?new Error(typeof t.error=="string"&&t.error?t.error:"The tool upstream rejected the request credentials."):new Error("Your session has expired. Run: visa-cli setup")}function no(e,t){let n=typeof t?.error=="string"&&t.error||typeof t?.message=="string"&&t.message||"";return n?new Error(n):e>=500||e===408||e===425||e===429?new Error(`Request failed (${e}). Try again.`):e===404?new Error(`Request failed (${e}) \u2014 not found; check the identifier or slug.`):new Error(`Request failed (${e}).`)}function P0(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 Gc(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var O0="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Xr(e){return typeof e=="string"?e.trim():""}function ro(e){let t=e&&typeof e=="object"?e:{},n=Xr(t.error)||Xr(t.message);if(!n)return O0;let r=Xr(t.error_code),s=[["surface",Xr(t.disabled_surface)],["flag",Xr(t.flag)],["correlation_id",Xr(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),o=s.length?` (${s.join(" ")})`:"";return r?`503 [${r}] ${n}${o}`:`503 ${n}${o}`}function so(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?$0.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(`
132
+ `}function Xf(e){return e.json===!0||e.isTTY!==!0}function Nc(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 Mc(e){if(e===!1)return null;if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--total-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e6)throw new Error("--total-cap must be between 1 and 10000 USD.");return n}function Zf(e,t){let n=Nc(e);if(n!==void 0)return n;if(Xf(t))return 500}function Qf(e,t){let n=Mc(e);if(n!==void 0)return n;if(Xf(t)||t.recommendedCapsAccepted===!0)return 2500}async function bt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var Qn=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},zr=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}},Vt=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}},vt=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}},he=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,s,o,i,a,c){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=s,this.paymentErrorClass=o,this.correlationId=i,this.transactionId=a,this.retryAfter=c}},it=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 em={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 Jr(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&&em[n]?em[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.`}qt();var h0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function rm(e,t){let n=nm(e),r=nm(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:y0(n.pre,r.pre)>0}function nm(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(h0);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function y0(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],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 wt(){return!!(sm(process.env.VISA_CLI_NO_UPDATE_CHECK)||sm(process.env.CI)||process.env.NODE_ENV==="test")}function sm(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}St();var k0="CARD_REENROLLMENT_REQUIRED",T0="https://auth.visacli.sh/enroll-card";function R0(){try{return new URL("/enroll-card",Se()).toString()}catch{return T0}}function I0(e){let t=R0();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 g.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var Sn="4.0.0-rc.17",$0=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;async function to(e){let t=null;try{t=await e.json()}catch{}return t&&(t.error_code==="TOOL_UPSTREAM_AUTH_FAILED"||typeof t.upstream_status=="number")?new Error(typeof t.error=="string"&&t.error?t.error:"The tool upstream rejected the request credentials."):new Error("Your session has expired. Run: visa-cli setup")}function no(e,t){let n=typeof t?.error=="string"&&t.error||typeof t?.message=="string"&&t.message||"";return n?new Error(n):e>=500||e===408||e===425||e===429?new Error(`Request failed (${e}). Try again.`):e===404?new Error(`Request failed (${e}) \u2014 not found; check the identifier or slug.`):new Error(`Request failed (${e}).`)}function P0(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 Gc(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var O0="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Xr(e){return typeof e=="string"?e.trim():""}function ro(e){let t=e&&typeof e=="object"?e:{},n=Xr(t.error)||Xr(t.message);if(!n)return O0;let r=Xr(t.error_code),s=[["surface",Xr(t.disabled_surface)],["flag",Xr(t.flag)],["correlation_id",Xr(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),o=s.length?` (${s.join(" ")})`:"";return r?`503 [${r}] ${n}${o}`:`503 ${n}${o}`}function so(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?$0.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(`
133
133
  `)}var Ke=class{constructor(t){this.getSessionToken=t;this.baseUrl=Se()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!wt()){let r=t.headers.get("X-Latest-Version");r&&rm(r,Sn)&&(this.lastSignals.updateAvailable={currentVersion:Sn,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return Sn}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Qn(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(ro(n))}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(so());let c={Authorization:`Bearer ${a}`};o&&(t==="GET"?c["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:o}),i&&(c["X-Visa-Meta-Tool"]=i),r&&(c["Content-Type"]="application/json");let l;try{l=await bt(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":Sn,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw new Error(Jr(d))}if(this.parseServerSignals(l),l.status===401)throw await to(l);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===k0){let f=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",p=I0(u?.reenroll_url),h=f?`${m} ending in ${f}`:"your card";throw new Error(`Please re-add ${h} to keep payments running. Open: ${p}`)}let d=Gc(u?.error_code);if(d)throw new it(u?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",d,{transactionId:typeof u?.transactionId=="string"?u.transactionId:void 0,retryable:!!u?.retryable,reconciliationRequired:u?.reconciliation_required!==!1});if(u?.declined){let f=Number(u.retryAfter??l.headers.get("Retry-After"));throw new he(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(f)&&f>0?f:void 0)}if(l.status===402){let f=u?.error||"Gateway returned 402",m=typeof u?.error_code=="string"?u.error_code:"";throw m==="SPENDING_LIMIT_EXCEEDED"||m==="DAILY_LIMIT_EXCEEDED"||m==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${f}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(f)}throw no(l.status,u)}return u}async shortcut(t,n,r,s,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s,o)}async shortcutWithSession(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(so());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Sn,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...n,...r};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await bt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(Jr(p))}if(this.parseServerSignals(d),d.status===401)throw await to(d);if(d.status===429){let p=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let v=Number(d.headers.get("Retry-After"))||1;throw new Vt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",v,d.status)}throw new Error(ro(m))}let p=P0(m?.error_code);if(p||d.status===410){let v=p??"BUDGET_CLOSED";throw new zr(m?.message||m?.error||"Your session was invalidated by the server.",v,{budgetId:n.session_budget_id,status:d.status})}if(m?.declined){let v=Number(m.retryAfter??d.headers.get("Retry-After"));throw new he(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(v)&&v>0?v:void 0)}let h=Gc(m?.error_code);throw h?new it(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):no(d.status,m)}return{data:m,voucherReceiptHeader:f}}async shortcutParentless(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(so());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Sn,"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}:{}};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await bt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(Jr(p))}if(this.parseServerSignals(d),d.status===401)throw await to(d);if(d.status===429){let p=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):d.status===404?new vt("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 p=typeof m?.error_code=="string"?m.error_code:void 0;if(d.status===410&&p==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new vt(m?.error||"Parentless single-call is not enabled on this server.",{status:d.status,serverErrorCode:p});if(d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let v=Number(d.headers.get("Retry-After"))||1;throw new Vt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",v,d.status)}throw new Error(ro(m))}if(m?.declined){let v=Number(m.retryAfter??d.headers.get("Retry-After"));throw new he(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(v)&&v>0?v:void 0)}let h=Gc(m?.error_code);throw h?new it(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):no(d.status,m)}return{data:m,voucherReceiptHeader:f}}async batchOpen(t){let n="/v1/batch/open",r=await this.getSessionToken();if(!r)throw new Error(so());let s={Authorization:`Bearer ${r}`,"X-Visa-CLI-Version":Sn,"X-Source":"cli","Content-Type":"application/json"},o={...t.attestation?{attestation:t.attestation}:{},nonce:t.nonce,approved_total_cents:t.approved_total_cents,batch_id:t.batch_id},i;try{i=await bt(`${this.baseUrl}${n}`,{method:"POST",headers:s,body:JSON.stringify(o),timeoutMs:void 0})}catch(u){throw new Error(Jr(u))}if(this.parseServerSignals(i),i.status===401)throw await to(i);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 vt("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===410&&u==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new vt(a?.error||"Parentless batch is not enabled on this server.",{status:i.status,serverErrorCode:u});if(i.status===503)throw new Error(ro(a));if(a?.declined){let d=Number(a.retryAfter??i.headers.get("Retry-After"));throw new he(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 no(i.status,a)}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,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(so());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Sn,"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}:{}};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await bt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(Jr(p))}if(this.parseServerSignals(d),d.status===401)throw await to(d);if(d.status===429){let p=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let p=Number(d.headers.get("Retry-After"))||1;throw new Vt(m?.message||m?.error||"Batch parent is being modified by another request. Retry shortly.",p,d.status)}throw new Error(ro(m))}if(m?.declined){let p=Number(m.retryAfter??d.headers.get("Retry-After"));throw new he(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(p)&&p>0?p:void 0)}throw no(d.status,m)}return{data:m,voucherReceiptHeader:f}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,s){let o=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),s?.limit!=null&&i.set("limit",String(s.limit)),s?.offset!=null&&i.set("offset",String(s.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,o)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async merchantDirectorySearch(t,n){let r=new URLSearchParams({provider:t.provider,q:t.q,protocol:t.protocol,max_price_usd:t.maxPriceUsd,limit:String(t.limit),offset:String(t.offset)});return this.request("GET",`/v1/merchant-directory/search?${r.toString()}`,void 0,void 0,n)}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await bt(`${this.baseUrl}/v1/platform/merchants/public`,{method:"GET",timeoutMs:8e3});if(!t.ok)return[];let n=await t.json();return Array.isArray(n.merchants)?n.merchants:[]}catch{return[]}}async getPublicMerchantDiscover(t){try{let n=await bt(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let s=r.toString(),o=s?`/v1/transactions?${s}`:"/v1/transactions";return this.request("GET",o,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,n){return this.request("POST","/v1/attestation-key",{publicKey:t,...n?{attestation:n}:{}})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async getPendingWebAuthenticators(t){return this.request("GET","/v1/webauthn/pending",void 0,void 0,t)}async authorizeWebAuthenticator(t,n){return this.request("POST","/v1/webauthn/authorize",t,void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(t){let n=new URLSearchParams;t?.limit!=null&&n.set("limit",String(t.limit)),t?.startingAfter!=null&&n.set("starting_after",String(t.startingAfter)),t?.endingBefore!=null&&n.set("ending_before",String(t.endingBefore));let r=n.toString();return this.request("GET",r?`/v1/api/keys?${r}`:"/v1/api/keys")}async listAllAppApiKeys(){let t=[],n=new Set,r,s=null,o=0;for(;;){let i=await this.listAppApiKeys({limit:100,...r!==void 0?{startingAfter:r}:{}});if(o+=1,s=i,t.push(...i.keys??[]),!i.has_more)break;if(i.next_cursor==null)throw new Error("API key pagination response did not include next_cursor.");if(n.has(i.next_cursor))throw new Error("API key pagination cursor did not advance.");n.add(i.next_cursor),r=i.next_cursor}return{...s??{success:!0,keys:[]},keys:t,limit:100,has_more:!1,next_cursor:null,previous_cursor:null,pages:o}}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};function oo(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function _m(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 ym(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function N0(e){let t=new Map;for(let n of e){let r=n.category||"other",s=t.get(r)??[];s.push(n),t.set(r,s)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function M0(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function L0(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function U0(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 bm(e){let t=M0(e),n=7,r=L0(e),s=U0(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(s,32))}`);for(let o of e)console.log(` ${o.id.padEnd(t)} ${oo(o.priceCents,o.priceDisplay).padEnd(n)} ${ym(o.category||"other",r).padEnd(r)} ${ym(_m(o),s)}`)}function vm(e){console.log(`
134
134
  Merchant tools
135
135
  `),bm(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 Wc(e){console.log(`
@@ -140,9 +140,9 @@ ${e} tools
140
140
  `),bm(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>\`
141
141
  `)}function Yc(e){if(e.count<=0)return;let t=[],n=e.byReason.kill_switch??0,r=e.byReason.flag_state_unknown??0;n>0&&t.push(`${n} suppressed by kill switch`),r>0&&t.push(`${r} suppressed while feature-flag store is unreachable`);let s=e.count-n-r;s>0&&t.push(`${s} unavailable`);let o=t.length>0?t.join(", "):`${e.count} hidden`;console.log(`
142
142
  Hidden: ${o}.`),n>0&&console.log("Inspect: `visa-cli tools --json` with query params `?available=all`, or check the admin Tool Hub flag list.")}var C={};Fr(C,{BRAND:()=>lv,DIRTY:()=>nr,EMPTY_PATH:()=>F0,INVALID:()=>D,NEVER:()=>Wv,OK:()=>Pe,ParseStatus:()=>Ae,Schema:()=>H,ZodAny:()=>En,ZodArray:()=>zt,ZodBigInt:()=>sr,ZodBoolean:()=>or,ZodBranded:()=>ao,ZodCatch:()=>hr,ZodDate:()=>ir,ZodDefault:()=>gr,ZodDiscriminatedUnion:()=>ki,ZodEffects:()=>Je,ZodEnum:()=>mr,ZodError:()=>He,ZodFirstPartyTypeKind:()=>j,ZodFunction:()=>Ri,ZodIntersection:()=>ur,ZodIssueCode:()=>S,ZodLazy:()=>dr,ZodLiteral:()=>fr,ZodMap:()=>rs,ZodNaN:()=>os,ZodNativeEnum:()=>pr,ZodNever:()=>ct,ZodNull:()=>cr,ZodNullable:()=>Et,ZodNumber:()=>rr,ZodObject:()=>Ve,ZodOptional:()=>Ye,ZodParsedType:()=>k,ZodPipeline:()=>co,ZodPromise:()=>An,ZodReadonly:()=>yr,ZodRecord:()=>Ti,ZodSchema:()=>H,ZodSet:()=>ss,ZodString:()=>Cn,ZodSymbol:()=>ts,ZodTransformer:()=>Je,ZodTuple:()=>Ct,ZodType:()=>H,ZodUndefined:()=>ar,ZodUnion:()=>lr,ZodUnknown:()=>Yt,ZodVoid:()=>ns,addIssueToContext:()=>E,any:()=>_v,array:()=>Sv,bigint:()=>mv,boolean:()=>Pm,coerce:()=>Gv,custom:()=>Rm,date:()=>pv,datetimeRegex:()=>km,defaultErrorMap:()=>Gt,discriminatedUnion:()=>Av,effect:()=>Dv,enum:()=>Mv,function:()=>Pv,getErrorMap:()=>Zr,getParsedType:()=>xt,instanceof:()=>dv,intersection:()=>kv,isAborted:()=>Ei,isAsync:()=>Qr,isDirty:()=>Ai,isValid:()=>xn,late:()=>uv,lazy:()=>Ov,literal:()=>Nv,makeIssue:()=>io,map:()=>Iv,nan:()=>fv,nativeEnum:()=>Lv,never:()=>vv,null:()=>yv,nullable:()=>Bv,number:()=>$m,object:()=>xv,objectUtil:()=>zc,oboolean:()=>Kv,onumber:()=>qv,optional:()=>jv,ostring:()=>Vv,pipeline:()=>Hv,preprocess:()=>Fv,promise:()=>Uv,quotelessJson:()=>D0,record:()=>Rv,set:()=>$v,setErrorMap:()=>B0,strictObject:()=>Cv,string:()=>Im,symbol:()=>gv,transformer:()=>Dv,tuple:()=>Tv,undefined:()=>hv,union:()=>Ev,unknown:()=>bv,util:()=>V,void:()=>wv});var V;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},e.getValidEnumValues=s=>{let o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(let i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(V||(V={}));var zc;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(zc||(zc={}));var k=V.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xt=e=>{switch(typeof e){case"undefined":return k.undefined;case"string":return k.string;case"number":return Number.isNaN(e)?k.nan:k.number;case"boolean":return k.boolean;case"function":return k.function;case"bigint":return k.bigint;case"symbol":return k.symbol;case"object":return Array.isArray(e)?k.array:e===null?k.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?k.promise:typeof Map<"u"&&e instanceof Map?k.map:typeof Set<"u"&&e instanceof Set?k.set:typeof Date<"u"&&e instanceof Date?k.date:k.object;default:return k.unknown}};var S=V.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"]),D0=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),He=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,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 s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,V.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};He.create=e=>new He(e);var j0=(e,t)=>{let n;switch(e.code){case S.invalid_type:e.received===k.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case S.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,V.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:n=`Unrecognized key(s) in object: ${V.joinValues(e.keys,", ")}`;break;case S.invalid_union:n="Invalid input";break;case S.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${V.joinValues(e.options)}`;break;case S.invalid_enum_value:n=`Invalid enum value. Expected ${V.joinValues(e.options)}, received '${e.received}'`;break;case S.invalid_arguments:n="Invalid function arguments";break;case S.invalid_return_type:n="Invalid function return type";break;case S.invalid_date:n="Invalid date";break;case S.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}"`:V.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case S.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 S.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 S.custom:n="Invalid input";break;case S.invalid_intersection_types:n="Intersection results could not be merged";break;case S.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case S.not_finite:n="Number must be finite";break;default:n=t.defaultError,V.assertNever(e)}return{message:n}},Gt=j0;var Sm=Gt;function B0(e){Sm=e}function Zr(){return Sm}var io=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:t,defaultError:a}).message;return{...s,path:o,message:a}},F0=[];function E(e,t){let n=Zr(),r=io({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Gt?void 0:Gt].filter(s=>!!s)});e.common.issues.push(r)}var Ae=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return D;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return D;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}},D=Object.freeze({status:"aborted"}),nr=e=>({status:"dirty",value:e}),Pe=e=>({status:"valid",value:e}),Ei=e=>e.status==="aborted",Ai=e=>e.status==="dirty",xn=e=>e.status==="valid",Qr=e=>typeof Promise<"u"&&e instanceof Promise;var N;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(N||(N={}));var ze=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},xm=(e,t)=>{if(xn(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 He(e.common.issues);return this._error=n,this._error}}};function B(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>{let{message: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:s}}var H=class{get description(){return this._def.description}_getType(t){return xt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:xt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Ae,ctx:{common:t.parent.common,data:t.data,parsedType:xt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Qr(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:xt(t)},s=this._parseSync({data:t,path:r.path,parent:r});return xm(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return xn(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=>xn(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:xt(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Qr(s)?s:Promise.resolve(s));return xm(r,o)}refine(t,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=t(s),a=()=>o.addIssue({code:S.custom,...r(s)});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,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new Je({schema:this,typeName:j.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 Ye.create(this,this._def)}nullable(){return Et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zt.create(this)}promise(){return An.create(this,this._def)}or(t){return lr.create([this,t],this._def)}and(t){return ur.create(this,t,this._def)}transform(t){return new Je({...B(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new gr({...B(this._def),innerType:this,defaultValue:n,typeName:j.ZodDefault})}brand(){return new ao({typeName:j.ZodBranded,type:this,...B(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new hr({...B(this._def),innerType:this,catchValue:n,typeName:j.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return co.create(this,t)}readonly(){return yr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},H0=/^c[^\s-]{8,}$/i,V0=/^[0-9a-z]+$/,q0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,K0=/^[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,G0=/^[a-z0-9_-]{21}$/i,W0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Y0=/^[-+]?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)?)??$/,z0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,J0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Jc,X0=/^(?:(?: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])$/,Z0=/^(?:(?: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])$/,Q0=/^(([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]))$/,ev=/^(([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])$/,tv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Em="((\\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])))",rv=new RegExp(`^${Em}$`);function Am(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 sv(e){return new RegExp(`^${Am(e)}$`)}function km(e){let t=`${Em}T${Am(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 ov(e,t){return!!((t==="v4"||!t)&&X0.test(e)||(t==="v6"||!t)&&Q0.test(e))}function iv(e,t){if(!W0.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function av(e,t){return!!((t==="v4"||!t)&&Z0.test(e)||(t==="v6"||!t)&&ev.test(e))}var Cn=class e extends H{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==k.string){let o=this._getOrReturnCtx(t);return E(o,{code:S.invalid_type,expected:k.string,received:o.parsedType}),D}let r=new Ae,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),E(s,{code:S.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),E(s,{code:S.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,a=t.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(t,s),i?E(s,{code:S.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&E(s,{code:S.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")z0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"email",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Jc||(Jc=new RegExp(J0,"u")),Jc.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"emoji",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")K0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"uuid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")G0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"nanoid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")H0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"cuid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")V0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"cuid2",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")q0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"ulid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),E(s,{validation:"url",code:S.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"regex",code:S.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),E(s,{code:S.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),E(s,{code:S.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),E(s,{code:S.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?km(o).test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:S.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?rv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:S.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?sv(o).test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:S.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Y0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"duration",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?ov(t.data,o.version)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"ip",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?iv(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"jwt",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?av(t.data,o.version)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"cidr",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?tv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"base64",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?nv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"base64url",code:S.invalid_string,message:o.message}),r.dirty()):V.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:S.invalid_string,...N.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...N.errToObj(t)})}url(t){return this._addCheck({kind:"url",...N.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...N.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...N.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...N.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...N.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...N.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...N.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...N.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...N.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...N.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...N.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...N.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,...N.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,...N.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...N.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...N.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...N.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...N.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...N.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...N.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...N.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...N.errToObj(n)})}nonempty(t){return this.min(1,N.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}};Cn.create=e=>new Cn({checks:[],typeName:j.ZodString,coerce:e?.coerce??!1,...B(e)});function cv(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return o%i/10**s}var rr=class e extends H{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==k.number){let o=this._getOrReturnCtx(t);return E(o,{code:S.invalid_type,expected:k.number,received:o.parsedType}),D}let r,s=new Ae;for(let o of this._def.checks)o.kind==="int"?V.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:S.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:S.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:S.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?cv(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),E(r,{code:S.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:S.not_finite,message:o.message}),s.dirty()):V.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,N.toString(n))}gt(t,n){return this.setLimit("min",t,!1,N.toString(n))}lte(t,n){return this.setLimit("max",t,!0,N.toString(n))}lt(t,n){return this.setLimit("max",t,!1,N.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:N.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:N.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:N.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.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"&&V.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)}};rr.create=e=>new rr({checks:[],typeName:j.ZodNumber,coerce:e?.coerce||!1,...B(e)});var sr=class e extends H{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==k.bigint)return this._getInvalidInput(t);let r,s=new Ae;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:S.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:S.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),E(r,{code:S.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):V.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return E(n,{code:S.invalid_type,expected:k.bigint,received:n.parsedType}),D}gte(t,n){return this.setLimit("min",t,!0,N.toString(n))}gt(t,n){return this.setLimit("min",t,!1,N.toString(n))}lte(t,n){return this.setLimit("max",t,!0,N.toString(n))}lt(t,n){return this.setLimit("max",t,!1,N.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:N.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}};sr.create=e=>new sr({checks:[],typeName:j.ZodBigInt,coerce:e?.coerce??!1,...B(e)});var or=class extends H{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==k.boolean){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:k.boolean,received:r.parsedType}),D}return Pe(t.data)}};or.create=e=>new or({typeName:j.ZodBoolean,coerce:e?.coerce||!1,...B(e)});var ir=class e extends H{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==k.date){let o=this._getOrReturnCtx(t);return E(o,{code:S.invalid_type,expected:k.date,received:o.parsedType}),D}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return E(o,{code:S.invalid_date}),D}let r=new Ae,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),E(s,{code:S.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),E(s,{code:S.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):V.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:N.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:N.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}};ir.create=e=>new ir({checks:[],coerce:e?.coerce||!1,typeName:j.ZodDate,...B(e)});var ts=class extends H{_parse(t){if(this._getType(t)!==k.symbol){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:k.symbol,received:r.parsedType}),D}return Pe(t.data)}};ts.create=e=>new ts({typeName:j.ZodSymbol,...B(e)});var ar=class extends H{_parse(t){if(this._getType(t)!==k.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:k.undefined,received:r.parsedType}),D}return Pe(t.data)}};ar.create=e=>new ar({typeName:j.ZodUndefined,...B(e)});var cr=class extends H{_parse(t){if(this._getType(t)!==k.null){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:k.null,received:r.parsedType}),D}return Pe(t.data)}};cr.create=e=>new cr({typeName:j.ZodNull,...B(e)});var En=class extends H{constructor(){super(...arguments),this._any=!0}_parse(t){return Pe(t.data)}};En.create=e=>new En({typeName:j.ZodAny,...B(e)});var Yt=class extends H{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Pe(t.data)}};Yt.create=e=>new Yt({typeName:j.ZodUnknown,...B(e)});var ct=class extends H{_parse(t){let n=this._getOrReturnCtx(t);return E(n,{code:S.invalid_type,expected:k.never,received:n.parsedType}),D}};ct.create=e=>new ct({typeName:j.ZodNever,...B(e)});var ns=class extends H{_parse(t){if(this._getType(t)!==k.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:k.void,received:r.parsedType}),D}return Pe(t.data)}};ns.create=e=>new ns({typeName:j.ZodVoid,...B(e)});var zt=class e extends H{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==k.array)return E(n,{code:S.invalid_type,expected:k.array,received:n.parsedType}),D;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(E(n,{code:i?S.too_big:S.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(E(n,{code:S.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(E(n,{code:S.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new ze(n,i,n.path,a)))).then(i=>Ae.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new ze(n,i,n.path,a)));return Ae.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:N.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:N.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:N.toString(n)}})}nonempty(t){return this.min(1,t)}};zt.create=(e,t)=>new zt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...B(t)});function es(e){if(e instanceof Ve){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ye.create(es(r))}return new Ve({...e._def,shape:()=>t})}else return e instanceof zt?new zt({...e._def,type:es(e.element)}):e instanceof Ye?Ye.create(es(e.unwrap())):e instanceof Et?Et.create(es(e.unwrap())):e instanceof Ct?Ct.create(e.items.map(t=>es(t))):e}var Ve=class e extends H{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=V.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==k.object){let l=this._getOrReturnCtx(t);return E(l,{code:S.invalid_type,expected:k.object,received:l.parsedType}),D}let{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof ct&&this._def.unknownKeys==="strip"))for(let l in s.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=o[l],d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ze(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof ct){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")a.length>0&&(E(s,{code:S.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=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ze(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,f=await u.value;l.push({key:d,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>Ae.mergeObjectSync(r,l)):Ae.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return N.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:N.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:j.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 V.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 V.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return es(this)}partial(t){let n={};for(let r of V.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of V.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ye;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return Tm(V.objectKeys(this.shape))}};Ve.create=(e,t)=>new Ve({shape:()=>e,unknownKeys:"strip",catchall:ct.create(),typeName:j.ZodObject,...B(t)});Ve.strictCreate=(e,t)=>new Ve({shape:()=>e,unknownKeys:"strict",catchall:ct.create(),typeName:j.ZodObject,...B(t)});Ve.lazycreate=(e,t)=>new Ve({shape:e,unknownKeys:"strip",catchall:ct.create(),typeName:j.ZodObject,...B(t)});var lr=class extends H{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new He(a.ctx.common.issues));return E(n,{code:S.invalid_union,unionErrors:i}),D}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let 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"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new He(c));return E(n,{code:S.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};lr.create=(e,t)=>new lr({options:e,typeName:j.ZodUnion,...B(t)});var Wt=e=>e instanceof dr?Wt(e.schema):e instanceof Je?Wt(e.innerType()):e instanceof fr?[e.value]:e instanceof mr?e.options:e instanceof pr?V.objectValues(e.enum):e instanceof gr?Wt(e._def.innerType):e instanceof ar?[void 0]:e instanceof cr?[null]:e instanceof Ye?[void 0,...Wt(e.unwrap())]:e instanceof Et?[null,...Wt(e.unwrap())]:e instanceof ao||e instanceof yr?Wt(e.unwrap()):e instanceof hr?Wt(e._def.innerType):[],ki=class e extends H{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==k.object)return E(n,{code:S.invalid_type,expected:k.object,received:n.parsedType}),D;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(E(n,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let o of n){let i=Wt(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,o)}}return new e({typeName:j.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...B(r)})}};function Xc(e,t){let n=xt(e),r=xt(t);if(e===t)return{valid:!0,data:e};if(n===k.object&&r===k.object){let s=V.objectKeys(t),o=V.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(let a of o){let c=Xc(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===k.array&&r===k.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let o=0;o<e.length;o++){let i=e[o],a=t[o],c=Xc(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===k.date&&r===k.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var ur=class extends H{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(Ei(o)||Ei(i))return D;let a=Xc(o.value,i.value);return a.valid?((Ai(o)||Ai(i))&&n.dirty(),{status:n.value,value:a.data}):(E(r,{code:S.invalid_intersection_types}),D)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};ur.create=(e,t,n)=>new ur({left:e,right:t,typeName:j.ZodIntersection,...B(n)});var Ct=class e extends H{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==k.array)return E(r,{code:S.invalid_type,expected:k.array,received:r.parsedType}),D;if(r.data.length<this._def.items.length)return E(r,{code:S.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&r.data.length>this._def.items.length&&(E(r,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ze(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Ae.mergeArray(n,i)):Ae.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ct.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ct({items:e,typeName:j.ZodTuple,rest:null,...B(t)})};var Ti=class e extends H{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==k.object)return E(r,{code:S.invalid_type,expected:k.object,received:r.parsedType}),D;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new ze(r,a,r.path,a)),value:i._parse(new ze(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ae.mergeObjectAsync(n,s):Ae.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof H?new e({keyType:t,valueType:n,typeName:j.ZodRecord,...B(r)}):new e({keyType:Cn.create(),valueType:t,typeName:j.ZodRecord,...B(n)})}},rs=class extends H{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==k.map)return E(r,{code:S.invalid_type,expected:k.map,received:r.parsedType}),D;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:s._parse(new ze(r,a,r.path,[l,"key"])),value:o._parse(new ze(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 D;(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 D;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};rs.create=(e,t,n)=>new rs({valueType:t,keyType:e,typeName:j.ZodMap,...B(n)});var ss=class e extends H{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==k.set)return E(r,{code:S.invalid_type,expected:k.set,received:r.parsedType}),D;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(E(r,{code:S.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(E(r,{code:S.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return D;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>o._parse(new ze(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:N.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:N.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};ss.create=(e,t)=>new ss({valueType:e,minSize:null,maxSize:null,typeName:j.ZodSet,...B(t)});var Ri=class e extends H{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==k.function)return E(n,{code:S.invalid_type,expected:k.function,received:n.parsedType}),D;function r(a,c){return io({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zr(),Gt].filter(l=>!!l),issueData:{code:S.invalid_arguments,argumentsError:c}})}function s(a,c){return io({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zr(),Gt].filter(l=>!!l),issueData:{code:S.invalid_return_type,returnTypeError:c}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof An){let a=this;return Pe(async function(...c){let l=new He([]),u=await a._def.args.parseAsync(c,o).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,o).catch(m=>{throw l.addIssue(s(d,m)),l})})}else{let a=this;return Pe(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new He([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new He([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ct.create(t).rest(Yt.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||Ct.create([]).rest(Yt.create()),returns:n||Yt.create(),typeName:j.ZodFunction,...B(r)})}},dr=class extends H{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})}};dr.create=(e,t)=>new dr({getter:e,typeName:j.ZodLazy,...B(t)});var fr=class extends H{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return E(n,{received:n.data,code:S.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:t.data}}get value(){return this._def.value}};fr.create=(e,t)=>new fr({value:e,typeName:j.ZodLiteral,...B(t)});function Tm(e,t){return new mr({values:e,typeName:j.ZodEnum,...B(t)})}var mr=class e extends H{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return E(n,{expected:V.joinValues(r),received:n.parsedType,code:S.invalid_type}),D}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 E(n,{received:n.data,code:S.invalid_enum_value,options:r}),D}return Pe(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})}};mr.create=Tm;var pr=class extends H{_parse(t){let n=V.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==k.string&&r.parsedType!==k.number){let s=V.objectValues(n);return E(r,{expected:V.joinValues(s),received:r.parsedType,code:S.invalid_type}),D}if(this._cache||(this._cache=new Set(V.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=V.objectValues(n);return E(r,{received:r.data,code:S.invalid_enum_value,options:s}),D}return Pe(t.data)}get enum(){return this._def.values}};pr.create=(e,t)=>new pr({values:e,typeName:j.ZodNativeEnum,...B(t)});var An=class extends H{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==k.promise&&n.common.async===!1)return E(n,{code:S.invalid_type,expected:k.promise,received:n.parsedType}),D;let r=n.parsedType===k.promise?n.data:Promise.resolve(n.data);return Pe(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};An.create=(e,t)=>new An({type:e,typeName:j.ZodPromise,...B(t)});var Je=class extends H{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:i=>{E(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return D;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?D:c.status==="dirty"?nr(c.value):n.value==="dirty"?nr(c.value):c});{if(n.value==="aborted")return D;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?D:a.status==="dirty"?nr(a.value):n.value==="dirty"?nr(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);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"?D:(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"?D:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!xn(i))return D;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>xn(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):D);V.assertNever(s)}};Je.create=(e,t,n)=>new Je({schema:e,typeName:j.ZodEffects,effect:t,...B(n)});Je.createWithPreprocess=(e,t,n)=>new Je({schema:t,effect:{type:"preprocess",transform:e},typeName:j.ZodEffects,...B(n)});var Ye=class extends H{_parse(t){return this._getType(t)===k.undefined?Pe(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ye.create=(e,t)=>new Ye({innerType:e,typeName:j.ZodOptional,...B(t)});var Et=class extends H{_parse(t){return this._getType(t)===k.null?Pe(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Et.create=(e,t)=>new Et({innerType:e,typeName:j.ZodNullable,...B(t)});var gr=class extends H{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===k.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};gr.create=(e,t)=>new gr({innerType:e,typeName:j.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...B(t)});var hr=class extends H{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Qr(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new He(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new He(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};hr.create=(e,t)=>new hr({innerType:e,typeName:j.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...B(t)});var os=class extends H{_parse(t){if(this._getType(t)!==k.nan){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:k.nan,received:r.parsedType}),D}return{status:"valid",value:t.data}}};os.create=e=>new os({typeName:j.ZodNaN,...B(e)});var lv=Symbol("zod_brand"),ao=class extends H{_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}},co=class e extends H{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?D:o.status==="dirty"?(n.dirty(),nr(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?D:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:j.ZodPipeline})}},yr=class extends H{_parse(t){let n=this._def.innerType._parse(t),r=s=>(xn(s)&&(s.value=Object.freeze(s.value)),s);return Qr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};yr.create=(e,t)=>new yr({innerType:e,typeName:j.ZodReadonly,...B(t)});function Cm(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Rm(e,t={},n){return e?En.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=Cm(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=Cm(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):En.create()}var uv={object:Ve.lazycreate},j;(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"})(j||(j={}));var dv=(e,t={message:`Input not instance of ${e.name}`})=>Rm(n=>n instanceof e,t),Im=Cn.create,$m=rr.create,fv=os.create,mv=sr.create,Pm=or.create,pv=ir.create,gv=ts.create,hv=ar.create,yv=cr.create,_v=En.create,bv=Yt.create,vv=ct.create,wv=ns.create,Sv=zt.create,xv=Ve.create,Cv=Ve.strictCreate,Ev=lr.create,Av=ki.create,kv=ur.create,Tv=Ct.create,Rv=Ti.create,Iv=rs.create,$v=ss.create,Pv=Ri.create,Ov=dr.create,Nv=fr.create,Mv=mr.create,Lv=pr.create,Uv=An.create,Dv=Je.create,jv=Ye.create,Bv=Et.create,Fv=Je.createWithPreprocess,Hv=co.create,Vv=()=>Im().optional(),qv=()=>$m().optional(),Kv=()=>Pm().optional(),Gv={string:(e=>Cn.create({...e,coerce:!0})),number:(e=>rr.create({...e,coerce:!0})),boolean:(e=>or.create({...e,coerce:!0})),bigint:(e=>sr.create({...e,coerce:!0})),date:(e=>ir.create({...e,coerce:!0}))};var Wv=D;var Yv=/^[A-Za-z0-9._-]+$/,zv=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,Om=new Set([".",".."]),je=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function Jv(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 je(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=n?e.slice(1,-2):e.slice(1,-1);if(!zv.test(s))throw new je(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=s.split("|");if(o.some(i=>Om.has(i)))throw new je(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:o}}if(Yv.test(e)){if(Om.has(e))throw new je(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new je(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function Xv(e){if(typeof e!="string"||e.length===0)throw new je("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new je("must start with '/'",e);if(e.slice(1).includes("//"))throw new je("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new je("must not end with '/'",e);let n=e.slice(1).split("/").map(o=>Jv(o,e));if(n.filter(o=>o.kind==="multi").length>1)throw new je("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new je("'**' may not be the first segment (a literal prefix anchor is required)",e);let s=n.findIndex(o=>o.kind==="alt-optional");if(s!==-1&&s!==n.length-1)throw new je("optional alternation '(...)?' is only allowed as the final segment",e);return n}function Zc(e){Xv(e)}var Nm=["tempo","mpp_self","merchant_self"],Mm=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],Lm=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],Um=["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 el=C.object({inputPerMillion:C.number().positive(),outputPerMillion:C.number().positive(),contextWindow:C.number().int().positive().optional(),maxOutput:C.number().int().positive().optional(),perRequestFeeCents:C.number().nonnegative().optional()}),Zv=C.object({strategy:C.enum(["flat","token","band"]).optional(),pricingModel:C.enum(["per-call","per-token","band"]).optional(),priceCents:C.number().nonnegative().optional(),currency:C.string().optional(),display:C.string().optional(),estimate:C.boolean().optional(),source:C.string().optional(),priceBand:C.record(C.unknown()).optional(),tokenPricing:el.optional()}).passthrough(),tl=C.discriminatedUnion("type",[C.object({type:C.literal("shortcut"),routedPath:C.string().min(1).startsWith("/")}),C.object({type:C.literal("custom"),merchantSlug:C.string().min(1),subPath:C.string().optional()}),C.object({type:C.literal("local"),fn:C.string().min(1)}),C.object({type:C.literal("read")})]),nl=C.object({amount:C.number().nonnegative(),currency:C.string().length(3).optional(),display:C.string().optional(),free:C.boolean().optional(),batchDiscount:C.number().min(0).max(100).optional()}),Dm=C.object({attestation:C.boolean().optional(),rateLimitMs:C.number().positive().optional()}),jm=C.object({displayName:C.string().optional(),feedbackEligible:C.boolean().optional(),suggestionEligible:C.boolean().optional(),batchable:C.boolean().optional()}),Bm=C.object({enabled:C.boolean().optional(),gatewayPath:C.string().min(1).startsWith("/").optional(),method:C.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:C.number().int().positive().max(12e4).optional()}).strict(),Qv=C.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),ew=120,tw=120,nw=1200,rw=/^[^\u0000-\u001F\u007F]+$/;function Qc(e,t){return C.string().min(1).max(e).regex(rw,`${t} must not contain control characters`)}var rl={id:C.string().min(1),name:Qc(ew,"name"),description:Qc(nw,"description"),provider:C.string().min(1),model:C.string().min(1),category:Qv,priceCents:C.number().nonnegative(),inputSchema:C.record(C.unknown()),gatewayUrl:C.string().min(1),merchantName:Qc(tw,"merchantName"),isAsync:C.boolean().optional(),pollUrl:C.string().optional(),pollInterval:C.number().positive().optional(),pollTimeout:C.number().positive().optional(),tags:C.array(C.string()).optional(),tokenPricing:el.optional(),priceDisplay:C.string().optional(),pricingModel:C.enum(["per-call","per-token","band"]).optional(),pricingInfo:Zv.optional(),status:C.enum(["available","unavailable"]).optional(),handler:tl.optional(),pricing:nl.optional(),security:Dm.optional(),engagement:jm.optional(),gatewayConfig:Bm.optional(),freeReadPathPattern:C.string().optional().superRefine((e,t)=>{if(e!==void 0)try{Zc(e)}catch(n){t.addIssue({code:C.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:C.boolean().optional(),beta:C.boolean().optional(),deprecated:C.boolean().optional(),internal:C.boolean().optional(),employeeOnly:C.boolean().optional(),employeeOnlyRolloutFlag:C.string().min(1).max(100).optional(),replacementTool:C.string().optional(),minCliVersion:C.string().optional(),sunsetAt:C.string().optional(),rail:C.enum(Nm).optional(),executionKind:C.enum(Mm).optional(),resultKind:C.enum(Lm).optional(),extractionMode:C.enum(Um).optional(),pricingStrategy:C.enum(["flat","token","band"]).optional()},Fm=C.object({...rl,dispatch:C.literal("routed"),routedPath:C.string().min(1).startsWith("/")}).strict(),Hm=C.object({...rl,dispatch:C.literal("enveloped")}).strict(),Vm=C.object({...rl,handler:tl,pricing:nl}).strict(),qm=C.union([C.discriminatedUnion("dispatch",[Fm,Hm]),Vm]);var iw="https://fal.run",Ym="https://openrouter.mpp.tempo.xyz",ol=1024,$i=8192,aw=4096,cw=10;function lw(e){return e>=cw?aw:$i}function zm(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):ol;return Math.min(n,t)}var uw=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function Jm(e){for(let t of uw)delete e[t];return e}function dw(e){let{attestation:t,tool_id:n,...r}=e;return Jm(r)}var Km={"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 Ii(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i=Jm({...o});return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&Km[r]&&(i.image_size=Km[r]),i)}function fw(e){let{attestation:t,tool_id:n,...r}=e;return r}function Gm(e){let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let s=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-s)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]}function mw(e,t,n,r,s,o,i,a,c){return{id:e,name:t,description:n,provider:r,model:s.replace(/^\//,""),category:o,gatewayUrl:`https://${r}${s}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:s},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...c}}function pw(e,t,n,r,s,o,i,a){return mw(e,t,n,"suno-ai",r,s,o,i,{merchantName:"Suno AI",...a})}function ye(e,t,n,r,s,o,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:s,priceCents:o,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${iw}/${r}`,merchantName:"fal.ai",buildBody:dw,tags:[],...a}}function Xm(e,t=$i){return n=>{let{attestation:r,tool_id:s,model:o,prompt:i,system_prompt:a,max_tokens:c,max_completion_tokens:l,n:u,messages:d,temperature:f,...m}=n;return typeof o=="string"&&o.length>0&&o!==e&&console.warn("[catalog] openrouterBuildBody: caller model override ignored",{catalogModel:e,callerModel:o}),{messages:Array.isArray(d)?d:[...a?[{role:"system",content:a}]:[],{role:"user",content:i}],temperature:f??.7,...m,model:e,max_tokens:zm(c??l,t),usage:{include:!0}}}}function Zm(e,t=$i){return n=>{let{attestation:r,tool_id:s,prompt:o,image_url:i,aspect_ratio:a,max_tokens:c,max_completion_tokens:l,n:u,model:d,messages:f,image_config:m,temperature:p,...h}=n,v=[{type:"text",text:o}];return typeof i=="string"&&i.length>0&&v.push({type:"image_url",image_url:{url:i}}),{messages:Array.isArray(f)?f:[{role:"user",content:v}],temperature:p??.7,...h,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:zm(c??l,t),usage:{include:!0}}}}function le(e,t,n,r,s,o,i){let a=i?.maxOutputTokens??lw(o),c=i?.perRequestFeeCents??0,l=500/1e6*s*100,u=500/1e6*o*100,d=Math.max(1,Math.ceil(l+u+c)),{perRequestFeeCents:f,maxOutputTokens:m,...p}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:d,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:`Maximum tokens in response (default: ${ol}); 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:`${Ym}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Xm(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...c>0?{perRequestFeeCents:c}:{}},...p}}function sl(e,t,n,r,s,o){let i=o?.maxOutputTokens??$i,{maxOutputTokens:a,...c}=o??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",pricingStrategy:"band",priceCents:s,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:`Maximum text tokens in response metadata (default: ${ol}); 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:`${Ym}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Zm(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var il=[ye("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"]}),ye("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:Ii}),ye("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:Ii}),ye("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:Ii}),ye("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"]}),sl("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),sl("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}}),sl("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}}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),pw("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:s,...o}=e;return{prompt:r,customMode:!1,instrumental:typeof s=="boolean"?s:!1,model:"V4",...o}}}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),le("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"]}),le("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"]}),le("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"]}),le("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"]}),le("or-claude-opus-4-8","Claude Opus 4.8","Anthropic's newest flagship. 1M context, strongest reasoning + coding.","anthropic/claude-opus-4.8",15,75,{tags:["llm","claude","anthropic","reasoning","coding","newest"]}),le("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"]}),le("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"]}),le("or-claude-opus-fast","Claude Opus 4.8 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.8-fast",10,50,{tags:["llm","claude","anthropic","fast"]}),le("or-claude-haiku","Claude Haiku 4.5","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-haiku-4.5",1,5,{tags:["llm","claude","anthropic","fast"]}),le("or-gemini-pro","Gemini 2.5 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.5-flash",.3,2.5,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),le("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"]}),le("or-gemini-3-pro","Gemini 3.1 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3.1-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),le("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"]}),le("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"]}),le("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"]}),le("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"]}),le("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2512",.5,1.5,{tags:["llm","mistral","multilingual","european"]}),le("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"]}),le("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"]}),le("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"]}),le("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"]}),le("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"]}),le("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:Gm,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:fw,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=>Ii({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"]},ye("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"}),ye("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:Gm,tags:["onchain","prices","allium","crypto","legacy"]}];function lo(e){return il.find(t=>t.id===e)}var yw=[{type:"integer",matches:e=>typeof e=="number"&&Number.isInteger(e),phrase:"an integer"},{type:"number",matches:e=>typeof e=="number"&&Number.isFinite(e),phrase:"a number"},{type:"string",matches:e=>typeof e=="string",phrase:"a string"},{type:"boolean",matches:e=>typeof e=="boolean",phrase:"a boolean"},{type:"array",matches:e=>Array.isArray(e),phrase:"an array"},{type:"object",matches:e=>typeof e=="object"&&e!==null&&!Array.isArray(e),phrase:"an object"}];function _w(e,t){let r=(Array.isArray(t.type)?t.type:t.type!==void 0?[t.type]:[]).flatMap(o=>yw.filter(i=>i.type===o)),s=new Set(r.filter(o=>o.matches(e)).map(o=>o.type));return{declared:r,matched:s}}function al(e,t,n){if(n.enum&&!n.enum.includes(t))return`${e} must be one of: ${n.enum.map(String).join(", ")}.`;let{declared:r,matched:s}=_w(t,n);if(r.length>0&&s.size===0)return`${e} must be ${r.map(o=>o.phrase).join(" or ")}.`;if(s.has("string")&&typeof t=="string"){if(t.trim()==="")return`${e} cannot be empty.`;if(n.minLength!==void 0&&t.length<n.minLength)return`${e} is too short.`;if(n.maxLength!==void 0&&t.length>n.maxLength)return`${e} is too long.`}if(typeof t=="number"){if(n.minimum!==void 0&&t<n.minimum)return`${e} must be at least ${n.minimum}.`;if(n.maximum!==void 0&&t>n.maximum)return`${e} must be at most ${n.maximum}.`}return null}var Oa=R(as());var Li=require("child_process"),fp=require("util"),mp=R(require("crypto")),ne=R(require("fs")),pp=R(require("os")),Oe=R(require("path"));qt();var ut=(0,fp.promisify)(Li.execFile),qw=6e4,Kw=()=>process.platform==="darwin",kn=()=>process.platform==="win32",Tn=Oe.join(pp.homedir(),".visa-mcp","bin"),_r=Oe.join(Tn,"Visa CLI"),Zt=Oe.join(Tn,"visa-keychain-win.exe"),gp=Oe.join(__dirname,"..","native"),rp="6",sp=Oe.join(Tn,"visa-keychain.version"),op=Oe.join(Tn,"visa-keychain.sha256"),ip="1",ap=Oe.join(Tn,"visa-keychain-win.version"),cp=Oe.join(Tn,"visa-keychain-win.sha256"),hp=[Oe.join(gp,"bin","win32-x64","visa-keychain-win.exe"),Oe.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),Oe.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Oi(e){let t=ne.readFileSync(e);return mp.createHash("sha256").update(t).digest("hex")}function Gw(e){let t=e.trim();if(t.startsWith("OK:"))return t.slice(3);if(t==="OK")return;let n=t.startsWith("ERROR:")?t.slice(6):"Unknown error";throw new Error(n)}function lp(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function up(e){let t=Math.max(1,Math.round(e/1e3));return new Error(`Timed out waiting for Touch ID/device approval after ${t}s.`)}async function cl(){try{if(ne.readFileSync(sp,"utf-8").trim()===rp&&ne.existsSync(_r)){let r=ne.readFileSync(op,"utf-8").trim();if(Oi(_r)!==r)g.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ne.unlinkSync(_r);else return _r}}catch{}let e=Oe.join(gp,"visa-keychain.m");if(ne.existsSync(e)||(e=Oe.resolve(__dirname,"..","..","native","visa-keychain.m")),ne.existsSync(e)||(e=Oe.resolve(__dirname,"..","native","visa-keychain.m")),!ne.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ne.mkdirSync(Tn,{recursive:!0,mode:448});try{await ut("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",_r,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Oi(_r);return ne.writeFileSync(op,t,{mode:384}),ne.writeFileSync(sp,rp,{mode:384}),_r}function yp(){for(let e of hp)if(ne.existsSync(e))return e;return null}async function cs(){try{if(ne.readFileSync(ap,"utf-8").trim()===ip&&ne.existsSync(Zt)){let r=ne.readFileSync(cp,"utf-8").trim();if(Oi(Zt)!==r)g.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),ne.unlinkSync(Zt);else return Zt}}catch{}let e=yp();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
143
- If building from source, run native/build-win.bat first.`);ne.mkdirSync(Tn,{recursive:!0}),ne.copyFileSync(e,Zt);let t=Oi(Zt);return ne.writeFileSync(cp,t,{mode:384}),ne.writeFileSync(ap,ip,{mode:384}),Zt}async function Ww(){return kn()?cs():cl()}var Ni="visa-cli",Mi="attestation-key";async function Yw(e){try{await ut("security",["delete-generic-password","-s",Ni,"-a",Mi],{timeout:5e3})}catch{}await ut("security",["add-generic-password","-s",Ni,"-a",Mi,"-w",e],{timeout:5e3})}function zw(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:"",s=[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(s)?{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(s)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:s||"Could not read the local attestation key from Keychain."}}async function Jw(){try{let{stdout:e}=await ut("security",["find-generic-password","-s",Ni,"-a",Mi,"-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:zw(e)}}}async function ll(){let e=await Jw();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 _p(e){let t=await Ww(),n;try{n=(await ut(t,e,{timeout:6e4})).stdout}catch(r){n=r.stdout||"";let s=n.trim();throw s.startsWith("ERROR:")?new Error(s.slice(6)):new Error(r.stderr?.toString().trim()||r.message||"Unknown error")}return Gw(n)}var dp=!1;function Xw(){if(!kn())return!1;try{return ne.existsSync(Zt)||yp()!==null?!0:(dp||(dp=!0,g.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Zt,searchedPrebuiltPaths:hp})),!1)}catch{return!1}}function de(){return Hr()||Kw()?!0:kn()?Xw():!1}async function Ui(){if(kn()){let s=await cs(),{stdout:o}=await ut(s,["generate-key"],{timeout:3e4}),i=o.trim();if(i.startsWith("OK:"))return i.slice(3);throw new Error(i.startsWith("ERROR:")?i.slice(6):"Key generation failed")}let e=await _p(["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 Yw(n),r}async function Di(){if(kn())try{let e=await cs(),{stdout:t}=await ut(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await ll()!==null}async function bp(){if(Hr())return"mock-public-key-spki";if(kn()){let n=await cs(),{stdout:r}=await ut(n,["public-key"],{timeout:6e4}),s=r.trim();if(s.startsWith("OK:"))return s.slice(3);throw new Error(s.startsWith("ERROR:")?s.slice(6):"Attestation key not found. Run setup to generate a new key.")}let e=await ll();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await cl();return new Promise((n,r)=>{let s=(0,Li.execFile)(t,["public-key"],{timeout:6e4},(o,i)=>{let a=(i||"").trim();if(o){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(o.stderr?.toString().trim()||o.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});s.stdin.write(e),s.stdin.end()})}async function Rn(e,t,n={}){if(Hr())return Promise.resolve(Pd());let r=n.timeoutMs??qw;if(kn()){let a=await cs(),c=["sign",e];t&&c.push(t);let l;try{l=(await ut(a,c,{timeout:r})).stdout}catch(d){throw lp(d)?up(r):d}let u=l.trim();if(u.startsWith("OK:"))return u.slice(3);throw new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error")}let s=await ll();if(!s)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await cl(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Li.execFile)(o,i,{timeout:r},(u,d)=>{let f=(d||"").trim();if(u){f.startsWith("ERROR:")?c(new Error(f.slice(6))):lp(u)?c(up(r)):c(new Error(u.stderr?.toString().trim()||u.message||"Unknown error"));return}f.startsWith("OK:")?a(f.slice(3)):c(new Error(f.startsWith("ERROR:")?f.slice(6):"Unknown error"))});l.stdin.write(s),l.stdin.end()})}async function ji(){if(kn()){try{let e=await cs();await ut(e,["delete-key"],{timeout:1e4})}catch{}return}try{await ut("security",["delete-generic-password","-s",Ni,"-a",Mi],{timeout:5e3})}catch{}try{await _p(["delete-key"])}catch{}}qt();var Zw=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Qw=[...Zw.map(e=>({id:`legacy.${e}`,toolId:e,targetToolId:e,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function ul(e,t=Qw){for(let n of t)if(n.toolId===e.requestedTool)return n.targetToolId;return null}function dl(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function vp(e=process.env){return dl(e)!==null}var eS=new Set(["false","0","no","off","disable","disabled"]),tS=new Set(["true","1","yes","on","enable","enabled"]);function wp(e){let t=(e??"").trim().toLowerCase();return t?eS.has(t)?!1:!!tS.has(t):!0}function Sp(e=process.env){return wp(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function xp(e=process.env){return wp(e.VISA_CLI_PARENTLESS_BATCH)}var gy=require("child_process"),Ce=R(require("crypto")),pt=R(require("fs")),$o=R(require("os")),Na=R(require("path"));function At(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),s=n.content?.[0]?.text,o=typeof s=="string"?Vr(s):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Vr(i):null;if(!o&&!c)return e;let l=o??c,u=o?"content":"urls",d;try{d=Us(l,{tag:nS(r,n)})}catch(m){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${m instanceof Error?m.message:String(m)}`}}let f={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?f.urls=void 0:(f.content=Array.isArray(n.content)?[...n.content]:[{}],f.content[0]={...f.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),f}function nS(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}qt();var fl=!1;async function br(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!de())throw r;if(g.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(fl)throw g.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;fl=!0,g.info("attestation:starting-browser-recovery");try{let o=await n();if(!o.success)throw g.error("attestation:browser-recovery-failed",{message:o.message}),r;let i=await Ui();await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),g.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),g.info("attestation:key-reregistered-after-recovery");let a=await t();return fl=!1,a}catch(o){throw g.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}function kt(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Bi(e,t){if(!de())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 Di())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 kt(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."}}St();var Cp="4.0.0-rc.16";function ml(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function pl(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=Si(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Xe(e){return e==null?"\u2014":e?"yes":"no"}function Fi(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function rS(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function sS(){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=Kc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Vc,source:{kind:"default"}}}async function fo(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(A){n=A?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=qc("auth.serverUrl"),i=Se(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:Xe(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}}),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:Xe(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:Xe(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:de(),formatted:Xe(de()),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:Fi(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Fi(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Fi(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Fi(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let f=t?.cards?.find(A=>A.isDefault)??t?.cards?.[0];f&&r.push({key:"cards.default",value:{brand:f.brand??null,last4:f.last4},formatted:`${f.brand||"card"} \u2022\u2022\u2022\u2022 ${f.last4}`,source:{kind:"server"}});let m=sS();r.push({key:"credit.sessionCapCents",value:m.value,formatted:rS(m.value),source:m.source});let p=mm();p.length>0&&r.push({key:"settings.retired",value:p.map(A=>A.key),formatted:p.map(A=>A.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${p.map(A=>`visa-cli config unset ${A.key}`).join(" && ")}`});let h=pl("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:h.value,formatted:Xe(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let v=pl("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:v.value,formatted:Xe(v.value),source:v.source});let I=wt(),_;process.env.VISA_CLI_NO_UPDATE_CHECK?_={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?_={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?_={kind:"env",var:"NODE_ENV"}:_={kind:"default"},r.push({key:"ui.updateCheck",value:!I,formatted:Xe(!I),source:_});let b=pl("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:b.value,formatted:Xe(b.value),source:b.source});let w=process.env.VISA_DRY_RUN,T=vp();if(r.push({key:"tools.dryRun",value:T,formatted:Xe(T),source:w===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:Cp,formatted:Cp,source:{kind:"default"}}),e.includeDev){let A=process.env.VISA_MOCK_KEYCHAIN,y=dn();r.push({key:"dev.mockKeychain",value:y,formatted:Xe(y),source:ml("VISA_MOCK_KEYCHAIN",!!A),hint:nc()});let x=process.env.VISA_MOCK_TOUCHID,Y=Hr();r.push({key:"dev.mockTouchid",value:Y,formatted:Xe(Y),source:ml("VISA_MOCK_TOUCHID",!!x),hint:nc()});let X=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!X,formatted:Xe(!!X),source:ml("VISA_CLI_DEBUG",!!X)})}return{entries:r,statusError:n}}function oS(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 Ep(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${oS(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
143
+ If building from source, run native/build-win.bat first.`);ne.mkdirSync(Tn,{recursive:!0}),ne.copyFileSync(e,Zt);let t=Oi(Zt);return ne.writeFileSync(cp,t,{mode:384}),ne.writeFileSync(ap,ip,{mode:384}),Zt}async function Ww(){return kn()?cs():cl()}var Ni="visa-cli",Mi="attestation-key";async function Yw(e){try{await ut("security",["delete-generic-password","-s",Ni,"-a",Mi],{timeout:5e3})}catch{}await ut("security",["add-generic-password","-s",Ni,"-a",Mi,"-w",e],{timeout:5e3})}function zw(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:"",s=[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(s)?{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(s)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:s||"Could not read the local attestation key from Keychain."}}async function Jw(){try{let{stdout:e}=await ut("security",["find-generic-password","-s",Ni,"-a",Mi,"-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:zw(e)}}}async function ll(){let e=await Jw();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 _p(e){let t=await Ww(),n;try{n=(await ut(t,e,{timeout:6e4})).stdout}catch(r){n=r.stdout||"";let s=n.trim();throw s.startsWith("ERROR:")?new Error(s.slice(6)):new Error(r.stderr?.toString().trim()||r.message||"Unknown error")}return Gw(n)}var dp=!1;function Xw(){if(!kn())return!1;try{return ne.existsSync(Zt)||yp()!==null?!0:(dp||(dp=!0,g.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Zt,searchedPrebuiltPaths:hp})),!1)}catch{return!1}}function de(){return Hr()||Kw()?!0:kn()?Xw():!1}async function Ui(){if(kn()){let s=await cs(),{stdout:o}=await ut(s,["generate-key"],{timeout:3e4}),i=o.trim();if(i.startsWith("OK:"))return i.slice(3);throw new Error(i.startsWith("ERROR:")?i.slice(6):"Key generation failed")}let e=await _p(["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 Yw(n),r}async function Di(){if(kn())try{let e=await cs(),{stdout:t}=await ut(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await ll()!==null}async function bp(){if(Hr())return"mock-public-key-spki";if(kn()){let n=await cs(),{stdout:r}=await ut(n,["public-key"],{timeout:6e4}),s=r.trim();if(s.startsWith("OK:"))return s.slice(3);throw new Error(s.startsWith("ERROR:")?s.slice(6):"Attestation key not found. Run setup to generate a new key.")}let e=await ll();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await cl();return new Promise((n,r)=>{let s=(0,Li.execFile)(t,["public-key"],{timeout:6e4},(o,i)=>{let a=(i||"").trim();if(o){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(o.stderr?.toString().trim()||o.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});s.stdin.write(e),s.stdin.end()})}async function Rn(e,t,n={}){if(Hr())return Promise.resolve(Pd());let r=n.timeoutMs??qw;if(kn()){let a=await cs(),c=["sign",e];t&&c.push(t);let l;try{l=(await ut(a,c,{timeout:r})).stdout}catch(d){throw lp(d)?up(r):d}let u=l.trim();if(u.startsWith("OK:"))return u.slice(3);throw new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error")}let s=await ll();if(!s)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await cl(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Li.execFile)(o,i,{timeout:r},(u,d)=>{let f=(d||"").trim();if(u){f.startsWith("ERROR:")?c(new Error(f.slice(6))):lp(u)?c(up(r)):c(new Error(u.stderr?.toString().trim()||u.message||"Unknown error"));return}f.startsWith("OK:")?a(f.slice(3)):c(new Error(f.startsWith("ERROR:")?f.slice(6):"Unknown error"))});l.stdin.write(s),l.stdin.end()})}async function ji(){if(kn()){try{let e=await cs();await ut(e,["delete-key"],{timeout:1e4})}catch{}return}try{await ut("security",["delete-generic-password","-s",Ni,"-a",Mi],{timeout:5e3})}catch{}try{await _p(["delete-key"])}catch{}}qt();var Zw=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Qw=[...Zw.map(e=>({id:`legacy.${e}`,toolId:e,targetToolId:e,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function ul(e,t=Qw){for(let n of t)if(n.toolId===e.requestedTool)return n.targetToolId;return null}function dl(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function vp(e=process.env){return dl(e)!==null}var eS=new Set(["false","0","no","off","disable","disabled"]),tS=new Set(["true","1","yes","on","enable","enabled"]);function wp(e){let t=(e??"").trim().toLowerCase();return t?eS.has(t)?!1:!!tS.has(t):!0}function Sp(e=process.env){return wp(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function xp(e=process.env){return wp(e.VISA_CLI_PARENTLESS_BATCH)}var gy=require("child_process"),Ce=R(require("crypto")),pt=R(require("fs")),$o=R(require("os")),Na=R(require("path"));function At(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),s=n.content?.[0]?.text,o=typeof s=="string"?Vr(s):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Vr(i):null;if(!o&&!c)return e;let l=o??c,u=o?"content":"urls",d;try{d=Us(l,{tag:nS(r,n)})}catch(m){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${m instanceof Error?m.message:String(m)}`}}let f={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?f.urls=void 0:(f.content=Array.isArray(n.content)?[...n.content]:[{}],f.content[0]={...f.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),f}function nS(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}qt();var fl=!1;async function br(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!de())throw r;if(g.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(fl)throw g.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;fl=!0,g.info("attestation:starting-browser-recovery");try{let o=await n();if(!o.success)throw g.error("attestation:browser-recovery-failed",{message:o.message}),r;let i=await Ui();await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),g.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),g.info("attestation:key-reregistered-after-recovery");let a=await t();return fl=!1,a}catch(o){throw g.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}function kt(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Bi(e,t){if(!de())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 Di())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 kt(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."}}St();var Cp="4.0.0-rc.17";function ml(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function pl(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=Si(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Xe(e){return e==null?"\u2014":e?"yes":"no"}function Fi(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function rS(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function sS(){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=Kc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Vc,source:{kind:"default"}}}async function fo(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(A){n=A?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=qc("auth.serverUrl"),i=Se(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:Xe(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}}),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:Xe(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:Xe(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:de(),formatted:Xe(de()),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:Fi(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Fi(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Fi(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Fi(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let f=t?.cards?.find(A=>A.isDefault)??t?.cards?.[0];f&&r.push({key:"cards.default",value:{brand:f.brand??null,last4:f.last4},formatted:`${f.brand||"card"} \u2022\u2022\u2022\u2022 ${f.last4}`,source:{kind:"server"}});let m=sS();r.push({key:"credit.sessionCapCents",value:m.value,formatted:rS(m.value),source:m.source});let p=mm();p.length>0&&r.push({key:"settings.retired",value:p.map(A=>A.key),formatted:p.map(A=>A.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${p.map(A=>`visa-cli config unset ${A.key}`).join(" && ")}`});let h=pl("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:h.value,formatted:Xe(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let v=pl("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:v.value,formatted:Xe(v.value),source:v.source});let I=wt(),_;process.env.VISA_CLI_NO_UPDATE_CHECK?_={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?_={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?_={kind:"env",var:"NODE_ENV"}:_={kind:"default"},r.push({key:"ui.updateCheck",value:!I,formatted:Xe(!I),source:_});let b=pl("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:b.value,formatted:Xe(b.value),source:b.source});let w=process.env.VISA_DRY_RUN,T=vp();if(r.push({key:"tools.dryRun",value:T,formatted:Xe(T),source:w===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:Cp,formatted:Cp,source:{kind:"default"}}),e.includeDev){let A=process.env.VISA_MOCK_KEYCHAIN,y=dn();r.push({key:"dev.mockKeychain",value:y,formatted:Xe(y),source:ml("VISA_MOCK_KEYCHAIN",!!A),hint:nc()});let x=process.env.VISA_MOCK_TOUCHID,Y=Hr();r.push({key:"dev.mockTouchid",value:Y,formatted:Xe(Y),source:ml("VISA_MOCK_TOUCHID",!!x),hint:nc()});let X=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!X,formatted:Xe(!!X),source:ml("VISA_CLI_DEBUG",!!X)})}return{entries:r,statusError:n}}function oS(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 Ep(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${oS(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
144
144
  `)}function Ap(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 kp(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/1)} images. Try something now, or save them for later.`,balanceUsd:t,examples:[{tool:"fal-flux-schnell",cost:"$0.01",what:"an AI image"},{tool:"or-gpt-4o-mini",cost:"token-priced",what:"a quick model call"},{tool:"fal-ace-step-music",cost:"$0.02",what:"a music track"}]}}}St();qt();var In=require("fs"),Rp=require("os"),gl=require("path"),iS=(0,gl.join)((0,Rp.homedir)(),".visa-mcp"),Tp=(0,gl.join)(iS,"mcp-session-budget.json");function Hi(){try{(0,In.existsSync)(Tp)&&(0,In.unlinkSync)(Tp)}catch{}}var yl=require("crypto"),dt=R(as()),wr=null,Ge=0,Pn=0,qe=0,$n=null,_l=null,bl=null,vr=Promise.resolve();function aS(e){return Number((0,dt.fromCents)(e))}function $p(e){return(0,dt.toCents)((0,dt.micros)(BigInt(e)))}function Ip(e){return(0,dt.toWire)((0,dt.fromCents)(e))}function hl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Vi(e){return typeof e=="string"&&/^\d+$/.test(e)}var cS=43,lS=new RegExp(`^[A-Za-z0-9_-]{${cS}}$`);function uS(e){return typeof e=="string"&&lS.test(e)}function dS(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||wr&&e.session_id!==wr||typeof e.nonce!="string"||e.nonce.length===0||!uS(e.server_signature)||!hl(e.cumulative)||!hl(e.remaining)||!hl(e.delta)||e.cumulative<Ge||qe>0&&e.cumulative>qe||qe>0&&e.remaining>qe||e.cumulative_micros!==void 0&&!Vi(e.cumulative_micros)||e.remaining_micros!==void 0&&!Vi(e.remaining_micros)||e.delta_micros!==void 0&&!Vi(e.delta_micros)||e.reserved_micros!==void 0&&!Vi(e.reserved_micros))}function Qt(e){wr=e,Ge=0,Pn=0,qe=0,$n=null,_l=null,bl=null,vr=Promise.resolve()}function mo(e){qe=Math.max(0,Math.floor(e))}function vl(){return wr}function wl(e){if(!wr)return null;let t=Ge+Pn;return qe>0&&t>qe&&(t=qe),{session_budget_id:wr,cumulative_micros:aS(t),nonce:(0,yl.randomUUID)(),idempotency_key:e||(0,yl.randomUUID)()}}function po(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 dS(r)?(Ge=Math.max(Ge,r.cumulative),Pn=0,$n=r,r):null}function Pp(){return $n}function Sl(e){let t=$p(e.cumulative_micros);Ge=Math.max(Ge,t),Pn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ge,remaining:Math.max(0,qe-Ge),delta:0,cumulative_micros:Ip(Ge),remaining_micros:Ip(Math.max(0,qe-Ge)),delta_micros:"0",nonce:e.nonce};return $n=n,n}function go(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,dt.toCents)((0,dt.micros)(n));if(!Number.isFinite(r)||r<0)return;_l=t;let s=e,o=typeof s.session_id=="string"?s.session_id:wr??"";$n?(typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)&&($n.remaining_micros=s.remaining_micros),typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)&&($n.delta_micros=s.charged_micros)):$n={session_id:o,cumulative:r,remaining:0,delta:0,nonce:typeof s.transaction_id=="string"?s.transaction_id:"",remaining_micros:typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)?s.remaining_micros:void 0,delta_micros:typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)?s.charged_micros:void 0}}function Op(e){let t=e.receipt??null;bl={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:$p(e.voucher.cumulative_micros),estimatedCumulativeCents:qi(),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 Np(){return bl}function Mp(){return Ge}function Lp(){return _l}function qi(){let e=Ge+Pn;return qe>0&&e>qe&&(e=qe),e}function xl(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return vr=vr.then(()=>{Pn+=t}),vr}function ho(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return vr=vr.then(()=>{Pn=Math.max(0,Pn-t)}),vr}var fS=10,mS=1,fe=null,Up=Promise.resolve();function Cl(e){let t=Up.catch(()=>{}).then(e);return Up=t.then(()=>{},()=>{}),t}var xe=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 El(e,t,n){return Cl(()=>Dp(e,t,n))}async function Dp(e,t,n){if(Hi(),fe&&new Date(fe.expiresAt).getTime()>Date.now())return vl()!==fe.budgetId&&(Qt(fe.budgetId),mo(fe.totalCents)),g.info("mcp-session:active-hit",{budgetId:fe.budgetId,tool:n.toolName,remainingEstimatedCents:fe.totalCents-qi()}),{budgetId:fe.budgetId,isFresh:!1,totalCents:fe.totalCents,requestedCapCents:fe.totalCents,appliedCapCents:fe.totalCents,clampedReason:null};fe&&(fe=null,Qt(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);let s=n.sessionKind??"explicit",o=s==="one_shot"?mS:fS,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new xe(r.balanceCents,i);let a=n.capCentsOverride??hm(),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:s,...u?{attestation:u}:{}});if(!d.success||!d.budget){let m=d.error||"unknown error";throw new Error(`Failed to open credit session: ${m}`)}let f={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return fe=f,Qt(f.budgetId),mo(f.totalCents),g.info("mcp-session:opened",{budgetId:f.budgetId,capCents:f.totalCents,requestedCapCents:a,clampedReason:l,sessionKind:s,expiresAt:f.expiresAt,tool:n.toolName}),{budgetId:f.budgetId,isFresh:!0,totalCents:f.totalCents,requestedCapCents:a,appliedCapCents:f.totalCents,clampedReason:l}}async function jp(e,t,n){return Cl(async()=>{let s=On()?await Bp(e):null,o=await Dp(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function Bp(e){let n=On()?.budgetId??vl(),r=!1,s,o;if(n)try{let i=await e.closeSession(n);r=!!i?.success,typeof i?.finalCumulativeCents=="number"&&(s=i.finalCumulativeCents),typeof i?.finalCumulativeMicros=="string"&&(o=i.finalCumulativeMicros)}catch(i){g.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return Hi(),fe=null,Qt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:s,finalCumulativeMicros:o}}async function Ki(e){return Cl(()=>Bp(e))}function On(){return Hi(),fe?new Date(fe.expiresAt).getTime()<=Date.now()?(fe=null,Qt(null),null):{budgetId:fe.budgetId,totalCents:fe.totalCents,lastReceiptCumulative:Mp(),lastReceiptCumulativeMicros:Pp()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Lp(),estimatedCumulative:qi(),lastToolSpend:Np(),expiresAt:fe.expiresAt}:null}var Hp=R(as()),Fp=10000n;function pS(e){return e<=0n?0:Number((e+Fp-1n)/Fp)}function Vp(e){return pS((0,Hp.fromUsd)(e))}var Gi=R(as()),gS=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Wi(e){if(typeof e!="string"||!gS.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 s=Number(r);return s<=0?{ok:!1,error:"amount must be greater than $0.00"}:{ok:!0,cents:s,displayUsd:(0,Gi.toDisplay)((0,Gi.fromCents)(s),{symbol:""})}}var Yi="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.",qp="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.";St();var ny=Promise.resolve();function yE(e,t){if(e)try{let n=(0,Oa.fromWire)(e),r=n%10000n===0n?2:6;return(0,Oa.toDisplay)(n,{decimals:r})}catch{}return`$${(t/100).toFixed(2)}`}var ry=!1,sy=!1,oy=!1;function Ma(e){let t=ny.catch(()=>{}).then(e);return ny=t.then(()=>{},()=>{}),t}async function hy(e){let t=await Ee(()=>El(U,nt,{toolName:e.toolId,userContext:e.userContext}));await xl(e.estimatedAmountCents);let n=wl(e.idempotencyKey);if(!n)throw await ho(e.estimatedAmountCents),new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await kE(),s,o,i=async()=>U.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:s,voucherReceiptHeader:o}=await i())}catch(u){if(u instanceof Vt){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;g.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(f=>setTimeout(f,d)),{data:s,voucherReceiptHeader:o}=await i()}else throw u}}catch(u){if(await ho(e.estimatedAmountCents),u instanceof zr){if(g.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Ki(U),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 oy||(oy=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
145
- To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),g.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),yy(e)}throw u instanceof Vt?(g.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=po(o)??(n?Sl(n):null);if(go(s?.receipt_v2),Op({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),ju(s))return At(s);let c=await Du();if(e.idempotencyKey&&Bu(s,c,e.idempotencyKey))return At(s);let l=c?Ro(c):null;return At(Fu(s,r,l))}function et(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Ia(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(Ia).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Ia(r)}`).join(",")}}`}function Uu(e,t,n,r){let s=Ce.createHash("sha256").update(`${n}:${Ia(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function _E(e,t){return`${e}:${t}`}function bE(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 $a(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=mt(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=bE(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:_E(e,t),index:t,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function yy(e){return Ee(()=>wE(e))}async function _y(e,t,n){if(ju(e))return At(e);let r=await Du();if(n&&Bu(e,r,n))return At(e);let s=r?Ro(r):null;return At(Fu(e,t,s))}async function vE(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 nt("shortcut_call",t,e.toolId,n,e.userContext);g.info("parentless-single-call:attempt",{tool:e.toolId,approvedMaxCents:t,attested:!!r});let s=r?.nonce??(await U.getAttestationChallenge()).nonce,{data:o,voucherReceiptHeader:i}=await U.shortcutParentless(e.toolId,{...r?{attestation:r}:{},nonce:s,approved_max_cents:t,idempotency_key:e.idempotencyKey},e.toolParams,e.timeoutMs,e.userContext,e.metaTool);return po(i),go(o?.receipt_v2),g.info("parentless-single-call:completed",{tool:e.toolId}),_y(o,e.beforeBalanceMicros,e.idempotencyKey)}async function wE(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await U.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new xe(n.balanceCents,t);let r=t,s=Ro(n);if(Sp()&&!ry){let u=e.idempotencyKey??Ce.randomUUID();try{return await vE({toolId:e.toolId,toolParams:e.toolParams,estimatedAmountCents:e.estimatedAmountCents,cap:r,beforeBalanceMicros:s,userContext:e.userContext,metaTool:e.metaTool,timeoutMs:e.timeoutMs,idempotencyKey:u})}catch(d){if(d instanceof vt)ry=!0,g.info("parentless-single-call:falling-back-to-session",{tool:e.toolId,status:d.status,serverErrorCode:d.serverErrorCode});else throw d}}let o=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await nt("session_create",r,"Visa CLI Session",o,e.userContext),a=await U.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;Qt(c),mo(a.budget.totalCents),g.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let l=!1;try{await xl(e.estimatedAmountCents);let u=wl(e.idempotencyKey);if(!u)throw await ho(e.estimatedAmountCents),new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:d,voucherReceiptHeader:f}=await U.shortcutWithSession(e.toolId,u,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(po(f)||Sl(u),l=!0,go(d?.receipt_v2),ju(d))return At(d);let m=await Du();if(e.idempotencyKey&&Bu(d,m,e.idempotencyKey))return At(d);let p=m?Ro(m):null;return At(Fu(d,s,p))}catch(u){throw l||await ho(e.estimatedAmountCents),u}finally{try{await U.closeSession(c)}catch(u){g.warn("on-demand-session:close-failed",{budgetId:c,error:u?.message||String(u)})}Qt(null),g.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Kn(e){return Ma(async()=>On()?hy(e):yy(e))}function La(){return Se()}var SE="https://v4-verify-web-visa-code-preview.up.railway.app";function xE(e=Hu){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function by(e=process.env,t=Hu){return e.VISA_VERIFY_WEB_URL?e.VISA_VERIFY_WEB_URL:xE(t)?null:SE}var U=new Ke(()=>G.getSessionToken());function mt(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Ro(e){return mt(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function CE(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,s=r/100n,o=r%100n;return`$${s.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function EE(e){let t=mt(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=mt(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=mt(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function To(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function AE(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 kE(){try{let e=await U.getBalance();return e.success?Ro(e):null}catch{return null}}async function Du(){try{let e=await U.getBalance();return e.success?e:null}catch{return null}}function ju(e){if(!e||e.success===!1)return!1;let t=mt(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=mt(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function Bu(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=mt(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function Fu(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var Hu="4.0.0-rc.16",t$=["","","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',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Generate an image of a sunset over Tokyo" \u2192 discover_tools \u2192 execute_tool','\u2022 "Make a 4-second video of a penguin juggling" \u2192 discover_tools \u2192 execute_tool','\u2022 "Make a song about coding late at night" \u2192 discover_tools \u2192 execute_tool','\u2022 "Run a reasoning model on this prompt" \u2192 discover_tools \u2192 execute_tool','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
145
+ To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),g.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),yy(e)}throw u instanceof Vt?(g.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=po(o)??(n?Sl(n):null);if(go(s?.receipt_v2),Op({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),ju(s))return At(s);let c=await Du();if(e.idempotencyKey&&Bu(s,c,e.idempotencyKey))return At(s);let l=c?Ro(c):null;return At(Fu(s,r,l))}function et(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Ia(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(Ia).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Ia(r)}`).join(",")}}`}function Uu(e,t,n,r){let s=Ce.createHash("sha256").update(`${n}:${Ia(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function _E(e,t){return`${e}:${t}`}function bE(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 $a(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=mt(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=bE(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:_E(e,t),index:t,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function yy(e){return Ee(()=>wE(e))}async function _y(e,t,n){if(ju(e))return At(e);let r=await Du();if(n&&Bu(e,r,n))return At(e);let s=r?Ro(r):null;return At(Fu(e,t,s))}async function vE(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 nt("shortcut_call",t,e.toolId,n,e.userContext);g.info("parentless-single-call:attempt",{tool:e.toolId,approvedMaxCents:t,attested:!!r});let s=r?.nonce??(await U.getAttestationChallenge()).nonce,{data:o,voucherReceiptHeader:i}=await U.shortcutParentless(e.toolId,{...r?{attestation:r}:{},nonce:s,approved_max_cents:t,idempotency_key:e.idempotencyKey},e.toolParams,e.timeoutMs,e.userContext,e.metaTool);return po(i),go(o?.receipt_v2),g.info("parentless-single-call:completed",{tool:e.toolId}),_y(o,e.beforeBalanceMicros,e.idempotencyKey)}async function wE(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await U.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new xe(n.balanceCents,t);let r=t,s=Ro(n);if(Sp()&&!ry){let u=e.idempotencyKey??Ce.randomUUID();try{return await vE({toolId:e.toolId,toolParams:e.toolParams,estimatedAmountCents:e.estimatedAmountCents,cap:r,beforeBalanceMicros:s,userContext:e.userContext,metaTool:e.metaTool,timeoutMs:e.timeoutMs,idempotencyKey:u})}catch(d){if(d instanceof vt)ry=!0,g.info("parentless-single-call:falling-back-to-session",{tool:e.toolId,status:d.status,serverErrorCode:d.serverErrorCode});else throw d}}let o=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await nt("session_create",r,"Visa CLI Session",o,e.userContext),a=await U.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;Qt(c),mo(a.budget.totalCents),g.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let l=!1;try{await xl(e.estimatedAmountCents);let u=wl(e.idempotencyKey);if(!u)throw await ho(e.estimatedAmountCents),new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:d,voucherReceiptHeader:f}=await U.shortcutWithSession(e.toolId,u,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(po(f)||Sl(u),l=!0,go(d?.receipt_v2),ju(d))return At(d);let m=await Du();if(e.idempotencyKey&&Bu(d,m,e.idempotencyKey))return At(d);let p=m?Ro(m):null;return At(Fu(d,s,p))}catch(u){throw l||await ho(e.estimatedAmountCents),u}finally{try{await U.closeSession(c)}catch(u){g.warn("on-demand-session:close-failed",{budgetId:c,error:u?.message||String(u)})}Qt(null),g.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Kn(e){return Ma(async()=>On()?hy(e):yy(e))}function La(){return Se()}var SE="https://v4-verify-web-visa-code-preview.up.railway.app";function xE(e=Hu){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function by(e=process.env,t=Hu){return e.VISA_VERIFY_WEB_URL?e.VISA_VERIFY_WEB_URL:xE(t)?null:SE}var U=new Ke(()=>G.getSessionToken());function mt(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Ro(e){return mt(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function CE(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,s=r/100n,o=r%100n;return`$${s.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function EE(e){let t=mt(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=mt(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=mt(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function To(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function AE(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 kE(){try{let e=await U.getBalance();return e.success?Ro(e):null}catch{return null}}async function Du(){try{let e=await U.getBalance();return e.success?e:null}catch{return null}}function ju(e){if(!e||e.success===!1)return!1;let t=mt(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=mt(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function Bu(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=mt(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function Fu(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var Hu="4.0.0-rc.17",t$=["","","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',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Generate an image of a sunset over Tokyo" \u2192 discover_tools \u2192 execute_tool','\u2022 "Make a 4-second video of a penguin juggling" \u2192 discover_tools \u2192 execute_tool','\u2022 "Make a song about coding late at night" \u2192 discover_tools \u2192 execute_tool','\u2022 "Run a reasoning model on this prompt" \u2192 discover_tools \u2192 execute_tool','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
146
146
  `);function tt(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=Hs(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(pm())return{opened:!1,url:t,blockedReason:"suppressed"};let n=hc();if(n.headless)return g.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let s=[La(),by()].filter(i=>!!i).map(i=>Yd(t,i)).find(Boolean)??null;if(!s)return g.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=Jd(s);return o?((0,gy.execFile)(o.cmd,o.args,i=>{i&&g.warn(`Browser open failed: ${i.message}. URL: ${s}`)}),{opened:!0,url:s}):(g.info(`No browser command for platform "${$o.platform()}". URL: ${s}`),{opened:!1,url:s,blockedReason:"unsupported_platform"})}async function Ee(e){return br(U,e,Ty)}var vy="get_cards",wy="set_default_card";function TE(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 '${vy}' to see enrolled cards and '${wy}' to switch, then retry the original request.`}function RE(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 '${vy}' to see enrolled cards and '${wy}' to switch. Do not retry automatically.`}function gt(e,t){let n=e.retryable?TE(e.code,e.retryAfter):RE(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 IE(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 Es=null,$E=3e4;function Sy(){Es=null}var qn=class extends Error{constructor(n){super(`${Pa()} attestation is required for this action, but it is not available in this MCP process. `+Vu());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function Ua(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. `+Vu()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function PE(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:Yi,agent_guidance:qp}}function Pa(){return process.platform==="darwin"?"Touch ID":"local biometric"}function Vu(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or call auth_recovery to re-sync a drifted local attestation key, 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. Call auth_recovery to re-sync a drifted local attestation key, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}async function OE(e){let t=Date.now();if(Es&&Es.expiresAt>t)return{required:Es.required,hasRegisteredKey:Es.hasRegisteredKey};try{let n=await U.getStatus(e),r=kt(n),s=n.attestationRequired!==!1;return Es={required:s,hasRegisteredKey:r,expiresAt:t+$E},{required:s,hasRegisteredKey:r}}catch{return{required:!0,hasRegisteredKey:!0}}}async function nt(e,t,n,r,s,o){if(!o?.forceRequired){let i=await OE(s);if(!i.required){g.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){g.info("attestation:skipped-no-registered-key",{context:e});return}}if(!de())throw g.warn("attestation:unavailable",{context:e}),new qn(e);g.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await U.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");g.info("touchid:prompt",{context:e,amount:t,merchant:n});let c=await Rn(a,r);return g.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:c,nonce:i,amount:t,merchant:n}}catch(i){throw/cancel|dismiss/i.test(i.message??"")?(g.warn("attestation:cancelled",{context:e,merchant:n}),new Error("Touch ID was cancelled or dismissed. For automated environments (CI, scripts, MCP hooks without user present), run `visa-cli config biometric off` to enable paid calls without Touch ID.")):(g.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i)}}var iy="[dry-run] https://placeholder.visa-cli.dev/image.png",NE=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"]),ME=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 LE(e){return e.startsWith("or-")?"llm":NE.has(e)?"image":ME.has(e)?"video":UE(e)?"media":null}function UE(e){let t=lo(e);return t?!Da(t):!1}function DE(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function jE(e){return e==="llm"?"OpenRouter":"fal.ai"}function As(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:jE(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${DE(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[iy],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:iy,metadata:{dry_run:!0}}}}async function Nu(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await U.emitTelemetry([{id:Ce.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(s){g.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var BE="https://openrouter.ai/api/v1/chat/completions",FE="openrouter/free",HE=50,VE=15e3;function qE(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 KE(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return g.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:As("llm",e,t,n),degraded:!0,resolvedModel:null};let s=qE(t),o;try{o=await bt(BE,{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:FE,messages:[{role:"user",content:s}],max_tokens:HE}),timeoutMs:VE})}catch(u){return g.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:As("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!o.ok){let u=await o.text().catch(()=>"");return g.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:o.status,bodyExcerpt:u.slice(0,200)}),{result:As("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await o.json()}catch(u){return g.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:As("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 Po(e,t,n,r){let s=dl();if(!s)return null;let o=LE(e);if(!o)return null;let i=Date.now();if(s==="mock"){let l=As(o,e,t,r);return await Nu({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"mock"}),g.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),l}if(o!=="llm"){g.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:o});let l=As(o,e,t,r);return await Nu({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 KE(e,t,r);return await Nu({toolName:r??e,resolvedModel:c??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),g.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),a}async function cn(e,t,n,r){let s=await U.paymentPreview({tool:e,url:t,...r&&Object.keys(r).length>0?{params:r}:{}},n);if(!s||!s.merchantName||s.amount===void 0||s.amount===null||s.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(s.amount)||s.amount<0||s.amount>999999)throw new Error(`Invalid payment amount: ${s.amount}. Payment rejected for safety.`);return s}function ln(e){return Vp(e.amount)}function GE(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,ln(t[e.resolvedTool]))}function WE(){return Na.join($o.homedir(),".visa-mcp","allium-results")}var n$=16*1024,r$=50*1024*1024;function YE(){let e=WE();try{if(!pt.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=pt.readdirSync(e),n=0,r=0;for(let s of t)try{let o=pt.statSync(Na.join(e,s));o.isFile()&&(n+=o.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return g.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var ay=3600*1e3,Mu=0;function zE(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Oo(e){if(!gm()&&!(Date.now()<Mu))try{if(!await G.getSessionToken())return;await U.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}}),g.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(zE(t)){let n=Mu===0;Mu=Date.now()+ay,n&&g.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:ay});return}g.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function JE(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),s=(e.start_date||"").trim(),o=(e.end_date||s).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(s))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(o&&!/^\d{4}-\d{2}$/.test(o))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,c=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;g.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await Ee(async()=>{let l=await nt("get_visa_smi",a,i,c),u=await U.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:l,idempotencyKey:Ce.randomUUID()},t);return u.success?g.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):g.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(l){if(l instanceof he)return g.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),gt(l,{amount:a,merchantName:i,description:"Visa SMI data"});throw g.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:l.message}),l}}async function XE(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 Po("generate_image_card",e,t);if(n)return n;let r=await cn("generate_image_card",void 0,t),s=Ce.randomUUID();g.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await Ee(async()=>{let o;try{o=await Kn({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:ln(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof xe)return et(i);throw i}return g.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>tt(i)),Oo({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):g.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return g.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),gt(o,r);throw un(o,{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName}),o}}async function ZE(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 Po("generate_image_fast_card",e,t);if(n)return n;let r=await cn("generate_image_fast_card",void 0,t),s=Ce.randomUUID();g.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await Ee(async()=>{let o;try{o=await Kn({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:ln(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof xe)return et(i);throw i}return g.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>tt(i)),Oo({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):g.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return g.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),gt(o,r);throw un(o,{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName}),o}}async function QE(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 Po("generate_video_tempo_card",e,t);if(n)return n;let r=await cn("generate_video_tempo_card",void 0,t),s=Ce.randomUUID();g.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await Ee(async()=>{let o;try{o=await Kn({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:ln(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof xe)return et(i);throw i}return g.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>tt(i)),Oo({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):g.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return g.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),gt(o,r);throw un(o,{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName}),o}}async function eA(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 cn("generate_music_tempo_card",void 0,t),r=Ce.randomUUID();g.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Ee(async()=>{let s;try{s=await Kn({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:ln(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof xe)return et(o);throw o}return g.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(o=>tt(o)),Oo({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??n.amount,transactionId:s.transactionId,userContext:t})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,g.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):g.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof he)return g.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),gt(s,n);throw un(s,{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function tA(e,t){let n=await cn("check_music_status_tempo_card",void 0,t),r=Ce.randomUUID();g.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Ee(async()=>{let s;try{s=await Kn({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:ln(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof xe)return et(o);throw o}return g.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>tt(o)),s})}catch(s){if(s instanceof he)return g.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),gt(s,n);throw un(s,{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function nA(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 cn("query_onchain_prices",void 0,t),r=Ce.randomUUID();g.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await Ee(async()=>{let s;try{s=await Kn({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:ln(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof xe)return et(o);throw o}if(g.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(s?.data))s.data=s.data.map(o=>{if("mint"in o&&!("address"in o)){let{mint:i,...a}=o;return{address:i,...a}}return o});else if(s&&"mint"in s&&!("address"in s)){let{mint:o,...i}=s;return{address:o,...i}}return s})}catch(s){if(s instanceof he)return g.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),gt(s,n);throw un(s,{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName}),s}}var rA=["generate_music_tempo_card"],Cs=10,cy=5,ly=new Map;function uy(e){let t=ly.get(e);if(t!==void 0)return t;let r=lo(e)?.isAsync===!0||rA.includes(e);return ly.set(e,r),r}var sA=36e4,oA=18e4,iA=15e3,aA=12e4,cA=2e3;function Lu(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function lA(e,t){return Ce.createHash("sha256").update(`${e}:${Ia(t)}`).digest("hex")}function uA(e){let{results:t,batchId:n,index:r,item:s,itemResult:o,preview:i,isFree:a,catalogName:c}=e;a&&o&&typeof o=="object"&&!Array.isArray(o)&&o.merchantName==null&&(o.merchantName=c??s.resolvedTool),t.push({success:o?.success!==!1,tool:s.resolvedTool,...o,...$a(n,r,o)});let l=0,u=0n;if(o?.success!==!1){let d=mt(o?.amountMicros??o?.amount_micros),f=typeof o?.amount=="number"?o.amount:i?.amount??0;d!==null&&d>0n?u+=d:u+=BigInt(Math.round(f*1e6)),l+=f}return o?.urls&&o.urls.forEach(d=>tt(d)),{deltaCharged:l,deltaMicros:u}}function dA(e){let{results:t,resolvedItems:n,uniqueTools:r,isHomogeneous:s,primaryTool:o,merchantNames:i,totalAmount:a,totalCharged:c,totalChargedMicros:l,batchId:u,mode:d}=e,f=t.filter(I=>I?.success===!1).length,m=t.length-f,p=t.flatMap(I=>Array.isArray(I?.urls)?I.urls:[]),h=l>0n?Number(l)/1e6:Math.round((c+Number.EPSILON)*100)/100,v=m===0?"failure":f===0?"success":"partial";return g.info("payment:success",{tool:"batch",batchTool:o,count:n.length,totalAmount:a,totalCharged:h,merchant:i,successCount:m,failedCount:f,outcome:v,mode:d,batchId:u}),{success:m>0,outcome:v,batch_id:u,tool:s?r[0]:o,count:n.length,successCount:m,failedCount:f,totalCharged:h,...l>0n?{totalChargedMicros:l.toString(),amountMicros:l.toString(),amount_micros:l.toString()}:{},merchantName:i,results:t,...p.length?{urls:p}:{}}}async function fA(e){let{resolvedItems:t,previews:n,freeTools:r,catalogEntries:s,itemCeilingCents:o,batchCeilingCents:i,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,timeoutMs:f,batchId:m,userContext:p}=e,h=i,v=await U.getBalance();if(!v.success)throw new Error(`Could not read balance: ${v.error||"unknown error"}`);if(v.balanceCents<h)throw new xe(v.balanceCents,h);let I=`batch-${m}`,_=`spend up to $${(h/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:b}=await Ee(async()=>{let y=await nt("batch_open",h,I,_,p,{forceRequired:!0}),x=y?.nonce??(await U.getAttestationChallenge()).nonce;g.info("parentless-batch:open-attempt",{batchTool:l,count:t.length,approvedTotalCents:h,attested:!!y});let{batch_parent_id:Y}=await U.batchOpen({...y?{attestation:y}:{},nonce:x,approved_total_cents:h,batch_id:m});return{batchParentId:Y}});g.info("parentless-batch:opened",{batchTool:l,count:t.length,batchParentId:b});let w=[],T=0,A=0n;try{for(let y=0;y<t.length;y+=1){let x=t[y],Y=n[x.resolvedTool],X=r.has(x.resolvedTool);try{let K;if(X)K=await U.shortcut(x.resolvedTool,x.params,f,p,"batch");else{let{data:Z,voucherReceiptHeader:Os}=await U.shortcutParentlessBatchItem(x.resolvedTool,{batch_parent_id:b,batch_id:m,batch_index:y,batch_request_hash:lA(x.resolvedTool,x.params),item_ceiling_cents:o[y],idempotency_key:Uu(m,y,x.resolvedTool,x.params)},x.params,f,p,"batch");po(Os),go(Z?.receipt_v2),K=await _y(Z,null,Uu(m,y,x.resolvedTool,x.params))}let{deltaCharged:be,deltaMicros:se}=uA({results:w,batchId:m,index:y,item:x,itemResult:K,preview:Y,isFree:X,catalogName:s[x.resolvedTool]?.name});T+=be,A+=se}catch(K){if(K instanceof xe&&w.length===0)return et(K);g.warn("payment:batch-item-failed",{tool:x.resolvedTool,index:y,error:K?.message||String(K)}),w.push({success:!1,tool:x.resolvedTool,...$a(m,y),error:K?.message||String(K)})}}return dA({results:w,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:T,totalChargedMicros:A,batchId:m,mode:"parentless"})}catch(y){if(y instanceof he)return g.warn("payment:declined",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,code:y.code,retryable:y.retryable}),gt(y,{amount:d,merchantName:u});throw un(y,{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u}),y}}async function mA(e,t){let n;if(Array.isArray(e.requests)&&e.requests.length>Cs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Cs} items. Please split into smaller batches.`};if(e.requests?.some(y=>y.tool||y.tool_id)&&e.requests)n=e.requests.map(y=>{let x=y.tool||y.tool_id||e.tool;if(!x)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let Y=ul({requestedTool:x})??x,{tool:X,tool_id:K,tier:be,params:se,...Z}=y,Os=se&&typeof se=="object"?{...se,...Z}:Z;return{resolvedTool:Y,params:Os}});else if(e.tool){let y=ul({requestedTool:e.tool})??e.tool;if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return Lu("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>Cs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Cs} items. Please split into smaller batches.`}}n=(e.requests||(e.count!==void 0&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(Y=>({resolvedTool:y,params:Y}))}else return Lu("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Lu("BATCH_EMPTY","Batch requires at least one item.");if(n.length>Cs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Cs} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(uy)&&n.length>cy)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${cy} 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 Ry(y);let l=new Set(i.filter(y=>c[y]&&Da(c[y]))),u={};for(let y of i)l.has(y)||(u[y]=await cn(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let f=n.map(y=>GE(y,u,l)),m=f.reduce((y,x)=>y+x,0),p=[...new Set([...Object.values(u).map(y=>y.merchantName),...i.filter(y=>l.has(y)).map(y=>c[y]?.name??y)])].join(", "),h=a?i[0]:"mixed";g.info("payment:attempt",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p,heterogeneous:!a});let v=n.some(y=>uy(y.resolvedTool)),I=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),_=v?sA:I?oA+n.length*iA:aA+n.length*cA,b=Ce.randomUUID(),w=[],T=0,A=0n;return Ma(async()=>{let y=!On();if(xp()&&!sy&&y&&m>0)try{return await fA({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:f,batchCeilingCents:m,uniqueTools:i,isHomogeneous:a,primaryTool:h,merchantNames:p,totalAmount:d,timeoutMs:_,batchId:b,userContext:t})}catch(x){if(x instanceof vt)sy=!0,g.info("parentless-batch:falling-back-to-session",{batchTool:h,count:n.length,status:x.status,serverErrorCode:x.serverErrorCode});else{if(x instanceof xe)return et(x);throw x}}if(y&&m>0)try{let x=m;await Ee(()=>El(U,nt,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:x,capCentsOverride:x}))}catch(x){return x instanceof xe?et(x):(g.warn("payment:batch-prewarm-failed",{batchTool:h,count:n.length,error:x?.message||String(x)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:x?.message||"Failed to authenticate batch session",tool:h,count:n.length,failedCount:n.length,results:[]})}try{for(let se=0;se<n.length;se+=1){let Z=n[se],Os=u[Z.resolvedTool];try{let ue=l.has(Z.resolvedTool)?await U.shortcut(Z.resolvedTool,Z.params,_,t,"batch"):await hy({toolId:Z.resolvedTool,toolParams:Z.params,estimatedAmountCents:f[se],userContext:t,metaTool:"batch",timeoutMs:_,idempotencyKey:Uu(b,se,Z.resolvedTool,Z.params)});if(l.has(Z.resolvedTool)&&ue&&typeof ue=="object"&&!Array.isArray(ue)&&ue.merchantName==null&&(ue.merchantName=c[Z.resolvedTool]?.name??Z.resolvedTool),w.push({success:ue?.success!==!1,tool:Z.resolvedTool,...ue,...$a(b,se,ue)}),ue?.success!==!1){let Ns=mt(ue?.amountMicros??ue?.amount_micros),Sd=typeof ue?.amount=="number"?ue.amount:Os?.amount??0;Ns!==null&&Ns>0n?A+=Ns:A+=BigInt(Math.round(Sd*1e6)),T+=Sd}ue?.urls&&ue.urls.forEach(Ns=>tt(Ns))}catch(ue){if(ue instanceof xe&&w.length===0)return et(ue);g.warn("payment:batch-item-failed",{tool:Z.resolvedTool,index:se,error:ue?.message||String(ue)}),w.push({success:!1,tool:Z.resolvedTool,...$a(b,se),error:ue?.message||String(ue)})}}let x=w.filter(se=>se?.success===!1).length,Y=w.length-x,X=w.flatMap(se=>Array.isArray(se?.urls)?se.urls:[]),K=A>0n?Number(A)/1e6:Math.round((T+Number.EPSILON)*100)/100,be=Y===0?"failure":x===0?"success":"partial";return g.info("payment:success",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,totalCharged:K,merchant:p,successCount:Y,failedCount:x,outcome:be,mode:"session",batchId:b}),{success:Y>0,outcome:be,batch_id:b,tool:a?i[0]:h,count:n.length,successCount:Y,failedCount:x,totalCharged:K,...A>0n?{totalChargedMicros:A.toString(),amountMicros:A.toString(),amount_micros:A.toString()}:{},merchantName:p,results:w,...X.length?{urls:X}:{}}}catch(x){if(x instanceof he)return g.warn("payment:declined",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p,code:x.code,retryable:x.retryable}),gt(x,{amount:d,merchantName:p});throw un(x,{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p}),x}finally{if(y){let x=await Ki(U);g.info("batch-session:closed",{budgetId:x.budgetId,closedServerSide:x.closedServerSide})}}})}function pA(){let e=!1,t;try{let r=Na.join($o.homedir(),".claude","settings.json");if(pt.existsSync(r)){let s=JSON.parse(pt.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=bn(o)}}catch{}let n=ai();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function gA(e){let[t,n]=await Promise.all([U.getStatus(e),U.getBalance().catch(o=>(g.warn("get_status:balance_fetch_failed",{error:o?.message||String(o)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=YE();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=pA(),!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=Hu,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:qu(o)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(t.balanceCents=n.balanceCents,t.balanceMicros=n.balanceMicros,t.amountUsd=n.amountUsd);let s=On();if(t.sessionMode=!!s,s){let o=Math.max(0,s.totalCents-s.estimatedCumulative);t.activeSession={budgetId:s.budgetId,capCents:s.totalCents,capUsd:s.totalCents/100,lastReceiptCumulativeCents:s.lastReceiptCumulative,estimatedCumulativeCents:s.estimatedCumulative,spentCents:s.estimatedCumulative,spentUsd:s.estimatedCumulative/100,estimatedRemainingCents:o,estimatedRemainingUsd:o/100,...s.lastToolSpend?{lastToolSpend:{toolName:s.lastToolSpend.toolName,resolvedToolId:s.lastToolSpend.resolvedToolId,estimatedAmountCents:s.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:s.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:s.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:s.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:s.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:s.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:s.lastToolSpend.receiptRemainingCents,recordedAt:s.lastToolSpend.recordedAt}}:{},expiresAt:s.expiresAt}}return t}function qu(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),r=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",s=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${s}`}async function xy(e,t){try{let r=((await U.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return qu(r)}catch(n){g.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function hA(e){let n=(await U.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(s=>!Number.isInteger(s?.id)||s.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(s=>({...s,displayName:qu(s)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function yA(e,t){return await U.getTransactions({limit:e.limit,offset:e.offset},t)}async function _A(e,t){return await U.feedback(e.message,e.transaction_id,t)}async function bA(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Lr("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=Wi(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,s=r/100,o=Ce.randomUUID();g.info("buy_credits:attempt",{amountCents:r});try{return await Ee(async()=>{let i=await nt("balance-topup",s,"Visa CLI Balance",`top up balance with $${n.displayUsd}`,t,{forceRequired:!0}),a=await U.topupBalance({amount_cents:r,idempotency_key:o,attestation:i});if(a.success){g.info("buy_credits:success",{amountCents:r,balanceCents:a.balanceCents,balanceMicros:a.balanceMicros});let c=yE(a.balanceMicros,a.balanceCents??0),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 g.warn("buy_credits:failed",{amountCents:r,error:a.error}),a})}catch(i){if(i instanceof qn)return PE();if(i instanceof it)return g.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),IE(i);throw g.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function Lr(e,t){return{success:!1,error:t,code:e,message:t}}async function vA(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Lr("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 Lr("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 Lr("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return Lr("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");g.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await Ee(async()=>{let n=await nt("spending-controls",0,"","update spending controls"),r=await U.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return g.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(g.error("spending_controls:failure",{error:n.message}),n instanceof qn)return Ua(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return Lr("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function wA(e){let t=await fo({api:U,includeDev:!!e.includeDev});return{config:t.entries.map(n=>({key:n.key,value:n.value,source:n.source,hint:n.hint})),statusError:t.statusError}}var Ku=new Set(["auth.serverUrl"]);function Io(){return Object.keys(tr).filter(e=>!Ku.has(e)).sort()}function Cy(e,t){let n=t==="set"?`visa-cli config set ${e}=<value>`:`visa-cli config unset ${e}`;return{success:!1,error:`${e} cannot be changed via MCP. Run \`${n}\` directly from a shell instead.`,code:"MCP_FORBIDDEN_KEY",reason:"auth-trust-boundary key \u2014 a prompt-injected agent could redirect bearer-auth API calls to an attacker host (codex CLI-001 #752).",settableKeys:Io()}}async function SA(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."};if(Ku.has(e.key))return g.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Cy(e.key,"set");g.info("config:set",{key:e.key});try{let t=xi(e.key,e.value);return g.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 at?"UNKNOWN_KEY":t instanceof Kt?"SERVER_CONTROLLED":t instanceof vn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof at?`Unknown setting "${e.key}". MCP-settable keys: ${Io().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return g.warn("config:set:rejected",{key:e.key,code:n,error:r}),{success:!1,error:r,code:n,settableKeys:Io()}}}async function xA(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."};if(Ku.has(e.key))return g.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Cy(e.key,"unset");g.info("config:unset",{key:e.key});try{let t=Ci(e.key);return g.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 at?"UNKNOWN_KEY":t instanceof Kt?"SERVER_CONTROLLED":t instanceof vn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof at?`Unknown setting "${e.key}". MCP-settable keys: ${Io().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return g.warn("config:unset:rejected",{key:e.key,code:n,error:r}),{success:!1,error:r,code:n,settableKeys:Io()}}}async function CA(e){let t=await U.getStatus(e),n=t.attestationRequired!==!1,r=kt(t),s=de(),o=n?r?s?`${Pa()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Pa()} is not available in this process. ${Vu()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:s,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&s,canDisableFromThisDevice:!n||!r||s,message:o}}async function EA(e){g.info("biometric:on");let t=await Bi(U,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 U.setBiometricPreference({required:!0},e);return n.success?(Sy(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function AA(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Lr("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.");g.info("biometric:off");try{return await Ee(async()=>{let n=await U.getStatus(t),r;if(kt(n)&&(r=await nt("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Pa()} confirmation required to disable \u2014 not available on this device.`);let s=await U.setBiometricPreference({required:!1,attestation:r},t);if(!s.success)throw new Error(s.error||"unknown error");return Sy(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(g.error("biometric:off:failure",{error:n.message}),n instanceof qn)return Ua(n,"biometric_off");throw n}}var dy=3e4,kA=3e5;async function Ey(e,t,n="login"){let r=Ce.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`,o=tt(s);return!o.opened&&o.blockedReason!=="non_internal_host"&&o.blockedReason!=="invalid_url"?Ay(s,o,n):o.opened?{...await ky(r,t,n),browserUrl:s}:{success:!1,browserUrl:s,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${s}`}}function Ay(e,t,n){let r=n==="enrollment"?"card enrollment":n==="attestation-recovery"?"biometric reset":"login",s=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 ${s}. Open this URL to continue ${r}: ${e}`}}async function ky(e,t,n="login"){let r=Date.now()+kA;for(;Date.now()<r;)try{let o=await fetch(`${La()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:dy,...t&&{user_context:t}}),signal:AbortSignal.timeout(dy+5e3)});if(!o.ok){await hn(o,a=>{g.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:a})});continue}let i=await o.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return g.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=kp(a);if(n!=="enrollment"&&i.sessionToken){await G.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return g.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 g.info("auth:card_added",{last4:l,bonusCents:a}),{success:!0,message:`Card ending in ${l} enrolled and ready for payments.`,...c||{}}}}catch{await hn(void 0,o=>{g.warn("auth_status:retry_after_network_error",{delayMs:o})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function Ty(e){let t=Ce.randomUUID(),n;try{n=await U.startAttestationRecovery(t,e)}catch(o){return{success:!1,message:`Could not start biometric reset: ${o?.message||"unknown error"}`}}if(!n.success||!n.recoveryUrl)return{success:!1,message:n.error||"Could not start biometric reset. Please try again."};let r=tt(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?Ay(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await ky(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 TA(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."};g.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,s=`remove ${await xy(n,t)}`;try{return await Ee(async()=>{let o=await nt(r,0,"",s,t,{forceRequired:!0}),i=await U.removeCard(n,{attestation:o},t);return g.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(o){if(g.error("cards:remove_failure",{cardId:n,error:o.message}),o instanceof qn)return Ua(o,"remove_card");throw o}}async function RA(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."};g.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,s=`set ${await xy(n,t)} as default`;try{return await Ee(async()=>{let o=await nt(r,0,"",s,t,{forceRequired:!0}),i=await U.setDefaultCard(n,{attestation:o},t);return g.info("cards:set_default_success",{cardId:n}),i})}catch(o){if(g.error("cards:set_default_failure",{cardId:n,error:o.message}),o instanceof qn)return Ua(o,"set_default_card");throw o}}async function IA(e){return g.info("auth:login_attempt"),Ey(`${La()}/login`,e)}async function $A(e=by()){if(!e)return{success:!1,message:"The Visa Verified Agent enrollment flow is not yet publicly available in stable builds. Set VISA_VERIFY_WEB_URL to a deployment URL to use enroll_agent."};g.info("agent:enroll_open",{url:e});let t=tt(e),n="sign in \u2192 pick your .visa name \u2192 wallet \u2192 card (secure fields) \u2192 bank verification with passkey \u2192 mint";return t.opened?{success:!0,opened:!0,browserUrl:t.url,message:`Opened the Visa Verified Agent enrollment in your browser (${n}). Access is currently tester-gated \u2014 if sign-in shows "private testing", ask for the v4_verify_web_access flag.`}:{success:!0,opened:!1,requiresBrowser:!0,browserUrl:t.url??e,message:`Open this URL in a browser to enroll your agent (${n}): ${t.url??e}`}}function PA(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 OA(e={},t){let n;try{n=PA(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Ma(async()=>{let r=await Ee(()=>jp(U,nt,{toolName:"start_session",userContext:t,capCentsOverride:n}));g.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let s=(r.appliedCapCents/100).toFixed(2),o=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${s} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${o} was clamped to your prepaid balance of $${s}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function NA(){let e=On();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 MA(){return Ma(async()=>{let e=On();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 Ki(U);g.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=EE(e),r=mt(t.finalCumulativeMicros),s=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),o=Number(s/10000n);return g.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:s.toString(),finalSpendCents:o,finalSpendSource:r!==null?"server.finalCumulativeMicros":typeof t.finalCumulativeCents=="number"?"server.finalCumulativeCents":n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:o,finalEstimatedCumulativeMicros:s.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${CE(s)} of $${(e.totalCents/100).toFixed(2)} cap. Future paid calls are pay-as-you-go until you start a new explicit approval window.`:"Explicit approval window cleared locally; server-side close call did not succeed (likely already closed). Future paid calls are pay-as-you-go until you start a new explicit approval window."}})}async function LA(e){if(g.info("auth:add_card_attempt"),!await G.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await U.createEnrollCode();return Ey(`${La()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function fy(){if(await G.clearAll(),de())try{await ji()}catch{}}async function UA(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(g.info("reset:attempt"),e.localOnly)return await fy(),g.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 U.getStatus(t);if(r&&kt(r)){let s=await Ty(t);if(!s.success)return s;n=!0}}catch(r){let s=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(s))return{success:!1,message:`Could not check server biometric state: ${s}`};g.warn("reset:server_attestation_status_unavailable",{error:s})}try{await U.logout(void 0,t)}catch{}return await fy(),g.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 DA(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;g.info("catalog:discover",{query:t,category:n,browseAll:r});try{let o=(await U.catalogSearch(t,n)).tools||[];if(o.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let l of o){let u=l.category||"other";(a[u]??=[]).push(l)}let c=Object.keys(a).sort().map(l=>{let u=a[l].map((f,m)=>`${m+1}. **${f.name}** (${f.id})
147
147
  ${f.description}
148
148
  Provider: ${f.provider} | Price: ${my(f)}${py(f)}
@@ -170,7 +170,7 @@ Use execute_tool with the tool id and required params to run any of these.`}],_t
170
170
  `),!0}function Oy(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){let o={};for(let i of t)o[i]=Py(i,n[i]?.description);return o}let r=Object.keys(n).slice(0,2);if(r.length===0)return{prompt:"a lobster"};let s={};for(let o of r)s[o]=Py(o,n[o]?.description);return s}function Py(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 XA(e){let t=Mt(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=Mt(e.referralLink,"");if(r&&n.push(` Your link ${r}`),typeof e.referralCount=="number"&&Number.isFinite(e.referralCount)){let s=Math.max(0,Math.trunc(e.referralCount));n.push(` Joined ${s} ${s===1?"person":"people"} via your link`)}return n}var ZA=20;function My(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=o1(e.spendingControls).dailyLimit,a=Math.max(0,No(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,No(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(t1),f=d.slice(0,3),m=n1(d,3),p=(e.cards??[]).slice(0,3),h=r.latestVersion?Ur(r.latestVersion):"",v=r.updateCheckDisabled?"update checks disabled":h?`update ready: v${h}`:"up to date",I=Math.round(l*100),_=Mt(e.status,e.enrolled?"approved":"not enrolled"),w=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${_} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${v}`,`Top-up meter: ${Ny(l)} ${String(I).padStart(3," ")}% | remaining ${ks(c)}/day | daily top-up cap ${ks(i)}`,"","Card top-ups",` Remaining ${ks(c)} / ${ks(i)}`,` Usage ${Ny(l)} ${I}%`,` Top-ups today ${ks(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...p.length>0?p.map(A=>` ${s1(A)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((A,y)=>` ${y+1}. ${A}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(A=>` ${r1(A)}`):[" No receipts yet"]],T=XA(e);return T.length>0&&w.push("",...T),h&&!r.updateCheckDisabled?(w.push("",`Update: v${h} ready \u2014 run \`visa-cli update\``),r.updateMessage&&w.push(` ${Ur(r.updateMessage)}`)):r.updateMessage&&w.push("",`Update: ${Ur(r.updateMessage)}`),`${w.join(`
171
171
  `)}
172
172
  `}function QA(e){return e.tool_name!=null}function e1(e){return No(e.amount)===0&&e.status==="failed"}function t1(e){return QA(e)&&!e1(e)}function n1(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=Mt(s.merchant_name,"Unknown merchant"),i=Mt(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function r1(e){let t=Mt(e.merchant_name,"Unknown merchant"),n=Mt(e.tool_name,"unknown_tool"),r=ks(No(e.amount)),s=Mt(e.status,"unknown"),o=i1(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function s1(e){let t=Mt(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function o1(e){return{dailyLimit:No(e?.daily_limit??e?.dailyLimit??0)}}function No(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function ks(e){return`$${e.toFixed(2)}`}function Ny(e,t=ZA){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Mt(e,t){let n=Ur(e??"").trim();return n.length>0?n:t}function i1(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Mt(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function Ur(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 a1=/^[1-9]\d{0,9}$/;function Gu(e){if(!a1.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 Ly(e){let t=Ur(e.brand||"Visa"),n=Ur(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 Lt=R(require("fs")),_e=R(require("path")),c1=["npm","pnpm","yarn","bun"],l1=/\s+/,u1=process.platform==="win32"?"visa-cli.cmd":"visa-cli",Wu=["node_modules","@visa","cli"];function d1(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(l1)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return c1.includes(s)?s:void 0}function Yu(e){if(!e)return;let t=e;try{t=Lt.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 f1(e=process.argv[1]){return d1()??Yu(process.env.npm_execpath)??Yu(process.env.npm_node_execpath)??Yu(e)}function m1(e=process.env.PATH??""){let t=[];for(let n of e.split(_e.delimiter))n&&t.push(n);return t}function p1(e=process.env.PATH??""){let t=new Set,n=[];for(let r of m1(e))try{let s=_e.join(r,u1);Lt.accessSync(s,Lt.constants.X_OK);let o=_e.resolve(s);t.has(o)||(t.add(o),n.push(s))}catch{}return n}function Uy(e){try{let t=Lt.readFileSync(_e.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function g1(e){let t=_e.resolve(e).split(_e.sep);for(let n=t.length-Wu.length;n>=0;n--)if(Wu.every((r,s)=>t[n+s]===r)){let r=t.slice(0,n+Wu.length).join(_e.sep)||_e.sep;if(Uy(r))return r}}function h1(e){if(!e)return;let t=_e.normalize(e),n=t.split(_e.sep),r=o=>o.every((a,c)=>n[n.length-o.length+c]===a)?n.slice(0,-o.length).join(_e.sep)||_e.parse(t).root:void 0,s=r(["lib","node_modules","@visa","cli"]);if(s)return s;if(process.platform==="win32")return r(["node_modules","@visa","cli"])}function y1(e,t){let n=_e.resolve(e);try{n=Lt.realpathSync(e)}catch{}let r=g1(n);return{binPath:e,realPath:n,packageRoot:r,version:r?Uy(r):void 0,prefix:h1(r),isActive:n===t}}function _1(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?_e.resolve(n):"";try{n&&(r=Lt.realpathSync(n))}catch{}let s=e?[e]:[n,...p1(t)].filter(Boolean),o=new Map;for(let d of s){let f=y1(d,r),m=o.get(f.realPath);o.set(f.realPath,m?{...f,binPath:m.binPath}:f)}let i=[...o.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 b1(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function zu(e,t,n,r={}){let s=t??f1(n)??"npm",o=r.withDiagnostics?_1(n):void 0,a=`@visa/cli@${e??"latest"}`;switch(s){case"npm":if(o?.hasConflictingInstalls&&o.recommendedPrefix){let c=o.recommendedPrefix;return{packageManager:s,command:"npm",args:["install","-g","--prefix",c,a],display:`npm install -g --prefix ${b1(c)} ${a}`,diagnostics:o}}return{packageManager:s,command:"npm",args:["install","-g",a],display:`npm install -g ${a}`,diagnostics:o};case"pnpm":return{packageManager:s,command:"pnpm",args:["add","-g",a],display:`pnpm add -g ${a}`,diagnostics:o};case"yarn":return{packageManager:s,command:"yarn",args:["global","add",a],display:`yarn global add ${a}`,diagnostics:o};case"bun":return{packageManager:s,command:"bun",args:["add","-g",a],display:`bun add -g ${a}`,diagnostics:o}}}function v1(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 Ju(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(v1)];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(`
173
- `)}var Wa=R(as());function w1(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function Dy(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=w1(e);return e.attestationRequired!==!1||t?{canContinue:!1,message:"Biometric attestation is unavailable, but this account requires a registered local attestation key.",hint:"Options: (1) Re-run setup from a device with Touch ID (Mac) or Windows Hello (PC). (2) Server/CI with no display: from a browser-authenticated device run `visa-cli config biometric off`, then re-run setup here \u2014 setup succeeds once the server no longer requires a local key."}:{canContinue:!0,message:"Biometric attestation is unavailable; continuing only because server biometric policy is disabled and no attestation key is registered."}}async function jy(){await G.deleteSessionToken()}var Be=R(require("fs")),ja=R(require("os")),Dr=R(require("path"));xa();St();xo();var Xu="4.0.0-rc.16",Mo=Dr.join(ja.homedir(),".visa-cli","agents");function Fy(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.agent_jkt=="string"&&typeof t.name=="string"&&t.public_key_jwk?.kty==="OKP"&&t.public_key_jwk.crv==="Ed25519"&&typeof t.public_key_jwk.x=="string"&&t.private_key_jwk?.kty==="OKP"&&t.private_key_jwk.crv==="Ed25519"&&typeof t.private_key_jwk.x=="string"&&typeof t.private_key_jwk.d=="string"&&typeof t.binding_jwt=="string"&&typeof t.auth_url=="string"&&typeof t.created_at=="string"}function S1(){return!!(process.env.VISA_DEV==="1"||Xu==="0.0.0"||Xu.startsWith("0.0.")||/-rc\.|-beta\./.test(Xu))}function x1(e=Mo){Be.mkdirSync(e,{recursive:!0,mode:448})}function Ts(e,t=Mo){return Dr.join(t,`${e}.json`)}function C1(e=Mo){return Be.existsSync(e)?Be.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>Dr.join(e,t)):[]}function E1(e,t=Mo){let n=Ts(e,t);if(!Be.existsSync(n))return null;try{let r=JSON.parse(Be.readFileSync(n,"utf8"));return Fy(r)?r:null}catch{return null}}function By(e,t=Mo){x1(t);let n=Ts(e.agent_jkt,t);Be.writeFileSync(n,JSON.stringify(e,null,2),{mode:384})}function A1(e){let t=e.split(".");if(t.length!==3)return null;try{let n=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return n===null||typeof n!="object"||Array.isArray(n)?null:n}catch{return null}}async function k1(e){let t=e.authUrl??Se(),n=e.apiKey??process.env.VISA_CLI_API_KEY?.trim();if(!n)throw new Error("No Visa Key configured \u2014 run `visa-cli setup` first, mint one with `visa-cli keys create`, and set VISA_CLI_API_KEY.");let{secretKey:r}=Ih(),s=Oh(r),o={kty:"OKP",crv:"Ed25519",x:s.x},i=Ca(o),a={agent_jkt:i,name:e.name,public_key_jwk:o,private_key_jwk:s,binding_jwt:"",auth_url:t,created_at:new Date().toISOString()};By(a,e.agentDir);let c;try{c=await So({authUrl:t,apiKey:n,seed:Sa(s),name:e.name,fetchImpl:e.fetchImpl,nowSec:e.nowSec})}catch(l){let u=l instanceof Nr||l instanceof Ze;if(u)try{Be.rmSync(Ts(i,e.agentDir),{force:!0})}catch{}let d=T1(l);throw u?d:new Error(`${d.message} The agent key was kept because issuance may have committed; inspect it with \`visa-cli agent show ${i}\` before creating another agent.`)}return a.binding_jwt=c.binding,By(a,e.agentDir),{record:a,expiresInSeconds:c.expires_in}}function T1(e){if(e instanceof Ze)return new Error(`No card on file \u2014 enroll a card first (visa-cli setup): ${e.enrollUrl}`);if(e instanceof Nr){if(e.status===404)return new Error("Agent binding issuance is not enabled on this server.");if(e.status===401)return new Error("Not authenticated \u2014 run `visa-cli setup` first (and set VISA_CLI_API_KEY to a valid Visa Key).")}return e instanceof Error?e:new Error(String(e))}function Hy(e){if(!S1())return;let t=e.command("agent").description("(dev/rc) Manage agent identities \u2014 Visa-signed bindings minted by the auth service.");t.command("create").description("Generate an Ed25519 keypair and mint a Visa-signed binding for it via POST /v2/harness/agents.").option("--name <name>","Human-readable name for this agent",`${process.env.USER??"user"}@${ja.hostname()}`).action(async n=>{try{let{record:r,expiresInSeconds:s}=await k1({name:n.name}),o=new Date(Date.now()+s*1e3).toISOString();process.stdout.write(["\u2713 Agent bound",` agent jkt: ${r.agent_jkt}`,` name: ${r.name}`,` expires: ${o} (${s}s)`,` key file: ${Ts(r.agent_jkt)}`,"","Inspect the binding claims with:","",` visa-cli agent show ${r.agent_jkt}`,""].join(`
173
+ `)}var Wa=R(as());function w1(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function Dy(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=w1(e);return e.attestationRequired!==!1||t?{canContinue:!1,message:"Biometric attestation is unavailable, but this account requires a registered local attestation key.",hint:"Options: (1) Re-run setup from a device with Touch ID (Mac) or Windows Hello (PC). (2) Server/CI with no display: from a browser-authenticated device run `visa-cli config biometric off`, then re-run setup here \u2014 setup succeeds once the server no longer requires a local key."}:{canContinue:!0,message:"Biometric attestation is unavailable; continuing only because server biometric policy is disabled and no attestation key is registered."}}async function jy(){await G.deleteSessionToken()}var Be=R(require("fs")),ja=R(require("os")),Dr=R(require("path"));xa();St();xo();var Xu="4.0.0-rc.17",Mo=Dr.join(ja.homedir(),".visa-cli","agents");function Fy(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.agent_jkt=="string"&&typeof t.name=="string"&&t.public_key_jwk?.kty==="OKP"&&t.public_key_jwk.crv==="Ed25519"&&typeof t.public_key_jwk.x=="string"&&t.private_key_jwk?.kty==="OKP"&&t.private_key_jwk.crv==="Ed25519"&&typeof t.private_key_jwk.x=="string"&&typeof t.private_key_jwk.d=="string"&&typeof t.binding_jwt=="string"&&typeof t.auth_url=="string"&&typeof t.created_at=="string"}function S1(){return!!(process.env.VISA_DEV==="1"||Xu==="0.0.0"||Xu.startsWith("0.0.")||/-rc\.|-beta\./.test(Xu))}function x1(e=Mo){Be.mkdirSync(e,{recursive:!0,mode:448})}function Ts(e,t=Mo){return Dr.join(t,`${e}.json`)}function C1(e=Mo){return Be.existsSync(e)?Be.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>Dr.join(e,t)):[]}function E1(e,t=Mo){let n=Ts(e,t);if(!Be.existsSync(n))return null;try{let r=JSON.parse(Be.readFileSync(n,"utf8"));return Fy(r)?r:null}catch{return null}}function By(e,t=Mo){x1(t);let n=Ts(e.agent_jkt,t);Be.writeFileSync(n,JSON.stringify(e,null,2),{mode:384})}function A1(e){let t=e.split(".");if(t.length!==3)return null;try{let n=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return n===null||typeof n!="object"||Array.isArray(n)?null:n}catch{return null}}async function k1(e){let t=e.authUrl??Se(),n=e.apiKey??process.env.VISA_CLI_API_KEY?.trim();if(!n)throw new Error("No Visa Key configured \u2014 run `visa-cli setup` first, mint one with `visa-cli keys create`, and set VISA_CLI_API_KEY.");let{secretKey:r}=Ih(),s=Oh(r),o={kty:"OKP",crv:"Ed25519",x:s.x},i=Ca(o),a={agent_jkt:i,name:e.name,public_key_jwk:o,private_key_jwk:s,binding_jwt:"",auth_url:t,created_at:new Date().toISOString()};By(a,e.agentDir);let c;try{c=await So({authUrl:t,apiKey:n,seed:Sa(s),name:e.name,fetchImpl:e.fetchImpl,nowSec:e.nowSec})}catch(l){let u=l instanceof Nr||l instanceof Ze;if(u)try{Be.rmSync(Ts(i,e.agentDir),{force:!0})}catch{}let d=T1(l);throw u?d:new Error(`${d.message} The agent key was kept because issuance may have committed; inspect it with \`visa-cli agent show ${i}\` before creating another agent.`)}return a.binding_jwt=c.binding,By(a,e.agentDir),{record:a,expiresInSeconds:c.expires_in}}function T1(e){if(e instanceof Ze)return new Error(`No card on file \u2014 enroll a card first (visa-cli setup): ${e.enrollUrl}`);if(e instanceof Nr){if(e.status===404)return new Error("Agent binding issuance is not enabled on this server.");if(e.status===401)return new Error("Not authenticated \u2014 run `visa-cli setup` first (and set VISA_CLI_API_KEY to a valid Visa Key).")}return e instanceof Error?e:new Error(String(e))}function Hy(e){if(!S1())return;let t=e.command("agent").description("(dev/rc) Manage agent identities \u2014 Visa-signed bindings minted by the auth service.");t.command("create").description("Generate an Ed25519 keypair and mint a Visa-signed binding for it via POST /v2/harness/agents.").option("--name <name>","Human-readable name for this agent",`${process.env.USER??"user"}@${ja.hostname()}`).action(async n=>{try{let{record:r,expiresInSeconds:s}=await k1({name:n.name}),o=new Date(Date.now()+s*1e3).toISOString();process.stdout.write(["\u2713 Agent bound",` agent jkt: ${r.agent_jkt}`,` name: ${r.name}`,` expires: ${o} (${s}s)`,` key file: ${Ts(r.agent_jkt)}`,"","Inspect the binding claims with:","",` visa-cli agent show ${r.agent_jkt}`,""].join(`
174
174
  `))}catch(r){process.stderr.write(`agent create failed: ${r instanceof Error?r.message:String(r)}
175
175
  `),process.exit(1)}}),t.command("list").description("List locally stored agent identities.").action(()=>{let n=C1();if(n.length===0){process.stdout.write("No agents yet. Run `visa-cli agent create` to bind one.\n");return}for(let r of n){let s;try{s=JSON.parse(Be.readFileSync(r,"utf8"))}catch{process.stderr.write(`Skipped unreadable agent record: ${Dr.basename(r)}
176
176
  `);continue}if(!Fy(s)){process.stderr.write(`Skipped legacy agent record: ${Dr.basename(r)}; run \`visa-cli agent create\` to migrate it.
@@ -178,7 +178,7 @@ Use execute_tool with the tool id and required params to run any of these.`}],_t
178
178
  `)}}),t.command("show <jkt>").description("Show an agent record and the decoded (unverified) binding claims.").action(n=>{let r=E1(n);if(!r){let o=Ts(n);process.stderr.write(Be.existsSync(o)?`Legacy or unreadable agent record: ${n}; run \`visa-cli agent create\` to migrate it.
179
179
  `:`Agent not found: ${n}
180
180
  `),process.exit(1)}let s=r.binding_jwt?A1(r.binding_jwt):null;process.stdout.write([`agent jkt: ${r.agent_jkt}`,`name: ${r.name}`,`created: ${r.created_at}`,`auth server: ${r.auth_url}`,`public key: ${r.public_key_jwk.x} (Ed25519, OKP)`,`key file: ${Ts(r.agent_jkt)}`,"binding claims (decoded locally, NOT verified):",s?JSON.stringify(s,null,2):" (no binding stored or malformed JWT)",""].join(`
181
- `))})}Xl();xs();xo();var R1="4.0.0-rc.16";async function Vy(e){let t=await Ru(e);console.log(`\u2713 registered "${t.relayName}" on the "${t.mesh}" mesh`),console.log(` peer: ${t.peerId??"(pending)"}`),console.log(` identity: ${t.tapAgentId?`reused TAP key ${t.tapAgentId}`:"stable Subway key (no TAP agent found)"}`),console.log(` relay: ${Ao} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var Lo=(e,t)=>{if(t instanceof Ze){console.error(`\u2717 ${e}: ${t.message}`),console.error(` \u2192 enroll a card: ${t.enrollUrl}`),console.error(" \u2192 then re-run: visa register <name>"),process.exitCode=1;return}console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function qy(e){if(!Eu(R1))return;e.command("register <name>").description(`Register a name on the "${Ie}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async n=>{try{await Vy(n)}catch(r){Lo("register",r)}});let t=e.command("subway").description("Subway agent-to-agent messaging over the Visa CLI.");t.command("register <name>").description("Alias of `visa register <name>`.").action(async n=>{try{await Vy(n)}catch(r){Lo("register",r)}}),t.command("send <to> <text>").description("Send a direct signed message to another agent.").option("--as <name>","Registered name to send as (default: the only one registered)").action(async(n,r,s)=>{try{let o=Ra(s.as),i=await $u(o,n,r);console.log(`\u2713 sent to ${i.to} as ${i.as}`)}catch(o){Lo("send",o)}}),t.command("find <name>").description("Look up another agent on the .visa relay \u2014 is it live, and who is it?").action(async n=>{try{let r=await Iu(n);r.found?(console.log(`\u2713 ${r.relayName} is live`),console.log(` peer: ${r.peerId}`)):(console.log(`\u2717 ${r.relayName} not found${r.error?` (${r.error})`:""}`),process.exitCode=1)}catch(r){Lo("find",r)}}),t.command("listen").description("Stay connected and print inbound messages (Ctrl-C to stop).").option("--as <name>","Registered name to listen as (default: the only one registered)").option("--room <topic>","Also subscribe to a room topic").action(async n=>{try{let r=Ra(n.as),s=ws(r,{autoReconnect:!0});await Ss(s);let o=a=>new Date(a).toLocaleTimeString();s.onMessage(a=>{let c=a.verified?"":" (unverified)";console.log(`[${o(a.timestampMs)}] ${a.fromName}${c}: ${a.payload}`)}),n.room&&s.subscribe(n.room,a=>{console.log(`[${o(a.timestampMs)}] #${a.topic} ${a.fromName}: ${a.payload}`)}),console.log(`\u2026 listening as ${Ar(r)} on "${Ie}" mesh${n.room?` (room #${n.room})`:""}. Ctrl-C to stop.`);let i=()=>{s.disconnect(),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i),await new Promise(()=>{})}catch(r){Lo("listen",r)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let n=Pu();if(n.length===0){console.log("No Subway names registered. Run `visa register <name>`.");return}for(let r of n)console.log(`${r.relayName} mesh=${r.mesh} peer=${r.peerId??"?"} ${r.tapAgentId?`tap=${r.tapAgentId}`:"(standalone key)"} registered=${r.registeredAt}`)})}St();qt();St();var I1=["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","enroll_agent","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"],$1=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"];function P1(){let e=new Set;for(let t of I1)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of $1)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var M$=P1();var Zu=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 F$=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Zu]);St();var W=R(require("fs")),F=R(require("path")),Ky=R(require("os")),me=Ky.homedir(),O1=["Claude_","Anthropic.ClaudeDesktop_"],Rs=class extends Error{constructor(n,r,s){super(M1(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function Gy(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
181
+ `))})}Xl();xs();xo();var R1="4.0.0-rc.17";async function Vy(e){let t=await Ru(e);console.log(`\u2713 registered "${t.relayName}" on the "${t.mesh}" mesh`),console.log(` peer: ${t.peerId??"(pending)"}`),console.log(` identity: ${t.tapAgentId?`reused TAP key ${t.tapAgentId}`:"stable Subway key (no TAP agent found)"}`),console.log(` relay: ${Ao} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var Lo=(e,t)=>{if(t instanceof Ze){console.error(`\u2717 ${e}: ${t.message}`),console.error(` \u2192 enroll a card: ${t.enrollUrl}`),console.error(" \u2192 then re-run: visa register <name>"),process.exitCode=1;return}console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function qy(e){if(!Eu(R1))return;e.command("register <name>").description(`Register a name on the "${Ie}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async n=>{try{await Vy(n)}catch(r){Lo("register",r)}});let t=e.command("subway").description("Subway agent-to-agent messaging over the Visa CLI.");t.command("register <name>").description("Alias of `visa register <name>`.").action(async n=>{try{await Vy(n)}catch(r){Lo("register",r)}}),t.command("send <to> <text>").description("Send a direct signed message to another agent.").option("--as <name>","Registered name to send as (default: the only one registered)").action(async(n,r,s)=>{try{let o=Ra(s.as),i=await $u(o,n,r);console.log(`\u2713 sent to ${i.to} as ${i.as}`)}catch(o){Lo("send",o)}}),t.command("find <name>").description("Look up another agent on the .visa relay \u2014 is it live, and who is it?").action(async n=>{try{let r=await Iu(n);r.found?(console.log(`\u2713 ${r.relayName} is live`),console.log(` peer: ${r.peerId}`)):(console.log(`\u2717 ${r.relayName} not found${r.error?` (${r.error})`:""}`),process.exitCode=1)}catch(r){Lo("find",r)}}),t.command("listen").description("Stay connected and print inbound messages (Ctrl-C to stop).").option("--as <name>","Registered name to listen as (default: the only one registered)").option("--room <topic>","Also subscribe to a room topic").action(async n=>{try{let r=Ra(n.as),s=ws(r,{autoReconnect:!0});await Ss(s);let o=a=>new Date(a).toLocaleTimeString();s.onMessage(a=>{let c=a.verified?"":" (unverified)";console.log(`[${o(a.timestampMs)}] ${a.fromName}${c}: ${a.payload}`)}),n.room&&s.subscribe(n.room,a=>{console.log(`[${o(a.timestampMs)}] #${a.topic} ${a.fromName}: ${a.payload}`)}),console.log(`\u2026 listening as ${Ar(r)} on "${Ie}" mesh${n.room?` (room #${n.room})`:""}. Ctrl-C to stop.`);let i=()=>{s.disconnect(),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i),await new Promise(()=>{})}catch(r){Lo("listen",r)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let n=Pu();if(n.length===0){console.log("No Subway names registered. Run `visa register <name>`.");return}for(let r of n)console.log(`${r.relayName} mesh=${r.mesh} peer=${r.peerId??"?"} ${r.tapAgentId?`tap=${r.tapAgentId}`:"(standalone key)"} registered=${r.registeredAt}`)})}St();qt();St();var I1=["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","enroll_agent","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"],$1=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"];function P1(){let e=new Set;for(let t of I1)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of $1)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var M$=P1();var Zu=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 F$=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Zu]);St();var W=R(require("fs")),F=R(require("path")),Ky=R(require("os")),me=Ky.homedir(),O1=["Claude_","Anthropic.ClaudeDesktop_"],Rs=class extends Error{constructor(n,r,s){super(M1(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function Gy(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
182
182
  `)}function N1(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Gy(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function M1(e,t,n){let r=t.replace(me,"~"),s=Gy(n).split(`
183
183
  `).find(Boolean),o=s?` (${s})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${o}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${o}.`}function Uo(){return process.env.APPDATA||F.join(me,"AppData","Roaming")}function L1(){return process.env.LOCALAPPDATA||F.join(me,"AppData","Local")}function Qu(e){return process.platform==="win32"?e.win32:e.posix}function Wy(){if(process.platform!=="win32")return;let e=F.join(L1(),"Packages");if(W.existsSync(e))try{let t=W.readdirSync(e,"utf-8");for(let n of O1){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return F.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function Yy(){if(process.platform==="win32"){let e=Wy();return e?F.join(e,"claude_desktop_config.json"):F.join(Uo(),"Claude","claude_desktop_config.json")}return F.join(me,"Library","Application Support","Claude","claude_desktop_config.json")}function zy(){if(process.platform!=="win32")return[F.join(me,"Library","Application Support","Claude")];let e=[F.join(Uo(),"Claude")],t=Wy();return t&&e.push(t),e}function Ba(e){return e.id==="claude-desktop"?Yy():e.globalConfigPath}function U1(e){return e.id==="claude-desktop"?zy():e.detectPaths}var ht=[{id:"claude",displayName:"Claude Code",globalConfigPath:F.join(me,".claude.json"),configKey:"mcpServers",detectPaths:[F.join(me,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:Yy(),configKey:"mcpServers",detectPaths:zy(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:F.join(me,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[F.join(me,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:F.join(me,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[F.join(me,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:F.join(me,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[F.join(me,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:Qu({win32:F.join(Uo(),"Roo","mcp_settings.json"),posix:F.join(me,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[F.join(me,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:F.join(me,".vscode","mcp.json"),configKey:"servers",detectPaths:[F.join(me,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:Qu({win32:F.join(Uo(),"Zed","settings.json"),posix:F.join(me,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:Qu({win32:[F.join(Uo(),"Zed")],posix:[F.join(me,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:F.join(me,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[F.join(me,".codex")],postInstallHint:"Restart Codex to connect."}];function ed(e){return ht.find(t=>t.id===e)}function Do(e){return U1(e).some(t=>{if(t.includes("*")){let n=F.dirname(t),r=F.basename(t).replaceAll("*","");if(!W.existsSync(n))return!1;try{return W.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return W.existsSync(t)})}function Jy(){return{command:"node",args:[F.resolve(__dirname,"mcp-server/index.js")]}}function td(e,t){return t==="project"?"json":e.configFormat??"json"}function D1(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 nd(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(o=>o.trim()===n);if(r===-1)return;let s=r+1;for(;s<e.length&&!e[s].trim().startsWith("[");)s++;return{start:r,end:s}}function rd(e,t){let n=e.split(`
184
184
  `),r=nd(n,t);if(!r)return;let s={};for(let o=r.start+1;o<r.end;o++){let i=n[o].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(s[i[1]]=D1(i[2]))}return Object.keys(s).length>0?s:void 0}function j1(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`