@visa/cli 4.1.0-rc.58 → 4.1.0-rc.59

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,10 +1,10 @@
1
1
  "use strict";var I6t=Object.create;var yj=Object.defineProperty;var P6t=Object.getOwnPropertyDescriptor;var C6t=Object.getOwnPropertyNames;var O6t=Object.getPrototypeOf,k6t=Object.prototype.hasOwnProperty;var k=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var g=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Oi=(e,t)=>{for(var r in t)yj(e,r,{get:t[r],enumerable:!0})},Z9e=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of C6t(t))!k6t.call(e,i)&&i!==r&&yj(e,i,{get:()=>t[i],enumerable:!(n=P6t(t,i))||n.enumerable});return e};var _e=(e,t,r)=>(r=e!=null?I6t(O6t(e)):{},Z9e(t||!e||!e.__esModule?yj(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>Z9e(yj({},"__esModule",{value:!0}),e);var A0,_ee=k(()=>{"use strict";A0="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function vee(e){return`${e}-${tSe.randomBytes(24).toString("base64url")}`}function nSe(e=process.env){return e.NODE_ENV==="test"||e[rSe]==="true"}function oy(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&nSe(e)}function BT(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&nSe(e)}function wee(){return`Set ${rSe}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function iSe(){return X9e??=vee("mock-session"),X9e}function oSe(e=process.env){return e.NODE_ENV==="test"?A0:(Q9e??=vee("mock-rc"),Q9e)}function sSe(){return eSe??=vee("mock-signature"),eSe}var tSe,rSe,X9e,Q9e,eSe,gj=k(()=>{"use strict";tSe=_e(require("crypto"));_ee();rSe="VISA_ALLOW_INSECURE_MOCKS"});function N6t(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
2
- `)}function Iee(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=N6t(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}function lf(){return process.platform!=="darwin"?Promise.resolve(!1):(aSe??=(async()=>{try{return await ql("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return Iee(e)}})(),aSe)}async function B6t(){if(!await lf())return null;try{let{stdout:e}=await ql("security",["find-generic-password","-s",hd,"-a",sy,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Iee(e))throw new _j("Unable to read Visa CLI credentials from macOS Keychain. In sandboxed agents such as Codex, rerun with keychain access or run this command outside the sandbox.");return null}}async function j6t(e){if(!await lf())return!1;try{try{await ql("security",["delete-generic-password","-s",hd,"-a",sy],{timeout:5e3})}catch{}return await ql("security",["add-generic-password","-s",hd,"-a",sy,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function U6t(){if(await lf())try{await ql("security",["delete-generic-password","-s",hd,"-a",sy],{timeout:5e3})}catch{}}async function M6t(){if(!Pee())return null;try{let{stdout:e}=await ql("secret-tool",["lookup","service",hd,"account",sy],{timeout:5e3});return e.trim()||null}catch{return null}}async function q6t(e){if(!Pee())return!1;try{let t=(0,vj.execFile)("secret-tool",["store","--label",`${hd} ${sy}`,"service",hd,"account",sy]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((r,n)=>{t.on("exit",i=>i===0?r():n(new Error(`secret-tool exited ${i}`))),t.on("error",n)}),new Promise((r,n)=>setTimeout(()=>{t.kill(),n(new Error("secret-tool timed out"))},R6t))]),!0):!1}catch{return!1}}async function D6t(){if(Pee())try{await ql("secret-tool",["clear","service",hd,"account",sy],{timeout:5e3})}catch{}}function Pee(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function L6t(){if(!await lf())return null;try{let{stdout:e}=await ql("security",["find-generic-password","-s",hd,"-a",bj,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function z6t(e){if(await lf())try{try{await ql("security",["delete-generic-password","-s",hd,"-a",bj],{timeout:5e3})}catch{}await ql("security",["add-generic-password","-s",hd,"-a",bj,"-w",e],{timeout:5e3})}catch{}}async function H6t(){if(await lf())try{await ql("security",["delete-generic-password","-s",hd,"-a",bj],{timeout:5e3})}catch{}}function Aee(){try{return ay.readFileSync(jT,"utf-8").trim()||null}catch(e){if(Iee(e))throw new _j(`Unable to read Visa CLI credentials from ${jT}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function uSe(e){ay.mkdirSync(Tee,{recursive:!0,mode:448}),ay.writeFileSync(jT,e,{mode:384}),process.platform==="win32"&&$6t(jT)}function xee(){try{ay.unlinkSync(jT)}catch{}}function $6t(e){try{let t=wj.userInfo().username;(0,vj.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},r=>{r&&console.error(`[visa-cli] icacls ACL restriction failed: ${r.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function Eee(){switch(process.platform){case"darwin":return{get:B6t,store:j6t,delete:U6t};case"linux":return{get:M6t,store:q6t,delete:D6t};default:return{get:async()=>Aee(),store:async e=>{try{return uSe(e),!0}catch{return!1}},delete:async()=>xee(),storesInSessionFile:!0}}}var vj,cSe,ay,wj,See,ql,Tee,jT,hd,sy,bj,R6t,_j,aSe,pn,x0=k(()=>{"use strict";vj=require("child_process"),cSe=require("util"),ay=_e(require("fs")),wj=_e(require("os")),See=_e(require("path"));gj();ql=(0,cSe.promisify)(vj.execFile),Tee=See.join(wj.homedir(),".visa-mcp"),jT=See.join(Tee,"session-token"),hd="visa-cli",sy="session-token",bj="rc-access",R6t=5e3,_j=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};aSe=null;pn=class{static async getSessionToken(){if(oy())return Promise.resolve(iSe());let t=Eee(),r=await t.get();if(r)return r;let n=Aee();return n?(await t.store(n),n):null}static async saveSessionToken(t){if(oy())return;let r=Eee();if(await r.store(t)){if(await r.get()===t){r.storesInSessionFile||xee();return}await r.delete()}if(uSe(t),Aee()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Tee} is writable.`))}static async getRcAccessToken(){return oy()?oSe():L6t()}static async saveRcAccessToken(t){oy()||await z6t(t)}static async deleteSessionToken(){if(oy())return;await Eee().delete(),xee()}static async clearAll(){await this.deleteSessionToken(),await H6t()}}});var Ej=g((Ejr,F6t)=>{F6t.exports={name:"@visa/cli",version:"4.1.0-rc.58",description:"Visa CLI runtime for stable agent identity and separately authorized payment capabilities",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/agent-mail build && pnpm --filter @visa/wallet-tools build && pnpm --filter @visa/checkout-engine 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: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","@ucp-js/sdk":"0.4.1",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","playwright-core":"^1.48.2"},devDependencies:{"@visa/agent-mail":"workspace:*","@visa/checkout-engine":"workspace:*","@visa/crypto":"workspace:*","@visa/identity":"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.65.0","@typescript-eslint/parser":"^8.65.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 UT(e=process.env,t=process.platform){return e.VISA_CLI_NO_BROWSER==="1"||e.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.SSH_CONNECTION||e.SSH_TTY?{headless:!0,reason:"SSH session detected"}:t==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function rvt(e){let r=e.length+4;return[`\u250C${"\u2500".repeat(r)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(r)}\u2518`].join(`
2
+ `)}function Iee(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=N6t(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}function lf(){return process.platform!=="darwin"?Promise.resolve(!1):(aSe??=(async()=>{try{return await ql("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return Iee(e)}})(),aSe)}async function B6t(){if(!await lf())return null;try{let{stdout:e}=await ql("security",["find-generic-password","-s",hd,"-a",sy,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Iee(e))throw new _j("Unable to read Visa CLI credentials from macOS Keychain. In sandboxed agents such as Codex, rerun with keychain access or run this command outside the sandbox.");return null}}async function j6t(e){if(!await lf())return!1;try{try{await ql("security",["delete-generic-password","-s",hd,"-a",sy],{timeout:5e3})}catch{}return await ql("security",["add-generic-password","-s",hd,"-a",sy,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function U6t(){if(await lf())try{await ql("security",["delete-generic-password","-s",hd,"-a",sy],{timeout:5e3})}catch{}}async function M6t(){if(!Pee())return null;try{let{stdout:e}=await ql("secret-tool",["lookup","service",hd,"account",sy],{timeout:5e3});return e.trim()||null}catch{return null}}async function q6t(e){if(!Pee())return!1;try{let t=(0,vj.execFile)("secret-tool",["store","--label",`${hd} ${sy}`,"service",hd,"account",sy]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((r,n)=>{t.on("exit",i=>i===0?r():n(new Error(`secret-tool exited ${i}`))),t.on("error",n)}),new Promise((r,n)=>setTimeout(()=>{t.kill(),n(new Error("secret-tool timed out"))},R6t))]),!0):!1}catch{return!1}}async function D6t(){if(Pee())try{await ql("secret-tool",["clear","service",hd,"account",sy],{timeout:5e3})}catch{}}function Pee(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function L6t(){if(!await lf())return null;try{let{stdout:e}=await ql("security",["find-generic-password","-s",hd,"-a",bj,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function z6t(e){if(await lf())try{try{await ql("security",["delete-generic-password","-s",hd,"-a",bj],{timeout:5e3})}catch{}await ql("security",["add-generic-password","-s",hd,"-a",bj,"-w",e],{timeout:5e3})}catch{}}async function H6t(){if(await lf())try{await ql("security",["delete-generic-password","-s",hd,"-a",bj],{timeout:5e3})}catch{}}function Aee(){try{return ay.readFileSync(jT,"utf-8").trim()||null}catch(e){if(Iee(e))throw new _j(`Unable to read Visa CLI credentials from ${jT}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function uSe(e){ay.mkdirSync(Tee,{recursive:!0,mode:448}),ay.writeFileSync(jT,e,{mode:384}),process.platform==="win32"&&$6t(jT)}function xee(){try{ay.unlinkSync(jT)}catch{}}function $6t(e){try{let t=wj.userInfo().username;(0,vj.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},r=>{r&&console.error(`[visa-cli] icacls ACL restriction failed: ${r.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function Eee(){switch(process.platform){case"darwin":return{get:B6t,store:j6t,delete:U6t};case"linux":return{get:M6t,store:q6t,delete:D6t};default:return{get:async()=>Aee(),store:async e=>{try{return uSe(e),!0}catch{return!1}},delete:async()=>xee(),storesInSessionFile:!0}}}var vj,cSe,ay,wj,See,ql,Tee,jT,hd,sy,bj,R6t,_j,aSe,pn,x0=k(()=>{"use strict";vj=require("child_process"),cSe=require("util"),ay=_e(require("fs")),wj=_e(require("os")),See=_e(require("path"));gj();ql=(0,cSe.promisify)(vj.execFile),Tee=See.join(wj.homedir(),".visa-mcp"),jT=See.join(Tee,"session-token"),hd="visa-cli",sy="session-token",bj="rc-access",R6t=5e3,_j=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};aSe=null;pn=class{static async getSessionToken(){if(oy())return Promise.resolve(iSe());let t=Eee(),r=await t.get();if(r)return r;let n=Aee();return n?(await t.store(n),n):null}static async saveSessionToken(t){if(oy())return;let r=Eee();if(await r.store(t)){if(await r.get()===t){r.storesInSessionFile||xee();return}await r.delete()}if(uSe(t),Aee()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Tee} is writable.`))}static async getRcAccessToken(){return oy()?oSe():L6t()}static async saveRcAccessToken(t){oy()||await z6t(t)}static async deleteSessionToken(){if(oy())return;await Eee().delete(),xee()}static async clearAll(){await this.deleteSessionToken(),await H6t()}}});var Ej=g((Ejr,F6t)=>{F6t.exports={name:"@visa/cli",version:"4.1.0-rc.59",description:"Visa CLI runtime for stable agent identity and separately authorized payment capabilities",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/shared build && pnpm --filter @visa/observability build && 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/agent-mail build && pnpm --filter @visa/wallet-tools build && pnpm --filter @visa/checkout-engine 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: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","@ucp-js/sdk":"0.4.1",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","playwright-core":"^1.48.2"},devDependencies:{"@visa/agent-mail":"workspace:*","@visa/checkout-engine":"workspace:*","@visa/crypto":"workspace:*","@visa/identity":"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.65.0","@typescript-eslint/parser":"^8.65.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 UT(e=process.env,t=process.platform){return e.VISA_CLI_NO_BROWSER==="1"||e.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.SSH_CONNECTION||e.SSH_TTY?{headless:!0,reason:"SSH session detected"}:t==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function rvt(e){let r=e.length+4;return[`\u250C${"\u2500".repeat(r)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(r)}\u2518`].join(`
3
3
  `)}function MT(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="https:"&&t.protocol!=="http:"?null:t.toString()}function gSe(e,t){let r=MT(e);if(!r)return null;let n,i;try{n=new URL(r),i=new URL(t)}catch{return null}return n.origin===i.origin?r:null}function bSe(e,t){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}function _Se(e,t=process.platform){let r=MT(e);return r?bSe(r,t):null}function hSe(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function N_(e,t={}){let r=t.log??(u=>console.log(u)),n=t.env??process.env,i=t.platform??process.platform,o=MT(e),s=t.spawn??((u,d,l)=>{(0,ySe.execFile)(u,d,p=>l(p))});r(""),r(" Sign in to Visa CLI by opening this URL in your browser:"),r("");for(let u of rvt(o??e).split(`
4
4
  `))r(` ${u}`);if(r(""),!o){r(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),r(" Open the URL above manually to continue."),r("");return}let a=UT(n,i);if(a.headless){r(` (${a.reason} \u2014 skipping browser auto-open.)`),r(" Open the URL above on any device with a browser. The CLI will"),r(" continue waiting for you to complete sign-in."),r("");return}let c=bSe(o,i);if(!c){r(` No known browser-open command for platform "${i}".`),r(" Open the URL above manually to continue."),r("");return}await new Promise(u=>{let d=l=>{l?hSe(r,l):(r(" Opened browser. Waiting for you to sign in..."),r("")),u()};try{s(c.cmd,c.args,d)}catch(l){hSe(r,l instanceof Error?l:new Error(String(l))),u()}})}var ySe,Tj=k(()=>{"use strict";ySe=require("child_process")});async function iTe(e,t){let r=t?.timeoutMs??3e4,n=new AbortController,i=setTimeout(()=>n.abort(),r);try{let{timeoutMs:o,...s}=t??{};return await fetch(e,{...s,signal:n.signal})}finally{clearTimeout(i)}}var oTe=k(()=>{"use strict"});var Lj,sTe=k(()=>{"use strict";Lj=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}}});function cTe(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 r=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return r&&aTe[r]?aTe[r]:`Network error contacting the Visa CLI server (${r?`${r}: ${typeof t.message=="string"?t.message:"unknown"}`:typeof t.message=="string"&&t.message.length>0?t.message:"unknown error"}). Check https://visacli.sh for status.`}var aTe,uTe=k(()=>{"use strict";aTe={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 lTe(e,t){let r=dTe(e),n=dTe(t);if(!r||!n)return!1;for(let i=0;i<3;i++)if(r.main[i]!==n.main[i])return r.main[i]>n.main[i];return r.pre&&!n.pre?!1:!r.pre&&n.pre?!0:!r.pre&&!n.pre?!1:Hvt(r.pre,n.pre)>0}function dTe(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(zvt);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function Hvt(e,t){let r=e.split("."),n=t.split("."),i=Math.max(r.length,n.length);for(let o=0;o<i;o++){if(o>=r.length)return-1;if(o>=n.length)return 1;let s=r[o],a=n[o],c=/^\d+$/.test(s),u=/^\d+$/.test(a);if(c&&u){let d=Number(s)-Number(a);if(d!==0)return d}else{if(c)return-1;if(u)return 1;if(s<a)return-1;if(s>a)return 1}}return 0}var zvt,pTe=k(()=>{"use strict";zvt=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/});function uy(){return!!(fTe(process.env.VISA_CLI_NO_UPDATE_CHECK)||fTe(process.env.CI)||process.env.NODE_ENV==="test")}function fTe(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var FT=k(()=>{"use strict"});var zj,mTe,hTe,Fee,VT,yTe=k(()=>{"use strict";zj=_e(require("fs")),mTe=_e(require("path")),hTe=_e(require("os")),Fee=mTe.join(hTe.homedir(),".visa-mcp"),VT=class{static ensureConfigDir(){zj.existsSync(Fee)||zj.mkdirSync(Fee,{recursive:!0,mode:448})}static getConfigDir(){return Fee}}});function Fvt(){cc.existsSync(Kee)||cc.mkdirSync(Kee,{recursive:!0,mode:448})}function Vvt(){if(!Vee){if(Fvt(),cc.existsSync(KT)&&cc.statSync(KT).size>$vt){let t=KT+".1";cc.existsSync(t)&&cc.unlinkSync(t),cc.renameSync(KT,t)}Vee=cc.createWriteStream(KT,{flags:"a"})}return Vee}function Kvt(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"}function Hj(e,...t){let r=new Date().toISOString(),n=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),i=`[${r}] [${e}] ${n}
5
5
  `;Kvt(e)&&process.stderr.write(i),Vvt().write(i)}var cc,Gee,gTe,Kee,KT,$vt,Vee,ke,yd=k(()=>{"use strict";cc=_e(require("fs")),Gee=_e(require("path")),gTe=_e(require("os")),Kee=Gee.join(gTe.homedir(),".visa-mcp"),KT=Gee.join(Kee,"mcp-server.log"),$vt=5*1024*1024,Vee=null;ke={debug:(...e)=>Hj("DEBUG",...e),info:(...e)=>Hj("INFO",...e),warn:(...e)=>Hj("WARN",...e),error:(...e)=>Hj("ERROR",...e)}});function bTe(e){let t=_Te.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function $j(){return vTe.join(VT.getConfigDir(),Gvt)}function wTe(e){if((0,Jee.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Jvt(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let r=Number.parseInt(t[1],16),n=Number.parseInt(t[2],16);if(!Number.isFinite(r)||!Number.isFinite(n))return!1;let i=[r>>8&255,r&255,n>>8&255,n&255].join(".");return wTe(i)}function Yvt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,Jee.isIP)(t);return r===4?wTe(t):r===6?t==="::1"||Jvt(t):!1}function Wee(e,t="auth.serverUrl"){let r;try{r=new URL(e)}catch{throw new Error(`${t} must be a valid URL (got: ${JSON.stringify(e)})`)}if(r.username||r.password)throw new Error(`${t} must not include username or password credentials`);if(r.protocol!=="https:"&&!(r.protocol==="http:"&&Yvt(r.hostname)))throw new Error(`${t} ${Wvt}`)}function Fj(){let e=$j();if(!dy.existsSync(e))return{};try{let t=dy.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(ke.warn("settings:corrupt",{path:bTe(e),reason:"not_object"}),{}):r}catch(t){return ke.warn("settings:corrupt",{path:bTe(e),error:t?.message||String(t)}),{}}}function ETe(e){VT.ensureConfigDir();let t=$j(),r=`${t}.tmp`,n=JSON.stringify(e,null,2)+`
6
6
  `;dy.writeFileSync(r,n,{mode:384}),dy.renameSync(r,t)}function Yee(e){let t=Fj()[e];return typeof t=="string"?t:void 0}function Zee(e){let t=Fj()[e];return typeof t=="boolean"?t:void 0}function Vj(e,t){let r=L_[e];if(!r)throw new Dl(e);let n;if(r.type==="boolean")if(typeof t=="boolean")n=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")n=!0;else if(o==="false")n=!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(r.type==="number")if(typeof t=="number")n=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)})`);n=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`);n=t}r.validate&&r.validate(n);let i=Fj();return i[e]=n,ETe(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:$j()}}function Kj(e){let t=L_[e];if(!t)throw new Dl(e);let r=Fj(),n=e in r;return n&&(delete r[e],ETe(r)),{key:e,removed:n,requiresRestart:n&&!!t.requiresRestart,path:$j()}}function Qvt(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function e5t(){try{let e=Ej();return Qvt(e.version)}catch{return!1}}function t5t(e){return e.envVar!==void 0&&e.envVar!==""?(Wee(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Wee(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Xvt:Zvt}function Ta(){return t5t({envVar:process.env.VISA_AUTH_URL,settingValue:Yee("auth.serverUrl"),isPrerelease:e5t()})}function ATe(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Zee("ui.suppressBrowser")??!1}var dy,Jee,_Te,vTe,Gvt,Wvt,L_,Dl,Zvt,Xvt,ly=k(()=>{"use strict";dy=_e(require("fs")),Jee=require("node:net"),_Te=_e(require("os")),vTe=_e(require("path"));yTe();yd();Gvt="settings.json",Wvt="must use https unless it points at localhost/loopback for local development";L_={"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");Wee(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."}};Dl=class extends Error{constructor(t){let r=Object.keys(L_).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}.`),this.name="UnknownSettingKeyError"}};Zvt="https://auth.visacli.sh",Xvt="https://auth-visa-code-preview.up.railway.app"});function n5t(e,t){let r=typeof t?.error=="string"&&t.error||typeof t?.message=="string"&&t.message||"";return r?new Error(r):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 Q4(e){return typeof e=="string"?e.trim():""}function o5t(e){let t=e&&typeof e=="object"?e:{},r=Q4(t.error)||Q4(t.message);if(!r)return i5t;let n=Q4(t.error_code),i=[["surface",Q4(t.disabled_surface)],["flag",Q4(t.flag)],["correlation_id",Q4(t.correlation_id)]].filter(([,s])=>s).map(([s,a])=>`${s}=${a}`),o=i.length?` (${i.join(" ")})`:"";return n?`503 [${n}] ${r}${o}`:`503 ${r}${o}`}function s5t(e=process.env,t=process.stdin.isTTY){let r=["Not logged in. No local Visa CLI session credentials were found."],n=e.VISA_CLI_API_KEY?.trim();return n?r5t.test(n)?(r.push("VISA_CLI_API_KEY is set, but this operation requires an enrolled device session."),r.push("Use the Visa Key with X-Api-Key on the /v2/harness/* surface.")):(r.push("VISA_CLI_API_KEY is set but has invalid format (expected vk_live_<...> or vk_test_<...>)."),r.push("Create a new Visa Key with: visa-cli keys create <app-name>")):r.push("Ask your agent to call `enroll_agent` to connect this device."),t===!1&&r.push("Complete enrollment in a normal terminal, then restart the MCP client."),r.join(`
7
- `)}var Gj,r5t,i5t,bu,e8=k(()=>{"use strict";oTe();sTe();uTe();pTe();FT();ly();Gj="4.1.0-rc.58",r5t=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;i5t="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";bu=class{constructor(t){this.getSessionToken=t;this.baseUrl=Ta()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!uy()){let n=t.headers.get("X-Latest-Version");n&&lTe(n,Gj)&&(this.lastSignals.updateAvailable={currentVersion:Gj,latestVersion:n})}let r=t.headers.get("X-Feedback-Prompt");if(r)try{this.lastSignals.feedbackPrompt=JSON.parse(r)}catch{}}getClientVersion(){return Gj}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Lj(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t){let r=null;try{r=await t.json()}catch{}throw new Error(o5t(r))}async request(t,r,n,i,o){let s=await this.getSessionToken();if(!s)throw new Error(s5t());let a={Authorization:`Bearer ${s}`};o&&(t==="GET"?a["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):n={...n||{},user_context:o}),n&&(a["Content-Type"]="application/json");let c;try{c=await iTe(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":Gj,"X-Source":"cli"},body:n?JSON.stringify(n):void 0,timeoutMs:i})}catch(d){throw new Error(cTe(d))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your device session has expired. Ask your agent to call `enroll_agent` to reconnect.");if(c.status===429){let d=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s, then retry.`)}c.status===503&&await this.throwServerUnavailable(c);let u;try{u=await c.json()}catch{throw c.status===500?new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${r}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`):(this.throwIfAttestationDrift(u),n5t(c.status,u));return u}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async merchantDirectorySearch(t,r){let n=new URLSearchParams;return t.provider&&n.set("provider",t.provider),t.q&&n.set("q",t.q),t.protocol&&n.set("protocol",t.protocol),t.maxPriceUsd&&n.set("max_price_usd",t.maxPriceUsd),n.set("limit",String(t.limit)),n.set("offset",String(t.offset)),this.request("GET",`/v1/merchant-directory/search?${n.toString()}`,void 0,void 0,r)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getAgentTapStatus(t){try{return await this.request("GET",`/v4/agent-bindings/${encodeURIComponent(t)}/tap-status`)}catch{return null}}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,r){return this.request("POST","/v1/attestation-key",{publicKey:t,...r?{attestation:r}:{}})}async startAttestationRecovery(t,r){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,r)}async setBiometricPreference(t,r){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,r)}async getPendingWebAuthenticators(t){return this.request("GET","/v1/webauthn/pending",void 0,void 0,t)}async authorizeWebAuthenticator(t,r){return this.request("POST","/v1/webauthn/authorize",t,void 0,r)}async logout(t,r){return this.request("POST","/v4/logout",t,void 0,r)}async feedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(t){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.startingAfter!=null&&r.set("starting_after",String(t.startingAfter)),t?.endingBefore!=null&&r.set("ending_before",String(t.endingBefore));let n=r.toString();return this.request("GET",n?`/v1/api/keys?${n}`:"/v1/api/keys")}async listAllAppApiKeys(){let t=[],r=new Set,n,i=null,o=0;for(;;){let s=await this.listAppApiKeys({limit:100,...n!==void 0?{startingAfter:n}:{}});if(o+=1,i=s,t.push(...s.keys??[]),!s.has_more)break;if(s.next_cursor==null)throw new Error("API key pagination response did not include next_cursor.");if(r.has(s.next_cursor))throw new Error("API key pagination cursor did not advance.");r.add(s.next_cursor),n=s.next_cursor}return{...i??{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 submitFeedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async getFeedback(t,r){let n=new URLSearchParams;t&&n.set("limit",String(t));let i=n.toString();return this.request("GET",`/v1/feedback${i?"?"+i:""}`,void 0,void 0,r)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}async createCapabilityAttach(t,r){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/capability-attach`,{protocolVersion:2,capability:r.capability,aggregateCeilingCents:r.aggregateCeilingCents,perPurchaseCents:r.perPurchaseCents})}async issueAgentEmailChannel(t,r){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/channels/email`,{},void 0,r)}async beginAgentMailRuntimeCredential(t,r){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/channels/email/runtime-credential`,{},void 0,r)}async claimAgentMailRuntimeCredential(t,r,n){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/channels/email/runtime-credentials/${encodeURIComponent(r)}/claim`,n)}}});function Xee(e=xTe){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function STe(e=xTe){return/-(?:rc|alpha|beta)\./i.test(e)}function Qee(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function py(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return t?Qee(t):STe()?c5t:a5t}function TTe(e){return`${Qee(e)}${u5t}`}function d5t(e=process.env){return!!e.VISA_VERIFY_WEB_URL?.trim()||STe()}function ete(e,t=process.env){if(!e||!d5t(t))return e;try{let r=new URL(py(t)),n=new URL(e);return n.protocol=r.protocol,n.host=r.host,n.toString()}catch{return e}}async function ITe(e,t=fetch){let r=`${Qee(e)}/api/agent-enroll/health`,n;try{n=await t(r,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Could not verify the v4 sign-in service. Try again shortly.")}if(!n.ok)throw new Error(`V4 sign-in readiness check failed (${n.status}).`);if((await n.json().catch(()=>null))?.clients?.auth!=="turnkey")throw new Error("V4 sign-in is not enabled on this deployment; refusing to open the retired GitHub flow.")}var xTe,a5t,c5t,u5t,Wj=k(()=>{"use strict";xTe="4.1.0-rc.58",a5t="https://app.visacli.sh",c5t="https://web-visa-code-preview.up.railway.app",u5t="/agent/enroll"});function L5t(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function SIe(e,t,r=""){let n=L5t(e),i=e?.length,o=t!==void 0;if(!n||o&&i!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=n?`length=${i}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return e}function QTe(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 z5t(e,t){SIe(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function mte(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ste(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function H5t(e,t={}){let r=(i,o)=>e(o).update(i).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>e(i),Object.assign(r,t),Object.freeze(r)}function V5t(e,t=!1){return t?{h:Number(e&eU),l:Number(e>>eIe&eU)}:{h:Number(e>>eIe&eU)|0,l:Number(e&eU)|0}}function K5t(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=V5t(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function O0(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function iwt(){return U5t.randomSecretKey()}function K_(e){return k5t(e)}function IIe(){let e=iwt();return{secretKey:e,publicKey:K_(e)}}function PIe(e){if(e.length!==iIe)throw new Error(`Ed25519 seed must be ${iIe} bytes, got ${e.length}`);return{secretKey:e,publicKey:K_(e)}}function gy(e,t){return B5t(t,e)}function owt(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function swt(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function uU(e){return owt(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function OIe(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return swt(r)}function awt(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function G_(e){let t=K_(e);return{kty:"OKP",crv:"Ed25519",x:uU(t),d:uU(e)}}function by(e){return{kty:"OKP",crv:"Ed25519",x:uU(e)}}function a8(e){if(awt(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return OIe(e.d)}function sIe(e,t){return e<t?-1:e>t?1:0}function cte(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Er(e){if(typeof e!="string"||!dwt.test(e))return!1;try{let t=OIe(e);return t.byteLength===32&&uU(t)===e}catch{return!1}}function ute(e,t,r){let n=Object.keys(t).filter(i=>!r.has(i));if(n.length>0)throw new Error(`${e} contains unknown field(s): ${n.sort().join(", ")}`)}function gwt(e,t){if(typeof t!="string"||!uwt.test(t))throw new Error(`${e} must be a UUID`)}function WT(e,t){return gwt(e,t),t.toLowerCase()}function aIe(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let r=pwt.exec(t);if(!r)throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let[,n,i,o,s,a,c]=r,u=Number(n),d=Number(i),l=Number(o),p=Number(s),f=Number(a),m=Number(c),h=new Date(0);if(h.setUTCFullYear(u,d-1,l),h.setUTCHours(p,f,m,0),u===0||h.getUTCFullYear()!==u||h.getUTCMonth()!==d-1||h.getUTCDate()!==l||h.getUTCHours()!==p||h.getUTCMinutes()!==f||h.getUTCSeconds()!==m)throw new Error(`${e} must be a valid calendar timestamp`);let y=Date.parse(t);if(!Number.isFinite(y))throw new Error(`${e} must be a valid ISO timestamp`);return new Date(y).toISOString()}function nU(e,t,r=!1){if(typeof t!="string"||!lwt.test(t))throw new Error(`${e} must be a canonical non-negative integer micros string`);if(!r&&t==="0")throw new Error(`${e} must be positive`);if(BigInt(t)>mwt)throw new Error(`${e} exceeds the PostgreSQL BIGINT range`);return t}function bwt(e,t){if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>fwt)throw new Error(`${e} must be a positive PostgreSQL INTEGER`);return t}function cIe(e,t){if(typeof t!="string")throw new Error(`${e} must be a string`);if(kIe.test(t))throw new Error(`${e} must be a bounded non-empty payee without control characters`);let r=t.normalize("NFC").trim();if(r.length===0||r.length>hwt)throw new Error(`${e} must be a bounded non-empty payee without control characters`);return r}function _wt(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(kIe.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function dte(e,t){return typeof e=="string"&&t.includes(e)}function vwt(e){if(!cte(e))throw new Error("agent authority grant must be an object");if(ute("agent authority grant",e,new Set(["v","grantId","agentId","version","budgetEpochId","budgetEpochMode","status","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt","supersedesGrantId"])),e.v!==i8)throw new Error("grant.v must be 2");let t=WT("grantId",e.grantId),r=WT("agentId",e.agentId),n=bwt("version",e.version),i=WT("budgetEpochId",e.budgetEpochId);if(!dte(e.budgetEpochMode,cwt))throw new Error("budgetEpochMode must be new or continue");if(!dte(e.status,["active","superseded","revoked"]))throw new Error("invalid grant status");if(e.currency!=="USD")throw new Error("currency must be 'USD'");if(e.valuationPolicy!==ate)throw new Error(`valuationPolicy must be '${ate}'`);let o=nU("totalMicros",e.totalMicros),s=nU("perTransactionMicros",e.perTransactionMicros);if(BigInt(s)>BigInt(o))throw new Error("perTransactionMicros cannot exceed totalMicros");if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("scopes must be a non-empty array");let a=e.scopes.map(l=>{if(!cte(l))throw new Error("grant scope must be an object");if(ute("grant scope",l,new Set(["scope","totalMicros","perTransactionMicros","instrumentRef"])),!dte(l.scope,yy))throw new Error("invalid authorization scope");let p=l.totalMicros===void 0?void 0:nU("scope.totalMicros",l.totalMicros),f=l.perTransactionMicros===void 0?void 0:nU("scope.perTransactionMicros",l.perTransactionMicros);if(p!==void 0&&BigInt(p)>BigInt(o))throw new Error("scope.totalMicros cannot exceed the aggregate totalMicros");if(f!==void 0&&BigInt(f)>BigInt(s))throw new Error("scope.perTransactionMicros cannot exceed the aggregate perTransactionMicros");if(p!==void 0&&f!==void 0&&BigInt(f)>BigInt(p))throw new Error("scope.perTransactionMicros cannot exceed scope.totalMicros");let m=_wt("scope.instrumentRef",l.instrumentRef,255);return{scope:l.scope,...p!==void 0?{totalMicros:p}:{},...f!==void 0?{perTransactionMicros:f}:{},instrumentRef:m}});if(new Set(a.map(({scope:l})=>l)).size!==a.length)throw new Error("scopes must not repeat");let c;if(e.payeeConstraints!==void 0){if(!Array.isArray(e.payeeConstraints)||e.payeeConstraints.length===0||e.payeeConstraints.length>oIe)throw new Error(`payeeConstraints must contain between 1 and ${oIe} entries`);if(c=e.payeeConstraints.map(p=>{if(!cte(p))throw new Error("payee constraint must be an object");if(ute("payee constraint",p,new Set(["scope","kind","canonicalId"])),p.scope==="card:vic"&&p.kind==="processor_merchant_id")return{scope:p.scope,kind:p.kind,canonicalId:cIe("payee constraint canonicalId",p.canonicalId)};if(p.scope==="wallet:x402"&&p.kind==="evm_address"){let f=cIe("payee constraint canonicalId",p.canonicalId).toLowerCase();if(!ywt.test(f))throw new Error("wallet payee constraint canonicalId must be an EVM address");return{scope:p.scope,kind:p.kind,canonicalId:f}}throw new Error("payee constraint scope/kind combination is invalid")}),c.some(p=>!a.some(({scope:f})=>f===p.scope)))throw new Error("payee constraint scope must be present in grant scopes");let l=c.map(({scope:p,kind:f,canonicalId:m})=>`${p}:${f}:${m}`);if(new Set(l).size!==l.length)throw new Error("payeeConstraints must not repeat after normalization")}let u=aIe("effectiveAt",e.effectiveAt),d=aIe("expiresAt",e.expiresAt);if(Date.parse(d)<=Date.parse(u))throw new Error("expiresAt must be after effectiveAt");if(e.supersedesGrantId!==void 0&&WT("supersedesGrantId",e.supersedesGrantId)===t)throw new Error("a grant cannot supersede itself");return{v:i8,grantId:t,agentId:r,version:n,budgetEpochId:i,budgetEpochMode:e.budgetEpochMode,status:e.status,currency:"USD",valuationPolicy:ate,totalMicros:o,perTransactionMicros:s,scopes:[...a].sort((l,p)=>sIe(l.scope,p.scope)),...c!==void 0?{payeeConstraints:[...c].sort((l,p)=>sIe(`${l.scope}:${l.kind}:${l.canonicalId}`,`${p.scope}:${p.kind}:${p.canonicalId}`))}:{},effectiveAt:u,expiresAt:d,...e.supersedesGrantId!==void 0?{supersedesGrantId:WT("supersedesGrantId",e.supersedesGrantId)}:{}}}function jIe(e,t){return e<t?-1:e>t?1:0}function _u(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gd(e,t,r){let n=new Set(r),i=Object.keys(t).filter(o=>!n.has(o));if(i.length>0)throw new Error(`${e} contains unknown field(s): ${i.sort().join(", ")}`)}function Cwt(e){if(typeof e!="string")throw new Error("displayName must be a string");if(pU.test(e))throw new Error("displayName must be bounded, non-empty text without control characters");let t=e.normalize("NFC").trim().replace(/ {2,}/g," ");if(t.length===0||t.length>Awt)throw new Error("displayName must be bounded, non-empty text without control characters");return t}function Owt(e){if(typeof e!="string")throw new Error("dotVisaAddress must be a string");if(pU.test(e))throw new Error("dotVisaAddress must be a valid .visa address");let t=e.trim().toLowerCase();if(!Ewt.test(t))throw new Error("dotVisaAddress must be a valid .visa address");return t}function iU(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(pU.test(t)||BIe.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function kwt(e){if(!_u(e))throw new Error("runtime context v2 must be an object");gd("runtime context v2",e,["runtime","contextLabel","cliVersion","platform"]);let t=iU("runtime",e.runtime,Swt),r=iU("contextLabel",e.contextLabel,Twt),n=e.cliVersion===void 0?void 0:iU("cliVersion",e.cliVersion,Iwt),i=e.platform===void 0?void 0:iU("platform",e.platform,Pwt);return{runtime:t,contextLabel:r,...n!==void 0?{cliVersion:n}:{},...i!==void 0?{platform:i}:{}}}function Ate(e){if(typeof e!="string"||!NIe.test(e))throw new Error("pairingId must be a server-generated pairing id")}function ZT(e){if(e!==jt)throw new Error("protocolVersion must be 2")}function Ll(e,t){if(typeof t!="string"||!xwt.test(t))throw new Error(`${e} must be a canonical lowercase UUID`)}function Gi(e,t){if(!Er(t))throw new Error(`${e} must be 32 canonical unpadded base64url bytes`)}function UIe(e){if(typeof e!="string"||!Rwt.test(e))throw new Error("attachId must be a server-generated capability-attach id")}function Nwt(e){if(typeof e!="string"||!dU.includes(e))throw new Error(`capability must be one of ${dU.join(", ")}`)}function Bwt(e){if(typeof e!="string"||!yy.includes(e))throw new Error(`rail must be one of ${yy.join(", ")}`)}function lIe(e,t){if(typeof t!="string"||t.length===0||t.length>dIe||pU.test(t)||BIe.test(t))throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let r;try{r=new URL(t)}catch{throw new Error(`${e} must be a bounded absolute HTTP(S) URL`)}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.hostname.length===0||r.username.length>0||r.password.length>0||r.hash.length>0)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let n=r.toString();if(n.length>dIe)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);return n}function MIe(){return YT.default.randomBytes(32).toString("base64url")}function qIe(e){if(!Er(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return QT(e)}function jwt(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function Uwt(e){let t=jwt(e);return`${t.slice(0,4)}-${t.slice(4)}`}function fU(){return YT.default.randomBytes(32).toString("base64url")}function k0(e){if(!Er(e))throw new Error("claim token must be 32 unpadded base64url bytes");return QT(`visa-agent-pairing-claim-token:v1:${e}`)}function mU(e,t){k0(t);let r=YT.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<wwt;i+=1)n+=Ete[r[i]&RIe];return Uwt(n)}function DIe(e){if(!_u(e))throw new Error("pairing terms v2 must be an object");if(gd("pairing terms v2",e,["v","pairingId","agentId","agentSelection","identityKeyJkt","ownerPublicId","displayName","dotVisaAddress","authority"]),e.v!==i8)throw new Error("pairing terms v2 must carry v=2");if(typeof e.pairingId!="string"||!NIe.test(e.pairingId))throw new Error("pairingId must be a server-issued pairing id");if(typeof e.agentId!="string"||!uIe.test(e.agentId))throw new Error("agentId must be a UUID");if(e.agentSelection!=="new"&&e.agentSelection!=="existing")throw new Error("agentSelection must be new or existing");if(!Er(e.identityKeyJkt))throw new Error("identityKeyJkt must be a canonical 32-byte base64url thumbprint");if(typeof e.ownerPublicId!="string"||!uIe.test(e.ownerPublicId))throw new Error("ownerPublicId must be a UUID");let t=e.agentId.toLowerCase(),r=e.ownerPublicId.toLowerCase(),n=Cwt(e.displayName),i=e.dotVisaAddress===void 0?void 0:Owt(e.dotVisaAddress);if(e.authority===null){if(e.agentSelection==="existing")throw new Error("an existing-agent pairing must bind its exact current authority; identity-only attachment requires a future explicit no-spend key policy");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:null,displayName:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:i8})}if(!_u(e.authority))throw new Error("pairing authority must be an object or null");if(gd("pairing authority",e.authority,["grantId","grantVersion","supersedesGrantId","budgetEpochId","budgetEpochMode","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt"]),!Array.isArray(e.authority.scopes)||e.authority.scopes.length===0||e.authority.scopes.length>yy.length)throw new Error(`pairing authority scopes must contain between 1 and ${yy.length} entries`);let o=new Map,s=e.authority.scopes.map(c=>{if(!_u(c))throw new Error("pairing authority scope must be an object");if(Object.prototype.hasOwnProperty.call(c,"instrumentRef"))throw new Error("pairing authority scopes may not supply instrumentRef; auth resolves it");if(gd("pairing authority scope",c,["scope","totalMicros","perTransactionMicros","instrumentCommitment"]),!yy.includes(c.scope))throw new Error("invalid authorization scope");let u=c.scope;if(!Er(c.instrumentCommitment))throw new Error("every approved scope requires a 32-byte instrumentCommitment");return o.set(u,c.instrumentCommitment),{scope:u,instrumentRef:c.instrumentCommitment,...c.totalMicros!==void 0?{totalMicros:c.totalMicros}:{},...c.perTransactionMicros!==void 0?{perTransactionMicros:c.perTransactionMicros}:{}}}),a=vwt({v:i8,grantId:e.authority.grantId,agentId:t,version:e.authority.grantVersion,budgetEpochId:e.authority.budgetEpochId,budgetEpochMode:e.authority.budgetEpochMode,status:"active",currency:e.authority.currency,valuationPolicy:e.authority.valuationPolicy,totalMicros:e.authority.totalMicros,perTransactionMicros:e.authority.perTransactionMicros,scopes:s,...e.authority.payeeConstraints!==void 0?{payeeConstraints:e.authority.payeeConstraints}:{},effectiveAt:e.authority.effectiveAt,expiresAt:e.authority.expiresAt,...e.authority.supersedesGrantId!==void 0?{supersedesGrantId:e.authority.supersedesGrantId}:{}});if(e.agentSelection==="new"&&(a.version>1||a.supersedesGrantId!==void 0))throw new Error("a new-agent pairing cannot replace or supersede an existing grant; replacement authority belongs to an existing agent");if(a.version===1&&(a.budgetEpochMode!=="new"||a.supersedesGrantId!==void 0))throw new Error("an initial pairing grant must start a new budget epoch and supersede nothing");if(a.version>1&&a.supersedesGrantId===void 0)throw new Error("a replacement pairing grant must name its direct predecessor");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:{...a.payeeConstraints!==void 0?{payeeConstraints:a.payeeConstraints}:{},currency:a.currency,effectiveAt:a.effectiveAt,expiresAt:a.expiresAt,grantId:a.grantId,grantVersion:a.version,budgetEpochId:a.budgetEpochId,budgetEpochMode:a.budgetEpochMode,...a.supersedesGrantId!==void 0?{supersedesGrantId:a.supersedesGrantId}:{},perTransactionMicros:a.perTransactionMicros,scopes:a.scopes.map(({scope:c,totalMicros:u,perTransactionMicros:d})=>{let l=o.get(c);if(l===void 0)throw new Error("canonical scope lost its approved instrument commitment");return{instrumentCommitment:l,...d!==void 0?{perTransactionMicros:d}:{},scope:c,...u!==void 0?{totalMicros:u}:{}}}),totalMicros:a.totalMicros,valuationPolicy:a.valuationPolicy},displayName:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:i8})}function Mwt(e){return QT(`visa-agent-pairing-terms:v2:${DIe(e)}`)}function xte(e){if(!_u(e))throw new Error("pairing claim v2 must be an object");gd("pairing claim v2",e,["protocolVersion","pairingId","agentId","serverNonce","claimTokenHash","identityKeyJkt","runtime"]),ZT(e.protocolVersion),Ate(e.pairingId),Ll("agentId",e.agentId),Gi("serverNonce",e.serverNonce),Gi("claimTokenHash",e.claimTokenHash),Gi("identityKeyJkt",e.identityKeyJkt);let t=kwt(e.runtime);return eI("visa-agent-pairing-claim:v2",{agentId:e.agentId,claimTokenHash:e.claimTokenHash,cliVersion:t.cliVersion??"",contextLabel:t.contextLabel,identityKeyJkt:e.identityKeyJkt,pairingId:e.pairingId,platform:t.platform??"",protocolVersion:String(e.protocolVersion),runtime:t.runtime,serverNonce:e.serverNonce})}function LIe(e){if(!_u(e))throw new Error("pairing activation v2 must be an object");return gd("pairing activation v2",e,["protocolVersion","pairingId","agentId","ownerPublicId","claimTokenHash","identityKeyJkt","ceremonyHash","deliveryArtifactHash"]),ZT(e.protocolVersion),Ate(e.pairingId),Ll("agentId",e.agentId),Ll("ownerPublicId",e.ownerPublicId),Gi("claimTokenHash",e.claimTokenHash),Gi("identityKeyJkt",e.identityKeyJkt),Gi("ceremonyHash",e.ceremonyHash),Gi("deliveryArtifactHash",e.deliveryArtifactHash),eI("visa-agent-pairing-activation:v2",{agentId:e.agentId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,protocolVersion:String(e.protocolVersion)})}function zIe(e){if(!_u(e))throw new Error("capability attach claim v2 must be an object");return gd("capability attach claim v2",e,["protocolVersion","attachId","agentId","capability","serverNonce","claimTokenHash","identityKeyJkt"]),ZT(e.protocolVersion),UIe(e.attachId),Ll("agentId",e.agentId),Nwt(e.capability),Gi("serverNonce",e.serverNonce),Gi("claimTokenHash",e.claimTokenHash),Gi("identityKeyJkt",e.identityKeyJkt),eI("visa-agent-capability-attach-claim:v2",{agentId:e.agentId,attachId:e.attachId,capability:e.capability,claimTokenHash:e.claimTokenHash,identityKeyJkt:e.identityKeyJkt,protocolVersion:String(e.protocolVersion),serverNonce:e.serverNonce})}function HIe(e){if(!_u(e))throw new Error("agent mail credential claim v2 must be an object");return gd("agent mail credential claim v2",e,["protocolVersion","credentialId","agentId","channelId","serverNonce","identityKeyJkt"]),ZT(e.protocolVersion),Ll("credentialId",e.credentialId),Ll("agentId",e.agentId),Ll("channelId",e.channelId),Gi("serverNonce",e.serverNonce),Gi("identityKeyJkt",e.identityKeyJkt),eI("visa-agent-mail-credential-claim:v2",{agentId:e.agentId,channelId:e.channelId,credentialId:e.credentialId,identityKeyJkt:e.identityKeyJkt,protocolVersion:String(e.protocolVersion),serverNonce:e.serverNonce})}function Ste(e){if(!_u(e))throw new Error("capability attach activation v2 must be an object");return gd("capability attach activation v2",e,["protocolVersion","attachId","agentId","ownerPublicId","identityKeyJkt","claimTokenHash","grantHash","ceremonyHash","deliveryArtifactHash","rail"]),ZT(e.protocolVersion),UIe(e.attachId),Ll("agentId",e.agentId),Ll("ownerPublicId",e.ownerPublicId),Gi("identityKeyJkt",e.identityKeyJkt),Gi("claimTokenHash",e.claimTokenHash),Gi("grantHash",e.grantHash),Gi("ceremonyHash",e.ceremonyHash),Gi("deliveryArtifactHash",e.deliveryArtifactHash),Bwt(e.rail),eI("visa-agent-capability-attach-activation:v2",{agentId:e.agentId,attachId:e.attachId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,grantHash:e.grantHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,protocolVersion:String(e.protocolVersion),rail:e.rail})}function XT(e){if(!_u(e))throw new Error("pairing delivery artifact v2 must be an object");if(gd("pairing delivery artifact v2",e,["v","kind","pairingId","agentId","ownerPublicId","identityKey","terms","ceremonyHash","issuer","activationAudience"]),e.v!==jt)throw new Error("pairing delivery artifact v2 must carry v=2");if(e.kind!=="agent-pairing-delivery")throw new Error("pairing delivery artifact kind must be agent-pairing-delivery");if(Ate(e.pairingId),Ll("agentId",e.agentId),Ll("ownerPublicId",e.ownerPublicId),Gi("ceremonyHash",e.ceremonyHash),!_u(e.identityKey))throw new Error("pairing delivery identityKey must be an object");if(gd("pairing delivery identityKey",e.identityKey,["jkt","publicJwk"]),Gi("identityKey.jkt",e.identityKey.jkt),!_u(e.identityKey.publicJwk))throw new Error("pairing delivery identityKey.publicJwk must be an object");let t=e.identityKey.publicJwk;if(gd("pairing delivery identityKey.publicJwk",t,["kty","crv","x"]),t.kty!=="OKP"||t.crv!=="Ed25519")throw new Error("pairing delivery identity key must be a public Ed25519 OKP JWK");Gi("identityKey.publicJwk.x",t.x);let r=QT(JSON.stringify({crv:"Ed25519",kty:"OKP",x:t.x}));if(e.identityKey.jkt!==r)throw new Error("identityKey.jkt must equal the RFC 7638 thumbprint of publicJwk");if(!_u(e.terms))throw new Error("pairing delivery terms must be PairingTermsV2");if(e.terms.agentSelection!=="new"||e.terms.authority!==null)throw new Error("pairing delivery terms must be a new identity-only pairing");if(e.terms.pairingId!==e.pairingId||e.terms.agentId!==e.agentId||e.terms.ownerPublicId!==e.ownerPublicId||e.terms.identityKeyJkt!==e.identityKey.jkt)throw new Error("pairing delivery terms must match the exact ceremony principals and key");let n=DIe(e.terms);if(Mwt(e.terms)!==e.ceremonyHash)throw new Error("ceremonyHash must equal the hash of the exact canonical v2 terms");let i=lIe("issuer",e.issuer),o=lIe("activationAudience",e.activationAudience);return hte({activationAudience:o,agentId:e.agentId,ceremonyHash:e.ceremonyHash,identityKey:{jkt:e.identityKey.jkt,publicJwk:{crv:"Ed25519",kty:"OKP",x:t.x}},issuer:i,kind:"agent-pairing-delivery",ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,terms:JSON.parse(n),v:jt})}function $Ie(e){return QT(`visa-agent-pairing-delivery-artifact:v2:${XT(e)}`)}function QT(e){return YT.default.createHash("sha256").update(e,"utf8").digest("base64url")}function eI(e,t){return`${e}
7
+ `)}var Gj,r5t,i5t,bu,e8=k(()=>{"use strict";oTe();sTe();uTe();pTe();FT();ly();Gj="4.1.0-rc.59",r5t=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;i5t="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";bu=class{constructor(t){this.getSessionToken=t;this.baseUrl=Ta()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!uy()){let n=t.headers.get("X-Latest-Version");n&&lTe(n,Gj)&&(this.lastSignals.updateAvailable={currentVersion:Gj,latestVersion:n})}let r=t.headers.get("X-Feedback-Prompt");if(r)try{this.lastSignals.feedbackPrompt=JSON.parse(r)}catch{}}getClientVersion(){return Gj}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Lj(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t){let r=null;try{r=await t.json()}catch{}throw new Error(o5t(r))}async request(t,r,n,i,o){let s=await this.getSessionToken();if(!s)throw new Error(s5t());let a={Authorization:`Bearer ${s}`};o&&(t==="GET"?a["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):n={...n||{},user_context:o}),n&&(a["Content-Type"]="application/json");let c;try{c=await iTe(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":Gj,"X-Source":"cli"},body:n?JSON.stringify(n):void 0,timeoutMs:i})}catch(d){throw new Error(cTe(d))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your device session has expired. Ask your agent to call `enroll_agent` to reconnect.");if(c.status===429){let d=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s, then retry.`)}c.status===503&&await this.throwServerUnavailable(c);let u;try{u=await c.json()}catch{throw c.status===500?new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${r}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`):(this.throwIfAttestationDrift(u),n5t(c.status,u));return u}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async merchantDirectorySearch(t,r){let n=new URLSearchParams;return t.provider&&n.set("provider",t.provider),t.q&&n.set("q",t.q),t.protocol&&n.set("protocol",t.protocol),t.maxPriceUsd&&n.set("max_price_usd",t.maxPriceUsd),n.set("limit",String(t.limit)),n.set("offset",String(t.offset)),this.request("GET",`/v1/merchant-directory/search?${n.toString()}`,void 0,void 0,r)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getAgentTapStatus(t){try{return await this.request("GET",`/v4/agent-bindings/${encodeURIComponent(t)}/tap-status`)}catch{return null}}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,r){return this.request("POST","/v1/attestation-key",{publicKey:t,...r?{attestation:r}:{}})}async startAttestationRecovery(t,r){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,r)}async setBiometricPreference(t,r){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,r)}async getPendingWebAuthenticators(t){return this.request("GET","/v1/webauthn/pending",void 0,void 0,t)}async authorizeWebAuthenticator(t,r){return this.request("POST","/v1/webauthn/authorize",t,void 0,r)}async logout(t,r){return this.request("POST","/v4/logout",t,void 0,r)}async feedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(t){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.startingAfter!=null&&r.set("starting_after",String(t.startingAfter)),t?.endingBefore!=null&&r.set("ending_before",String(t.endingBefore));let n=r.toString();return this.request("GET",n?`/v1/api/keys?${n}`:"/v1/api/keys")}async listAllAppApiKeys(){let t=[],r=new Set,n,i=null,o=0;for(;;){let s=await this.listAppApiKeys({limit:100,...n!==void 0?{startingAfter:n}:{}});if(o+=1,i=s,t.push(...s.keys??[]),!s.has_more)break;if(s.next_cursor==null)throw new Error("API key pagination response did not include next_cursor.");if(r.has(s.next_cursor))throw new Error("API key pagination cursor did not advance.");r.add(s.next_cursor),n=s.next_cursor}return{...i??{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 submitFeedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async getFeedback(t,r){let n=new URLSearchParams;t&&n.set("limit",String(t));let i=n.toString();return this.request("GET",`/v1/feedback${i?"?"+i:""}`,void 0,void 0,r)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}async createCapabilityAttach(t,r){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/capability-attach`,{protocolVersion:2,capability:r.capability,aggregateCeilingCents:r.aggregateCeilingCents,perPurchaseCents:r.perPurchaseCents})}async issueAgentEmailChannel(t,r){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/channels/email`,{},void 0,r)}async beginAgentMailRuntimeCredential(t,r){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/channels/email/runtime-credential`,{},void 0,r)}async claimAgentMailRuntimeCredential(t,r,n){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/channels/email/runtime-credentials/${encodeURIComponent(r)}/claim`,n)}}});function Xee(e=xTe){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function STe(e=xTe){return/-(?:rc|alpha|beta)\./i.test(e)}function Qee(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function py(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return t?Qee(t):STe()?c5t:a5t}function TTe(e){return`${Qee(e)}${u5t}`}function d5t(e=process.env){return!!e.VISA_VERIFY_WEB_URL?.trim()||STe()}function ete(e,t=process.env){if(!e||!d5t(t))return e;try{let r=new URL(py(t)),n=new URL(e);return n.protocol=r.protocol,n.host=r.host,n.toString()}catch{return e}}async function ITe(e,t=fetch){let r=`${Qee(e)}/api/agent-enroll/health`,n;try{n=await t(r,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Could not verify the v4 sign-in service. Try again shortly.")}if(!n.ok)throw new Error(`V4 sign-in readiness check failed (${n.status}).`);if((await n.json().catch(()=>null))?.clients?.auth!=="turnkey")throw new Error("V4 sign-in is not enabled on this deployment; refusing to open the retired GitHub flow.")}var xTe,a5t,c5t,u5t,Wj=k(()=>{"use strict";xTe="4.1.0-rc.59",a5t="https://app.visacli.sh",c5t="https://web-visa-code-preview.up.railway.app",u5t="/agent/enroll"});function L5t(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function SIe(e,t,r=""){let n=L5t(e),i=e?.length,o=t!==void 0;if(!n||o&&i!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=n?`length=${i}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return e}function QTe(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 z5t(e,t){SIe(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function mte(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ste(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function H5t(e,t={}){let r=(i,o)=>e(o).update(i).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>e(i),Object.assign(r,t),Object.freeze(r)}function V5t(e,t=!1){return t?{h:Number(e&eU),l:Number(e>>eIe&eU)}:{h:Number(e>>eIe&eU)|0,l:Number(e&eU)|0}}function K5t(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=V5t(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function O0(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function iwt(){return U5t.randomSecretKey()}function K_(e){return k5t(e)}function IIe(){let e=iwt();return{secretKey:e,publicKey:K_(e)}}function PIe(e){if(e.length!==iIe)throw new Error(`Ed25519 seed must be ${iIe} bytes, got ${e.length}`);return{secretKey:e,publicKey:K_(e)}}function gy(e,t){return B5t(t,e)}function owt(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function swt(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function uU(e){return owt(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function OIe(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return swt(r)}function awt(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function G_(e){let t=K_(e);return{kty:"OKP",crv:"Ed25519",x:uU(t),d:uU(e)}}function by(e){return{kty:"OKP",crv:"Ed25519",x:uU(e)}}function a8(e){if(awt(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return OIe(e.d)}function sIe(e,t){return e<t?-1:e>t?1:0}function cte(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Er(e){if(typeof e!="string"||!dwt.test(e))return!1;try{let t=OIe(e);return t.byteLength===32&&uU(t)===e}catch{return!1}}function ute(e,t,r){let n=Object.keys(t).filter(i=>!r.has(i));if(n.length>0)throw new Error(`${e} contains unknown field(s): ${n.sort().join(", ")}`)}function gwt(e,t){if(typeof t!="string"||!uwt.test(t))throw new Error(`${e} must be a UUID`)}function WT(e,t){return gwt(e,t),t.toLowerCase()}function aIe(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let r=pwt.exec(t);if(!r)throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let[,n,i,o,s,a,c]=r,u=Number(n),d=Number(i),l=Number(o),p=Number(s),f=Number(a),m=Number(c),h=new Date(0);if(h.setUTCFullYear(u,d-1,l),h.setUTCHours(p,f,m,0),u===0||h.getUTCFullYear()!==u||h.getUTCMonth()!==d-1||h.getUTCDate()!==l||h.getUTCHours()!==p||h.getUTCMinutes()!==f||h.getUTCSeconds()!==m)throw new Error(`${e} must be a valid calendar timestamp`);let y=Date.parse(t);if(!Number.isFinite(y))throw new Error(`${e} must be a valid ISO timestamp`);return new Date(y).toISOString()}function nU(e,t,r=!1){if(typeof t!="string"||!lwt.test(t))throw new Error(`${e} must be a canonical non-negative integer micros string`);if(!r&&t==="0")throw new Error(`${e} must be positive`);if(BigInt(t)>mwt)throw new Error(`${e} exceeds the PostgreSQL BIGINT range`);return t}function bwt(e,t){if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>fwt)throw new Error(`${e} must be a positive PostgreSQL INTEGER`);return t}function cIe(e,t){if(typeof t!="string")throw new Error(`${e} must be a string`);if(kIe.test(t))throw new Error(`${e} must be a bounded non-empty payee without control characters`);let r=t.normalize("NFC").trim();if(r.length===0||r.length>hwt)throw new Error(`${e} must be a bounded non-empty payee without control characters`);return r}function _wt(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(kIe.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function dte(e,t){return typeof e=="string"&&t.includes(e)}function vwt(e){if(!cte(e))throw new Error("agent authority grant must be an object");if(ute("agent authority grant",e,new Set(["v","grantId","agentId","version","budgetEpochId","budgetEpochMode","status","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt","supersedesGrantId"])),e.v!==i8)throw new Error("grant.v must be 2");let t=WT("grantId",e.grantId),r=WT("agentId",e.agentId),n=bwt("version",e.version),i=WT("budgetEpochId",e.budgetEpochId);if(!dte(e.budgetEpochMode,cwt))throw new Error("budgetEpochMode must be new or continue");if(!dte(e.status,["active","superseded","revoked"]))throw new Error("invalid grant status");if(e.currency!=="USD")throw new Error("currency must be 'USD'");if(e.valuationPolicy!==ate)throw new Error(`valuationPolicy must be '${ate}'`);let o=nU("totalMicros",e.totalMicros),s=nU("perTransactionMicros",e.perTransactionMicros);if(BigInt(s)>BigInt(o))throw new Error("perTransactionMicros cannot exceed totalMicros");if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("scopes must be a non-empty array");let a=e.scopes.map(l=>{if(!cte(l))throw new Error("grant scope must be an object");if(ute("grant scope",l,new Set(["scope","totalMicros","perTransactionMicros","instrumentRef"])),!dte(l.scope,yy))throw new Error("invalid authorization scope");let p=l.totalMicros===void 0?void 0:nU("scope.totalMicros",l.totalMicros),f=l.perTransactionMicros===void 0?void 0:nU("scope.perTransactionMicros",l.perTransactionMicros);if(p!==void 0&&BigInt(p)>BigInt(o))throw new Error("scope.totalMicros cannot exceed the aggregate totalMicros");if(f!==void 0&&BigInt(f)>BigInt(s))throw new Error("scope.perTransactionMicros cannot exceed the aggregate perTransactionMicros");if(p!==void 0&&f!==void 0&&BigInt(f)>BigInt(p))throw new Error("scope.perTransactionMicros cannot exceed scope.totalMicros");let m=_wt("scope.instrumentRef",l.instrumentRef,255);return{scope:l.scope,...p!==void 0?{totalMicros:p}:{},...f!==void 0?{perTransactionMicros:f}:{},instrumentRef:m}});if(new Set(a.map(({scope:l})=>l)).size!==a.length)throw new Error("scopes must not repeat");let c;if(e.payeeConstraints!==void 0){if(!Array.isArray(e.payeeConstraints)||e.payeeConstraints.length===0||e.payeeConstraints.length>oIe)throw new Error(`payeeConstraints must contain between 1 and ${oIe} entries`);if(c=e.payeeConstraints.map(p=>{if(!cte(p))throw new Error("payee constraint must be an object");if(ute("payee constraint",p,new Set(["scope","kind","canonicalId"])),p.scope==="card:vic"&&p.kind==="processor_merchant_id")return{scope:p.scope,kind:p.kind,canonicalId:cIe("payee constraint canonicalId",p.canonicalId)};if(p.scope==="wallet:x402"&&p.kind==="evm_address"){let f=cIe("payee constraint canonicalId",p.canonicalId).toLowerCase();if(!ywt.test(f))throw new Error("wallet payee constraint canonicalId must be an EVM address");return{scope:p.scope,kind:p.kind,canonicalId:f}}throw new Error("payee constraint scope/kind combination is invalid")}),c.some(p=>!a.some(({scope:f})=>f===p.scope)))throw new Error("payee constraint scope must be present in grant scopes");let l=c.map(({scope:p,kind:f,canonicalId:m})=>`${p}:${f}:${m}`);if(new Set(l).size!==l.length)throw new Error("payeeConstraints must not repeat after normalization")}let u=aIe("effectiveAt",e.effectiveAt),d=aIe("expiresAt",e.expiresAt);if(Date.parse(d)<=Date.parse(u))throw new Error("expiresAt must be after effectiveAt");if(e.supersedesGrantId!==void 0&&WT("supersedesGrantId",e.supersedesGrantId)===t)throw new Error("a grant cannot supersede itself");return{v:i8,grantId:t,agentId:r,version:n,budgetEpochId:i,budgetEpochMode:e.budgetEpochMode,status:e.status,currency:"USD",valuationPolicy:ate,totalMicros:o,perTransactionMicros:s,scopes:[...a].sort((l,p)=>sIe(l.scope,p.scope)),...c!==void 0?{payeeConstraints:[...c].sort((l,p)=>sIe(`${l.scope}:${l.kind}:${l.canonicalId}`,`${p.scope}:${p.kind}:${p.canonicalId}`))}:{},effectiveAt:u,expiresAt:d,...e.supersedesGrantId!==void 0?{supersedesGrantId:WT("supersedesGrantId",e.supersedesGrantId)}:{}}}function jIe(e,t){return e<t?-1:e>t?1:0}function _u(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gd(e,t,r){let n=new Set(r),i=Object.keys(t).filter(o=>!n.has(o));if(i.length>0)throw new Error(`${e} contains unknown field(s): ${i.sort().join(", ")}`)}function Cwt(e){if(typeof e!="string")throw new Error("displayName must be a string");if(pU.test(e))throw new Error("displayName must be bounded, non-empty text without control characters");let t=e.normalize("NFC").trim().replace(/ {2,}/g," ");if(t.length===0||t.length>Awt)throw new Error("displayName must be bounded, non-empty text without control characters");return t}function Owt(e){if(typeof e!="string")throw new Error("dotVisaAddress must be a string");if(pU.test(e))throw new Error("dotVisaAddress must be a valid .visa address");let t=e.trim().toLowerCase();if(!Ewt.test(t))throw new Error("dotVisaAddress must be a valid .visa address");return t}function iU(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(pU.test(t)||BIe.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function kwt(e){if(!_u(e))throw new Error("runtime context v2 must be an object");gd("runtime context v2",e,["runtime","contextLabel","cliVersion","platform"]);let t=iU("runtime",e.runtime,Swt),r=iU("contextLabel",e.contextLabel,Twt),n=e.cliVersion===void 0?void 0:iU("cliVersion",e.cliVersion,Iwt),i=e.platform===void 0?void 0:iU("platform",e.platform,Pwt);return{runtime:t,contextLabel:r,...n!==void 0?{cliVersion:n}:{},...i!==void 0?{platform:i}:{}}}function Ate(e){if(typeof e!="string"||!NIe.test(e))throw new Error("pairingId must be a server-generated pairing id")}function ZT(e){if(e!==jt)throw new Error("protocolVersion must be 2")}function Ll(e,t){if(typeof t!="string"||!xwt.test(t))throw new Error(`${e} must be a canonical lowercase UUID`)}function Gi(e,t){if(!Er(t))throw new Error(`${e} must be 32 canonical unpadded base64url bytes`)}function UIe(e){if(typeof e!="string"||!Rwt.test(e))throw new Error("attachId must be a server-generated capability-attach id")}function Nwt(e){if(typeof e!="string"||!dU.includes(e))throw new Error(`capability must be one of ${dU.join(", ")}`)}function Bwt(e){if(typeof e!="string"||!yy.includes(e))throw new Error(`rail must be one of ${yy.join(", ")}`)}function lIe(e,t){if(typeof t!="string"||t.length===0||t.length>dIe||pU.test(t)||BIe.test(t))throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let r;try{r=new URL(t)}catch{throw new Error(`${e} must be a bounded absolute HTTP(S) URL`)}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.hostname.length===0||r.username.length>0||r.password.length>0||r.hash.length>0)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let n=r.toString();if(n.length>dIe)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);return n}function MIe(){return YT.default.randomBytes(32).toString("base64url")}function qIe(e){if(!Er(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return QT(e)}function jwt(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function Uwt(e){let t=jwt(e);return`${t.slice(0,4)}-${t.slice(4)}`}function fU(){return YT.default.randomBytes(32).toString("base64url")}function k0(e){if(!Er(e))throw new Error("claim token must be 32 unpadded base64url bytes");return QT(`visa-agent-pairing-claim-token:v1:${e}`)}function mU(e,t){k0(t);let r=YT.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<wwt;i+=1)n+=Ete[r[i]&RIe];return Uwt(n)}function DIe(e){if(!_u(e))throw new Error("pairing terms v2 must be an object");if(gd("pairing terms v2",e,["v","pairingId","agentId","agentSelection","identityKeyJkt","ownerPublicId","displayName","dotVisaAddress","authority"]),e.v!==i8)throw new Error("pairing terms v2 must carry v=2");if(typeof e.pairingId!="string"||!NIe.test(e.pairingId))throw new Error("pairingId must be a server-issued pairing id");if(typeof e.agentId!="string"||!uIe.test(e.agentId))throw new Error("agentId must be a UUID");if(e.agentSelection!=="new"&&e.agentSelection!=="existing")throw new Error("agentSelection must be new or existing");if(!Er(e.identityKeyJkt))throw new Error("identityKeyJkt must be a canonical 32-byte base64url thumbprint");if(typeof e.ownerPublicId!="string"||!uIe.test(e.ownerPublicId))throw new Error("ownerPublicId must be a UUID");let t=e.agentId.toLowerCase(),r=e.ownerPublicId.toLowerCase(),n=Cwt(e.displayName),i=e.dotVisaAddress===void 0?void 0:Owt(e.dotVisaAddress);if(e.authority===null){if(e.agentSelection==="existing")throw new Error("an existing-agent pairing must bind its exact current authority; identity-only attachment requires a future explicit no-spend key policy");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:null,displayName:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:i8})}if(!_u(e.authority))throw new Error("pairing authority must be an object or null");if(gd("pairing authority",e.authority,["grantId","grantVersion","supersedesGrantId","budgetEpochId","budgetEpochMode","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt"]),!Array.isArray(e.authority.scopes)||e.authority.scopes.length===0||e.authority.scopes.length>yy.length)throw new Error(`pairing authority scopes must contain between 1 and ${yy.length} entries`);let o=new Map,s=e.authority.scopes.map(c=>{if(!_u(c))throw new Error("pairing authority scope must be an object");if(Object.prototype.hasOwnProperty.call(c,"instrumentRef"))throw new Error("pairing authority scopes may not supply instrumentRef; auth resolves it");if(gd("pairing authority scope",c,["scope","totalMicros","perTransactionMicros","instrumentCommitment"]),!yy.includes(c.scope))throw new Error("invalid authorization scope");let u=c.scope;if(!Er(c.instrumentCommitment))throw new Error("every approved scope requires a 32-byte instrumentCommitment");return o.set(u,c.instrumentCommitment),{scope:u,instrumentRef:c.instrumentCommitment,...c.totalMicros!==void 0?{totalMicros:c.totalMicros}:{},...c.perTransactionMicros!==void 0?{perTransactionMicros:c.perTransactionMicros}:{}}}),a=vwt({v:i8,grantId:e.authority.grantId,agentId:t,version:e.authority.grantVersion,budgetEpochId:e.authority.budgetEpochId,budgetEpochMode:e.authority.budgetEpochMode,status:"active",currency:e.authority.currency,valuationPolicy:e.authority.valuationPolicy,totalMicros:e.authority.totalMicros,perTransactionMicros:e.authority.perTransactionMicros,scopes:s,...e.authority.payeeConstraints!==void 0?{payeeConstraints:e.authority.payeeConstraints}:{},effectiveAt:e.authority.effectiveAt,expiresAt:e.authority.expiresAt,...e.authority.supersedesGrantId!==void 0?{supersedesGrantId:e.authority.supersedesGrantId}:{}});if(e.agentSelection==="new"&&(a.version>1||a.supersedesGrantId!==void 0))throw new Error("a new-agent pairing cannot replace or supersede an existing grant; replacement authority belongs to an existing agent");if(a.version===1&&(a.budgetEpochMode!=="new"||a.supersedesGrantId!==void 0))throw new Error("an initial pairing grant must start a new budget epoch and supersede nothing");if(a.version>1&&a.supersedesGrantId===void 0)throw new Error("a replacement pairing grant must name its direct predecessor");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:{...a.payeeConstraints!==void 0?{payeeConstraints:a.payeeConstraints}:{},currency:a.currency,effectiveAt:a.effectiveAt,expiresAt:a.expiresAt,grantId:a.grantId,grantVersion:a.version,budgetEpochId:a.budgetEpochId,budgetEpochMode:a.budgetEpochMode,...a.supersedesGrantId!==void 0?{supersedesGrantId:a.supersedesGrantId}:{},perTransactionMicros:a.perTransactionMicros,scopes:a.scopes.map(({scope:c,totalMicros:u,perTransactionMicros:d})=>{let l=o.get(c);if(l===void 0)throw new Error("canonical scope lost its approved instrument commitment");return{instrumentCommitment:l,...d!==void 0?{perTransactionMicros:d}:{},scope:c,...u!==void 0?{totalMicros:u}:{}}}),totalMicros:a.totalMicros,valuationPolicy:a.valuationPolicy},displayName:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:i8})}function Mwt(e){return QT(`visa-agent-pairing-terms:v2:${DIe(e)}`)}function xte(e){if(!_u(e))throw new Error("pairing claim v2 must be an object");gd("pairing claim v2",e,["protocolVersion","pairingId","agentId","serverNonce","claimTokenHash","identityKeyJkt","runtime"]),ZT(e.protocolVersion),Ate(e.pairingId),Ll("agentId",e.agentId),Gi("serverNonce",e.serverNonce),Gi("claimTokenHash",e.claimTokenHash),Gi("identityKeyJkt",e.identityKeyJkt);let t=kwt(e.runtime);return eI("visa-agent-pairing-claim:v2",{agentId:e.agentId,claimTokenHash:e.claimTokenHash,cliVersion:t.cliVersion??"",contextLabel:t.contextLabel,identityKeyJkt:e.identityKeyJkt,pairingId:e.pairingId,platform:t.platform??"",protocolVersion:String(e.protocolVersion),runtime:t.runtime,serverNonce:e.serverNonce})}function LIe(e){if(!_u(e))throw new Error("pairing activation v2 must be an object");return gd("pairing activation v2",e,["protocolVersion","pairingId","agentId","ownerPublicId","claimTokenHash","identityKeyJkt","ceremonyHash","deliveryArtifactHash"]),ZT(e.protocolVersion),Ate(e.pairingId),Ll("agentId",e.agentId),Ll("ownerPublicId",e.ownerPublicId),Gi("claimTokenHash",e.claimTokenHash),Gi("identityKeyJkt",e.identityKeyJkt),Gi("ceremonyHash",e.ceremonyHash),Gi("deliveryArtifactHash",e.deliveryArtifactHash),eI("visa-agent-pairing-activation:v2",{agentId:e.agentId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,protocolVersion:String(e.protocolVersion)})}function zIe(e){if(!_u(e))throw new Error("capability attach claim v2 must be an object");return gd("capability attach claim v2",e,["protocolVersion","attachId","agentId","capability","serverNonce","claimTokenHash","identityKeyJkt"]),ZT(e.protocolVersion),UIe(e.attachId),Ll("agentId",e.agentId),Nwt(e.capability),Gi("serverNonce",e.serverNonce),Gi("claimTokenHash",e.claimTokenHash),Gi("identityKeyJkt",e.identityKeyJkt),eI("visa-agent-capability-attach-claim:v2",{agentId:e.agentId,attachId:e.attachId,capability:e.capability,claimTokenHash:e.claimTokenHash,identityKeyJkt:e.identityKeyJkt,protocolVersion:String(e.protocolVersion),serverNonce:e.serverNonce})}function HIe(e){if(!_u(e))throw new Error("agent mail credential claim v2 must be an object");return gd("agent mail credential claim v2",e,["protocolVersion","credentialId","agentId","channelId","serverNonce","identityKeyJkt"]),ZT(e.protocolVersion),Ll("credentialId",e.credentialId),Ll("agentId",e.agentId),Ll("channelId",e.channelId),Gi("serverNonce",e.serverNonce),Gi("identityKeyJkt",e.identityKeyJkt),eI("visa-agent-mail-credential-claim:v2",{agentId:e.agentId,channelId:e.channelId,credentialId:e.credentialId,identityKeyJkt:e.identityKeyJkt,protocolVersion:String(e.protocolVersion),serverNonce:e.serverNonce})}function Ste(e){if(!_u(e))throw new Error("capability attach activation v2 must be an object");return gd("capability attach activation v2",e,["protocolVersion","attachId","agentId","ownerPublicId","identityKeyJkt","claimTokenHash","grantHash","ceremonyHash","deliveryArtifactHash","rail"]),ZT(e.protocolVersion),UIe(e.attachId),Ll("agentId",e.agentId),Ll("ownerPublicId",e.ownerPublicId),Gi("identityKeyJkt",e.identityKeyJkt),Gi("claimTokenHash",e.claimTokenHash),Gi("grantHash",e.grantHash),Gi("ceremonyHash",e.ceremonyHash),Gi("deliveryArtifactHash",e.deliveryArtifactHash),Bwt(e.rail),eI("visa-agent-capability-attach-activation:v2",{agentId:e.agentId,attachId:e.attachId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,grantHash:e.grantHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,protocolVersion:String(e.protocolVersion),rail:e.rail})}function XT(e){if(!_u(e))throw new Error("pairing delivery artifact v2 must be an object");if(gd("pairing delivery artifact v2",e,["v","kind","pairingId","agentId","ownerPublicId","identityKey","terms","ceremonyHash","issuer","activationAudience"]),e.v!==jt)throw new Error("pairing delivery artifact v2 must carry v=2");if(e.kind!=="agent-pairing-delivery")throw new Error("pairing delivery artifact kind must be agent-pairing-delivery");if(Ate(e.pairingId),Ll("agentId",e.agentId),Ll("ownerPublicId",e.ownerPublicId),Gi("ceremonyHash",e.ceremonyHash),!_u(e.identityKey))throw new Error("pairing delivery identityKey must be an object");if(gd("pairing delivery identityKey",e.identityKey,["jkt","publicJwk"]),Gi("identityKey.jkt",e.identityKey.jkt),!_u(e.identityKey.publicJwk))throw new Error("pairing delivery identityKey.publicJwk must be an object");let t=e.identityKey.publicJwk;if(gd("pairing delivery identityKey.publicJwk",t,["kty","crv","x"]),t.kty!=="OKP"||t.crv!=="Ed25519")throw new Error("pairing delivery identity key must be a public Ed25519 OKP JWK");Gi("identityKey.publicJwk.x",t.x);let r=QT(JSON.stringify({crv:"Ed25519",kty:"OKP",x:t.x}));if(e.identityKey.jkt!==r)throw new Error("identityKey.jkt must equal the RFC 7638 thumbprint of publicJwk");if(!_u(e.terms))throw new Error("pairing delivery terms must be PairingTermsV2");if(e.terms.agentSelection!=="new"||e.terms.authority!==null)throw new Error("pairing delivery terms must be a new identity-only pairing");if(e.terms.pairingId!==e.pairingId||e.terms.agentId!==e.agentId||e.terms.ownerPublicId!==e.ownerPublicId||e.terms.identityKeyJkt!==e.identityKey.jkt)throw new Error("pairing delivery terms must match the exact ceremony principals and key");let n=DIe(e.terms);if(Mwt(e.terms)!==e.ceremonyHash)throw new Error("ceremonyHash must equal the hash of the exact canonical v2 terms");let i=lIe("issuer",e.issuer),o=lIe("activationAudience",e.activationAudience);return hte({activationAudience:o,agentId:e.agentId,ceremonyHash:e.ceremonyHash,identityKey:{jkt:e.identityKey.jkt,publicJwk:{crv:"Ed25519",kty:"OKP",x:t.x}},issuer:i,kind:"agent-pairing-delivery",ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,terms:JSON.parse(n),v:jt})}function $Ie(e){return QT(`visa-agent-pairing-delivery-artifact:v2:${XT(e)}`)}function QT(e){return YT.default.createHash("sha256").update(e,"utf8").digest("base64url")}function eI(e,t){return`${e}
8
8
  ${Object.entries(t).sort(([r],[n])=>jIe(r,n)).map(([r,n])=>`${r}=${n}`).join(`
9
9
  `)}`}function hte(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(hte).join(",")}]`;let t=e;return`{${Object.keys(t).sort(jIe).map(r=>`${JSON.stringify(r)}:${hte(t[r])}`).join(",")}}`}var YT,pIe,sU,oU,KTe,GTe,nte,ite,w5t,o8,E5t,cs,A5t,x5t,S5t,ff,lU,yte,fIe,gte,C0,WTe,bte,mIe,T5t,s8,hIe,aU,H_,Sn,JTe,Ve,yIe,gIe,bIe,_Ie,ote,lte,JT,V_,F_,vIe,wIe,pf,I5t,YTe,P5t,pte,C5t,_te,EIe,O5t,vte,k5t,R5t,N5t,B5t,wte,AIe,j5t,U5t,cU,M5t,xIe,fte,q5t,ZTe,XTe,D5t,$5t,F5t,$s,eU,eIe,tIe,rIe,r8,n8,tU,rU,G5t,W5t,J5t,Y5t,Z5t,X5t,TIe,Q5t,ewt,my,hy,twt,rwt,nwt,nIe,iIe,sUr,CIe,aUr,cUr,uUr,dUr,i8,cwt,ate,yy,uwt,dwt,lwt,pwt,kIe,fwt,mwt,oIe,hwt,ywt,lUr,dU,jt,Ete,wwt,RIe,NIe,uIe,pU,Ewt,Awt,xwt,Swt,Twt,Iwt,Pwt,dIe,BIe,Rwt,W_=k(()=>{"use strict";YT=_e(require("node:crypto"),1),pIe=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:sU,n:oU,Gx:KTe,Gy:GTe,a:nte,d:ite,h:w5t}=pIe,o8=32,E5t=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},cs=(e="")=>{let t=new Error(e);throw E5t(t,cs),t},A5t=e=>typeof e=="bigint",x5t=e=>typeof e=="string",S5t=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,ff=(e,t,r="")=>{let n=S5t(e),i=e?.length,o=t!==void 0;if(!n||o&&i!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=n?`length=${i}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return e},lU=e=>new Uint8Array(e),yte=e=>Uint8Array.from(e),fIe=(e,t)=>e.toString(16).padStart(t,"0"),gte=e=>Array.from(ff(e)).map(t=>fIe(t,2)).join(""),C0={_0:48,_9:57,A:65,F:70,a:97,f:102},WTe=e=>{if(e>=C0._0&&e<=C0._9)return e-C0._0;if(e>=C0.A&&e<=C0.F)return e-(C0.A-10);if(e>=C0.a&&e<=C0.f)return e-(C0.a-10)},bte=e=>{let t="hex invalid";if(!x5t(e))return cs(t);let r=e.length,n=r/2;if(r%2)return cs(t);let i=lU(n);for(let o=0,s=0;o<n;o++,s+=2){let a=WTe(e.charCodeAt(s)),c=WTe(e.charCodeAt(s+1));if(a===void 0||c===void 0)return cs(t);i[o]=a*16+c}return i},mIe=()=>globalThis?.crypto,T5t=()=>mIe()?.subtle??cs("crypto.subtle must be defined, consider polyfill"),s8=(...e)=>{let t=0;for(let i of e)t+=ff(i).length;let r=lU(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},hIe=(e=o8)=>mIe().getRandomValues(lU(e)),aU=BigInt,H_=(e,t,r,n="bad number: out of range")=>{if(!A5t(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Sn=(e,t=sU)=>{let r=e%t;return r>=0n?r:t+r},JTe=(1n<<255n)-1n,Ve=e=>{e<0n&&cs("negative coordinate");let t=(e>>255n)*19n+(e&JTe);return t=(t>>255n)*19n+(t&JTe),t%sU},yIe=e=>Sn(e,oU),gIe=(e,t)=>{(e===0n||t<=0n)&&cs("no inverse n="+e+" mod="+t);let r=Sn(e,t),n=t,i=0n,o=1n,s=1n,a=0n;for(;r!==0n;){let c=n/r,u=n%r,d=i-s*c,l=o-a*c;n=r,r=u,i=s,o=a,s=d,a=l}return n===1n?Sn(i,t):cs("no inverse")},bIe=e=>{let t=AIe[e];return typeof t!="function"&&cs("hashes."+e+" not set"),t},_Ie=e=>ff(e,64,"digest"),ote=e=>e instanceof JT?e:cs("Point expected"),lte=2n**256n,JT=class $_{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=lte;this.X=H_(t,0n,o),this.Y=H_(r,0n,o),this.Z=H_(n,1n,o),this.T=H_(i,0n,o),Object.freeze(this)}static CURVE(){return pIe}static fromAffine(t){return new $_(t.x,t.y,1n,Ve(t.x*t.y))}static fromBytes(t,r=!1){let n=ite,i=yte(ff(t,o8)),o=t[31];i[31]=o&-129;let s=wIe(i);H_(s,0n,r?lte:sU);let c=Ve(s*s),u=Sn(c-1n),d=Ve(n*c+1n),{isValid:l,value:p}=P5t(u,d);l||cs("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&cs("bad point: x==0, isLastByteOdd"),m!==f&&(p=Sn(-p)),new $_(p,s,1n,Ve(p*s))}static fromHex(t,r){return $_.fromBytes(bte(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=nte,r=ite,n=this;if(n.is0())return cs("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=Ve(i*i),u=Ve(o*o),d=Ve(s*s),l=Ve(d*d),p=Ve(c*t),f=Ve(d*(p+u)),m=Sn(l+Ve(r*Ve(c*u)));if(f!==m)return cs("bad point: equation left != right (1)");let h=Ve(i*o),y=Ve(s*a);return h!==y?cs("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=ote(t),c=Ve(r*a),u=Ve(o*i),d=Ve(n*a),l=Ve(s*i);return c===u&&d===l}is0(){return this.equals(F_)}negate(){return new $_(Sn(-this.X),this.Y,this.Z,Sn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=nte,o=Ve(t*t),s=Ve(r*r),a=Ve(2n*n*n),c=Ve(i*o),u=Sn(t+r),d=Sn(Ve(u*u)-o-s),l=Sn(c+s),p=Sn(l-a),f=Sn(c-s),m=Ve(d*p),h=Ve(l*f),y=Ve(d*f),v=Ve(p*l);return new $_(m,h,v,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=ote(t),d=nte,l=ite,p=Ve(r*s),f=Ve(n*a),m=Ve(Ve(o*l)*u),h=Ve(i*c),y=Sn(Ve(Sn(r+n)*Sn(s+a))-p-f),v=Sn(h-m),E=Sn(h+m),b=Sn(f-Ve(d*p)),w=Ve(y*v),A=Ve(E*b),x=Ve(y*b),S=Ve(v*E);return new $_(w,A,S,x)}subtract(t){return this.add(ote(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(H_(t,1n,oU),!r&&this.is0()))return F_;if(t===1n)return this;if(this.equals(V_))return D5t(t).p;let n=F_,i=V_;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?n=n.add(o):r&&(i=i.add(o));return n}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:n}=this;if(this.equals(F_))return{x:0n,y:1n};let i=gIe(n,sU);Ve(n*i)!==1n&&cs("invalid inverse");let o=Ve(t*i),s=Ve(r*i);return{x:o,y:s}}toBytes(){let{x:t,y:r}=this.toAffine(),n=vIe(r);return n[31]|=t&1n?128:0,n}toHex(){return gte(this.toBytes())}clearCofactor(){return this.multiply(aU(w5t),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(oU/2n,!1).double();return oU%2n&&(t=t.add(this)),t.is0()}},V_=new JT(KTe,GTe,1n,Sn(KTe*GTe)),F_=new JT(0n,1n,1n,0n);JT.BASE=V_;JT.ZERO=F_;vIe=e=>bte(fIe(H_(e,0n,lte),64)).reverse(),wIe=e=>aU("0x"+gte(yte(ff(e)).reverse())),pf=(e,t)=>{let r=e;for(;t-- >0n;)r=Ve(r*r);return r},I5t=e=>{let t=Ve(e*e),r=Ve(t*e),n=Ve(pf(r,2n)*r),i=Ve(pf(n,1n)*e),o=Ve(pf(i,5n)*i),s=Ve(pf(o,10n)*o),a=Ve(pf(s,20n)*s),c=Ve(pf(a,40n)*a),u=Ve(pf(c,80n)*c),d=Ve(pf(u,80n)*c),l=Ve(pf(d,10n)*o);return{pow_p_5_8:Ve(pf(l,2n)*e),b2:r}},YTe=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,P5t=(e,t)=>{let r=Ve(t*Ve(t*t)),n=Ve(Ve(r*r)*t),i=I5t(Ve(e*n)).pow_p_5_8,o=Ve(e*Ve(r*i)),s=Ve(t*Ve(o*o)),a=o,c=Ve(o*YTe),u=s===e,d=s===Sn(-e),l=s===Sn(-e*YTe);return u&&(o=a),(d||l)&&(o=c),(Sn(o)&1n)===1n&&(o=Sn(-o)),{isValid:u||d,value:o}},pte=e=>yIe(wIe(e)),C5t=(...e)=>Promise.resolve(bIe("sha512Async")(s8(...e))).then(_Ie),_te=(...e)=>_Ie(bIe("sha512")(s8(...e))),EIe=e=>{let t=yte(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=pte(r),o=V_.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},O5t=e=>C5t(ff(e,o8)).then(EIe),vte=e=>EIe(_te(ff(e,o8))),k5t=e=>vte(e).pointBytes,R5t=e=>e.finish(_te(e.hashable)),N5t=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=pte(t),s=V_.multiply(o).toBytes();return{hashable:s8(s,n,r),finish:u=>{let d=yIe(o+pte(u)*i);return ff(s8(s,vIe(d)),64)}}},B5t=(e,t)=>{let r=ff(e),n=vte(t),i=_te(n.prefix,r);return R5t(N5t(n,i,r))},wte=Object.freeze({bytesToHex:gte,hexToBytes:bte,concatBytes:s8,mod:Sn,invert:gIe,randomBytes:hIe}),AIe={sha512Async:async e=>{let t=T5t(),r=s8(e);return lU(await t.digest("SHA-512",r.buffer))},sha512:void 0},j5t=e=>(e=e===void 0?hIe(o8):e,ff(e,o8)),U5t=Object.freeze({getExtendedPublicKeyAsync:O5t,getExtendedPublicKey:vte,randomSecretKey:j5t}),cU=8,M5t=256,xIe=Math.ceil(M5t/cU)+1,fte=2**(cU-1),q5t=()=>{let e=[],t=V_,r=t;for(let n=0;n<xIe;n++){r=t,e.push(r);for(let i=1;i<fte;i++)r=r.add(t),e.push(r);t=r.double()}return e},ZTe=void 0,XTe=(e,t)=>{let r=t.negate();return e?r:t},D5t=e=>{let t=ZTe||(ZTe=q5t()),r=F_,n=V_,i=2**cU,o=i,s=aU(i-1),a=aU(cU);for(let c=0;c<xIe;c++){let u=Number(e&s);e>>=a,u>fte&&(u-=o,e+=1n);let d=c*fte,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(XTe(f,t[l])):r=r.add(XTe(m,t[p]))}return e!==0n&&cs("invalid wnaf"),{p:r,f:n}};$5t=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),F5t=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ste(this.buffer)}update(e){QTe(this),SIe(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let o=0;o<i;){let s=Math.min(n-this.pos,i-o);if(s===n){let a=ste(e);for(;n<=i-o;o+=n)this.process(a,o);continue}r.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){QTe(this),z5t(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,mte(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(r,0),o=0);for(let d=o;d<n;d++)t[d]=0;r.setBigUint64(n-8,BigInt(this.length*8),i),this.process(r,0);let s=ste(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:i,destroyed:o,pos:s}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=s,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},$s=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),eU=BigInt(2**32-1),eIe=BigInt(32);tIe=(e,t,r)=>e>>>r,rIe=(e,t,r)=>e<<32-r|t>>>r,r8=(e,t,r)=>e>>>r|t<<32-r,n8=(e,t,r)=>e<<32-r|t>>>r,tU=(e,t,r)=>e<<64-r|t>>>r-32,rU=(e,t,r)=>e>>>r-32|t<<64-r;G5t=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),W5t=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,J5t=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Y5t=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,Z5t=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),X5t=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,TIe=K5t(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Q5t=TIe[0],ewt=TIe[1],my=new Uint32Array(80),hy=new Uint32Array(80),twt=class extends F5t{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:s,Dl:a,Eh:c,El:u,Fh:d,Fl:l,Gh:p,Gl:f,Hh:m,Hl:h}=this;return[e,t,r,n,i,o,s,a,c,u,d,l,p,f,m,h]}set(e,t,r,n,i,o,s,a,c,u,d,l,p,f,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=l|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let E=0;E<16;E++,t+=4)my[E]=e.getUint32(t),hy[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let b=my[E-15]|0,w=hy[E-15]|0,A=r8(b,w,1)^r8(b,w,8)^tIe(b,w,7),x=n8(b,w,1)^n8(b,w,8)^rIe(b,w,7),S=my[E-2]|0,I=hy[E-2]|0,T=r8(S,I,19)^tU(S,I,61)^tIe(S,I,6),C=n8(S,I,19)^rU(S,I,61)^rIe(S,I,6),U=J5t(x,C,hy[E-7],hy[E-16]),M=Y5t(U,A,T,my[E-7],my[E-16]);my[E]=M|0,hy[E]=U|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:s,Cl:a,Dh:c,Dl:u,Eh:d,El:l,Fh:p,Fl:f,Gh:m,Gl:h,Hh:y,Hl:v}=this;for(let E=0;E<80;E++){let b=r8(d,l,14)^r8(d,l,18)^tU(d,l,41),w=n8(d,l,14)^n8(d,l,18)^rU(d,l,41),A=d&p^~d&m,x=l&f^~l&h,S=Z5t(v,w,x,ewt[E],hy[E]),I=X5t(S,y,b,A,Q5t[E],my[E]),T=S|0,C=r8(r,n,28)^tU(r,n,34)^tU(r,n,39),U=n8(r,n,28)^rU(r,n,34)^rU(r,n,39),M=r&i^r&s^i&s,j=n&o^n&a^o&a;y=m|0,v=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=O0(c|0,u|0,I|0,T|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let R=G5t(T,U,j);r=W5t(R,I,C,M),n=R|0}({h:r,l:n}=O0(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=O0(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=O0(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=O0(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=O0(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=O0(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=O0(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:v}=O0(this.Hh|0,this.Hl|0,y|0,v|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,v)}roundClean(){mte(my,hy)}destroy(){this.destroyed=!0,mte(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},rwt=class extends twt{Ah=$s[0]|0;Al=$s[1]|0;Bh=$s[2]|0;Bl=$s[3]|0;Ch=$s[4]|0;Cl=$s[5]|0;Dh=$s[6]|0;Dl=$s[7]|0;Eh=$s[8]|0;El=$s[9]|0;Fh=$s[10]|0;Fl=$s[11]|0;Gh=$s[12]|0;Gl=$s[13]|0;Hh=$s[14]|0;Hl=$s[15]|0;constructor(){super(64)}},nwt=H5t(()=>new rwt,$5t(3)),nIe=AIe;nIe.sha512||(nIe.sha512=e=>nwt(e));iIe=32;sUr=wte.bytesToHex,CIe=wte.hexToBytes,aUr=wte.concatBytes;cUr=new TextEncoder;uUr=CIe("302e020100300506032b657004220420"),dUr=CIe("302a300506032b6570032100"),i8=2,cwt=["new","continue"],ate="nominal_usd_usdc_parity",yy=["card:vic","wallet:x402"],uwt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,dwt=/^[A-Za-z0-9_-]{43}$/,lwt=/^(?:0|[1-9][0-9]*)$/,pwt=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/,kIe=/[\u0000-\u001f\u007f]/,fwt=2147483647,mwt=9223372036854775807n,oIe=100,hwt=512,ywt=/^0x[0-9a-f]{40}$/,lUr=new TextEncoder;dU=["card","wallet"],jt=2,Ete="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",wwt=8,RIe=Ete.length-1;if((Ete.length&RIe)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");NIe=/^ap_[A-Za-z0-9_-]{24}$/,uIe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,pU=/[\p{Cc}\p{Cf}]/u,Ewt=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.visa$/,Awt=255,xwt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Swt=100,Twt=200,Iwt=64,Pwt=100,dIe=2048,BIe=/[\u0080-\u009f\u2028\u2029]/;Rwt=/^ca_[A-Za-z0-9_-]{24}$/;});var KIe={};Oi(KIe,{VisaBindingRequiredError:()=>mf,jkt:()=>hf,readSeed:()=>tI});function hf(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return FIe.createHash("sha256").update(t,"utf8").digest("base64url")}function tI(e){let t=new Uint8Array(VIe.readFileSync(e));if(t.length!==32)throw new Error("Subway identity key must be a 32-byte Ed25519 seed");return t}var FIe,VIe,mf,rI=k(()=>{"use strict";FIe=_e(require("node:crypto")),VIe=_e(require("node:fs"));mf=class extends Error{reason;constructor(t="No active .visa mesh admission binding is stored. Identity pairing does not grant a .visa name or TAP/channel binding; configure that capability separately when its approval flow is available."){super(t),this.name="VisaBindingRequiredError",this.reason="missing_or_incompatible"}}});function Tte(e,t){switch(e){case"name_not_found":return new GIe(t);case"delivery_failed":return new WIe(t);case"timeout":return new nI(t);case"not_registered":return new JIe;case"register_failed":return new hU(t);case"invalid_message":return new YIe(t);case"rate_limited":return new ZIe(t);default:return new yf(e,t)}}var yf,GIe,WIe,nI,JIe,Fs,YIe,hU,ZIe,Ite=k(()=>{"use strict";yf=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},GIe=class extends yf{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},WIe=class extends yf{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},nI=class extends yf{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},JIe=class extends yf{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},Fs=class extends yf{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},YIe=class extends yf{constructor(e){super("invalid_message",e),this.name="InvalidMessageError"}},hU=class extends yf{constructor(e){super("register_failed",e),this.name="RegisterFailedError"}},ZIe=class extends yf{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});var XIe,Pte=k(()=>{"use strict";XIe=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')})});function Q_(e){return e.includes(".")?e:`${e}.relay`}function Cte(){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 qwt(){if(typeof WebSocket<"u")return WebSocket;try{let e=XIe("ws");return e.default??e}catch{return}}function Dwt(e,t,r){return Math.min(Math.max(e,t),r)}function d4t(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function M7e(e,t,r=""){let n=d4t(e),i=e?.length;if(!n||t!==void 0){let s=r&&`"${r}" `,a="",c=n?`length=${i}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return e}function s7e(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 l4t(e,t){M7e(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function iI(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Nte(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function bf(e,t){return e<<32-t|e>>>t}function q7e(e,t={}){let r=(i,o)=>e(o).update(i).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>e(i),Object.assign(r,t),Object.freeze(r)}function p4t(e,t,r){return e&t^~e&r}function f4t(e,t,r){return e&t^e&r^t&r}function m4t(e,t=!1){return t?{h:Number(e&yU),l:Number(e>>a7e&yU)}:{h:Number(e>>a7e&yU)|0,l:Number(e&yU)|0}}function h4t(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=m4t(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function N0(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function k4t(e){return n4t(e)}function R4t(e,t){return s4t(t,e)}function B4t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function M4t(e){let t=N4t(C4t(e.payload)),r=`${e.messageId}
10
10
  ${e.senderPeerId}
@@ -45,7 +45,7 @@ ${e.nonce}`;return j4t.encode(r)}function q4t(e,t,r,n,i,o,s){return M4t({message
45
45
  `)}}catch(n){throw x3t(n)?new _re(e,r,n):n}return{installed:!0,configPath:r,message:e.postInstallHint}}function R3t(e){for(let t of e.split(`
46
46
  `)){if(t.trim()===""||KU(t)>0)continue;let r=t.trim();if(!(r.startsWith("#")||r==="---"||r==="..."||r.startsWith("- "))&&!/^[^\s:#][^:]*:(\s|$)/.test(r))return!1}return!0}function bre(e,t){return e?e.command===t.command&&Array.isArray(e.args)&&e.args.length===t.args.length&&t.args.every((r,n)=>e.args[n]===r):!1}function KPe(e,t,r=JU()){let n=e.configFormat??"json";try{let i=Yt.existsSync(t),o=i?Yt.readFileSync(t,"utf-8"):"",s;if(n==="toml"){if(bre(Sre(o,"visa-cli"),r))return{status:"already-mounted",configPath:t};s=HPe(o,"visa-cli",r)}else if(n==="yaml"){if(i&&!R3t(o))return{status:"error",configPath:t,error:`existing config at ${t} does not look like editable YAML \u2014 fix or remove it, then re-run`};if(bre(Ire(o,"visa-cli"),r))return{status:"already-mounted",configPath:t};s=FPe(o,"visa-cli",r)}else{let a={};if(i){try{a=JSON.parse(o)}catch{return{status:"error",configPath:t,error:`existing config at ${t} is not valid JSON \u2014 fix or remove it, then re-run`}}if(!a||typeof a!="object"||Array.isArray(a))return{status:"error",configPath:t,error:`existing config at ${t} is not a JSON object \u2014 fix or remove it, then re-run`}}if(bre(Ere(a,e.configKey)?.["visa-cli"],r))return{status:"already-mounted",configPath:t};LPe(a,e.configKey)["visa-cli"]=e.buildEntry?e.buildEntry(r):r,s=JSON.stringify(a,null,2)+`
47
47
  `}return Yt.mkdirSync(Nt.dirname(t),{recursive:!0}),Yt.writeFileSync(t,s),{status:"mounted",configPath:t}}catch(i){return{status:"error",configPath:t,error:i instanceof Error?i.message:String(i)}}}function GPe(e,t="global"){let r=t==="project"?Nt.join(process.cwd(),".mcp.json"):vre(e);if(!Yt.existsSync(r))return{removed:!1,configPath:r};let n=Are(e,t);if(n==="toml"){let s=Yt.readFileSync(r,"utf-8");return Sre(s,"visa-cli")?(Yt.writeFileSync(r,P3t(s,"visa-cli")),{removed:!0,configPath:r}):{removed:!1,configPath:r}}if(n==="yaml"){let s=Yt.readFileSync(r,"utf-8");return Ire(s,"visa-cli")?(Yt.writeFileSync(r,k3t(s,"visa-cli")),{removed:!0,configPath:r}):{removed:!1,configPath:r}}let i;try{i=JSON.parse(Yt.readFileSync(r,"utf-8"))}catch{return{removed:!1,configPath:r}}let o=Ere(i,e.configKey);return!o||!o["visa-cli"]?{removed:!1,configPath:r}:(delete o["visa-cli"],Yt.writeFileSync(r,JSON.stringify(i,null,2)+`
48
- `),{removed:!0,configPath:r})}function Pre(e,t="global"){let r=t==="project"?Nt.join(process.cwd(),".mcp.json"):vre(e);if(!Yt.existsSync(r))return!1;let n=Are(e,t);if(n==="toml")try{let i=Yt.readFileSync(r,"utf-8");return!!Sre(i,"visa-cli")}catch{return!1}if(n==="yaml")try{let i=Yt.readFileSync(r,"utf-8");return!!Ire(i,"visa-cli")}catch{return!1}try{let i=JSON.parse(Yt.readFileSync(r,"utf-8"));return!!Ere(i,e.configKey)?.["visa-cli"]}catch{return!1}}var Yt,Nt,jPe,In,A3t,_re,WU,$Pe,Cre=k(()=>{"use strict";Yt=_e(require("fs")),Nt=_e(require("path")),jPe=_e(require("os")),In=jPe.homedir(),A3t=["Claude_","Anthropic.ClaudeDesktop_"],_re=class extends Error{constructor(r,n,i){super(S3t(r,n,i));this.client=r;this.configPath=n;this.name="McpConfigAccessError"}client;configPath};WU=[{id:"claude",displayName:"Claude Code",globalConfigPath:Nt.join(In,".claude.json"),configKey:"mcpServers",detectPaths:[Nt.join(In,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:qPe(),configKey:"mcpServers",detectPaths:DPe(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:Nt.join(In,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[Nt.join(In,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:Nt.join(In,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[Nt.join(In,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:Nt.join(In,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[Nt.join(In,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:gre({win32:Nt.join(fI(),"Roo","mcp_settings.json"),posix:Nt.join(In,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[Nt.join(In,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:Nt.join(In,".vscode","mcp.json"),configKey:"servers",detectPaths:[Nt.join(In,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:gre({win32:Nt.join(fI(),"Zed","settings.json"),posix:Nt.join(In,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:gre({win32:[Nt.join(fI(),"Zed")],posix:[Nt.join(In,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:Nt.join(In,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[Nt.join(In,".codex")],postInstallHint:"Restart Codex to connect."},{id:"openclaw",displayName:"OpenClaw",globalConfigPath:Nt.join(In,".openclaw","openclaw.json"),configKey:"mcp.servers",detectPaths:[Nt.join(In,".openclaw")],postInstallHint:"Restart OpenClaw (or reload its config) to connect."},{id:"hermes",displayName:"Hermes",globalConfigPath:Nt.join(In,".hermes","config.yaml"),configKey:"mcp_servers",configFormat:"yaml",detectPaths:[Nt.join(In,".hermes")],postInstallHint:"Restart Hermes to connect."}];$Pe="mcp_servers"});function Ore(e,t={}){let r=t.home??YU.homedir(),n=t.cwd??process.cwd();switch(e){case"openclaw":return ni.join(r,".openclaw","skills");case"hermes":return ni.join(r,".hermes","skills");case"claude-code":case"claude":return ni.join(r,".claude","skills");case"default":case"agentskills":return ni.join(n,".agents","skills");default:return null}}function N3t(e={}){let t=e.home??YU.homedir(),r=[["openclaw",ni.join(t,".openclaw")],["hermes",ni.join(t,".hermes")],["claude-code",ni.join(t,".claude")]];for(let[n,i]of r)if(Gs.existsSync(i))return{runtime:n,base:Ore(n,e)};return{runtime:"default",base:Ore("default",e)}}function WPe(e){let t=[ni.join(e,"skills",L0),ni.join(e,"..","skills",L0),ni.join(e,"..","..","visa-cli-openclaw","skills",L0),ni.join(e,"..","..","..","visa-cli-openclaw","skills",L0)];for(let r of t)if(Gs.existsSync(ni.join(r,"SKILL.md")))return r;return null}function B3t(e){let{bundledDir:t,base:r,force:n}=e;if(!Gs.existsSync(ni.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t} (no SKILL.md)`);let i=ni.join(r,L0),o=Gs.existsSync(i)&&Gs.readdirSync(i).length>0;if(o&&!n)throw new Error(`${i} already exists \u2014 re-run with --force to overwrite, or --print to view the skill.`);return Gs.mkdirSync(r,{recursive:!0}),o&&Gs.rmSync(i,{recursive:!0,force:!0}),Gs.cpSync(t,i,{recursive:!0}),{installedDir:i,files:j3t(i),overwrote:o}}function j3t(e){let t=[],r=(n,i)=>{for(let o of Gs.readdirSync(n,{withFileTypes:!0})){let s=i?ni.join(i,o.name):o.name;o.isDirectory()?r(ni.join(n,o.name),s):t.push(s)}};return r(e,""),t.sort()}function JPe(e){return Gs.readFileSync(ni.join(e,"SKILL.md"),"utf8")}function M3t(e){let{runtime:t}=e;if(!U3t.includes(t))return{runtime:t,status:"skipped",path:null,note:t==="claude-code"||t==="claude"?"Claude Code mounts MCP servers via its own config \u2014 run `visa-cli connect claude` to have the CLI write it.":"no known MCP config for this target \u2014 the skill can drive the raw `visa` CLI instead."};let r=mI(t),n=e.home?ni.join(e.home,ni.relative(YU.homedir(),r.globalConfigPath)):r.globalConfigPath,i=KPe(r,n,JU());return i.status==="error"?{runtime:t,status:"error",path:i.configPath,note:i.error}:{runtime:t,status:i.status,path:i.configPath}}function YPe(e){let t,r;if(e.dir)t=ni.resolve(e.dir),r="custom";else if(e.runtime){let o=Ore(e.runtime,e);if(!o)throw new Error(`unknown runtime "${e.runtime}" \u2014 use openclaw | hermes | claude-code | default, or pass --dir.`);t=o,r=e.runtime}else{let o=N3t(e);t=o.base,r=o.runtime}let n=B3t({bundledDir:e.bundledDir,base:t,force:e.force}),i=e.mount===!1?{runtime:r,status:"skipped",path:null,note:"mount disabled with --no-mount"}:M3t({runtime:r,home:e.home});return{skill:L0,runtime:r,installedDir:n.installedDir,files:n.files,overwrote:n.overwrote,mount:i}}var Gs,YU,ni,L0,U3t,ZPe=k(()=>{"use strict";Gs=_e(require("fs")),YU=_e(require("os")),ni=_e(require("path"));Cre();L0="pair-visa-agent";U3t=["openclaw","hermes"]});function q3t(e,t={}){let r=t.execPath??process.execPath,n=t.cliEntry??process.argv[1],i=String(t.intervalSec??5),o=String(t.timeoutSec??840),s=["agent","enroll-claim",...e?["--url",e]:[],"--interval",i,"--timeout",o,"--format","json"];return n?{cmd:r,args:[n,...s]}:{cmd:"visa",args:s}}async function QPe(e,t=XPe.spawn){try{let{cmd:r,args:n}=q3t(e),i=t(r,n,{detached:!0,stdio:"ignore"});return typeof i.once!="function"?i.pid===void 0?{started:!1,error:"background process did not report a pid"}:(i.unref(),{started:!0,pid:i.pid}):await new Promise(o=>{let s=!1,a=c=>{s||(s=!0,o(c))};i.once?.("error",c=>{a({started:!1,error:c.message||"background process failed to start"})}),i.once?.("spawn",()=>{if(i.pid===void 0){a({started:!1,error:"background process did not report a pid"});return}i.unref(),a({started:!0,pid:i.pid})})})}catch(r){return{started:!1,error:r instanceof Error?r.message:"background process failed to start"}}}var XPe,eCe=k(()=>{"use strict";XPe=require("node:child_process")});function iCe(e=process.env){return e[L3t]==="true"}function G3t(e){return typeof e=="string"&&dU.includes(e)}function c6(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function QU(e){return typeof e=="string"&&z3t.test(e)}function Nre(e){return typeof e=="string"&&H3t.test(e)}function ZU(e){return typeof e=="string"&&$3t.test(e)}function eM(e){return typeof e=="string"&&yy.includes(e)}function sCe(e){return e===null||typeof e=="string"&&e.length>0&&e.length<=V3t&&!K3t.test(e)}function Y3t(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function Z3t(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function aCe(e){if(e.length===0||e.length>F3t)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&Z3t(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function X3t(e){if(typeof e!="string")return!1;try{return aCe(e)===e}catch{return!1}}function cCe(e){return c6(e)&&e.protocolVersion===jt&&QU(e.attachId)&&Nre(e.agentId)&&X3t(e.authUrl)&&G3t(e.capability)&&eM(e.rail)&&oCe[e.capability]===e.rail&&e.currency==="USD"&&ZU(e.aggregateCeilingMicros)&&ZU(e.perTransactionMicros)&&sCe(e.instrumentLabel)&&Er(e.serverNonce)&&Er(e.identityKeyJkt)&&Er(e.claimToken)&&Y3t(e.createdAt)}function Bre(e,t=hI){if(!QU(e))throw new Error("attach id must use the canonical ca_ + 24 base64url form");return Rre.join(t,`${e}.json`)}function Q3t(e){Oy.mkdirSync(e,{recursive:!0,mode:448});let t=Oy.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("capability-attach directory must be a real directory, not a symlink");Oy.chmodSync(e,448),lc(e)}function eEt(e,t=hI){if(!cCe(e))throw new Error("refusing to write an invalid capability-attach ceremony record");Q3t(t),D0(Bre(e.attachId,t),JSON.stringify(e,null,2))}function jre(e,t=hI){if(!QU(e))return null;let r=a6(Bre(e,t));if(r===null)return null;let n;try{n=JSON.parse(r)}catch{throw new Error(`local capability-attach state for ${e} contains invalid JSON`)}if(!cCe(n)||n.attachId!==e)throw new Error(`local capability-attach state for ${e} is invalid or misbound`);return n}function tCe(e,t=hI){jre(e,t)&&lc(t)&&Oy.rmSync(Bre(e,t),{force:!0})}function XU(e,t="capability-attach operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function kre(e,t){return t?t.aborted?Promise.reject(XU(t)):new Promise((r,n)=>{let i=()=>n(XU(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function Ure(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("capability-attach operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`capability-attach request timed out after ${rCe}ms`)),rCe);s.unref?.();try{if(i.signal.aborted)throw XU(i.signal);let a=await kre(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":D3t,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await kre(a.json(),i.signal)}catch{if(i.signal.aborted)throw XU(i.signal);c={}}if(!a.ok&&a.status!==202){let u=c6(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`capability-attach server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}function uCe(e,t){return Buffer.from(gy(e,Buffer.from(t,"utf8"))).toString("base64url")}function dCe(e,t,r){let n=g8(e,r);if(!n||!zl(n))throw new Error(`no paired identity for agent ${e} on this machine \u2014 run \`visa agent pair\` first`);if(n.identity_key.jkt!==t||hf(n.identity_key.public_jwk)!==t)throw new Error("the paired agent key rotated since this ceremony was created; start over");return{seed:Buffer.from(n.identity_key.private_jwk.d,"base64url"),publicJwk:n.identity_key.public_jwk,jkt:n.identity_key.jkt}}async function lCe(e){let t=e.attachDir??hI,r=e.capability,n=g8(e.agentId,e.agentDir);if(!n||!zl(n))throw new Error(`no paired identity for agent ${e.agentId} on this machine \u2014 run \`visa agent pair\` first`);let i=aCe(e.authUrl??n.auth_url??Ta());if(!Number.isSafeInteger(e.aggregateCeilingCents)||e.aggregateCeilingCents<=0||!Number.isSafeInteger(e.perPurchaseCents)||e.perPurchaseCents<=0||e.perPurchaseCents>e.aggregateCeilingCents)throw new Error("ceiling and per-transaction caps must be positive, with per-transaction \u2264 ceiling");let o=await e.createCall(e.agentId,{protocolVersion:jt,capability:r,aggregateCeilingCents:e.aggregateCeilingCents,perPurchaseCents:e.perPurchaseCents});if(!c6(o)||o.protocolVersion!==jt||!QU(o.attachId)||o.agentId!==e.agentId||o.state!=="attach_initiated"||o.capability!==r||!eM(o.rail)||o.rail!==oCe[r]||o.currency!=="USD"||!ZU(o.aggregateCeilingMicros)||!ZU(o.perTransactionMicros)||!sCe(o.instrumentLabel??null)||!Er(o.serverNonce))throw new Error("capability-attach server returned an invalid create response");let s={protocolVersion:jt,attachId:o.attachId,agentId:e.agentId,authUrl:i,capability:r,rail:o.rail,currency:"USD",aggregateCeilingMicros:o.aggregateCeilingMicros,perTransactionMicros:o.perTransactionMicros,instrumentLabel:o.instrumentLabel??null,serverNonce:o.serverNonce,identityKeyJkt:n.identity_key.jkt,claimToken:fU(),createdAt:new Date().toISOString()};return eEt(s,t),s}function tEt(e,t,r){let n=uCe(r,zIe({protocolVersion:jt,attachId:e.attachId,agentId:e.agentId,capability:e.capability,serverNonce:e.serverNonce,claimTokenHash:k0(e.claimToken),identityKeyJkt:e.identityKeyJkt}));return{protocolVersion:jt,agentId:e.agentId,identityPublicJwk:t,signature:n,claimToken:e.claimToken}}async function pCe(e){let{pending:t}=e,r=e.fetchImpl??fetch,n=dCe(t.agentId,t.identityKeyJkt,e.agentDir),{body:i}=await Ure(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(tEt(t,n.publicJwk,n.seed))},r,{signal:e.signal});if(!c6(i)||i.protocolVersion!==jt||i.attachId!==t.attachId||i.agentId!==t.agentId||i.state!=="attach_claimed"||i.capabilityToken!==t.claimToken)throw new Error("capability-attach server returned an invalid claim response");return t}function rEt(e,t){if(!c6(e)||e.protocolVersion!==jt||e.attachId!==t.attachId||e.agentId!==t.agentId||!eM(e.rail)||e.rail!==t.rail||e.identityKeyJkt!==t.identityKeyJkt||e.claimTokenHash!==k0(t.claimToken)||!Nre(e.ownerPublicId)||!Er(e.grantHash)||!Er(e.ceremonyHash)||!Er(e.deliveryArtifactHash))throw new Error("capability-attach server returned an invalid activation-delivery artifact");let r={protocolVersion:jt,attachId:t.attachId,agentId:t.agentId,ownerPublicId:e.ownerPublicId,identityKeyJkt:t.identityKeyJkt,claimTokenHash:k0(t.claimToken),grantHash:e.grantHash,ceremonyHash:e.ceremonyHash,deliveryArtifactHash:e.deliveryArtifactHash,rail:t.rail};return Ste(r),r}async function nEt(e,t,r,n){let{status:i,body:o}=await Ure(`${e.authUrl}/v4/agents/${encodeURIComponent(e.agentId)}/capability-attach/${encodeURIComponent(e.attachId)}/delivery`,{method:"GET",cache:"no-store",headers:{"x-agent-capability-token":e.claimToken}},t,{signal:r});if(!c6(o)||o.attachId!==e.attachId||o.agentId!==e.agentId)throw new Error("capability-attach server returned an invalid delivery response");let s=typeof o.state=="string"?o.state:"";if(!W3t.has(s))throw new Error("capability-attach server returned an invalid delivery response");if(n?.(s),J3t.has(s))throw new Error(`capability-attach ceremony ended in state ${s}`);if(i===202||s!=="human_authorized"&&s!=="grant_activated")return null;let a=rEt(o.artifact,e);if(o.deliveryArtifactHash!==a.deliveryArtifactHash)throw new Error("capability-attach delivery hash does not match its artifact");return a}async function iEt(e){let{pending:t}=e,r=e.fetchImpl??fetch,n;try{n=await nEt(t,r,e.signal,e.onState)}catch(a){throw a instanceof Error&&/ceremony ended in state (failed|expired)/.test(a.message)&&tCe(t.attachId,e.attachDir),a}if(!n)return null;let i=dCe(t.agentId,t.identityKeyJkt,e.agentDir),o=uCe(i.seed,Ste(n)),{body:s}=await Ure(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","x-agent-capability-token":t.claimToken},body:JSON.stringify({protocolVersion:jt,agentId:t.agentId,signature:o})},r,{signal:e.signal});if(!c6(s)||s.protocolVersion!==jt||s.attachId!==t.attachId||s.agentId!==t.agentId||s.state!=="grant_activated"||!eM(s.rail)||s.rail!==t.rail||!Nre(s.grantId)||!Number.isSafeInteger(s.grantVersion)||typeof s.replay!="boolean")throw new Error("capability-attach server returned an invalid activation response");return tCe(t.attachId,e.attachDir),{attachId:t.attachId,agentId:t.agentId,rail:t.rail,aggregateCeilingMicros:t.aggregateCeilingMicros,perTransactionMicros:t.perTransactionMicros,grantId:s.grantId,grantVersion:s.grantVersion,replay:s.replay}}async function Mre(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await iEt({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await kre(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization of the spending grant")}var Oy,nCe,Rre,D3t,hI,L3t,z3t,H3t,$3t,F3t,V3t,K3t,oCe,W3t,J3t,rCe,fCe=k(()=>{"use strict";Oy=_e(require("node:fs")),nCe=_e(require("node:os")),Rre=_e(require("node:path"));W_();ly();rI();lI();u6();D3t="4.1.0-rc.58",hI=Rre.join(nCe.homedir(),".visa-cli","capability-attach"),L3t="VISA_V4_CAPABILITY_ATTACH_ENABLED";z3t=/^ca_[A-Za-z0-9_-]{24}$/,H3t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,$3t=/^(0|[1-9][0-9]{0,17})$/,F3t=2048,V3t=255,K3t=/[\p{Cc}\p{Cf}\u2028\u2029]/u,oCe={card:"card:vic",wallet:"wallet:x402"};W3t=new Set(["attach_initiated","attach_claimed","human_authorized","grant_activated","failed","expired"]),J3t=new Set(["failed","expired"]);rCe=3e4});var CCe={};Oi(CCe,{agentFilePath:()=>_8,agentFormatIsJson:()=>d6,attachAgentCommand:()=>Gre,attachPollOptsFromFlags:()=>zre,claimOptsFromFlags:()=>b8,decodeBindingClaims:()=>w8,enrollClaimEnvelope:()=>SCe,formatUsdMicros:()=>gI,isAgentCommandEnabled:()=>xCe,isAgentRecord:()=>Fre,isAgentRecordV2:()=>zl,isStoredAgentRecord:()=>Vre,listAgentFiles:()=>iM,listLegacyAgentRecords:()=>aM,loginClaimEnvelope:()=>TCe,loginClaimOptsFromFlags:()=>PCe,newestAgentRecord:()=>sM,newestAgentRecordV2:()=>v8,parseUsdToCents:()=>Lre,readAgent:()=>g8,renderGrantActivated:()=>Hre,writeAgent:()=>Kre});function Fre(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.registration_jwt=="string"&&typeof t.wallet_public_key=="string"&&typeof t.pairing_id=="string"&&(t.pairing_status==="activated"||t.pairing_status==="revoked")&&t.artifacts!==null&&typeof t.artifacts=="object"&&!Array.isArray(t.artifacts)&&typeof t.auth_url=="string"&&typeof t.created_at=="string"}function sEt(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function aEt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function cEt(e){if(typeof e!="string"||e.length===0||e.length>2048)return!1;try{let t=new URL(e);if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&aEt(t.hostname)))return!1;let r=t.pathname.replace(/\/+$/,""),n=`${t.origin}${r===""||r==="/"?"":r}`;return e===n}catch{return!1}}function uEt(e){return typeof e=="string"&&e.length>0&&e.length<=255&&!oEt.test(e)&&e===e.normalize("NFC").trim().replace(/ {2,}/g," ")}function dEt(e,t){try{let r=G_(Buffer.from(e.d,"base64url"));return r.d===e.d&&r.x===t.x}catch{return!1}}function mCe(e){if(e.length===0||e.length>Dre)return null;let t=e.split(".");if(t.length!==3||t.some(r=>!/^[A-Za-z0-9_-]+$/.test(r)))return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function hCe(e){return Number.isSafeInteger(e.iat)&&Number.isSafeInteger(e.exp)&&e.iat>=0&&e.exp>e.iat}function lEt(e){let t=mCe(e.activation_credentials.binding_jwt),r=mCe(e.activation_credentials.registration_jwt);return!t||!r||!hCe(t)||!hCe(r)?!1:t.v===jt&&t.sub===e.agent_id&&t.owner_public_id===e.owner_public_id&&t.name===e.display_name&&t.jkt===e.identity_key.jkt&&t.mesh==="visa"&&t.mode==="identity_only"&&t.card_verified===!1&&r.sub===e.identity_key.jkt&&r.name===e.display_name&&r.pol==="visa-agent-identity-only-v2"&&!!r.cnf&&typeof r.cnf=="object"&&!Array.isArray(r.cnf)&&r.cnf.jkt===e.identity_key.jkt}function ACe(e){return typeof e=="string"&&(l6.test(e)||Er(e))}function yI(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function zl(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(!yI(e,["v","agent_id","owner_public_id","display_name","identity_key","pairing_id","pairing_status","activation_credentials","delivery_artifact","auth_url","created_at"])||t.v!==jt||typeof t.agent_id!="string"||!l6.test(t.agent_id)||typeof t.owner_public_id!="string"||!l6.test(t.owner_public_id)||!uEt(t.display_name)||!t.identity_key||!yI(t.identity_key,["jkt","public_jwk","private_jwk","custody"])||t.identity_key.custody!=="runtime"||!yI(t.identity_key.public_jwk??{},["kty","crv","x"])||!yI(t.identity_key.private_jwk??{},["kty","crv","x","d"])||!Er(t.identity_key.jkt)||t.identity_key.public_jwk?.kty!=="OKP"||t.identity_key.public_jwk.crv!=="Ed25519"||!Er(t.identity_key.public_jwk.x)||t.identity_key.private_jwk?.kty!=="OKP"||t.identity_key.private_jwk.crv!=="Ed25519"||!Er(t.identity_key.private_jwk.x)||!Er(t.identity_key.private_jwk.d)||t.identity_key.public_jwk.x!==t.identity_key.private_jwk.x||!dEt(t.identity_key.private_jwk,t.identity_key.public_jwk)||typeof t.pairing_id!="string"||t.pairing_status!=="activated"||!t.activation_credentials||!yI(t.activation_credentials,["binding_jwt","registration_jwt"])||typeof t.activation_credentials.binding_jwt!="string"||t.activation_credentials.binding_jwt.length===0||t.activation_credentials.binding_jwt.length>Dre||typeof t.activation_credentials.registration_jwt!="string"||t.activation_credentials.registration_jwt.length===0||t.activation_credentials.registration_jwt.length>Dre||!t.delivery_artifact||!cEt(t.auth_url)||!sEt(t.created_at)||!lEt(t))return!1;try{let r=JSON.parse(XT(t.delivery_artifact));return r.agentId===t.agent_id&&r.pairingId===t.pairing_id&&r.ownerPublicId===t.owner_public_id&&r.terms.displayName===t.display_name&&r.identityKey.jkt===t.identity_key.jkt&&r.identityKey.publicJwk.x===t.identity_key.public_jwk.x}catch{return!1}}function Vre(e){return zl(e)||Fre(e)}function xCe(){return!0}function d6(e){return e==="json"}function SCe(e){switch(e.status){case"activated":return{json:{status:"activated",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,displayName:e.displayName,identityKeyJkt:e.identityKeyJkt},exitCode:0};case"not_ready":return{json:{status:"not_ready",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,likelyExpired:e.likelyExpired,error:e.likelyExpired?"the pairing authorization window has expired":"not ready yet \u2014 finish the human authorization in the browser"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no agent pairing in progress"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function TCe(e){switch(e.status){case"claimed":return{json:{status:"claimed",sessionSaved:!0},exitCode:0};case"not_ready":return{json:{status:"not_ready",likelyExpired:e.likelyExpired,error:e.likelyExpired?"the 15-minute v4 sign-in window has likely expired":"not ready yet \u2014 finish browser sign-in and terminal-code confirmation"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no v4 sign-in handoff is in progress"},exitCode:1};case"confirm_mismatch":return{json:{status:"confirm_mismatch",confirmCode:e.confirmCode,error:"this v4 sign-in handoff did not match this terminal"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function b8(e){let t=e.interval&&e.interval>0?e.interval:3,r=e.attempts&&e.attempts>0?e.attempts:5;return e.timeout&&e.timeout>0&&(r=Math.max(1,Math.ceil(e.timeout/t))),{attempts:r,delayMs:t*1e3}}function Lre(e){let t=e.trim().replace(/^\$/,"");if(!/^\d{1,15}(\.\d{1,2})?$/.test(t))throw new Error(`invalid USD amount "${e}" \u2014 use dollars like 25 or 25.50`);let[r,n=""]=t.split("."),i=Number(r)*100+Number(n.padEnd(2,"0"));if(!Number.isSafeInteger(i)||i<=0)throw new Error(`invalid USD amount "${e}" \u2014 must be greater than zero`);return i}function gI(e){let t=Number(e);return Number.isFinite(t)?`$${(t/1e6).toFixed(2)}`:`${e} micros`}function zre(e){if(!(e.attempts!==void 0&&e.attempts>0||e.interval!==void 0&&e.interval>0||e.timeout!==void 0&&e.timeout>0))return{maxPolls:450,pollIntervalMs:2e3};let r=b8({...e,interval:e.interval&&e.interval>0?e.interval:2});return{maxPolls:r.attempts,pollIntervalMs:r.delayMs}}function Hre(e){return`\u2713 Spending authority active for agent ${e.agentId} \u2014 ${gI(e.aggregateCeilingMicros)} ceiling.
48
+ `),{removed:!0,configPath:r})}function Pre(e,t="global"){let r=t==="project"?Nt.join(process.cwd(),".mcp.json"):vre(e);if(!Yt.existsSync(r))return!1;let n=Are(e,t);if(n==="toml")try{let i=Yt.readFileSync(r,"utf-8");return!!Sre(i,"visa-cli")}catch{return!1}if(n==="yaml")try{let i=Yt.readFileSync(r,"utf-8");return!!Ire(i,"visa-cli")}catch{return!1}try{let i=JSON.parse(Yt.readFileSync(r,"utf-8"));return!!Ere(i,e.configKey)?.["visa-cli"]}catch{return!1}}var Yt,Nt,jPe,In,A3t,_re,WU,$Pe,Cre=k(()=>{"use strict";Yt=_e(require("fs")),Nt=_e(require("path")),jPe=_e(require("os")),In=jPe.homedir(),A3t=["Claude_","Anthropic.ClaudeDesktop_"],_re=class extends Error{constructor(r,n,i){super(S3t(r,n,i));this.client=r;this.configPath=n;this.name="McpConfigAccessError"}client;configPath};WU=[{id:"claude",displayName:"Claude Code",globalConfigPath:Nt.join(In,".claude.json"),configKey:"mcpServers",detectPaths:[Nt.join(In,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:qPe(),configKey:"mcpServers",detectPaths:DPe(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:Nt.join(In,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[Nt.join(In,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:Nt.join(In,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[Nt.join(In,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:Nt.join(In,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[Nt.join(In,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:gre({win32:Nt.join(fI(),"Roo","mcp_settings.json"),posix:Nt.join(In,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[Nt.join(In,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:Nt.join(In,".vscode","mcp.json"),configKey:"servers",detectPaths:[Nt.join(In,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:gre({win32:Nt.join(fI(),"Zed","settings.json"),posix:Nt.join(In,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:gre({win32:[Nt.join(fI(),"Zed")],posix:[Nt.join(In,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:Nt.join(In,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[Nt.join(In,".codex")],postInstallHint:"Restart Codex to connect."},{id:"openclaw",displayName:"OpenClaw",globalConfigPath:Nt.join(In,".openclaw","openclaw.json"),configKey:"mcp.servers",detectPaths:[Nt.join(In,".openclaw")],postInstallHint:"Restart OpenClaw (or reload its config) to connect."},{id:"hermes",displayName:"Hermes",globalConfigPath:Nt.join(In,".hermes","config.yaml"),configKey:"mcp_servers",configFormat:"yaml",detectPaths:[Nt.join(In,".hermes")],postInstallHint:"Restart Hermes to connect."}];$Pe="mcp_servers"});function Ore(e,t={}){let r=t.home??YU.homedir(),n=t.cwd??process.cwd();switch(e){case"openclaw":return ni.join(r,".openclaw","skills");case"hermes":return ni.join(r,".hermes","skills");case"claude-code":case"claude":return ni.join(r,".claude","skills");case"default":case"agentskills":return ni.join(n,".agents","skills");default:return null}}function N3t(e={}){let t=e.home??YU.homedir(),r=[["openclaw",ni.join(t,".openclaw")],["hermes",ni.join(t,".hermes")],["claude-code",ni.join(t,".claude")]];for(let[n,i]of r)if(Gs.existsSync(i))return{runtime:n,base:Ore(n,e)};return{runtime:"default",base:Ore("default",e)}}function WPe(e){let t=[ni.join(e,"skills",L0),ni.join(e,"..","skills",L0),ni.join(e,"..","..","visa-cli-openclaw","skills",L0),ni.join(e,"..","..","..","visa-cli-openclaw","skills",L0)];for(let r of t)if(Gs.existsSync(ni.join(r,"SKILL.md")))return r;return null}function B3t(e){let{bundledDir:t,base:r,force:n}=e;if(!Gs.existsSync(ni.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t} (no SKILL.md)`);let i=ni.join(r,L0),o=Gs.existsSync(i)&&Gs.readdirSync(i).length>0;if(o&&!n)throw new Error(`${i} already exists \u2014 re-run with --force to overwrite, or --print to view the skill.`);return Gs.mkdirSync(r,{recursive:!0}),o&&Gs.rmSync(i,{recursive:!0,force:!0}),Gs.cpSync(t,i,{recursive:!0}),{installedDir:i,files:j3t(i),overwrote:o}}function j3t(e){let t=[],r=(n,i)=>{for(let o of Gs.readdirSync(n,{withFileTypes:!0})){let s=i?ni.join(i,o.name):o.name;o.isDirectory()?r(ni.join(n,o.name),s):t.push(s)}};return r(e,""),t.sort()}function JPe(e){return Gs.readFileSync(ni.join(e,"SKILL.md"),"utf8")}function M3t(e){let{runtime:t}=e;if(!U3t.includes(t))return{runtime:t,status:"skipped",path:null,note:t==="claude-code"||t==="claude"?"Claude Code mounts MCP servers via its own config \u2014 run `visa-cli connect claude` to have the CLI write it.":"no known MCP config for this target \u2014 the skill can drive the raw `visa` CLI instead."};let r=mI(t),n=e.home?ni.join(e.home,ni.relative(YU.homedir(),r.globalConfigPath)):r.globalConfigPath,i=KPe(r,n,JU());return i.status==="error"?{runtime:t,status:"error",path:i.configPath,note:i.error}:{runtime:t,status:i.status,path:i.configPath}}function YPe(e){let t,r;if(e.dir)t=ni.resolve(e.dir),r="custom";else if(e.runtime){let o=Ore(e.runtime,e);if(!o)throw new Error(`unknown runtime "${e.runtime}" \u2014 use openclaw | hermes | claude-code | default, or pass --dir.`);t=o,r=e.runtime}else{let o=N3t(e);t=o.base,r=o.runtime}let n=B3t({bundledDir:e.bundledDir,base:t,force:e.force}),i=e.mount===!1?{runtime:r,status:"skipped",path:null,note:"mount disabled with --no-mount"}:M3t({runtime:r,home:e.home});return{skill:L0,runtime:r,installedDir:n.installedDir,files:n.files,overwrote:n.overwrote,mount:i}}var Gs,YU,ni,L0,U3t,ZPe=k(()=>{"use strict";Gs=_e(require("fs")),YU=_e(require("os")),ni=_e(require("path"));Cre();L0="pair-visa-agent";U3t=["openclaw","hermes"]});function q3t(e,t={}){let r=t.execPath??process.execPath,n=t.cliEntry??process.argv[1],i=String(t.intervalSec??5),o=String(t.timeoutSec??840),s=["agent","enroll-claim",...e?["--url",e]:[],"--interval",i,"--timeout",o,"--format","json"];return n?{cmd:r,args:[n,...s]}:{cmd:"visa",args:s}}async function QPe(e,t=XPe.spawn){try{let{cmd:r,args:n}=q3t(e),i=t(r,n,{detached:!0,stdio:"ignore"});return typeof i.once!="function"?i.pid===void 0?{started:!1,error:"background process did not report a pid"}:(i.unref(),{started:!0,pid:i.pid}):await new Promise(o=>{let s=!1,a=c=>{s||(s=!0,o(c))};i.once?.("error",c=>{a({started:!1,error:c.message||"background process failed to start"})}),i.once?.("spawn",()=>{if(i.pid===void 0){a({started:!1,error:"background process did not report a pid"});return}i.unref(),a({started:!0,pid:i.pid})})})}catch(r){return{started:!1,error:r instanceof Error?r.message:"background process failed to start"}}}var XPe,eCe=k(()=>{"use strict";XPe=require("node:child_process")});function iCe(e=process.env){return e[L3t]==="true"}function G3t(e){return typeof e=="string"&&dU.includes(e)}function c6(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function QU(e){return typeof e=="string"&&z3t.test(e)}function Nre(e){return typeof e=="string"&&H3t.test(e)}function ZU(e){return typeof e=="string"&&$3t.test(e)}function eM(e){return typeof e=="string"&&yy.includes(e)}function sCe(e){return e===null||typeof e=="string"&&e.length>0&&e.length<=V3t&&!K3t.test(e)}function Y3t(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function Z3t(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function aCe(e){if(e.length===0||e.length>F3t)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&Z3t(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function X3t(e){if(typeof e!="string")return!1;try{return aCe(e)===e}catch{return!1}}function cCe(e){return c6(e)&&e.protocolVersion===jt&&QU(e.attachId)&&Nre(e.agentId)&&X3t(e.authUrl)&&G3t(e.capability)&&eM(e.rail)&&oCe[e.capability]===e.rail&&e.currency==="USD"&&ZU(e.aggregateCeilingMicros)&&ZU(e.perTransactionMicros)&&sCe(e.instrumentLabel)&&Er(e.serverNonce)&&Er(e.identityKeyJkt)&&Er(e.claimToken)&&Y3t(e.createdAt)}function Bre(e,t=hI){if(!QU(e))throw new Error("attach id must use the canonical ca_ + 24 base64url form");return Rre.join(t,`${e}.json`)}function Q3t(e){Oy.mkdirSync(e,{recursive:!0,mode:448});let t=Oy.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("capability-attach directory must be a real directory, not a symlink");Oy.chmodSync(e,448),lc(e)}function eEt(e,t=hI){if(!cCe(e))throw new Error("refusing to write an invalid capability-attach ceremony record");Q3t(t),D0(Bre(e.attachId,t),JSON.stringify(e,null,2))}function jre(e,t=hI){if(!QU(e))return null;let r=a6(Bre(e,t));if(r===null)return null;let n;try{n=JSON.parse(r)}catch{throw new Error(`local capability-attach state for ${e} contains invalid JSON`)}if(!cCe(n)||n.attachId!==e)throw new Error(`local capability-attach state for ${e} is invalid or misbound`);return n}function tCe(e,t=hI){jre(e,t)&&lc(t)&&Oy.rmSync(Bre(e,t),{force:!0})}function XU(e,t="capability-attach operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function kre(e,t){return t?t.aborted?Promise.reject(XU(t)):new Promise((r,n)=>{let i=()=>n(XU(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function Ure(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("capability-attach operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`capability-attach request timed out after ${rCe}ms`)),rCe);s.unref?.();try{if(i.signal.aborted)throw XU(i.signal);let a=await kre(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":D3t,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await kre(a.json(),i.signal)}catch{if(i.signal.aborted)throw XU(i.signal);c={}}if(!a.ok&&a.status!==202){let u=c6(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`capability-attach server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}function uCe(e,t){return Buffer.from(gy(e,Buffer.from(t,"utf8"))).toString("base64url")}function dCe(e,t,r){let n=g8(e,r);if(!n||!zl(n))throw new Error(`no paired identity for agent ${e} on this machine \u2014 run \`visa agent pair\` first`);if(n.identity_key.jkt!==t||hf(n.identity_key.public_jwk)!==t)throw new Error("the paired agent key rotated since this ceremony was created; start over");return{seed:Buffer.from(n.identity_key.private_jwk.d,"base64url"),publicJwk:n.identity_key.public_jwk,jkt:n.identity_key.jkt}}async function lCe(e){let t=e.attachDir??hI,r=e.capability,n=g8(e.agentId,e.agentDir);if(!n||!zl(n))throw new Error(`no paired identity for agent ${e.agentId} on this machine \u2014 run \`visa agent pair\` first`);let i=aCe(e.authUrl??n.auth_url??Ta());if(!Number.isSafeInteger(e.aggregateCeilingCents)||e.aggregateCeilingCents<=0||!Number.isSafeInteger(e.perPurchaseCents)||e.perPurchaseCents<=0||e.perPurchaseCents>e.aggregateCeilingCents)throw new Error("ceiling and per-transaction caps must be positive, with per-transaction \u2264 ceiling");let o=await e.createCall(e.agentId,{protocolVersion:jt,capability:r,aggregateCeilingCents:e.aggregateCeilingCents,perPurchaseCents:e.perPurchaseCents});if(!c6(o)||o.protocolVersion!==jt||!QU(o.attachId)||o.agentId!==e.agentId||o.state!=="attach_initiated"||o.capability!==r||!eM(o.rail)||o.rail!==oCe[r]||o.currency!=="USD"||!ZU(o.aggregateCeilingMicros)||!ZU(o.perTransactionMicros)||!sCe(o.instrumentLabel??null)||!Er(o.serverNonce))throw new Error("capability-attach server returned an invalid create response");let s={protocolVersion:jt,attachId:o.attachId,agentId:e.agentId,authUrl:i,capability:r,rail:o.rail,currency:"USD",aggregateCeilingMicros:o.aggregateCeilingMicros,perTransactionMicros:o.perTransactionMicros,instrumentLabel:o.instrumentLabel??null,serverNonce:o.serverNonce,identityKeyJkt:n.identity_key.jkt,claimToken:fU(),createdAt:new Date().toISOString()};return eEt(s,t),s}function tEt(e,t,r){let n=uCe(r,zIe({protocolVersion:jt,attachId:e.attachId,agentId:e.agentId,capability:e.capability,serverNonce:e.serverNonce,claimTokenHash:k0(e.claimToken),identityKeyJkt:e.identityKeyJkt}));return{protocolVersion:jt,agentId:e.agentId,identityPublicJwk:t,signature:n,claimToken:e.claimToken}}async function pCe(e){let{pending:t}=e,r=e.fetchImpl??fetch,n=dCe(t.agentId,t.identityKeyJkt,e.agentDir),{body:i}=await Ure(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(tEt(t,n.publicJwk,n.seed))},r,{signal:e.signal});if(!c6(i)||i.protocolVersion!==jt||i.attachId!==t.attachId||i.agentId!==t.agentId||i.state!=="attach_claimed"||i.capabilityToken!==t.claimToken)throw new Error("capability-attach server returned an invalid claim response");return t}function rEt(e,t){if(!c6(e)||e.protocolVersion!==jt||e.attachId!==t.attachId||e.agentId!==t.agentId||!eM(e.rail)||e.rail!==t.rail||e.identityKeyJkt!==t.identityKeyJkt||e.claimTokenHash!==k0(t.claimToken)||!Nre(e.ownerPublicId)||!Er(e.grantHash)||!Er(e.ceremonyHash)||!Er(e.deliveryArtifactHash))throw new Error("capability-attach server returned an invalid activation-delivery artifact");let r={protocolVersion:jt,attachId:t.attachId,agentId:t.agentId,ownerPublicId:e.ownerPublicId,identityKeyJkt:t.identityKeyJkt,claimTokenHash:k0(t.claimToken),grantHash:e.grantHash,ceremonyHash:e.ceremonyHash,deliveryArtifactHash:e.deliveryArtifactHash,rail:t.rail};return Ste(r),r}async function nEt(e,t,r,n){let{status:i,body:o}=await Ure(`${e.authUrl}/v4/agents/${encodeURIComponent(e.agentId)}/capability-attach/${encodeURIComponent(e.attachId)}/delivery`,{method:"GET",cache:"no-store",headers:{"x-agent-capability-token":e.claimToken}},t,{signal:r});if(!c6(o)||o.attachId!==e.attachId||o.agentId!==e.agentId)throw new Error("capability-attach server returned an invalid delivery response");let s=typeof o.state=="string"?o.state:"";if(!W3t.has(s))throw new Error("capability-attach server returned an invalid delivery response");if(n?.(s),J3t.has(s))throw new Error(`capability-attach ceremony ended in state ${s}`);if(i===202||s!=="human_authorized"&&s!=="grant_activated")return null;let a=rEt(o.artifact,e);if(o.deliveryArtifactHash!==a.deliveryArtifactHash)throw new Error("capability-attach delivery hash does not match its artifact");return a}async function iEt(e){let{pending:t}=e,r=e.fetchImpl??fetch,n;try{n=await nEt(t,r,e.signal,e.onState)}catch(a){throw a instanceof Error&&/ceremony ended in state (failed|expired)/.test(a.message)&&tCe(t.attachId,e.attachDir),a}if(!n)return null;let i=dCe(t.agentId,t.identityKeyJkt,e.agentDir),o=uCe(i.seed,Ste(n)),{body:s}=await Ure(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","x-agent-capability-token":t.claimToken},body:JSON.stringify({protocolVersion:jt,agentId:t.agentId,signature:o})},r,{signal:e.signal});if(!c6(s)||s.protocolVersion!==jt||s.attachId!==t.attachId||s.agentId!==t.agentId||s.state!=="grant_activated"||!eM(s.rail)||s.rail!==t.rail||!Nre(s.grantId)||!Number.isSafeInteger(s.grantVersion)||typeof s.replay!="boolean")throw new Error("capability-attach server returned an invalid activation response");return tCe(t.attachId,e.attachDir),{attachId:t.attachId,agentId:t.agentId,rail:t.rail,aggregateCeilingMicros:t.aggregateCeilingMicros,perTransactionMicros:t.perTransactionMicros,grantId:s.grantId,grantVersion:s.grantVersion,replay:s.replay}}async function Mre(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await iEt({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await kre(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization of the spending grant")}var Oy,nCe,Rre,D3t,hI,L3t,z3t,H3t,$3t,F3t,V3t,K3t,oCe,W3t,J3t,rCe,fCe=k(()=>{"use strict";Oy=_e(require("node:fs")),nCe=_e(require("node:os")),Rre=_e(require("node:path"));W_();ly();rI();lI();u6();D3t="4.1.0-rc.59",hI=Rre.join(nCe.homedir(),".visa-cli","capability-attach"),L3t="VISA_V4_CAPABILITY_ATTACH_ENABLED";z3t=/^ca_[A-Za-z0-9_-]{24}$/,H3t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,$3t=/^(0|[1-9][0-9]{0,17})$/,F3t=2048,V3t=255,K3t=/[\p{Cc}\p{Cf}\u2028\u2029]/u,oCe={card:"card:vic",wallet:"wallet:x402"};W3t=new Set(["attach_initiated","attach_claimed","human_authorized","grant_activated","failed","expired"]),J3t=new Set(["failed","expired"]);rCe=3e4});var CCe={};Oi(CCe,{agentFilePath:()=>_8,agentFormatIsJson:()=>d6,attachAgentCommand:()=>Gre,attachPollOptsFromFlags:()=>zre,claimOptsFromFlags:()=>b8,decodeBindingClaims:()=>w8,enrollClaimEnvelope:()=>SCe,formatUsdMicros:()=>gI,isAgentCommandEnabled:()=>xCe,isAgentRecord:()=>Fre,isAgentRecordV2:()=>zl,isStoredAgentRecord:()=>Vre,listAgentFiles:()=>iM,listLegacyAgentRecords:()=>aM,loginClaimEnvelope:()=>TCe,loginClaimOptsFromFlags:()=>PCe,newestAgentRecord:()=>sM,newestAgentRecordV2:()=>v8,parseUsdToCents:()=>Lre,readAgent:()=>g8,renderGrantActivated:()=>Hre,writeAgent:()=>Kre});function Fre(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.registration_jwt=="string"&&typeof t.wallet_public_key=="string"&&typeof t.pairing_id=="string"&&(t.pairing_status==="activated"||t.pairing_status==="revoked")&&t.artifacts!==null&&typeof t.artifacts=="object"&&!Array.isArray(t.artifacts)&&typeof t.auth_url=="string"&&typeof t.created_at=="string"}function sEt(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function aEt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function cEt(e){if(typeof e!="string"||e.length===0||e.length>2048)return!1;try{let t=new URL(e);if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&aEt(t.hostname)))return!1;let r=t.pathname.replace(/\/+$/,""),n=`${t.origin}${r===""||r==="/"?"":r}`;return e===n}catch{return!1}}function uEt(e){return typeof e=="string"&&e.length>0&&e.length<=255&&!oEt.test(e)&&e===e.normalize("NFC").trim().replace(/ {2,}/g," ")}function dEt(e,t){try{let r=G_(Buffer.from(e.d,"base64url"));return r.d===e.d&&r.x===t.x}catch{return!1}}function mCe(e){if(e.length===0||e.length>Dre)return null;let t=e.split(".");if(t.length!==3||t.some(r=>!/^[A-Za-z0-9_-]+$/.test(r)))return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function hCe(e){return Number.isSafeInteger(e.iat)&&Number.isSafeInteger(e.exp)&&e.iat>=0&&e.exp>e.iat}function lEt(e){let t=mCe(e.activation_credentials.binding_jwt),r=mCe(e.activation_credentials.registration_jwt);return!t||!r||!hCe(t)||!hCe(r)?!1:t.v===jt&&t.sub===e.agent_id&&t.owner_public_id===e.owner_public_id&&t.name===e.display_name&&t.jkt===e.identity_key.jkt&&t.mesh==="visa"&&t.mode==="identity_only"&&t.card_verified===!1&&r.sub===e.identity_key.jkt&&r.name===e.display_name&&r.pol==="visa-agent-identity-only-v2"&&!!r.cnf&&typeof r.cnf=="object"&&!Array.isArray(r.cnf)&&r.cnf.jkt===e.identity_key.jkt}function ACe(e){return typeof e=="string"&&(l6.test(e)||Er(e))}function yI(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function zl(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(!yI(e,["v","agent_id","owner_public_id","display_name","identity_key","pairing_id","pairing_status","activation_credentials","delivery_artifact","auth_url","created_at"])||t.v!==jt||typeof t.agent_id!="string"||!l6.test(t.agent_id)||typeof t.owner_public_id!="string"||!l6.test(t.owner_public_id)||!uEt(t.display_name)||!t.identity_key||!yI(t.identity_key,["jkt","public_jwk","private_jwk","custody"])||t.identity_key.custody!=="runtime"||!yI(t.identity_key.public_jwk??{},["kty","crv","x"])||!yI(t.identity_key.private_jwk??{},["kty","crv","x","d"])||!Er(t.identity_key.jkt)||t.identity_key.public_jwk?.kty!=="OKP"||t.identity_key.public_jwk.crv!=="Ed25519"||!Er(t.identity_key.public_jwk.x)||t.identity_key.private_jwk?.kty!=="OKP"||t.identity_key.private_jwk.crv!=="Ed25519"||!Er(t.identity_key.private_jwk.x)||!Er(t.identity_key.private_jwk.d)||t.identity_key.public_jwk.x!==t.identity_key.private_jwk.x||!dEt(t.identity_key.private_jwk,t.identity_key.public_jwk)||typeof t.pairing_id!="string"||t.pairing_status!=="activated"||!t.activation_credentials||!yI(t.activation_credentials,["binding_jwt","registration_jwt"])||typeof t.activation_credentials.binding_jwt!="string"||t.activation_credentials.binding_jwt.length===0||t.activation_credentials.binding_jwt.length>Dre||typeof t.activation_credentials.registration_jwt!="string"||t.activation_credentials.registration_jwt.length===0||t.activation_credentials.registration_jwt.length>Dre||!t.delivery_artifact||!cEt(t.auth_url)||!sEt(t.created_at)||!lEt(t))return!1;try{let r=JSON.parse(XT(t.delivery_artifact));return r.agentId===t.agent_id&&r.pairingId===t.pairing_id&&r.ownerPublicId===t.owner_public_id&&r.terms.displayName===t.display_name&&r.identityKey.jkt===t.identity_key.jkt&&r.identityKey.publicJwk.x===t.identity_key.public_jwk.x}catch{return!1}}function Vre(e){return zl(e)||Fre(e)}function xCe(){return!0}function d6(e){return e==="json"}function SCe(e){switch(e.status){case"activated":return{json:{status:"activated",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,displayName:e.displayName,identityKeyJkt:e.identityKeyJkt},exitCode:0};case"not_ready":return{json:{status:"not_ready",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,likelyExpired:e.likelyExpired,error:e.likelyExpired?"the pairing authorization window has expired":"not ready yet \u2014 finish the human authorization in the browser"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no agent pairing in progress"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function TCe(e){switch(e.status){case"claimed":return{json:{status:"claimed",sessionSaved:!0},exitCode:0};case"not_ready":return{json:{status:"not_ready",likelyExpired:e.likelyExpired,error:e.likelyExpired?"the 15-minute v4 sign-in window has likely expired":"not ready yet \u2014 finish browser sign-in and terminal-code confirmation"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no v4 sign-in handoff is in progress"},exitCode:1};case"confirm_mismatch":return{json:{status:"confirm_mismatch",confirmCode:e.confirmCode,error:"this v4 sign-in handoff did not match this terminal"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function b8(e){let t=e.interval&&e.interval>0?e.interval:3,r=e.attempts&&e.attempts>0?e.attempts:5;return e.timeout&&e.timeout>0&&(r=Math.max(1,Math.ceil(e.timeout/t))),{attempts:r,delayMs:t*1e3}}function Lre(e){let t=e.trim().replace(/^\$/,"");if(!/^\d{1,15}(\.\d{1,2})?$/.test(t))throw new Error(`invalid USD amount "${e}" \u2014 use dollars like 25 or 25.50`);let[r,n=""]=t.split("."),i=Number(r)*100+Number(n.padEnd(2,"0"));if(!Number.isSafeInteger(i)||i<=0)throw new Error(`invalid USD amount "${e}" \u2014 must be greater than zero`);return i}function gI(e){let t=Number(e);return Number.isFinite(t)?`$${(t/1e6).toFixed(2)}`:`${e} micros`}function zre(e){if(!(e.attempts!==void 0&&e.attempts>0||e.interval!==void 0&&e.interval>0||e.timeout!==void 0&&e.timeout>0))return{maxPolls:450,pollIntervalMs:2e3};let r=b8({...e,interval:e.interval&&e.interval>0?e.interval:2});return{maxPolls:r.attempts,pollIntervalMs:r.delayMs}}function Hre(e){return`\u2713 Spending authority active for agent ${e.agentId} \u2014 ${gI(e.aggregateCeilingMicros)} ceiling.
49
49
  Rail: ${e.rail}
50
50
  Per transaction: ${gI(e.perTransactionMicros)}
51
51
  Grant: ${e.grantId} (v${e.grantVersion})
@@ -193,7 +193,7 @@ Full request-key fingerprint to compare exactly: ${i.identityKeyJkt}
193
193
  `:`Agent not found: ${n}
194
194
  `),process.exitCode=1;return}if(zl(i)){let s=w8(i.activation_credentials.binding_jwt);process.stdout.write([`agent id: ${i.agent_id}`,`name: ${i.display_name}`,`owner id: ${i.owner_public_id}`,`key fingerprint: ${i.identity_key.jkt} (Ed25519, runtime custody)`,`created: ${i.created_at}`,`auth server: ${i.auth_url}`,`pairing: ${i.pairing_id}`,`status: ${i.pairing_status}`,`key file: ${_8(i.agent_id)}`,"key custody: exportable owner-only runtime file (mode 0600; macOS/Linux)","key recovery: unavailable; copying transfers identity proof and loss blocks new proofs","binding claims (decoded locally, NOT verified):",s?JSON.stringify(s,null,2):" (stored binding is malformed)",""].join(`
195
195
  `));return}let o=i.binding_jwt?w8(i.binding_jwt):null;process.stdout.write(["record: legacy v1 (key-addressed; no stable agent id)",`key jkt: ${i.agent_jkt}`,`name: ${i.name}`,`created: ${i.created_at}`,`auth server: ${i.auth_url}`,`pairing: ${i.pairing_id}`,`status: ${i.pairing_status}`,`public key: ${i.public_key_jwk.x} (Ed25519, OKP)`,"registration: stored",`key file: ${_8(i.agent_jkt)}`,"binding claims (decoded locally, NOT verified):",o?JSON.stringify(o,null,2):" (no binding stored or malformed JWT)",""].join(`
196
- `))})}var vf,$re,z0,qre,Ry,Ny,l6,Dre,oEt,u6=k(()=>{"use strict";vf=_e(require("fs")),$re=_e(require("os")),z0=_e(require("path")),qre=require("node:readline/promises");W_();Ry=_e(ure());Tj();Wj();lI();VU();NPe();ZPe();eCe();dM();fCe();e8();x0();Ny=z0.join($re.homedir(),".visa-cli","agents");l6=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Dre=32768,oEt=/[\p{Cc}\p{Cf}\u2028\u2029]/u});var tne={};Oi(tne,{SUBWAY_PROTOCOL:()=>LCe,registerDirect:()=>NEt,resolveDirect:()=>BEt});function Zre(e,t){let r=typeof t=="bigint"?t:BigInt(t);for(;r>0x7fn;)e.push(Number(r&0x7fn|0x80n)),r>>=7n;e.push(Number(r))}function vd(e,t){let r=0n,n=0n,i=t;for(;;){let o=e[i++];if(r|=BigInt(o&127)<<n,(o&128)===0)break;n+=7n}return[r,i]}function Xre(e,t){return e<<3|t}function EI(e,t,r){e.push(Xre(t,2)),Zre(e,r.length);for(let n of r)e.push(n)}function wEt(e,t){let r=[];return EI(r,1,Yre.encode(e)),t&&t.length>0&&EI(r,2,Yre.encode(t)),Uint8Array.from(r)}function EEt(e,t,r){let n=[];return r!==0n&&(n.push(Xre(1,0)),Zre(n,r)),EI(n,2,wEt(e,t)),Uint8Array.from(n)}function AEt(e){let t=[];return EI(t,1,Yre.encode(e)),Uint8Array.from(t)}function xEt(e,t){let r=[];return t!==0n&&(r.push(Xre(1,0)),Zre(r,t)),EI(r,3,AEt(e)),Uint8Array.from(r)}function SEt(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=vd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=vd(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=vd(e,t),u=c,d=u+Number(a);r.error=qCe.decode(e.subarray(u,d)),t=d}else t=Qre(e,t,s)}return r}function TEt(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=vd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=vd(e,t),u=c,d=u+Number(a);r.peerId=e.subarray(u,d),t=d}else if(o===2&&s===2){let[a,c]=vd(e,t),u=c,d=u+Number(a);r.error=qCe.decode(e.subarray(u,d)),t=d}else t=Qre(e,t,s)}return r}function Qre(e,t,r){if(r===0)return vd(e,t)[1];if(r===2){let[n,i]=vd(e,t);return i+Number(n)}if(r===5)return t+4;if(r===1)return t+8;throw new Error(`unsupported wire type ${r}`)}function DCe(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=vd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=vd(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=vd(e,t),u=c,d=u+Number(a);r.registerNameResponse=SEt(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=vd(e,t),u=c,d=u+Number(a);r.resolveNameResponse=TEt(e.subarray(u,d)),t=d}else t=Qre(e,t,s)}return r}function IEt(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function ene(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function PEt(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=ene(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:DCe(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function CEt(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=ene(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:DCe(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Jre(e){let t=e.reduce((i,o)=>i+o.length,0),r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}async function REt(e){let t=[],r=0,n=-1;for await(let i of e){let o=i instanceof Uint8Array?i:i.subarray();if(t.push(o),r+=o.length,r>OCe)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+ene(Jre(t).subarray(0,4)),n>OCe))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return Jre(t).subarray(0,n)}return Jre(t)}async function zCe(e){return(0,kCe.createLibp2p)({...e?{privateKey:await(0,jCe.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,RCe.tcp)()],connectionEncrypters:[(0,NCe.noise)()],streamMuxers:[(0,BCe.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function HCe(e,t,r){let n=await e.dialProtocol((0,UCe.multiaddr)(t),LCe,{signal:AbortSignal.timeout(OEt)});n.send(IEt(r));let i;return Promise.race([REt(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),kEt)})]).finally(()=>clearTimeout(i))}async function NEt(e){let t=await zCe(e.seed);try{let r=await HCe(t,e.relayMultiaddr,EEt(e.name,e.binding,e.requestId??1n)),n=PEt(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function BEt(e){let t=await zCe(e.seed);try{let r=await HCe(t,e.relayMultiaddr,xEt(e.name,e.requestId??1n)),n=CEt(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,MCe.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var kCe,RCe,NCe,BCe,jCe,UCe,MCe,Yre,qCe,LCe,OEt,kEt,OCe,rne=k(()=>{"use strict";Pte();kCe=require("libp2p"),RCe=require("@libp2p/tcp"),NCe=require("@chainsafe/libp2p-noise"),BCe=require("@chainsafe/libp2p-yamux"),jCe=require("@libp2p/crypto/keys"),UCe=require("@multiformats/multiaddr"),MCe=require("uint8arrays/to-string"),Yre=new TextEncoder,qCe=new TextDecoder;LCe="/subway/p2p/1.0.0",OEt=15e3,kEt=15e3,OCe=1<<20});var TI={};Oi(TI,{DEFAULT_VISA_RELAY_MULTIADDR:()=>$Ce,MESH:()=>ki,RELAY_URL:()=>xI,connectOrThrow:()=>x8,ensureMailbox:()=>yne,hydrateInbox:()=>YCe,isSubwayEnabled:()=>ane,listRegistered:()=>fne,loadBindingFor:()=>dne,loadRegistry:()=>f6,makeClient:()=>A8,meshName:()=>wf,pairedVisaBinding:()=>GCe,pairedVisaBindingForIdentity:()=>WCe,persistInbox:()=>hne,readInbox:()=>DEt,registerName:()=>SI,resolveActingName:()=>fM,resolveMeshName:()=>lne,seedSubwayKeyFromExactIdentity:()=>KCe,seedSubwayKeyFromTapAgent:()=>VCe,sendMessage:()=>pne,sendVia:()=>LEt,subwayKeyPath:()=>une,visaRelayMultiaddr:()=>sne});function sne(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??$Ce}function wf(e){return e.includes(".")?e:`${e}.${ki}`}function ane(e){if(process.env.VISA_DEV==="1")return!0;let t=e??"0.0.0";return t==="0.0.0"||t.startsWith("0.0.")?!0:/-rc\.|-beta\./.test(t)}function cne(){Ws.mkdirSync(E8,{recursive:!0,mode:448})}function FCe(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function une(e){return AI.join(E8,`${FCe(e)}.key`)}function f6(){if(!Ws.existsSync(one))return{};try{return JSON.parse(Ws.readFileSync(one,"utf8"))}catch{return{}}}function nne(e){cne(),Ws.writeFileSync(one,JSON.stringify(e,null,2),{mode:384})}function ine(){try{return pM.userInfo().username}catch{return"local"}}function VCe(e){if(Ws.existsSync(e))return null;let t=sM();if(!t)return null;try{let r=a8(t.private_key_jwk);return cne(),Ws.writeFileSync(e,Buffer.from(r),{mode:384}),t.agent_jkt}catch{return null}}function KCe(e,t){let r=a8(t.identityPrivateJwk);if(hf(by(K_(r)))!==t.identityKeyJkt)throw new mf("The selected agent identity key does not match its stable record. Refusing .visa registration.");if(Ws.existsSync(e)){if(hf(by(K_(tI(e))))!==t.identityKeyJkt)throw new mf("The existing Subway key belongs to a different agent. Refusing to replace it implicitly.");return t.stableAgentId}return cne(),Ws.writeFileSync(e,Buffer.from(r),{mode:384}),t.stableAgentId}function A8(e,t={}){return new oPe({name:wf(e),url:xI,keyPath:une(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function dne(e){if(ki!=="visa")return;let t=f6()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function x8(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${xI})`)),t))])}function fM(e){if(e)return e;let t=Object.keys(f6());if(t.length===1)return t[0];throw t.length===0?new Error("No Subway names registered yet. Run `visa register <name>` first."):new Error(`Multiple names registered (${t.join(", ")}). Pass --as <name>.`)}function GCe(e,t=Date.now()){let r=sM();if(!r?.binding_jwt)return null;let n=w8(r.binding_jwt);if(!n||n.mesh!=="visa"||n.name!==e||n.jkt!==r.agent_jkt)return null;let i=typeof n.exp=="number"?n.exp:NaN;return!Number.isFinite(i)||i*1e3<=t?null:{binding:r.binding_jwt,bindingExpiresAt:new Date(i*1e3).toISOString(),identityKeyJkt:r.agent_jkt}}function WCe(e,t,r=Date.now()){for(let n of aM()){if(n.agent_jkt!==t)continue;let i=w8(n.binding_jwt);if(!i||i.mesh!=="visa"||i.name!==e||i.jkt!==t)continue;let o=typeof i.exp=="number"?i.exp:NaN;if(!(!Number.isFinite(o)||o*1e3<=r))return{binding:n.binding_jwt,bindingExpiresAt:new Date(o*1e3).toISOString(),identityKeyJkt:t}}return null}async function SI(e,t={}){let r=une(e),n=wf(e),i,o;if(t.exactIdentity){if(o=ki==="visa"?WCe(n,t.exactIdentity.identityKeyJkt):null,ki==="visa"&&!o)throw new mf;i=KCe(r,t.exactIdentity)}else i=VCe(r),o=ki==="visa"?GCe(n):null;let s,a={};if(o){if(!Ws.existsSync(r))throw new mf("A stored .visa binding exists, but its runtime-held identity key is unavailable. A new identity pairing cannot recreate this separate channel binding.");if(hf(by(K_(tI(r))))!==o.identityKeyJkt)throw new mf("The stored .visa binding does not match this Subway identity key. Refusing to present a mismatched legacy admission artifact.");s=o.binding,a={binding:o.binding,bindingExpiresAt:o.bindingExpiresAt}}else if(ki==="visa")throw new mf;let c=ki==="visa"?sne():process.env.SUBWAY_RELAY_MULTIADDR;if(ki==="visa"&&c){let{registerDirect:d}=await Promise.resolve().then(()=>(rne(),tne)),l=await d({relayMultiaddr:c,seed:tI(r),name:n,binding:s});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let p=f6();return p[e]={relayName:n,mesh:ki,peerId:l.peerId,owner:ine(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},nne(p),{relayName:n,mesh:ki,peerId:l.peerId,tapAgentId:i,...s?{binding:s}:{}}}if(ki==="visa"&&!process.env.SUBWAY_RELAY){let d=f6();return d[e]={relayName:n,mesh:ki,peerId:null,owner:ine(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},nne(d),{relayName:n,mesh:ki,peerId:null,tapAgentId:i,...s?{binding:s}:{},note:s?"Visa binding ready; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa directory/TAP admission binding is stored. Identity pairing does not issue one; use a separately approved directory capability when available."}}let u=A8(e,{autoReconnect:!1,binding:s});try{await x8(u);let d=f6();return d[e]={relayName:n,mesh:ki,peerId:u.peerId,owner:ine(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},nne(d),{relayName:n,mesh:ki,peerId:u.peerId,tapAgentId:i,...s?{binding:s}:{}}}finally{u.disconnect()}}async function lne(e){let t=wf(e),r=ki==="visa"?sne():process.env.SUBWAY_RELAY_MULTIADDR;if(ki==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(rne(),tne)),i=await n({relayMultiaddr:r,name:t});return{relayName:t,found:i.found,peerId:i.peerId,error:i.error}}throw new Error("subway find needs the .visa mesh with a dedicated relay \u2014 set SUBWAY_MESH=visa and SUBWAY_RELAY_MULTIADDR.")}async function pne(e,t,r){let n=A8(e,{autoReconnect:!1,binding:dne(e)});try{await x8(n);let i=wf(t);return await n.sendSigned(i,"chat",r),{to:i,as:wf(e)}}finally{n.disconnect()}}function fne(){let e=f6();return Object.entries(e).map(([t,r])=>({name:t,...r}))}function JCe(e,t=E8){return AI.join(t,`${FCe(e)}.inbox.json`)}function UEt(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.from=="string"&&typeof t.text=="string"&&typeof t.ts=="number"&&typeof t.verified=="boolean"}function YCe(e,t=E8){try{let r=JSON.parse(Ws.readFileSync(JCe(e,t),"utf8"));return Array.isArray(r)?r.filter(UEt).slice(-mne):[]}catch{return[]}}function hne(e,t,r=E8){try{Ws.mkdirSync(r,{recursive:!0,mode:448}),Ws.writeFileSync(JCe(e,r),JSON.stringify(t.slice(-mne),null,2),{mode:384})}catch{}}function MEt(e,t){if(t.dirty=!0,t.flushTimer)return;let r=setTimeout(()=>{t.flushTimer=null,t.dirty&&(t.dirty=!1,hne(e,t.buffer))},jEt);typeof r.unref=="function"&&r.unref(),t.flushTimer=r}function qEt(e,t){t.flushTimer&&(clearTimeout(t.flushTimer),t.flushTimer=null),t.dirty=!1,hne(e,t.buffer)}async function yne(e){let t=lM.get(e);if(t)return{relayName:wf(e),peerId:t.client.peerId};let r=A8(e,{autoReconnect:!0,binding:dne(e)}),n=YCe(e),i={client:r,buffer:n,flushTimer:null,dirty:!1};return r.onMessage(o=>{n.push({from:o.fromName,text:o.payload,ts:o.timestampMs,verified:!!o.verified}),n.length>mne&&n.shift(),MEt(e,i)}),lM.set(e,i),await x8(r),{relayName:wf(e),peerId:r.peerId}}async function DEt(e,t=20,r=!1){await yne(e);let n=lM.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0,qEt(e,n)),i}async function LEt(e,t,r){await yne(e);let n=lM.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=wf(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:wf(e)}}var Ws,pM,AI,ki,$Ce,xI,E8,one,lM,mne,jEt,m6=k(()=>{"use strict";Zte();W_();Ws=_e(require("fs")),pM=_e(require("os")),AI=_e(require("path"));rI();u6();ki=process.env.SUBWAY_MESH??"relay",$Ce="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";xI=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";E8=AI.join(pM.homedir(),".visa-cli","subway"),one=AI.join(E8,"registry.json");lM=new Map,mne=200,jEt=100});var pOe={};Oi(pOe,{PAIRING_DIR:()=>Af,cancelPairing:()=>Wre,claimPairing:()=>p6,getPairingStatus:()=>uM,initiatePairing:()=>wI,latestPendingHumanPairing:()=>rM,latestPendingRuntimePairing:()=>vM,pairingFilePath:()=>_M,pollAndActivatePairing:()=>nM,readPendingPairing:()=>_d,registerOnVisaMeshIfEnabled:()=>cM,removePendingPairing:()=>vI,tryActivatePairing:()=>Sne,verifyPairing:()=>ky,writePendingPairing:()=>xne});async function cM(e){if(process.env.SUBWAY_MESH!=="visa")return!1;try{return await SI(e),!0}catch(t){return ke.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)}),!1}}function pc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ef(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function _ne(e){return typeof e=="string"&&$Et.test(e)}function S8(e){return typeof e=="string"&&FEt.test(e)}function II(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function nOe(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function hM(e){if(typeof e!="string"||e.length===0||e.length>rOe)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&nOe(t.hostname))&&t.username.length===0&&t.password.length===0}catch{return!1}}function bM(e){if(e.length===0||e.length>rOe)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&nOe(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function vne(e){if(typeof e!="string")return!1;try{return bM(e)===e}catch{return!1}}function GEt(e){return pc(e)&&Ef(e,["kty","crv","x"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Er(e.x)}function WEt(e){return pc(e)&&Ef(e,["kty","crv","x","d"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Er(e.x)&&Er(e.d)}function JEt(e,t){try{let r=G_(Buffer.from(e.d,"base64url"));return r.x===t.x&&r.d===e.d}catch{return!1}}function mM(e,t){if(typeof e!="string"||VEt.test(e))return null;let r=e.normalize("NFC").trim();return r.length>0&&r.length<=t?r:null}function iOe(e){if(!pc(e)||!Ef(e,["runtime","contextLabel","cliVersion","platform"]))return null;let t=mM(e.runtime,100),r=mM(e.contextLabel,200),n=e.cliVersion===void 0?void 0:mM(e.cliVersion,64),i=e.platform===void 0?void 0:mM(e.platform,100);return!t||!r||e.cliVersion!==void 0&&!n||e.platform!==void 0&&!i?null:{runtime:t,contextLabel:r,...n?{cliVersion:n}:{},...i?{platform:i}:{}}}function YEt(e){if(!pc(e))return!1;let t=iOe(e);return t?t.runtime===e.runtime&&t.contextLabel===e.contextLabel&&t.cliVersion===e.cliVersion&&t.platform===e.platform:!1}function oOe(e){return pc(e)?Ef(e,["role","protocolVersion","pairingId","agentId","verifier","authUrl","skillUrl","expiresAt","createdAt"])&&e.role==="human"&&e.protocolVersion===jt&&S8(e.pairingId)&&_ne(e.agentId)&&Er(e.verifier)&&vne(e.authUrl)&&hM(e.skillUrl)&&II(e.expiresAt)&&II(e.createdAt):!1}function sOe(e){return!pc(e)||!Ef(e,["role","protocolVersion","pairingId","agentId","authUrl","claimToken","serverNonce","identityKeyJkt","identityPublicJwk","identityPrivateJwk","runtime","createdAt"])||e.role!=="runtime"||e.protocolVersion!==jt||!S8(e.pairingId)||!_ne(e.agentId)||!vne(e.authUrl)||!Er(e.claimToken)||!Er(e.serverNonce)||!Er(e.identityKeyJkt)||!GEt(e.identityPublicJwk)||!WEt(e.identityPrivateJwk)||!YEt(e.runtime)||!II(e.createdAt)?!1:e.identityPublicJwk.x===e.identityPrivateJwk.x&&hf(e.identityPublicJwk)===e.identityKeyJkt&&JEt(e.identityPrivateJwk,e.identityPublicJwk)}function ZEt(e){return pc(e)&&Ef(e,["protocolVersion","verifier","authUrl","createdAt"])&&e.protocolVersion===jt&&Er(e.verifier)&&vne(e.authUrl)&&II(e.createdAt)}function PI(e,t,r){if(!pc(e)||e.protocolVersion!==jt||!S8(e.pairingId)||!_ne(e.agentId)||typeof e.state!="string"||!KEt.has(e.state)||!II(e.expiresAt)||e.skillUrl!==void 0&&!hM(e.skillUrl)||e.authorizationUrl!==void 0&&!hM(e.authorizationUrl)||e.serverNonce!==void 0&&!Er(e.serverNonce)||e.authApiUrl!==void 0&&!hM(e.authApiUrl)||e.failureCode!==void 0&&typeof e.failureCode!="string"||t!==void 0&&e.pairingId!==t||r!==void 0&&e.agentId!==r)throw new Error("pairing server returned an invalid v2 status response")}function _M(e,t,r=Af){if(!S8(e))throw new Error("pairing id must use the canonical ap_ + 24 base64url form");return gM.join(r,`${e}.${t}.json`)}function aOe(e){Hl.mkdirSync(e,{recursive:!0,mode:448});let t=Hl.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("pairing directory must be a real directory, not a symlink");Hl.chmodSync(e,448),lc(e)}function wne(e){return gM.join(e,zEt)}function Ene(e){let t=a6(wne(e));if(t===null)return null;let r;try{r=JSON.parse(t)}catch{throw new Error("local pairing initiation state contains invalid JSON")}if(!ZEt(r))throw new Error("local pairing initiation state is invalid");return r}function XEt(e,t){aOe(t),D0(wne(t),JSON.stringify(e,null,2))}function ZCe(e,t){let r=Ene(t);if(!r)return;let n=_d(e,"human",t);n&&n.verifier===r.verifier&&n.authUrl===r.authUrl&&Ane(t)}function Ane(e){Ene(e)&&lc(e)&&Hl.rmSync(wne(e),{force:!0})}function xne(e,t=Af){if(!(e.role==="human"?oOe(e):sOe(e)))throw new Error("refusing to write invalid protocol-v2 pending pairing state");aOe(t);let n=_M(e.pairingId,e.role,t);D0(n,JSON.stringify(e,null,2))}function vI(e,t,r=Af){_d(e,t,r)&&lc(r)&&Hl.rmSync(_M(e,t,r),{force:!0})}function gne(e,t=Af){vI(e,"human",t),vI(e,"runtime",t),Ane(t)}function _d(e,t,r=Af){if(!S8(e))return null;let n=a6(_M(e,t,r));if(n===null)return null;let i;try{i=JSON.parse(n)}catch{throw new Error(`local ${t} pairing state for ${e} contains invalid JSON`)}if(t==="human"){if(!oOe(i)||i.pairingId!==e)throw new Error(`local human pairing state for ${e} is invalid or misbound`);return i}if(!sOe(i)||i.pairingId!==e)throw new Error(`local runtime pairing state for ${e} is invalid or misbound`);return i}function cOe(e,t){return lc(t)?Hl.readdirSync(t).filter(n=>n.endsWith(`.${e}.json`)).map(n=>{let i=n.slice(0,-`.${e}.json`.length);if(!S8(i))throw new Error(`local ${e} pairing filename ${n} is invalid`);return _d(i,e,t)}).filter(n=>n!==null).sort((n,i)=>i.createdAt.localeCompare(n.createdAt))[0]??null:null}function rM(e=Af){return cOe("human",e)}function vM(e=Af){return cOe("runtime",e)}function yM(e,t="pairing operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function bne(e,t){return t?t.aborted?Promise.reject(yM(t)):new Promise((r,n)=>{let i=()=>n(yM(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function h6(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("pairing operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`pairing request timed out after ${XCe}ms`)),XCe);s.unref?.();try{if(i.signal.aborted)throw yM(i.signal);let a=await bne(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":tOe,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await bne(a.json(),i.signal)}catch{if(i.signal.aborted)throw yM(i.signal);c={}}if(!a.ok&&a.status!==202){let u=pc(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`pairing server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}async function wI(e={}){let t=bM(e.authUrl??Ta()),r=e.pairingDir??Af,n=Ene(r),i=n?Date.parse(n.createdAt):Number.NaN,o=n!==null&&Number.isFinite(i)&&Date.now()-i<HEt;if(o&&n.authUrl!==t)throw new Error("a pairing initiation is pending for a different auth origin; retry it first");let s=o?n:{protocolVersion:jt,verifier:MIe(),authUrl:t,createdAt:new Date().toISOString()};o||XEt(s,r);let a=s.verifier,{body:c}=await h6(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:jt,cliChallenge:qIe(a)})},e.fetchImpl??fetch,{signal:e.signal});if(PI(c),c.state!=="awaiting_agent"||!c.skillUrl)throw new Error("pairing server returned an incomplete v2 initiation response");let u={role:"human",protocolVersion:jt,pairingId:c.pairingId,agentId:c.agentId,verifier:a,authUrl:t,skillUrl:ete(c.skillUrl),expiresAt:c.expiresAt,createdAt:new Date().toISOString()};return xne(u,r),e.retainInitiationDraft||Ane(r),u}function uOe(e){return e.authorizationUrl?{...e,authorizationUrl:ete(e.authorizationUrl)}:e}async function ky(e){let{pairing:t}=e,{body:r}=await h6(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:jt,verifier:t.verifier,code:e.code})},e.fetchImpl??fetch,{signal:e.signal});return PI(r,t.pairingId,t.agentId),uOe(r)}async function uM(e){let t=bM(e.authUrl??Ta()),{body:r}=await h6(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch,{signal:e.signal});return PI(r,e.pairingId,e.expectedAgentId),uOe(r)}function dOe(e,t){return Buffer.from(gy(e,Buffer.from(t,"utf8"))).toString("base64url")}function QEt(e){let t=dOe(Buffer.from(e.identityPrivateJwk.d,"base64url"),xte({protocolVersion:jt,pairingId:e.pairingId,agentId:e.agentId,serverNonce:e.serverNonce,claimTokenHash:k0(e.claimToken),identityKeyJkt:e.identityKeyJkt,runtime:e.runtime}));return{protocolVersion:jt,agentId:e.agentId,identityPublicJwk:e.identityPublicJwk,runtime:e.runtime,signature:t,claimToken:e.claimToken}}async function QCe(e,t,r){let{body:n}=await h6(`${e.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(QEt(e))},t,{signal:r}),i=n;if(!pc(i)||!Ef(i,["protocolVersion","pairingId","agentId","state","verificationCode","claimToken"])||i.protocolVersion!==jt||i.pairingId!==e.pairingId||i.agentId!==e.agentId||typeof i.state!="string"||!["agent_claimed","code_verified","awaiting_human","authorized","delivered","activated"].includes(i.state)||i.claimToken!==e.claimToken||typeof i.verificationCode!="string"||i.verificationCode!==mU(e.pairingId,e.claimToken))throw new Error("pairing server returned an invalid v2 claim response");return{pending:e,verificationCode:i.verificationCode}}async function p6(e){let t=bM(e.authUrl??Ta()),r=e.fetchImpl??fetch,n=e.pairingDir??Af,i=iOe({runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:tOe});if(!i)throw new Error("runtime metadata must be canonical, bounded, non-empty text");let o=_d(e.pairingId,"runtime",n);if(o){if(o.authUrl!==t||o.runtime.runtime!==i.runtime||o.runtime.contextLabel!==i.contextLabel)throw new Error("this pairing already has a different pending runtime claim; resume it");return ZCe(o.pairingId,n),QCe(o,r,e.signal)}let s=await uM({pairingId:e.pairingId,authUrl:t,fetchImpl:r,signal:e.signal});if(s.state!=="awaiting_agent"||!Er(s.serverNonce))throw new Error(`pairing cannot be claimed from state ${s.state}`);let a=IIe(),c=G_(a.secretKey),u=by(a.publicKey),d=hf(u),l=i,p=fU();xte({protocolVersion:jt,pairingId:e.pairingId,agentId:s.agentId,serverNonce:s.serverNonce,claimTokenHash:k0(p),identityKeyJkt:d,runtime:l});let f={role:"runtime",protocolVersion:jt,pairingId:e.pairingId,agentId:s.agentId,authUrl:t,claimToken:p,serverNonce:s.serverNonce,identityKeyJkt:d,identityPublicJwk:u,identityPrivateJwk:c,runtime:l,createdAt:new Date().toISOString()};return xne(f,n),ZCe(f.pairingId,n),QCe(f,r,e.signal)}async function lOe(e){let t=e.fetchImpl??fetch,{body:r,status:n}=await h6(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/delivery`,{method:"GET",headers:{"X-Agent-Pairing-Token":e.pending.claimToken},cache:"no-store"},t,{signal:e.signal});if(n===202){if(PI(r,e.pending.pairingId,e.pending.agentId),e.onState?.(r.state),["expired","cancelled","failed","revoked"].includes(r.state))throw gne(e.pending.pairingId,e.pairingDir),new Error(`pairing ended in state ${r.state}`);return null}if(!pc(r)||!Ef(r,["protocolVersion","pairingId","agentId","state","artifact","deliveryArtifactHash"])||r.protocolVersion!==jt||r.pairingId!==e.pending.pairingId||r.agentId!==e.pending.agentId||r.state!=="delivered"&&r.state!=="activated"||!pc(r.artifact)||!Er(r.deliveryArtifactHash))throw new Error("pairing delivery omitted the canonical v2 identity artifact");e.onState?.(r.state);let i=XT(r.artifact),o=JSON.parse(i),s=$Ie(o);if(s!==r.deliveryArtifactHash||o.pairingId!==e.pending.pairingId||o.agentId!==e.pending.agentId||o.identityKey.jkt!==e.pending.identityKeyJkt||o.identityKey.publicJwk.x!==e.pending.identityPublicJwk.x)throw new Error("pairing v2 delivery artifact did not match this pending identity claim");let a=dOe(Buffer.from(e.pending.identityPrivateJwk.d,"base64url"),LIe({protocolVersion:jt,pairingId:e.pending.pairingId,agentId:e.pending.agentId,ownerPublicId:o.ownerPublicId,claimTokenHash:k0(e.pending.claimToken),identityKeyJkt:e.pending.identityKeyJkt,ceremonyHash:o.ceremonyHash,deliveryArtifactHash:s})),c=await h6(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Pairing-Token":e.pending.claimToken},body:JSON.stringify({protocolVersion:jt,agentId:e.pending.agentId,signature:a})},t,{signal:e.signal}),u=o.terms,d=c.body;if(!pc(d)||!Ef(d,["protocolVersion","state","pairingId","agentId","ownerPublicId","identityKeyJkt","displayName","credentials"])||d.protocolVersion!==jt||d.state!=="activated"||d.pairingId!==e.pending.pairingId||d.agentId!==e.pending.agentId||d.ownerPublicId!==o.ownerPublicId||d.identityKeyJkt!==e.pending.identityKeyJkt||d.displayName!==u.displayName||!pc(d.credentials)||!Ef(d.credentials,["bindingJwt","registrationJwt"])||typeof d.credentials.bindingJwt!="string"||d.credentials.bindingJwt.length===0||typeof d.credentials.registrationJwt!="string"||d.credentials.registrationJwt.length===0)throw new Error("pairing server returned an invalid v2 activation response");let l={v:jt,agent_id:e.pending.agentId,owner_public_id:o.ownerPublicId,display_name:c.body.displayName,identity_key:{jkt:e.pending.identityKeyJkt,public_jwk:e.pending.identityPublicJwk,private_jwk:e.pending.identityPrivateJwk,custody:"runtime"},pairing_id:e.pending.pairingId,pairing_status:"activated",activation_credentials:{binding_jwt:d.credentials.bindingJwt,registration_jwt:d.credentials.registrationJwt},delivery_artifact:o,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};(e.writeAgentRecord??Kre)(l,e.agentDir),gne(e.pending.pairingId,e.pairingDir);let p=await cM(l.display_name);return process.env.SUBWAY_MESH==="visa"&&ke.info("agent:fresh_activate_mesh",{name:l.display_name,meshRegistered:p}),{record:l,name:l.display_name,agentId:l.agent_id,identityKeyJkt:l.identity_key.jkt}}async function Sne(e){return lOe(e)}async function nM(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await lOe({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await bne(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization")}async function Wre(e){let{pairing:t}=e,{body:r}=await h6(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:jt,verifier:t.verifier})},e.fetchImpl??fetch,{signal:e.signal});return PI(r,t.pairingId,t.agentId),r.state==="cancelled"&&gne(t.pairingId,e.pairingDir),r}var Hl,eOe,gM,tOe,Af,zEt,HEt,$Et,FEt,VEt,KEt,rOe,XCe,dM=k(()=>{"use strict";Hl=_e(require("node:fs")),eOe=_e(require("node:os")),gM=_e(require("node:path"));W_();ly();Wj();yd();rI();m6();lI();u6();tOe="4.1.0-rc.58",Af=gM.join(eOe.homedir(),".visa-cli","pairings"),zEt=".initiation.v2.json",HEt=15*6e4,$Et=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,FEt=/^ap_[A-Za-z0-9_-]{24}$/,VEt=/[\p{Cc}\p{Cf}\u2028\u2029]/u,KEt=new Set(["awaiting_agent","agent_claimed","code_verified","awaiting_human","authorized","delivered","activated","expired","cancelled","failed","revoked"]),rOe=2048;XCe=3e4});function fOe(e){return e.reason instanceof Error?e.reason:new Error("agent pairing timed out")}function eAt(e,t){return t?t.aborted?Promise.reject(fOe(t)):new Promise((r,n)=>{let i=()=>n(fOe(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}function tAt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return t===e.length?e:e.slice(0,t)}function mOe(e,t){if(t!==void 0&&tAt(t)!==e)throw new Error("auth URL does not match the pending pairing; resume with the original origin")}function rAt(e){return{status:"activated",protocolVersion:jt,pairingId:e.record.pairing_id,agentId:e.agentId,displayName:e.name,identityKeyJkt:e.identityKeyJkt}}async function bI(e={}){let t=vM(e.pairingDir);if(t){mOe(t.authUrl,e.authUrl);let s=_d(t.pairingId,"human",e.pairingDir);if(!s||s.agentId!==t.agentId)throw new Error("a runtime pairing is already pending without its local human proof; resume or cancel it before starting another");let a=await p6({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}}),c=await ky({pairing:s,code:a.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!c.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:jt,pairingId:t.pairingId,agentId:t.agentId,requestKeyFingerprint:t.identityKeyJkt,authorizationUrl:c.authorizationUrl,expiresAt:s.expiresAt}}let r=await wI({authUrl:e.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{},retainInitiationDraft:!0}),{pending:n,verificationCode:i}=await p6({pairingId:r.pairingId,runtime:e.runtime??"visa-cli",contextLabel:e.contextLabel??"Pair this runtime",authUrl:r.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});if(n.agentId!==r.agentId)throw new Error("pairing claim returned a different stable agent id");let o=await ky({pairing:r,code:i,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!o.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:jt,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:n.identityKeyJkt,authorizationUrl:o.authorizationUrl,expiresAt:r.expiresAt}}function nAt(e,t){if(!e)return!1;let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&t>=r}async function _I(e={}){let t=vM(e.pairingDir);if(!t)return{status:"no_pending"};let r=_d(t.pairingId,"human",e.pairingDir);try{mOe(t.authUrl,e.authUrl);let n=Math.max(1,e.attempts??1),i=e.sleep??(o=>new Promise(s=>setTimeout(s,o)));for(let o=0;o<n;o+=1){let s="",a=await Sne({pending:t,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,agentDir:e.agentDir,...e.signal?{signal:e.signal}:{},onState:c=>{s=c}});if(a)return rAt(a);if(o===0&&["awaiting_agent","agent_claimed","code_verified"].includes(s)){if(!r)throw new Error("pending pairing is missing its local human verification proof");let c=await p6({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});await ky({pairing:r,code:c.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}})}o+1<n&&await eAt(i(e.delayMs??3e3),e.signal)}return{status:"not_ready",protocolVersion:jt,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:nAt(r,(e.now??Date.now)())}}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}async function BPe(e){if(typeof e!="string"||e.trim().length===0)return!1;try{return await pn.saveSessionToken(e),!0}catch{return!1}}var VU=k(()=>{"use strict";W_();x0();dM()});var One={};Oi(One,{CardDrawRefusedError:()=>y6,cardDrawIntentHash:()=>SOe,decimalUsdToCents:()=>Cne,fetchCardDrawVerdict:()=>gAt,loadCardMandateCapability:()=>yAt,registerCardMandate:()=>bAt});function lAt(e){if(e.kty!=="OKP")throw new Error(`computeJkt expects an OKP JWK; got kty="${e.kty}"`);let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return(0,Pne.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function pAt(e){let{secretKey:t,publicKey:r}=PIe(e),n=G_(t),i=by(r);return{privateJwk:n,publicJwk:i,jkt:lAt(i)}}async function AOe(e,t){let n={cnf:{jwk:{kty:e.publicJwk.kty,crv:e.publicJwk.crv,x:e.publicJwk.x}},nonce:t.nonce,aud:t.audience,iat:t.nowSec};t.intentHash!==void 0&&(n.int=t.intentHash);let i={alg:"EdDSA",kid:e.jkt,typ:dAt},o=`${wOe(i)}.${wOe(n)}`,s=a8(e.privateJwk),a=gy(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function xOe(e){let{amount:t,currency:r,payee:n,intentId:i}=e;if(!Number.isSafeInteger(t)||t<=0)throw new Error(`intent.amount must be a positive safe integer in minor units (cents); got ${String(t)}`);let o=typeof r=="string"?r.toUpperCase():"";if(!fAt.has(o))throw new Error(`intent.currency must be a supported ISO 4217 code; got ${JSON.stringify(r)}`);if(typeof n!="string"||n.length===0)throw new Error("intent.payee must be a non-empty string");if(i!==void 0&&(typeof i!="string"||i.length===0))throw new Error("intent.intentId, when present, must be a non-empty string");let s=JSON.stringify({v:mAt,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,Pne.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function hAt(e){let t=e.split(".");if(t.length!==3)return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return typeof r.mode=="string"?r.mode:null}catch{return null}}function Cne(e){let t=/^([0-9]+)(?:\.([0-9]{1,2}))?$/.exec(e);if(!t)return null;let r=Number(t[1]),n=Number(((t[2]??"")+"00").slice(0,2)),i=r*100+n;return Number.isSafeInteger(i)?i:null}function SOe(e,t){let r=Cne(e.amount);return r===null?null:xOe({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function yAt(e={}){let r=(e.record!==void 0?e.record?[e.record]:[]:e.records??(u6(),ie(CCe)).listLegacyAgentRecords()).flatMap(i=>{if(!i.binding_jwt||!i.auth_url)return[];let o=hAt(i.binding_jwt);if(o!=="card"&&o!=="both")return[];let s;try{s=pAt(a8(i.private_key_jwk))}catch{return[]}return s.jkt!==i.agent_jkt?[]:[{record:i,capability:{agentKey:s,agentJkt:i.agent_jkt,authBaseUrl:i.auth_url}}]}),n=e.agentRef?.trim();if(n){let i=n.replace(/\.visa$/i,"").toLowerCase(),o=r.filter(({record:s})=>s.agent_jkt===n||s.name.replace(/\.visa$/i,"").toLowerCase()===i);if(o.length>1)throw new Error(`more than one card capability is named "${n}"; select the exact request-key JKT`);return o[0]?.capability??null}if(r.length>1)throw new Error("more than one card-capable agent is available; select one explicitly with --agent (name or request-key JKT)");return r[0]?.capability??null}async function EM(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(new Error(`card authority request timed out after ${EOe}ms`)),EOe);i.unref?.();try{return await e(t,{...r,redirect:"error",signal:n.signal})}finally{clearTimeout(i)}}function TOe(e){return e.replace(/\/+$/,"")}async function gAt(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=TOe(e.authBaseUrl),i=SOe(e.draw,e.drawId);if(i===null)throw new y6(400,["invalid_amount"]);let o=await EM(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new y6(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new y6(502,["challenge_malformed"]);let a=await AOe(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await EM(t,`${n}/v4/card/draw-verdict`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"},body:JSON.stringify({nonce:s.nonce,popJwt:a,mandateId:e.mandateId,drawId:e.drawId,draw:e.draw})}),u=await c.json().catch(()=>null);if(!c.ok||!u?.ok||typeof u.verdict!="string")throw new y6(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function bAt(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=TOe(e.authBaseUrl),i=Cne(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=xOe({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await EM(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!s.ok)return{ok:!1,reason:"challenge_failed"};let a=await s.json();if(!a.nonce||!a.audience)return{ok:!1,reason:"challenge_malformed"};let c=await AOe(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await EM(t,`${n}/v4/card/mandate/register`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"},body:JSON.stringify({nonce:a.nonce,popJwt:c,mandateId:e.mandateId,mintToken:e.mintToken})}),d=await u.json().catch(()=>null);return!u.ok||!d?.ok?{ok:!1,reason:d?.reasons?.[0]??"register_refused"}:{ok:!0}}catch(t){return{ok:!1,reason:t instanceof Error?t.message:String(t)}}}var Pne,dAt,wOe,fAt,mAt,y6,EOe,kne=k(()=>{"use strict";Pne=require("node:crypto");W_();dAt="visa-agent-pop+jwt",wOe=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");fAt=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),mAt=1;y6=class extends Error{constructor(r,n){super(`card draw refused (${r}): ${n.join(", ")||"unknown"}`);this.status=r;this.reasons=n;this.name="CardDrawRefusedError"}status;reasons},EOe=3e4});var tRe=g(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});Kl.formatCents=eRe;Kl.formatUsd=FSt;Kl.formatMicros=$M;Kl.formatMicrosWire=VSt;Kl.formatTxAmount=KSt;Kl.formatDate=GSt;Kl.formatRelativeTime=WSt;Kl.formatTime=JSt;Kl.formatAge=YSt;var Qke=1e6,$St=100;function eRe(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let i=(e/$St).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function FSt(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let n=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${n}`:n}function $M(e,t={}){let r=t.fallback??"\u2014",n=typeof e=="string"?e===""?null:Number(e):e;if(n==null||!Number.isFinite(n))return r;let o=(n/Qke).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&n>0?`+${o}`:o}function VSt(e,t,r={}){return e&&/^-?\d+$/.test(e)?$M(e,r):t!=null&&Number.isFinite(t)?eRe(t,r):r.fallback??"\u2014"}function KSt(e,t={}){let r=Number(e.amount_micros);if(Number.isFinite(r)&&e.amount_micros!=null&&e.amount_micros!=="")return $M(r,t);let n=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(n)?$M(n*Qke,t):t.fallback??"\u2014"}function GSt(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function WSt(e,t=Date.now()){if(!e)return"\u2014";let r=Date.parse(e);if(Number.isNaN(r))return"\u2014";let n=t-r,i=n>=0,o=Math.abs(n),s=Math.floor(o/1e3),a=Math.floor(s/60),c=Math.floor(a/60),u=Math.floor(c/24),d=Math.floor(u/7),l=Math.floor(u/30),p=Math.floor(u/365);return s<45?"just now":a<1?i?"a minute ago":"in a minute":a<60?V8(n,i,a,"minute"):c<24?V8(n,i,c,"hour"):u===1?i?"yesterday":"tomorrow":u<7?V8(n,i,u,"day"):d<4?V8(n,i,d,"week"):l<12?V8(n,i,l,"month"):V8(n,i,p,"year")}function V8(e,t,r,n){let i=r!==1?"s":"";return t?`${r} ${n}${i} ago`:`in ${r} ${n}${i}`}function JSt(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}function YSt(e,t){if(!e)return"";let r=Date.parse(e);if(Number.isNaN(r))return"";let n=Math.max(0,t-r),i=Math.floor(n/1e3);if(i<45)return"just now";let o=Math.floor(i/60);if(o<60)return`${o}m ago`;let s=Math.floor(o/60);if(s<24)return`${s}h ago`;let a=Math.floor(s/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 K8=g(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.formatAge=Qt.formatTime=Qt.formatRelativeTime=Qt.formatDate=Qt.formatTxAmount=Qt.formatMicrosWire=Qt.formatMicros=Qt.formatUsd=Qt.formatCents=void 0;Qt.micros=ZSt;Qt.fromCents=XSt;Qt.fromUsdc=QSt;Qt.fromUsd=eTt;Qt.toCents=tTt;Qt.toCentsForAcquirer=rTt;Qt.toUsdc=nTt;Qt.toWire=iTt;Qt.fromWire=oTt;Qt.toDisplay=sTt;Qt.toUsdRounded2dp=aTt;Qt.add=cTt;Qt.sub=uTt;Qt.clampNonNegative=dTt;Qt.isNonNegative=lTt;Qt.max=pTt;Qt.min=fTt;var W0=10000n,rRe=1000000n;function ZSt(e){return e}function XSt(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*W0}function QSt(e){return e}function eTt(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function tTt(e){if(e>=0n)return Number(e/W0);let t=e/W0,r=e%W0;return Number(r===0n?t:t-1n)}function rTt(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/W0)}function nTt(e){return e}function iTt(e){return e.toString()}function oTt(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 sTt(e,t={}){let r=t.decimals??2,n=t.symbol??"$",i=e<0n,o=i?-e:e,s=o/rRe,a=o%rRe,c=i?"-":"";if(r===0)return`${c}${n}${s.toString()}`;let u=a.toString().padStart(6,"0").slice(0,r);return`${c}${n}${s.toString()}.${u}`}function aTt(e){let t=e<0n,r=t?-e:e,n=r/W0,o=r%W0*2n,s;o<W0?s=n:o>W0?s=n+1n:s=n%2n===0n?n:n+1n;let a=Number(s)/100;return t?-a:a}function cTt(e,t){return e+t}function uTt(e,t){return e-t}function dTt(e){return e<0n?0n:e}function lTt(e){return e>=0n}function pTt(e,t){return e>t?e:t}function fTt(e,t){return e<t?e:t}var J0=tRe();Object.defineProperty(Qt,"formatCents",{enumerable:!0,get:function(){return J0.formatCents}});Object.defineProperty(Qt,"formatUsd",{enumerable:!0,get:function(){return J0.formatUsd}});Object.defineProperty(Qt,"formatMicros",{enumerable:!0,get:function(){return J0.formatMicros}});Object.defineProperty(Qt,"formatMicrosWire",{enumerable:!0,get:function(){return J0.formatMicrosWire}});Object.defineProperty(Qt,"formatTxAmount",{enumerable:!0,get:function(){return J0.formatTxAmount}});Object.defineProperty(Qt,"formatDate",{enumerable:!0,get:function(){return J0.formatDate}});Object.defineProperty(Qt,"formatRelativeTime",{enumerable:!0,get:function(){return J0.formatRelativeTime}});Object.defineProperty(Qt,"formatTime",{enumerable:!0,get:function(){return J0.formatTime}});Object.defineProperty(Qt,"formatAge",{enumerable:!0,get:function(){return J0.formatAge}})});var nie=g(hc=>{"use strict";var mTt=hc&&hc.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),hTt=hc&&hc.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),iRe=hc&&hc.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),i=0;i<n.length;i++)n[i]!=="default"&&mTt(r,t,n[i]);return hTt(r,t),r}})();Object.defineProperty(hc,"__esModule",{value:!0});hc.pruneResponsesDir=rie;hc.isTextualContentType=FM;hc.isValidUtf8=sRe;hc.spillFilename=aRe;hc.describePaidBody=eie;hc.capturePaidResponse=wTt;var Pf=iRe(require("fs")),JI=iRe(require("path")),yTt=require("node:crypto"),oRe=16*1024,Qne=2*1024,gTt=64*1024*1024,bTt=3e4,tie=256*1024*1024;function rie(e,t=tie,r){try{let n=r?JI.basename(r):null,i=Pf.readdirSync(e).map(s=>{if(s.includes(".part-"))return null;try{let a=Pf.statSync(JI.join(e,s));return a.isFile()?{name:s,size:a.size,mtime:a.mtimeMs}:null}catch{return null}}).filter(s=>s!==null).sort((s,a)=>s.name===n?-1:a.name===n?1:a.mtime-s.mtime),o=0;for(let s of i)if(o+=s.size,o>t&&s.name!==n)try{Pf.rmSync(JI.join(e,s.name),{force:!0})}catch{}}catch{}}var _Tt=new Set(["application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/csv"]);function FM(e){if(!e)return!1;let t=e.split(";",1)[0].trim().toLowerCase();return t.startsWith("text/")||t.endsWith("+json")||t.endsWith("+xml")||_Tt.has(t)}function sRe(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e),!0}catch{return!1}}var vTt={"application/json":".json","application/pdf":".pdf","audio/mpeg":".mp3","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/svg+xml":".svg","image/webp":".webp","text/csv":".csv","text/html":".html","text/plain":".txt","video/mp4":".mp4"};function aRe(e,t,r){let n="unknown-host";try{n=new URL(e).hostname.toLowerCase()}catch{}let i=n.replace(/[^a-z0-9.-]/g,"_").slice(0,80),o=(t??"").split(";",1)[0].trim().toLowerCase(),s=vTt[o]??(FM(t)?".txt":".bin");return`${r.toISOString().replace(/[:.]/g,"-")}-${i}${s}`}function cRe(e,t,r){let n=aRe(t,r,new Date),i=JI.extname(n),o=n.slice(0,n.length-i.length);return JI.join(e,`${o}-${(0,yTt.randomBytes)(8).toString("hex")}${i}`)}function uRe(e){Pf.mkdirSync(e,{recursive:!0,mode:448})}function nRe(e,t){let r=0;for(;r<t.length;){let n=Pf.writeSync(e,t,r,t.length-r,null);if(n<=0)throw new Error("Paid response file write made no progress.");r+=n}}function eie(e,t,r,n,i){let o=r?FM(r):sRe(n),s={status:t,contentType:r??"unknown",bodyBytes:n.length};if(n.length===0)return{...s,body:""};if(o&&n.length<=oRe)return{...s,body:n.toString("utf-8")};uRe(i);let a=cRe(i,e,r);return Pf.writeFileSync(a,n,{flag:"wx",mode:384}),rie(i,tie,a),{...s,bodyFile:a,...o?{bodyPreview:n.subarray(0,Qne).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}async function wTt(e,t,r,n={}){let i=n.maxBytes??gTt,o=n.timeoutMs??bTt;if(!Number.isSafeInteger(i)||i<=0)throw new Error("Paid response capture maxBytes must be a positive safe integer.");if(!Number.isFinite(o)||o<=0)throw new Error("Paid response capture timeoutMs must be positive.");let s=t.headers.get("content-length");if(s&&/^\d+$/.test(s.trim())){let b=Number(s);if(Number.isSafeInteger(b)&&b>i)throw t.body?.cancel("paid response exceeds capture limit").catch(()=>{}),new Error(`Merchant response body exceeds the ${i}-byte capture limit (declared ${b} bytes).`)}if(!t.body)return eie(e,t.status,t.headers.get("content-type"),Buffer.alloc(0),r);let a=t.body.getReader(),c=Date.now(),u=[],d=0,l=0,p=null,f=null,m=null,h=[],y=0,v=()=>{p!==null&&(Pf.closeSync(p),p=null)},E=()=>{if(v(),m)try{Pf.rmSync(m,{force:!0})}catch{}};try{for(;;){let A=o-(Date.now()-c);if(A<=0)throw new Error(`Merchant response body timed out after ${o}ms.`);let x,S=new Promise((C,U)=>{x=setTimeout(()=>U(new Error(`Merchant response body timed out after ${o}ms.`)),A)}),I;try{I=await Promise.race([a.read(),S])}finally{x&&clearTimeout(x)}if(I.done)break;let T=Buffer.from(I.value);if(l+=T.length,l>i)throw new Error(`Merchant response body exceeded the ${i}-byte capture limit.`);if(y<Qne){let C=T.subarray(0,Math.min(T.length,Qne-y));h.push(Buffer.from(C)),y+=C.length}if(p===null){if(u.push(T),d+=T.length,d<=oRe)continue;uRe(r),f=cRe(r,e,t.headers.get("content-type")),m=`${f}.part-${process.pid}-${Math.random().toString(16).slice(2)}`,p=Pf.openSync(m,"wx",384);for(let C of u)nRe(p,C);u.length=0,d=0}else nRe(p,T)}if(p===null){let A=Buffer.concat(u,d);return eie(e,t.status,t.headers.get("content-type"),A,r)}v(),Pf.renameSync(m,f),m=null,rie(r,tie,f);let b=t.headers.get("content-type"),w=b?FM(b):!1;return{status:t.status,contentType:b??"unknown",bodyBytes:l,bodyFile:f,...w?{bodyPreview:Buffer.concat(h).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}catch(b){throw a.cancel("paid response capture failed").catch(()=>{}),E(),b}finally{try{a.releaseLock()}catch{}}}});var zy=g(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.TURNKEY_API_BASE_URL_ENV=go.CIRCLE_TESTNET_FAUCET_URL=go.NETWORK_ENV=go.NETWORKS=void 0;go.resolveNetwork=ETt;go.turnkeyApiBaseUrl=xTt;go.explorerTxUrl=STt;go.explorerAddressUrl=TTt;go.NETWORKS={"base-mainnet":{id:"base-mainnet",caip2:"eip155:8453",chainId:8453,usdc:{address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",eip712Domain:{name:"USD Coin",version:"2"}},rpcUrl:"https://mainnet.base.org",explorerBaseUrl:"https://basescan.org",isTestnet:!1},"base-sepolia":{id:"base-sepolia",caip2:"eip155:84532",chainId:84532,usdc:{address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",eip712Domain:{name:"USDC",version:"2"}},rpcUrl:"https://sepolia.base.org",explorerBaseUrl:"https://sepolia.basescan.org",isTestnet:!0}};go.NETWORK_ENV="VISA_V4_NETWORK";go.CIRCLE_TESTNET_FAUCET_URL="https://faucet.circle.com";var dRe={"base-mainnet":"base-mainnet","base-sepolia":"base-sepolia","eip155:8453":"base-mainnet","eip155:84532":"base-sepolia"};function ETt(e=process.env){let t=(e[go.NETWORK_ENV]??"").trim();if(t==="")return go.NETWORKS["base-mainnet"];let r=dRe[t.toLowerCase()];if(!r)throw new Error(`unknown ${go.NETWORK_ENV} value ${JSON.stringify(t)} \u2014 valid values: `+Object.keys(dRe).join(", "));return go.NETWORKS[r]}go.TURNKEY_API_BASE_URL_ENV="TURNKEY_API_BASE_URL";var ATt="https://api.turnkey.com";function xTt(e=process.env){let t=(e[go.TURNKEY_API_BASE_URL_ENV]??"").trim();return t===""?ATt:t}function STt(e,t){return`${e.explorerBaseUrl}/tx/${t}`}function TTt(e,t){return`${e.explorerBaseUrl}/address/${t}`}});var lRe=g(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.version=void 0;VM.version="1.2.3"});var B6=g(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0});KM.BaseError=void 0;var ITt=lRe(),iie=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${ITt.version}`].join(`
196
+ `))})}var vf,$re,z0,qre,Ry,Ny,l6,Dre,oEt,u6=k(()=>{"use strict";vf=_e(require("fs")),$re=_e(require("os")),z0=_e(require("path")),qre=require("node:readline/promises");W_();Ry=_e(ure());Tj();Wj();lI();VU();NPe();ZPe();eCe();dM();fCe();e8();x0();Ny=z0.join($re.homedir(),".visa-cli","agents");l6=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Dre=32768,oEt=/[\p{Cc}\p{Cf}\u2028\u2029]/u});var tne={};Oi(tne,{SUBWAY_PROTOCOL:()=>LCe,registerDirect:()=>NEt,resolveDirect:()=>BEt});function Zre(e,t){let r=typeof t=="bigint"?t:BigInt(t);for(;r>0x7fn;)e.push(Number(r&0x7fn|0x80n)),r>>=7n;e.push(Number(r))}function vd(e,t){let r=0n,n=0n,i=t;for(;;){let o=e[i++];if(r|=BigInt(o&127)<<n,(o&128)===0)break;n+=7n}return[r,i]}function Xre(e,t){return e<<3|t}function EI(e,t,r){e.push(Xre(t,2)),Zre(e,r.length);for(let n of r)e.push(n)}function wEt(e,t){let r=[];return EI(r,1,Yre.encode(e)),t&&t.length>0&&EI(r,2,Yre.encode(t)),Uint8Array.from(r)}function EEt(e,t,r){let n=[];return r!==0n&&(n.push(Xre(1,0)),Zre(n,r)),EI(n,2,wEt(e,t)),Uint8Array.from(n)}function AEt(e){let t=[];return EI(t,1,Yre.encode(e)),Uint8Array.from(t)}function xEt(e,t){let r=[];return t!==0n&&(r.push(Xre(1,0)),Zre(r,t)),EI(r,3,AEt(e)),Uint8Array.from(r)}function SEt(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=vd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=vd(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=vd(e,t),u=c,d=u+Number(a);r.error=qCe.decode(e.subarray(u,d)),t=d}else t=Qre(e,t,s)}return r}function TEt(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=vd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=vd(e,t),u=c,d=u+Number(a);r.peerId=e.subarray(u,d),t=d}else if(o===2&&s===2){let[a,c]=vd(e,t),u=c,d=u+Number(a);r.error=qCe.decode(e.subarray(u,d)),t=d}else t=Qre(e,t,s)}return r}function Qre(e,t,r){if(r===0)return vd(e,t)[1];if(r===2){let[n,i]=vd(e,t);return i+Number(n)}if(r===5)return t+4;if(r===1)return t+8;throw new Error(`unsupported wire type ${r}`)}function DCe(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=vd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=vd(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=vd(e,t),u=c,d=u+Number(a);r.registerNameResponse=SEt(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=vd(e,t),u=c,d=u+Number(a);r.resolveNameResponse=TEt(e.subarray(u,d)),t=d}else t=Qre(e,t,s)}return r}function IEt(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function ene(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function PEt(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=ene(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:DCe(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function CEt(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=ene(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:DCe(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Jre(e){let t=e.reduce((i,o)=>i+o.length,0),r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}async function REt(e){let t=[],r=0,n=-1;for await(let i of e){let o=i instanceof Uint8Array?i:i.subarray();if(t.push(o),r+=o.length,r>OCe)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+ene(Jre(t).subarray(0,4)),n>OCe))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return Jre(t).subarray(0,n)}return Jre(t)}async function zCe(e){return(0,kCe.createLibp2p)({...e?{privateKey:await(0,jCe.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,RCe.tcp)()],connectionEncrypters:[(0,NCe.noise)()],streamMuxers:[(0,BCe.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function HCe(e,t,r){let n=await e.dialProtocol((0,UCe.multiaddr)(t),LCe,{signal:AbortSignal.timeout(OEt)});n.send(IEt(r));let i;return Promise.race([REt(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),kEt)})]).finally(()=>clearTimeout(i))}async function NEt(e){let t=await zCe(e.seed);try{let r=await HCe(t,e.relayMultiaddr,EEt(e.name,e.binding,e.requestId??1n)),n=PEt(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function BEt(e){let t=await zCe(e.seed);try{let r=await HCe(t,e.relayMultiaddr,xEt(e.name,e.requestId??1n)),n=CEt(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,MCe.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var kCe,RCe,NCe,BCe,jCe,UCe,MCe,Yre,qCe,LCe,OEt,kEt,OCe,rne=k(()=>{"use strict";Pte();kCe=require("libp2p"),RCe=require("@libp2p/tcp"),NCe=require("@chainsafe/libp2p-noise"),BCe=require("@chainsafe/libp2p-yamux"),jCe=require("@libp2p/crypto/keys"),UCe=require("@multiformats/multiaddr"),MCe=require("uint8arrays/to-string"),Yre=new TextEncoder,qCe=new TextDecoder;LCe="/subway/p2p/1.0.0",OEt=15e3,kEt=15e3,OCe=1<<20});var TI={};Oi(TI,{DEFAULT_VISA_RELAY_MULTIADDR:()=>$Ce,MESH:()=>ki,RELAY_URL:()=>xI,connectOrThrow:()=>x8,ensureMailbox:()=>yne,hydrateInbox:()=>YCe,isSubwayEnabled:()=>ane,listRegistered:()=>fne,loadBindingFor:()=>dne,loadRegistry:()=>f6,makeClient:()=>A8,meshName:()=>wf,pairedVisaBinding:()=>GCe,pairedVisaBindingForIdentity:()=>WCe,persistInbox:()=>hne,readInbox:()=>DEt,registerName:()=>SI,resolveActingName:()=>fM,resolveMeshName:()=>lne,seedSubwayKeyFromExactIdentity:()=>KCe,seedSubwayKeyFromTapAgent:()=>VCe,sendMessage:()=>pne,sendVia:()=>LEt,subwayKeyPath:()=>une,visaRelayMultiaddr:()=>sne});function sne(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??$Ce}function wf(e){return e.includes(".")?e:`${e}.${ki}`}function ane(e){if(process.env.VISA_DEV==="1")return!0;let t=e??"0.0.0";return t==="0.0.0"||t.startsWith("0.0.")?!0:/-rc\.|-beta\./.test(t)}function cne(){Ws.mkdirSync(E8,{recursive:!0,mode:448})}function FCe(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function une(e){return AI.join(E8,`${FCe(e)}.key`)}function f6(){if(!Ws.existsSync(one))return{};try{return JSON.parse(Ws.readFileSync(one,"utf8"))}catch{return{}}}function nne(e){cne(),Ws.writeFileSync(one,JSON.stringify(e,null,2),{mode:384})}function ine(){try{return pM.userInfo().username}catch{return"local"}}function VCe(e){if(Ws.existsSync(e))return null;let t=sM();if(!t)return null;try{let r=a8(t.private_key_jwk);return cne(),Ws.writeFileSync(e,Buffer.from(r),{mode:384}),t.agent_jkt}catch{return null}}function KCe(e,t){let r=a8(t.identityPrivateJwk);if(hf(by(K_(r)))!==t.identityKeyJkt)throw new mf("The selected agent identity key does not match its stable record. Refusing .visa registration.");if(Ws.existsSync(e)){if(hf(by(K_(tI(e))))!==t.identityKeyJkt)throw new mf("The existing Subway key belongs to a different agent. Refusing to replace it implicitly.");return t.stableAgentId}return cne(),Ws.writeFileSync(e,Buffer.from(r),{mode:384}),t.stableAgentId}function A8(e,t={}){return new oPe({name:wf(e),url:xI,keyPath:une(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function dne(e){if(ki!=="visa")return;let t=f6()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function x8(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${xI})`)),t))])}function fM(e){if(e)return e;let t=Object.keys(f6());if(t.length===1)return t[0];throw t.length===0?new Error("No Subway names registered yet. Run `visa register <name>` first."):new Error(`Multiple names registered (${t.join(", ")}). Pass --as <name>.`)}function GCe(e,t=Date.now()){let r=sM();if(!r?.binding_jwt)return null;let n=w8(r.binding_jwt);if(!n||n.mesh!=="visa"||n.name!==e||n.jkt!==r.agent_jkt)return null;let i=typeof n.exp=="number"?n.exp:NaN;return!Number.isFinite(i)||i*1e3<=t?null:{binding:r.binding_jwt,bindingExpiresAt:new Date(i*1e3).toISOString(),identityKeyJkt:r.agent_jkt}}function WCe(e,t,r=Date.now()){for(let n of aM()){if(n.agent_jkt!==t)continue;let i=w8(n.binding_jwt);if(!i||i.mesh!=="visa"||i.name!==e||i.jkt!==t)continue;let o=typeof i.exp=="number"?i.exp:NaN;if(!(!Number.isFinite(o)||o*1e3<=r))return{binding:n.binding_jwt,bindingExpiresAt:new Date(o*1e3).toISOString(),identityKeyJkt:t}}return null}async function SI(e,t={}){let r=une(e),n=wf(e),i,o;if(t.exactIdentity){if(o=ki==="visa"?WCe(n,t.exactIdentity.identityKeyJkt):null,ki==="visa"&&!o)throw new mf;i=KCe(r,t.exactIdentity)}else i=VCe(r),o=ki==="visa"?GCe(n):null;let s,a={};if(o){if(!Ws.existsSync(r))throw new mf("A stored .visa binding exists, but its runtime-held identity key is unavailable. A new identity pairing cannot recreate this separate channel binding.");if(hf(by(K_(tI(r))))!==o.identityKeyJkt)throw new mf("The stored .visa binding does not match this Subway identity key. Refusing to present a mismatched legacy admission artifact.");s=o.binding,a={binding:o.binding,bindingExpiresAt:o.bindingExpiresAt}}else if(ki==="visa")throw new mf;let c=ki==="visa"?sne():process.env.SUBWAY_RELAY_MULTIADDR;if(ki==="visa"&&c){let{registerDirect:d}=await Promise.resolve().then(()=>(rne(),tne)),l=await d({relayMultiaddr:c,seed:tI(r),name:n,binding:s});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let p=f6();return p[e]={relayName:n,mesh:ki,peerId:l.peerId,owner:ine(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},nne(p),{relayName:n,mesh:ki,peerId:l.peerId,tapAgentId:i,...s?{binding:s}:{}}}if(ki==="visa"&&!process.env.SUBWAY_RELAY){let d=f6();return d[e]={relayName:n,mesh:ki,peerId:null,owner:ine(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},nne(d),{relayName:n,mesh:ki,peerId:null,tapAgentId:i,...s?{binding:s}:{},note:s?"Visa binding ready; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa directory/TAP admission binding is stored. Identity pairing does not issue one; use a separately approved directory capability when available."}}let u=A8(e,{autoReconnect:!1,binding:s});try{await x8(u);let d=f6();return d[e]={relayName:n,mesh:ki,peerId:u.peerId,owner:ine(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},nne(d),{relayName:n,mesh:ki,peerId:u.peerId,tapAgentId:i,...s?{binding:s}:{}}}finally{u.disconnect()}}async function lne(e){let t=wf(e),r=ki==="visa"?sne():process.env.SUBWAY_RELAY_MULTIADDR;if(ki==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(rne(),tne)),i=await n({relayMultiaddr:r,name:t});return{relayName:t,found:i.found,peerId:i.peerId,error:i.error}}throw new Error("subway find needs the .visa mesh with a dedicated relay \u2014 set SUBWAY_MESH=visa and SUBWAY_RELAY_MULTIADDR.")}async function pne(e,t,r){let n=A8(e,{autoReconnect:!1,binding:dne(e)});try{await x8(n);let i=wf(t);return await n.sendSigned(i,"chat",r),{to:i,as:wf(e)}}finally{n.disconnect()}}function fne(){let e=f6();return Object.entries(e).map(([t,r])=>({name:t,...r}))}function JCe(e,t=E8){return AI.join(t,`${FCe(e)}.inbox.json`)}function UEt(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.from=="string"&&typeof t.text=="string"&&typeof t.ts=="number"&&typeof t.verified=="boolean"}function YCe(e,t=E8){try{let r=JSON.parse(Ws.readFileSync(JCe(e,t),"utf8"));return Array.isArray(r)?r.filter(UEt).slice(-mne):[]}catch{return[]}}function hne(e,t,r=E8){try{Ws.mkdirSync(r,{recursive:!0,mode:448}),Ws.writeFileSync(JCe(e,r),JSON.stringify(t.slice(-mne),null,2),{mode:384})}catch{}}function MEt(e,t){if(t.dirty=!0,t.flushTimer)return;let r=setTimeout(()=>{t.flushTimer=null,t.dirty&&(t.dirty=!1,hne(e,t.buffer))},jEt);typeof r.unref=="function"&&r.unref(),t.flushTimer=r}function qEt(e,t){t.flushTimer&&(clearTimeout(t.flushTimer),t.flushTimer=null),t.dirty=!1,hne(e,t.buffer)}async function yne(e){let t=lM.get(e);if(t)return{relayName:wf(e),peerId:t.client.peerId};let r=A8(e,{autoReconnect:!0,binding:dne(e)}),n=YCe(e),i={client:r,buffer:n,flushTimer:null,dirty:!1};return r.onMessage(o=>{n.push({from:o.fromName,text:o.payload,ts:o.timestampMs,verified:!!o.verified}),n.length>mne&&n.shift(),MEt(e,i)}),lM.set(e,i),await x8(r),{relayName:wf(e),peerId:r.peerId}}async function DEt(e,t=20,r=!1){await yne(e);let n=lM.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0,qEt(e,n)),i}async function LEt(e,t,r){await yne(e);let n=lM.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=wf(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:wf(e)}}var Ws,pM,AI,ki,$Ce,xI,E8,one,lM,mne,jEt,m6=k(()=>{"use strict";Zte();W_();Ws=_e(require("fs")),pM=_e(require("os")),AI=_e(require("path"));rI();u6();ki=process.env.SUBWAY_MESH??"relay",$Ce="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";xI=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";E8=AI.join(pM.homedir(),".visa-cli","subway"),one=AI.join(E8,"registry.json");lM=new Map,mne=200,jEt=100});var pOe={};Oi(pOe,{PAIRING_DIR:()=>Af,cancelPairing:()=>Wre,claimPairing:()=>p6,getPairingStatus:()=>uM,initiatePairing:()=>wI,latestPendingHumanPairing:()=>rM,latestPendingRuntimePairing:()=>vM,pairingFilePath:()=>_M,pollAndActivatePairing:()=>nM,readPendingPairing:()=>_d,registerOnVisaMeshIfEnabled:()=>cM,removePendingPairing:()=>vI,tryActivatePairing:()=>Sne,verifyPairing:()=>ky,writePendingPairing:()=>xne});async function cM(e){if(process.env.SUBWAY_MESH!=="visa")return!1;try{return await SI(e),!0}catch(t){return ke.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)}),!1}}function pc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ef(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function _ne(e){return typeof e=="string"&&$Et.test(e)}function S8(e){return typeof e=="string"&&FEt.test(e)}function II(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function nOe(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function hM(e){if(typeof e!="string"||e.length===0||e.length>rOe)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&nOe(t.hostname))&&t.username.length===0&&t.password.length===0}catch{return!1}}function bM(e){if(e.length===0||e.length>rOe)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&nOe(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function vne(e){if(typeof e!="string")return!1;try{return bM(e)===e}catch{return!1}}function GEt(e){return pc(e)&&Ef(e,["kty","crv","x"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Er(e.x)}function WEt(e){return pc(e)&&Ef(e,["kty","crv","x","d"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Er(e.x)&&Er(e.d)}function JEt(e,t){try{let r=G_(Buffer.from(e.d,"base64url"));return r.x===t.x&&r.d===e.d}catch{return!1}}function mM(e,t){if(typeof e!="string"||VEt.test(e))return null;let r=e.normalize("NFC").trim();return r.length>0&&r.length<=t?r:null}function iOe(e){if(!pc(e)||!Ef(e,["runtime","contextLabel","cliVersion","platform"]))return null;let t=mM(e.runtime,100),r=mM(e.contextLabel,200),n=e.cliVersion===void 0?void 0:mM(e.cliVersion,64),i=e.platform===void 0?void 0:mM(e.platform,100);return!t||!r||e.cliVersion!==void 0&&!n||e.platform!==void 0&&!i?null:{runtime:t,contextLabel:r,...n?{cliVersion:n}:{},...i?{platform:i}:{}}}function YEt(e){if(!pc(e))return!1;let t=iOe(e);return t?t.runtime===e.runtime&&t.contextLabel===e.contextLabel&&t.cliVersion===e.cliVersion&&t.platform===e.platform:!1}function oOe(e){return pc(e)?Ef(e,["role","protocolVersion","pairingId","agentId","verifier","authUrl","skillUrl","expiresAt","createdAt"])&&e.role==="human"&&e.protocolVersion===jt&&S8(e.pairingId)&&_ne(e.agentId)&&Er(e.verifier)&&vne(e.authUrl)&&hM(e.skillUrl)&&II(e.expiresAt)&&II(e.createdAt):!1}function sOe(e){return!pc(e)||!Ef(e,["role","protocolVersion","pairingId","agentId","authUrl","claimToken","serverNonce","identityKeyJkt","identityPublicJwk","identityPrivateJwk","runtime","createdAt"])||e.role!=="runtime"||e.protocolVersion!==jt||!S8(e.pairingId)||!_ne(e.agentId)||!vne(e.authUrl)||!Er(e.claimToken)||!Er(e.serverNonce)||!Er(e.identityKeyJkt)||!GEt(e.identityPublicJwk)||!WEt(e.identityPrivateJwk)||!YEt(e.runtime)||!II(e.createdAt)?!1:e.identityPublicJwk.x===e.identityPrivateJwk.x&&hf(e.identityPublicJwk)===e.identityKeyJkt&&JEt(e.identityPrivateJwk,e.identityPublicJwk)}function ZEt(e){return pc(e)&&Ef(e,["protocolVersion","verifier","authUrl","createdAt"])&&e.protocolVersion===jt&&Er(e.verifier)&&vne(e.authUrl)&&II(e.createdAt)}function PI(e,t,r){if(!pc(e)||e.protocolVersion!==jt||!S8(e.pairingId)||!_ne(e.agentId)||typeof e.state!="string"||!KEt.has(e.state)||!II(e.expiresAt)||e.skillUrl!==void 0&&!hM(e.skillUrl)||e.authorizationUrl!==void 0&&!hM(e.authorizationUrl)||e.serverNonce!==void 0&&!Er(e.serverNonce)||e.authApiUrl!==void 0&&!hM(e.authApiUrl)||e.failureCode!==void 0&&typeof e.failureCode!="string"||t!==void 0&&e.pairingId!==t||r!==void 0&&e.agentId!==r)throw new Error("pairing server returned an invalid v2 status response")}function _M(e,t,r=Af){if(!S8(e))throw new Error("pairing id must use the canonical ap_ + 24 base64url form");return gM.join(r,`${e}.${t}.json`)}function aOe(e){Hl.mkdirSync(e,{recursive:!0,mode:448});let t=Hl.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("pairing directory must be a real directory, not a symlink");Hl.chmodSync(e,448),lc(e)}function wne(e){return gM.join(e,zEt)}function Ene(e){let t=a6(wne(e));if(t===null)return null;let r;try{r=JSON.parse(t)}catch{throw new Error("local pairing initiation state contains invalid JSON")}if(!ZEt(r))throw new Error("local pairing initiation state is invalid");return r}function XEt(e,t){aOe(t),D0(wne(t),JSON.stringify(e,null,2))}function ZCe(e,t){let r=Ene(t);if(!r)return;let n=_d(e,"human",t);n&&n.verifier===r.verifier&&n.authUrl===r.authUrl&&Ane(t)}function Ane(e){Ene(e)&&lc(e)&&Hl.rmSync(wne(e),{force:!0})}function xne(e,t=Af){if(!(e.role==="human"?oOe(e):sOe(e)))throw new Error("refusing to write invalid protocol-v2 pending pairing state");aOe(t);let n=_M(e.pairingId,e.role,t);D0(n,JSON.stringify(e,null,2))}function vI(e,t,r=Af){_d(e,t,r)&&lc(r)&&Hl.rmSync(_M(e,t,r),{force:!0})}function gne(e,t=Af){vI(e,"human",t),vI(e,"runtime",t),Ane(t)}function _d(e,t,r=Af){if(!S8(e))return null;let n=a6(_M(e,t,r));if(n===null)return null;let i;try{i=JSON.parse(n)}catch{throw new Error(`local ${t} pairing state for ${e} contains invalid JSON`)}if(t==="human"){if(!oOe(i)||i.pairingId!==e)throw new Error(`local human pairing state for ${e} is invalid or misbound`);return i}if(!sOe(i)||i.pairingId!==e)throw new Error(`local runtime pairing state for ${e} is invalid or misbound`);return i}function cOe(e,t){return lc(t)?Hl.readdirSync(t).filter(n=>n.endsWith(`.${e}.json`)).map(n=>{let i=n.slice(0,-`.${e}.json`.length);if(!S8(i))throw new Error(`local ${e} pairing filename ${n} is invalid`);return _d(i,e,t)}).filter(n=>n!==null).sort((n,i)=>i.createdAt.localeCompare(n.createdAt))[0]??null:null}function rM(e=Af){return cOe("human",e)}function vM(e=Af){return cOe("runtime",e)}function yM(e,t="pairing operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function bne(e,t){return t?t.aborted?Promise.reject(yM(t)):new Promise((r,n)=>{let i=()=>n(yM(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function h6(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("pairing operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`pairing request timed out after ${XCe}ms`)),XCe);s.unref?.();try{if(i.signal.aborted)throw yM(i.signal);let a=await bne(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":tOe,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await bne(a.json(),i.signal)}catch{if(i.signal.aborted)throw yM(i.signal);c={}}if(!a.ok&&a.status!==202){let u=pc(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`pairing server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}async function wI(e={}){let t=bM(e.authUrl??Ta()),r=e.pairingDir??Af,n=Ene(r),i=n?Date.parse(n.createdAt):Number.NaN,o=n!==null&&Number.isFinite(i)&&Date.now()-i<HEt;if(o&&n.authUrl!==t)throw new Error("a pairing initiation is pending for a different auth origin; retry it first");let s=o?n:{protocolVersion:jt,verifier:MIe(),authUrl:t,createdAt:new Date().toISOString()};o||XEt(s,r);let a=s.verifier,{body:c}=await h6(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:jt,cliChallenge:qIe(a)})},e.fetchImpl??fetch,{signal:e.signal});if(PI(c),c.state!=="awaiting_agent"||!c.skillUrl)throw new Error("pairing server returned an incomplete v2 initiation response");let u={role:"human",protocolVersion:jt,pairingId:c.pairingId,agentId:c.agentId,verifier:a,authUrl:t,skillUrl:ete(c.skillUrl),expiresAt:c.expiresAt,createdAt:new Date().toISOString()};return xne(u,r),e.retainInitiationDraft||Ane(r),u}function uOe(e){return e.authorizationUrl?{...e,authorizationUrl:ete(e.authorizationUrl)}:e}async function ky(e){let{pairing:t}=e,{body:r}=await h6(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:jt,verifier:t.verifier,code:e.code})},e.fetchImpl??fetch,{signal:e.signal});return PI(r,t.pairingId,t.agentId),uOe(r)}async function uM(e){let t=bM(e.authUrl??Ta()),{body:r}=await h6(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch,{signal:e.signal});return PI(r,e.pairingId,e.expectedAgentId),uOe(r)}function dOe(e,t){return Buffer.from(gy(e,Buffer.from(t,"utf8"))).toString("base64url")}function QEt(e){let t=dOe(Buffer.from(e.identityPrivateJwk.d,"base64url"),xte({protocolVersion:jt,pairingId:e.pairingId,agentId:e.agentId,serverNonce:e.serverNonce,claimTokenHash:k0(e.claimToken),identityKeyJkt:e.identityKeyJkt,runtime:e.runtime}));return{protocolVersion:jt,agentId:e.agentId,identityPublicJwk:e.identityPublicJwk,runtime:e.runtime,signature:t,claimToken:e.claimToken}}async function QCe(e,t,r){let{body:n}=await h6(`${e.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(QEt(e))},t,{signal:r}),i=n;if(!pc(i)||!Ef(i,["protocolVersion","pairingId","agentId","state","verificationCode","claimToken"])||i.protocolVersion!==jt||i.pairingId!==e.pairingId||i.agentId!==e.agentId||typeof i.state!="string"||!["agent_claimed","code_verified","awaiting_human","authorized","delivered","activated"].includes(i.state)||i.claimToken!==e.claimToken||typeof i.verificationCode!="string"||i.verificationCode!==mU(e.pairingId,e.claimToken))throw new Error("pairing server returned an invalid v2 claim response");return{pending:e,verificationCode:i.verificationCode}}async function p6(e){let t=bM(e.authUrl??Ta()),r=e.fetchImpl??fetch,n=e.pairingDir??Af,i=iOe({runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:tOe});if(!i)throw new Error("runtime metadata must be canonical, bounded, non-empty text");let o=_d(e.pairingId,"runtime",n);if(o){if(o.authUrl!==t||o.runtime.runtime!==i.runtime||o.runtime.contextLabel!==i.contextLabel)throw new Error("this pairing already has a different pending runtime claim; resume it");return ZCe(o.pairingId,n),QCe(o,r,e.signal)}let s=await uM({pairingId:e.pairingId,authUrl:t,fetchImpl:r,signal:e.signal});if(s.state!=="awaiting_agent"||!Er(s.serverNonce))throw new Error(`pairing cannot be claimed from state ${s.state}`);let a=IIe(),c=G_(a.secretKey),u=by(a.publicKey),d=hf(u),l=i,p=fU();xte({protocolVersion:jt,pairingId:e.pairingId,agentId:s.agentId,serverNonce:s.serverNonce,claimTokenHash:k0(p),identityKeyJkt:d,runtime:l});let f={role:"runtime",protocolVersion:jt,pairingId:e.pairingId,agentId:s.agentId,authUrl:t,claimToken:p,serverNonce:s.serverNonce,identityKeyJkt:d,identityPublicJwk:u,identityPrivateJwk:c,runtime:l,createdAt:new Date().toISOString()};return xne(f,n),ZCe(f.pairingId,n),QCe(f,r,e.signal)}async function lOe(e){let t=e.fetchImpl??fetch,{body:r,status:n}=await h6(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/delivery`,{method:"GET",headers:{"X-Agent-Pairing-Token":e.pending.claimToken},cache:"no-store"},t,{signal:e.signal});if(n===202){if(PI(r,e.pending.pairingId,e.pending.agentId),e.onState?.(r.state),["expired","cancelled","failed","revoked"].includes(r.state))throw gne(e.pending.pairingId,e.pairingDir),new Error(`pairing ended in state ${r.state}`);return null}if(!pc(r)||!Ef(r,["protocolVersion","pairingId","agentId","state","artifact","deliveryArtifactHash"])||r.protocolVersion!==jt||r.pairingId!==e.pending.pairingId||r.agentId!==e.pending.agentId||r.state!=="delivered"&&r.state!=="activated"||!pc(r.artifact)||!Er(r.deliveryArtifactHash))throw new Error("pairing delivery omitted the canonical v2 identity artifact");e.onState?.(r.state);let i=XT(r.artifact),o=JSON.parse(i),s=$Ie(o);if(s!==r.deliveryArtifactHash||o.pairingId!==e.pending.pairingId||o.agentId!==e.pending.agentId||o.identityKey.jkt!==e.pending.identityKeyJkt||o.identityKey.publicJwk.x!==e.pending.identityPublicJwk.x)throw new Error("pairing v2 delivery artifact did not match this pending identity claim");let a=dOe(Buffer.from(e.pending.identityPrivateJwk.d,"base64url"),LIe({protocolVersion:jt,pairingId:e.pending.pairingId,agentId:e.pending.agentId,ownerPublicId:o.ownerPublicId,claimTokenHash:k0(e.pending.claimToken),identityKeyJkt:e.pending.identityKeyJkt,ceremonyHash:o.ceremonyHash,deliveryArtifactHash:s})),c=await h6(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Pairing-Token":e.pending.claimToken},body:JSON.stringify({protocolVersion:jt,agentId:e.pending.agentId,signature:a})},t,{signal:e.signal}),u=o.terms,d=c.body;if(!pc(d)||!Ef(d,["protocolVersion","state","pairingId","agentId","ownerPublicId","identityKeyJkt","displayName","credentials"])||d.protocolVersion!==jt||d.state!=="activated"||d.pairingId!==e.pending.pairingId||d.agentId!==e.pending.agentId||d.ownerPublicId!==o.ownerPublicId||d.identityKeyJkt!==e.pending.identityKeyJkt||d.displayName!==u.displayName||!pc(d.credentials)||!Ef(d.credentials,["bindingJwt","registrationJwt"])||typeof d.credentials.bindingJwt!="string"||d.credentials.bindingJwt.length===0||typeof d.credentials.registrationJwt!="string"||d.credentials.registrationJwt.length===0)throw new Error("pairing server returned an invalid v2 activation response");let l={v:jt,agent_id:e.pending.agentId,owner_public_id:o.ownerPublicId,display_name:c.body.displayName,identity_key:{jkt:e.pending.identityKeyJkt,public_jwk:e.pending.identityPublicJwk,private_jwk:e.pending.identityPrivateJwk,custody:"runtime"},pairing_id:e.pending.pairingId,pairing_status:"activated",activation_credentials:{binding_jwt:d.credentials.bindingJwt,registration_jwt:d.credentials.registrationJwt},delivery_artifact:o,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};(e.writeAgentRecord??Kre)(l,e.agentDir),gne(e.pending.pairingId,e.pairingDir);let p=await cM(l.display_name);return process.env.SUBWAY_MESH==="visa"&&ke.info("agent:fresh_activate_mesh",{name:l.display_name,meshRegistered:p}),{record:l,name:l.display_name,agentId:l.agent_id,identityKeyJkt:l.identity_key.jkt}}async function Sne(e){return lOe(e)}async function nM(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await lOe({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await bne(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization")}async function Wre(e){let{pairing:t}=e,{body:r}=await h6(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:jt,verifier:t.verifier})},e.fetchImpl??fetch,{signal:e.signal});return PI(r,t.pairingId,t.agentId),r.state==="cancelled"&&gne(t.pairingId,e.pairingDir),r}var Hl,eOe,gM,tOe,Af,zEt,HEt,$Et,FEt,VEt,KEt,rOe,XCe,dM=k(()=>{"use strict";Hl=_e(require("node:fs")),eOe=_e(require("node:os")),gM=_e(require("node:path"));W_();ly();Wj();yd();rI();m6();lI();u6();tOe="4.1.0-rc.59",Af=gM.join(eOe.homedir(),".visa-cli","pairings"),zEt=".initiation.v2.json",HEt=15*6e4,$Et=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,FEt=/^ap_[A-Za-z0-9_-]{24}$/,VEt=/[\p{Cc}\p{Cf}\u2028\u2029]/u,KEt=new Set(["awaiting_agent","agent_claimed","code_verified","awaiting_human","authorized","delivered","activated","expired","cancelled","failed","revoked"]),rOe=2048;XCe=3e4});function fOe(e){return e.reason instanceof Error?e.reason:new Error("agent pairing timed out")}function eAt(e,t){return t?t.aborted?Promise.reject(fOe(t)):new Promise((r,n)=>{let i=()=>n(fOe(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}function tAt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return t===e.length?e:e.slice(0,t)}function mOe(e,t){if(t!==void 0&&tAt(t)!==e)throw new Error("auth URL does not match the pending pairing; resume with the original origin")}function rAt(e){return{status:"activated",protocolVersion:jt,pairingId:e.record.pairing_id,agentId:e.agentId,displayName:e.name,identityKeyJkt:e.identityKeyJkt}}async function bI(e={}){let t=vM(e.pairingDir);if(t){mOe(t.authUrl,e.authUrl);let s=_d(t.pairingId,"human",e.pairingDir);if(!s||s.agentId!==t.agentId)throw new Error("a runtime pairing is already pending without its local human proof; resume or cancel it before starting another");let a=await p6({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}}),c=await ky({pairing:s,code:a.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!c.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:jt,pairingId:t.pairingId,agentId:t.agentId,requestKeyFingerprint:t.identityKeyJkt,authorizationUrl:c.authorizationUrl,expiresAt:s.expiresAt}}let r=await wI({authUrl:e.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{},retainInitiationDraft:!0}),{pending:n,verificationCode:i}=await p6({pairingId:r.pairingId,runtime:e.runtime??"visa-cli",contextLabel:e.contextLabel??"Pair this runtime",authUrl:r.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});if(n.agentId!==r.agentId)throw new Error("pairing claim returned a different stable agent id");let o=await ky({pairing:r,code:i,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!o.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:jt,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:n.identityKeyJkt,authorizationUrl:o.authorizationUrl,expiresAt:r.expiresAt}}function nAt(e,t){if(!e)return!1;let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&t>=r}async function _I(e={}){let t=vM(e.pairingDir);if(!t)return{status:"no_pending"};let r=_d(t.pairingId,"human",e.pairingDir);try{mOe(t.authUrl,e.authUrl);let n=Math.max(1,e.attempts??1),i=e.sleep??(o=>new Promise(s=>setTimeout(s,o)));for(let o=0;o<n;o+=1){let s="",a=await Sne({pending:t,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,agentDir:e.agentDir,...e.signal?{signal:e.signal}:{},onState:c=>{s=c}});if(a)return rAt(a);if(o===0&&["awaiting_agent","agent_claimed","code_verified"].includes(s)){if(!r)throw new Error("pending pairing is missing its local human verification proof");let c=await p6({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});await ky({pairing:r,code:c.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}})}o+1<n&&await eAt(i(e.delayMs??3e3),e.signal)}return{status:"not_ready",protocolVersion:jt,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:nAt(r,(e.now??Date.now)())}}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}async function BPe(e){if(typeof e!="string"||e.trim().length===0)return!1;try{return await pn.saveSessionToken(e),!0}catch{return!1}}var VU=k(()=>{"use strict";W_();x0();dM()});var One={};Oi(One,{CardDrawRefusedError:()=>y6,cardDrawIntentHash:()=>SOe,decimalUsdToCents:()=>Cne,fetchCardDrawVerdict:()=>gAt,loadCardMandateCapability:()=>yAt,registerCardMandate:()=>bAt});function lAt(e){if(e.kty!=="OKP")throw new Error(`computeJkt expects an OKP JWK; got kty="${e.kty}"`);let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return(0,Pne.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function pAt(e){let{secretKey:t,publicKey:r}=PIe(e),n=G_(t),i=by(r);return{privateJwk:n,publicJwk:i,jkt:lAt(i)}}async function AOe(e,t){let n={cnf:{jwk:{kty:e.publicJwk.kty,crv:e.publicJwk.crv,x:e.publicJwk.x}},nonce:t.nonce,aud:t.audience,iat:t.nowSec};t.intentHash!==void 0&&(n.int=t.intentHash);let i={alg:"EdDSA",kid:e.jkt,typ:dAt},o=`${wOe(i)}.${wOe(n)}`,s=a8(e.privateJwk),a=gy(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function xOe(e){let{amount:t,currency:r,payee:n,intentId:i}=e;if(!Number.isSafeInteger(t)||t<=0)throw new Error(`intent.amount must be a positive safe integer in minor units (cents); got ${String(t)}`);let o=typeof r=="string"?r.toUpperCase():"";if(!fAt.has(o))throw new Error(`intent.currency must be a supported ISO 4217 code; got ${JSON.stringify(r)}`);if(typeof n!="string"||n.length===0)throw new Error("intent.payee must be a non-empty string");if(i!==void 0&&(typeof i!="string"||i.length===0))throw new Error("intent.intentId, when present, must be a non-empty string");let s=JSON.stringify({v:mAt,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,Pne.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function hAt(e){let t=e.split(".");if(t.length!==3)return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return typeof r.mode=="string"?r.mode:null}catch{return null}}function Cne(e){let t=/^([0-9]+)(?:\.([0-9]{1,2}))?$/.exec(e);if(!t)return null;let r=Number(t[1]),n=Number(((t[2]??"")+"00").slice(0,2)),i=r*100+n;return Number.isSafeInteger(i)?i:null}function SOe(e,t){let r=Cne(e.amount);return r===null?null:xOe({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function yAt(e={}){let r=(e.record!==void 0?e.record?[e.record]:[]:e.records??(u6(),ie(CCe)).listLegacyAgentRecords()).flatMap(i=>{if(!i.binding_jwt||!i.auth_url)return[];let o=hAt(i.binding_jwt);if(o!=="card"&&o!=="both")return[];let s;try{s=pAt(a8(i.private_key_jwk))}catch{return[]}return s.jkt!==i.agent_jkt?[]:[{record:i,capability:{agentKey:s,agentJkt:i.agent_jkt,authBaseUrl:i.auth_url}}]}),n=e.agentRef?.trim();if(n){let i=n.replace(/\.visa$/i,"").toLowerCase(),o=r.filter(({record:s})=>s.agent_jkt===n||s.name.replace(/\.visa$/i,"").toLowerCase()===i);if(o.length>1)throw new Error(`more than one card capability is named "${n}"; select the exact request-key JKT`);return o[0]?.capability??null}if(r.length>1)throw new Error("more than one card-capable agent is available; select one explicitly with --agent (name or request-key JKT)");return r[0]?.capability??null}async function EM(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(new Error(`card authority request timed out after ${EOe}ms`)),EOe);i.unref?.();try{return await e(t,{...r,redirect:"error",signal:n.signal})}finally{clearTimeout(i)}}function TOe(e){return e.replace(/\/+$/,"")}async function gAt(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=TOe(e.authBaseUrl),i=SOe(e.draw,e.drawId);if(i===null)throw new y6(400,["invalid_amount"]);let o=await EM(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new y6(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new y6(502,["challenge_malformed"]);let a=await AOe(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await EM(t,`${n}/v4/card/draw-verdict`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"},body:JSON.stringify({nonce:s.nonce,popJwt:a,mandateId:e.mandateId,drawId:e.drawId,draw:e.draw})}),u=await c.json().catch(()=>null);if(!c.ok||!u?.ok||typeof u.verdict!="string")throw new y6(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function bAt(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=TOe(e.authBaseUrl),i=Cne(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=xOe({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await EM(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!s.ok)return{ok:!1,reason:"challenge_failed"};let a=await s.json();if(!a.nonce||!a.audience)return{ok:!1,reason:"challenge_malformed"};let c=await AOe(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await EM(t,`${n}/v4/card/mandate/register`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"},body:JSON.stringify({nonce:a.nonce,popJwt:c,mandateId:e.mandateId,mintToken:e.mintToken})}),d=await u.json().catch(()=>null);return!u.ok||!d?.ok?{ok:!1,reason:d?.reasons?.[0]??"register_refused"}:{ok:!0}}catch(t){return{ok:!1,reason:t instanceof Error?t.message:String(t)}}}var Pne,dAt,wOe,fAt,mAt,y6,EOe,kne=k(()=>{"use strict";Pne=require("node:crypto");W_();dAt="visa-agent-pop+jwt",wOe=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");fAt=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),mAt=1;y6=class extends Error{constructor(r,n){super(`card draw refused (${r}): ${n.join(", ")||"unknown"}`);this.status=r;this.reasons=n;this.name="CardDrawRefusedError"}status;reasons},EOe=3e4});var tRe=g(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});Kl.formatCents=eRe;Kl.formatUsd=FSt;Kl.formatMicros=$M;Kl.formatMicrosWire=VSt;Kl.formatTxAmount=KSt;Kl.formatDate=GSt;Kl.formatRelativeTime=WSt;Kl.formatTime=JSt;Kl.formatAge=YSt;var Qke=1e6,$St=100;function eRe(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let i=(e/$St).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function FSt(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let n=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${n}`:n}function $M(e,t={}){let r=t.fallback??"\u2014",n=typeof e=="string"?e===""?null:Number(e):e;if(n==null||!Number.isFinite(n))return r;let o=(n/Qke).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&n>0?`+${o}`:o}function VSt(e,t,r={}){return e&&/^-?\d+$/.test(e)?$M(e,r):t!=null&&Number.isFinite(t)?eRe(t,r):r.fallback??"\u2014"}function KSt(e,t={}){let r=Number(e.amount_micros);if(Number.isFinite(r)&&e.amount_micros!=null&&e.amount_micros!=="")return $M(r,t);let n=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(n)?$M(n*Qke,t):t.fallback??"\u2014"}function GSt(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function WSt(e,t=Date.now()){if(!e)return"\u2014";let r=Date.parse(e);if(Number.isNaN(r))return"\u2014";let n=t-r,i=n>=0,o=Math.abs(n),s=Math.floor(o/1e3),a=Math.floor(s/60),c=Math.floor(a/60),u=Math.floor(c/24),d=Math.floor(u/7),l=Math.floor(u/30),p=Math.floor(u/365);return s<45?"just now":a<1?i?"a minute ago":"in a minute":a<60?V8(n,i,a,"minute"):c<24?V8(n,i,c,"hour"):u===1?i?"yesterday":"tomorrow":u<7?V8(n,i,u,"day"):d<4?V8(n,i,d,"week"):l<12?V8(n,i,l,"month"):V8(n,i,p,"year")}function V8(e,t,r,n){let i=r!==1?"s":"";return t?`${r} ${n}${i} ago`:`in ${r} ${n}${i}`}function JSt(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}function YSt(e,t){if(!e)return"";let r=Date.parse(e);if(Number.isNaN(r))return"";let n=Math.max(0,t-r),i=Math.floor(n/1e3);if(i<45)return"just now";let o=Math.floor(i/60);if(o<60)return`${o}m ago`;let s=Math.floor(o/60);if(s<24)return`${s}h ago`;let a=Math.floor(s/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 K8=g(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.formatAge=Qt.formatTime=Qt.formatRelativeTime=Qt.formatDate=Qt.formatTxAmount=Qt.formatMicrosWire=Qt.formatMicros=Qt.formatUsd=Qt.formatCents=void 0;Qt.micros=ZSt;Qt.fromCents=XSt;Qt.fromUsdc=QSt;Qt.fromUsd=eTt;Qt.toCents=tTt;Qt.toCentsForAcquirer=rTt;Qt.toUsdc=nTt;Qt.toWire=iTt;Qt.fromWire=oTt;Qt.toDisplay=sTt;Qt.toUsdRounded2dp=aTt;Qt.add=cTt;Qt.sub=uTt;Qt.clampNonNegative=dTt;Qt.isNonNegative=lTt;Qt.max=pTt;Qt.min=fTt;var W0=10000n,rRe=1000000n;function ZSt(e){return e}function XSt(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*W0}function QSt(e){return e}function eTt(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function tTt(e){if(e>=0n)return Number(e/W0);let t=e/W0,r=e%W0;return Number(r===0n?t:t-1n)}function rTt(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/W0)}function nTt(e){return e}function iTt(e){return e.toString()}function oTt(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 sTt(e,t={}){let r=t.decimals??2,n=t.symbol??"$",i=e<0n,o=i?-e:e,s=o/rRe,a=o%rRe,c=i?"-":"";if(r===0)return`${c}${n}${s.toString()}`;let u=a.toString().padStart(6,"0").slice(0,r);return`${c}${n}${s.toString()}.${u}`}function aTt(e){let t=e<0n,r=t?-e:e,n=r/W0,o=r%W0*2n,s;o<W0?s=n:o>W0?s=n+1n:s=n%2n===0n?n:n+1n;let a=Number(s)/100;return t?-a:a}function cTt(e,t){return e+t}function uTt(e,t){return e-t}function dTt(e){return e<0n?0n:e}function lTt(e){return e>=0n}function pTt(e,t){return e>t?e:t}function fTt(e,t){return e<t?e:t}var J0=tRe();Object.defineProperty(Qt,"formatCents",{enumerable:!0,get:function(){return J0.formatCents}});Object.defineProperty(Qt,"formatUsd",{enumerable:!0,get:function(){return J0.formatUsd}});Object.defineProperty(Qt,"formatMicros",{enumerable:!0,get:function(){return J0.formatMicros}});Object.defineProperty(Qt,"formatMicrosWire",{enumerable:!0,get:function(){return J0.formatMicrosWire}});Object.defineProperty(Qt,"formatTxAmount",{enumerable:!0,get:function(){return J0.formatTxAmount}});Object.defineProperty(Qt,"formatDate",{enumerable:!0,get:function(){return J0.formatDate}});Object.defineProperty(Qt,"formatRelativeTime",{enumerable:!0,get:function(){return J0.formatRelativeTime}});Object.defineProperty(Qt,"formatTime",{enumerable:!0,get:function(){return J0.formatTime}});Object.defineProperty(Qt,"formatAge",{enumerable:!0,get:function(){return J0.formatAge}})});var nie=g(hc=>{"use strict";var mTt=hc&&hc.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),hTt=hc&&hc.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),iRe=hc&&hc.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),i=0;i<n.length;i++)n[i]!=="default"&&mTt(r,t,n[i]);return hTt(r,t),r}})();Object.defineProperty(hc,"__esModule",{value:!0});hc.pruneResponsesDir=rie;hc.isTextualContentType=FM;hc.isValidUtf8=sRe;hc.spillFilename=aRe;hc.describePaidBody=eie;hc.capturePaidResponse=wTt;var Pf=iRe(require("fs")),JI=iRe(require("path")),yTt=require("node:crypto"),oRe=16*1024,Qne=2*1024,gTt=64*1024*1024,bTt=3e4,tie=256*1024*1024;function rie(e,t=tie,r){try{let n=r?JI.basename(r):null,i=Pf.readdirSync(e).map(s=>{if(s.includes(".part-"))return null;try{let a=Pf.statSync(JI.join(e,s));return a.isFile()?{name:s,size:a.size,mtime:a.mtimeMs}:null}catch{return null}}).filter(s=>s!==null).sort((s,a)=>s.name===n?-1:a.name===n?1:a.mtime-s.mtime),o=0;for(let s of i)if(o+=s.size,o>t&&s.name!==n)try{Pf.rmSync(JI.join(e,s.name),{force:!0})}catch{}}catch{}}var _Tt=new Set(["application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/csv"]);function FM(e){if(!e)return!1;let t=e.split(";",1)[0].trim().toLowerCase();return t.startsWith("text/")||t.endsWith("+json")||t.endsWith("+xml")||_Tt.has(t)}function sRe(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e),!0}catch{return!1}}var vTt={"application/json":".json","application/pdf":".pdf","audio/mpeg":".mp3","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/svg+xml":".svg","image/webp":".webp","text/csv":".csv","text/html":".html","text/plain":".txt","video/mp4":".mp4"};function aRe(e,t,r){let n="unknown-host";try{n=new URL(e).hostname.toLowerCase()}catch{}let i=n.replace(/[^a-z0-9.-]/g,"_").slice(0,80),o=(t??"").split(";",1)[0].trim().toLowerCase(),s=vTt[o]??(FM(t)?".txt":".bin");return`${r.toISOString().replace(/[:.]/g,"-")}-${i}${s}`}function cRe(e,t,r){let n=aRe(t,r,new Date),i=JI.extname(n),o=n.slice(0,n.length-i.length);return JI.join(e,`${o}-${(0,yTt.randomBytes)(8).toString("hex")}${i}`)}function uRe(e){Pf.mkdirSync(e,{recursive:!0,mode:448})}function nRe(e,t){let r=0;for(;r<t.length;){let n=Pf.writeSync(e,t,r,t.length-r,null);if(n<=0)throw new Error("Paid response file write made no progress.");r+=n}}function eie(e,t,r,n,i){let o=r?FM(r):sRe(n),s={status:t,contentType:r??"unknown",bodyBytes:n.length};if(n.length===0)return{...s,body:""};if(o&&n.length<=oRe)return{...s,body:n.toString("utf-8")};uRe(i);let a=cRe(i,e,r);return Pf.writeFileSync(a,n,{flag:"wx",mode:384}),rie(i,tie,a),{...s,bodyFile:a,...o?{bodyPreview:n.subarray(0,Qne).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}async function wTt(e,t,r,n={}){let i=n.maxBytes??gTt,o=n.timeoutMs??bTt;if(!Number.isSafeInteger(i)||i<=0)throw new Error("Paid response capture maxBytes must be a positive safe integer.");if(!Number.isFinite(o)||o<=0)throw new Error("Paid response capture timeoutMs must be positive.");let s=t.headers.get("content-length");if(s&&/^\d+$/.test(s.trim())){let b=Number(s);if(Number.isSafeInteger(b)&&b>i)throw t.body?.cancel("paid response exceeds capture limit").catch(()=>{}),new Error(`Merchant response body exceeds the ${i}-byte capture limit (declared ${b} bytes).`)}if(!t.body)return eie(e,t.status,t.headers.get("content-type"),Buffer.alloc(0),r);let a=t.body.getReader(),c=Date.now(),u=[],d=0,l=0,p=null,f=null,m=null,h=[],y=0,v=()=>{p!==null&&(Pf.closeSync(p),p=null)},E=()=>{if(v(),m)try{Pf.rmSync(m,{force:!0})}catch{}};try{for(;;){let A=o-(Date.now()-c);if(A<=0)throw new Error(`Merchant response body timed out after ${o}ms.`);let x,S=new Promise((C,U)=>{x=setTimeout(()=>U(new Error(`Merchant response body timed out after ${o}ms.`)),A)}),I;try{I=await Promise.race([a.read(),S])}finally{x&&clearTimeout(x)}if(I.done)break;let T=Buffer.from(I.value);if(l+=T.length,l>i)throw new Error(`Merchant response body exceeded the ${i}-byte capture limit.`);if(y<Qne){let C=T.subarray(0,Math.min(T.length,Qne-y));h.push(Buffer.from(C)),y+=C.length}if(p===null){if(u.push(T),d+=T.length,d<=oRe)continue;uRe(r),f=cRe(r,e,t.headers.get("content-type")),m=`${f}.part-${process.pid}-${Math.random().toString(16).slice(2)}`,p=Pf.openSync(m,"wx",384);for(let C of u)nRe(p,C);u.length=0,d=0}else nRe(p,T)}if(p===null){let A=Buffer.concat(u,d);return eie(e,t.status,t.headers.get("content-type"),A,r)}v(),Pf.renameSync(m,f),m=null,rie(r,tie,f);let b=t.headers.get("content-type"),w=b?FM(b):!1;return{status:t.status,contentType:b??"unknown",bodyBytes:l,bodyFile:f,...w?{bodyPreview:Buffer.concat(h).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}catch(b){throw a.cancel("paid response capture failed").catch(()=>{}),E(),b}finally{try{a.releaseLock()}catch{}}}});var zy=g(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.TURNKEY_API_BASE_URL_ENV=go.CIRCLE_TESTNET_FAUCET_URL=go.NETWORK_ENV=go.NETWORKS=void 0;go.resolveNetwork=ETt;go.turnkeyApiBaseUrl=xTt;go.explorerTxUrl=STt;go.explorerAddressUrl=TTt;go.NETWORKS={"base-mainnet":{id:"base-mainnet",caip2:"eip155:8453",chainId:8453,usdc:{address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",eip712Domain:{name:"USD Coin",version:"2"}},rpcUrl:"https://mainnet.base.org",explorerBaseUrl:"https://basescan.org",isTestnet:!1},"base-sepolia":{id:"base-sepolia",caip2:"eip155:84532",chainId:84532,usdc:{address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",eip712Domain:{name:"USDC",version:"2"}},rpcUrl:"https://sepolia.base.org",explorerBaseUrl:"https://sepolia.basescan.org",isTestnet:!0}};go.NETWORK_ENV="VISA_V4_NETWORK";go.CIRCLE_TESTNET_FAUCET_URL="https://faucet.circle.com";var dRe={"base-mainnet":"base-mainnet","base-sepolia":"base-sepolia","eip155:8453":"base-mainnet","eip155:84532":"base-sepolia"};function ETt(e=process.env){let t=(e[go.NETWORK_ENV]??"").trim();if(t==="")return go.NETWORKS["base-mainnet"];let r=dRe[t.toLowerCase()];if(!r)throw new Error(`unknown ${go.NETWORK_ENV} value ${JSON.stringify(t)} \u2014 valid values: `+Object.keys(dRe).join(", "));return go.NETWORKS[r]}go.TURNKEY_API_BASE_URL_ENV="TURNKEY_API_BASE_URL";var ATt="https://api.turnkey.com";function xTt(e=process.env){let t=(e[go.TURNKEY_API_BASE_URL_ENV]??"").trim();return t===""?ATt:t}function STt(e,t){return`${e.explorerBaseUrl}/tx/${t}`}function TTt(e,t){return`${e.explorerBaseUrl}/address/${t}`}});var lRe=g(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.version=void 0;VM.version="1.2.3"});var B6=g(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0});KM.BaseError=void 0;var ITt=lRe(),iie=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${ITt.version}`].join(`
197
197
  `);super(o),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.shortMessage=t}};KM.BaseError=iie});var pRe=g(oie=>{"use strict";Object.defineProperty(oie,"__esModule",{value:!0});oie.narrow=PTt;function PTt(e){return e}});var YI=g(Y0=>{"use strict";Object.defineProperty(Y0,"__esModule",{value:!0});Y0.isTupleRegex=Y0.integerRegex=Y0.bytesRegex=void 0;Y0.execTyped=CTt;function CTt(e,t){return e.exec(t)?.groups}Y0.bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;Y0.integerRegex=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;Y0.isTupleRegex=/^\(.+?\).*?$/});var cie=g(aie=>{"use strict";Object.defineProperty(aie,"__esModule",{value:!0});aie.formatAbiParameter=sie;var OTt=YI(),fRe=/^tuple(?<array>(\[(\d*)\])*)$/;function sie(e){let t=e.type;if(fRe.test(e.type)&&"components"in e){t="(";let r=e.components.length;for(let i=0;i<r;i++){let o=e.components[i];t+=sie(o),i<r-1&&(t+=", ")}let n=(0,OTt.execTyped)(fRe,e.type);return t+=`)${n?.array||""}`,sie({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}});var die=g(uie=>{"use strict";Object.defineProperty(uie,"__esModule",{value:!0});uie.formatAbiParameters=RTt;var kTt=cie();function RTt(e){let t="",r=e.length;for(let n=0;n<r;n++){let i=e[n];t+=(0,kTt.formatAbiParameter)(i),n!==r-1&&(t+=", ")}return t}});var pie=g(lie=>{"use strict";Object.defineProperty(lie,"__esModule",{value:!0});lie.formatAbiItem=NTt;var ZI=die();function NTt(e){return e.type==="function"?`function ${e.name}(${(0,ZI.formatAbiParameters)(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${(0,ZI.formatAbiParameters)(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${(0,ZI.formatAbiParameters)(e.inputs)})`:e.type==="error"?`error ${e.name}(${(0,ZI.formatAbiParameters)(e.inputs)})`:e.type==="constructor"?`constructor(${(0,ZI.formatAbiParameters)(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}});var mRe=g(fie=>{"use strict";Object.defineProperty(fie,"__esModule",{value:!0});fie.formatAbi=jTt;var BTt=pie();function jTt(e){let t=[],r=e.length;for(let n=0;n<r;n++){let i=e[n],o=(0,BTt.formatAbiItem)(i);t.push(o)}return t}});var j6=g(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.functionModifiers=Ri.eventModifiers=Ri.modifiers=void 0;Ri.isErrorSignature=UTt;Ri.execErrorSignature=MTt;Ri.isEventSignature=qTt;Ri.execEventSignature=DTt;Ri.isFunctionSignature=LTt;Ri.execFunctionSignature=zTt;Ri.isStructSignature=HTt;Ri.execStructSignature=$Tt;Ri.isConstructorSignature=FTt;Ri.execConstructorSignature=VTt;Ri.isFallbackSignature=KTt;Ri.execFallbackSignature=GTt;Ri.isReceiveSignature=JTt;var G8=YI(),hRe=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function UTt(e){return hRe.test(e)}function MTt(e){return(0,G8.execTyped)(hRe,e)}var yRe=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function qTt(e){return yRe.test(e)}function DTt(e){return(0,G8.execTyped)(yRe,e)}var gRe=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function LTt(e){return gRe.test(e)}function zTt(e){return(0,G8.execTyped)(gRe,e)}var bRe=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function HTt(e){return bRe.test(e)}function $Tt(e){return(0,G8.execTyped)(bRe,e)}var _Re=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function FTt(e){return _Re.test(e)}function VTt(e){return(0,G8.execTyped)(_Re,e)}var vRe=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function KTt(e){return vRe.test(e)}function GTt(e){return(0,G8.execTyped)(vRe,e)}var WTt=/^receive\(\) external payable$/;function JTt(e){return WTt.test(e)}Ri.modifiers=new Set(["memory","indexed","storage","calldata"]);Ri.eventModifiers=new Set(["indexed"]);Ri.functionModifiers=new Set(["calldata","memory","storage"])});var XI=g(Hy=>{"use strict";Object.defineProperty(Hy,"__esModule",{value:!0});Hy.UnknownSolidityTypeError=Hy.UnknownTypeError=Hy.InvalidAbiItemError=void 0;var gie=B6(),mie=class extends gie.BaseError{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}};Hy.InvalidAbiItemError=mie;var hie=class extends gie.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}};Hy.UnknownTypeError=hie;var yie=class extends gie.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}};Hy.UnknownSolidityTypeError=yie});var W8=g(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.InvalidAbiTypeParameterError=Ys.InvalidFunctionModifierError=Ys.InvalidModifierError=Ys.SolidityProtectedKeywordError=Ys.InvalidParameterError=Ys.InvalidAbiParametersError=Ys.InvalidAbiParameterError=void 0;var U6=B6(),bie=class extends U6.BaseError{constructor({param:t}){super("Failed to parse ABI parameter.",{details:`parseAbiParameter(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameter-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParameterError"})}};Ys.InvalidAbiParameterError=bie;var _ie=class extends U6.BaseError{constructor({params:t}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}};Ys.InvalidAbiParametersError=_ie;var vie=class extends U6.BaseError{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}};Ys.InvalidParameterError=vie;var wie=class extends U6.BaseError{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}};Ys.SolidityProtectedKeywordError=wie;var Eie=class extends U6.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}};Ys.InvalidModifierError=Eie;var Aie=class extends U6.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}};Ys.InvalidFunctionModifierError=Aie;var xie=class extends U6.BaseError{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}};Ys.InvalidAbiTypeParameterError=xie});var GM=g($y=>{"use strict";Object.defineProperty($y,"__esModule",{value:!0});$y.InvalidStructSignatureError=$y.UnknownSignatureError=$y.InvalidSignatureError=void 0;var Pie=B6(),Sie=class extends Pie.BaseError{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}};$y.InvalidSignatureError=Sie;var Tie=class extends Pie.BaseError{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}};$y.UnknownSignatureError=Tie;var Iie=class extends Pie.BaseError{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}};$y.InvalidStructSignatureError=Iie});var Oie=g(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0});WM.CircularReferenceError=void 0;var YTt=B6(),Cie=class extends YTt.BaseError{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}};WM.CircularReferenceError=Cie});var Rie=g(JM=>{"use strict";Object.defineProperty(JM,"__esModule",{value:!0});JM.InvalidParenthesisError=void 0;var ZTt=B6(),kie=class extends ZTt.BaseError{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};JM.InvalidParenthesisError=kie});var wRe=g(QI=>{"use strict";Object.defineProperty(QI,"__esModule",{value:!0});QI.parameterCache=void 0;QI.getParameterCacheKey=XTt;function XTt(e,t,r){let n="";if(r)for(let i of Object.entries(r)){if(!i)continue;let o="";for(let s of i[1])o+=`[${s.type}${s.name?`:${s.name}`:""}]`;n+=`(${i[0]}{${o}})`}return t?`${t}:${e}${n}`:`${e}${n}`}QI.parameterCache=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});var q6=g(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});wu.parseSignature=tIt;wu.parseFunctionSignature=ERe;wu.parseEventSignature=ARe;wu.parseErrorSignature=xRe;wu.parseConstructorSignature=SRe;wu.parseFallbackSignature=TRe;wu.parseAbiParameter=M6;wu.splitParameters=Pd;wu.isSolidityType=IRe;wu.isSolidityKeyword=PRe;wu.isValidDataLocation=CRe;var J8=YI(),QTt=XI(),YM=W8(),Y8=GM(),eIt=Rie(),ZM=wRe(),Pa=j6();function tIt(e,t={}){if((0,Pa.isFunctionSignature)(e))return ERe(e,t);if((0,Pa.isEventSignature)(e))return ARe(e,t);if((0,Pa.isErrorSignature)(e))return xRe(e,t);if((0,Pa.isConstructorSignature)(e))return SRe(e,t);if((0,Pa.isFallbackSignature)(e))return TRe(e);if((0,Pa.isReceiveSignature)(e))return{type:"receive",stateMutability:"payable"};throw new Y8.UnknownSignatureError({signature:e})}function ERe(e,t={}){let r=(0,Pa.execFunctionSignature)(e);if(!r)throw new Y8.InvalidSignatureError({signature:e,type:"function"});let n=Pd(r.parameters),i=[],o=n.length;for(let a=0;a<o;a++)i.push(M6(n[a],{modifiers:Pa.functionModifiers,structs:t,type:"function"}));let s=[];if(r.returns){let a=Pd(r.returns),c=a.length;for(let u=0;u<c;u++)s.push(M6(a[u],{modifiers:Pa.functionModifiers,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:i,outputs:s}}function ARe(e,t={}){let r=(0,Pa.execEventSignature)(e);if(!r)throw new Y8.InvalidSignatureError({signature:e,type:"event"});let n=Pd(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(M6(n[s],{modifiers:Pa.eventModifiers,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:i}}function xRe(e,t={}){let r=(0,Pa.execErrorSignature)(e);if(!r)throw new Y8.InvalidSignatureError({signature:e,type:"error"});let n=Pd(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(M6(n[s],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:i}}function SRe(e,t={}){let r=(0,Pa.execConstructorSignature)(e);if(!r)throw new Y8.InvalidSignatureError({signature:e,type:"constructor"});let n=Pd(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(M6(n[s],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:i}}function TRe(e){let t=(0,Pa.execFallbackSignature)(e);if(!t)throw new Y8.InvalidSignatureError({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}var rIt=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,nIt=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,iIt=/^u?int$/;function M6(e,t){let r=(0,ZM.getParameterCacheKey)(e,t?.type,t?.structs);if(ZM.parameterCache.has(r))return ZM.parameterCache.get(r);let n=J8.isTupleRegex.test(e),i=(0,J8.execTyped)(n?nIt:rIt,e);if(!i)throw new YM.InvalidParameterError({param:e});if(i.name&&PRe(i.name))throw new YM.SolidityProtectedKeywordError({param:e,name:i.name});let o=i.name?{name:i.name}:{},s=i.modifier==="indexed"?{indexed:!0}:{},a=t?.structs??{},c,u={};if(n){c="tuple";let l=Pd(i.type),p=[],f=l.length;for(let m=0;m<f;m++)p.push(M6(l[m],{structs:a}));u={components:p}}else if(i.type in a)c="tuple",u={components:a[i.type]};else if(iIt.test(i.type))c=`${i.type}256`;else if(i.type==="address payable")c="address";else if(c=i.type,t?.type!=="struct"&&!IRe(c))throw new QTt.UnknownSolidityTypeError({type:c});if(i.modifier){if(!t?.modifiers?.has?.(i.modifier))throw new YM.InvalidModifierError({param:e,type:t?.type,modifier:i.modifier});if(Pa.functionModifiers.has(i.modifier)&&!CRe(c,!!i.array))throw new YM.InvalidFunctionModifierError({param:e,type:t?.type,modifier:i.modifier})}let d={type:`${c}${i.array??""}`,...o,...s,...u};return ZM.parameterCache.set(r,d),d}function Pd(e,t=[],r="",n=0){let i=e.trim().length;for(let o=0;o<i;o++){let s=e[o],a=e.slice(o+1);switch(s){case",":return n===0?Pd(a,[...t,r.trim()]):Pd(a,t,`${r}${s}`,n);case"(":return Pd(a,t,`${r}${s}`,n+1);case")":return Pd(a,t,`${r}${s}`,n-1);default:return Pd(a,t,`${r}${s}`,n)}}if(r==="")return t;if(n!==0)throw new eIt.InvalidParenthesisError({current:r,depth:n});return t.push(r.trim()),t}function IRe(e){return e==="address"||e==="bool"||e==="function"||e==="string"||J8.bytesRegex.test(e)||J8.integerRegex.test(e)}var oIt=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function PRe(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||J8.bytesRegex.test(e)||J8.integerRegex.test(e)||oIt.test(e)}function CRe(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}});var e7=g(Nie=>{"use strict";Object.defineProperty(Nie,"__esModule",{value:!0});Nie.parseStructs=uIt;var ORe=YI(),sIt=XI(),aIt=W8(),kRe=GM(),cIt=Oie(),RRe=j6(),NRe=q6();function uIt(e){let t={},r=e.length;for(let s=0;s<r;s++){let a=e[s];if(!(0,RRe.isStructSignature)(a))continue;let c=(0,RRe.execStructSignature)(a);if(!c)throw new kRe.InvalidSignatureError({signature:a,type:"struct"});let u=c.properties.split(";"),d=[],l=u.length;for(let p=0;p<l;p++){let m=u[p].trim();if(!m)continue;let h=(0,NRe.parseAbiParameter)(m,{type:"struct"});d.push(h)}if(!d.length)throw new kRe.InvalidStructSignatureError({signature:a});t[c.name]=d}let n={},i=Object.entries(t),o=i.length;for(let s=0;s<o;s++){let[a,c]=i[s];n[a]=BRe(c,t)}return n}var dIt=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function BRe(e=[],t={},r=new Set){let n=[],i=e.length;for(let o=0;o<i;o++){let s=e[o];if(ORe.isTupleRegex.test(s.type))n.push(s);else{let c=(0,ORe.execTyped)(dIt,s.type);if(!c?.type)throw new aIt.InvalidAbiTypeParameterError({abiParameter:s});let{array:u,type:d}=c;if(d in t){if(r.has(d))throw new cIt.CircularReferenceError({type:d});n.push({...s,type:`tuple${u??""}`,components:BRe(t[d],t,new Set([...r,d]))})}else if((0,NRe.isSolidityType)(d))n.push(s);else throw new sIt.UnknownTypeError({type:d})}}return n}});var jRe=g(Bie=>{"use strict";Object.defineProperty(Bie,"__esModule",{value:!0});Bie.parseAbi=mIt;var lIt=j6(),pIt=e7(),fIt=q6();function mIt(e){let t=(0,pIt.parseStructs)(e),r=[],n=e.length;for(let i=0;i<n;i++){let o=e[i];(0,lIt.isStructSignature)(o)||r.push((0,fIt.parseSignature)(o,t))}return r}});var MRe=g(jie=>{"use strict";Object.defineProperty(jie,"__esModule",{value:!0});jie.parseAbiItem=bIt;var hIt=XI(),yIt=j6(),gIt=e7(),URe=q6();function bIt(e){let t;if(typeof e=="string")t=(0,URe.parseSignature)(e);else{let r=(0,gIt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,yIt.isStructSignature)(o)){t=(0,URe.parseSignature)(o,r);break}}}if(!t)throw new hIt.InvalidAbiItemError({signature:e});return t}});var DRe=g(Mie=>{"use strict";Object.defineProperty(Mie,"__esModule",{value:!0});Mie.parseAbiParameter=wIt;var _It=W8(),Uie=j6(),vIt=e7(),qRe=q6();function wIt(e){let t;if(typeof e=="string")t=(0,qRe.parseAbiParameter)(e,{modifiers:Uie.modifiers});else{let r=(0,vIt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,Uie.isStructSignature)(o)){t=(0,qRe.parseAbiParameter)(o,{modifiers:Uie.modifiers,structs:r});break}}}if(!t)throw new _It.InvalidAbiParameterError({param:e});return t}});var HRe=g(Die=>{"use strict";Object.defineProperty(Die,"__esModule",{value:!0});Die.parseAbiParameters=xIt;var EIt=W8(),qie=j6(),AIt=e7(),LRe=q6(),zRe=q6();function xIt(e){let t=[];if(typeof e=="string"){let r=(0,LRe.splitParameters)(e),n=r.length;for(let i=0;i<n;i++)t.push((0,zRe.parseAbiParameter)(r[i],{modifiers:qie.modifiers}))}else{let r=(0,AIt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if((0,qie.isStructSignature)(o))continue;let s=(0,LRe.splitParameters)(o),a=s.length;for(let c=0;c<a;c++)t.push((0,zRe.parseAbiParameter)(s[c],{modifiers:qie.modifiers,structs:r}))}}if(t.length===0)throw new EIt.InvalidAbiParametersError({params:e});return t}});var t7=g(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.CircularReferenceError=ft.InvalidParenthesisError=ft.UnknownSignatureError=ft.InvalidSignatureError=ft.InvalidStructSignatureError=ft.InvalidAbiParameterError=ft.InvalidAbiParametersError=ft.InvalidParameterError=ft.SolidityProtectedKeywordError=ft.InvalidModifierError=ft.InvalidFunctionModifierError=ft.InvalidAbiTypeParameterError=ft.UnknownSolidityTypeError=ft.InvalidAbiItemError=ft.UnknownTypeError=ft.parseAbiParameters=ft.parseAbiParameter=ft.parseAbiItem=ft.parseAbi=ft.formatAbiParameters=ft.formatAbiParameter=ft.formatAbiItem=ft.formatAbi=ft.narrow=ft.BaseError=void 0;var SIt=B6();Object.defineProperty(ft,"BaseError",{enumerable:!0,get:function(){return SIt.BaseError}});var TIt=pRe();Object.defineProperty(ft,"narrow",{enumerable:!0,get:function(){return TIt.narrow}});var IIt=mRe();Object.defineProperty(ft,"formatAbi",{enumerable:!0,get:function(){return IIt.formatAbi}});var PIt=pie();Object.defineProperty(ft,"formatAbiItem",{enumerable:!0,get:function(){return PIt.formatAbiItem}});var CIt=cie();Object.defineProperty(ft,"formatAbiParameter",{enumerable:!0,get:function(){return CIt.formatAbiParameter}});var OIt=die();Object.defineProperty(ft,"formatAbiParameters",{enumerable:!0,get:function(){return OIt.formatAbiParameters}});var kIt=jRe();Object.defineProperty(ft,"parseAbi",{enumerable:!0,get:function(){return kIt.parseAbi}});var RIt=MRe();Object.defineProperty(ft,"parseAbiItem",{enumerable:!0,get:function(){return RIt.parseAbiItem}});var NIt=DRe();Object.defineProperty(ft,"parseAbiParameter",{enumerable:!0,get:function(){return NIt.parseAbiParameter}});var BIt=HRe();Object.defineProperty(ft,"parseAbiParameters",{enumerable:!0,get:function(){return BIt.parseAbiParameters}});var Lie=XI();Object.defineProperty(ft,"UnknownTypeError",{enumerable:!0,get:function(){return Lie.UnknownTypeError}});Object.defineProperty(ft,"InvalidAbiItemError",{enumerable:!0,get:function(){return Lie.InvalidAbiItemError}});Object.defineProperty(ft,"UnknownSolidityTypeError",{enumerable:!0,get:function(){return Lie.UnknownSolidityTypeError}});var D6=W8();Object.defineProperty(ft,"InvalidAbiTypeParameterError",{enumerable:!0,get:function(){return D6.InvalidAbiTypeParameterError}});Object.defineProperty(ft,"InvalidFunctionModifierError",{enumerable:!0,get:function(){return D6.InvalidFunctionModifierError}});Object.defineProperty(ft,"InvalidModifierError",{enumerable:!0,get:function(){return D6.InvalidModifierError}});Object.defineProperty(ft,"SolidityProtectedKeywordError",{enumerable:!0,get:function(){return D6.SolidityProtectedKeywordError}});Object.defineProperty(ft,"InvalidParameterError",{enumerable:!0,get:function(){return D6.InvalidParameterError}});Object.defineProperty(ft,"InvalidAbiParametersError",{enumerable:!0,get:function(){return D6.InvalidAbiParametersError}});Object.defineProperty(ft,"InvalidAbiParameterError",{enumerable:!0,get:function(){return D6.InvalidAbiParameterError}});var zie=GM();Object.defineProperty(ft,"InvalidStructSignatureError",{enumerable:!0,get:function(){return zie.InvalidStructSignatureError}});Object.defineProperty(ft,"InvalidSignatureError",{enumerable:!0,get:function(){return zie.InvalidSignatureError}});Object.defineProperty(ft,"UnknownSignatureError",{enumerable:!0,get:function(){return zie.UnknownSignatureError}});var jIt=Rie();Object.defineProperty(ft,"InvalidParenthesisError",{enumerable:!0,get:function(){return jIt.InvalidParenthesisError}});var UIt=Oie();Object.defineProperty(ft,"CircularReferenceError",{enumerable:!0,get:function(){return UIt.CircularReferenceError}})});var sr=g(Hie=>{"use strict";Object.defineProperty(Hie,"__esModule",{value:!0});Hie.getAction=MIt;function MIt(e,t,r){let n=e[t.name];if(typeof n=="function")return n;let i=e[r];return typeof i=="function"?i:o=>t(e,o)}});var Cf=g(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0});XM.formatAbiItem=DIt;XM.formatAbiParams=$ie;var qIt=Hn();function DIt(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new qIt.InvalidDefinitionTypeError(e.type);return`${e.name}(${$ie(e.inputs,{includeName:t})})`}function $ie(e,{includeName:t=!1}={}){return e?e.map(r=>LIt(r,{includeName:t})).join(t?", ":","):""}function LIt(e,{includeName:t}){return e.type.startsWith("tuple")?`(${$ie(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}});var ps=g(Fie=>{"use strict";Object.defineProperty(Fie,"__esModule",{value:!0});Fie.isHex=zIt;function zIt(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}});var fs=g(Vie=>{"use strict";Object.defineProperty(Vie,"__esModule",{value:!0});Vie.size=$It;var HIt=ps();function $It(e){return(0,HIt.isHex)(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}});var $Re=g(QM=>{"use strict";Object.defineProperty(QM,"__esModule",{value:!0});QM.version=void 0;QM.version="2.54.6"});var Ct=g(r7=>{"use strict";Object.defineProperty(r7,"__esModule",{value:!0});r7.BaseError=void 0;r7.setErrorConfig=FIt;var FRe=$Re(),eq={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${FRe.version}`};function FIt(e){eq=e}var Kie=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=eq.getDocsUrl?.({...r,docsPath:i}),s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...o?[`Docs: ${o}`]:[],...n?[`Details: ${n}`]:[],...eq.version?[`Version: ${eq.version}`]:[]].join(`
198
198
  `);super(s,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=FRe.version}walk(t){return VRe(this,t)}};r7.BaseError=Kie;function VRe(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?VRe(e.cause,t):t?null:e}});var Hn=g(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.UnsupportedPackedAbiType=lt.InvalidDefinitionTypeError=lt.InvalidArrayError=lt.InvalidAbiDecodingTypeError=lt.InvalidAbiEncodingTypeError=lt.DecodeLogTopicsMismatch=lt.DecodeLogDataMismatch=lt.BytesSizeMismatchError=lt.AbiItemAmbiguityError=lt.AbiFunctionSignatureNotFoundError=lt.AbiFunctionOutputsNotFoundError=lt.AbiFunctionNotFoundError=lt.AbiEventNotFoundError=lt.AbiEventSignatureNotFoundError=lt.AbiEventSignatureEmptyTopicsError=lt.AbiErrorSignatureNotFoundError=lt.AbiErrorNotFoundError=lt.AbiErrorInputsNotFoundError=lt.AbiEncodingLengthMismatchError=lt.AbiEncodingBytesSizeMismatchError=lt.AbiEncodingArrayLengthMismatchError=lt.AbiDecodingZeroDataError=lt.AbiDecodingDataSizeTooSmallError=lt.AbiDecodingDataSizeInvalidError=lt.AbiConstructorParamsNotFoundError=lt.AbiConstructorNotFoundError=void 0;var n7=Cf(),VIt=fs(),fn=Ct(),Gie=class extends fn.BaseError{constructor({docsPath:t}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
199
199
  `),{docsPath:t,name:"AbiConstructorNotFoundError"})}};lt.AbiConstructorNotFoundError=Gie;var Wie=class extends fn.BaseError{constructor({docsPath:t}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
@@ -20924,7 +20924,7 @@ ${n}
20924
20924
  `),LT(zT(),n+`
20925
20925
  `)}catch{}}function MSe(e){try{let t=Nj();if(!t)return;let r=Math.max(Date.now(),t.renderedAt+1),n={...t,refreshFailedAt:r,refreshErrorReason:DT(e).slice(0,200)};LT(U_(),JSON.stringify(n)+`
20926
20926
  `)}catch{}}function j_(){try{Ar.unlinkSync(OSe())}catch{}}function Nj(){let e=U_();if(!Ar.existsSync(e))return null;try{return JSON.parse(Ar.readFileSync(e,"utf-8"))}catch{return null}}function qSe(){return Nj()?.status??null}function Svt(){if(process.env.JEST_WORKER_ID)return;let e=OSe();try{if(Ar.mkdirSync(Kr.dirname(e),{recursive:!0}),!Ovt(e))return;let t=process.argv[1]?Kr.resolve(process.argv[1]):"";if(!t){j_();return}let r=Pj(),n=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),i=r==="no-color"||n==="light"||n==="dark"?{}:{VISA_CLI_HUD_THEME:r},o=(0,PSe.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...i,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});o.once("error",j_),o.unref()}catch{j_()}}function DT(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 Tvt=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function Ivt(e){let t=[],r=`__VISA_CLI_HUD_SGR_${(0,Bee.randomBytes)(8).toString("hex")}_`,n=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!Tvt.test(o))return"";let s=`${r}${t.length}__`;return t.push(o),s}),i=new RegExp(`${r}(\\d+)__`,"g");return DT(n).replace(i,(o,s)=>t[Number(s)]??"")}var ac={get reset(){return zs().reset},get visaBlue(){return zs().visaBlue},get visaBlueSoft(){return zs().visaBlueSoft},get visaGold(){return zs().visaGold},get green(){return zs().green},get muted(){return zs().muted},get chrome(){return zs().chrome}};function gu(e,t){return e.length===0||process.env.NO_COLOR||Cj()?e:`${t}${e}${ac.reset}`}function ISe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qee(){let e=M_.homedir();if(!e||!Kr.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Kr.resolve(e)}function Pvt(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Cvt(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Ovt(e){for(let t=0;t<2;t+=1){let r;try{return r=Ar.openSync(e,"wx"),Ar.writeFileSync(r,String(Date.now())),!0}catch(n){if(n?.code!=="EEXIST")return!1;try{let i=Ar.statSync(e);if(Date.now()-i.mtimeMs<=hvt)return!1;Ar.unlinkSync(e)}catch{}}finally{r!==void 0&&Ar.closeSync(r)}}return!1}function Nee(e){return e instanceof Error?e.message:"unknown file system error"}function LT(e,t){Ar.mkdirSync(Kr.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${(0,Bee.randomBytes)(8).toString("hex")}.tmp`;try{Ar.writeFileSync(r,t),Ar.renameSync(r,e)}catch(n){try{Ar.unlinkSync(r)}catch{}throw n}}var kvt=1440*60*1e3;function jj(e,t){ko.mkdirSync(Sa.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${zSe.randomBytes(8).toString("hex")}.tmp`;try{ko.writeFileSync(r,JSON.stringify(t,null,2)+`
20927
- `),ko.renameSync(r,e)}catch(n){try{ko.unlinkSync(r)}catch{}throw n}}function DSe(e){return`'${e.replace(/'/g,"'\\''")}'`}var Lee="# visa-cli-hud-v1";function Uj(e,t){if(!e&&!t&&Rvt())return`visa-cli config statusline ${Lee}`;let r=e??process.execPath,n=t??process.argv[1]??"",i=n?Sa.resolve(n):"";return`${i?`${DSe(r)} ${DSe(i)} config statusline`:"visa-cli config statusline"} ${Lee}`}function Rvt(){try{return(0,HSe.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function cy(e){return typeof e!="string"?!1:e.includes(Lee)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Nvt(){return"4.1.0-rc.58"}function Mj(e){let t=Sa.dirname(Sa.resolve(e));return Sa.basename(t)===".claude"?Sa.dirname(t):$Se.homedir()}function Bj(e,t){let r=Sa.relative(t,e);return!r.startsWith("..")&&!Sa.isAbsolute(r)?`~/${r}`:e}function Bvt(e){return Sa.join(Mj(e),".visa-cli","hud-self-heal.json")}function jvt(e,t,r,n){try{if(!ko.existsSync(e))return!1;let i=JSON.parse(ko.readFileSync(e,"utf-8"));return i.version===t&&typeof i.checkedAt=="number"&&r-i.checkedAt<n}catch{return!1}}function Dee(e,t,r){try{jj(e,{version:t,checkedAt:r})}catch{}}function Uvt(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function qj(e,t={}){let r=t.now??Date.now(),n=t.version??Nvt(),i=t.stampPath??Bvt(e),o=t.minIntervalMs??kvt,s=[],a=!1,c=!1;if(!t.force&&jvt(i,n,r,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:s,skippedReason:"recently checked"};try{if(!ko.existsSync(e))return Dee(i,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s};let u=JSON.parse(ko.readFileSync(e,"utf-8")),d=u.statusLine,l=d&&typeof d=="object"&&!Array.isArray(d)?d.command:"";if(!cy(l))return Dee(i,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s};let p=(t.getCommand??Uj)();if(l!==p&&(u.statusLine=Uvt(d,p),jj(e,u),a=!0,s.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!Dj()){let f=Mj(e);if(q_(f).length>0){let h=S0(null,f);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let y=h.rcPaths.map(v=>Bj(v,f)).join(", ");c=!0,s.push(`Cleaned legacy shell-prompt HUD block from ${y}.`)}}}return Dee(i,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s}}catch(u){if(t.force){let d=u instanceof Error?u.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${d}. Run: visa-cli config hud doctor
20927
+ `),ko.renameSync(r,e)}catch(n){try{ko.unlinkSync(r)}catch{}throw n}}function DSe(e){return`'${e.replace(/'/g,"'\\''")}'`}var Lee="# visa-cli-hud-v1";function Uj(e,t){if(!e&&!t&&Rvt())return`visa-cli config statusline ${Lee}`;let r=e??process.execPath,n=t??process.argv[1]??"",i=n?Sa.resolve(n):"";return`${i?`${DSe(r)} ${DSe(i)} config statusline`:"visa-cli config statusline"} ${Lee}`}function Rvt(){try{return(0,HSe.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function cy(e){return typeof e!="string"?!1:e.includes(Lee)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Nvt(){return"4.1.0-rc.59"}function Mj(e){let t=Sa.dirname(Sa.resolve(e));return Sa.basename(t)===".claude"?Sa.dirname(t):$Se.homedir()}function Bj(e,t){let r=Sa.relative(t,e);return!r.startsWith("..")&&!Sa.isAbsolute(r)?`~/${r}`:e}function Bvt(e){return Sa.join(Mj(e),".visa-cli","hud-self-heal.json")}function jvt(e,t,r,n){try{if(!ko.existsSync(e))return!1;let i=JSON.parse(ko.readFileSync(e,"utf-8"));return i.version===t&&typeof i.checkedAt=="number"&&r-i.checkedAt<n}catch{return!1}}function Dee(e,t,r){try{jj(e,{version:t,checkedAt:r})}catch{}}function Uvt(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function qj(e,t={}){let r=t.now??Date.now(),n=t.version??Nvt(),i=t.stampPath??Bvt(e),o=t.minIntervalMs??kvt,s=[],a=!1,c=!1;if(!t.force&&jvt(i,n,r,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:s,skippedReason:"recently checked"};try{if(!ko.existsSync(e))return Dee(i,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s};let u=JSON.parse(ko.readFileSync(e,"utf-8")),d=u.statusLine,l=d&&typeof d=="object"&&!Array.isArray(d)?d.command:"";if(!cy(l))return Dee(i,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s};let p=(t.getCommand??Uj)();if(l!==p&&(u.statusLine=Uvt(d,p),jj(e,u),a=!0,s.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!Dj()){let f=Mj(e);if(q_(f).length>0){let h=S0(null,f);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let y=h.rcPaths.map(v=>Bj(v,f)).join(", ");c=!0,s.push(`Cleaned legacy shell-prompt HUD block from ${y}.`)}}}return Dee(i,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s}}catch(u){if(t.force){let d=u instanceof Error?u.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${d}. Run: visa-cli config hud doctor
20928
20928
  `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s}}}function Mvt(e,t){let r=Mj(t),n=q_(r);if(n.length===0)return e;let i=n.map(o=>Bj(o,r)).join(", ");return`${e}
20929
20929
  Note: a shell-prompt HUD block was detected in ${i}. If it is unintended, remove it with: visa-cli config hud disable shell`}function Dj(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 LSe(e,t){let r=Mj(t),n=q_(r);if(n.length===0)return e;let i=n.map(s=>Bj(s,r)).join(", ");if(Dj())return`${e}
20930
20930
  Note: a legacy shell-prompt HUD block was detected in ${i}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let o=S0(null,r);if(o.removed&&o.rcPaths&&o.rcPaths.length>0){let s=o.rcPaths.map(a=>Bj(a,r)).join(", ");return`${e}
@@ -20934,8 +20934,8 @@ Note: a legacy shell-prompt HUD block was detected in ${i} but could not be auto
20934
20934
  `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...Lvt([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${zee(e.daily_cap_cents)}/day`],["Total cap",ZSe(e.total_cap_cents)],["Allowed tools",XSe(e.allowed_tools)]]),"","Guardrails",`- Spend: ${zee(e.daily_cap_cents)}/day, ${ZSe(e.total_cap_cents)} total`,`- Tools: ${XSe(e.allowed_tools)}`,"- Auth: X-Api-Key header for supported v4 services","Save this key now - it won't be shown again."];return e.biometric_warning?r.push("",QSe,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",QSe),`${r.join(`
20935
20935
  `)}
20936
20936
  `}function tTe(e){return e.json===!0||e.isTTY!==!0}function Hee(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 r=Math.round(t*100);if(r<100||r>1e4)throw new Error("--daily-cap must be between 1 and 100 USD.");return r}function $ee(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 r=Math.round(t*100);if(r<100||r>1e6)throw new Error("--total-cap must be between 1 and 10000 USD.");return r}function rTe(e,t){let r=Hee(e);if(r!==void 0)return r;if(tTe(t))return 500}function nTe(e,t){let r=$ee(e);if(r!==void 0)return r;if(tTe(t)||t.recommendedCapsAccepted===!0)return 2500}e8();e8();Wj();var tte=require("child_process"),MTe=require("util"),qTe=_e(require("crypto")),tn=_e(require("fs")),DTe=_e(require("os")),Hs=_e(require("path"));yd();gj();x0();var I0=(0,MTe.promisify)(tte.execFile),l5t=6e4,p5t=()=>process.platform==="darwin",t8=()=>process.platform==="win32",fy=Hs.join(DTe.homedir(),".visa-mcp","bin"),z_=Hs.join(fy,"Visa CLI"),T0=Hs.join(fy,"visa-keychain-win.exe"),LTe=Hs.join(__dirname,"..","native"),PTe="6",CTe=Hs.join(fy,"visa-keychain.version"),OTe=Hs.join(fy,"visa-keychain.sha256"),kTe="1",RTe=Hs.join(fy,"visa-keychain-win.version"),NTe=Hs.join(fy,"visa-keychain-win.sha256"),zTe=[Hs.join(LTe,"bin","win32-x64","visa-keychain-win.exe"),Hs.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),Hs.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Jj(e){let t=tn.readFileSync(e);return qTe.createHash("sha256").update(t).digest("hex")}function f5t(e){let t=e.trim();if(t.startsWith("OK:"))return t.slice(3);if(t==="OK")return;let r=t.startsWith("ERROR:")?t.slice(6):"Unknown error";throw new Error(r)}function BTe(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function jTe(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 HTe(){try{if(tn.readFileSync(CTe,"utf-8").trim()===PTe&&tn.existsSync(z_)){let n=tn.readFileSync(OTe,"utf-8").trim();if(Jj(z_)!==n)ke.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),tn.unlinkSync(z_);else return z_}}catch{}let e=Hs.join(LTe,"visa-keychain.m");if(tn.existsSync(e)||(e=Hs.resolve(__dirname,"..","..","native","visa-keychain.m")),tn.existsSync(e)||(e=Hs.resolve(__dirname,"..","native","visa-keychain.m")),!tn.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");tn.mkdirSync(fy,{recursive:!0,mode:448});try{await I0("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",z_,e],{timeout:3e4})}catch(r){throw r.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):r}let t=Jj(z_);return tn.writeFileSync(OTe,t,{mode:384}),tn.writeFileSync(CTe,PTe,{mode:384}),z_}function $Te(){for(let e of zTe)if(tn.existsSync(e))return e;return null}async function Xj(){try{if(tn.readFileSync(RTe,"utf-8").trim()===kTe&&tn.existsSync(T0)){let n=tn.readFileSync(NTe,"utf-8").trim();if(Jj(T0)!==n)ke.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),tn.unlinkSync(T0);else return T0}}catch{}let e=$Te();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
20937
- If building from source, run native/build-win.bat first.`);tn.mkdirSync(fy,{recursive:!0}),tn.copyFileSync(e,T0);let t=Jj(T0);return tn.writeFileSync(NTe,t,{mode:384}),tn.writeFileSync(RTe,kTe,{mode:384}),T0}async function m5t(){return t8()?Xj():HTe()}var Yj="visa-cli",Zj="attestation-key";async function h5t(e){if(!await lf())throw new Error("macOS Keychain is unavailable in this environment (no default keychain), so the Touch ID key cannot be stored. Run this command in a regular user session.");try{await I0("security",["delete-generic-password","-s",Yj,"-a",Zj],{timeout:5e3})}catch{}try{await I0("security",["add-generic-password","-s",Yj,"-a",Zj,"-w",e],{timeout:5e3})}catch(t){throw new Error(`Could not store the Touch ID key in the macOS Keychain (${y5t(t)}).`)}}function y5t(e){let t=e,r=[t?.stderr,t?.message].filter(n=>typeof n=="string").join(" ").toLowerCase();return/canceled|cancelled/.test(r)?"the Keychain authorization was canceled":/locked/.test(r)?"the Keychain is locked":/not permitted|permission denied|not authorized/.test(r)?"Keychain access was denied":/could not be found|no default keychain/.test(r)?"no default keychain was found":"the security tool reported an error"}function g5t(e){let t=typeof e?.code=="number"?e.code:void 0,r=typeof e?.stderr=="string"?e.stderr:"",n=typeof e?.stdout=="string"?e.stdout:"",i=[r,n,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(i)?{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(i)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:i||"Could not read the local attestation key from Keychain."}}async function b5t(){if(!await lf())return{key:null,status:{state:"denied",usable:!1,message:"macOS Keychain is unavailable in this environment (no default keychain)."}};try{let{stdout:e}=await I0("security",["find-generic-password","-s",Yj,"-a",Zj,"-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:g5t(e)}}}async function _5t(){let e=await b5t();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 FTe(e){let t=await m5t(),r;try{r=(await I0(t,e,{timeout:6e4})).stdout}catch(n){r=n.stdout||"";let i=r.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(n.stderr?.toString().trim()||n.message||"Unknown error")}return f5t(r)}var UTe=!1;function v5t(){if(!t8())return!1;try{return tn.existsSync(T0)||$Te()!==null?!0:(UTe||(UTe=!0,ke.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:T0,searchedPrebuiltPaths:zTe})),!1)}catch{return!1}}function P0(){return BT()||p5t()?!0:t8()?v5t():!1}async function VTe(){if(t8()){let i=await Xj(),{stdout:o}=await I0(i,["generate-key"],{timeout:3e4}),s=o.trim();if(s.startsWith("OK:"))return s.slice(3);throw new Error(s.startsWith("ERROR:")?s.slice(6):"Key generation failed")}let e=await FTe(["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 r=e.slice(0,t),n=e.slice(t+1);return await h5t(r),n}async function rte(e,t,r={}){if(BT())return Promise.resolve(sSe());let n=r.timeoutMs??l5t;if(t8()){let a=await Xj(),c=["sign",e];t&&c.push(t);let u;try{u=(await I0(a,c,{timeout:n})).stdout}catch(l){throw BTe(l)?jTe(n):l}let d=u.trim();if(d.startsWith("OK:"))return d.slice(3);throw new Error(d.startsWith("ERROR:")?d.slice(6):"Unknown error")}let i=await _5t();if(!i)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await HTe(),s=["sign",e];return t&&s.push(t),new Promise((a,c)=>{let u=(0,tte.execFile)(o,s,{timeout:n},(d,l)=>{let p=(l||"").trim();if(d){p.startsWith("ERROR:")?c(new Error(p.slice(6))):BTe(d)?c(jTe(n)):c(new Error(d.stderr?.toString().trim()||d.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):c(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});u.stdin.write(i),u.stdin.end()})}async function Qj(){if(t8()){try{let e=await Xj();await I0(e,["delete-key"],{timeout:1e4})}catch{}return}if(await lf())try{await I0("security",["delete-generic-password","-s",Yj,"-a",Zj],{timeout:5e3})}catch{}try{await FTe(["delete-key"])}catch{}}x0();yd();Tj();VU();u6();var qke=require("child_process"),DM=_e(require("fs")),LM=_e(require("os")),Dke=_e(require("path"));FT();ly();gj();var hOe="4.1.0-rc.58";function Tne(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function iAt(e,t,r){let n=process.env[e];if(n!==void 0)return{value:r==="opt-in"?n==="true":n!=="false",source:{kind:"env",var:e}};let i=Zee(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function T8(e){return e==null?"\u2014":e?"yes":"no"}async function CI(e){let t=null,r=null;try{t=await e.api.getStatus()}catch(l){r=l?.message||"unknown error"}let n=[],i=process.env.VISA_AUTH_URL,o=Yee("auth.serverUrl"),s=Ta(),a=i!==void 0&&i!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};n.push({key:"auth.serverUrl",value:s,formatted:s,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}),n.push({key:"account.enrolled",value:t?.enrolled??null,formatted:T8(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),t?.login&&n.push({key:"account.principal",value:t.login,formatted:t.principalKind?`${t.login} (${t.principalKind})`:t.login,source:{kind:"server"},hint:"The identity your CLI session resolves on. Feature-flag access (checkout, mandate) is granted per this exact principal."}),t?.userId&&n.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=iAt("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:T8(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=uy(),d;if(process.env.VISA_CLI_NO_UPDATE_CHECK?d={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?d={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?d={kind:"env",var:"NODE_ENV"}:d={kind:"default"},n.push({key:"ui.updateCheck",value:!u,formatted:T8(!u),source:d}),n.push({key:"client.version",value:hOe,formatted:hOe,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=oy();n.push({key:"dev.mockKeychain",value:p,formatted:T8(p),source:Tne("VISA_MOCK_KEYCHAIN",!!l),hint:wee()});let f=process.env.VISA_MOCK_TOUCHID,m=BT();n.push({key:"dev.mockTouchid",value:m,formatted:T8(m),source:Tne("VISA_MOCK_TOUCHID",!!f),hint:wee()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:T8(!!h),source:Tne("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}function oAt(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 yOe(e,t={}){if(e.length===0)return"";let r=Math.max(...e.map(o=>o.key.length)),n=Math.max(...e.map(o=>o.formatted.length)),i=[];for(let o of e){let s=o.key.padEnd(r+2),a=o.formatted.padEnd(n+2);i.push(`${s}${a}(${oAt(o.source)})`),t.verbose&&o.hint&&i.push(` ${"\u21B3".padStart(r)} ${o.hint}`)}return i.join(`
20938
- `)}function gOe(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)}var Nne=require("node:os"),NI=require("node:path"),BI=require("node:fs/promises"),POe=require("node:fs"),COe=require("node:url"),OOe=require("node:crypto");yd();var sAt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function I8(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!sAt.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var H0=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function bOe(e){let t;try{t=new URL(e)}catch{throw new H0(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new H0(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}yd();var aAt={ucp_checkout_handoff:"checkout_agent_access",ucp_checkout_reconcile:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},cAt=300*1e3,Ine={},_Oe=0,OI=null;function uAt(){return OI||(OI=(async()=>{try{let e=await wd.getFeatureFlags();Ine=e&&e.flags||{},_Oe=Date.now()}catch(e){Ine={},ke.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{OI=null}})(),OI)}async function kI(){Date.now()-_Oe<cAt||await uAt()}function By(e){let t=aAt[e];return t?Ine[t]!==!0:!1}var vOe=require("node:crypto"),RI=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},wM=class{constructor(t={}){this.options=t}options;jobsByOperation=new Map;operationByReview=new Map;now(){return(this.options.now??Date.now)()}activeTtlMs(){return this.options.activeTtlMs??300*1e3}terminalTtlMs(){return this.options.terminalTtlMs??300*1e3}async waitUntilQueryable(t){let r;try{await Promise.race([t,new Promise(n=>{r=setTimeout(n,Math.max(0,this.options.initialWaitMs??1e3)),r.unref?.()})])}finally{r&&clearTimeout(r)}}finish(t,r){t.inFlight=!1,t.status=r,t.expiresAtMs=this.now()+this.terminalTtlMs(),t.resolveReady()}pruneExpired(){let t=this.now();for(let[r,n]of this.jobsByOperation)if(!(n.expiresAtMs>t)){if(n.inFlight){(n.status==="starting"||n.status==="awaiting_passkey")&&(n.status="reconciling",n.error="Approval handoff expired while the checkout was in progress; reconcile with the merchant before retrying",n.resolveReady()),n.expiresAtMs=t+this.terminalTtlMs();continue}this.jobsByOperation.delete(r),this.operationByReview.get(n.reviewId)===r&&this.operationByReview.delete(n.reviewId)}}snapshot(t){return{operationId:t.operationId,reviewId:t.reviewId,status:t.status,approvalUrl:t.approvalUrl,result:t.result,error:t.error,expiresAt:new Date(t.expiresAtMs).toISOString()}}get(t){this.pruneExpired();let r=this.jobsByOperation.get(t);return r?this.snapshot(r):null}async start(t){this.pruneExpired();let r=this.operationByReview.get(t.reviewId),n=r?this.jobsByOperation.get(r):void 0;if(n){if(n.fingerprint!==t.fingerprint)throw new RI(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??vOe.randomUUID)(),a={operationId:s,reviewId:t.reviewId,fingerprint:t.fingerprint,status:"starting",approvalUrl:null,result:null,error:null,expiresAtMs:this.now()+this.activeTtlMs(),inFlight:!0,ready:o,resolveReady:i};this.jobsByOperation.set(s,a),this.operationByReview.set(t.reviewId,s);let c=u=>{a.status==="starting"&&(a.approvalUrl=u,a.status="awaiting_passkey",a.resolveReady())};return Promise.resolve().then(()=>t.run(c)).then(u=>{a.result=u,a.error=null,this.finish(a,"completed")}).catch(u=>{a.error=u instanceof Error?u.message:String(u),this.finish(a,"failed")}),await this.waitUntilQueryable(o),this.snapshot(a)}};function kOe(e){return[(0,NI.join)(e,"checkout-engine","index.js"),(0,NI.join)(e,"..","checkout-engine","index.js")]}function _At(e,t=POe.existsSync){return kOe(e).find(r=>t(r))??null}var AM=null,ROe=async()=>{if(AM)return AM;let e=_At(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${kOe(__dirname).join(" and ")}).`);return AM=(await import((0,COe.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await vAt(),cardMandateRegister:await wAt()}),AM};async function vAt(){let e=await Promise.resolve().then(()=>(kne(),One));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function wAt(){let e=await Promise.resolve().then(()=>(kne(),One));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),register:t=>e.registerCardMandate(t)}}async function Bne(){return By("pay_merchant")?(await kI(),By("pay_merchant")):!1}var NOe=(0,NI.join)((0,Nne.homedir)(),".visa-mcp","agent-credential.json"),BOe=(0,NI.join)((0,Nne.homedir)(),".visa-mcp","contact.json"),jOe=new wM;function jI(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var EAt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function UOe(e){return EAt.has(e)?e:null}async function xM(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"pay_merchant",user_prompt:"",tool_params:JSON.stringify({action:e.action,rail:"card",merchant_host:e.merchantHost,amount_minor:e.amountMinor,payment_amount_unit:"major",currency:e.currency,...e.submit===void 0?{}:{submit:e.submit},source:e.source??null,draw_id:e.drawId??null}),result_success:e.success,result_error:e.errorMessage?jI(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null,source:e.source??null,remainingMinor:e.remainingMinor??null,...e.paymentStatus?{paymentStatus:e.paymentStatus}:{},...e.settlementVerified===void 0?{}:{settlementVerified:e.settlementVerified}}),payment_rail:e.action==="pay"&&e.submit===!0?"card":null,payment_amount:e.action==="pay"&&e.submit===!0&&e.source!=="mandate"?e.amountMinor/100:null,payment_currency:UOe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/checkout",resolved_model:null,session_budget_id:null}])}catch(t){ke.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function IOe(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"start_card_mandate",user_prompt:"",tool_params:JSON.stringify({rail:"card",merchant_host:e.merchantHost,ceiling_minor:e.ceilingMinor,currency:e.currency}),result_success:e.success,result_error:e.errorMessage?jI(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,mandateId:e.mandateId??null,remainingMinor:e.remainingMinor??null}),payment_rail:null,payment_amount:null,payment_currency:UOe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/mandate",resolved_model:null,session_budget_id:null}])}catch(t){ke.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function Rne(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new H0(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function MOe(e,t){if(e.status==="completed")return{...e.result??{},action:t,approvalStatus:"completed",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt};if(e.status==="failed"){let r=jI(e.error??"approval failed");return{success:!1,action:t,approvalStatus:"failed",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:`${r}. Nothing was charged unless a returned receipt explicitly says confirmed.`}}return e.status==="awaiting_passkey"&&e.approvalUrl?{success:!0,action:t,approvalStatus:"awaiting_passkey",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,requiresBrowser:!0,browserUrl:e.approvalUrl,approval:{type:"visa_passkey",url:e.approvalUrl,expiresAt:e.expiresAt,button:{label:"Open Visa approval",webApp:{url:e.approvalUrl}}},message:"Open the Visa approval link and complete the passkey. This Telegram or messaging handoff is not itself the passkey and has not charged the card."}:e.status==="reconciling"?{success:!1,action:t,approvalStatus:"reconciling",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:"The approval window expired while checkout was still in progress. Check this operation again for a receipt and reconcile with the merchant before starting a fresh review."}:{success:!0,action:t,approvalStatus:"starting",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:"Visa is preparing the hosted passkey approval. Check this approval again shortly."}}async function qOe(e={},t={}){if(await(t.flagDisabled??Bne)())return{success:!1,message:"pay_merchant_status requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let n=typeof e.operationId=="string"&&/^[A-Za-z0-9_-]{1,200}$/.test(e.operationId)?e.operationId:null;if(!n)return{success:!1,action:"status",approvalStatus:"unknown",message:'A valid operationId from pay_merchant action "authorize" is required.'};let o=(t.approvalJobs??jOe).get(n);return o?MOe(o,"status"):{success:!1,action:"status",operationId:n,approvalStatus:"unknown",message:"No active approval operation exists. It may have expired or the MCP process may have restarted. If approval or merchant submission may have begun, reconcile the merchant order or receipt before starting a fresh review; never retry a purchase blindly."}}async function DOe(e={},t={}){let r=(e.rail??"card").toLowerCase();if(r!=="card")return{success:!1,message:`pay_merchant only implements the "card" rail today (got ${JSON.stringify(r)}). For stablecoin/x402, use the wallet tools (wallet_pay / wallet_directory_pay).`};let n=t.verifyUrl!==void 0?t.verifyUrl:Xee()&&!process.env.VISA_VERIFY_WEB_URL?null:py();if(n===null)return{success:!1,message:"pay_merchant is not available in stable CLI builds (it runs an on-device mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??Bne)())return{success:!1,message:"pay_merchant requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let o=e.action??"review";if(!["review","pay","authorize"].includes(o))return{success:!1,message:`Unknown pay_merchant action ${JSON.stringify(o)}. Use "review" (default), "authorize", or "pay".`};let s=t.approvalJobs??jOe,a,c,u=(e.currency??"USD").toUpperCase();if(!/^[A-Z]{3}$/.test(u))return{success:!1,message:`Invalid currency ${JSON.stringify(e.currency)}. Expected a 3-letter ISO code like "USD".`};try{a=bOe(e.url??"").toString(),c=Rne(e.amount)}catch(I){if(I instanceof H0)return{success:!1,message:I.message};throw I}let d=t.credentialPath??NOe,l=t.contactPath??BOe;try{await(0,BI.readFile)(d,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no checkout started."}}let p;try{p=JSON.parse(await(0,BI.readFile)(l,"utf8"))}catch{return{success:!1,message:`No contact details at ${l}. Write your name/email/address there (chmod 600) first.`}}let f=null;if(o==="pay"||o==="authorize"){let I=typeof e.confirm=="string"?e.confirm.trim():"",T=/^PAY (\S+)$/.exec(I);if(!T)return{success:!1,action:o,message:'Confirmation required: pass confirm:"PAY <reviewId>" using the reviewId from a prior pay_merchant { action:"review" } call. Nothing was charged.'};f=T[1]}let m=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1";if(o==="pay"&&!m)return{success:!1,action:"pay",reviewId:f,outcome:"not-submitted",paymentStatus:"not_submitted",settlementVerified:!1,message:'Checkout submission is disabled. No payment credential was requested, filled, or submitted. Use action:"review" for safe inspection, or explicitly enable checkout submission before a real pay call.'};let h=t.loadEngine??ROe,y;try{y=await h()}catch(I){let T=I instanceof Error?I.message:String(I);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(T))return{success:!1,message:/checkout engine was not packaged/.test(T)?"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No charge was made.":"The checkout browser runtime is not installed (playwright-core is an optional dependency of @visa/cli). Install it with `npm i playwright-core` in the CLI install, then retry. No charge was made."};throw I}let v={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},E=t.emitTelemetry??(I=>wd.emitTelemetry(I)),b=new URL(a).hostname,w=Math.round(Number(c)*100),A=Date.now();if(o==="review"){ke.info("pay_merchant:review",{host:b,currency:u});let I;try{I=await y.review(v)}catch(T){throw await xM({emitTelemetry:E,action:"review",merchantHost:b,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:T instanceof Error?T.message:String(T),startedAt:A}),T}return await xM({emitTelemetry:E,action:"review",merchantHost:b,amountMinor:w,currency:u,outcome:"reviewed",success:!0,startedAt:A}),{success:!0,action:"review",...I,message:`Review ${I.reviewId}: ${I.merchantHost} wants ${I8(I.amountMinor,I.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${I.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let x=f,S=async I=>{ke.info("pay_merchant:pay",{reviewId:x,submit:m,approvalMode:o==="authorize"?"handoff":"blocking"});let T;try{T=await y.pay({...v,reviewId:x,submit:m,...I?{onApprovalUrl:I}:{}})}catch(j){throw await xM({emitTelemetry:E,action:"pay",merchantHost:b,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:j instanceof Error?j.message:String(j),startedAt:A,submit:m}),j}let C=T.outcome==="confirmed"||T.outcome==="reviewed-dry-run",U=T.outcome==="reviewed-dry-run"?"not_submitted":T.outcome==="declined"?"declined":"unverified";await xM({emitTelemetry:E,action:"pay",merchantHost:b,amountMinor:w,currency:u,outcome:T.outcome,confirmationRef:T.confirmationRef,success:C,errorMessage:C?null:T.detail??T.outcome,startedAt:A,submit:m,source:T.source??null,remainingMinor:T.remainingMinor??null,paymentStatus:U,settlementVerified:!1,drawId:T.source==="mandate"?x:null});let M=T.source==="mandate"?` Credential issued from a tap-free active mandate${typeof T.remainingMinor=="number"?` (${T.remainingMinor} ${u} minor units remaining)`:""}.`:T.source==="fresh-tap"?" Credential issued with a fresh per-purchase passkey.":"";return{success:C,action:"pay",reviewId:x,...T,paymentStatus:U,settlementVerified:!1,message:T.outcome==="confirmed"?`Checkout submitted. The merchant reported confirmation ${T.confirmationRef??"(none captured)"}, but processor settlement is not independently verified. Receipt ${T.receiptPath??"(not written)"}.${M}`:T.outcome==="reviewed-dry-run"?"Checkout review validated without requesting, filling, or submitting a payment credential.":T.outcome==="filled-dry-run"?`Legacy credential-disclosure dry-run completed. A usable credential reached the merchant page and may have consumed authority even though no submit click was made.${M}`:`Outcome: ${T.outcome}${T.detail?` \u2014 ${T.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}};if(o==="authorize"){let I=(0,OOe.createHash)("sha256").update(JSON.stringify([x,a,c,u,m])).digest("hex");ke.info("pay_merchant:approval_handoff_started",{reviewId:x,merchantHost:b,currency:u,submit:m});try{let T=await s.start({reviewId:x,fingerprint:I,run:async C=>{try{let U=await S(M=>{ke.info("pay_merchant:approval_handoff_ready",{reviewId:x}),C(M)});return ke.info("pay_merchant:approval_handoff_completed",{reviewId:x,success:U.success===!0}),U}catch(U){throw ke.warn("pay_merchant:approval_handoff_failed",{reviewId:x,error:jI(U instanceof Error?U.message:String(U))}),U}}});return MOe(T,"authorize")}catch(T){if(T instanceof RI)return ke.warn("pay_merchant:approval_handoff_conflict",{reviewId:x}),{success:!1,action:"authorize",reviewId:x,approvalStatus:"conflict",message:"This review already has an approval handoff with different checkout inputs. Do not retry it; create and confirm a fresh review."};throw T}}return S()}async function LOe(e={},t={}){let r=t.verifyUrl!==void 0?t.verifyUrl:py();if(r===null)return{success:!1,message:"start_card_mandate is not available in stable CLI builds (it runs a server-side mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??Bne)())return{success:!1,message:"start_card_mandate requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let i="USD",o;try{o=Rne(e.ceiling)}catch(b){if(b instanceof H0)return{success:!1,message:b.message};throw b}let s;if(e.perTransaction!==void 0){try{s=Rne(e.perTransaction)}catch(b){if(b instanceof H0)return{success:!1,message:b.message};throw b}if(Number(s)>Number(o))return{success:!1,message:"perTransaction cannot exceed the ceiling."}}let a;if(e.intent!==void 0){if(typeof e.intent!="string")return{success:!1,message:"intent must be a short string."};let b=e.intent.replace(/[\p{Cc}\u2028\u2029]/gu,"").trim().slice(0,200).trim();a=b.length>0?b:void 0}let c=t.credentialPath??NOe,u=t.contactPath??BOe;try{await(0,BI.readFile)(c,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no budget was created."}}let d;try{d=JSON.parse(await(0,BI.readFile)(u,"utf8"))}catch{return{success:!1,message:`No contact details at ${u}. Write your name/email/address there (chmod 600) first.`}}let l=t.loadEngine??ROe,p;try{p=await l()}catch(b){let w=b instanceof Error?b.message:String(b);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(w))return{success:!1,message:"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No mandate was created."};throw b}let f="retail-mcc-5999",m=Math.round(Number(o)*100),h=t.emitTelemetry??(b=>wd.emitTelemetry(b)),y=Date.now();ke.info("start_card_mandate:create",{host:f,currency:i});let v;try{v=await p.startCardMandate({...e.agent?.trim()?{agentRef:e.agent.trim()}:{},ceiling:o,currency:i,credentialPath:c,contact:d,approvalBaseUrl:r,...s!==void 0?{perTransaction:s}:{},...a!==void 0?{intent:a}:{}})}catch(b){let w=b instanceof Error?jI(b.message):String(b);return ke.warn("start_card_mandate:failed",{message:w}),await IOe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:"engine-error",success:!1,errorMessage:b instanceof Error?b.message:String(b),startedAt:y}),{success:!1,message:`Could not create the mandate: ${w}`}}let E=v.registerFailed===!0;return E&&ke.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:f}),await IOe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:E?"created-register-failed":"created",success:!E,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:y}),E?{success:!1,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} was created but could NOT be registered for tap-free draws, so it will not be used \u2014 your next pay_merchant will fall through to a fresh per-purchase passkey tap. Re-run to try again once the auth server is reachable.`}:{success:!0,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} active: up to ${I8(m,v.currencyCode)} at eligible retail merchants (network category 5999), across up to ${v.maxDraws} purchases, until ${v.expiresAt}. pay_merchant will draw against it tap-free until the budget, purchase count, or time limit is reached. A declined draw leaves the budget untouched and disables this mandate; the next checkout can use a fresh per-purchase approval.`}}var Rke=require("node:crypto");var Pke=require("node:crypto");var Lr={};Oi(Lr,{BRAND:()=>WAt,DIRTY:()=>g6,EMPTY_PATH:()=>TAt,INVALID:()=>bt,NEVER:()=>xxt,OK:()=>Js,ParseStatus:()=>ls,Schema:()=>zt,ZodAny:()=>My,ZodArray:()=>K0,ZodBigInt:()=>_6,ZodBoolean:()=>v6,ZodBranded:()=>MI,ZodCatch:()=>k6,ZodDate:()=>w6,ZodDefault:()=>O6,ZodDiscriminatedUnion:()=>IM,ZodEffects:()=>xd,ZodEnum:()=>P6,ZodError:()=>fc,ZodFirstPartyTypeKind:()=>xt,ZodFunction:()=>CM,ZodIntersection:()=>S6,ZodIssueCode:()=>ye,ZodLazy:()=>T6,ZodLiteral:()=>I6,ZodMap:()=>N8,ZodNaN:()=>j8,ZodNativeEnum:()=>C6,ZodNever:()=>$l,ZodNull:()=>A6,ZodNullable:()=>Tf,ZodNumber:()=>b6,ZodObject:()=>mc,ZodOptional:()=>Ed,ZodParsedType:()=>je,ZodPipeline:()=>qI,ZodPromise:()=>qy,ZodReadonly:()=>R6,ZodRecord:()=>PM,ZodSchema:()=>zt,ZodSet:()=>B8,ZodString:()=>Uy,ZodSymbol:()=>k8,ZodTransformer:()=>xd,ZodTuple:()=>Sf,ZodType:()=>zt,ZodUndefined:()=>E6,ZodUnion:()=>x6,ZodUnknown:()=>V0,ZodVoid:()=>R8,addIssueToContext:()=>Ie,any:()=>Td,array:()=>ue,bigint:()=>XAt,boolean:()=>Sd,coerce:()=>vu,custom:()=>WOe,date:()=>QAt,datetimeRegex:()=>KOe,defaultErrorMap:()=>$0,discriminatedUnion:()=>sxt,effect:()=>yxt,enum:()=>Id,function:()=>lxt,getErrorMap:()=>P8,getParsedType:()=>xf,instanceof:()=>YAt,intersection:()=>axt,isAborted:()=>SM,isAsync:()=>C8,isDirty:()=>TM,isValid:()=>jy,late:()=>JAt,lazy:()=>pxt,literal:()=>fxt,makeIssue:()=>UI,map:()=>uxt,nan:()=>ZAt,nativeEnum:()=>mxt,never:()=>nxt,null:()=>U8,nullable:()=>bxt,number:()=>kr,object:()=>fe,objectUtil:()=>jne,oboolean:()=>Axt,onumber:()=>Ext,optional:()=>gxt,ostring:()=>wxt,pipeline:()=>vxt,preprocess:()=>_xt,promise:()=>hxt,quotelessJson:()=>AAt,record:()=>Xt,set:()=>dxt,setErrorMap:()=>SAt,strictObject:()=>oxt,string:()=>z,symbol:()=>ext,transformer:()=>yxt,tuple:()=>cxt,undefined:()=>txt,union:()=>M8,unknown:()=>rxt,util:()=>Zt,void:()=>ixt});var Zt;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return e.objectValues(s)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(let s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Zt||(Zt={}));var jne;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(jne||(jne={}));var je=Zt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xf=e=>{switch(typeof e){case"undefined":return je.undefined;case"string":return je.string;case"number":return Number.isNaN(e)?je.nan:je.number;case"boolean":return je.boolean;case"function":return je.function;case"bigint":return je.bigint;case"symbol":return je.symbol;case"object":return Array.isArray(e)?je.array:e===null?je.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?je.promise:typeof Map<"u"&&e instanceof Map?je.map:typeof Set<"u"&&e instanceof Set?je.set:typeof Date<"u"&&e instanceof Date?je.date:je.object;default:return je.unknown}};var ye=Zt.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"]),AAt=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),fc=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}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,Zt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};fc.create=e=>new fc(e);var xAt=(e,t)=>{let r;switch(e.code){case ye.invalid_type:e.received===je.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ye.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Zt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Zt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Zt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Zt.joinValues(e.options)}, received '${e.received}'`;break;case ye.invalid_arguments:r="Invalid function arguments";break;case ye.invalid_return_type:r="Invalid function return type";break;case ye.invalid_date:r="Invalid date";break;case ye.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Zt.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ye.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case ye.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case ye.custom:r="Invalid input";break;case ye.invalid_intersection_types:r="Intersection results could not be merged";break;case ye.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ye.not_finite:r="Number must be finite";break;default:r=t.defaultError,Zt.assertNever(e)}return{message:r}},$0=xAt;var zOe=$0;function SAt(e){zOe=e}function P8(){return zOe}var UI=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:t,defaultError:a}).message;return{...i,path:o,message:a}},TAt=[];function Ie(e,t){let r=P8(),n=UI({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===$0?void 0:$0].filter(i=>!!i)});e.common.issues.push(n)}var ls=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return bt;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return bt;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:t.value,value:n}}},bt=Object.freeze({status:"aborted"}),g6=e=>({status:"dirty",value:e}),Js=e=>({status:"valid",value:e}),SM=e=>e.status==="aborted",TM=e=>e.status==="dirty",jy=e=>e.status==="valid",C8=e=>typeof Promise<"u"&&e instanceof Promise;var tt;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(tt||(tt={}));var Ad=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}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}},HOe=(e,t)=>{if(jy(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 r=new fc(e.common.issues);return this._error=r,this._error}}};function qt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var zt=class{get description(){return this._def.description}_getType(t){return xf(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:xf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ls,ctx:{common:t.parent.common,data:t.data,parsedType:xf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(C8(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xf(t)},i=this._parseSync({data:t,path:n.path,parent:n});return HOe(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xf(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return jy(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>jy(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xf(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(C8(i)?i:Promise.resolve(i));return HOe(n,o)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=t(i),a=()=>o.addIssue({code:ye.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new xd({schema:this,typeName:xt.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:r=>this["~validate"](r)}}optional(){return Ed.create(this,this._def)}nullable(){return Tf.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return K0.create(this)}promise(){return qy.create(this,this._def)}or(t){return x6.create([this,t],this._def)}and(t){return S6.create(this,t,this._def)}transform(t){return new xd({...qt(this._def),schema:this,typeName:xt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new O6({...qt(this._def),innerType:this,defaultValue:r,typeName:xt.ZodDefault})}brand(){return new MI({typeName:xt.ZodBranded,type:this,...qt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new k6({...qt(this._def),innerType:this,catchValue:r,typeName:xt.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return qI.create(this,t)}readonly(){return R6.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},IAt=/^c[^\s-]{8,}$/i,PAt=/^[0-9a-z]+$/,CAt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,OAt=/^[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,kAt=/^[a-z0-9_-]{21}$/i,RAt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,NAt=/^[-+]?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)?)??$/,BAt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,jAt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Une,UAt=/^(?:(?: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])$/,MAt=/^(?:(?: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])$/,qAt=/^(([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]))$/,DAt=/^(([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])$/,LAt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,zAt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,FOe="((\\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])))",HAt=new RegExp(`^${FOe}$`);function VOe(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function $At(e){return new RegExp(`^${VOe(e)}$`)}function KOe(e){let t=`${FOe}T${VOe(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function FAt(e,t){return!!((t==="v4"||!t)&&UAt.test(e)||(t==="v6"||!t)&&qAt.test(e))}function VAt(e,t){if(!RAt.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function KAt(e,t){return!!((t==="v4"||!t)&&MAt.test(e)||(t==="v6"||!t)&&DAt.test(e))}var Uy=class e extends zt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==je.string){let o=this._getOrReturnCtx(t);return Ie(o,{code:ye.invalid_type,expected:je.string,received:o.parsedType}),bt}let n=new ls,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=t.data.length>o.value,a=t.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(t,i),s?Ie(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Ie(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")BAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Une||(Une=new RegExp(jAt,"u")),Une.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")OAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")kAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")IAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")PAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")CAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"ulid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Ie(i,{validation:"url",code:ye.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"regex",code:ye.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.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)||(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?KOe(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?HAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?$At(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?NAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?FAt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?VAt(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?KAt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?LAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?zAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Zt.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:ye.invalid_string,...tt.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...tt.errToObj(t)})}url(t){return this._addCheck({kind:"url",...tt.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...tt.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...tt.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...tt.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...tt.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...tt.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...tt.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...tt.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...tt.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...tt.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...tt.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...tt.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,...tt.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,...tt.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...tt.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...tt.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...tt.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...tt.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...tt.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...tt.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...tt.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...tt.errToObj(r)})}nonempty(t){return this.min(1,tt.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 r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Uy.create=e=>new Uy({checks:[],typeName:xt.ZodString,coerce:e?.coerce??!1,...qt(e)});function GAt(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return o%s/10**i}var b6=class e extends zt{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)!==je.number){let o=this._getOrReturnCtx(t);return Ie(o,{code:ye.invalid_type,expected:je.number,received:o.parsedType}),bt}let n,i=new ls;for(let o of this._def.checks)o.kind==="int"?Zt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?GAt(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.not_finite,message:o.message}),i.dirty()):Zt.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,tt.toString(r))}gt(t,r){return this.setLimit("min",t,!1,tt.toString(r))}lte(t,r){return this.setLimit("max",t,!0,tt.toString(r))}lt(t,r){return this.setLimit("max",t,!1,tt.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:tt.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:tt.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:tt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:tt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:tt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:tt.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:tt.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:tt.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:tt.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:tt.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Zt.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};b6.create=e=>new b6({checks:[],typeName:xt.ZodNumber,coerce:e?.coerce||!1,...qt(e)});var _6=class e extends zt{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)!==je.bigint)return this._getInvalidInput(t);let n,i=new ls;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Zt.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Ie(r,{code:ye.invalid_type,expected:je.bigint,received:r.parsedType}),bt}gte(t,r){return this.setLimit("min",t,!0,tt.toString(r))}gt(t,r){return this.setLimit("min",t,!1,tt.toString(r))}lte(t,r){return this.setLimit("max",t,!0,tt.toString(r))}lt(t,r){return this.setLimit("max",t,!1,tt.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:tt.toString(i)}]})}_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:tt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:tt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:tt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:tt.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:tt.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};_6.create=e=>new _6({checks:[],typeName:xt.ZodBigInt,coerce:e?.coerce??!1,...qt(e)});var v6=class extends zt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==je.boolean){let n=this._getOrReturnCtx(t);return Ie(n,{code:ye.invalid_type,expected:je.boolean,received:n.parsedType}),bt}return Js(t.data)}};v6.create=e=>new v6({typeName:xt.ZodBoolean,coerce:e?.coerce||!1,...qt(e)});var w6=class e extends zt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==je.date){let o=this._getOrReturnCtx(t);return Ie(o,{code:ye.invalid_type,expected:je.date,received:o.parsedType}),bt}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Ie(o,{code:ye.invalid_date}),bt}let n=new ls,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Zt.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:tt.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:tt.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};w6.create=e=>new w6({checks:[],coerce:e?.coerce||!1,typeName:xt.ZodDate,...qt(e)});var k8=class extends zt{_parse(t){if(this._getType(t)!==je.symbol){let n=this._getOrReturnCtx(t);return Ie(n,{code:ye.invalid_type,expected:je.symbol,received:n.parsedType}),bt}return Js(t.data)}};k8.create=e=>new k8({typeName:xt.ZodSymbol,...qt(e)});var E6=class extends zt{_parse(t){if(this._getType(t)!==je.undefined){let n=this._getOrReturnCtx(t);return Ie(n,{code:ye.invalid_type,expected:je.undefined,received:n.parsedType}),bt}return Js(t.data)}};E6.create=e=>new E6({typeName:xt.ZodUndefined,...qt(e)});var A6=class extends zt{_parse(t){if(this._getType(t)!==je.null){let n=this._getOrReturnCtx(t);return Ie(n,{code:ye.invalid_type,expected:je.null,received:n.parsedType}),bt}return Js(t.data)}};A6.create=e=>new A6({typeName:xt.ZodNull,...qt(e)});var My=class extends zt{constructor(){super(...arguments),this._any=!0}_parse(t){return Js(t.data)}};My.create=e=>new My({typeName:xt.ZodAny,...qt(e)});var V0=class extends zt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Js(t.data)}};V0.create=e=>new V0({typeName:xt.ZodUnknown,...qt(e)});var $l=class extends zt{_parse(t){let r=this._getOrReturnCtx(t);return Ie(r,{code:ye.invalid_type,expected:je.never,received:r.parsedType}),bt}};$l.create=e=>new $l({typeName:xt.ZodNever,...qt(e)});var R8=class extends zt{_parse(t){if(this._getType(t)!==je.undefined){let n=this._getOrReturnCtx(t);return Ie(n,{code:ye.invalid_type,expected:je.void,received:n.parsedType}),bt}return Js(t.data)}};R8.create=e=>new R8({typeName:xt.ZodVoid,...qt(e)});var K0=class e extends zt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==je.array)return Ie(r,{code:ye.invalid_type,expected:je.array,received:r.parsedType}),bt;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Ie(r,{code:s?ye.too_big:ye.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Ie(r,{code:ye.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Ie(r,{code:ye.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new Ad(r,s,r.path,a)))).then(s=>ls.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Ad(r,s,r.path,a)));return ls.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:tt.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:tt.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:tt.toString(r)}})}nonempty(t){return this.min(1,t)}};K0.create=(e,t)=>new K0({type:e,minLength:null,maxLength:null,exactLength:null,typeName:xt.ZodArray,...qt(t)});function O8(e){if(e instanceof mc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Ed.create(O8(n))}return new mc({...e._def,shape:()=>t})}else return e instanceof K0?new K0({...e._def,type:O8(e.element)}):e instanceof Ed?Ed.create(O8(e.unwrap())):e instanceof Tf?Tf.create(O8(e.unwrap())):e instanceof Sf?Sf.create(e.items.map(t=>O8(t))):e}var mc=class e extends zt{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(),r=Zt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==je.object){let u=this._getOrReturnCtx(t);return Ie(u,{code:ye.invalid_type,expected:je.object,received:u.parsedType}),bt}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof $l&&this._def.unknownKeys==="strip"))for(let u in i.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let d=o[u],l=i.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new Ad(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof $l){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")a.length>0&&(Ie(i,{code:ye.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=i.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new Ad(i,l,i.path,d)),alwaysSet:d in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,p=await d.value;u.push({key:l,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>ls.mergeObjectSync(n,u)):ls.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return tt.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:tt.errToObj(t).message??i}:{message:i}}}:{}})}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:xt.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of Zt.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of Zt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return O8(this)}partial(t){let r={};for(let n of Zt.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of Zt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Ed;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return GOe(Zt.objectKeys(this.shape))}};mc.create=(e,t)=>new mc({shape:()=>e,unknownKeys:"strip",catchall:$l.create(),typeName:xt.ZodObject,...qt(t)});mc.strictCreate=(e,t)=>new mc({shape:()=>e,unknownKeys:"strict",catchall:$l.create(),typeName:xt.ZodObject,...qt(t)});mc.lazycreate=(e,t)=>new mc({shape:e,unknownKeys:"strip",catchall:$l.create(),typeName:xt.ZodObject,...qt(t)});var x6=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(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 r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new fc(a.ctx.common.issues));return Ie(r,{code:ye.invalid_union,unionErrors:s}),bt}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new fc(c));return Ie(r,{code:ye.invalid_union,unionErrors:a}),bt}}get options(){return this._def.options}};x6.create=(e,t)=>new x6({options:e,typeName:xt.ZodUnion,...qt(t)});var F0=e=>e instanceof T6?F0(e.schema):e instanceof xd?F0(e.innerType()):e instanceof I6?[e.value]:e instanceof P6?e.options:e instanceof C6?Zt.objectValues(e.enum):e instanceof O6?F0(e._def.innerType):e instanceof E6?[void 0]:e instanceof A6?[null]:e instanceof Ed?[void 0,...F0(e.unwrap())]:e instanceof Tf?[null,...F0(e.unwrap())]:e instanceof MI||e instanceof R6?F0(e.unwrap()):e instanceof k6?F0(e._def.innerType):[],IM=class e extends zt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==je.object)return Ie(r,{code:ye.invalid_type,expected:je.object,received:r.parsedType}),bt;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(Ie(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),bt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let s=F0(o.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new e({typeName:xt.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...qt(n)})}};function Mne(e,t){let r=xf(e),n=xf(t);if(e===t)return{valid:!0,data:e};if(r===je.object&&n===je.object){let i=Zt.objectKeys(t),o=Zt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=Mne(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===je.array&&n===je.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=t[o],c=Mne(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===je.date&&n===je.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var S6=class extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(SM(o)||SM(s))return bt;let a=Mne(o.value,s.value);return a.valid?((TM(o)||TM(s))&&r.dirty(),{status:r.value,value:a.data}):(Ie(n,{code:ye.invalid_intersection_types}),bt)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};S6.create=(e,t,r)=>new S6({left:e,right:t,typeName:xt.ZodIntersection,...qt(r)});var Sf=class e extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.array)return Ie(n,{code:ye.invalid_type,expected:je.array,received:n.parsedType}),bt;if(n.data.length<this._def.items.length)return Ie(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),bt;!this._def.rest&&n.data.length>this._def.items.length&&(Ie(n,{code:ye.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ad(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ls.mergeArray(r,s)):ls.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Sf.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Sf({items:e,typeName:xt.ZodTuple,rest:null,...qt(t)})};var PM=class e extends zt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.object)return Ie(n,{code:ye.invalid_type,expected:je.object,received:n.parsedType}),bt;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Ad(n,a,n.path,a)),value:s._parse(new Ad(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ls.mergeObjectAsync(r,i):ls.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof zt?new e({keyType:t,valueType:r,typeName:xt.ZodRecord,...qt(n)}):new e({keyType:Uy.create(),valueType:t,typeName:xt.ZodRecord,...qt(r)})}},N8=class extends zt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.map)return Ie(n,{code:ye.invalid_type,expected:je.map,received:n.parsedType}),bt;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new Ad(n,a,n.path,[u,"key"])),value:o._parse(new Ad(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return bt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return bt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};N8.create=(e,t,r)=>new N8({valueType:t,keyType:e,typeName:xt.ZodMap,...qt(r)});var B8=class e extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.set)return Ie(n,{code:ye.invalid_type,expected:je.set,received:n.parsedType}),bt;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Ie(n,{code:ye.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Ie(n,{code:ye.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(c){let u=new Set;for(let d of c){if(d.status==="aborted")return bt;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new Ad(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:tt.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:tt.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};B8.create=(e,t)=>new B8({valueType:e,minSize:null,maxSize:null,typeName:xt.ZodSet,...qt(t)});var CM=class e extends zt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==je.function)return Ie(r,{code:ye.invalid_type,expected:je.function,received:r.parsedType}),bt;function n(a,c){return UI({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,P8(),$0].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return UI({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,P8(),$0].filter(u=>!!u),issueData:{code:ye.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof qy){let a=this;return Js(async function(...c){let u=new fc([]),d=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(s,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(f=>{throw u.addIssue(i(l,f)),u})})}else{let a=this;return Js(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new fc([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new fc([i(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Sf.create(t).rest(V0.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,r,n){return new e({args:t||Sf.create([]).rest(V0.create()),returns:r||V0.create(),typeName:xt.ZodFunction,...qt(n)})}},T6=class extends zt{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};T6.create=(e,t)=>new T6({getter:e,typeName:xt.ZodLazy,...qt(t)});var I6=class extends zt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Ie(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),bt}return{status:"valid",value:t.data}}get value(){return this._def.value}};I6.create=(e,t)=>new I6({value:e,typeName:xt.ZodLiteral,...qt(t)});function GOe(e,t){return new P6({values:e,typeName:xt.ZodEnum,...qt(t)})}var P6=class e extends zt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Ie(r,{expected:Zt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),bt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return Ie(r,{received:r.data,code:ye.invalid_enum_value,options:n}),bt}return Js(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};P6.create=GOe;var C6=class extends zt{_parse(t){let r=Zt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==je.string&&n.parsedType!==je.number){let i=Zt.objectValues(r);return Ie(n,{expected:Zt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),bt}if(this._cache||(this._cache=new Set(Zt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Zt.objectValues(r);return Ie(n,{received:n.data,code:ye.invalid_enum_value,options:i}),bt}return Js(t.data)}get enum(){return this._def.values}};C6.create=(e,t)=>new C6({values:e,typeName:xt.ZodNativeEnum,...qt(t)});var qy=class extends zt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==je.promise&&r.common.async===!1)return Ie(r,{code:ye.invalid_type,expected:je.promise,received:r.parsedType}),bt;let n=r.parsedType===je.promise?r.data:Promise.resolve(r.data);return Js(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};qy.create=(e,t)=>new qy({type:e,typeName:xt.ZodPromise,...qt(t)});var xd=class extends zt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s=>{Ie(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return bt;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?bt:c.status==="dirty"?g6(c.value):r.value==="dirty"?g6(c.value):c});{if(r.value==="aborted")return bt;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?bt:a.status==="dirty"?g6(a.value):r.value==="dirty"?g6(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.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(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?bt:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?bt:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!jy(s))return bt;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>jy(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):bt);Zt.assertNever(i)}};xd.create=(e,t,r)=>new xd({schema:e,typeName:xt.ZodEffects,effect:t,...qt(r)});xd.createWithPreprocess=(e,t,r)=>new xd({schema:t,effect:{type:"preprocess",transform:e},typeName:xt.ZodEffects,...qt(r)});var Ed=class extends zt{_parse(t){return this._getType(t)===je.undefined?Js(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ed.create=(e,t)=>new Ed({innerType:e,typeName:xt.ZodOptional,...qt(t)});var Tf=class extends zt{_parse(t){return this._getType(t)===je.null?Js(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Tf.create=(e,t)=>new Tf({innerType:e,typeName:xt.ZodNullable,...qt(t)});var O6=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===je.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};O6.create=(e,t)=>new O6({innerType:e,typeName:xt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...qt(t)});var k6=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return C8(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new fc(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new fc(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};k6.create=(e,t)=>new k6({innerType:e,typeName:xt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...qt(t)});var j8=class extends zt{_parse(t){if(this._getType(t)!==je.nan){let n=this._getOrReturnCtx(t);return Ie(n,{code:ye.invalid_type,expected:je.nan,received:n.parsedType}),bt}return{status:"valid",value:t.data}}};j8.create=e=>new j8({typeName:xt.ZodNaN,...qt(e)});var WAt=Symbol("zod_brand"),MI=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},qI=class e extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?bt:o.status==="dirty"?(r.dirty(),g6(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?bt:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:xt.ZodPipeline})}},R6=class extends zt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(jy(i)&&(i.value=Object.freeze(i.value)),i);return C8(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};R6.create=(e,t)=>new R6({innerType:e,typeName:xt.ZodReadonly,...qt(t)});function $Oe(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function WOe(e,t={},r){return e?My.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=$Oe(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=$Oe(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):My.create()}var JAt={object:mc.lazycreate},xt;(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"})(xt||(xt={}));var YAt=(e,t={message:`Input not instance of ${e.name}`})=>WOe(r=>r instanceof e,t),z=Uy.create,kr=b6.create,ZAt=j8.create,XAt=_6.create,Sd=v6.create,QAt=w6.create,ext=k8.create,txt=E6.create,U8=A6.create,Td=My.create,rxt=V0.create,nxt=$l.create,ixt=R8.create,ue=K0.create,fe=mc.create,oxt=mc.strictCreate,M8=x6.create,sxt=IM.create,axt=S6.create,cxt=Sf.create,Xt=PM.create,uxt=N8.create,dxt=B8.create,lxt=CM.create,pxt=T6.create,fxt=I6.create,Id=P6.create,mxt=C6.create,hxt=qy.create,yxt=xd.create,gxt=Ed.create,bxt=Tf.create,_xt=xd.createWithPreprocess,vxt=qI.create,wxt=()=>z().optional(),Ext=()=>kr().optional(),Axt=()=>Sd().optional(),vu={string:(e=>Uy.create({...e,coerce:!0})),number:(e=>b6.create({...e,coerce:!0})),boolean:(e=>v6.create({...e,coerce:!0})),bigint:(e=>_6.create({...e,coerce:!0})),date:(e=>w6.create({...e,coerce:!0}))};var xxt=bt;var Txt=Id(["enc","sig"]),Ixt=Id(["markdown","plain"]),Pxt=Id(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),Cxt=Id(["error","info","warning"]),L8=Id(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),Oxt=Id(["completed","failed","pending"]),kxt=Id(["digital","pickup","shipping"]),Rxt=Id(["fulfilled","partial","processing","removed"]),Nxt=Id(["across","each"]),qne=Id(["pickup","shipping"]),Bxt=fe({config:Xt(z(),Td()),config_schema:z(),id:z(),instrument_schemas:ue(z()),name:z(),spec:z(),version:z()}),jxt=fe({alg:z().optional(),crv:z().optional(),e:z().optional(),kid:z(),kty:z(),n:z().optional(),use:Txt.optional(),x:z().optional(),y:z().optional()}),Uxt=fe({config:Xt(z(),Td()).optional(),extends:z().optional(),name:z(),schema:z(),spec:z(),version:z()}),Mxt=fe({endpoint:z()}),qxt=fe({schema:z()}),JOe=fe({endpoint:z(),schema:z()}),Dxt=JOe,Lxt=JOe,Ia=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional()}),yo=fe({address_country:z().optional(),address_region:z().optional(),currency:z().optional(),eligibility:ue(z()).optional(),intent:z().optional(),language:z().optional(),postal_code:z().optional()}),Dne=yo,YOe=fe({id:z()}),zxt=YOe,Hxt=YOe,DI=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional()}),OM=fe({type:z()}),Yi=fe({"dev.ucp.buyer_ip":z().optional(),"dev.ucp.user_agent":z().optional()}),Lne=Yi,ZOe=fe({id:z(),image_url:z().optional(),price:kr(),title:z()}),kM=fe({amount:kr(),display_text:z().optional(),type:z()}),Dy=fe({title:z().optional(),type:z(),url:z()}),G0=fe({code:z().optional(),content:z(),content_type:Ixt.optional(),path:z().optional(),severity:Pxt.optional(),type:Cxt,image_url:z().optional(),presentation:z().optional(),url:z().optional()}),zne=G0,z8=fe({id:z(),label:z().optional(),permalink_url:z()}),$xt=fe({amount:kr(),display_text:z()}),Fxt=fe({config:Xt(z(),Td()).optional(),extends:z().optional(),name:z(),schema:z().optional(),spec:z().optional(),version:z()}),Hne=fe({id:z(),quantity:kr()}),Vxt=Hne,Kxt=Hne,Gxt=Hne,Wxt=fe({fulfilled:kr(),original:kr().optional(),total:kr()}),Jxt=fe({billing_address:DI.optional(),credential:OM.optional(),display:Xt(z(),Td()).optional(),handler_id:z(),id:z(),type:z()}),Yxt=fe({checkout_mandate:z()}),Zxt=fe({merchant_authorization:z().optional(),checkout_mandate:z()}),Xxt=fe({analytics:Sd().optional(),marketing:Sd().optional(),preferences:Sd().optional(),sale_of_data:Sd().optional()});var Qxt=Xxt;var XOe=fe({codes:ue(z()).optional()}),e9t=XOe,t9t=fe({amount:kr(),path:z()}),r9t=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional(),id:z().optional(),address:DI.optional(),name:z().optional()}),n9t=fe({carrier:z().optional(),description:z().optional(),earliest_fulfillment_time:vu.date().optional(),id:z(),latest_fulfillment_time:vu.date().optional(),title:z(),totals:ue(kM)}),i9t=fe({description:z().optional(),fulfillable_on:M8([U8(),z()]).optional(),line_item_ids:ue(z()),type:qne}),o9t=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional(),id:z(),address:DI.optional(),name:z().optional()}),s9t=fe({max:kr().optional(),min:kr().optional()}),LI=fe({taxonomy:z().optional(),value:z()}),zI=fe({html:z().optional(),markdown:z().optional(),plain:z().optional()}),q8=fe({amount:kr(),currency:z()}),HI=fe({alt_text:z().optional(),height:kr().optional(),type:z(),url:z(),width:kr().optional()}),a9t=fe({id:z().optional(),label:z()}),$I=fe({count:kr().optional(),scale_max:kr(),scale_min:kr().optional(),value:kr()}),QOe=fe({available:Sd().optional(),status:z().optional()}),c9t=QOe,eke=fe({type:z(),value:z()}),u9t=eke,d9t=fe({id:z(),match:z().optional()}),$ne=fe({id:z().optional(),label:z(),name:z()}),tke=$ne,rke=fe({links:ue(Dy).optional(),name:z().optional()}),l9t=rke,nke=fe({unit:z(),value:kr()});var p9t=nke,f9t=fe({cursor:z().optional(),limit:kr().optional()}),m9t=fe({cursor:z().optional(),has_next_page:Sd(),total_count:kr().optional()}),h9t=fe({handlers:ue(Bxt).optional()}),y9t=fe({a2a:Mxt.optional(),embedded:qxt.optional(),mcp:Dxt.optional(),rest:Lxt.optional(),spec:z(),version:z()}),H8=fe({item:zxt,quantity:kr()}),g9t=fe({billing_address:DI.optional(),credential:OM.optional(),display:Xt(z(),Td()).optional(),handler_id:z(),id:z(),type:z(),selected:Sd().optional()}),FI=fe({id:z().optional(),item:Hxt,parent_id:z().optional(),quantity:kr()}),RM=fe({instruments:ue(g9t).optional()}),b9t=RM,VI=RM,$8=RM,NM=RM,N6=fe({id:z(),item:ZOe,parent_id:z().optional(),quantity:kr(),totals:ue(kM)}),Ly=fe({amount:kr(),display_text:z().optional(),type:z(),lines:ue($xt).optional()}),Fl=fe({capabilities:Xt(z(),ue(Fxt)),version:z()}),_9t=fe({description:z().optional(),id:z(),line_items:ue(Vxt).optional(),occurred_at:vu.date(),status:Oxt,totals:ue(kM).optional(),type:z()}),v9t=fe({carrier:z().optional(),description:z().optional(),id:z(),line_items:ue(Kxt),occurred_at:vu.date(),tracking_number:z().optional(),tracking_url:z().optional(),type:z()}),w9t=fe({description:z().optional(),destination:DI,fulfillable_on:z().optional(),id:z(),line_items:ue(Gxt),method_type:kxt}),E9t=fe({id:z(),item:ZOe,parent_id:z().optional(),quantity:Wxt,status:Rxt,totals:ue(kM)}),Tqr=fe({payment_data:Jxt}),Iqr=fe({ap2:Yxt.optional()}),Pqr=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy),messages:ue(G0).optional(),order:z8.optional(),payment:$8.optional(),signals:Yi.optional(),status:L8,totals:ue(Ly),ucp:Fl,ap2:Zxt.optional()}),Fne=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),consent:Qxt.optional()}),A9t=Fne,x9t=Fne,ike=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(FI),payment:NM.optional(),signals:Yi.optional(),discounts:e9t.optional()}),S9t=fe({allocations:ue(t9t).optional(),amount:kr(),automatic:Sd().optional(),code:z().optional(),eligibility:z().optional(),method:Nxt.optional(),priority:kr().optional(),provisional:Sd().optional(),title:z()}),oke=fe({id:z(),line_item_ids:ue(z()),options:ue(n9t).optional(),selected_option_id:M8([U8(),z()]).optional()}),T9t=fe({destinations:ue(o9t).optional(),groups:ue(oke).optional(),id:z(),line_item_ids:ue(z()),selected_destination_id:M8([U8(),z()]).optional(),type:qne}),Cqr=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(H8),signals:Yi.optional()}),Oqr=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),id:z(),line_items:ue(FI),signals:Yi.optional()}),kqr=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy).optional(),messages:ue(G0).optional(),signals:Yi.optional(),totals:ue(Ly),ucp:Fl}),I9t=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(FI),payment:NM.optional(),signals:Yi.optional()}),ske=I9t,Rqr=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy),messages:ue(G0).optional(),order:z8.optional(),payment:$8.optional(),signals:Yi.optional(),status:L8,totals:ue(Ly),ucp:Fl,cart_id:z().optional()}),Vne=fe({categories:ue(z()).optional(),price:s9t.optional()}),D8=fe({max:q8,min:q8}),Kne=fe({name:z(),values:ue(a9t)}),ake=fe({amount:kr(),currency:z(),measure:nke,reference:p9t}),P9t=ake,Nqr=fe({attribution:Xt(z(),z()).optional(),context:Dne.optional(),filters:Vne.optional(),id:z(),preferences:ue(z()).optional(),selected:ue(tke).optional(),signals:Lne.optional()}),Bqr=fe({attribution:Xt(z(),z()).optional(),context:Dne.optional(),filters:Vne.optional(),pagination:f9t.optional(),query:z().optional(),signals:Lne.optional()}),C9t=fe({capabilities:ue(Uxt),services:Xt(z(),y9t),version:z()}),jqr=fe({attribution:Xt(z(),z()).optional(),payment:b9t,signals:Yi.optional()}),cke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy),messages:ue(G0).optional(),order:z8.optional(),payment:$8.optional(),signals:Yi.optional(),status:L8,totals:ue(Ly),ucp:Fl}),O9t=fe({events:ue(v9t).optional(),expectations:ue(w9t).optional()}),uke=fe({attribution:Xt(z(),z()).optional(),buyer:Fne.optional(),context:yo.optional(),line_items:ue(H8),payment:VI.optional(),signals:Yi.optional()}),dke=fe({attribution:Xt(z(),z()).optional(),buyer:x9t.optional(),context:yo.optional(),line_items:ue(FI),payment:NM.optional(),signals:Yi.optional()}),lke=fe({attribution:Xt(z(),z()).optional(),buyer:A9t.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy),messages:ue(G0).optional(),order:z8.optional(),payment:$8.optional(),signals:Yi.optional(),status:L8,totals:ue(Ly),ucp:Fl}),pke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(H8),payment:VI.optional(),signals:Yi.optional(),discounts:XOe.optional()}),k9t=fe({applied:ue(S9t).optional(),codes:ue(z()).optional()}),R9t=fe({destinations:ue(r9t).optional(),groups:ue(oke).optional(),line_item_ids:ue(z()).optional(),selected_destination_id:M8([U8(),z()]).optional(),type:qne}),N9t=fe({available_methods:ue(i9t).optional(),methods:ue(T9t).optional()}),fke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(H8),payment:VI.optional(),signals:Yi.optional(),cart_id:z().optional()}),Uqr=fe({attribution:Xt(z(),z()).optional(),context:Dne.optional(),filters:Vne.optional(),ids:ue(z()),signals:Lne.optional()}),B9t=fe({availability:QOe.optional(),barcodes:ue(eke).optional(),categories:ue(LI).optional(),description:zI,handle:z().optional(),id:z(),list_price:q8.optional(),media:ue(HI).optional(),metadata:Xt(z(),Td()).optional(),options:ue($ne).optional(),price:q8,rating:$I.optional(),seller:rke.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:ake.optional(),url:z().optional(),inputs:ue(d9t)}),mke=fe({availability:c9t.optional(),barcodes:ue(u9t).optional(),categories:ue(LI).optional(),description:zI,handle:z().optional(),id:z(),list_price:q8.optional(),media:ue(HI).optional(),metadata:Xt(z(),Td()).optional(),options:ue($ne).optional(),price:q8,rating:$I.optional(),seller:l9t.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:P9t.optional(),url:z().optional()}),j9t=fe({categories:ue(LI).optional(),description:zI,handle:z().optional(),id:z(),list_price_range:D8.optional(),media:ue(HI).optional(),metadata:Xt(z(),Td()).optional(),options:ue(Kne).optional(),price_range:D8,rating:$I.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(mke)}),Mqr=fe({payment:h9t.optional(),signing_keys:ue(jxt).optional(),ucp:C9t}),hke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(H8),payment:VI.optional(),signals:Yi.optional()}),U9t=fe({adjustments:ue(_9t).optional(),attribution:Xt(z(),z()).optional(),checkout_id:z(),currency:z(),fulfillment:O9t,id:z(),label:z().optional(),line_items:ue(E9t),messages:ue(G0).optional(),permalink_url:z(),totals:ue(Ly),ucp:Fl}),yke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy),messages:ue(G0).optional(),order:z8.optional(),payment:$8.optional(),signals:Yi.optional(),status:L8,totals:ue(Ly),ucp:Fl,discounts:k9t.optional()}),gke=fe({methods:ue(R9t).optional()}),bke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(FI),payment:NM.optional(),signals:Yi.optional(),fulfillment:gke.optional()}),_ke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy),messages:ue(G0).optional(),order:z8.optional(),payment:$8.optional(),signals:Yi.optional(),status:L8,totals:ue(Ly),ucp:Fl,fulfillment:N9t.optional()}),M9t=fe({categories:ue(LI).optional(),description:zI,handle:z().optional(),id:z(),list_price_range:D8.optional(),media:ue(HI).optional(),metadata:Xt(z(),Td()).optional(),options:ue(Kne).optional(),price_range:D8,rating:$I.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(B9t)}),q9t=fe({options:ue(Kne).optional(),selected:ue(tke).optional(),categories:ue(LI).optional(),description:zI,handle:z().optional(),id:z(),list_price_range:D8.optional(),media:ue(HI).optional(),metadata:Xt(z(),Td()).optional(),price_range:D8,rating:$I.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(mke)}),qqr=fe({messages:ue(zne).optional(),pagination:m9t.optional(),products:ue(j9t),ucp:Fl}),vke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(H8),payment:VI.optional(),signals:Yi.optional(),fulfillment:gke.optional()}),Dqr=fe({messages:ue(zne).optional(),products:ue(M9t),ucp:Fl}),Lqr=fe({messages:ue(zne).optional(),product:q9t,ucp:Fl});var Fqr=OM.extend({token:Lr.string().optional()}),D9t=Lr.object({webhook_url:Lr.string().url().optional()}),wke=cke.extend(_ke.pick({fulfillment:!0}).shape).extend(yke.pick({discounts:!0}).shape).extend(lke.pick({buyer:!0}).shape).extend({platform:D9t.optional()}),Eke=hke.extend(vke.pick({fulfillment:!0}).shape).extend(pke.pick({discounts:!0}).shape).extend(uke.pick({buyer:!0}).shape).extend(fke.pick({cart_id:!0}).shape),Ake=ske.extend(bke.pick({fulfillment:!0}).shape).extend(ike.pick({discounts:!0}).shape).extend(dke.pick({buyer:!0}).shape);yd();async function BM(e,t,r){let n=e.headers.get("content-length");if(n!==null){let c=Number(n);if(Number.isSafeInteger(c)&&c>t)throw new Error(r)}if(!e.body)return"";let i=e.body.getReader(),o=new TextDecoder,s=0,a="";try{for(;;){let{done:c,value:u}=await i.read();if(c)break;if(s+=u.byteLength,s>t){try{await i.cancel()}catch{}throw new Error(r)}a+=o.decode(u,{stream:!0})}return a+o.decode()}finally{i.releaseLock()}}function jM(e,t){let r=new AbortController,n=()=>r.abort(t?.reason);t?.aborted?n():t?.addEventListener("abort",n,{once:!0});let i=setTimeout(()=>r.abort(),e);return{signal:r.signal,cleanup:()=>{clearTimeout(i),t?.removeEventListener("abort",n)}}}var L9t=3e4,xke=2*1024*1024,Vl=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function Ske(e,t){let r=new URL(e);if(r.protocol!=="https:")throw new Error(`${t} must use HTTPS`);if(r.username||r.password)throw new Error(`${t} must not contain embedded credentials`);if(r.hash)throw new Error(`${t} must not contain a fragment`);return r}function Tke(e,t){if(!/^[A-Z]{3}$/.test(String(e.currency??"")))throw new Error("UCP checkout input requires an uppercase ISO 4217 currency");if(!Array.isArray(e.line_items)||e.line_items.length===0)throw new Error("UCP checkout input requires at least one line item");if(Object.hasOwn(e,"id"))throw new Error("UCP checkout input must not contain an id; pass it as a top-level argument");if(!(t==="create"?Eke:Ake).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function z9t(e){if(!e||typeof e!="object")return!1;let t=e;if(t.jsonrpc!=="2.0"||!Object.hasOwn(t,"id")||t.id!==null&&typeof t.id!="string"&&typeof t.id!="number")return!1;let r=Object.hasOwn(t,"result"),n=Object.hasOwn(t,"error");if(r===n)return!1;if(!n)return!0;let i=t.error;return!!i&&typeof i=="object"&&!Array.isArray(i)&&typeof i.code=="number"&&typeof i.message=="string"}function Ike(e,t,r,n){try{e[t](r,n)}catch{}}function H9t(e){if(!e||typeof e!="object")return e;let t=e,r=t.ucp;if(!r||typeof r!="object")return e;let n=r.capabilities;return!n||typeof n!="object"||Array.isArray(n)?e:{...t,ucp:{...r,capabilities:Object.fromEntries(Object.entries(n).map(([i,o])=>[i,Array.isArray(o)?o.map(s=>s&&typeof s=="object"?{...s,name:i}:s):o]))}}}var UM=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=Ske(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=Ske(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??L9t,this.boundaryLogger=t.logger??ke}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:Tke(t,"create")})}async getCheckout(t){if(!t)throw new Error("UCP checkout id is required");return await this.callCheckout("get_checkout",{meta:this.metadata(),id:t})}async updateCheckout(t,r){if(!t)throw new Error("UCP checkout id is required");return await this.callCheckout("update_checkout",{meta:this.metadata(),id:t,checkout:Tke(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=jM(this.timeoutMs,this.signal),o=(0,Pke.randomUUID)(),s=new URL(this.endpoint).origin,a=Date.now(),c;try{let u=await this.fetchImpl(this.endpoint,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:n,method:"tools/call",params:{name:t,arguments:r}}),signal:i.signal});c=u.status;let d;try{d=await BM(u,xke,"UCP MCP response exceeds the 2 MiB limit")}catch(m){throw m instanceof Error&&m.message==="UCP MCP response exceeds the 2 MiB limit"?new Vl(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>xke)throw new Vl("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new Vl("UCP MCP response is not valid JSON",void 0,u.status)}if(!z9t(l))throw new Vl("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new Vl("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new Vl(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new Vl(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new Vl("UCP MCP response is missing result.structuredContent");if(!wke.safeParse(H9t(p.structuredContent)).success)throw new Vl("UCP checkout response failed schema validation");return Ike(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw Ike(this.boundaryLogger,"warn","ucp:checkout_rpc_failed",{correlationId:o,endpointOrigin:s,rpcMethod:t,...c===void 0?{}:{httpStatus:c},elapsedMs:Date.now()-a,errorClass:u instanceof Error?u.name:"UnknownError"}),u}finally{i.cleanup()}}};var Oke=require("node:crypto");yd();var qM="2026-04-08",$9t="dev.ucp.shopping",F9t="dev.ucp.shopping.checkout",V9t=1024*1024,K9t=1e4,G9t="https://ucp.dev",KI=Lr.string().url().refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password},"must be an HTTPS URL without embedded credentials"),W9t=Lr.object({version:Lr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:KI,schema:KI,transport:Lr.enum(["rest","mcp","a2a","embedded"]),endpoint:KI.optional()}).passthrough(),J9t=Lr.object({version:Lr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:KI,schema:KI,extends:Lr.union([Lr.string(),Lr.array(Lr.string()).min(1)]).optional()}).passthrough(),Y9t=Lr.object({ucp:Lr.object({version:Lr.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:Lr.record(Lr.array(W9t)),capabilities:Lr.record(Lr.array(J9t)),payment_handlers:Lr.record(Lr.array(Lr.unknown())).optional()}).passthrough(),signing_keys:Lr.array(Lr.unknown()).optional()}).passthrough();function Z9t(e,t){let r=new URL(e);if(r.protocol!=="https:")throw new Error(`${t} must use HTTPS`);if(r.username||r.password)throw new Error(`${t} must not contain embedded credentials`);if(r.pathname!=="/"||r.search||r.hash)throw new Error(`${t} must be a bare origin`);return r}function MM(e,t){if(new URL(e).origin!==G9t)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function Cke(e,t,r,n){try{e[t](r,n)}catch{}}async function X9t(e,t={}){let r=Z9t(e,"UCP business URL"),n=jM(t.timeoutMs??K9t,t.signal),i=t.logger??ke,o=(0,Oke.randomUUID)(),s=Date.now(),a;try{let c=await(t.fetch??fetch)(new URL("/.well-known/ucp",r),{headers:{accept:"application/json"},redirect:"error",signal:n.signal});if(a=c.status,!c.ok)throw new Error(`UCP profile fetch failed with HTTP ${c.status}`);let u=await BM(c,V9t,"UCP profile exceeds the 1 MiB response limit"),d;try{d=JSON.parse(u)}catch{throw new Error("UCP profile response is not valid JSON")}let l=Y9t.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return Cke(i,"info","ucp:profile_fetch",{correlationId:o,businessOrigin:r.origin,method:"GET",httpStatus:a,elapsedMs:Date.now()-s}),{businessOrigin:r.origin,profile:l.data}}catch(c){throw Cke(i,"warn","ucp:profile_fetch_failed",{correlationId:o,businessOrigin:r.origin,method:"GET",...a===void 0?{}:{httpStatus:a},elapsedMs:Date.now()-s,errorClass:c instanceof Error?c.name:"UnknownError"}),c}finally{n.cleanup()}}function Q9t(e){if(e.ucp.version!==qM)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[F9t]?.find(i=>i.version===qM);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");MM(t.spec,"Checkout capability spec"),MM(t.schema,"Checkout capability schema");let r=e.ucp.services[$9t]?.find(i=>i.version===qM&&i.transport==="mcp");if(!r)throw new Error("Business does not advertise a UCP shopping MCP service");if(!r.endpoint)throw new Error("UCP shopping MCP service is missing its endpoint");MM(r.spec,"Shopping service spec"),MM(r.schema,"Shopping service schema");let n=new URL(r.endpoint);if(n.hash)throw new Error("UCP shopping MCP endpoint must not contain a fragment");return n.toString()}async function kke(e,t={}){let r=await X9t(e,t);return{...r,endpoint:Q9t(r.profile),version:qM}}var eSt="https://app.visacli.sh/.well-known/ucp";function tSt(e){let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.hash)throw new Error("UCP platform profile URL must be HTTPS and credential-free");return t.toString()}function rSt(e,t){if(typeof e=="string")try{let r=new URL(e);r.protocol==="https:"&&!r.username&&!r.password&&t.add(r.origin.toLowerCase())}catch{}}function Gne(e,t=new Set){if(Array.isArray(e))for(let r of e)Gne(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?rSt(n,t):Gne(n,t);return t}function nSt(e,t,r){let n=new URL(e),i=new URL(t);if(i.protocol!=="https:"||i.username||i.password)throw new Error("UCP continuation URL must be HTTPS and credential-free");let o=i.hostname.toLowerCase(),s=n.hostname.toLowerCase();if(i.origin.toLowerCase()===n.origin.toLowerCase())return i.hash="",{url:i.toString(),sourceHost:o,targetHost:s,originRewritten:!1};let a=r.ucp.services["dev.ucp.shopping"],c=Gne(a);if(!(o.endsWith(".myshopify.com")&&c.has(i.origin.toLowerCase())))throw new Error(`Refusing cross-host UCP continuation from ${o} to ${s}`);return i.hash="",{url:i.toString(),sourceHost:o,targetHost:o,originRewritten:!1}}function Nke(e){let t=Array.isArray(e.totals)?e.totals.find(a=>a&&typeof a=="object"&&a.type==="total"):void 0,r=t&&typeof t=="object"?t:void 0,n=r?.amount,o=r?.currency??e.currency;if(!Number.isSafeInteger(n)||Number(n)<0)throw new Error("UCP checkout is missing an integer totals[type=total].amount");if(o!=="USD")throw new Error(`UCP checkout handoff currently supports USD only; refusing ${String(o)} until currency exponents are implemented`);let s=Number(n);return{minor:s,decimal:`${Math.floor(s/100)}.${String(s%100).padStart(2,"0")}`,currency:o}}function iSt(e){return Array.isArray(e.messages)?e.messages.flatMap(t=>{if(!t||typeof t!="object")return[];let r=t,n={...typeof r.type=="string"?{type:r.type}:{},...typeof r.code=="string"?{code:r.code}:{},...typeof r.severity=="string"?{severity:r.severity}:{}};return Object.keys(n).length>0?[n]:[]}):[]}async function Bke(e,t){if(!e.business?.trim())throw new Error("UCP business origin is required");if(!e.checkoutId?.trim())throw new Error("UCP checkout id is required");let r=await(t.discover??kke)(e.business),i=await(t.getCheckout??(async(o,s)=>await new UM({endpoint:o.endpoint,platformProfileUrl:tSt(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??eSt)}).getCheckout(s)))(r,e.checkoutId);if(i.id!==e.checkoutId)throw new Error("UCP checkout response id does not match the requested checkout");return{service:r,checkout:i}}async function jke(e,t={}){let{service:r,checkout:n}=await Bke(e,t),i=String(n.status??"unknown");if(i==="completed")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_already_completed"};if(i!=="requires_escalation")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_escalated"};if(typeof n.continue_url!="string"||!n.continue_url)return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_continue_url"};let o=Nke(n),s=nSt(r.businessOrigin,n.continue_url,r.profile),a=`ucp_${(0,Rke.createHash)("sha256").update([r.businessOrigin,e.checkoutId,i,o.currency,String(o.minor),s.url].join("\0")).digest("hex").slice(0,24)}`;return{success:!0,status:"ready_for_review",checkoutId:e.checkoutId,handoffId:a,checkoutStatus:"requires_escalation",amount:o,merchant:{businessOrigin:r.businessOrigin,sourceHost:s.sourceHost,targetHost:s.targetHost,originRewritten:s.originRewritten},payMerchantRequest:{action:"review",url:s.url,amount:o.decimal,currency:o.currency},messages:iSt(n),nextAction:"Copy the payMerchantRequest checkout fields unchanged to pay_merchant and include its required user_context. Show the returned merchant and exact total to the user; never authorize until they explicitly approve PAY <reviewId>."}}function oSt(e){if(!e.order||typeof e.order!="object"||Array.isArray(e.order))return null;let t=e.order;if(typeof t.id!="string"||!t.id.trim()||typeof t.permalink_url!="string"||!t.permalink_url)return null;let r;try{r=new URL(t.permalink_url)}catch{return null}return r.protocol!=="https:"||r.username||r.password||r.hash?null:{id:t.id,permalinkHost:r.hostname.toLowerCase()}}async function Uke(e,t={}){if(!Number.isSafeInteger(e.expectedAmountMinor)||e.expectedAmountMinor<0)throw new Error("UCP reconciliation expectedAmountMinor must be a non-negative integer");if(e.expectedCurrency!=="USD")throw new Error("UCP reconciliation currently supports expectedCurrency USD only");let{checkout:r}=await Bke(e,t),n=Nke(r),i=String(r.status??"unknown");if(n.minor!==e.expectedAmountMinor)return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"amount_mismatch",amount:n,nextAction:"Do not retry payment. The merchant checkout total no longer matches the reviewed amount; reconcile the merchant order manually."};if(i!=="completed")return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_completed",amount:n,nextAction:"Do not retry payment. Poll this same checkout or inspect the merchant order before starting any new review."};let o=oSt(r);return o?{success:!0,status:"confirmed",checkoutId:e.checkoutId,checkoutStatus:"completed",amount:n,order:o,nextAction:"Report success only after matching this UCP order id and amount to the Visa checkout receipt."}:{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_order_confirmation",amount:n,nextAction:"Do not report purchase success or retry payment. The checkout says completed but lacks a valid merchant order confirmation."}}ly();function Wne(){return Ta()}var wd=new bu(()=>pn.getSessionToken()),sSt="4.1.0-rc.58",xDr=["","","You're ready to go! Try:","","Verified Agent:",'\u2022 "Enroll this agent" \u2192 enroll_agent','\u2022 "Show my wallet and policy" \u2192 wallet_status','\u2022 "Find a paid weather service" \u2192 wallet_discover','\u2022 "Pay this x402 service with a $0.10 maximum" \u2192 wallet_pay','\u2022 "Review this card checkout" \u2192 pay_merchant','\u2022 "Show my account status" \u2192 get_status'].join(`
20937
+ If building from source, run native/build-win.bat first.`);tn.mkdirSync(fy,{recursive:!0}),tn.copyFileSync(e,T0);let t=Jj(T0);return tn.writeFileSync(NTe,t,{mode:384}),tn.writeFileSync(RTe,kTe,{mode:384}),T0}async function m5t(){return t8()?Xj():HTe()}var Yj="visa-cli",Zj="attestation-key";async function h5t(e){if(!await lf())throw new Error("macOS Keychain is unavailable in this environment (no default keychain), so the Touch ID key cannot be stored. Run this command in a regular user session.");try{await I0("security",["delete-generic-password","-s",Yj,"-a",Zj],{timeout:5e3})}catch{}try{await I0("security",["add-generic-password","-s",Yj,"-a",Zj,"-w",e],{timeout:5e3})}catch(t){throw new Error(`Could not store the Touch ID key in the macOS Keychain (${y5t(t)}).`)}}function y5t(e){let t=e,r=[t?.stderr,t?.message].filter(n=>typeof n=="string").join(" ").toLowerCase();return/canceled|cancelled/.test(r)?"the Keychain authorization was canceled":/locked/.test(r)?"the Keychain is locked":/not permitted|permission denied|not authorized/.test(r)?"Keychain access was denied":/could not be found|no default keychain/.test(r)?"no default keychain was found":"the security tool reported an error"}function g5t(e){let t=typeof e?.code=="number"?e.code:void 0,r=typeof e?.stderr=="string"?e.stderr:"",n=typeof e?.stdout=="string"?e.stdout:"",i=[r,n,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(i)?{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(i)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:i||"Could not read the local attestation key from Keychain."}}async function b5t(){if(!await lf())return{key:null,status:{state:"denied",usable:!1,message:"macOS Keychain is unavailable in this environment (no default keychain)."}};try{let{stdout:e}=await I0("security",["find-generic-password","-s",Yj,"-a",Zj,"-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:g5t(e)}}}async function _5t(){let e=await b5t();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 FTe(e){let t=await m5t(),r;try{r=(await I0(t,e,{timeout:6e4})).stdout}catch(n){r=n.stdout||"";let i=r.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(n.stderr?.toString().trim()||n.message||"Unknown error")}return f5t(r)}var UTe=!1;function v5t(){if(!t8())return!1;try{return tn.existsSync(T0)||$Te()!==null?!0:(UTe||(UTe=!0,ke.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:T0,searchedPrebuiltPaths:zTe})),!1)}catch{return!1}}function P0(){return BT()||p5t()?!0:t8()?v5t():!1}async function VTe(){if(t8()){let i=await Xj(),{stdout:o}=await I0(i,["generate-key"],{timeout:3e4}),s=o.trim();if(s.startsWith("OK:"))return s.slice(3);throw new Error(s.startsWith("ERROR:")?s.slice(6):"Key generation failed")}let e=await FTe(["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 r=e.slice(0,t),n=e.slice(t+1);return await h5t(r),n}async function rte(e,t,r={}){if(BT())return Promise.resolve(sSe());let n=r.timeoutMs??l5t;if(t8()){let a=await Xj(),c=["sign",e];t&&c.push(t);let u;try{u=(await I0(a,c,{timeout:n})).stdout}catch(l){throw BTe(l)?jTe(n):l}let d=u.trim();if(d.startsWith("OK:"))return d.slice(3);throw new Error(d.startsWith("ERROR:")?d.slice(6):"Unknown error")}let i=await _5t();if(!i)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await HTe(),s=["sign",e];return t&&s.push(t),new Promise((a,c)=>{let u=(0,tte.execFile)(o,s,{timeout:n},(d,l)=>{let p=(l||"").trim();if(d){p.startsWith("ERROR:")?c(new Error(p.slice(6))):BTe(d)?c(jTe(n)):c(new Error(d.stderr?.toString().trim()||d.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):c(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});u.stdin.write(i),u.stdin.end()})}async function Qj(){if(t8()){try{let e=await Xj();await I0(e,["delete-key"],{timeout:1e4})}catch{}return}if(await lf())try{await I0("security",["delete-generic-password","-s",Yj,"-a",Zj],{timeout:5e3})}catch{}try{await FTe(["delete-key"])}catch{}}x0();yd();Tj();VU();u6();var qke=require("child_process"),DM=_e(require("fs")),LM=_e(require("os")),Dke=_e(require("path"));FT();ly();gj();var hOe="4.1.0-rc.59";function Tne(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function iAt(e,t,r){let n=process.env[e];if(n!==void 0)return{value:r==="opt-in"?n==="true":n!=="false",source:{kind:"env",var:e}};let i=Zee(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function T8(e){return e==null?"\u2014":e?"yes":"no"}async function CI(e){let t=null,r=null;try{t=await e.api.getStatus()}catch(l){r=l?.message||"unknown error"}let n=[],i=process.env.VISA_AUTH_URL,o=Yee("auth.serverUrl"),s=Ta(),a=i!==void 0&&i!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};n.push({key:"auth.serverUrl",value:s,formatted:s,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}),n.push({key:"account.enrolled",value:t?.enrolled??null,formatted:T8(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),t?.login&&n.push({key:"account.principal",value:t.login,formatted:t.principalKind?`${t.login} (${t.principalKind})`:t.login,source:{kind:"server"},hint:"The identity your CLI session resolves on. Feature-flag access (checkout, mandate) is granted per this exact principal."}),t?.userId&&n.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=iAt("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:T8(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=uy(),d;if(process.env.VISA_CLI_NO_UPDATE_CHECK?d={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?d={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?d={kind:"env",var:"NODE_ENV"}:d={kind:"default"},n.push({key:"ui.updateCheck",value:!u,formatted:T8(!u),source:d}),n.push({key:"client.version",value:hOe,formatted:hOe,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=oy();n.push({key:"dev.mockKeychain",value:p,formatted:T8(p),source:Tne("VISA_MOCK_KEYCHAIN",!!l),hint:wee()});let f=process.env.VISA_MOCK_TOUCHID,m=BT();n.push({key:"dev.mockTouchid",value:m,formatted:T8(m),source:Tne("VISA_MOCK_TOUCHID",!!f),hint:wee()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:T8(!!h),source:Tne("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}function oAt(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 yOe(e,t={}){if(e.length===0)return"";let r=Math.max(...e.map(o=>o.key.length)),n=Math.max(...e.map(o=>o.formatted.length)),i=[];for(let o of e){let s=o.key.padEnd(r+2),a=o.formatted.padEnd(n+2);i.push(`${s}${a}(${oAt(o.source)})`),t.verbose&&o.hint&&i.push(` ${"\u21B3".padStart(r)} ${o.hint}`)}return i.join(`
20938
+ `)}function gOe(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)}var Nne=require("node:os"),NI=require("node:path"),BI=require("node:fs/promises"),POe=require("node:fs"),COe=require("node:url"),OOe=require("node:crypto");yd();var sAt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function I8(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!sAt.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var H0=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function bOe(e){let t;try{t=new URL(e)}catch{throw new H0(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new H0(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}yd();var aAt={ucp_checkout_handoff:"checkout_agent_access",ucp_checkout_reconcile:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},cAt=300*1e3,Ine={},_Oe=0,OI=null;function uAt(){return OI||(OI=(async()=>{try{let e=await wd.getFeatureFlags();Ine=e&&e.flags||{},_Oe=Date.now()}catch(e){Ine={},ke.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{OI=null}})(),OI)}async function kI(){Date.now()-_Oe<cAt||await uAt()}function By(e){let t=aAt[e];return t?Ine[t]!==!0:!1}var vOe=require("node:crypto"),RI=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},wM=class{constructor(t={}){this.options=t}options;jobsByOperation=new Map;operationByReview=new Map;now(){return(this.options.now??Date.now)()}activeTtlMs(){return this.options.activeTtlMs??300*1e3}terminalTtlMs(){return this.options.terminalTtlMs??300*1e3}async waitUntilQueryable(t){let r;try{await Promise.race([t,new Promise(n=>{r=setTimeout(n,Math.max(0,this.options.initialWaitMs??1e3)),r.unref?.()})])}finally{r&&clearTimeout(r)}}finish(t,r){t.inFlight=!1,t.status=r,t.expiresAtMs=this.now()+this.terminalTtlMs(),t.resolveReady()}pruneExpired(){let t=this.now();for(let[r,n]of this.jobsByOperation)if(!(n.expiresAtMs>t)){if(n.inFlight){(n.status==="starting"||n.status==="awaiting_passkey")&&(n.status="reconciling",n.error="Approval handoff expired while the checkout was in progress; reconcile with the merchant before retrying",n.resolveReady()),n.expiresAtMs=t+this.terminalTtlMs();continue}this.jobsByOperation.delete(r),this.operationByReview.get(n.reviewId)===r&&this.operationByReview.delete(n.reviewId)}}snapshot(t){return{operationId:t.operationId,reviewId:t.reviewId,status:t.status,approvalUrl:t.approvalUrl,result:t.result,error:t.error,expiresAt:new Date(t.expiresAtMs).toISOString()}}get(t){this.pruneExpired();let r=this.jobsByOperation.get(t);return r?this.snapshot(r):null}async start(t){this.pruneExpired();let r=this.operationByReview.get(t.reviewId),n=r?this.jobsByOperation.get(r):void 0;if(n){if(n.fingerprint!==t.fingerprint)throw new RI(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??vOe.randomUUID)(),a={operationId:s,reviewId:t.reviewId,fingerprint:t.fingerprint,status:"starting",approvalUrl:null,result:null,error:null,expiresAtMs:this.now()+this.activeTtlMs(),inFlight:!0,ready:o,resolveReady:i};this.jobsByOperation.set(s,a),this.operationByReview.set(t.reviewId,s);let c=u=>{a.status==="starting"&&(a.approvalUrl=u,a.status="awaiting_passkey",a.resolveReady())};return Promise.resolve().then(()=>t.run(c)).then(u=>{a.result=u,a.error=null,this.finish(a,"completed")}).catch(u=>{a.error=u instanceof Error?u.message:String(u),this.finish(a,"failed")}),await this.waitUntilQueryable(o),this.snapshot(a)}};function kOe(e){return[(0,NI.join)(e,"checkout-engine","index.js"),(0,NI.join)(e,"..","checkout-engine","index.js")]}function _At(e,t=POe.existsSync){return kOe(e).find(r=>t(r))??null}var AM=null,ROe=async()=>{if(AM)return AM;let e=_At(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${kOe(__dirname).join(" and ")}).`);return AM=(await import((0,COe.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await vAt(),cardMandateRegister:await wAt()}),AM};async function vAt(){let e=await Promise.resolve().then(()=>(kne(),One));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function wAt(){let e=await Promise.resolve().then(()=>(kne(),One));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),register:t=>e.registerCardMandate(t)}}async function Bne(){return By("pay_merchant")?(await kI(),By("pay_merchant")):!1}var NOe=(0,NI.join)((0,Nne.homedir)(),".visa-mcp","agent-credential.json"),BOe=(0,NI.join)((0,Nne.homedir)(),".visa-mcp","contact.json"),jOe=new wM;function jI(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var EAt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function UOe(e){return EAt.has(e)?e:null}async function xM(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"pay_merchant",user_prompt:"",tool_params:JSON.stringify({action:e.action,rail:"card",merchant_host:e.merchantHost,amount_minor:e.amountMinor,payment_amount_unit:"major",currency:e.currency,...e.submit===void 0?{}:{submit:e.submit},source:e.source??null,draw_id:e.drawId??null}),result_success:e.success,result_error:e.errorMessage?jI(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null,source:e.source??null,remainingMinor:e.remainingMinor??null,...e.paymentStatus?{paymentStatus:e.paymentStatus}:{},...e.settlementVerified===void 0?{}:{settlementVerified:e.settlementVerified}}),payment_rail:e.action==="pay"&&e.submit===!0?"card":null,payment_amount:e.action==="pay"&&e.submit===!0&&e.source!=="mandate"?e.amountMinor/100:null,payment_currency:UOe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/checkout",resolved_model:null,session_budget_id:null}])}catch(t){ke.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function IOe(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"start_card_mandate",user_prompt:"",tool_params:JSON.stringify({rail:"card",merchant_host:e.merchantHost,ceiling_minor:e.ceilingMinor,currency:e.currency}),result_success:e.success,result_error:e.errorMessage?jI(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,mandateId:e.mandateId??null,remainingMinor:e.remainingMinor??null}),payment_rail:null,payment_amount:null,payment_currency:UOe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/mandate",resolved_model:null,session_budget_id:null}])}catch(t){ke.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function Rne(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new H0(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function MOe(e,t){if(e.status==="completed")return{...e.result??{},action:t,approvalStatus:"completed",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt};if(e.status==="failed"){let r=jI(e.error??"approval failed");return{success:!1,action:t,approvalStatus:"failed",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:`${r}. Nothing was charged unless a returned receipt explicitly says confirmed.`}}return e.status==="awaiting_passkey"&&e.approvalUrl?{success:!0,action:t,approvalStatus:"awaiting_passkey",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,requiresBrowser:!0,browserUrl:e.approvalUrl,approval:{type:"visa_passkey",url:e.approvalUrl,expiresAt:e.expiresAt,button:{label:"Open Visa approval",webApp:{url:e.approvalUrl}}},message:"Open the Visa approval link and complete the passkey. This Telegram or messaging handoff is not itself the passkey and has not charged the card."}:e.status==="reconciling"?{success:!1,action:t,approvalStatus:"reconciling",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:"The approval window expired while checkout was still in progress. Check this operation again for a receipt and reconcile with the merchant before starting a fresh review."}:{success:!0,action:t,approvalStatus:"starting",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:"Visa is preparing the hosted passkey approval. Check this approval again shortly."}}async function qOe(e={},t={}){if(await(t.flagDisabled??Bne)())return{success:!1,message:"pay_merchant_status requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let n=typeof e.operationId=="string"&&/^[A-Za-z0-9_-]{1,200}$/.test(e.operationId)?e.operationId:null;if(!n)return{success:!1,action:"status",approvalStatus:"unknown",message:'A valid operationId from pay_merchant action "authorize" is required.'};let o=(t.approvalJobs??jOe).get(n);return o?MOe(o,"status"):{success:!1,action:"status",operationId:n,approvalStatus:"unknown",message:"No active approval operation exists. It may have expired or the MCP process may have restarted. If approval or merchant submission may have begun, reconcile the merchant order or receipt before starting a fresh review; never retry a purchase blindly."}}async function DOe(e={},t={}){let r=(e.rail??"card").toLowerCase();if(r!=="card")return{success:!1,message:`pay_merchant only implements the "card" rail today (got ${JSON.stringify(r)}). For stablecoin/x402, use the wallet tools (wallet_pay / wallet_directory_pay).`};let n=t.verifyUrl!==void 0?t.verifyUrl:Xee()&&!process.env.VISA_VERIFY_WEB_URL?null:py();if(n===null)return{success:!1,message:"pay_merchant is not available in stable CLI builds (it runs an on-device mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??Bne)())return{success:!1,message:"pay_merchant requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let o=e.action??"review";if(!["review","pay","authorize"].includes(o))return{success:!1,message:`Unknown pay_merchant action ${JSON.stringify(o)}. Use "review" (default), "authorize", or "pay".`};let s=t.approvalJobs??jOe,a,c,u=(e.currency??"USD").toUpperCase();if(!/^[A-Z]{3}$/.test(u))return{success:!1,message:`Invalid currency ${JSON.stringify(e.currency)}. Expected a 3-letter ISO code like "USD".`};try{a=bOe(e.url??"").toString(),c=Rne(e.amount)}catch(I){if(I instanceof H0)return{success:!1,message:I.message};throw I}let d=t.credentialPath??NOe,l=t.contactPath??BOe;try{await(0,BI.readFile)(d,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no checkout started."}}let p;try{p=JSON.parse(await(0,BI.readFile)(l,"utf8"))}catch{return{success:!1,message:`No contact details at ${l}. Write your name/email/address there (chmod 600) first.`}}let f=null;if(o==="pay"||o==="authorize"){let I=typeof e.confirm=="string"?e.confirm.trim():"",T=/^PAY (\S+)$/.exec(I);if(!T)return{success:!1,action:o,message:'Confirmation required: pass confirm:"PAY <reviewId>" using the reviewId from a prior pay_merchant { action:"review" } call. Nothing was charged.'};f=T[1]}let m=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1";if(o==="pay"&&!m)return{success:!1,action:"pay",reviewId:f,outcome:"not-submitted",paymentStatus:"not_submitted",settlementVerified:!1,message:'Checkout submission is disabled. No payment credential was requested, filled, or submitted. Use action:"review" for safe inspection, or explicitly enable checkout submission before a real pay call.'};let h=t.loadEngine??ROe,y;try{y=await h()}catch(I){let T=I instanceof Error?I.message:String(I);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(T))return{success:!1,message:/checkout engine was not packaged/.test(T)?"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No charge was made.":"The checkout browser runtime is not installed (playwright-core is an optional dependency of @visa/cli). Install it with `npm i playwright-core` in the CLI install, then retry. No charge was made."};throw I}let v={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},E=t.emitTelemetry??(I=>wd.emitTelemetry(I)),b=new URL(a).hostname,w=Math.round(Number(c)*100),A=Date.now();if(o==="review"){ke.info("pay_merchant:review",{host:b,currency:u});let I;try{I=await y.review(v)}catch(T){throw await xM({emitTelemetry:E,action:"review",merchantHost:b,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:T instanceof Error?T.message:String(T),startedAt:A}),T}return await xM({emitTelemetry:E,action:"review",merchantHost:b,amountMinor:w,currency:u,outcome:"reviewed",success:!0,startedAt:A}),{success:!0,action:"review",...I,message:`Review ${I.reviewId}: ${I.merchantHost} wants ${I8(I.amountMinor,I.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${I.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let x=f,S=async I=>{ke.info("pay_merchant:pay",{reviewId:x,submit:m,approvalMode:o==="authorize"?"handoff":"blocking"});let T;try{T=await y.pay({...v,reviewId:x,submit:m,...I?{onApprovalUrl:I}:{}})}catch(j){throw await xM({emitTelemetry:E,action:"pay",merchantHost:b,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:j instanceof Error?j.message:String(j),startedAt:A,submit:m}),j}let C=T.outcome==="confirmed"||T.outcome==="reviewed-dry-run",U=T.outcome==="reviewed-dry-run"?"not_submitted":T.outcome==="declined"?"declined":"unverified";await xM({emitTelemetry:E,action:"pay",merchantHost:b,amountMinor:w,currency:u,outcome:T.outcome,confirmationRef:T.confirmationRef,success:C,errorMessage:C?null:T.detail??T.outcome,startedAt:A,submit:m,source:T.source??null,remainingMinor:T.remainingMinor??null,paymentStatus:U,settlementVerified:!1,drawId:T.source==="mandate"?x:null});let M=T.source==="mandate"?` Credential issued from a tap-free active mandate${typeof T.remainingMinor=="number"?` (${T.remainingMinor} ${u} minor units remaining)`:""}.`:T.source==="fresh-tap"?" Credential issued with a fresh per-purchase passkey.":"";return{success:C,action:"pay",reviewId:x,...T,paymentStatus:U,settlementVerified:!1,message:T.outcome==="confirmed"?`Checkout submitted. The merchant reported confirmation ${T.confirmationRef??"(none captured)"}, but processor settlement is not independently verified. Receipt ${T.receiptPath??"(not written)"}.${M}`:T.outcome==="reviewed-dry-run"?"Checkout review validated without requesting, filling, or submitting a payment credential.":T.outcome==="filled-dry-run"?`Legacy credential-disclosure dry-run completed. A usable credential reached the merchant page and may have consumed authority even though no submit click was made.${M}`:`Outcome: ${T.outcome}${T.detail?` \u2014 ${T.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}};if(o==="authorize"){let I=(0,OOe.createHash)("sha256").update(JSON.stringify([x,a,c,u,m])).digest("hex");ke.info("pay_merchant:approval_handoff_started",{reviewId:x,merchantHost:b,currency:u,submit:m});try{let T=await s.start({reviewId:x,fingerprint:I,run:async C=>{try{let U=await S(M=>{ke.info("pay_merchant:approval_handoff_ready",{reviewId:x}),C(M)});return ke.info("pay_merchant:approval_handoff_completed",{reviewId:x,success:U.success===!0}),U}catch(U){throw ke.warn("pay_merchant:approval_handoff_failed",{reviewId:x,error:jI(U instanceof Error?U.message:String(U))}),U}}});return MOe(T,"authorize")}catch(T){if(T instanceof RI)return ke.warn("pay_merchant:approval_handoff_conflict",{reviewId:x}),{success:!1,action:"authorize",reviewId:x,approvalStatus:"conflict",message:"This review already has an approval handoff with different checkout inputs. Do not retry it; create and confirm a fresh review."};throw T}}return S()}async function LOe(e={},t={}){let r=t.verifyUrl!==void 0?t.verifyUrl:py();if(r===null)return{success:!1,message:"start_card_mandate is not available in stable CLI builds (it runs a server-side mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??Bne)())return{success:!1,message:"start_card_mandate requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let i="USD",o;try{o=Rne(e.ceiling)}catch(b){if(b instanceof H0)return{success:!1,message:b.message};throw b}let s;if(e.perTransaction!==void 0){try{s=Rne(e.perTransaction)}catch(b){if(b instanceof H0)return{success:!1,message:b.message};throw b}if(Number(s)>Number(o))return{success:!1,message:"perTransaction cannot exceed the ceiling."}}let a;if(e.intent!==void 0){if(typeof e.intent!="string")return{success:!1,message:"intent must be a short string."};let b=e.intent.replace(/[\p{Cc}\u2028\u2029]/gu,"").trim().slice(0,200).trim();a=b.length>0?b:void 0}let c=t.credentialPath??NOe,u=t.contactPath??BOe;try{await(0,BI.readFile)(c,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no budget was created."}}let d;try{d=JSON.parse(await(0,BI.readFile)(u,"utf8"))}catch{return{success:!1,message:`No contact details at ${u}. Write your name/email/address there (chmod 600) first.`}}let l=t.loadEngine??ROe,p;try{p=await l()}catch(b){let w=b instanceof Error?b.message:String(b);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(w))return{success:!1,message:"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No mandate was created."};throw b}let f="retail-mcc-5999",m=Math.round(Number(o)*100),h=t.emitTelemetry??(b=>wd.emitTelemetry(b)),y=Date.now();ke.info("start_card_mandate:create",{host:f,currency:i});let v;try{v=await p.startCardMandate({...e.agent?.trim()?{agentRef:e.agent.trim()}:{},ceiling:o,currency:i,credentialPath:c,contact:d,approvalBaseUrl:r,...s!==void 0?{perTransaction:s}:{},...a!==void 0?{intent:a}:{}})}catch(b){let w=b instanceof Error?jI(b.message):String(b);return ke.warn("start_card_mandate:failed",{message:w}),await IOe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:"engine-error",success:!1,errorMessage:b instanceof Error?b.message:String(b),startedAt:y}),{success:!1,message:`Could not create the mandate: ${w}`}}let E=v.registerFailed===!0;return E&&ke.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:f}),await IOe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:E?"created-register-failed":"created",success:!E,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:y}),E?{success:!1,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} was created but could NOT be registered for tap-free draws, so it will not be used \u2014 your next pay_merchant will fall through to a fresh per-purchase passkey tap. Re-run to try again once the auth server is reachable.`}:{success:!0,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} active: up to ${I8(m,v.currencyCode)} at eligible retail merchants (network category 5999), across up to ${v.maxDraws} purchases, until ${v.expiresAt}. pay_merchant will draw against it tap-free until the budget, purchase count, or time limit is reached. A declined draw leaves the budget untouched and disables this mandate; the next checkout can use a fresh per-purchase approval.`}}var Rke=require("node:crypto");var Pke=require("node:crypto");var Lr={};Oi(Lr,{BRAND:()=>WAt,DIRTY:()=>g6,EMPTY_PATH:()=>TAt,INVALID:()=>bt,NEVER:()=>xxt,OK:()=>Js,ParseStatus:()=>ls,Schema:()=>zt,ZodAny:()=>My,ZodArray:()=>K0,ZodBigInt:()=>_6,ZodBoolean:()=>v6,ZodBranded:()=>MI,ZodCatch:()=>k6,ZodDate:()=>w6,ZodDefault:()=>O6,ZodDiscriminatedUnion:()=>IM,ZodEffects:()=>xd,ZodEnum:()=>P6,ZodError:()=>fc,ZodFirstPartyTypeKind:()=>xt,ZodFunction:()=>CM,ZodIntersection:()=>S6,ZodIssueCode:()=>ye,ZodLazy:()=>T6,ZodLiteral:()=>I6,ZodMap:()=>N8,ZodNaN:()=>j8,ZodNativeEnum:()=>C6,ZodNever:()=>$l,ZodNull:()=>A6,ZodNullable:()=>Tf,ZodNumber:()=>b6,ZodObject:()=>mc,ZodOptional:()=>Ed,ZodParsedType:()=>je,ZodPipeline:()=>qI,ZodPromise:()=>qy,ZodReadonly:()=>R6,ZodRecord:()=>PM,ZodSchema:()=>zt,ZodSet:()=>B8,ZodString:()=>Uy,ZodSymbol:()=>k8,ZodTransformer:()=>xd,ZodTuple:()=>Sf,ZodType:()=>zt,ZodUndefined:()=>E6,ZodUnion:()=>x6,ZodUnknown:()=>V0,ZodVoid:()=>R8,addIssueToContext:()=>Ie,any:()=>Td,array:()=>ue,bigint:()=>XAt,boolean:()=>Sd,coerce:()=>vu,custom:()=>WOe,date:()=>QAt,datetimeRegex:()=>KOe,defaultErrorMap:()=>$0,discriminatedUnion:()=>sxt,effect:()=>yxt,enum:()=>Id,function:()=>lxt,getErrorMap:()=>P8,getParsedType:()=>xf,instanceof:()=>YAt,intersection:()=>axt,isAborted:()=>SM,isAsync:()=>C8,isDirty:()=>TM,isValid:()=>jy,late:()=>JAt,lazy:()=>pxt,literal:()=>fxt,makeIssue:()=>UI,map:()=>uxt,nan:()=>ZAt,nativeEnum:()=>mxt,never:()=>nxt,null:()=>U8,nullable:()=>bxt,number:()=>kr,object:()=>fe,objectUtil:()=>jne,oboolean:()=>Axt,onumber:()=>Ext,optional:()=>gxt,ostring:()=>wxt,pipeline:()=>vxt,preprocess:()=>_xt,promise:()=>hxt,quotelessJson:()=>AAt,record:()=>Xt,set:()=>dxt,setErrorMap:()=>SAt,strictObject:()=>oxt,string:()=>z,symbol:()=>ext,transformer:()=>yxt,tuple:()=>cxt,undefined:()=>txt,union:()=>M8,unknown:()=>rxt,util:()=>Zt,void:()=>ixt});var Zt;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return e.objectValues(s)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(let s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Zt||(Zt={}));var jne;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(jne||(jne={}));var je=Zt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xf=e=>{switch(typeof e){case"undefined":return je.undefined;case"string":return je.string;case"number":return Number.isNaN(e)?je.nan:je.number;case"boolean":return je.boolean;case"function":return je.function;case"bigint":return je.bigint;case"symbol":return je.symbol;case"object":return Array.isArray(e)?je.array:e===null?je.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?je.promise:typeof Map<"u"&&e instanceof Map?je.map:typeof Set<"u"&&e instanceof Set?je.set:typeof Date<"u"&&e instanceof Date?je.date:je.object;default:return je.unknown}};var ye=Zt.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"]),AAt=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),fc=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}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,Zt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};fc.create=e=>new fc(e);var xAt=(e,t)=>{let r;switch(e.code){case ye.invalid_type:e.received===je.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ye.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Zt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Zt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Zt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Zt.joinValues(e.options)}, received '${e.received}'`;break;case ye.invalid_arguments:r="Invalid function arguments";break;case ye.invalid_return_type:r="Invalid function return type";break;case ye.invalid_date:r="Invalid date";break;case ye.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Zt.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ye.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case ye.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case ye.custom:r="Invalid input";break;case ye.invalid_intersection_types:r="Intersection results could not be merged";break;case ye.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ye.not_finite:r="Number must be finite";break;default:r=t.defaultError,Zt.assertNever(e)}return{message:r}},$0=xAt;var zOe=$0;function SAt(e){zOe=e}function P8(){return zOe}var UI=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:t,defaultError:a}).message;return{...i,path:o,message:a}},TAt=[];function Ie(e,t){let r=P8(),n=UI({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===$0?void 0:$0].filter(i=>!!i)});e.common.issues.push(n)}var ls=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return bt;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return bt;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:t.value,value:n}}},bt=Object.freeze({status:"aborted"}),g6=e=>({status:"dirty",value:e}),Js=e=>({status:"valid",value:e}),SM=e=>e.status==="aborted",TM=e=>e.status==="dirty",jy=e=>e.status==="valid",C8=e=>typeof Promise<"u"&&e instanceof Promise;var tt;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(tt||(tt={}));var Ad=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}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}},HOe=(e,t)=>{if(jy(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 r=new fc(e.common.issues);return this._error=r,this._error}}};function qt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var zt=class{get description(){return this._def.description}_getType(t){return xf(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:xf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ls,ctx:{common:t.parent.common,data:t.data,parsedType:xf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(C8(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xf(t)},i=this._parseSync({data:t,path:n.path,parent:n});return HOe(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xf(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return jy(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>jy(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xf(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(C8(i)?i:Promise.resolve(i));return HOe(n,o)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=t(i),a=()=>o.addIssue({code:ye.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new xd({schema:this,typeName:xt.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:r=>this["~validate"](r)}}optional(){return Ed.create(this,this._def)}nullable(){return Tf.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return K0.create(this)}promise(){return qy.create(this,this._def)}or(t){return x6.create([this,t],this._def)}and(t){return S6.create(this,t,this._def)}transform(t){return new xd({...qt(this._def),schema:this,typeName:xt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new O6({...qt(this._def),innerType:this,defaultValue:r,typeName:xt.ZodDefault})}brand(){return new MI({typeName:xt.ZodBranded,type:this,...qt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new k6({...qt(this._def),innerType:this,catchValue:r,typeName:xt.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return qI.create(this,t)}readonly(){return R6.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},IAt=/^c[^\s-]{8,}$/i,PAt=/^[0-9a-z]+$/,CAt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,OAt=/^[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,kAt=/^[a-z0-9_-]{21}$/i,RAt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,NAt=/^[-+]?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)?)??$/,BAt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,jAt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Une,UAt=/^(?:(?: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])$/,MAt=/^(?:(?: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])$/,qAt=/^(([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]))$/,DAt=/^(([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])$/,LAt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,zAt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,FOe="((\\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])))",HAt=new RegExp(`^${FOe}$`);function VOe(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function $At(e){return new RegExp(`^${VOe(e)}$`)}function KOe(e){let t=`${FOe}T${VOe(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function FAt(e,t){return!!((t==="v4"||!t)&&UAt.test(e)||(t==="v6"||!t)&&qAt.test(e))}function VAt(e,t){if(!RAt.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function KAt(e,t){return!!((t==="v4"||!t)&&MAt.test(e)||(t==="v6"||!t)&&DAt.test(e))}var Uy=class e extends zt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==je.string){let o=this._getOrReturnCtx(t);return Ie(o,{code:ye.invalid_type,expected:je.string,received:o.parsedType}),bt}let n=new ls,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=t.data.length>o.value,a=t.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(t,i),s?Ie(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Ie(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")BAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Une||(Une=new RegExp(jAt,"u")),Une.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")OAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")kAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")IAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")PAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")CAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"ulid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Ie(i,{validation:"url",code:ye.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"regex",code:ye.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.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)||(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?KOe(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?HAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?$At(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?NAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?FAt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?VAt(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?KAt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?LAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?zAt.test(t.data)||(i=this._getOrReturnCtx(t,i),Ie(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Zt.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:ye.invalid_string,...tt.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...tt.errToObj(t)})}url(t){return this._addCheck({kind:"url",...tt.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...tt.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...tt.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...tt.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...tt.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...tt.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...tt.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...tt.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...tt.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...tt.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...tt.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...tt.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,...tt.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,...tt.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...tt.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...tt.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...tt.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...tt.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...tt.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...tt.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...tt.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...tt.errToObj(r)})}nonempty(t){return this.min(1,tt.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 r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Uy.create=e=>new Uy({checks:[],typeName:xt.ZodString,coerce:e?.coerce??!1,...qt(e)});function GAt(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return o%s/10**i}var b6=class e extends zt{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)!==je.number){let o=this._getOrReturnCtx(t);return Ie(o,{code:ye.invalid_type,expected:je.number,received:o.parsedType}),bt}let n,i=new ls;for(let o of this._def.checks)o.kind==="int"?Zt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?GAt(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.not_finite,message:o.message}),i.dirty()):Zt.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,tt.toString(r))}gt(t,r){return this.setLimit("min",t,!1,tt.toString(r))}lte(t,r){return this.setLimit("max",t,!0,tt.toString(r))}lt(t,r){return this.setLimit("max",t,!1,tt.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:tt.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:tt.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:tt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:tt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:tt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:tt.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:tt.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:tt.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:tt.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:tt.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Zt.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};b6.create=e=>new b6({checks:[],typeName:xt.ZodNumber,coerce:e?.coerce||!1,...qt(e)});var _6=class e extends zt{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)!==je.bigint)return this._getInvalidInput(t);let n,i=new ls;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),Ie(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Zt.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Ie(r,{code:ye.invalid_type,expected:je.bigint,received:r.parsedType}),bt}gte(t,r){return this.setLimit("min",t,!0,tt.toString(r))}gt(t,r){return this.setLimit("min",t,!1,tt.toString(r))}lte(t,r){return this.setLimit("max",t,!0,tt.toString(r))}lt(t,r){return this.setLimit("max",t,!1,tt.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:tt.toString(i)}]})}_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:tt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:tt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:tt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:tt.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:tt.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};_6.create=e=>new _6({checks:[],typeName:xt.ZodBigInt,coerce:e?.coerce??!1,...qt(e)});var v6=class extends zt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==je.boolean){let n=this._getOrReturnCtx(t);return Ie(n,{code:ye.invalid_type,expected:je.boolean,received:n.parsedType}),bt}return Js(t.data)}};v6.create=e=>new v6({typeName:xt.ZodBoolean,coerce:e?.coerce||!1,...qt(e)});var w6=class e extends zt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==je.date){let o=this._getOrReturnCtx(t);return Ie(o,{code:ye.invalid_type,expected:je.date,received:o.parsedType}),bt}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Ie(o,{code:ye.invalid_date}),bt}let n=new ls,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),Ie(i,{code:ye.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Zt.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:tt.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:tt.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};w6.create=e=>new w6({checks:[],coerce:e?.coerce||!1,typeName:xt.ZodDate,...qt(e)});var k8=class extends zt{_parse(t){if(this._getType(t)!==je.symbol){let n=this._getOrReturnCtx(t);return Ie(n,{code:ye.invalid_type,expected:je.symbol,received:n.parsedType}),bt}return Js(t.data)}};k8.create=e=>new k8({typeName:xt.ZodSymbol,...qt(e)});var E6=class extends zt{_parse(t){if(this._getType(t)!==je.undefined){let n=this._getOrReturnCtx(t);return Ie(n,{code:ye.invalid_type,expected:je.undefined,received:n.parsedType}),bt}return Js(t.data)}};E6.create=e=>new E6({typeName:xt.ZodUndefined,...qt(e)});var A6=class extends zt{_parse(t){if(this._getType(t)!==je.null){let n=this._getOrReturnCtx(t);return Ie(n,{code:ye.invalid_type,expected:je.null,received:n.parsedType}),bt}return Js(t.data)}};A6.create=e=>new A6({typeName:xt.ZodNull,...qt(e)});var My=class extends zt{constructor(){super(...arguments),this._any=!0}_parse(t){return Js(t.data)}};My.create=e=>new My({typeName:xt.ZodAny,...qt(e)});var V0=class extends zt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Js(t.data)}};V0.create=e=>new V0({typeName:xt.ZodUnknown,...qt(e)});var $l=class extends zt{_parse(t){let r=this._getOrReturnCtx(t);return Ie(r,{code:ye.invalid_type,expected:je.never,received:r.parsedType}),bt}};$l.create=e=>new $l({typeName:xt.ZodNever,...qt(e)});var R8=class extends zt{_parse(t){if(this._getType(t)!==je.undefined){let n=this._getOrReturnCtx(t);return Ie(n,{code:ye.invalid_type,expected:je.void,received:n.parsedType}),bt}return Js(t.data)}};R8.create=e=>new R8({typeName:xt.ZodVoid,...qt(e)});var K0=class e extends zt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==je.array)return Ie(r,{code:ye.invalid_type,expected:je.array,received:r.parsedType}),bt;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Ie(r,{code:s?ye.too_big:ye.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Ie(r,{code:ye.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Ie(r,{code:ye.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new Ad(r,s,r.path,a)))).then(s=>ls.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Ad(r,s,r.path,a)));return ls.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:tt.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:tt.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:tt.toString(r)}})}nonempty(t){return this.min(1,t)}};K0.create=(e,t)=>new K0({type:e,minLength:null,maxLength:null,exactLength:null,typeName:xt.ZodArray,...qt(t)});function O8(e){if(e instanceof mc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Ed.create(O8(n))}return new mc({...e._def,shape:()=>t})}else return e instanceof K0?new K0({...e._def,type:O8(e.element)}):e instanceof Ed?Ed.create(O8(e.unwrap())):e instanceof Tf?Tf.create(O8(e.unwrap())):e instanceof Sf?Sf.create(e.items.map(t=>O8(t))):e}var mc=class e extends zt{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(),r=Zt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==je.object){let u=this._getOrReturnCtx(t);return Ie(u,{code:ye.invalid_type,expected:je.object,received:u.parsedType}),bt}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof $l&&this._def.unknownKeys==="strip"))for(let u in i.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let d=o[u],l=i.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new Ad(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof $l){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")a.length>0&&(Ie(i,{code:ye.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=i.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new Ad(i,l,i.path,d)),alwaysSet:d in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,p=await d.value;u.push({key:l,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>ls.mergeObjectSync(n,u)):ls.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return tt.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:tt.errToObj(t).message??i}:{message:i}}}:{}})}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:xt.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of Zt.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of Zt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return O8(this)}partial(t){let r={};for(let n of Zt.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of Zt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Ed;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return GOe(Zt.objectKeys(this.shape))}};mc.create=(e,t)=>new mc({shape:()=>e,unknownKeys:"strip",catchall:$l.create(),typeName:xt.ZodObject,...qt(t)});mc.strictCreate=(e,t)=>new mc({shape:()=>e,unknownKeys:"strict",catchall:$l.create(),typeName:xt.ZodObject,...qt(t)});mc.lazycreate=(e,t)=>new mc({shape:e,unknownKeys:"strip",catchall:$l.create(),typeName:xt.ZodObject,...qt(t)});var x6=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(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 r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new fc(a.ctx.common.issues));return Ie(r,{code:ye.invalid_union,unionErrors:s}),bt}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new fc(c));return Ie(r,{code:ye.invalid_union,unionErrors:a}),bt}}get options(){return this._def.options}};x6.create=(e,t)=>new x6({options:e,typeName:xt.ZodUnion,...qt(t)});var F0=e=>e instanceof T6?F0(e.schema):e instanceof xd?F0(e.innerType()):e instanceof I6?[e.value]:e instanceof P6?e.options:e instanceof C6?Zt.objectValues(e.enum):e instanceof O6?F0(e._def.innerType):e instanceof E6?[void 0]:e instanceof A6?[null]:e instanceof Ed?[void 0,...F0(e.unwrap())]:e instanceof Tf?[null,...F0(e.unwrap())]:e instanceof MI||e instanceof R6?F0(e.unwrap()):e instanceof k6?F0(e._def.innerType):[],IM=class e extends zt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==je.object)return Ie(r,{code:ye.invalid_type,expected:je.object,received:r.parsedType}),bt;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(Ie(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),bt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let s=F0(o.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new e({typeName:xt.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...qt(n)})}};function Mne(e,t){let r=xf(e),n=xf(t);if(e===t)return{valid:!0,data:e};if(r===je.object&&n===je.object){let i=Zt.objectKeys(t),o=Zt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=Mne(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===je.array&&n===je.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=t[o],c=Mne(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===je.date&&n===je.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var S6=class extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(SM(o)||SM(s))return bt;let a=Mne(o.value,s.value);return a.valid?((TM(o)||TM(s))&&r.dirty(),{status:r.value,value:a.data}):(Ie(n,{code:ye.invalid_intersection_types}),bt)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};S6.create=(e,t,r)=>new S6({left:e,right:t,typeName:xt.ZodIntersection,...qt(r)});var Sf=class e extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.array)return Ie(n,{code:ye.invalid_type,expected:je.array,received:n.parsedType}),bt;if(n.data.length<this._def.items.length)return Ie(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),bt;!this._def.rest&&n.data.length>this._def.items.length&&(Ie(n,{code:ye.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ad(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ls.mergeArray(r,s)):ls.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Sf.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Sf({items:e,typeName:xt.ZodTuple,rest:null,...qt(t)})};var PM=class e extends zt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.object)return Ie(n,{code:ye.invalid_type,expected:je.object,received:n.parsedType}),bt;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Ad(n,a,n.path,a)),value:s._parse(new Ad(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ls.mergeObjectAsync(r,i):ls.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof zt?new e({keyType:t,valueType:r,typeName:xt.ZodRecord,...qt(n)}):new e({keyType:Uy.create(),valueType:t,typeName:xt.ZodRecord,...qt(r)})}},N8=class extends zt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.map)return Ie(n,{code:ye.invalid_type,expected:je.map,received:n.parsedType}),bt;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new Ad(n,a,n.path,[u,"key"])),value:o._parse(new Ad(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return bt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return bt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};N8.create=(e,t,r)=>new N8({valueType:t,keyType:e,typeName:xt.ZodMap,...qt(r)});var B8=class e extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.set)return Ie(n,{code:ye.invalid_type,expected:je.set,received:n.parsedType}),bt;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Ie(n,{code:ye.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Ie(n,{code:ye.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(c){let u=new Set;for(let d of c){if(d.status==="aborted")return bt;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new Ad(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:tt.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:tt.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};B8.create=(e,t)=>new B8({valueType:e,minSize:null,maxSize:null,typeName:xt.ZodSet,...qt(t)});var CM=class e extends zt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==je.function)return Ie(r,{code:ye.invalid_type,expected:je.function,received:r.parsedType}),bt;function n(a,c){return UI({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,P8(),$0].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return UI({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,P8(),$0].filter(u=>!!u),issueData:{code:ye.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof qy){let a=this;return Js(async function(...c){let u=new fc([]),d=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(s,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(f=>{throw u.addIssue(i(l,f)),u})})}else{let a=this;return Js(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new fc([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new fc([i(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Sf.create(t).rest(V0.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,r,n){return new e({args:t||Sf.create([]).rest(V0.create()),returns:r||V0.create(),typeName:xt.ZodFunction,...qt(n)})}},T6=class extends zt{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};T6.create=(e,t)=>new T6({getter:e,typeName:xt.ZodLazy,...qt(t)});var I6=class extends zt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Ie(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),bt}return{status:"valid",value:t.data}}get value(){return this._def.value}};I6.create=(e,t)=>new I6({value:e,typeName:xt.ZodLiteral,...qt(t)});function GOe(e,t){return new P6({values:e,typeName:xt.ZodEnum,...qt(t)})}var P6=class e extends zt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Ie(r,{expected:Zt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),bt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return Ie(r,{received:r.data,code:ye.invalid_enum_value,options:n}),bt}return Js(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};P6.create=GOe;var C6=class extends zt{_parse(t){let r=Zt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==je.string&&n.parsedType!==je.number){let i=Zt.objectValues(r);return Ie(n,{expected:Zt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),bt}if(this._cache||(this._cache=new Set(Zt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Zt.objectValues(r);return Ie(n,{received:n.data,code:ye.invalid_enum_value,options:i}),bt}return Js(t.data)}get enum(){return this._def.values}};C6.create=(e,t)=>new C6({values:e,typeName:xt.ZodNativeEnum,...qt(t)});var qy=class extends zt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==je.promise&&r.common.async===!1)return Ie(r,{code:ye.invalid_type,expected:je.promise,received:r.parsedType}),bt;let n=r.parsedType===je.promise?r.data:Promise.resolve(r.data);return Js(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};qy.create=(e,t)=>new qy({type:e,typeName:xt.ZodPromise,...qt(t)});var xd=class extends zt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s=>{Ie(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return bt;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?bt:c.status==="dirty"?g6(c.value):r.value==="dirty"?g6(c.value):c});{if(r.value==="aborted")return bt;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?bt:a.status==="dirty"?g6(a.value):r.value==="dirty"?g6(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.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(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?bt:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?bt:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!jy(s))return bt;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>jy(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):bt);Zt.assertNever(i)}};xd.create=(e,t,r)=>new xd({schema:e,typeName:xt.ZodEffects,effect:t,...qt(r)});xd.createWithPreprocess=(e,t,r)=>new xd({schema:t,effect:{type:"preprocess",transform:e},typeName:xt.ZodEffects,...qt(r)});var Ed=class extends zt{_parse(t){return this._getType(t)===je.undefined?Js(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ed.create=(e,t)=>new Ed({innerType:e,typeName:xt.ZodOptional,...qt(t)});var Tf=class extends zt{_parse(t){return this._getType(t)===je.null?Js(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Tf.create=(e,t)=>new Tf({innerType:e,typeName:xt.ZodNullable,...qt(t)});var O6=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===je.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};O6.create=(e,t)=>new O6({innerType:e,typeName:xt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...qt(t)});var k6=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return C8(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new fc(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new fc(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};k6.create=(e,t)=>new k6({innerType:e,typeName:xt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...qt(t)});var j8=class extends zt{_parse(t){if(this._getType(t)!==je.nan){let n=this._getOrReturnCtx(t);return Ie(n,{code:ye.invalid_type,expected:je.nan,received:n.parsedType}),bt}return{status:"valid",value:t.data}}};j8.create=e=>new j8({typeName:xt.ZodNaN,...qt(e)});var WAt=Symbol("zod_brand"),MI=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},qI=class e extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?bt:o.status==="dirty"?(r.dirty(),g6(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?bt:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:xt.ZodPipeline})}},R6=class extends zt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(jy(i)&&(i.value=Object.freeze(i.value)),i);return C8(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};R6.create=(e,t)=>new R6({innerType:e,typeName:xt.ZodReadonly,...qt(t)});function $Oe(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function WOe(e,t={},r){return e?My.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=$Oe(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=$Oe(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):My.create()}var JAt={object:mc.lazycreate},xt;(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"})(xt||(xt={}));var YAt=(e,t={message:`Input not instance of ${e.name}`})=>WOe(r=>r instanceof e,t),z=Uy.create,kr=b6.create,ZAt=j8.create,XAt=_6.create,Sd=v6.create,QAt=w6.create,ext=k8.create,txt=E6.create,U8=A6.create,Td=My.create,rxt=V0.create,nxt=$l.create,ixt=R8.create,ue=K0.create,fe=mc.create,oxt=mc.strictCreate,M8=x6.create,sxt=IM.create,axt=S6.create,cxt=Sf.create,Xt=PM.create,uxt=N8.create,dxt=B8.create,lxt=CM.create,pxt=T6.create,fxt=I6.create,Id=P6.create,mxt=C6.create,hxt=qy.create,yxt=xd.create,gxt=Ed.create,bxt=Tf.create,_xt=xd.createWithPreprocess,vxt=qI.create,wxt=()=>z().optional(),Ext=()=>kr().optional(),Axt=()=>Sd().optional(),vu={string:(e=>Uy.create({...e,coerce:!0})),number:(e=>b6.create({...e,coerce:!0})),boolean:(e=>v6.create({...e,coerce:!0})),bigint:(e=>_6.create({...e,coerce:!0})),date:(e=>w6.create({...e,coerce:!0}))};var xxt=bt;var Txt=Id(["enc","sig"]),Ixt=Id(["markdown","plain"]),Pxt=Id(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),Cxt=Id(["error","info","warning"]),L8=Id(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),Oxt=Id(["completed","failed","pending"]),kxt=Id(["digital","pickup","shipping"]),Rxt=Id(["fulfilled","partial","processing","removed"]),Nxt=Id(["across","each"]),qne=Id(["pickup","shipping"]),Bxt=fe({config:Xt(z(),Td()),config_schema:z(),id:z(),instrument_schemas:ue(z()),name:z(),spec:z(),version:z()}),jxt=fe({alg:z().optional(),crv:z().optional(),e:z().optional(),kid:z(),kty:z(),n:z().optional(),use:Txt.optional(),x:z().optional(),y:z().optional()}),Uxt=fe({config:Xt(z(),Td()).optional(),extends:z().optional(),name:z(),schema:z(),spec:z(),version:z()}),Mxt=fe({endpoint:z()}),qxt=fe({schema:z()}),JOe=fe({endpoint:z(),schema:z()}),Dxt=JOe,Lxt=JOe,Ia=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional()}),yo=fe({address_country:z().optional(),address_region:z().optional(),currency:z().optional(),eligibility:ue(z()).optional(),intent:z().optional(),language:z().optional(),postal_code:z().optional()}),Dne=yo,YOe=fe({id:z()}),zxt=YOe,Hxt=YOe,DI=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional()}),OM=fe({type:z()}),Yi=fe({"dev.ucp.buyer_ip":z().optional(),"dev.ucp.user_agent":z().optional()}),Lne=Yi,ZOe=fe({id:z(),image_url:z().optional(),price:kr(),title:z()}),kM=fe({amount:kr(),display_text:z().optional(),type:z()}),Dy=fe({title:z().optional(),type:z(),url:z()}),G0=fe({code:z().optional(),content:z(),content_type:Ixt.optional(),path:z().optional(),severity:Pxt.optional(),type:Cxt,image_url:z().optional(),presentation:z().optional(),url:z().optional()}),zne=G0,z8=fe({id:z(),label:z().optional(),permalink_url:z()}),$xt=fe({amount:kr(),display_text:z()}),Fxt=fe({config:Xt(z(),Td()).optional(),extends:z().optional(),name:z(),schema:z().optional(),spec:z().optional(),version:z()}),Hne=fe({id:z(),quantity:kr()}),Vxt=Hne,Kxt=Hne,Gxt=Hne,Wxt=fe({fulfilled:kr(),original:kr().optional(),total:kr()}),Jxt=fe({billing_address:DI.optional(),credential:OM.optional(),display:Xt(z(),Td()).optional(),handler_id:z(),id:z(),type:z()}),Yxt=fe({checkout_mandate:z()}),Zxt=fe({merchant_authorization:z().optional(),checkout_mandate:z()}),Xxt=fe({analytics:Sd().optional(),marketing:Sd().optional(),preferences:Sd().optional(),sale_of_data:Sd().optional()});var Qxt=Xxt;var XOe=fe({codes:ue(z()).optional()}),e9t=XOe,t9t=fe({amount:kr(),path:z()}),r9t=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional(),id:z().optional(),address:DI.optional(),name:z().optional()}),n9t=fe({carrier:z().optional(),description:z().optional(),earliest_fulfillment_time:vu.date().optional(),id:z(),latest_fulfillment_time:vu.date().optional(),title:z(),totals:ue(kM)}),i9t=fe({description:z().optional(),fulfillable_on:M8([U8(),z()]).optional(),line_item_ids:ue(z()),type:qne}),o9t=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional(),id:z(),address:DI.optional(),name:z().optional()}),s9t=fe({max:kr().optional(),min:kr().optional()}),LI=fe({taxonomy:z().optional(),value:z()}),zI=fe({html:z().optional(),markdown:z().optional(),plain:z().optional()}),q8=fe({amount:kr(),currency:z()}),HI=fe({alt_text:z().optional(),height:kr().optional(),type:z(),url:z(),width:kr().optional()}),a9t=fe({id:z().optional(),label:z()}),$I=fe({count:kr().optional(),scale_max:kr(),scale_min:kr().optional(),value:kr()}),QOe=fe({available:Sd().optional(),status:z().optional()}),c9t=QOe,eke=fe({type:z(),value:z()}),u9t=eke,d9t=fe({id:z(),match:z().optional()}),$ne=fe({id:z().optional(),label:z(),name:z()}),tke=$ne,rke=fe({links:ue(Dy).optional(),name:z().optional()}),l9t=rke,nke=fe({unit:z(),value:kr()});var p9t=nke,f9t=fe({cursor:z().optional(),limit:kr().optional()}),m9t=fe({cursor:z().optional(),has_next_page:Sd(),total_count:kr().optional()}),h9t=fe({handlers:ue(Bxt).optional()}),y9t=fe({a2a:Mxt.optional(),embedded:qxt.optional(),mcp:Dxt.optional(),rest:Lxt.optional(),spec:z(),version:z()}),H8=fe({item:zxt,quantity:kr()}),g9t=fe({billing_address:DI.optional(),credential:OM.optional(),display:Xt(z(),Td()).optional(),handler_id:z(),id:z(),type:z(),selected:Sd().optional()}),FI=fe({id:z().optional(),item:Hxt,parent_id:z().optional(),quantity:kr()}),RM=fe({instruments:ue(g9t).optional()}),b9t=RM,VI=RM,$8=RM,NM=RM,N6=fe({id:z(),item:ZOe,parent_id:z().optional(),quantity:kr(),totals:ue(kM)}),Ly=fe({amount:kr(),display_text:z().optional(),type:z(),lines:ue($xt).optional()}),Fl=fe({capabilities:Xt(z(),ue(Fxt)),version:z()}),_9t=fe({description:z().optional(),id:z(),line_items:ue(Vxt).optional(),occurred_at:vu.date(),status:Oxt,totals:ue(kM).optional(),type:z()}),v9t=fe({carrier:z().optional(),description:z().optional(),id:z(),line_items:ue(Kxt),occurred_at:vu.date(),tracking_number:z().optional(),tracking_url:z().optional(),type:z()}),w9t=fe({description:z().optional(),destination:DI,fulfillable_on:z().optional(),id:z(),line_items:ue(Gxt),method_type:kxt}),E9t=fe({id:z(),item:ZOe,parent_id:z().optional(),quantity:Wxt,status:Rxt,totals:ue(kM)}),Tqr=fe({payment_data:Jxt}),Iqr=fe({ap2:Yxt.optional()}),Pqr=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy),messages:ue(G0).optional(),order:z8.optional(),payment:$8.optional(),signals:Yi.optional(),status:L8,totals:ue(Ly),ucp:Fl,ap2:Zxt.optional()}),Fne=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),consent:Qxt.optional()}),A9t=Fne,x9t=Fne,ike=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(FI),payment:NM.optional(),signals:Yi.optional(),discounts:e9t.optional()}),S9t=fe({allocations:ue(t9t).optional(),amount:kr(),automatic:Sd().optional(),code:z().optional(),eligibility:z().optional(),method:Nxt.optional(),priority:kr().optional(),provisional:Sd().optional(),title:z()}),oke=fe({id:z(),line_item_ids:ue(z()),options:ue(n9t).optional(),selected_option_id:M8([U8(),z()]).optional()}),T9t=fe({destinations:ue(o9t).optional(),groups:ue(oke).optional(),id:z(),line_item_ids:ue(z()),selected_destination_id:M8([U8(),z()]).optional(),type:qne}),Cqr=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(H8),signals:Yi.optional()}),Oqr=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),id:z(),line_items:ue(FI),signals:Yi.optional()}),kqr=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy).optional(),messages:ue(G0).optional(),signals:Yi.optional(),totals:ue(Ly),ucp:Fl}),I9t=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(FI),payment:NM.optional(),signals:Yi.optional()}),ske=I9t,Rqr=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy),messages:ue(G0).optional(),order:z8.optional(),payment:$8.optional(),signals:Yi.optional(),status:L8,totals:ue(Ly),ucp:Fl,cart_id:z().optional()}),Vne=fe({categories:ue(z()).optional(),price:s9t.optional()}),D8=fe({max:q8,min:q8}),Kne=fe({name:z(),values:ue(a9t)}),ake=fe({amount:kr(),currency:z(),measure:nke,reference:p9t}),P9t=ake,Nqr=fe({attribution:Xt(z(),z()).optional(),context:Dne.optional(),filters:Vne.optional(),id:z(),preferences:ue(z()).optional(),selected:ue(tke).optional(),signals:Lne.optional()}),Bqr=fe({attribution:Xt(z(),z()).optional(),context:Dne.optional(),filters:Vne.optional(),pagination:f9t.optional(),query:z().optional(),signals:Lne.optional()}),C9t=fe({capabilities:ue(Uxt),services:Xt(z(),y9t),version:z()}),jqr=fe({attribution:Xt(z(),z()).optional(),payment:b9t,signals:Yi.optional()}),cke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy),messages:ue(G0).optional(),order:z8.optional(),payment:$8.optional(),signals:Yi.optional(),status:L8,totals:ue(Ly),ucp:Fl}),O9t=fe({events:ue(v9t).optional(),expectations:ue(w9t).optional()}),uke=fe({attribution:Xt(z(),z()).optional(),buyer:Fne.optional(),context:yo.optional(),line_items:ue(H8),payment:VI.optional(),signals:Yi.optional()}),dke=fe({attribution:Xt(z(),z()).optional(),buyer:x9t.optional(),context:yo.optional(),line_items:ue(FI),payment:NM.optional(),signals:Yi.optional()}),lke=fe({attribution:Xt(z(),z()).optional(),buyer:A9t.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy),messages:ue(G0).optional(),order:z8.optional(),payment:$8.optional(),signals:Yi.optional(),status:L8,totals:ue(Ly),ucp:Fl}),pke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(H8),payment:VI.optional(),signals:Yi.optional(),discounts:XOe.optional()}),k9t=fe({applied:ue(S9t).optional(),codes:ue(z()).optional()}),R9t=fe({destinations:ue(r9t).optional(),groups:ue(oke).optional(),line_item_ids:ue(z()).optional(),selected_destination_id:M8([U8(),z()]).optional(),type:qne}),N9t=fe({available_methods:ue(i9t).optional(),methods:ue(T9t).optional()}),fke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(H8),payment:VI.optional(),signals:Yi.optional(),cart_id:z().optional()}),Uqr=fe({attribution:Xt(z(),z()).optional(),context:Dne.optional(),filters:Vne.optional(),ids:ue(z()),signals:Lne.optional()}),B9t=fe({availability:QOe.optional(),barcodes:ue(eke).optional(),categories:ue(LI).optional(),description:zI,handle:z().optional(),id:z(),list_price:q8.optional(),media:ue(HI).optional(),metadata:Xt(z(),Td()).optional(),options:ue($ne).optional(),price:q8,rating:$I.optional(),seller:rke.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:ake.optional(),url:z().optional(),inputs:ue(d9t)}),mke=fe({availability:c9t.optional(),barcodes:ue(u9t).optional(),categories:ue(LI).optional(),description:zI,handle:z().optional(),id:z(),list_price:q8.optional(),media:ue(HI).optional(),metadata:Xt(z(),Td()).optional(),options:ue($ne).optional(),price:q8,rating:$I.optional(),seller:l9t.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:P9t.optional(),url:z().optional()}),j9t=fe({categories:ue(LI).optional(),description:zI,handle:z().optional(),id:z(),list_price_range:D8.optional(),media:ue(HI).optional(),metadata:Xt(z(),Td()).optional(),options:ue(Kne).optional(),price_range:D8,rating:$I.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(mke)}),Mqr=fe({payment:h9t.optional(),signing_keys:ue(jxt).optional(),ucp:C9t}),hke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(H8),payment:VI.optional(),signals:Yi.optional()}),U9t=fe({adjustments:ue(_9t).optional(),attribution:Xt(z(),z()).optional(),checkout_id:z(),currency:z(),fulfillment:O9t,id:z(),label:z().optional(),line_items:ue(E9t),messages:ue(G0).optional(),permalink_url:z(),totals:ue(Ly),ucp:Fl}),yke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy),messages:ue(G0).optional(),order:z8.optional(),payment:$8.optional(),signals:Yi.optional(),status:L8,totals:ue(Ly),ucp:Fl,discounts:k9t.optional()}),gke=fe({methods:ue(R9t).optional()}),bke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(FI),payment:NM.optional(),signals:Yi.optional(),fulfillment:gke.optional()}),_ke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),continue_url:z().optional(),currency:z(),expires_at:vu.date().optional(),id:z(),line_items:ue(N6),links:ue(Dy),messages:ue(G0).optional(),order:z8.optional(),payment:$8.optional(),signals:Yi.optional(),status:L8,totals:ue(Ly),ucp:Fl,fulfillment:N9t.optional()}),M9t=fe({categories:ue(LI).optional(),description:zI,handle:z().optional(),id:z(),list_price_range:D8.optional(),media:ue(HI).optional(),metadata:Xt(z(),Td()).optional(),options:ue(Kne).optional(),price_range:D8,rating:$I.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(B9t)}),q9t=fe({options:ue(Kne).optional(),selected:ue(tke).optional(),categories:ue(LI).optional(),description:zI,handle:z().optional(),id:z(),list_price_range:D8.optional(),media:ue(HI).optional(),metadata:Xt(z(),Td()).optional(),price_range:D8,rating:$I.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(mke)}),qqr=fe({messages:ue(zne).optional(),pagination:m9t.optional(),products:ue(j9t),ucp:Fl}),vke=fe({attribution:Xt(z(),z()).optional(),buyer:Ia.optional(),context:yo.optional(),line_items:ue(H8),payment:VI.optional(),signals:Yi.optional(),fulfillment:gke.optional()}),Dqr=fe({messages:ue(zne).optional(),products:ue(M9t),ucp:Fl}),Lqr=fe({messages:ue(zne).optional(),product:q9t,ucp:Fl});var Fqr=OM.extend({token:Lr.string().optional()}),D9t=Lr.object({webhook_url:Lr.string().url().optional()}),wke=cke.extend(_ke.pick({fulfillment:!0}).shape).extend(yke.pick({discounts:!0}).shape).extend(lke.pick({buyer:!0}).shape).extend({platform:D9t.optional()}),Eke=hke.extend(vke.pick({fulfillment:!0}).shape).extend(pke.pick({discounts:!0}).shape).extend(uke.pick({buyer:!0}).shape).extend(fke.pick({cart_id:!0}).shape),Ake=ske.extend(bke.pick({fulfillment:!0}).shape).extend(ike.pick({discounts:!0}).shape).extend(dke.pick({buyer:!0}).shape);yd();async function BM(e,t,r){let n=e.headers.get("content-length");if(n!==null){let c=Number(n);if(Number.isSafeInteger(c)&&c>t)throw new Error(r)}if(!e.body)return"";let i=e.body.getReader(),o=new TextDecoder,s=0,a="";try{for(;;){let{done:c,value:u}=await i.read();if(c)break;if(s+=u.byteLength,s>t){try{await i.cancel()}catch{}throw new Error(r)}a+=o.decode(u,{stream:!0})}return a+o.decode()}finally{i.releaseLock()}}function jM(e,t){let r=new AbortController,n=()=>r.abort(t?.reason);t?.aborted?n():t?.addEventListener("abort",n,{once:!0});let i=setTimeout(()=>r.abort(),e);return{signal:r.signal,cleanup:()=>{clearTimeout(i),t?.removeEventListener("abort",n)}}}var L9t=3e4,xke=2*1024*1024,Vl=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function Ske(e,t){let r=new URL(e);if(r.protocol!=="https:")throw new Error(`${t} must use HTTPS`);if(r.username||r.password)throw new Error(`${t} must not contain embedded credentials`);if(r.hash)throw new Error(`${t} must not contain a fragment`);return r}function Tke(e,t){if(!/^[A-Z]{3}$/.test(String(e.currency??"")))throw new Error("UCP checkout input requires an uppercase ISO 4217 currency");if(!Array.isArray(e.line_items)||e.line_items.length===0)throw new Error("UCP checkout input requires at least one line item");if(Object.hasOwn(e,"id"))throw new Error("UCP checkout input must not contain an id; pass it as a top-level argument");if(!(t==="create"?Eke:Ake).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function z9t(e){if(!e||typeof e!="object")return!1;let t=e;if(t.jsonrpc!=="2.0"||!Object.hasOwn(t,"id")||t.id!==null&&typeof t.id!="string"&&typeof t.id!="number")return!1;let r=Object.hasOwn(t,"result"),n=Object.hasOwn(t,"error");if(r===n)return!1;if(!n)return!0;let i=t.error;return!!i&&typeof i=="object"&&!Array.isArray(i)&&typeof i.code=="number"&&typeof i.message=="string"}function Ike(e,t,r,n){try{e[t](r,n)}catch{}}function H9t(e){if(!e||typeof e!="object")return e;let t=e,r=t.ucp;if(!r||typeof r!="object")return e;let n=r.capabilities;return!n||typeof n!="object"||Array.isArray(n)?e:{...t,ucp:{...r,capabilities:Object.fromEntries(Object.entries(n).map(([i,o])=>[i,Array.isArray(o)?o.map(s=>s&&typeof s=="object"?{...s,name:i}:s):o]))}}}var UM=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=Ske(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=Ske(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??L9t,this.boundaryLogger=t.logger??ke}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:Tke(t,"create")})}async getCheckout(t){if(!t)throw new Error("UCP checkout id is required");return await this.callCheckout("get_checkout",{meta:this.metadata(),id:t})}async updateCheckout(t,r){if(!t)throw new Error("UCP checkout id is required");return await this.callCheckout("update_checkout",{meta:this.metadata(),id:t,checkout:Tke(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=jM(this.timeoutMs,this.signal),o=(0,Pke.randomUUID)(),s=new URL(this.endpoint).origin,a=Date.now(),c;try{let u=await this.fetchImpl(this.endpoint,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:n,method:"tools/call",params:{name:t,arguments:r}}),signal:i.signal});c=u.status;let d;try{d=await BM(u,xke,"UCP MCP response exceeds the 2 MiB limit")}catch(m){throw m instanceof Error&&m.message==="UCP MCP response exceeds the 2 MiB limit"?new Vl(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>xke)throw new Vl("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new Vl("UCP MCP response is not valid JSON",void 0,u.status)}if(!z9t(l))throw new Vl("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new Vl("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new Vl(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new Vl(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new Vl("UCP MCP response is missing result.structuredContent");if(!wke.safeParse(H9t(p.structuredContent)).success)throw new Vl("UCP checkout response failed schema validation");return Ike(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw Ike(this.boundaryLogger,"warn","ucp:checkout_rpc_failed",{correlationId:o,endpointOrigin:s,rpcMethod:t,...c===void 0?{}:{httpStatus:c},elapsedMs:Date.now()-a,errorClass:u instanceof Error?u.name:"UnknownError"}),u}finally{i.cleanup()}}};var Oke=require("node:crypto");yd();var qM="2026-04-08",$9t="dev.ucp.shopping",F9t="dev.ucp.shopping.checkout",V9t=1024*1024,K9t=1e4,G9t="https://ucp.dev",KI=Lr.string().url().refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password},"must be an HTTPS URL without embedded credentials"),W9t=Lr.object({version:Lr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:KI,schema:KI,transport:Lr.enum(["rest","mcp","a2a","embedded"]),endpoint:KI.optional()}).passthrough(),J9t=Lr.object({version:Lr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:KI,schema:KI,extends:Lr.union([Lr.string(),Lr.array(Lr.string()).min(1)]).optional()}).passthrough(),Y9t=Lr.object({ucp:Lr.object({version:Lr.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:Lr.record(Lr.array(W9t)),capabilities:Lr.record(Lr.array(J9t)),payment_handlers:Lr.record(Lr.array(Lr.unknown())).optional()}).passthrough(),signing_keys:Lr.array(Lr.unknown()).optional()}).passthrough();function Z9t(e,t){let r=new URL(e);if(r.protocol!=="https:")throw new Error(`${t} must use HTTPS`);if(r.username||r.password)throw new Error(`${t} must not contain embedded credentials`);if(r.pathname!=="/"||r.search||r.hash)throw new Error(`${t} must be a bare origin`);return r}function MM(e,t){if(new URL(e).origin!==G9t)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function Cke(e,t,r,n){try{e[t](r,n)}catch{}}async function X9t(e,t={}){let r=Z9t(e,"UCP business URL"),n=jM(t.timeoutMs??K9t,t.signal),i=t.logger??ke,o=(0,Oke.randomUUID)(),s=Date.now(),a;try{let c=await(t.fetch??fetch)(new URL("/.well-known/ucp",r),{headers:{accept:"application/json"},redirect:"error",signal:n.signal});if(a=c.status,!c.ok)throw new Error(`UCP profile fetch failed with HTTP ${c.status}`);let u=await BM(c,V9t,"UCP profile exceeds the 1 MiB response limit"),d;try{d=JSON.parse(u)}catch{throw new Error("UCP profile response is not valid JSON")}let l=Y9t.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return Cke(i,"info","ucp:profile_fetch",{correlationId:o,businessOrigin:r.origin,method:"GET",httpStatus:a,elapsedMs:Date.now()-s}),{businessOrigin:r.origin,profile:l.data}}catch(c){throw Cke(i,"warn","ucp:profile_fetch_failed",{correlationId:o,businessOrigin:r.origin,method:"GET",...a===void 0?{}:{httpStatus:a},elapsedMs:Date.now()-s,errorClass:c instanceof Error?c.name:"UnknownError"}),c}finally{n.cleanup()}}function Q9t(e){if(e.ucp.version!==qM)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[F9t]?.find(i=>i.version===qM);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");MM(t.spec,"Checkout capability spec"),MM(t.schema,"Checkout capability schema");let r=e.ucp.services[$9t]?.find(i=>i.version===qM&&i.transport==="mcp");if(!r)throw new Error("Business does not advertise a UCP shopping MCP service");if(!r.endpoint)throw new Error("UCP shopping MCP service is missing its endpoint");MM(r.spec,"Shopping service spec"),MM(r.schema,"Shopping service schema");let n=new URL(r.endpoint);if(n.hash)throw new Error("UCP shopping MCP endpoint must not contain a fragment");return n.toString()}async function kke(e,t={}){let r=await X9t(e,t);return{...r,endpoint:Q9t(r.profile),version:qM}}var eSt="https://app.visacli.sh/.well-known/ucp";function tSt(e){let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.hash)throw new Error("UCP platform profile URL must be HTTPS and credential-free");return t.toString()}function rSt(e,t){if(typeof e=="string")try{let r=new URL(e);r.protocol==="https:"&&!r.username&&!r.password&&t.add(r.origin.toLowerCase())}catch{}}function Gne(e,t=new Set){if(Array.isArray(e))for(let r of e)Gne(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?rSt(n,t):Gne(n,t);return t}function nSt(e,t,r){let n=new URL(e),i=new URL(t);if(i.protocol!=="https:"||i.username||i.password)throw new Error("UCP continuation URL must be HTTPS and credential-free");let o=i.hostname.toLowerCase(),s=n.hostname.toLowerCase();if(i.origin.toLowerCase()===n.origin.toLowerCase())return i.hash="",{url:i.toString(),sourceHost:o,targetHost:s,originRewritten:!1};let a=r.ucp.services["dev.ucp.shopping"],c=Gne(a);if(!(o.endsWith(".myshopify.com")&&c.has(i.origin.toLowerCase())))throw new Error(`Refusing cross-host UCP continuation from ${o} to ${s}`);return i.hash="",{url:i.toString(),sourceHost:o,targetHost:o,originRewritten:!1}}function Nke(e){let t=Array.isArray(e.totals)?e.totals.find(a=>a&&typeof a=="object"&&a.type==="total"):void 0,r=t&&typeof t=="object"?t:void 0,n=r?.amount,o=r?.currency??e.currency;if(!Number.isSafeInteger(n)||Number(n)<0)throw new Error("UCP checkout is missing an integer totals[type=total].amount");if(o!=="USD")throw new Error(`UCP checkout handoff currently supports USD only; refusing ${String(o)} until currency exponents are implemented`);let s=Number(n);return{minor:s,decimal:`${Math.floor(s/100)}.${String(s%100).padStart(2,"0")}`,currency:o}}function iSt(e){return Array.isArray(e.messages)?e.messages.flatMap(t=>{if(!t||typeof t!="object")return[];let r=t,n={...typeof r.type=="string"?{type:r.type}:{},...typeof r.code=="string"?{code:r.code}:{},...typeof r.severity=="string"?{severity:r.severity}:{}};return Object.keys(n).length>0?[n]:[]}):[]}async function Bke(e,t){if(!e.business?.trim())throw new Error("UCP business origin is required");if(!e.checkoutId?.trim())throw new Error("UCP checkout id is required");let r=await(t.discover??kke)(e.business),i=await(t.getCheckout??(async(o,s)=>await new UM({endpoint:o.endpoint,platformProfileUrl:tSt(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??eSt)}).getCheckout(s)))(r,e.checkoutId);if(i.id!==e.checkoutId)throw new Error("UCP checkout response id does not match the requested checkout");return{service:r,checkout:i}}async function jke(e,t={}){let{service:r,checkout:n}=await Bke(e,t),i=String(n.status??"unknown");if(i==="completed")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_already_completed"};if(i!=="requires_escalation")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_escalated"};if(typeof n.continue_url!="string"||!n.continue_url)return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_continue_url"};let o=Nke(n),s=nSt(r.businessOrigin,n.continue_url,r.profile),a=`ucp_${(0,Rke.createHash)("sha256").update([r.businessOrigin,e.checkoutId,i,o.currency,String(o.minor),s.url].join("\0")).digest("hex").slice(0,24)}`;return{success:!0,status:"ready_for_review",checkoutId:e.checkoutId,handoffId:a,checkoutStatus:"requires_escalation",amount:o,merchant:{businessOrigin:r.businessOrigin,sourceHost:s.sourceHost,targetHost:s.targetHost,originRewritten:s.originRewritten},payMerchantRequest:{action:"review",url:s.url,amount:o.decimal,currency:o.currency},messages:iSt(n),nextAction:"Copy the payMerchantRequest checkout fields unchanged to pay_merchant and include its required user_context. Show the returned merchant and exact total to the user; never authorize until they explicitly approve PAY <reviewId>."}}function oSt(e){if(!e.order||typeof e.order!="object"||Array.isArray(e.order))return null;let t=e.order;if(typeof t.id!="string"||!t.id.trim()||typeof t.permalink_url!="string"||!t.permalink_url)return null;let r;try{r=new URL(t.permalink_url)}catch{return null}return r.protocol!=="https:"||r.username||r.password||r.hash?null:{id:t.id,permalinkHost:r.hostname.toLowerCase()}}async function Uke(e,t={}){if(!Number.isSafeInteger(e.expectedAmountMinor)||e.expectedAmountMinor<0)throw new Error("UCP reconciliation expectedAmountMinor must be a non-negative integer");if(e.expectedCurrency!=="USD")throw new Error("UCP reconciliation currently supports expectedCurrency USD only");let{checkout:r}=await Bke(e,t),n=Nke(r),i=String(r.status??"unknown");if(n.minor!==e.expectedAmountMinor)return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"amount_mismatch",amount:n,nextAction:"Do not retry payment. The merchant checkout total no longer matches the reviewed amount; reconcile the merchant order manually."};if(i!=="completed")return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_completed",amount:n,nextAction:"Do not retry payment. Poll this same checkout or inspect the merchant order before starting any new review."};let o=oSt(r);return o?{success:!0,status:"confirmed",checkoutId:e.checkoutId,checkoutStatus:"completed",amount:n,order:o,nextAction:"Report success only after matching this UCP order id and amount to the Visa checkout receipt."}:{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_order_confirmation",amount:n,nextAction:"Do not report purchase success or retry payment. The checkout says completed but lacks a valid merchant order confirmation."}}ly();function Wne(){return Ta()}var wd=new bu(()=>pn.getSessionToken()),sSt="4.1.0-rc.59",xDr=["","","You're ready to go! Try:","","Verified Agent:",'\u2022 "Enroll this agent" \u2192 enroll_agent','\u2022 "Show my wallet and policy" \u2192 wallet_status','\u2022 "Find a paid weather service" \u2192 wallet_discover','\u2022 "Pay this x402 service with a $0.10 maximum" \u2192 wallet_pay','\u2022 "Review this card checkout" \u2192 pay_merchant','\u2022 "Show my account status" \u2192 get_status'].join(`
20939
20939
  `);function aSt(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=MT(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(ATe())return{opened:!1,url:t,blockedReason:"suppressed"};let r=UT();if(r.headless)return ke.info(`Browser auto-open skipped (${r.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let i=[Wne(),py()].filter(s=>!!s).map(s=>gSe(t,s)).find(Boolean)??null;if(!i)return ke.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=_Se(i);return o?((0,qke.execFile)(o.cmd,o.args,s=>{s&&ke.warn(`Browser open failed: ${s.message}. URL: ${i}`)}),{opened:!0,url:i}):(ke.info(`No browser command for platform "${LM.platform()}". URL: ${i}`),{opened:!1,url:i,blockedReason:"unsupported_platform"})}function cSt(){let e=!1,t;try{let n=Dke.join(LM.homedir(),".claude","settings.json");if(DM.existsSync(n)){let i=JSON.parse(DM.readFileSync(n,"utf-8")),o=typeof i.statusLine=="object"?i.statusLine.command:"";e=cy(o)}}catch{}let r=Rj();return r||(t="visa-cli config hud enable"),{statusLine:e,shellHud:r,...t?{shellHudSetup:t}:{}}}async function uSt(e){let t=await wd.getStatus(e);t.hud=cSt(),!t.hud.statusLine&&!t.hud.shellHud&&(t._hud_nudge="The user has no HUD surfaces enabled. Mention once, naturally, that they can enable the Visa HUD with `visa-cli config hud enable`."),t.version=sSt;try{let r=v8();if(r){let n=await wd.getAgentTapStatus(r.identity_key.jkt);n&&(t.tap={status:n.status,registeredAt:n.registeredAt})}}catch(r){ke.warn({component:"get-status-tap",msg:"tap_status_unavailable",error:r?.message})}return t}async function dSt(e,t){return await wd.feedback(e.message,e.transaction_id,t)}async function lSt(e){let t=await CI({api:wd,includeDev:!!e.includeDev});return{config:t.entries.map(r=>({key:r.key,value:r.value,source:r.source,hint:r.hint})),statusError:t.statusError}}var Jne=new Set(["auth.serverUrl"]);function GI(){return Object.keys(L_).filter(e=>!Jne.has(e)).sort()}function Lke(e,t){let r=t==="set"?`visa-cli config set ${e}=<value>`:`visa-cli config unset ${e}`;return{success:!1,error:`${e} cannot be changed via MCP. Run \`${r}\` 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:GI()}}async function pSt(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(Jne.has(e.key))return ke.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Lke(e.key,"set");ke.info("config:set",{key:e.key});try{let t=Vj(e.key,e.value);return ke.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 r=t instanceof Dl?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof Dl?`Unknown setting "${e.key}". MCP-settable keys: ${GI().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return ke.warn("config:set:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:GI()}}}async function fSt(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(Jne.has(e.key))return ke.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Lke(e.key,"unset");ke.info("config:unset",{key:e.key});try{let t=Kj(e.key);return ke.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 r=t instanceof Dl?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof Dl?`Unknown setting "${e.key}". MCP-settable keys: ${GI().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return ke.warn("config:unset:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:GI()}}}async function mSt(e=Wne(),t=!1){if(!e)return{success:!1,message:"No auth server is configured. Set auth.serverUrl before pairing this runtime."};if(!t){let r=v8();if(r){let n=r.display_name,i;if(process.env.SUBWAY_MESH==="visa"&&n){let{registerOnVisaMeshIfEnabled:s}=await Promise.resolve().then(()=>(dM(),pOe));i=await s(n)}ke.info("agent:enroll_already_connected",{keyBound:!0,meshRegistered:i});let o=i===void 0?"":i?` Registered ${n??"this device"} on the .visa mesh.`:` Could not reach the .visa mesh \u2014 run \`visa register ${n??"<name>"}\` to join it.`;return{success:!0,alreadyConnected:!0,...n?{name:n}:{},keyBound:!0,...i!==void 0?{meshRegistered:i}:{},message:`This device is already connected${n?` as ${n}`:""} \u2014 nothing to pair. To add or change spending on this identity, approve it in your account settings (agent card \u2192 Spend).`+o+' Call enroll_agent with {"action":"start","force":true} to start a brand-new enrollment anyway.'}}}try{let r=await bI({authUrl:e,runtime:"visa-cli-mcp",contextLabel:"Pair this MCP runtime"});ke.info("agent:pairing_open",{pairingId:r.pairingId,agentId:r.agentId});let n=aSt(r.authorizationUrl),i=n.url??r.authorizationUrl;return{success:!0,protocolVersion:r.protocolVersion,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:r.requestKeyFingerprint,opened:n.opened,requiresBrowser:!n.opened,browserUrl:i,expiresAt:r.expiresAt,message:n.opened?`Opened the authorization page for agent ${r.agentId}. Compare public request-key fingerprint ${r.requestKeyFingerprint} exactly, approve the runtime, then call enroll_agent with {"action":"claim"}. Pairing establishes identity only; payment methods and communication channels are configured separately.`:`Open ${i} to approve agent ${r.agentId}. Compare public request-key fingerprint ${r.requestKeyFingerprint} exactly, then call enroll_agent with {"action":"claim"}. Pairing establishes identity only; payment methods and communication channels are configured separately.`}}catch(r){return{success:!1,message:r instanceof Error?r.message:String(r)}}}async function hSt(e=Wne()){if(!e)return{success:!1,message:"No auth server is configured. Set auth.serverUrl before pairing this runtime."};let t=await _I({authUrl:e});switch(ke.info("agent:enroll_claim",{status:t.status}),t.status){case"activated":return{success:!0,status:t.status,protocolVersion:t.protocolVersion,pairingId:t.pairingId,agentId:t.agentId,displayName:t.displayName,identityKeyJkt:t.identityKeyJkt,message:`Agent ${t.displayName} (${t.agentId}) is paired to this runtime. Its exportable Ed25519 private identity key remains in an owner-only local file. Copying that file transfers identity proof; losing it blocks new proofs because same-agent key recovery is not available yet. Payment methods and communication channels are configured separately.`};case"no_pending":return{success:!1,message:'No pairing is in progress on this device \u2014 call enroll_agent with {"action":"start"} first.'};case"not_ready":return{success:!1,status:t.status,protocolVersion:t.protocolVersion,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:t.likelyExpired,message:t.likelyExpired?"This pairing has likely expired. Start a fresh pairing ceremony.":`Authorization is not complete for agent ${t.agentId}. Approve the browser request, then claim again.`};case"error":return{success:!1,message:t.message}}}async function Mke(){if(await pn.clearAll(),!!P0())try{await Qj()}catch(e){ke.warn("reset:touchid_key_delete_failed",{error:e instanceof Error?e.message:String(e)})}}async function ySt(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(ke.info("reset:attempt"),e.localOnly)return await Mke(),ke.info("reset:success",{localOnly:!0}),{success:!0,message:"Device account state reset locally. The account session credential and local biometric key were removed. Stored agent identity records and server-side agents were not changed. Agent pairing is not account-session or biometric recovery."};try{await wd.logout(void 0,t)}catch{}return await Mke(),ke.info("reset:success"),{success:!0,message:"Device account state reset. The server session, local account credential, and local biometric key were removed. Stored agent identity records and server-side agents were not changed. Agent pairing is not account-session or biometric recovery."}}async function gSt(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:r}=await Promise.resolve().then(()=>(m6(),TI)),n=await t(e.name);return await r(e.name),{success:!0,...n}}catch(t){let{VisaBindingRequiredError:r}=await Promise.resolve().then(()=>(rI(),KIe));return t instanceof r?{success:!1,binding_required:!0,reason:t.reason,recovery_tool:null,error:t.message,message:`${t.message} Pairing alone does not provision a .visa name or TAP/channel binding.`}:{success:!1,error:t instanceof Error?t.message:String(t)}}}async function bSt(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(m6(),TI));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function _St(e){if(!e.to||!e.text)return{success:!1,error:"to and text are required"};try{let{sendVia:t,resolveActingName:r}=await Promise.resolve().then(()=>(m6(),TI)),n=e.as??r(void 0);return{success:!0,...await t(n,e.to,e.text)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function vSt(e){try{let{readInbox:t,resolveActingName:r,meshName:n}=await Promise.resolve().then(()=>(m6(),TI)),i=e.as??r(void 0),o=await t(i,e.limit??20,!!e.clear);return{success:!0,as:n(i),count:o.length,messages:o}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}var F8=class{static async subwayRegister(t){return gSt(t||{})}static async subwayFind(t){return bSt(t||{})}static async subwaySend(t){return _St(t||{})}static async subwayInbox(t){return vSt(t||{})}static async getStatus(t){return uSt(t)}static async feedback(t,r){return dSt(t,r)}static async configList(t){return lSt(t||{})}static async configSet(t){return pSt(t||{})}static async configUnset(t){return fSt(t||{})}static async reset(t,r){return ySt(t,r)}static async enrollAgent(t={},r){let n=t?.action??"start";return n==="start"?mSt(void 0,t?.force===!0):n==="claim"?hSt():{success:!1,message:`Unknown enroll_agent action ${JSON.stringify(n)}. Use "start" (default \u2014 opens identity-pairing approval) or "claim" (activates the approved identity on this runtime).`}}static async payMerchant(t={},r){return DOe(t)}static async ucpCheckoutHandoff(t,r){return By("ucp_checkout_handoff")&&(await kI(),By("ucp_checkout_handoff"))?{success:!1,message:"ucp_checkout_handoff requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."}:jke(t)}static async ucpCheckoutReconcile(t,r){if(By("ucp_checkout_reconcile")&&(await kI(),By("ucp_checkout_reconcile")))return{success:!1,message:"ucp_checkout_reconcile requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let n=Date.now(),i=(()=>{try{return new URL(t.business).hostname}catch{return"invalid"}})();ke.info("ucp_checkout_reconcile:start",{businessHost:i});try{let o=await Uke(t);return ke.info("ucp_checkout_reconcile:complete",{businessHost:i,checkoutStatus:o.checkoutStatus,reconciliationStatus:o.status,durationMs:Date.now()-n}),o}catch(o){throw ke.warn("ucp_checkout_reconcile:failed",{businessHost:i,durationMs:Date.now()-n,errorName:o instanceof Error?o.name:"unknown"}),o}}static async payMerchantStatus(t={},r){return qOe(t)}static async startCardMandate(t={},r){return LOe(t)}static async submitFeedback(t,r,n){ke.info("feedback:submit",{length:t.length,transactionId:r,hasContext:!!n});try{let i=await wd.submitFeedback(t,r,n);return ke.info("feedback:submitted",{transactionId:r}),i}catch(i){let o=i instanceof Error?i.message:"Unknown error";throw ke.error("feedback:error",{error:o,transactionId:r}),i}}static async getFeedback(t,r){ke.info("feedback:list",{limit:t||20});try{let n=await wd.getFeedback(t,r);return ke.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let i=n instanceof Error?n.message:"Unknown error";throw ke.error("feedback:error",{error:i}),n}}};async function zke(e,t,r,n){let i=n.log??console.log,o=n.error??console.error,s=n.exit??(c=>process.exit(c)),a=n.env??process.env;try{let c=r.currency,u=r.rail,d=await n.payMerchant({action:"review",rail:u,url:e,amount:t,currency:c});if(!d||d.success!==!0)return o(d?.message||"Review failed."),void s(1);if(i(d.message),!r.submit){i("Review only \u2014 nothing charged. Re-run with --submit to authorize (passkey required).");return}let l=d.reviewId;if(typeof l!="string"||l.length===0)return o("Review did not return a usable reviewId \u2014 cannot authorize a charge. Nothing charged."),void s(1);a.CHECKOUT_AGENT_ALLOW_SUBMIT="1";let p=await n.payMerchant({action:"pay",rail:u,url:e,amount:t,currency:c,confirm:`PAY ${l}`});if(i(p?.message),!p||p.success!==!0)return void s(1)}catch(c){return o("Error:",c.message),void s(1)}}var Hke=require("node:fs/promises"),$ke=require("node:os"),Fke=require("node:path");async function Vke(e,t,r){let n=r.log??console.log,i=r.error??console.error,o=r.exit??(s=>process.exit(s));try{let s={...t.agent?{agent:t.agent}:{},ceiling:e,...t.perTransaction?{perTransaction:t.perTransaction}:{},...t.intent?{intent:t.intent}:{}},a=await r.startCardMandate(s);if(!a||a.success!==!0)return i(a?.message||"Could not create the mandate."),void o(1);n(a.message),n(""),n(` mandate: ${a.mandateId}`),n(` ceiling: ${a.ceiling} ${a.currency}`),typeof a.remainingMinor=="number"&&n(` remaining: ${I8(a.remainingMinor,a.currency??"USD")}`),n(" scope: eligible retail merchants (network category 5999)"),typeof a.maxPurchases=="number"&&n(` purchases: up to ${a.maxPurchases}`),a.expiresAt&&n(` expires: ${a.expiresAt}`)}catch(s){return i("Error:",s.message),void o(1)}}var wSt=300*1e3;function ESt(){return process.env.VISA_CARD_MANDATE_LEDGER_FILE??(0,Fke.join)((0,$ke.homedir)(),".visa-mcp","card-mandates.json")}async function ASt(){try{let e=JSON.parse(await(0,Hke.readFile)(ESt(),"utf8"));return!e||!Array.isArray(e.mandates)?{mandates:[]}:e}catch(e){if(e.code==="ENOENT")return null;throw e}}function xSt(e,t){let r=(e.reservations??[]).reduce((n,i)=>{let o=i.reservedAt!==void 0?Date.parse(i.reservedAt):NaN;return!Number.isFinite(o)||t-o>wSt?n:n+i.amountMinor},0);return e.ceilingMinor-e.spentMinor-r}function SSt(e){return e.length>18?`${e.slice(0,8)}\u2026${e.slice(-6)}`:e}async function Kke(e={}){let t=e.log??console.log,r=e.error??console.error,n=e.exit??(s=>process.exit(s)),i=e.readLedger??ASt,o=(e.now??(()=>new Date))().getTime();try{let c=((await i())?.mandates??[]).filter(u=>{let d=Date.parse(u.expiresAt);return Number.isFinite(d)&&d>o});if(c.length===0){t("No active mandates. Create one with: visa-cli mandate start <ceiling>");return}t(`Active mandates
20940
20940
  `);for(let u of c){if(t(` ${u.mandateId}`),t(u.crossMerchant?" scope: eligible retail merchants (network category 5999)":` merchant: ${u.merchantName||u.merchantHost||"(unknown)"}`),u.agentJkt&&t(` request key: ${SSt(u.agentJkt)}`),t(` remaining: ${I8(xSt(u,o),u.currencyCode)}`),Number.isSafeInteger(u.maxDraws)&&u.maxDraws>0){let d=(u.draws??[]).filter(l=>l.status==="committed").length;t(` credentials issued: ${d} of ${u.maxDraws}`)}t(` expires: ${u.expiresAt}`),u.unhonoredAt&&t(` unhonored: yes (disabled ${u.unhonoredAt}) \u2014 next checkout uses a fresh tap`),u.registerFailedAt&&t(` register: FAILED (${u.registerFailedAt}) \u2014 not used for tap-free draws; next checkout uses a fresh tap`)}}catch(s){return r("Error:",s.message),void n(1)}}yd();FT();function Gke(e,t=process.stderr){if(uy()||!e?.updateAvailable)return!1;let{latestVersion:r}=e.updateAvailable;if(!r)return!1;let n=`Update available: v${r}. Run: visa-cli update`;return t.write(`
20941
20941
  \x1B[33m\u2191 ${n}\x1B[0m
@@ -20951,7 +20951,7 @@ If building from source, run native/build-win.bat first.`);tn.mkdirSync(fy,{recu
20951
20951
  `)}function vBr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(t-1,0))}\u2026`}function wBr(e){if(e.length===0)return"No matching paid services.";let t=["ID","Protocol","Price","Health","Service"],r=e.map(i=>[i.id,i.protocol,i.listedPriceUsd?`$${i.listedPriceUsd}`:"runtime",i.health,vBr(i.name,48)]),n=t.map((i,o)=>Math.max(i.length,...r.map(s=>s[o].length)));return[t,...r].map(i=>i.map((o,s)=>o.padEnd(n[s])).join(" ").trimEnd()).join(`
20952
20952
  `)}function EBr(){let e=WU.map(r=>({id:r.id,detected:wre(r),connected:Pre(r)})),t={id:Math.max(6,...e.map(r=>r.id.length))};return[`${"Client".padEnd(t.id)} Detected Connected`,...e.map(r=>`${r.id.padEnd(t.id)} ${(r.detected?"yes":"no").padEnd(8)} ${r.connected?"yes":"no"}`)].join(`
20953
20953
  `)}function ABr(e,t){if(e==="find"){let r=t.listings;q9e(wBr(r));return}if(e==="connections"){q9e(EBr());return}q9e(JSON.stringify(t,null,2))}async function cf(e,t,r){let n="table";try{n=_Br(t);let i=await r();n==="table"?ABr(e,i):Xne(Jke(e,{data:i}),n)}catch(i){let o=i instanceof Error?i.message:String(i);n==="table"?process.stderr.write(`Error: ${o}
20954
- `):Xne(Yke(e,o),n),process.exitCode=1}}function xBr(){this.help({error:!1})}function k_t(e){af(e.command("find <intent>").description("Find payable services by outcome; discovery never spends money.").option("--provider <provider>",`Directory provider: all, ${uee.join(", ")}`,"all").option("--protocol <protocol>","Filter by payment protocol: x402, mpp, l402, vic").option("--max <usd>","Only show listings at or below this advisory price").option("--limit <count>","Maximum results","10")).action(async(r,n)=>{await cf("find",n,async()=>{let i=["all",...uee];if(!i.includes(n.provider))throw new Error(`--provider must be one of: ${i.join(", ")}`);let o=["x402","mpp","l402","vic"];if(n.protocol&&!o.includes(n.protocol))throw new Error(`--protocol must be one of: ${o.join(", ")}`);let s=Number(n.limit);if(!Number.isInteger(s)||s<1||s>50)throw new Error("--limit must be an integer between 1 and 50");return k_().find({intent:r,provider:n.provider,protocol:n.protocol,maxUsd:n.max,limit:s})})}),af(e.command("inspect [listing-id]").description("Inspect a directory listing or fetch a fresh x402 challenge without paying.").option("--url <url>","Inspect an advanced direct endpoint instead of a listing").option("--input <source>","POST JSON from @file or - for stdin")).action(async(r,n)=>{await cf("inspect",n,()=>k_().inspect({listingId:r,url:n.url,bodyJson:O_t(n.input)}))}),af(e.command("pay [listing-id]").description("Disclose a bounded x402 authorization; the outcome remains reconciling until trusted settlement evidence exists.").option("--url <url>","Pay an advanced direct endpoint instead of a listing").requiredOption("--max <usd>","Hard USD ceiling; the wallet refuses a pricier challenge").option("--input <source>","POST JSON from @file or - for stdin")).action(async(r,n)=>{await cf("pay",n,()=>k_().pay({listingId:r,url:n.url,maxUsd:n.max,bodyJson:O_t(n.input)}))});let t=e.command("wallet").description("Inspect, fund, and constrain the principal v4 wallet.").action(xBr);af(t.command("show").description("Show wallet, network, policy, and budgets.")).action(async r=>cf("wallet show",r,()=>k_().status())),af(t.command("fund").description("Show the wallet funding address and network guidance.")).action(async r=>cf("wallet fund",r,()=>k_().fund())),af(t.command("limits").description("Show or update wallet spending limits.").option("--per-transaction <usd>","Per-transaction cap").option("--daily <usd>","Daily cap").option("--session <usd>","Current session cap").option("--expires-at <timestamp>","ISO timestamp after which paying is blocked")).action(async r=>cf("wallet limits",r,()=>k_().limits({perTransaction:r.perTransaction,daily:r.daily,session:r.session,expiresAt:r.expiresAt}))),af(e.command("activity").description("Show legacy receipts and reconciling x402 authorizations.").option("--limit <count>","Return at most the newest N activity entries")).action(async r=>{await cf("activity",r,()=>{let n=r.limit===void 0?void 0:Number(r.limit);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error("--limit must be a positive integer");return k_().activity(n)})}),af(e.command("receipt <activity-id>").description("Show one journaled wallet activity entry by its stable id.")).action(async(r,n)=>{await cf("receipt",n,()=>k_().receipt(r))}),af(e.command("connections").description("Show supported MCP client connections.")).action(async r=>cf("connections",r,async()=>WU.map(n=>({id:n.id,name:n.displayName,detected:wre(n),connected:Pre(n)})))),af(e.command("connect <client>").description("Connect Visa to an AI or MCP client.")).action(async(r,n)=>{await cf("connect",n,async()=>{let i=mI(r);if(!i)throw new Error(`unknown client: ${r}`);return VPe(i)})}),af(e.command("disconnect <client>").description("Remove Visa from an AI or MCP client.")).action(async(r,n)=>{await cf("disconnect",n,async()=>{let i=mI(r);if(!i)throw new Error(`unknown client: ${r}`);return GPe(i)})})}yd();var L9e=!1;async function z9e(e,t,r){try{return await t()}catch(n){if(!(n.message==="Invalid signature"||n.code==="ATTESTATION_KEY_DRIFT"||n.error_code==="ATTESTATION_KEY_DRIFT"||n.name==="AttestationDriftError")||!P0())throw n;if(ke.warn("attestation:key-mismatch",{action:"browser-recovery"}),r){if(L9e)throw ke.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),n;L9e=!0,ke.info("attestation:starting-browser-recovery");try{let o=await r();if(!o.success)throw ke.error("attestation:browser-recovery-failed",{message:o.message}),n;let s=await VTe();await e.registerAttestationKey(s),await e.setBiometricPreference({required:!0}),ke.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),ke.info("attestation:key-reregistered-after-recovery");let a=await t();return L9e=!1,a}catch(o){throw ke.error("attestation:recovery-failure",{error:o.message}),n}}throw n}}function H9e(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}u6();Zte();m6();var SBr="4.1.0-rc.58";async function R_t(e){let t=await SI(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: ${xI} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var fj=(e,t)=>{console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function N_t(e){if(!ane(SBr))return;e.command("register <name>",{hidden:!0}).description(`Register a name on the "${ki}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async r=>{try{await R_t(r)}catch(n){fj("register",n)}});let t=e.command("subway",{hidden:!0}).description("Subway agent-to-agent messaging over the Visa CLI.");t.command("register <name>").description("Alias of `visa register <name>`.").action(async r=>{try{await R_t(r)}catch(n){fj("register",n)}}),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(r,n,i)=>{try{let o=fM(i.as),s=await pne(o,r,n);console.log(`\u2713 sent to ${s.to} as ${s.as}`)}catch(o){fj("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 r=>{try{let n=await lne(r);n.found?(console.log(`\u2713 ${n.relayName} is live`),console.log(` peer: ${n.peerId}`)):(console.log(`\u2717 ${n.relayName} not found${n.error?` (${n.error})`:""}`),process.exitCode=1)}catch(n){fj("find",n)}}),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 r=>{try{let n=fM(r.as),i=A8(n,{autoReconnect:!0});await x8(i);let o=a=>new Date(a).toLocaleTimeString();i.onMessage(a=>{let c=a.verified?"":" (unverified)";console.log(`[${o(a.timestampMs)}] ${a.fromName}${c}: ${a.payload}`)}),r.room&&i.subscribe(r.room,a=>{console.log(`[${o(a.timestampMs)}] #${a.topic} ${a.fromName}: ${a.payload}`)}),console.log(`\u2026 listening as ${Q_(n)} on "${ki}" mesh${r.room?` (room #${r.room})`:""}. Ctrl-C to stop.`);let s=()=>{i.disconnect(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s),await new Promise(()=>{})}catch(n){fj("listen",n)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let r=fne();if(r.length===0){console.log("No Subway names registered. Run `visa register <name>`.");return}for(let n of r)console.log(`${n.relayName} mesh=${n.mesh} peer=${n.peerId??"?"} ${n.tapAgentId?`tap=${n.tapAgentId}`:"(standalone key)"} registered=${n.registeredAt}`)})}var zBr=_e(require("fs")),t6t=_e(require("os")),df=_e(require("path")),r6t=require("node:readline/promises");e8();x0();var iy=_e(require("fs")),E0=_e(require("path"));var TBr=1,V4={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},IBr=["terminal","claude","claude-code","all"];function lee(e){let t=e.toLowerCase();return IBr.includes(t)?t:null}var PBr=50,CBr=64*1024,B_t=10,$9e=80,ot={get reset(){return zs().reset},get visaBlue(){return zs().visaBlue},get visaBlueSoft(){return zs().visaBlueSoft},get visaGold(){return zs().visaGold},get green(){return zs().green},get muted(){return zs().muted},get chrome(){return zs().chrome}};function ct(e,t){return e.length===0||process.env.NO_COLOR||Cj()?e:`${t}${e}${ot.reset}`}function j_t(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function D_t(e=process.stdin){return e.isTTY?null:new Promise(t=>{let r=[],n=!1,i=()=>{e.removeListener("data",s),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(u)},o=d=>{n||(n=!0,i(),t(d))},s=d=>{r.push(typeof d=="string"?Buffer.from(d):d)},a=()=>{let d=Buffer.concat(r).toString("utf-8").trim();if(!d)return o(null);try{let l=JSON.parse(d);o(l&&typeof l=="object"?l:null)}catch{o(null)}},c=()=>o(null),u=setTimeout(()=>{r.length>0?a():o(null)},PBr);e.on("data",s),e.on("end",a),e.on("error",c)})}function mj(e){let r=Math.round(Math.max(0,Math.min(1,e))*10),n="\u2588".repeat(r),i="\u2591".repeat(10-r);return`${ct(n||"",ot.visaBlueSoft)}${ct(i||"",ot.chrome)}`}function hj(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function OBr(e){if(J_t(e))return RBr(e);let t=` ${ct("\u2502",ot.chrome)} `,r=dee(e)||"claude",n=e.cwd?mo(E0.basename(e.cwd)):"",i=pee(e.workspace),o=n||i,s=i&&i!==o?` ${ct(`@${i}`,ot.visaBlueSoft)}`:"",a=[ct(`[${r}]`,ot.visaBlueSoft)];o&&a.push(`${ct(o,ot.visaGold)}${s}`);let c=mo(e.git_branch??e.branch??"");c&&a.push(`${ct("git:(",ot.muted)}${ct(c,ot.visaBlueSoft)}${ct(")",ot.muted)}`);let u=a.join(t),d=Number(e.context_window?.context_window_size??0),l=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,p=e.context_window?.current_usage,f=[p?.input_tokens,p?.output_tokens,p?.cache_creation_input_tokens,p?.cache_read_input_tokens].filter(x=>typeof x=="number"&&Number.isFinite(x)),m=f.length>0?f.reduce((x,S)=>x+S,0):null,h=Number(e.context_window?.total_input_tokens??m??p?.input_tokens??0),y=l!==null?Math.max(0,Math.min(1,l/100)):d>0?Math.max(0,Math.min(1,h/d)):0,v=l!==null&&d>0?Math.round(y*d):h,E;if(d>0||l!==null){let x=`${String(Math.round(y*100)).padStart(2," ")}%`,S=d>0?` ${ct(`(${hj(v)}/${hj(d)})`,ot.muted)}`:"";E=`${ct("Context",ot.muted)} ${mj(y)} ${ct(x,ot.green)}${S}`}else E=`${ct("Context",ot.muted)} ${ct("-",ot.muted)}`;let b=L_t(e.rate_limits),w=[E];b&&w.push(b);let A=w.join(t);return`${u}
20954
+ `):Xne(Yke(e,o),n),process.exitCode=1}}function xBr(){this.help({error:!1})}function k_t(e){af(e.command("find <intent>").description("Find payable services by outcome; discovery never spends money.").option("--provider <provider>",`Directory provider: all, ${uee.join(", ")}`,"all").option("--protocol <protocol>","Filter by payment protocol: x402, mpp, l402, vic").option("--max <usd>","Only show listings at or below this advisory price").option("--limit <count>","Maximum results","10")).action(async(r,n)=>{await cf("find",n,async()=>{let i=["all",...uee];if(!i.includes(n.provider))throw new Error(`--provider must be one of: ${i.join(", ")}`);let o=["x402","mpp","l402","vic"];if(n.protocol&&!o.includes(n.protocol))throw new Error(`--protocol must be one of: ${o.join(", ")}`);let s=Number(n.limit);if(!Number.isInteger(s)||s<1||s>50)throw new Error("--limit must be an integer between 1 and 50");return k_().find({intent:r,provider:n.provider,protocol:n.protocol,maxUsd:n.max,limit:s})})}),af(e.command("inspect [listing-id]").description("Inspect a directory listing or fetch a fresh x402 challenge without paying.").option("--url <url>","Inspect an advanced direct endpoint instead of a listing").option("--input <source>","POST JSON from @file or - for stdin")).action(async(r,n)=>{await cf("inspect",n,()=>k_().inspect({listingId:r,url:n.url,bodyJson:O_t(n.input)}))}),af(e.command("pay [listing-id]").description("Disclose a bounded x402 authorization; the outcome remains reconciling until trusted settlement evidence exists.").option("--url <url>","Pay an advanced direct endpoint instead of a listing").requiredOption("--max <usd>","Hard USD ceiling; the wallet refuses a pricier challenge").option("--input <source>","POST JSON from @file or - for stdin")).action(async(r,n)=>{await cf("pay",n,()=>k_().pay({listingId:r,url:n.url,maxUsd:n.max,bodyJson:O_t(n.input)}))});let t=e.command("wallet").description("Inspect, fund, and constrain the principal v4 wallet.").action(xBr);af(t.command("show").description("Show wallet, network, policy, and budgets.")).action(async r=>cf("wallet show",r,()=>k_().status())),af(t.command("fund").description("Show the wallet funding address and network guidance.")).action(async r=>cf("wallet fund",r,()=>k_().fund())),af(t.command("limits").description("Show or update wallet spending limits.").option("--per-transaction <usd>","Per-transaction cap").option("--daily <usd>","Daily cap").option("--session <usd>","Current session cap").option("--expires-at <timestamp>","ISO timestamp after which paying is blocked")).action(async r=>cf("wallet limits",r,()=>k_().limits({perTransaction:r.perTransaction,daily:r.daily,session:r.session,expiresAt:r.expiresAt}))),af(e.command("activity").description("Show legacy receipts and reconciling x402 authorizations.").option("--limit <count>","Return at most the newest N activity entries")).action(async r=>{await cf("activity",r,()=>{let n=r.limit===void 0?void 0:Number(r.limit);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error("--limit must be a positive integer");return k_().activity(n)})}),af(e.command("receipt <activity-id>").description("Show one journaled wallet activity entry by its stable id.")).action(async(r,n)=>{await cf("receipt",n,()=>k_().receipt(r))}),af(e.command("connections").description("Show supported MCP client connections.")).action(async r=>cf("connections",r,async()=>WU.map(n=>({id:n.id,name:n.displayName,detected:wre(n),connected:Pre(n)})))),af(e.command("connect <client>").description("Connect Visa to an AI or MCP client.")).action(async(r,n)=>{await cf("connect",n,async()=>{let i=mI(r);if(!i)throw new Error(`unknown client: ${r}`);return VPe(i)})}),af(e.command("disconnect <client>").description("Remove Visa from an AI or MCP client.")).action(async(r,n)=>{await cf("disconnect",n,async()=>{let i=mI(r);if(!i)throw new Error(`unknown client: ${r}`);return GPe(i)})})}yd();var L9e=!1;async function z9e(e,t,r){try{return await t()}catch(n){if(!(n.message==="Invalid signature"||n.code==="ATTESTATION_KEY_DRIFT"||n.error_code==="ATTESTATION_KEY_DRIFT"||n.name==="AttestationDriftError")||!P0())throw n;if(ke.warn("attestation:key-mismatch",{action:"browser-recovery"}),r){if(L9e)throw ke.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),n;L9e=!0,ke.info("attestation:starting-browser-recovery");try{let o=await r();if(!o.success)throw ke.error("attestation:browser-recovery-failed",{message:o.message}),n;let s=await VTe();await e.registerAttestationKey(s),await e.setBiometricPreference({required:!0}),ke.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),ke.info("attestation:key-reregistered-after-recovery");let a=await t();return L9e=!1,a}catch(o){throw ke.error("attestation:recovery-failure",{error:o.message}),n}}throw n}}function H9e(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}u6();Zte();m6();var SBr="4.1.0-rc.59";async function R_t(e){let t=await SI(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: ${xI} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var fj=(e,t)=>{console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function N_t(e){if(!ane(SBr))return;e.command("register <name>",{hidden:!0}).description(`Register a name on the "${ki}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async r=>{try{await R_t(r)}catch(n){fj("register",n)}});let t=e.command("subway",{hidden:!0}).description("Subway agent-to-agent messaging over the Visa CLI.");t.command("register <name>").description("Alias of `visa register <name>`.").action(async r=>{try{await R_t(r)}catch(n){fj("register",n)}}),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(r,n,i)=>{try{let o=fM(i.as),s=await pne(o,r,n);console.log(`\u2713 sent to ${s.to} as ${s.as}`)}catch(o){fj("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 r=>{try{let n=await lne(r);n.found?(console.log(`\u2713 ${n.relayName} is live`),console.log(` peer: ${n.peerId}`)):(console.log(`\u2717 ${n.relayName} not found${n.error?` (${n.error})`:""}`),process.exitCode=1)}catch(n){fj("find",n)}}),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 r=>{try{let n=fM(r.as),i=A8(n,{autoReconnect:!0});await x8(i);let o=a=>new Date(a).toLocaleTimeString();i.onMessage(a=>{let c=a.verified?"":" (unverified)";console.log(`[${o(a.timestampMs)}] ${a.fromName}${c}: ${a.payload}`)}),r.room&&i.subscribe(r.room,a=>{console.log(`[${o(a.timestampMs)}] #${a.topic} ${a.fromName}: ${a.payload}`)}),console.log(`\u2026 listening as ${Q_(n)} on "${ki}" mesh${r.room?` (room #${r.room})`:""}. Ctrl-C to stop.`);let s=()=>{i.disconnect(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s),await new Promise(()=>{})}catch(n){fj("listen",n)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let r=fne();if(r.length===0){console.log("No Subway names registered. Run `visa register <name>`.");return}for(let n of r)console.log(`${n.relayName} mesh=${n.mesh} peer=${n.peerId??"?"} ${n.tapAgentId?`tap=${n.tapAgentId}`:"(standalone key)"} registered=${n.registeredAt}`)})}var zBr=_e(require("fs")),t6t=_e(require("os")),df=_e(require("path")),r6t=require("node:readline/promises");e8();x0();var iy=_e(require("fs")),E0=_e(require("path"));var TBr=1,V4={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},IBr=["terminal","claude","claude-code","all"];function lee(e){let t=e.toLowerCase();return IBr.includes(t)?t:null}var PBr=50,CBr=64*1024,B_t=10,$9e=80,ot={get reset(){return zs().reset},get visaBlue(){return zs().visaBlue},get visaBlueSoft(){return zs().visaBlueSoft},get visaGold(){return zs().visaGold},get green(){return zs().green},get muted(){return zs().muted},get chrome(){return zs().chrome}};function ct(e,t){return e.length===0||process.env.NO_COLOR||Cj()?e:`${t}${e}${ot.reset}`}function j_t(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function D_t(e=process.stdin){return e.isTTY?null:new Promise(t=>{let r=[],n=!1,i=()=>{e.removeListener("data",s),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(u)},o=d=>{n||(n=!0,i(),t(d))},s=d=>{r.push(typeof d=="string"?Buffer.from(d):d)},a=()=>{let d=Buffer.concat(r).toString("utf-8").trim();if(!d)return o(null);try{let l=JSON.parse(d);o(l&&typeof l=="object"?l:null)}catch{o(null)}},c=()=>o(null),u=setTimeout(()=>{r.length>0?a():o(null)},PBr);e.on("data",s),e.on("end",a),e.on("error",c)})}function mj(e){let r=Math.round(Math.max(0,Math.min(1,e))*10),n="\u2588".repeat(r),i="\u2591".repeat(10-r);return`${ct(n||"",ot.visaBlueSoft)}${ct(i||"",ot.chrome)}`}function hj(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function OBr(e){if(J_t(e))return RBr(e);let t=` ${ct("\u2502",ot.chrome)} `,r=dee(e)||"claude",n=e.cwd?mo(E0.basename(e.cwd)):"",i=pee(e.workspace),o=n||i,s=i&&i!==o?` ${ct(`@${i}`,ot.visaBlueSoft)}`:"",a=[ct(`[${r}]`,ot.visaBlueSoft)];o&&a.push(`${ct(o,ot.visaGold)}${s}`);let c=mo(e.git_branch??e.branch??"");c&&a.push(`${ct("git:(",ot.muted)}${ct(c,ot.visaBlueSoft)}${ct(")",ot.muted)}`);let u=a.join(t),d=Number(e.context_window?.context_window_size??0),l=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,p=e.context_window?.current_usage,f=[p?.input_tokens,p?.output_tokens,p?.cache_creation_input_tokens,p?.cache_read_input_tokens].filter(x=>typeof x=="number"&&Number.isFinite(x)),m=f.length>0?f.reduce((x,S)=>x+S,0):null,h=Number(e.context_window?.total_input_tokens??m??p?.input_tokens??0),y=l!==null?Math.max(0,Math.min(1,l/100)):d>0?Math.max(0,Math.min(1,h/d)):0,v=l!==null&&d>0?Math.round(y*d):h,E;if(d>0||l!==null){let x=`${String(Math.round(y*100)).padStart(2," ")}%`,S=d>0?` ${ct(`(${hj(v)}/${hj(d)})`,ot.muted)}`:"";E=`${ct("Context",ot.muted)} ${mj(y)} ${ct(x,ot.green)}${S}`}else E=`${ct("Context",ot.muted)} ${ct("-",ot.muted)}`;let b=L_t(e.rate_limits),w=[E];b&&w.push(b);let A=w.join(t);return`${u}
20955
20955
  ${A}`}function kBr(e){if(J_t(e))return null;let t=` ${ct("\u2502",ot.chrome)} `,r=dee(e)||"claude",n=e.cwd?mo(E0.basename(e.cwd)):"",i=pee(e.workspace),o=n||i,s=i&&i!==o?` ${ct(`@${i}`,ot.visaBlueSoft)}`:"",a=[ct(`[${r}]`,ot.visaBlueSoft)];o&&a.push(`${ct(o,ot.visaGold)}${s}`);let c=mo(e.git_branch??e.branch??"");c&&a.push(`${ct("git:(",ot.muted)}${ct(c,ot.visaBlueSoft)}${ct(")",ot.muted)}`);let u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,l=e.context_window?.current_usage,p=[l?.input_tokens,l?.output_tokens,l?.cache_creation_input_tokens,l?.cache_read_input_tokens].filter(w=>typeof w=="number"&&Number.isFinite(w)),f=p.length>0?p.reduce((w,A)=>w+A,0):null,m=Number(e.context_window?.total_input_tokens??f??l?.input_tokens??0),h=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,m/u)):0,y=d!==null&&u>0?Math.round(h*u):m,v;if(u>0||d!==null){let w=`${String(Math.round(h*100)).padStart(2," ")}%`,A=u>0?` ${ct(`(${hj(y)}/${hj(u)})`,ot.muted)}`:"";v=`${ct("Context",ot.muted)} ${mj(h)} ${ct(w,ot.green)}${A}`}else v=`${ct("Context",ot.muted)} ${ct("-",ot.muted)}`;let E=L_t(e.rate_limits),b=[v];return E&&b.push(E),{identity:a.join(t),metrics:b.join(t)}}function RBr(e){let t=` ${ct("\u2502",ot.chrome)} `,r=Y_t(e),n=r.model||"codex",i=[ct(`[${n}]`,ot.visaBlueSoft)];r.project&&i.push(ct(r.project,ot.visaGold)),r.gitBranch&&i.push(`${ct("git",ot.muted)} ${ct(r.gitBranch,ot.visaGold)}`);let o=i.join(t),s=[];if(typeof r.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,r.contextUsedPercent/100));s.push(`${ct("Context",ot.muted)} ${mj(c)} ${ct(`${Math.round(r.contextUsedPercent)}%`,ot.green)}`)}else if(typeof r.contextRemainingPercent=="number"){let c=100-r.contextRemainingPercent,u=Math.max(0,Math.min(1,c/100));s.push(`${ct("Context",ot.muted)} ${mj(u)} ${ct(`${Math.round(c)}%`,ot.green)}`)}typeof r.usedTokens=="number"&&s.push(`${ct("Tokens",ot.muted)} ${hj(r.usedTokens)}`),r.status&&s.push(`${ct("Status",ot.muted)} ${ct(r.status,ot.visaBlueSoft)}`),r.threadTitle&&s.push(`${ct("Thread",ot.muted)} ${ct(r.threadTitle,ot.visaBlueSoft)}`);let a=s.length>0?s.join(t):`${ct("Context",ot.muted)} ${ct("-",ot.muted)}`;return`${o}
20956
20956
  ${a}`}function NBr(e){if(typeof e!="number"||e<=0)return"";let r=(e>1e12?e:e*1e3)-Date.now();if(r<=0||r>=10080*60*1e3)return"";let n=Math.floor(r/6e4),i=Math.floor(n/60),o=n%60;return i>0?`${i}h ${o}m`:`${o}m`}function U_t(e,t){if(!e||typeof e.used_percentage!="number")return null;let r=Math.max(0,Math.min(100,e.used_percentage)),n=r/100,i=mj(n),o=r>=90?"\x1B[38;5;196m":r>=70?ot.visaGold:ot.green,s=`${String(Math.round(r)).padStart(2," ")}%`,a=NBr(e.resets_at),c=a?` ${ct(`(${a} / ${t})`,ot.muted)}`:` ${ct(`(${t})`,ot.muted)}`;return`${i} ${ct(s,o)}${c}`}function L_t(e){if(!e)return null;let t=U_t(e.five_hour,"5h"),r=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,n=r!==null&&r>=90?U_t(e.seven_day,"7d"):null;if(!t&&!n)return null;let i=` ${ct("\u2502",ot.chrome)} `,o=[t,n].filter(Boolean);return`${ct("Usage",ot.muted)} ${o.join(i)}`}function z_t(e){let t;try{let r=iy.statSync(e);if(!r.isFile())return null;let n=r.size;if(n===0)return null;let i=Math.min(n,CBr),o=n-i;t=iy.openSync(e,"r");let s=Buffer.alloc(i);iy.readSync(t,s,0,i,o);let a=s.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(iy.readSync(t,c,0,1,o-1),c[0]!==10){let u=a.indexOf(`
20957
20957
  `);u>=0&&(a=a.slice(u+1))}}return a}catch{return null}finally{if(t!==void 0)try{iy.closeSync(t)}catch{}}}function BBr(e){if(!e||typeof e!="object")return;let t=e,r=["file_path","path","notebook_path","pattern","command","url"];for(let n of r){let i=t[n];if(typeof i=="string"&&i.length>0){if(n.endsWith("_path")||n==="path"){let o=E0.basename(E0.dirname(i)),s=E0.basename(i);return o&&o!=="."&&o!=="/"?`${o}/${s}`:s}return i}}}function jBr(e){let t=e.split(`