@visa/cli 5.0.0-rc.401 → 5.0.0-rc.402

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,9 +1,9 @@
1
1
  "use strict";var Knt=Object.create;var lR=Object.defineProperty;var Wnt=Object.getOwnPropertyDescriptor;var Ynt=Object.getOwnPropertyNames;var Jnt=Object.getPrototypeOf,znt=Object.prototype.hasOwnProperty;var R=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var _=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},kh=(e,t)=>{for(var r in t)lR(e,r,{get:t[r],enumerable:!0})},Mae=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ynt(t))!znt.call(e,o)&&o!==r&&lR(e,o,{get:()=>t[o],enumerable:!(n=Wnt(t,o))||n.enumerable});return e};var j=(e,t,r)=>(r=e!=null?Knt(Jnt(e)):{},Mae(t||!e||!e.__esModule?lR(r,"default",{value:e,enumerable:!0}):r,e)),$=e=>Mae(lR({},"__esModule",{value:!0}),e);var Na,z5=R(()=>{"use strict";Na="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function Uae(e){return`${e}-${kae.randomBytes(24).toString("base64url")}`}function Znt(e=process.env){return e.NODE_ENV==="test"||e[Xnt]==="true"}function Ca(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&Znt(e)}function jae(){return Lae??=Uae("mock-session"),Lae}function X5(e=process.env){return e.NODE_ENV==="test"?Na:(Dae??=Uae("mock-rc"),Dae)}var kae,Xnt,Lae,Dae,Bae=R(()=>{"use strict";kae=j(require("crypto"));z5();Xnt="VISA_ALLOW_INSECURE_MOCKS"});function Tt(e=process.env){let t=e[Vae];return typeof t=="string"&&t.trim().length>0?t:fR.join(qae.homedir(),".visa-cli")}function Fae(e=process.env){let t=e[Vae];return typeof t=="string"&&t.trim().length>0}function Gae(e=process.env){let t=fR.resolve(Tt(e));return Hae.createHash("sha256").update(t).digest("hex").slice(0,16)}var Hae,qae,fR,Vae,Xo=R(()=>{"use strict";Hae=j(require("crypto")),qae=j(require("os")),fR=j(require("path")),Vae="VISA_CLI_HOME"});function Qnt(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function In(e,t){return new MT(`${e} ${t}`)}function _R(e=process.platform){if(e==="win32")throw new MT("owner-only identity files are not supported on Windows yet; protocol-v2 pairing is disabled until verified ACL storage is available")}function M_(e,t,r,n){try{return r.lstatSync(e)}catch(o){if(n&&Qnt(o))return null;throw In(t,"could not be inspected safely")}}function Wae(e,t){_R(t);let r=e.expectedUid??process.geteuid?.();if(!Number.isSafeInteger(r)||r<0)throw new MT("private state owner could not be verified against the process effective uid");return r}function Uh(e,t,r){return!(r!=="win32"||e.dev!==0||t.dev!==0||e.ino!==0||t.ino!==0)||e.dev===t.dev&&e.ino===t.ino}function pR(e,t,r,n){if(e.isSymbolicLink()||!e.isDirectory())throw In(t,"must be a real owner-only directory, not a symlink");if(r!=="win32"){if(e.uid!==n)throw In(t,"must be owned by the current effective user");if((e.mode&63)!==0)throw In(t,"must not grant access to group or other users (use mode 0700)")}}function xT(e,t,r,n){if(e.isSymbolicLink()||!e.isFile())throw In(t,"must be a real owner-only regular file, not a symlink");if(r!=="win32"){if(e.uid!==n)throw In(t,"must be owned by the current effective user");if((e.mode&63)!==0)throw In(t,"must not grant access to group or other users (use mode 0600)")}}function So(e,t={}){let r=t.ops??Z5,n=t.platform??process.platform,o=Wae(t,n),i=M_(e,"private state directory",r,!0);return i?(pR(i,"private state directory",n,o),!0):!1}function Q5(e,t={}){let r=t.ops??Z5,n=t.platform??process.platform,o=t.maxBytes??jh;if(!Number.isSafeInteger(o)||o<1)throw new Error("private state maximum size must be a positive safe integer");let i=Wae(t,n),s=L_.dirname(e),a=M_(s,"private state directory",r,!0);if(!a)return null;pR(a,"private state directory",n,i);let c=M_(e,"private state file",r,!0);if(!c)return null;xT(c,"private state file",n,i);let u;try{try{u=r.openSync(e,r.constants.O_RDONLY|(r.constants.O_NOFOLLOW??0))}catch{throw In("private state file","changed or could not be opened safely")}let d=r.fstatSync(u);if(xT(d,"private state file",n,i),!Uh(c,d,n))throw In("private state file","changed while it was being opened");if(!Number.isSafeInteger(d.size)||d.size<0||d.size>o)throw In("private state file",`exceeds the ${o}-byte safety limit`);let l=M_(e,"private state file",r,!1);if(xT(l,"private state file",n,i),!Uh(d,l,n))throw In("private state file","changed while it was being opened");let p=M_(s,"private state directory",r,!1);if(pR(p,"private state directory",n,i),!Uh(a,p,n))throw In("private state directory","changed while private state was being opened");let f=[],m=0;for(;m<=o;){let S=Buffer.allocUnsafe(Math.min(65536,o+1-m)),T=r.readSync(u,S,0,S.length,null);if(T===0)break;if(m+=T,m>o)throw In("private state file",`exceeds the ${o}-byte safety limit`);f.push(S.subarray(0,T))}let h=r.fstatSync(u);if(xT(h,"private state file",n,i),!Uh(d,h,n)||h.size!==d.size||h.mtimeMs!==d.mtimeMs||h.ctimeMs!==d.ctimeMs||m!==h.size)throw In("private state file","changed while it was being read");let E=M_(e,"private state file",r,!1);if(xT(E,"private state file",n,i),!Uh(h,E,n))throw In("private state file","changed while it was being read");let b=M_(s,"private state directory",r,!1);if(pR(b,"private state directory",n,i),!Uh(a,b,n))throw In("private state directory","changed while private state was being read");let A;try{A=new Kae.TextDecoder("utf-8",{fatal:!0}).decode(Buffer.concat(f,m))}catch{throw In("private state file","must contain valid UTF-8")}return{contents:A,mtimeMs:h.mtimeMs}}finally{u!==void 0&&r.closeSync(u)}}function To(e,t={}){return Q5(e,t)?.contents??null}function Pn(e,t,r=Z5,n=process.platform){_R(n);let o=L_.dirname(e),i=L_.join(o,`.${L_.basename(e)}.${process.pid}.${(0,$ae.randomBytes)(8).toString("hex")}.tmp`),s=r.constants.O_NOFOLLOW??0,a,c=!1;try{a=r.openSync(i,r.constants.O_WRONLY|r.constants.O_CREAT|r.constants.O_EXCL|s,384),r.writeFileSync(a,t,{encoding:"utf8"}),r.fsyncSync(a),r.closeSync(a),a=void 0,r.renameSync(i,e),c=!0;let u;try{u=r.openSync(e,r.constants.O_RDONLY|s),r.fsyncSync(u)}finally{u!==void 0&&r.closeSync(u)}let d;try{let l=r.constants.O_DIRECTORY??0;d=r.openSync(o,r.constants.O_RDONLY|l|s),r.fsyncSync(d)}finally{d!==void 0&&r.closeSync(d)}}finally{a!==void 0&&r.closeSync(a),c||r.rmSync(i,{force:!0})}}var $ae,Z5,L_,Kae,jh,MT,jl=R(()=>{"use strict";$ae=require("node:crypto"),Z5=j(require("node:fs")),L_=j(require("node:path")),Kae=require("node:util"),jh=1024*1024,MT=class extends Error{constructor(t){super(t),this.name="PrivateStateSecurityError"}}});function tB(e=process.env){return gR.join(Tt(e),"owner-profiles")}function rB(e=process.env){return gR.join(tB(e),"profiles.json")}function Jae(e,t){return`op_${(0,mR.createHash)("sha256").update(`${nB(e)}\0${t}`).digest("hex").slice(0,24)}`}function nB(e){let t=new URL(e);if(t.username||t.password||t.search||t.hash||t.pathname!==""&&t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","::1"].includes(t.hostname)))throw new Error("owner profile auth origin must be HTTPS (or HTTP loopback)");return t.origin}function zae(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(!eot.test(String(t.profileId??""))||!eB.test(String(t.ownerPublicId??""))||!eB.test(String(t.runtimeId??""))||typeof t.loginLabel!="string"||t.loginLabel.length<1||t.loginLabel.length>320||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt)))return!1;try{return nB(String(t.authOrigin??""))===t.authOrigin&&Jae(String(t.authOrigin),String(t.ownerPublicId))===t.profileId}catch{return!1}}function Yae(){return{version:1,activeProfileId:null,profiles:[]}}function LT(e=process.env){let t=rB(e);if(!Bl.existsSync(t))return Yae();let r=To(t,{maxBytes:128*1024});if(r===null)return Yae();let n;try{n=JSON.parse(r)}catch{throw new Error(`owner profile registry contains invalid JSON at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`)}if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`owner profile registry is invalid at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`);let o=n;if(o.version!==1||!Array.isArray(o.profiles)||!o.profiles.every(zae))throw new Error(`owner profile registry is invalid at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`);let i=o.profiles,s=new Set(i.map(c=>c.profileId));if(s.size!==i.length)throw new Error(`owner profile registry has duplicate profiles at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`);let a=o.activeProfileId;if(a!==null&&(typeof a!="string"||!s.has(a)))throw new Error(`owner profile registry active profile is invalid at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`);return{version:1,activeProfileId:a,profiles:i}}function Xae(e,t=process.env){let r=tB(t);Bl.mkdirSync(r,{recursive:!0,mode:448}),Bl.chmodSync(r,448),So(r),Pn(rB(t),JSON.stringify(e,null,2))}function Hl(e=process.env){return[...LT(e).profiles]}function wn(e=process.env){let t=LT(e);return t.profiles.find(r=>r.profileId===t.activeProfileId)??null}function Zae(e){let t=e.env??process.env,r=nB(e.authOrigin);if(!eB.test(e.ownerPublicId))throw new Error("owner profile requires a stable owner UUID");let n=e.loginLabel.normalize("NFC").trim();if(!n||n.length>320)throw new Error("owner profile login label is invalid");let o=LT(t),i=Jae(r,e.ownerPublicId),s=o.profiles.find(c=>c.profileId===i);return s?{...s,loginLabel:n}:{profileId:i,authOrigin:r,ownerPublicId:e.ownerPublicId,loginLabel:n,runtimeId:(0,mR.randomUUID)(),createdAt:(e.now??new Date).toISOString()}}function Qae(e,t=process.env){if(!zae(e))throw new Error("refusing to activate an invalid owner profile");let r=LT(t);return Xae({version:1,activeProfileId:e.profileId,profiles:[...r.profiles.filter(n=>n.profileId!==e.profileId),e]},t),e}function hR(e,t=process.env){let r=LT(t),n=r.profiles.filter(o=>o.profileId!==e);Xae({version:1,activeProfileId:r.activeProfileId===e?null:r.activeProfileId,profiles:n},t)}function ece(e=process.env){let t=rB(e);try{Bl.unlinkSync(t)}catch(r){if(r.code!=="ENOENT")throw r}}function ER(e){return`session-token:${e.profileId}`}function ql(e,t=process.env){return gR.join(tB(t),e.profileId,"session-token")}function oB(e){return`attestation-key:${e.profileId}:${e.runtimeId}`}var mR,Bl,gR,eot,eB,Bh=R(()=>{"use strict";mR=require("node:crypto"),Bl=j(require("node:fs")),gR=j(require("node:path"));Xo();jl();eot=/^op_[a-f0-9]{24}$/,eB=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/});function bc(e=process.env){let t=e.VISA_CLI_HOME,r=typeof t=="string"&&t.trim().length>0?t:UT.homedir();return Vh.join(r,".visa-mcp","session-token")}function Hh(e=process.env){let t=e.VISA_CLI_HOME,r=typeof t=="string"&&t.trim().length>0?t:UT.homedir();return Vh.join(r,".visa-mcp","rc-access")}function yR(e=process.env){return Fae(e)?`rc-access:home:${Gae(e)}`:Wu}function rot(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
2
2
  `)}function iB(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=rot(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}async function oce(e){try{await bi("security",["delete-generic-password","-s",Ai,"-a",e],{timeout:5e3})}catch{}}async function ice(e){await xa()&&await oce(oB(e))}async function oot(e=Hl()){if(!await xa())return;let t=new Set([...e.map(oB),not]);for(let r of t)await oce(r)}function xa(){return process.platform!=="darwin"?Promise.resolve(!1):(tce??=(async()=>{try{return await bi("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return iB(e)}})(),tce)}function iot(){if(process.platform!=="darwin")return!1;if(DT!==null)return DT;try{(0,k_.execFileSync)("security",["default-keychain","-d","user"],{timeout:1e3,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),DT=!0}catch{DT=!1}return DT}async function sot(e=Yu){if(!await xa())return null;try{let{stdout:t}=await bi("security",["find-generic-password","-s",Ai,"-a",e,"-w"],{timeout:5e3});return t.trim()||null}catch(t){if(iB(t))throw new TR("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 aot(e,t=Yu){if(!await xa())return!1;try{try{await bi("security",["delete-generic-password","-s",Ai,"-a",t],{timeout:5e3})}catch{}return await bi("security",["add-generic-password","-s",Ai,"-a",t,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function cot(e=Yu){if(await xa())try{await bi("security",["delete-generic-password","-s",Ai,"-a",e],{timeout:5e3})}catch{}}async function uot(e=Yu){if(!sB())return null;try{let{stdout:t}=await bi("secret-tool",["lookup","service",Ai,"account",e],{timeout:5e3});return t.trim()||null}catch{return null}}async function dot(e,t=Yu){if(!sB())return!1;try{let r=(0,k_.execFile)("secret-tool",["store","--label",`${Ai} ${t}`,"service",Ai,"account",t]);return r.stdin?(r.stdin.write(e),r.stdin.end(),await Promise.race([new Promise((n,o)=>{r.on("exit",i=>i===0?n():o(new Error(`secret-tool exited ${i}`))),r.on("error",o)}),new Promise((n,o)=>setTimeout(()=>{r.kill(),o(new Error("secret-tool timed out"))},tot))]),!0):!1}catch{return!1}}async function lot(e=Yu){if(sB())try{await bi("secret-tool",["clear","service",Ai,"account",e],{timeout:5e3})}catch{}}function sB(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function fot(e=Wu){if(!await xa())return null;try{let{stdout:t}=await bi("security",["find-generic-password","-s",Ai,"-a",e,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function pot(e,t=Wu){if(await xa())try{try{await bi("security",["delete-generic-password","-s",Ai,"-a",t],{timeout:5e3})}catch{}await bi("security",["add-generic-password","-s",Ai,"-a",t,"-w",e],{timeout:5e3})}catch{}}async function rce(e=Wu){if(await xa())try{await bi("security",["delete-generic-password","-s",Ai,"-a",e],{timeout:5e3})}catch{}}function _ot(e=Wu){if(!iot())return null;try{return(0,k_.execFileSync)("security",["find-generic-password","-s",Ai,"-a",e,"-w"],{timeout:1e3,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch{return null}}function qh(e=bc()){try{return Rn.readFileSync(e,"utf-8").trim()||null}catch(t){if(iB(t))throw new TR(`Unable to read Visa CLI credentials from ${e}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function SR(e,t=bc()){let r=Vh.dirname(t);Rn.mkdirSync(r,{recursive:!0,mode:448}),Rn.writeFileSync(t,e,{mode:384}),process.platform==="win32"&&mot(t)}function D_(e=bc()){try{Rn.unlinkSync(e)}catch{}}function mot(e){try{let t=UT.userInfo().username;(0,k_.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 kT(e=Yu,t=bc()){switch(process.platform){case"darwin":return{get:()=>sot(e),store:r=>aot(r,e),delete:()=>cot(e)};case"linux":return{get:()=>uot(e),store:r=>dot(r,e),delete:()=>lot(e)};default:return{get:async()=>qh(t),store:async r=>{try{return SR(r,t),!0}catch{return!1}},delete:async()=>D_(t),storesInSessionFile:!0}}}var k_,nce,Rn,UT,Vh,bi,Ai,Yu,Wu,tot,TR,tce,DT,not,ct,Vl=R(()=>{"use strict";k_=require("child_process"),nce=require("util"),Rn=j(require("fs")),UT=j(require("os")),Vh=j(require("path"));Bae();Xo();Bh();bi=(0,nce.promisify)(k_.execFile);Ai="visa-cli",Yu="session-token",Wu="rc-access";tot=5e3,TR=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};tce=null,DT=null,not="attestation-key";ct=class{static profileBackend(t){return kT(ER(t),ql(t))}static async getSessionToken(t=process.env){if(Ca(t))return Promise.resolve(jae());let r=wn(t);if(!r&&Hl(t).length>0)return null;let n=r?this.profileBackend(r):kT(),o=r?ql(r,t):bc(t),i=await n.get();if(i)return i;let s=qh(o);return s?(await n.store(s),s):null}static async saveSessionToken(t,r={}){let n=r.env??process.env;if(Ca(n))return;let o=wn(n);if(o){await this.saveProfileSessionToken(o,t,r);return}let i=kT(),s=bc(n),a=await i.store(t);if(a&&await i.get()===t){i.storesInSessionFile||D_(s);return}if(a&&await i.delete(),SR(t,s),qh(s)!==t)throw new Error("Failed to persist session token in the unlabeled slot.")}static async saveProfileSessionToken(t,r,n={}){let o=n.env??process.env;if(Ca(o))return;let i=this.profileBackend(t),s=ql(t,o);if(await i.store(r)){if(await i.get()===r){i.storesInSessionFile||D_(s),n.preserveLegacy||await this.deleteLegacySessionToken(o);return}await i.delete()}if(SR(r,s),qh(s)!==r)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Vh.dirname(s)} is writable.`));n.preserveLegacy||await this.deleteLegacySessionToken(o)}static async retireLegacySessionToken(t=process.env){Ca(t)||await this.deleteLegacySessionToken(t)}static async deleteLegacySessionToken(t=process.env){await kT().delete(),D_(bc(t))}static async getRcAccessRecord(t=process.env){if(Ca(t)){let s=X5(t);return{token:s,source:s?"keychain":null}}let r=yR(t),n=Hh(t),o=await fot(r);if(o)return{token:o,source:"keychain"};let i=qh(n);return i?{token:i,source:"file"}:{token:null,source:null}}static getRcAccessRecordSync(t=process.env){if(Ca(t)){let s=X5(t);return{token:s,source:s?"keychain":null}}let r=yR(t),n=Hh(t),o=_ot(r);if(o)return{token:o,source:"keychain"};let i=qh(n);return i?{token:i,source:"file"}:{token:null,source:null}}static async getRcAccessToken(t=process.env){return(await this.getRcAccessRecord(t)).token}static getRcAccessTokenSync(t=process.env){return this.getRcAccessRecordSync(t).token}static async saveRcAccessToken(t,r=process.env){if(Ca(r))return;let n=yR(r),o=Hh(r);await pot(t,n);try{SR(t,o)}catch{}}static async deleteRcAccessToken(t=process.env){if(Ca(t))return;let r=yR(t),n=Hh(t);await rce(r),r!==Wu&&await rce(Wu),D_(n)}static async deleteSessionToken(t=process.env){if(Ca(t))return;let r=wn(t),n=r?this.profileBackend(r):kT(),o=r?ql(r,t):bc(t);await n.delete(),D_(o)}static async deleteProfileSessionToken(t,r=process.env){Ca(r)||(await this.profileBackend(t).delete(),D_(ql(t,r)))}static async listKeychainItems(t){if(!await xa())return[];try{let{stdout:r}=await bi("security",["dump-keychain"],{timeout:5e3}),n=r.split(`
3
- `),o=[],i=null,s=null;for(let a of n){a.includes("keychain:")&&(i===t&&s&&!o.includes(s)&&o.push(s),i=null,s=null);let c=a.match(/"svce"<blob>="([^"]+)"/);c&&(i=c[1]);let u=a.match(/"acct"<blob>="([^"]+)"/);u&&(s=u[1])}return i===t&&s&&!o.includes(s)&&o.push(s),o}catch{return[]}}static async listStoredCredentials(t={}){let r=t.env??process.env,n=[];if(process.platform==="darwin"&&await xa())for(let a of["visa-cli","visa-mcp"]){let c=await this.listKeychainItems(a);for(let u of c)n.push({service:a,account:u,backend:"keychain"})}let o=bc(r);Rn.existsSync(o)&&n.push({service:"visa-cli",account:Yu,backend:"file",path:o});let i=Hl(r);for(let a of i){let c=ql(a,r);Rn.existsSync(c)&&n.push({service:"visa-cli",account:ER(a),backend:"file",path:c})}let s=Hh(r);return Rn.existsSync(s)&&n.push({service:"visa-cli",account:Wu,backend:"file",path:s}),n}static async purgeAll(t={}){let r=t.env??process.env,n=[];if(process.platform==="darwin"&&await xa())for(let a of["visa-cli","visa-mcp"]){let c=await this.listKeychainItems(a);for(let u of c)try{await bi("security",["delete-generic-password","-s",a,"-a",u],{timeout:5e3}),n.push({service:a,account:u,backend:"keychain"})}catch{}}let o=bc(r);if(Rn.existsSync(o))try{Rn.unlinkSync(o),n.push({service:"visa-cli",account:Yu,backend:"file",path:o})}catch{}let i=Hh(r);if(Rn.existsSync(i))try{Rn.unlinkSync(i),n.push({service:"visa-cli",account:Wu,backend:"file",path:i})}catch{}let s=Hl(r);for(let a of s){let c=ql(a,r);if(Rn.existsSync(c))try{Rn.unlinkSync(c),n.push({service:"visa-cli",account:ER(a),backend:"file",path:c})}catch{}}try{ece(r)}catch{}return await oot(s),n}static async clearAll(t=process.env){for(let r of Hl(t))await this.deleteProfileSessionToken(r,t);await this.deleteLegacySessionToken(t),await this.deleteRcAccessToken(t)}}});function sce(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let{approvalId:t,url:r,expiresAt:n}=e;if(typeof t!="string"||!got.test(t)||typeof n!="string"||!Number.isFinite(Date.parse(n))||typeof r!="string")return null;let o;try{o=new URL(r)}catch{return null}return o.protocol!=="https:"&&o.protocol!=="http:"||o.username||o.password||o.search||o.hash||o.pathname!==`/agent/enroll/approvals/wallet/${t}`?null:{approvalId:t,url:o.toString(),expiresAt:new Date(n).toISOString()}}var got,ace=R(()=>{"use strict";got=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i});function jT(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(aB,e)}function hot(e){return e.remedy?{remedyPath:e.remedy.path,remedyLabel:e.remedy.label}:{}}function bo(e,t={}){let r=aB[e],n=t.fix!==void 0?t.fix:r.fix;if(r.kind==="platform"&&r.escalation!=="awaiting_human"&&n!==null)throw new Error(`agent-contract: ${r.escalation} code "${e}" cannot carry a fix \u2014 no command resolves it`);return{code:e,kind:r.kind,fix:n,nextAction:t.nextAction??r.nextAction,...t.agentId?{agentId:t.agentId}:{},...hot(r)}}function Ac(e){if(e instanceof Xt)return e.diagnostic;if(e&&typeof e=="object"){let t=e,r=typeof t.agentId=="string"?t.agentId:t.details&&typeof t.details=="object"&&typeof t.details.agentId=="string"?t.details.agentId:void 0,n=r?{agentId:r}:{},o=e.underlying;if(o instanceof Xt)return o.diagnostic;let i=o?.code;if(i==="agent_paused"||i==="agent_revoked"||i==="device_key_replaced"||i==="grant_expired")return bo(i,n);let s=e.code??e.errorCode;if(jT(s))return bo(s,n);if(typeof s=="string"){let c=s.toLowerCase();if(jT(c))return bo(c,n)}let a=e.message;return jT(a)?bo(a,n):bo("unspecified_error",n)}return bo("unspecified_error")}function cce(e){if(!(e instanceof Xt)||!e.details)return;let t=e.details,r={};if(Number.isInteger(t.upstreamStatus)&&Number(t.upstreamStatus)>=100&&Number(t.upstreamStatus)<=599&&(r.upstreamStatus=t.upstreamStatus),jT(t.reason)&&t.reason===e.code&&(r.reason=t.reason),e.code==="terms_conflict"&&typeof t.purchaseId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t.purchaseId)&&(r.purchaseId=t.purchaseId),e.code==="purchase_transport_uncertain"&&(t.transportReason==="timeout"||t.transportReason==="network"||t.transportReason==="response")&&(r.transportReason=t.transportReason),e.code==="wallet_owner_approval_required"){let n=sce(t.approval);n&&(r.approval=n)}return Object.keys(r).length?r:void 0}var aB,sUr,Xt,vc=R(()=>{"use strict";ace();aB={update_required:{kind:"caller",fix:"npm install -g @visa/cli@rc",nextAction:"Upgrade Visa CLI to the minimum compatible version or newer, then retry the command."},session_required:{kind:"caller",fix:"agent_enroll",nextAction:"Run visa connect (shell) or call agent_enroll (MCP) and complete the browser sign-in. Both resume where they left off. Retry the original command after that."},identity_required:{kind:"caller",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Call agent_enroll or run visa connect, open the printed URL, enter the code at /agent/enroll/protected-agent, and have the owner approve the device and its limits. Both entrances use the same protected enrollment implementation."},legacy_door_removed:{kind:"caller",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Call agent_enroll or run visa connect, open the printed URL, enter the code at /agent/enroll/protected-agent, approve the device and its limits, then pay with the pay tool. Do not retry the retired command; nothing was signed, paired, or paid."},agent_selection_required:{kind:"caller",fix:null,nextAction:"Retry the command with one exact agent id from the executable choices in the error."},invalid_argument:{kind:"caller",fix:null,nextAction:"Correct the invalid argument named in the error, then retry the command once. Do not escalate this as a platform incident."},rate_limited:{kind:"caller",fix:"sleep <retry-after-seconds>",nextAction:"Wait the exact Retry-After duration named in the error, then retry the same request once. Do not retry sooner or switch agents to bypass the limit."},activity_entry_not_found:{kind:"caller",fix:"history",nextAction:'Call history for the same agent, select an exact activity id from that result, then read it with history { "id": "<activity-id>" }.'},wallet_network_mismatch:{kind:"caller",fix:"discover",nextAction:"The unpaid challenge offered no Tempo USDC.e payment this wallet can make. Nothing was reserved, signed, or paid. Choose a service that accepts Tempo; do not retry the same challenge unchanged."},agent_operations_cli_upgrade_required:{kind:"caller",fix:null,nextAction:"Use a reviewed CLI build at or above the minimum version named by the server, restart the agent session, and retry once. The payment was not sent."},agent_operation_forbidden:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This owner, agent, runtime, rail, or rollout state is not admitted to the universal payment route. Ask the owner to inspect the selected agent; do not retry through a legacy path."},runtime_context_not_found:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The server cannot find a current managed runtime contract for this exact agent and device. Ask the owner to inspect or renew that runtime before retrying."},product_policy_not_active:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet setup did not install its server-owned spend policy. Resume the owner-approved wallet setup for this agent; do not retry the payment unchanged."},runtime_spend_session_not_active:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet setup has no active runtime spend session. Resume the owner-approved wallet setup for this agent; do not retry the payment unchanged."},runtime_spend_attenuation_not_active:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet runtime spend limits are not bound to the active owner policy. Resume the owner-approved wallet setup for this agent; do not retry the payment unchanged."},runtime_revoked:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This exact runtime has been revoked. Do not reuse it; ask the owner to certify a new runtime for the same agent if access should continue.",remedy:{path:"/agent/enroll/agents",label:"Check the agent in the Console"}},certified_runtime_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This payment requires an owner-certified runtime. Ask the owner to approve the wallet runtime certificate, then retry once."},runtime_certificate_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet runtime certificate is invalid, expired, or no longer current. Ask the owner to renew it; do not retry unchanged."},runtime_delegation_missing:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This runtime has no active owner delegation for short signing leases. Ask the owner to finish secure wallet setup before retrying.",remedy:{path:"/agent/enroll/agents",label:"Finish the agent's wallet setup"}},runtime_delegation_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This runtime owner delegation has expired. Ask the owner to renew secure wallet authority before retrying.",remedy:{path:"/agent/enroll/agents",label:"Renew the agent's approval"}},runtime_authority_unavailable:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"The server could not verify runtime authority. Surface the outage to an operator and do not retry or fall back until authority health is restored."},universal_required_managed_only:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The universal route requires a fully managed TVC wallet for this agent. Ask the owner to finish managed wallet setup before retrying."},wallet_authority_cli_upgrade_required:{kind:"caller",fix:null,nextAction:"Upgrade the CLI to the minimum version named by the server, restart this agent session, and retry once. Nothing was signed or paid."},tap_signature_required:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"Escalate to a human. A TAP identity signer is available on this runtime but could not sign, so the paid request was not sent unsigned and nothing was paid. Do not retry the payment unsigned. Probe remains unsigned."},wallet_owner_approval_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was paid. Show the owner the approval link in details.approval.url, bare, and ask them to approve this exact payment before details.approval.expiresAt. Then call pay again with the SAME target, max, body and economicIntentId: until they sign, the retry returns this same refusal (safe to repeat every 15-30 seconds); once they sign, the identical authorization resumes. Do not change the payment or start a new one. If the approval expires first, the retry says so and nothing is paid: stop then."},wallet_owner_approval_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was paid. The owner's approval for this exact payment can no longer be used (it expired before the payment completed). Stop: do not call pay again with this economicIntentId, it will keep answering this. Tell the owner; only if they still want it, start a NEW payment with a NEW economicIntentId, which asks them to approve again."},attestation_key_drift:{kind:"caller",fix:"visa connect",nextAction:"This device holds a credential the server does not recognize (machine swap, keychain wipe, restored backup). Clear the stale local credential, enroll a fresh protected agent with visa connect, then retry."},rc_access_required:{kind:"platform",escalation:"awaiting_human",fix:"export VISA_RC_CODE=<access code>",nextAction:"This is a release-candidate build restricted to Visa employees. Set VISA_RC_CODE in this process, then retry. Ask your team lead or Visa Crypto Labs for the code \u2014 do not guess it."},early_access_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Escalate to a human: an admin must enable this tool for the account. Do not retry until they confirm."},capability_attach_pending_approval:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner to finish the approval already open in their browser at /agent/enroll/protected-agent \u2014 the device and its limits are approved there. Do not start a second ceremony; wait for the owner, then retry the original command."},card_checkout_not_on_pay:{kind:"caller",fix:"purchase_create",nextAction:"Nothing was probed further, created or charged. This URL answered no payment challenge, so it is an ordinary merchant checkout and `pay` cannot do it: `pay` spends from the agent wallet only. Card checkouts are the `purchase` resource (`purchase_create`, then `purchase_retrieve`), where Visa issues the credential and YOUR runtime drives the browser. Do not retry this target on `pay`."},card_draw_not_live:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Escalate to a human now. The card-draw surface is not live on this build (it is opt-in server-side), so no local configuration change makes this command work. Do not retry."},checkout_review_refused:{kind:"caller",fix:null,nextAction:"Nothing was charged. This checkout needs a supported card-field adapter. Choose another supported checkout, or give the merchant and adapter details to the product team; do not retry unchanged."},checkout_action_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was charged and no payment credential was requested. Ask the human to complete the named verification step, then retry the review once."},checkout_mandate_blocked:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was charged. Ask the owner to approve a mandate that covers the exact merchant, amount, and currency, then start a new review. Do not widen authority yourself."},card_mandate_activation_uncertain:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The owner approved the budget but the card network did not confirm its activation. No budget is usable and nothing was charged. Do not start another approval while this one is valid: ask the owner to review the budget in the Visa Console and, once the approval has expired or been revoked there, approve a fresh budget. Quote the request id when reporting it."},ucp_platform_profile_unavailable:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Do not retry this checkout. Escalate to the Visa deployment owner: the exact UCP platform profile advertised to merchants must serve a valid HTTPS JSON profile without redirects before checkout handoff can work."},wallet_capability_unavailable:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Escalate to a human now. The wallet capability is not served by this build. Do not retry."},surface_disabled:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Escalate to a human now. The server reports this surface disabled or not configured (kill switch or missing server config \u2014 see the flag and correlation_id in the error). No retry or local change resolves it."},wallet_grant_required:{kind:"platform",escalation:"awaiting_human",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"The Turnkey wallet is delegated by the human owner, not self-minted here. Call agent_enroll or ask the owner to run visa connect and approve the device and its limits at /agent/enroll/protected-agent, then retry.",remedy:{path:"/agent/enroll/agents",label:"Approve this agent in the Console"}},wallet_credential_required:{kind:"platform",escalation:"awaiting_human",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Call agent_enroll or ask the owner to run visa connect for the intended agent and approve the device and its limits at /agent/enroll/protected-agent, then retry. Identity alone does not grant spend authority.",remedy:{path:"/agent/enroll/agents",label:"Approve this agent in the Console"}},grant_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was reserved, signed, or charged. The owner's spending approval for this agent has expired. Ask the owner to renew it in the Visa Console at /agent/enroll/limits?agent=<agent-id> (the same limits are pre-filled), then retry the same payment once. Do not create a new agent or reconnect.",remedy:{path:"/agent/enroll/limits",label:"Renew the agent's approval"}},managed_limits_owner_controlled:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. Managed wallet limits are owner-set on the server. Read them with get_status, then ask the owner to change them in the Visa Console at /agent/enroll/limits?agent=<agent-id>.",remedy:{path:"/agent/enroll/limits",label:"Change the agent's limits"}},agent_paused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner to resume this exact agent in the Visa Console (Agents). Retry only after get_status reports it ready; do not create a replacement credential while the agent is paused.",remedy:{path:"/agent/enroll/agents",label:"Resume the agent in the Console"}},owner_declined:{kind:"caller",fix:null,nextAction:"The owner declined this payment; don't retry it. Nothing was charged. Tell the owner and move on; only if they ask for it again, start a new payment (a new economicIntentId or a new purchase), which asks them again."},owner_withdrawal_pending:{kind:"caller",fix:null,nextAction:"Nothing was signed or paid. The owner is withdrawing from this wallet and that transfer is still settling (at most about ten minutes). Retry the same payment in a minute; the budget is unchanged."},kill_switch_engaged:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Visa has paused payments on this rail (card, wallet or Tempo), or could not confirm they are open. Nothing was paid. Tell the owner, and try the same purchase again later; do not loop, switch rails to get around it, or create a replacement."},agent_revoked:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This agent is permanently revoked. Do not retry or reuse its credentials; ask the owner whether to pair a new agent identity.",remedy:{path:"/agent/enroll/agents",label:"Connect a new agent in the Console"}},device_key_replaced:{kind:"platform",escalation:"awaiting_human",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Nothing was paid. This computer's keys for the agent were replaced on another computer, which now is the agent. Do not retry here. To use this computer too, call agent_enroll (or have the owner run visa connect) and approve it as a new agent."},agent_stale:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The server cannot prove this agent is currently usable. Ask the owner to inspect its lifecycle and reauthorize it before retrying.",remedy:{path:"/agent/enroll/agents",label:"Check the agent in the Console"}},agent_lifecycle_unknown:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"The lifecycle state is unknown. Surface the full preflight result to a human and do not retry a money operation until the server reports active."},wallet_delivery_required:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"The approved wallet runtime was not delivered completely. Ask the owner to re-run visa connect and re-approve the device and its limits before paying; do not self-mint a mainnet wallet.",remedy:{path:"/agent/enroll/agents",label:"Reconnect this agent in the Console"}},wallet_authority_revoked:{kind:"caller",fix:"get_status",nextAction:"This wallet is preserved for recovery only. Inspect its balance and receipts with get_status or history; do not retry a payment or policy change until the owner approves a new wallet grant."},wallet_authority_replacement_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This compatibility error came from an older single-wallet runtime. Upgrade the CLI and re-run the wallet grant; current builds isolate wallet authority per agent."},wallet_policy_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed. Ask the owner to set per-purchase and daily spend caps in the Visa Console at /agent/enroll/limits?agent=<agent-id>, then retry once. Caps are enforced before anything is signed.",remedy:{path:"/agent/enroll/limits",label:"Set spending caps in the Console"}},wallet_funding_required:{kind:"caller",fix:"get_status",nextAction:"Ask the owner to add USDC.e on Tempo to their wallet before paying: the Visa Console shows the wallet's address and balance under Payments.",remedy:{path:"/agent/enroll/payments",label:"Add funds to the wallet"}},wallet_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner to finish wallet setup in the Visa console (their account has no usable wallet yet), then re-run the grant. Do not keep polling: the ceremony cannot complete until the wallet exists.",remedy:{path:"/agent/enroll/payments",label:"Finish wallet setup"}},checkout_agent_access_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Escalate to a human: this account is not enabled for agent checkout, so grant ceremonies are refused server-side. Do not retry until an admin confirms the account has access."},unknown_tool:{kind:"caller",fix:null,nextAction:"Call tools/list and dispatch one of the served names. The tool you asked for is not registered on this runtime."},handoff_not_found:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The Console claim code was not found or was mistyped. Ask the human for a fresh claim code from the Visa Console; do not retry this code."},handoff_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This Console claim code has expired. Ask the human to create a new setup code in the Visa Console."},handoff_already_redeemed:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This Console claim code has already been redeemed. Ask the human to create a new setup code in the Visa Console."},no_paired_agent:{kind:"caller",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"No protected agent on this device. Call agent_enroll or run visa connect and complete the owner ceremony at /agent/enroll/protected-agent first."},agent_id_required:{kind:"caller",fix:null,nextAction:"Pass the agentId to identify which agent ceremony to operate on."},already_terminal:{kind:"caller",fix:null,nextAction:"This ceremony is already terminal or cancelled. No further action needed."},purchase_transport_uncertain:{kind:"caller",fix:null,nextAction:"Wait briefly, then repeat the identical Visa purchase call with the same arguments, request key and purchase ID. The original request may have succeeded; its journal recovers the same attempt. Do not cancel, create a replacement or submit Pay at the merchant again. Escalate repeated transport failures."},purchase_refused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The authority refused this purchase request. Use the recorded upstream status and error to resolve the refusal before trying again. Preserve the original purchase and request key; a refusal is not permission to mint a replacement or repeat merchant payment."},recovery_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Inspect the original purchase and checkout with the owner or support. Preserve the purchase ID and request key. Do not create a replacement, release uncertain liability or submit Pay again."},card_recovery_unconfigured:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Card recovery is not configured. Ask support to restore the protected recovery worker before retrying the same Visa request. Preserve the purchase ID; do not create another purchase or click merchant Pay again."},card_recovery_original_not_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The original credential attempt is still live. Retrieve the same purchase without include:card and follow its continuation; do not force recovery, create another purchase or click merchant Pay again."},card_recovery_liability_present:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The original attempt still has liability. Ask support to reconcile that attempt and inspect the existing checkout. Do not release funds, issue replacement credentials or click merchant Pay again."},card_recovery_issuance_conflict:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Recovery found conflicting issuance evidence. Stop and ask support to reconcile the original purchase and attempt. Do not create another purchase or click merchant Pay again."},card_recovery_proof_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The recovery proof could not be verified. Ask support to repair recovery for the existing device and purchase; do not replay the invalid proof, replace the identity or click merchant Pay again."},card_purchase_quarantined:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This purchase is quarantined for reconciliation. Ask support to inspect its original attempt and the existing checkout. Do not create another purchase, release its liability or click merchant Pay again."},card_credential_not_available:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Credentials are not available for this purchase state. Retrieve the same purchase without include:card and follow its continuation. Do not recreate the purchase or click merchant Pay again."},purchase_submission_observed:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Submission was already reported for this purchase. Inspect the existing merchant checkout and report its current state on the same purchase. Do not request replacement credentials or click merchant Pay again."},protected_card_request_invalid:{kind:"caller",fix:null,nextAction:"The card executor refused the saved delivery request, usually because its admission has expired. Retrieve the same purchase and follow its continuation; if it reads expired, run purchase create again with the same request file. Do not create a replacement purchase by hand."},protected_card_delivery_conflict:{kind:"caller",fix:null,nextAction:"The saved delivery request differs from the one already in progress for this attempt. Retrieve the same purchase and follow its continuation; do not alter or replay edited request bytes."},protected_card_authority_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The card authority did not answer the executor. Nothing was issued. Wait a moment and retrieve the same purchase; recovery continues server-side."},purchase_cancelled:{kind:"caller",fix:null,nextAction:"This purchase was cancelled; it accepts no new credential. Create a new purchase for a fresh checkout if the buyer still wants it. Do not click merchant Pay."},card_intent_unobserved:{kind:"caller",fix:null,nextAction:"The owner's card allowance for this agent is not active yet. Follow next.open_url so the owner finishes card setup, then retry the same checkout."},card_intent_mandate_exists:{kind:"caller",fix:null,nextAction:"The owner's current approval already has a card allowance in progress. Wait for it to finish (or ask the owner to check the limits page), then retry the same checkout."},card_intent_conflict:{kind:"caller",fix:null,nextAction:"A different card allowance request already exists under this id. Retrieve current status instead of resending edited request bytes."},card_vic_provider_refused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The provider refused credential issuance. Ask the owner or support to inspect the original purchase and provider refusal before retrying; an HTTP error does not prove its reservation was released. Do not create a replacement purchase or click merchant Pay again."},terms_conflict:{kind:"caller",fix:null,nextAction:"The request conflicts with the existing checkout commitment or quote bound. Retrieve the original purchase and compare the exact final terms. Do not change the request key or checkout ID to bypass the conflict; resolve it under the checkout replacement rules."},card_checkout_expired:{kind:"caller",fix:null,nextAction:"The exact checkout quote expired. Inspect the original purchase before obtaining a new final quote. Do not reuse stale terms or bypass checkout replacement rules by changing the request key or checkout ID."},card_mandate_expired:{kind:"caller",fix:null,nextAction:"The owner's card allowance for this agent lapsed (the provider limits each one to 7 days) while the approval itself is still valid; Visa is issuing a replacement under that approval. Wait afterMs and run the same purchase create again. Do not involve the owner or create a replacement purchase."},card_allowance_preparing:{kind:"caller",fix:null,nextAction:"Visa is issuing this agent's card allowance under the owner's existing approval. Wait afterMs and run the same purchase create again; the wait loop does this for you. Do not involve the owner or create a replacement purchase."},protected_card_instrument_inactive:{kind:"platform",escalation:"awaiting_human",fix:"purchase_create",nextAction:"This agent's card connection points at a saved-card record the owner has since replaced (re-verifying the card) or removed. Call purchase_create again with the saved resumeId: it returns one open_url that reconnects this agent to the owner's current saved card. The owner opens it once, then the same saved purchase resumes. Do not ask for card details, create another agent or purchase, or click merchant Pay again."},card_reservation_expired:{kind:"caller",fix:null,nextAction:"Retrieve the same purchase to resolve its expired reservation. Follow its current continuation; do not replay stale admission bytes or create a replacement to hide an unresolved attempt."},card_merchant_country_mismatch:{kind:"caller",fix:null,nextAction:"Use the actual merchant country consistently in the signed checkout terms and settlement envelope. Preserve the existing purchase commitment; do not change keys to bypass a terms conflict."},protected_grant_proof_mismatch:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner or support to verify the current grant and runtime proof for this existing agent. Do not retry an unchanged invalid proof or create replacement authority."},purchase_resume_invalid:{kind:"caller",fix:null,nextAction:"Use the exact saved purchase resume reference by itself; do not combine it with a new request. Preserve the original purchase and merchant checkout."},purchase_draft_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The saved purchase request is damaged or changed. Stop and ask support to recover the original draft; do not overwrite it, invent new terms or click merchant Pay again."},purchase_draft_not_found:{kind:"caller",fix:null,nextAction:"Use the original device and exact saved resume reference. Locate the existing draft before continuing; do not recreate the request or click merchant Pay again."},purchase_draft_agent_invalid:{kind:"caller",fix:null,nextAction:"Select the existing protected agent by its exact UUID and resume the original draft. Do not create a replacement identity or purchase."},purchase_draft_agent_mismatch:{kind:"caller",fix:null,nextAction:"Resume this draft with the same protected agent it already selected. Do not switch agents, replace the draft or click merchant Pay again."},purchase_draft_owner_mismatch:{kind:"caller",fix:null,nextAction:"Sign in as the owner who started this draft on the original device, then resume that same draft. Do not transfer it to another owner or create a replacement purchase."},purchase_draft_owner_required:{kind:"caller",fix:null,nextAction:"Complete the returned owner sign-in step, then resume the same saved draft. Do not start another identity enrollment or purchase."},purchase_draft_busy:{kind:"caller",fix:null,nextAction:"Wait for the current Visa purchase call to finish, then repeat the same resume reference. Do not run concurrent purchase calls, create a replacement or click merchant Pay again."},purchase_not_found:{kind:"caller",fix:null,nextAction:"Check the original purchase ID and selected agent. Recover the existing purchase record; do not mint a replacement merely because a read could not find it."},invalid_contract:{kind:"caller",fix:null,nextAction:"Correct the request using the declared tool schema, then retry only with valid input. Never fabricate facts or change existing payment identifiers to bypass their commitment."},invalid_amount:{kind:"caller",fix:null,nextAction:"Supply a positive canonical amount in the units required by the selected tool. Follow its total and precision constraints; never change identifiers to bypass an existing payment commitment."},invalid_currency:{kind:"caller",fix:null,nextAction:"Use the currency required by the selected payment profile. Do not infer merchant country from currency."},unsupported_version:{kind:"caller",fix:null,nextAction:"Use a supported protocol version and profile. Check the current tool schema or update Visa CLI, then retry the same logical operation without bypassing its existing commitment."},native_runtime_signer_not_installed:{kind:"platform",escalation:"awaiting_human",fix:"npm i -g @visa/cli@rc",nextAction:"The Visa CLI install on this machine has no native signer for this platform, so no wallet key can be proven. Ask the owner to reinstall Visa CLI; do not retry."},native_runtime_signer_not_executable:{kind:"platform",escalation:"awaiting_human",fix:"npm i -g @visa/cli@rc",nextAction:"The native signer is present but this machine will not run it, and Visa CLI could not repair its file mode. Ask the owner to reinstall Visa CLI, or to run chmod 755 on the path in the error; do not retry."},native_runtime_platform_unsupported:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Visa CLI ships no native signer for this operating system and CPU, so wallet keys cannot be held here. Surface this to the owner; do not retry."},native_runtime_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The native signer could not be started. The error names why (EACCES is the executable bit; ENOENT is a missing binary). Surface it to the owner; do not retry."},native_runtime_closed:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The native signer exited before answering. The error carries its exit code and its last output. Surface it to the owner; do not retry."},native_runtime_response_invalid:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"The native signer answered with something Visa CLI could not read, which usually means the CLI and its signer are from different builds. Ask the owner to reinstall Visa CLI; do not retry."},keychain_not_found:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This Mac user has no default keychain, so no agent key was stored or read and no system dialog was opened. Ask the owner to restore or create their login keychain in Keychain Access, then retry. On a server with no keychain, the owner can choose file custody explicitly with VISA_RUNTIME_CUSTODY_PROFILE=headless."},custody_store_unreadable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The agent key store on this machine could not be read (its permissions or the disk), so nothing was signed and nothing was changed. Ask the owner to restore read access to Visa CLI's agent-keys directory, then retry. Do not re-enroll: the key may still be there."},keychain_locked_or_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The macOS login keychain is locked or refused, so this agent's key could not be read. Nothing was signed or sent, and no new key was made. Ask the owner to unlock the login keychain (log in to the Mac, or open Keychain Access), then retry once."},custody_unavailable:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"This agent's key is not on this computer: it was set up by an older Visa CLI or on another computer. Nothing was signed or sent. Ask the owner to update Visa CLI (npm i -g @visa/cli@rc) and run visa connect on this computer, then approve the new agent in the browser."},protected_card_enrollment_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The owner must verify a payment card once for this account. Ask the owner to sign in at /agent/enroll and complete the Verify your card step, then retry the original command once.",remedy:{path:"/agent/enroll?enrollCard=1",label:"Verify a payment card"}},financial_rollout_approval_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The owner account is not approved for protected payments yet. Surface this to the owner; do not retry until they confirm access was granted."},key_purpose_mismatch:{kind:"platform",escalation:"awaiting_human",fix:"npm i -g @visa/cli@rc",nextAction:"The native signer refused to sign because this device key is bound to a different purpose (wallet, card, or identity) than the operation asked of it. Nothing was signed or sent. This is a Visa CLI defect or a CLI/signer version mismatch, not something a retry changes: ask the owner to update Visa CLI, then retry once. If it persists on the latest build, report it."},legacy_custody_profile_required:{kind:"platform",escalation:"awaiting_human",fix:"npm i -g @visa/cli@rc",nextAction:"The native signer refused to sign a wallet or card proof with an identity key. Nothing was signed or sent. This is a Visa CLI defect or a CLI/signer version mismatch: ask the owner to update Visa CLI, then retry once. If it persists on the latest build, report it."},identity_binding_mismatch:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The native signer refused because the request named a different agent or runtime than the device key is bound to. Nothing was signed or sent. Read get_status, then retry once with that agent's id; if it repeats, surface it to the owner rather than retrying."},proof_time_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The native signer refused a proof whose timestamp is outside its one-minute window, which means this machine's clock is wrong. Nothing was signed or sent. Ask the owner to sync the system clock, then retry once."},secret_service_locked_or_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The Linux Secret Service (the desktop keyring) is locked or refused Visa CLI, so the agent's key could not be read. Ask the owner to unlock the login keyring; on a machine without a desktop session (SSH, WSL, a server), set VISA_RUNTIME_CUSTODY_PROFILE=headless and run visa connect instead. Do not retry on your own."},secret_service_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"No Linux Secret Service is reachable (no desktop session: SSH, WSL, a container, or a server), so the agent's key could not be read. On such a machine, set VISA_RUNTIME_CUSTODY_PROFILE=headless (an owner-only key file) and run visa connect; in a desktop session, unlock the keyring (gnome-keyring or KWallet). Do not retry on your own."},secret_service_timeout:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The Linux Secret Service did not answer Visa CLI in time, usually because an unlock prompt is waiting. Ask the owner to answer or unlock the keyring, then retry once."},dpapi_locked_or_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Windows data protection (DPAPI) refused to open the agent key, usually because this is a different Windows user or profile than the one that set the agent up. Ask the owner to run Visa CLI as that user; do not retry on your own."},enrollment_device_approval_pending:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"This computer's agent setup is waiting for the owner's device approval, and starting another would strand it. Nothing was changed. Run visa connect (without --restart) to reopen the same approval, ask the owner to approve it, and only then use visa connect --restart if a replacement is still wanted."},enrollment_owner_mismatch:{kind:"platform",escalation:"awaiting_human",fix:"visa connect --restart (keep the signed-in account) or visa disconnect --all, then visa connect (switch accounts)",nextAction:"The agent approved for this terminal belongs to a different Visa account than the one this terminal is signed in to (the error names it), so nothing was connected. Let the owner choose. To keep the signed-in account: run visa connect --restart and open the new link while signed in to that account. To switch to the other account: visa disconnect --all signs this terminal out, but it also removes the Visa MCP server from every AI client, the spend HUD and any local card-delivery files, so run it only with the owner's say-so; then run visa connect and the owner signs in with the other account. Never approve for them."},wallet_key_setup_pending:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"This agent is connected but cannot pay yet: its key on the owner's Tempo wallet is not set up. The owner's open approval page finishes it on its own (it asks for USDC.e first if the wallet has none); if that page was closed, opening the Visa Console finishes it the same way. Then run visa connect (or call get_status) to confirm. Do not run visa connect --restart, and do not try a payment until it reports the key ready.",remedy:{path:"/agent/enroll/payments",label:"Finish the wallet in Payments"}},unspecified_error:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"This failure could not be classified, so it is reported as platform to avoid a silent retry loop. Surface the human-readable error to a human rather than retrying."},tempo_over_max:{kind:"caller",fix:null,nextAction:"Nothing was signed or paid. The charge costs more than max: raise max only if the human agreed to that price, otherwise stop."},tempo_budget_refused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The owner's spending budget or per-payment limit does not allow this payment. Ask the human to raise it in the Visa Console; do not retry until they have.",remedy:{path:"/agent/enroll/limits",label:"Change the agent's limits"}},tempo_chain_limit:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The wallet's weekly on-chain safety limit for this agent is used up; it refills on its weekly schedule, shown with the agent's limits in the Visa Console. Do not retry before then; tell the human if the purchase cannot wait.",remedy:{path:"/agent/enroll/limits",label:"Change the agent's limits"}},tempo_charge_expired:{kind:"caller",fix:"pay",nextAction:"Nothing was paid. The merchant charge expired before it was signed. Call pay again for the same target to get a fresh charge."},tempo_payment_unclear:{kind:"caller",fix:"pay",nextAction:"The payment may have gone through (charged: null). Do not start a new purchase. Call pay again with the SAME economicIntentId in about a minute: it reports whether the earlier payment landed and pays only if it provably did not. history shows it too."},tempo_payment_in_progress:{kind:"caller",fix:"pay",nextAction:"Another call is paying this exact purchase right now. Do not pay again; call pay again with the same economicIntentId in a minute to read its outcome."},tempo_payment_refused:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"Nothing was signed or paid. Visa refused this Tempo payment before signing. Tell the human and stop; do not retry."},tempo_charge_mismatch:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The merchant's Tempo charge does not match what this payment allows (payee, currency or paying account), checked on this machine. Do not retry; tell the human."},tempo_not_enabled:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was paid. This agent's wallet setup is not finished. Ask the owner to open Payments in the Visa Console (/agent/enroll/payments): the wallet finishes setting up there once it has funds. Then call pay again with the same economicIntentId.",remedy:{path:"/agent/enroll/payments",label:"Finish the wallet in Payments"}},tempo_unavailable:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Nothing was paid. Visa has wallet payments switched off right now. Tell the human; do not retry until Visa turns them on, and do not look for another way to pay this merchant."},merchant_not_supported:{kind:"caller",fix:null,nextAction:"Nothing was charged. This merchant does not accept Visa wallet payments (MPP on Tempo). Do not retry it on `pay`; pay a merchant that accepts Tempo, or tell the human."},merchant_unreachable:{kind:"caller",fix:null,nextAction:"Nothing was charged. The merchant URL could not be reached to read its price. Check the URL, then call pay again with the same economicIntentId."},purchase_on_retired_rail:{kind:"caller",fix:null,nextAction:"Nothing was paid. This purchase was started with the earlier wallet, before Visa moved wallet payments to Tempo. Do not pay it again: check `history` for its outcome, and use a new economicIntentId only for a genuinely new purchase."},tempo_owner_approval_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:`Nothing was paid. The owner chose "Ask me each time" for this agent's wallet payments, and this Tempo payment could not be sent to them for approval. Call pay again with the same economicIntentId: it asks the owner (the answer then carries the approval link). If it keeps failing, ask the human.`}},sUr=Object.keys(aB);Xt=class extends Error{diagnostic;details;constructor(t,r,n={}){super(t),this.name="AgentContractError";let o=n.agentId??(typeof n.details?.agentId=="string"?n.details.agentId:void 0);this.diagnostic=bo(r,{...n,...o?{agentId:o}:{}}),this.details=n.details}get code(){return this.diagnostic.code}}});var bR=_(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.CanonicalJsonError=_n.CANONICAL_OPAQUE_ID_MAX_BYTES=_n.CANONICAL_OPAQUE_ID_RE=_n.CANONICAL_OPAQUE_ID_PATTERN=void 0;_n.utf8ByteLength=dB;_n.isCanonicalText=uce;_n.compareCanonicalKeys=dce;_n.isCanonicalOpaqueId=lce;_n.assertCanonicalOpaqueId=yot;_n.canonicalJsonExact=uB;_n.CANONICAL_OPAQUE_ID_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$";_n.CANONICAL_OPAQUE_ID_RE=new RegExp(_n.CANONICAL_OPAQUE_ID_PATTERN);_n.CANONICAL_OPAQUE_ID_MAX_BYTES=128;var Eot=/[\u0000-\u001f\u007f\u2028\u2029]/,cB=new TextEncoder;function dB(e){return cB.encode(e).length}function uce(e,t){return typeof e=="string"&&e.length>0&&dB(e)<=t&&e.trim()===e&&e.normalize("NFC")===e&&!Eot.test(e)}function dce(e,t){let r=cB.encode(e),n=cB.encode(t),o=Math.min(r.length,n.length);for(let i=0;i<o;i+=1)if(r[i]!==n[i])return r[i]-n[i];return r.length-n.length}function lce(e){return typeof e=="string"&&dB(e)<=_n.CANONICAL_OPAQUE_ID_MAX_BYTES&&_n.CANONICAL_OPAQUE_ID_RE.test(e)}function yot(e,t="value"){if(!lce(e))throw new Error(`${t} must be a canonical opaque id (max 128 ASCII bytes)`)}var Sot=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,Ic=class extends Error{constructor(t){super(t),this.name="CanonicalJsonError"}};_n.CanonicalJsonError=Ic;function uB(e,t=0){if(t>16)throw new Ic("nesting is deeper than 16");if(e===null||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="string"){if(Sot.test(e))throw new Ic("text is not valid Unicode");return JSON.stringify(e)}if(typeof e=="number"){if(!Number.isSafeInteger(e)||Object.is(e,-0))throw new Ic("numbers must be whole and at most 2^53 - 1; put amounts and decimals in strings");return JSON.stringify(e)}if(Array.isArray(e)){if(e.length>1024)throw new Ic("an array has more than 1024 items");return`[${e.map(n=>uB(n,t+1)).join(",")}]`}if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new Ic("only JSON objects, arrays, strings, whole numbers and booleans");let r=Object.keys(e);if(r.length>512)throw new Ic("an object has more than 512 keys");for(let n of r)if(!uce(n,128))throw new Ic("keys must be non-empty trimmed NFC text of at most 128 bytes");return`{${r.sort(dce).map(n=>`${JSON.stringify(n)}:${uB(e[n],t+1)}`).join(",")}}`}});var Fl=_(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.AgentOperationContractError=Ma.AGENT_OPERATION_CONTRACT_ERROR_CODES=void 0;Ma.record=pce;Ma.bounded=_ce;Ma.canonicalJsonValue=mce;Ma.canonicalJson=Tot;Ma.canonicalEnvelopeJson=bot;var fce=bR();Ma.AGENT_OPERATION_CONTRACT_ERROR_CODES=["commitment_mismatch","intent_mismatch","invalid_amount","invalid_contract","invalid_currency","invalid_effect","invalid_evidence","invalid_principal","invalid_window","settlement_amount_invalid","unsupported_version"];var Ju=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="AgentOperationContractError"}};Ma.AgentOperationContractError=Ju;function pce(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new Ju("invalid_contract",`${t} must be an object`);return e}function _ce(e,t,r=4096){if(!(0,fce.isCanonicalText)(e,r))throw new Ju("invalid_contract",`${t} is not bounded canonical text`);return e}function mce(e,t=0){return AR(e,t,16)}function AR(e,t,r){if(t>r)throw new Ju("invalid_contract","payload nesting is too deep");if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isSafeInteger(e)&&!Object.is(e,-0))return e;if(typeof e=="number")throw new Ju("invalid_contract","JSON numbers must be safe canonical integers; use strings for larger or decimal values");if(Array.isArray(e)){if(e.length>1024)throw new Ju("invalid_contract","payload array is too large");return e.map(i=>AR(i,t+1,r))}let n=pce(e,"payload"),o=Object.entries(n);if(o.length>512)throw new Ju("invalid_contract","payload object is too large");return Object.fromEntries(o.sort(([i],[s])=>(0,fce.compareCanonicalKeys)(i,s)).map(([i,s])=>[_ce(i,"payload key",128),AR(s,t+1,r)]))}function Tot(e){return JSON.stringify(mce(e))}function bot(e){return JSON.stringify(AR(e,0,64))}});var zu=_(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.AGENT_OPERATION_TRANSITION_SQL_PREDICATE=be.AGENT_OPERATION_TERMINAL_SQL_LIST=be.AGENT_OPERATION_RESUMABLE_SQL_LIST=be.AGENT_OPERATION_TERMINAL_STATES=be.AGENT_OPERATION_EVIDENCE_ELIGIBLE_STATES=be.AGENT_OPERATION_RESUMABLE_STATES=be.AGENT_OPERATION_ALLOWED_TRANSITIONS=be.AGENT_OPERATION_STATES=be.EXECUTOR_BINDING_VERSION=be.EXECUTION_EVIDENCE_VERSION=be.AGENT_OPERATION_RESULT_VERSION=be.AGENT_OPERATION_VERSION=be.canonicalJsonValue=be.canonicalJson=be.AgentOperationContractError=be.AGENT_OPERATION_CONTRACT_ERROR_CODES=be.canonicalEnvelopeJson=void 0;be.isAgentOperationTransitionAllowed=wot;be.agentOperationIntentPreimage=Rot;be.parseAgentMoneyEconomics=Ece;be.parseAgentOperationStructure=yce;be.parseExecutionEvidence=Cot;be.parsePreparedAgentOperationStructure=xot;be.agentOperationPopSigningInput=Mot;var Se=Fl(),BT=Fl();Object.defineProperty(be,"canonicalEnvelopeJson",{enumerable:!0,get:function(){return BT.canonicalEnvelopeJson}});Object.defineProperty(be,"AGENT_OPERATION_CONTRACT_ERROR_CODES",{enumerable:!0,get:function(){return BT.AGENT_OPERATION_CONTRACT_ERROR_CODES}});Object.defineProperty(be,"AgentOperationContractError",{enumerable:!0,get:function(){return BT.AgentOperationContractError}});Object.defineProperty(be,"canonicalJson",{enumerable:!0,get:function(){return BT.canonicalJson}});Object.defineProperty(be,"canonicalJsonValue",{enumerable:!0,get:function(){return BT.canonicalJsonValue}});be.AGENT_OPERATION_VERSION=1;be.AGENT_OPERATION_RESULT_VERSION=1;be.EXECUTION_EVIDENCE_VERSION=1;be.EXECUTOR_BINDING_VERSION=1;var Aot=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,vot=/^[A-Za-z0-9_-]{43}$/,Iot=/^[a-z][a-z0-9]*(?:[._:-][a-z0-9]+)*$/,Pot=/^[A-Z][A-Z0-9]{2,11}$/,hce=96*1024,lB=9223372036854775807n;be.AGENT_OPERATION_STATES=["claimed","reserved","dispatched","authorized","settling","committed","released","indeterminate","denied"];be.AGENT_OPERATION_ALLOWED_TRANSITIONS={claimed:["reserved","denied"],reserved:["dispatched","released","indeterminate","settling"],dispatched:["authorized","released","indeterminate","settling"],authorized:["settling","indeterminate"],settling:["committed","released","indeterminate"],committed:[],released:[],indeterminate:["settling"],denied:[]};be.AGENT_OPERATION_RESUMABLE_STATES=["claimed","reserved","dispatched"];be.AGENT_OPERATION_EVIDENCE_ELIGIBLE_STATES=["reserved","dispatched","authorized","indeterminate"];be.AGENT_OPERATION_TERMINAL_STATES=["committed","released","denied"];function wot(e,t){return e===t||be.AGENT_OPERATION_ALLOWED_TRANSITIONS[e].includes(t)}function fB(e){return e.map(t=>`'${t}'`).join(", ")}be.AGENT_OPERATION_RESUMABLE_SQL_LIST=fB(be.AGENT_OPERATION_RESUMABLE_STATES);be.AGENT_OPERATION_TERMINAL_SQL_LIST=fB(be.AGENT_OPERATION_TERMINAL_STATES);be.AGENT_OPERATION_TRANSITION_SQL_PREDICATE=["NEW.state = OLD.state",...be.AGENT_OPERATION_STATES.filter(e=>be.AGENT_OPERATION_ALLOWED_TRANSITIONS[e].length>0).map(e=>`(OLD.state = '${e}' AND NEW.state IN (${fB(be.AGENT_OPERATION_ALLOWED_TRANSITIONS[e])}))`)].join(`
4
- OR `);function xs(e,t,r=[]){let n=new Set([...t,...r]);if(t.some(o=>!(o in e))||Object.keys(e).some(o=>!n.has(o)))throw new Se.AgentOperationContractError("invalid_contract","contract contains missing or unknown fields")}function Fh(e,t){let r=(0,Se.bounded)(e,t,36).toLowerCase();if(!Aot.test(r))throw new Se.AgentOperationContractError("invalid_contract",`${t} must be a UUID`);return r}function Pc(e,t){let r=(0,Se.bounded)(e,t,43);if(!vot.test(r)||!/[AEIMQUYcgkosw048]$/.test(r))throw new Se.AgentOperationContractError("invalid_contract",`${t} must be a canonical 32-byte hash`);return r}function vR(e,t){let r=(0,Se.bounded)(e,t,128);if(!Iot.test(r))throw new Se.AgentOperationContractError("invalid_contract",`${t} must be a stable lowercase token`);return r}function gce(e,t){let r=(0,Se.bounded)(e,t,32),n=Date.parse(r);if(!Number.isFinite(n)||new Date(n).toISOString()!==r)throw new Se.AgentOperationContractError("invalid_contract",`${t} must be canonical ISO-8601`);return r}function Rot(e){let t={domain:"visa.agent-operation-intent.v1",operationId:e.operationId,idempotencyKey:e.idempotencyKey,agentId:e.agentId,runtimeId:e.runtimeId,rail:e.rail,effect:e.effect,execution:{adapter:e.execution.adapter,commitment:e.execution.commitment,payloadHash:e.execution.payloadHash},createdAt:e.createdAt,expiresAt:e.expiresAt};return(0,Se.canonicalJson)(t)}function Oot(e){let t=(0,Se.record)(e,"principal");if(t.kind==="identity_pop")return xs(t,["kind","popJwt","keyJkt"]),{kind:t.kind,popJwt:(0,Se.bounded)(t.popJwt,"popJwt",16384),keyJkt:Pc(t.keyJkt,"keyJkt")};if(t.kind==="certified_runtime_pop")return xs(t,["kind","popJwt","runtimeCertificate","rootJkt","childJkt"]),{kind:t.kind,popJwt:(0,Se.bounded)(t.popJwt,"popJwt",16384),runtimeCertificate:(0,Se.bounded)(t.runtimeCertificate,"runtimeCertificate",32768),rootJkt:Pc(t.rootJkt,"rootJkt"),childJkt:Pc(t.childJkt,"childJkt")};if(t.kind==="delegated_runtime_lease_pop"){if(xs(t,["kind","v","popJwt","delegation","lease","rootJkt","runtimeJkt"]),t.v!==2)throw new Se.AgentOperationContractError("invalid_principal","delegated runtime lease principal must use version 2");return{kind:t.kind,v:t.v,popJwt:(0,Se.bounded)(t.popJwt,"popJwt",16384),delegation:(0,Se.bounded)(t.delegation,"delegation",32768),lease:(0,Se.bounded)(t.lease,"lease",32768),rootJkt:Pc(t.rootJkt,"rootJkt"),runtimeJkt:Pc(t.runtimeJkt,"runtimeJkt")}}if(t.kind==="tap_signature")return xs(t,["kind","signature","runtimeCertificate","signedPayload"]),{kind:t.kind,signature:(0,Se.bounded)(t.signature,"signature",2048),runtimeCertificate:(0,Se.bounded)(t.runtimeCertificate,"runtimeCertificate",32768),signedPayload:Pc(t.signedPayload,"signedPayload")};throw new Se.AgentOperationContractError("invalid_principal","unsupported principal proof kind")}function Ece(e){let t=(0,Se.record)(e,"money economics");xs(t,["amountMicros","currency","merchant"]);let r=(0,Se.bounded)(t.amountMicros,"amountMicros",40);if(!/^[1-9][0-9]*$/.test(r)||BigInt(r)>lB)throw new Se.AgentOperationContractError("invalid_amount","amountMicros must be positive and canonical");let n=(0,Se.bounded)(t.currency,"currency",12);if(!Pot.test(n))throw new Se.AgentOperationContractError("invalid_currency","currency must be canonical");let o=(0,Se.record)(t.merchant,"merchant");return xs(o,["id"],["name","url"]),{amountMicros:r,currency:n,merchant:{id:(0,Se.bounded)(o.id,"merchant.id",512),...o.name===void 0?{}:{name:(0,Se.bounded)(o.name,"merchant.name",255)},...o.url===void 0?{}:{url:(0,Se.bounded)(o.url,"merchant.url",2048)}}}}function Not(e){let t=(0,Se.record)(e,"effect");if(t.kind==="money"){xs(t,["kind","amountMicros","currency","merchant","grantId","budgetEpochId"],["maxAmountMicros"]);let r=Ece({amountMicros:t.amountMicros,currency:t.currency,merchant:t.merchant}),n;if(t.maxAmountMicros!==void 0&&(n=(0,Se.bounded)(t.maxAmountMicros,"maxAmountMicros",40),!/^[1-9][0-9]*$/.test(n)||BigInt(n)>lB))throw new Se.AgentOperationContractError("invalid_amount","maxAmountMicros must be positive and canonical");return{kind:t.kind,...r,grantId:Fh(t.grantId,"grantId"),budgetEpochId:Fh(t.budgetEpochId,"budgetEpochId"),...n===void 0?{}:{maxAmountMicros:n}}}if(t.kind==="resource")return xs(t,["kind","resource","action","audience"]),{kind:t.kind,resource:(0,Se.bounded)(t.resource,"resource",4096),action:vR(t.action,"action"),audience:(0,Se.bounded)(t.audience,"audience",255)};throw new Se.AgentOperationContractError("invalid_effect","unsupported operation effect")}function yce(e,t=Date.now()){let r=(0,Se.record)(e,"operation");if(xs(r,["v","operationId","idempotencyKey","agentId","runtimeId","rail","intentHash","principal","effect","execution","createdAt","expiresAt"]),r.v!==be.AGENT_OPERATION_VERSION)throw new Se.AgentOperationContractError("unsupported_version","unsupported operation version");let n=(0,Se.record)(r.execution,"execution");xs(n,["adapter","commitment","payloadHash","payload"]);let o=(0,Se.canonicalJsonValue)(n.payload);if(new TextEncoder().encode(JSON.stringify(o)).length>hce)throw new Se.AgentOperationContractError("invalid_contract","execution payload is too large");let i=Pc(n.commitment,"execution.commitment"),s=Pc(n.payloadHash,"execution.payloadHash"),a=gce(r.createdAt,"createdAt"),c=gce(r.expiresAt,"expiresAt");if(!Number.isFinite(t)||Date.parse(a)>t+3e4||Date.parse(a)<t-5*6e4||Date.parse(c)<=t||Date.parse(c)<=Date.parse(a)||Date.parse(c)-Date.parse(a)>10*6e4)throw new Se.AgentOperationContractError("invalid_window","operation validity window is not currently usable");let u={v:be.AGENT_OPERATION_VERSION,operationId:Fh(r.operationId,"operationId"),idempotencyKey:(0,Se.bounded)(r.idempotencyKey,"idempotencyKey",255),agentId:Fh(r.agentId,"agentId"),runtimeId:Fh(r.runtimeId,"runtimeId"),rail:vR(r.rail,"rail"),intentHash:Pc(r.intentHash,"intentHash"),principal:Oot(r.principal),effect:Not(r.effect),execution:{adapter:vR(n.adapter,"execution.adapter"),commitment:i,payloadHash:s,payload:o},createdAt:a,expiresAt:c};if(u.rail==="wallet:x402"&&u.effect.kind==="money"&&u.effect.merchant.url===void 0)throw new Se.AgentOperationContractError("invalid_contract","merchant.url is required for wallet:x402 operations");if(u.principal.kind==="tap_signature"&&u.principal.signedPayload!==u.intentHash)throw new Se.AgentOperationContractError("intent_mismatch","TAP signedPayload must equal the universal operation intentHash");return u}function Cot(e){let t=(0,Se.record)(e,"evidence");if(xs(t,["v","operationId","adapter","outcome","artifactHash","providerReference","proof"],["settledMicros"]),t.v!==be.EXECUTION_EVIDENCE_VERSION||t.outcome!=="committed"&&t.outcome!=="released")throw new Se.AgentOperationContractError("invalid_evidence","unsupported evidence version or outcome");let r;if(t.settledMicros!==void 0){if(r=(0,Se.bounded)(t.settledMicros,"settledMicros",40),!/^(?:0|[1-9][0-9]*)$/.test(r)||BigInt(r)>lB)throw new Se.AgentOperationContractError("invalid_evidence","settledMicros is not canonical");if(t.outcome==="released"&&r!=="0")throw new Se.AgentOperationContractError("settlement_amount_invalid","released evidence must settle zero")}let n=(0,Se.canonicalJsonValue)(t.proof);if(new TextEncoder().encode(JSON.stringify(n)).length>hce)throw new Se.AgentOperationContractError("invalid_evidence","evidence proof is too large");return{v:be.EXECUTION_EVIDENCE_VERSION,operationId:Fh(t.operationId,"operationId"),adapter:vR(t.adapter,"adapter"),outcome:t.outcome,artifactHash:Pc(t.artifactHash,"artifactHash"),...r===void 0?{}:{settledMicros:r},providerReference:(0,Se.bounded)(t.providerReference,"providerReference",255),proof:n}}function xot(e,t=Date.now()){let r=(0,Se.record)(e,"prepared operation");xs(r,["operationId","idempotencyKey","agentId","runtimeId","rail","intentHash","effect","execution","createdAt","expiresAt"]);let{v:n,principal:o,...i}=yce({...r,v:1,principal:{kind:"identity_pop",popJwt:"unsigned",keyJkt:"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}},t);return i}function Mot(e){let t=r=>btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(r)))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return`${t({alg:"EdDSA",kid:e.childJkt,typ:"visa-agent-pop+jwt"})}.${t({cnf:{jwk:{kty:e.childPublicJwk.kty,crv:e.childPublicJwk.crv,x:e.childPublicJwk.x}},nonce:e.operationId,aud:"visa-agent-operations:v1",iat:e.issuedAtSec,int:e.intentHash,...e.runtimeCertificate?{rkc:e.runtimeCertificate}:{}})}`}});var PR=_(IR=>{"use strict";Object.defineProperty(IR,"__esModule",{value:!0});IR.parsePurchaseTerms=Sce;IR.purchaseTermsPreimage=kot;var Et=Fl(),Lot=zu();function Gh(e,t){if(Object.keys(e).sort().join(",")!==[...t].sort().join(","))throw new Et.AgentOperationContractError("invalid_contract","purchase terms fields are not canonical")}function Sce(e){let t=(0,Et.record)(e,"purchase terms"),r=t.profile==="exact_card_checkout_v1";if(Gh(t,["v","profile","alternatives",...r?["checkout","disclosureMode",...t.merchantCountryCode===void 0?[]:["merchantCountryCode"]]:[]]),t.v!==1||typeof t.profile!="string"||!["url_resource_v1","approved_x402_request_v1","exact_card_checkout_v1"].includes(String(t.profile)))throw new Et.AgentOperationContractError("unsupported_version","unsupported purchase terms profile");if(!Array.isArray(t.alternatives)||t.alternatives.length<1||t.alternatives.length>2)throw new Et.AgentOperationContractError("invalid_contract","purchase requires one or two exact rail alternatives");let n=t.profile==="approved_x402_request_v1";if(n&&t.alternatives.length!==1)throw new Et.AgentOperationContractError("invalid_contract","request-bound purchase requires one wallet alternative");let o=t.alternatives.map(i=>{let s=(0,Et.record)(i,"purchase alternative"),a=(0,Lot.parseAgentMoneyEconomics)(s.economics),c=(0,Et.bounded)(a.merchant.url,"purchase resource URL",2048),u;try{u=new URL(c)}catch{throw new Et.AgentOperationContractError("invalid_contract","purchase resource URL is invalid")}if(u.protocol!=="https:"||u.username||u.password||u.hash)throw new Et.AgentOperationContractError("invalid_contract","purchase requires an HTTPS resource without credentials or fragment");if(s.rail==="wallet:x402"){Gh(s,["rail","economics","network","asset","payee",...n?["requestHash"]:[]]);let d=n?(0,Et.bounded)(s.requestHash,"request hash",43):void 0;if(d!==void 0&&!/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(d))throw new Et.AgentOperationContractError("invalid_contract","invalid request hash");let l=(0,Et.bounded)(s.network,"network",64),p=(0,Et.bounded)(s.asset,"asset",128),f=(0,Et.bounded)(s.payee,"payee",42);if(!/^eip155:[1-9][0-9]{0,15}$/.test(l)||!new RegExp(`^${l}/erc20:0x[0-9a-f]{40}$`).test(p)||!/^0x[0-9a-f]{40}$/.test(f)||a.currency!=="USDC")throw new Et.AgentOperationContractError("invalid_contract","invalid exact wallet economic coordinates");return{rail:s.rail,economics:a,network:l,asset:p,payee:f,...d?{requestHash:d}:{}}}if(s.rail==="card:vic"&&!n){if(Gh(s,["rail","economics","processorAction","captureMode"]),s.processorAction!=="charge_and_capture"||s.captureMode!=="exact"||a.currency!=="USD"||BigInt(a.amountMicros)%10000n!==0n)throw new Et.AgentOperationContractError("invalid_contract","purchase card profile requires exact whole-cent capture");return{rail:s.rail,economics:a,processorAction:"charge_and_capture",captureMode:"exact"}}throw new Et.AgentOperationContractError("invalid_contract","unsupported purchase rail")});if(new Set(o.map(i=>i.rail)).size!==o.length)throw new Et.AgentOperationContractError("invalid_contract","purchase rail alternatives must be unique");if(o.sort((i,s)=>i.rail<s.rail?-1:i.rail>s.rail?1:0),r){if(o.length!==1||o[0].rail!=="card:vic"||!o[0].economics.merchant.name)throw new Et.AgentOperationContractError("invalid_contract","exact checkout requires one card alternative");if(t.disclosureMode!=="private"&&t.disclosureMode!=="agent_history")throw new Et.AgentOperationContractError("invalid_contract","unsupported card disclosure mode");if(t.merchantCountryCode!==void 0&&(typeof t.merchantCountryCode!="string"||!/^[A-Z]{2}$/.test(t.merchantCountryCode)))throw new Et.AgentOperationContractError("invalid_contract","invalid merchant country");return{v:1,profile:"exact_card_checkout_v1",...t.merchantCountryCode===void 0?{}:{merchantCountryCode:t.merchantCountryCode},alternatives:o,checkout:Dot(t.checkout,o[0].economics.amountMicros),disclosureMode:t.disclosureMode}}return{v:1,profile:t.profile,alternatives:o}}function Dot(e,t){let r=(0,Et.record)(e,"checkout");Gh(r,["id","revision","source","expiresAt","items","taxMicros","shippingMicros","discountMicros","fulfillment","customerHash"]);let n=()=>{throw new Et.AgentOperationContractError("invalid_contract","invalid exact card checkout")},o=l=>((typeof l!="string"||!/^(0|[1-9][0-9]{0,17})$/.test(l)||BigInt(l)%10000n!==0n)&&n(),l),i=l=>((typeof l!="string"||!/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(l))&&n(),l);(r.source!=="runtime_observed"||typeof r.expiresAt!="string"||!Number.isFinite(Date.parse(r.expiresAt))||new Date(r.expiresAt).toISOString()!==r.expiresAt||!Array.isArray(r.items)||r.items.length<1||r.items.length>100)&&n();let s=r.items.map(l=>{let p=(0,Et.record)(l,"checkout item");return Gh(p,["id","name","quantity","totalMicros"]),(!Number.isSafeInteger(p.quantity)||Number(p.quantity)<1||Number(p.quantity)>1e6)&&n(),{id:(0,Et.bounded)(p.id,"checkout item ID",256),name:(0,Et.bounded)(p.name,"checkout item name",512),quantity:p.quantity,totalMicros:o(p.totalMicros)}});new Set(s.map(l=>l.id)).size!==s.length&&n();let a=o(r.taxMicros),c=o(r.shippingMicros),u=o(r.discountMicros);s.reduce((l,p)=>l+BigInt(p.totalMicros),0n)+BigInt(a)+BigInt(c)-BigInt(u)!==BigInt(t)&&n();let d=(0,Et.record)(r.fulfillment,"checkout fulfillment");return Gh(d,["method","detailsHash"]),{id:(0,Et.bounded)(r.id,"checkout ID",256),revision:(0,Et.bounded)(r.revision,"checkout revision",256),source:"runtime_observed",expiresAt:r.expiresAt,items:s,taxMicros:a,shippingMicros:c,discountMicros:u,fulfillment:{method:(0,Et.bounded)(d.method,"fulfillment method",256),detailsHash:i(d.detailsHash)},customerHash:i(r.customerHash)}}function kot(e){return(0,Et.canonicalJson)({domain:"visa.purchase-terms.v1",terms:Sce(e)})}});var pB=_(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.ACCOUNT_OPERATION_EVIDENCE_TYPES=Qn.ACCOUNT_OPERATION_PROOF_LEVELS=Qn.ACCOUNT_OPERATION_OUTCOMES=Qn.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=void 0;Qn.cardProofLevel=Uot;Qn.cardStatusClaimsProcessorTruth=jot;Qn.parseAccountOperationReceipt=qot;Qn.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=1;Qn.ACCOUNT_OPERATION_OUTCOMES=["pending","completed","failed","uncertain","released","reversed","disputed"];Qn.ACCOUNT_OPERATION_PROOF_LEVELS=["none","platform_observed","merchant_reported","owner_attested","processor_confirmed","network_verified","settled"];var Tce={sale_accepted:"merchant_reported",auth_held:"merchant_reported",capture_pending:"merchant_reported",captured:"processor_confirmed",voided:"processor_confirmed",refunded:"processor_confirmed",partially_refunded:"processor_confirmed",refund_pending:"processor_confirmed",chargeback_open:"processor_confirmed",chargeback_lost:"processor_confirmed",chargeback_won:"processor_confirmed",pending:"platform_observed",needs_reconciliation:"platform_observed"};function Uot(e,t){let r=Tce[e]??"platform_observed";return r==="processor_confirmed"&&!t?"merchant_reported":r}function jot(e){return Tce[e]==="processor_confirmed"}Qn.ACCOUNT_OPERATION_EVIDENCE_TYPES=["platform_activity","merchant_confirmation","card_lifecycle","onchain_transaction"];function Gl(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Xu(e){return e===null||typeof e=="string"}function HT(e){return typeof e=="string"&&e.length>0&&!Number.isNaN(Date.parse(e))}function $l(e,t){let r=Object.keys(e).sort(),n=[...t].sort();return r.length===n.length&&r.every((o,i)=>o===n[i])}function Bot(e){return Gl(e)?$l(e,["type","source","observedAt","reference","url"])&&typeof e.type=="string"&&Qn.ACCOUNT_OPERATION_EVIDENCE_TYPES.includes(e.type)&&typeof e.source=="string"&&HT(e.observedAt)&&Xu(e.reference)&&Xu(e.url):!1}function Hot(e){return Gl(e)?$l(e,["type","at"])&&typeof e.type=="string"&&e.type.length>0&&HT(e.at):!1}function qot(e){if(!Gl(e)||!$l(e,["schemaVersion","operationId","activityId","payment","route","party","authority","outcome","evidence","timeline","dataCompleteness"])||e.schemaVersion!==Qn.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION||typeof e.operationId!="string"||typeof e.activityId!="string"||e.dataCompleteness!=="complete"&&e.dataCompleteness!=="partial"||!Array.isArray(e.evidence)||!e.evidence.every(Bot)||!Array.isArray(e.timeline)||!e.timeline.every(Hot))return null;let t=e.payment,r=e.route,n=e.party,o=e.authority,i=e.outcome;return!Gl(t)||!$l(t,["amountAtomic","decimals","currency","merchant","description","createdAt"])||typeof t.amountAtomic!="string"||!/^\d+$/.test(t.amountAtomic)||typeof t.decimals!="number"||!Number.isInteger(t.decimals)||t.decimals<0||t.decimals>18||typeof t.currency!="string"||typeof t.merchant!="string"||typeof t.description!="string"||!HT(t.createdAt)||!Gl(r)||!$l(r,["rail","protocol","network","cardLast4"])||r.rail!=="wallet"&&r.rail!=="card"||!(r.protocol===null||r.protocol==="x402"||r.protocol==="mpp"||r.protocol==="vic"||r.protocol==="virtual_card")||!Xu(r.network)||!Xu(r.cardLast4)||!Gl(n)||!$l(n,["agentId","agentName"])||!Xu(n.agentId)||!Xu(n.agentName)||!Gl(o)||!$l(o,["grantId","mandateId","drawId"])||!Xu(o.grantId)||!Xu(o.mandateId)||!Xu(o.drawId)||!Gl(i)||!$l(i,["status","proofLevel","final","updatedAt","finalizesBy"])||typeof i.status!="string"||!Qn.ACCOUNT_OPERATION_OUTCOMES.includes(i.status)||typeof i.proofLevel!="string"||!Qn.ACCOUNT_OPERATION_PROOF_LEVELS.includes(i.proofLevel)||typeof i.final!="boolean"||!HT(i.updatedAt)||!(i.finalizesBy===null||HT(i.finalizesBy))?null:e}});var vce=_(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.PURCHASE_RESOURCE_AUDIENCE=is.PURCHASE_OBSERVATIONS=void 0;is.parsePurchaseReceipt=Got;is.parsePurchaseResourceRequest=Ace;is.purchaseResourceRequestHash=$ot;var Vot=require("node:crypto"),wc=Fl(),Fot=PR(),bce=pB();is.PURCHASE_OBSERVATIONS=["credential_delivered","submission_started","buyer_action_required","order_reported","submission_failed"];function Got(e,t){let r=(0,wc.record)(e,"purchase receipt"),n=(0,wc.record)(r.outcome,"purchase outcome");if(!t||r.operationId!==t||typeof r.credentialIssued!="boolean"||!bce.ACCOUNT_OPERATION_OUTCOMES.includes(n.status)||!bce.ACCOUNT_OPERATION_PROOF_LEVELS.includes(n.proofLevel)||typeof n.final!="boolean"||!Array.isArray(r.observations)||r.observations.length>is.PURCHASE_OBSERVATIONS.length||r.observations.some(i=>!is.PURCHASE_OBSERVATIONS.includes(i))||new Set(r.observations).size!==r.observations.length)throw new wc.AgentOperationContractError("invalid_contract","invalid purchase receipt");let o=r.refusal===void 0?void 0:(0,wc.record)(r.refusal,"refusal");if(o!==void 0&&(!Number.isSafeInteger(o.providerStatus)||Number(o.providerStatus)<100||Number(o.providerStatus)>999||typeof o.providerCode!="string"||!/^[a-z0-9_]{1,64}$/.test(o.providerCode)||n.status!=="failed"||n.final!==!0||r.credentialIssued!==!1))throw new wc.AgentOperationContractError("invalid_contract","invalid purchase refusal");return{operationId:t,credentialIssued:r.credentialIssued,outcome:{status:n.status,proofLevel:n.proofLevel,final:n.final},observations:r.observations,...o?{refusal:{providerStatus:Number(o.providerStatus),providerCode:o.providerCode}}:{}}}is.PURCHASE_RESOURCE_AUDIENCE="visa:purchase-resource:v1";function Ace(e){let t=(0,wc.record)(e,"purchase request"),r=()=>{throw new wc.AgentOperationContractError("invalid_contract","invalid purchase request")};(t.v!==1||typeof t.action!="string"||!["create","retrieve","cancel"].includes(t.action))&&r();let n=["v","action","requestId","agentId","runtimeId",...t.action==="create"?["requestKey","terms"]:["purchaseId"],...t.action==="retrieve"&&t.include!==void 0?["include"]:[],...t.action==="retrieve"&&t.observation!==void 0?["observation"]:[]];Object.keys(t).sort().join(",")!==n.sort().join(",")&&r(),t.include!==void 0&&t.include!=="card"&&r();let o;if(t.observation!==void 0){t.include!==void 0&&r();let s=(0,wc.record)(t.observation,"purchase observation");(Object.keys(s).sort().join(",")!=="attemptId,kind,termsHash"||!is.PURCHASE_OBSERVATIONS.includes(s.kind)||typeof s.attemptId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(s.attemptId)||typeof s.termsHash!="string"||!/^[A-Za-z0-9_-]{43}$/.test(s.termsHash))&&r(),o=s}for(let s of["requestId","agentId","runtimeId",...t.action==="create"?[]:["purchaseId"]])(typeof t[s]!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t[s]))&&r();let i={v:1,requestId:t.requestId,agentId:t.agentId,runtimeId:t.runtimeId};if(t.action==="create"){let s=(0,Fot.parsePurchaseTerms)(t.terms);return(s.profile!=="exact_card_checkout_v1"||s.alternatives.length!==1||s.alternatives[0].rail!=="card:vic")&&r(),{...i,action:"create",requestKey:(0,wc.bounded)(t.requestKey,"purchase request key",256),terms:s}}return{...i,action:t.action,purchaseId:t.purchaseId,...t.action==="retrieve"&&t.include==="card"?{include:"card"}:{},...o?{observation:o}:{}}}function $ot(e){return(0,Vot.createHash)("sha256").update((0,wc.canonicalJson)({domain:is.PURCHASE_RESOURCE_AUDIENCE,request:Ace(e)})).digest("base64url")}});var hB=_(Ot=>{"use strict";var Kot=Ot&&Ot.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),_B=Ot&&Ot.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Kot(t,e,r)};Object.defineProperty(Ot,"__esModule",{value:!0});Ot.CARD_ADMISSION_RECOVERY_AUDIENCE=void 0;Ot.cardAdmissionRecoveryRequestHash=Wot;Ot.agentOperationIntentHash=mB;Ot.agentExecutionCommitment=gB;Ot.purchaseTermsHash=Yot;Ot.purchaseAlternativeFromOperation=Jot;Ot.x402ResourceCommitment=zot;Ot.agentOperationIdempotencyKey=Pce;Ot.purchaseAttemptIdempotencyKey=Xot;Ot.agentOperationTermsFingerprint=wce;Ot.legacyAgentOperationEnvelopeFingerprint=Rce;Ot.persistedAgentOperationMatchesTerms=Zot;Ot.artifactHash=Qot;Ot.prepareAgentOperationV1=Oce;Ot.finalizeAgentOperationV1=Nce;Ot.createAgentOperationV1=tit;Ot.parseHistoricalAgentOperation=rit;Ot.parseAgentOperation=qT;var Rc=require("node:crypto"),wr=Fl(),Ice=PR();_B(PR(),Ot);_B(vce(),Ot);var wR=zu();_B(zu(),Ot);Ot.CARD_ADMISSION_RECOVERY_AUDIENCE="visa:card-admission-recovery:v1";function Wot(e,t){return(0,Rc.createHash)("sha256").update("visa:card-admission-recovery:v1\0","utf8").update((0,wr.canonicalJson)({original:e,replacement:t}),"utf8").digest("base64url")}function mB(e){return(0,Rc.createHash)("sha256").update((0,wR.agentOperationIntentPreimage)(e)).digest("base64url")}function gB(e){return(0,Rc.createHash)("sha256").update((0,wr.canonicalJson)(e)).digest("base64url")}function Yot(e){return(0,Rc.createHash)("sha256").update((0,Ice.purchaseTermsPreimage)(e)).digest("base64url")}function Jot(e,t=Date.now()){let r=qT(e,t);if(r.effect.kind!=="money")throw new wr.AgentOperationContractError("invalid_effect","purchase requires financial economics");let{amountMicros:n,currency:o,merchant:i}=r.effect,s={amountMicros:n,currency:o,merchant:i},a=(0,wr.record)(r.execution.payload,"purchase native payload"),c=r.rail==="wallet:x402"?["scheme","network","asset","payer","typedData","nonce","keyRef",...a.walletBinding===void 0?[]:["walletBinding"],...a.approvedRequest===void 0&&a.requestHash===void 0?[]:["approvedRequest","requestHash"]]:["mandateId","tokenId","processorIntentId","processorAction","captureMode"];if(Object.keys(a).sort().join(",")!==c.sort().join(","))throw new wr.AgentOperationContractError("invalid_contract","purchase producer has unrepresented native fields");let u;if(r.rail==="wallet:x402"&&r.execution.adapter==="wallet.eip3009"){let d=(0,wr.record)(a.typedData,"wallet typed data"),l=(0,wr.record)(d.message,"wallet message");if(a.scheme!=="exact"||l.value!==n)throw new wr.AgentOperationContractError("invalid_amount","wallet value differs from purchase amount");u={rail:r.rail,economics:s,network:a.network,asset:a.asset,payee:l.to,...a.approvedRequest===void 0&&a.requestHash===void 0?{}:{requestHash:a.requestHash}}}else if(r.rail==="card:vic"&&r.execution.adapter==="card.vic")u={rail:r.rail,economics:s,processorAction:a.processorAction,captureMode:a.captureMode};else throw new wr.AgentOperationContractError("invalid_contract","unsupported purchase producer profile");if(a.requestHash!==void 0&&(0,Rc.createHash)("sha256").update((0,wr.canonicalJson)(a.approvedRequest)).digest("base64url")!==a.requestHash)throw new wr.AgentOperationContractError("invalid_contract","purchase request hash mismatch");return(0,Ice.parsePurchaseTerms)({v:1,profile:a.requestHash===void 0?"url_resource_v1":"approved_x402_request_v1",alternatives:[u]}).alternatives[0]}function zot(e){let t=(0,wr.bounded)(e,"x402 resource",2048);return(0,Rc.createHash)("sha256").update(`visa-x402-resource:v1:${t}`,"utf8").digest("base64url")}function Pce(e){return`economic:${(0,Rc.createHash)("sha256").update((0,wr.canonicalJson)({domain:"visa.agent-operation-idempotency.v1",agentId:e.agentId,economicIntentId:e.economicIntentId})).digest("base64url")}`}function Xot(e){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;for(let r of["agentId","purchaseId","attemptId"])if(typeof e[r]!="string"||!t.test(e[r]))throw new wr.AgentOperationContractError("invalid_contract",`${r} must be a canonical UUID`);if(typeof e.termsHash!="string"||!/^[A-Za-z0-9_-]{43}$/.test(e.termsHash)||Buffer.from(e.termsHash,"base64url").toString("base64url")!==e.termsHash)throw new wr.AgentOperationContractError("invalid_contract","termsHash must be canonical SHA-256");return Pce({agentId:e.agentId,economicIntentId:`purchase:${e.purchaseId}:attempt:${e.attemptId}:terms:${e.termsHash}`})}function wce(e){return(0,Rc.createHash)("sha256").update((0,wr.canonicalJson)({domain:"visa.agent-operation-terms.v1",operationId:e.operationId,idempotencyKey:e.idempotencyKey,agentId:e.agentId,runtimeId:e.runtimeId,rail:e.rail,effect:e.effect,execution:e.execution})).digest("base64url")}function Rce(e){return(0,Rc.createHash)("sha256").update((0,wr.canonicalJson)(e)).digest("base64url")}function Zot(e,t,r){return t===r?!0:wce(e)!==r?!1:t===Rce(e)}function Qot(e){return(0,Rc.createHash)("sha256").update((0,wr.canonicalJson)(e)).digest("base64url")}var eit={kind:"identity_pop",popJwt:"unsigned",keyJkt:Buffer.alloc(32).toString("base64url")};function Oce(e,t=Date.now()){let r={v:wR.AGENT_OPERATION_VERSION,...e,principal:eit,intentHash:Buffer.alloc(32).toString("base64url"),execution:{...e.execution,payloadHash:gB(e.execution.payload)}};r.intentHash=mB(r);let n=qT(r,t),{v:o,principal:i,...s}=n;return s}function Nce(e,t,r=Date.now()){return qT({v:wR.AGENT_OPERATION_VERSION,...e,principal:t},r)}function tit(e,t=Date.now()){let{principal:r,...n}=e;return Nce(Oce(n,t),r,t)}function rit(e){let t=(0,wr.record)(e,"historical operation");if(typeof t.createdAt!="string")throw new wr.AgentOperationContractError("invalid_window","historical operation creation time is missing");return qT(e,Date.parse(t.createdAt))}function qT(e,t=Date.now()){let r=(0,wR.parseAgentOperationStructure)(e,t);if(gB(r.execution.payload)!==r.execution.payloadHash)throw new wr.AgentOperationContractError("commitment_mismatch","execution payload does not match its commitment");if(mB(r)!==r.intentHash)throw new wr.AgentOperationContractError("intent_mismatch","intentHash does not bind the exact operation effect and execution commitment");return r}});var $h=_((IUr,oit)=>{oit.exports={name:"@visa/cli",version:"5.0.0-rc.401",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","visa-runtime-converge":"./dist/managed-runtime/resolve-and-update.mjs"},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",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:packed":"node scripts/packed-cli-smoke.mjs","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","coinbase:onramp":"pnpm exec tsx tests/e2e/coinbase-onramp-harness/run.ts","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/ext-apps":"1.7.5","@modelcontextprotocol/server":"2.0.0","@ucp-js/sdk":"0.4.4",commander:"^12.1.0",punycode:"^2.3.1",toml:"^4.3.0",yaml:"^2.9.0",zod:"^3.25.76"},devDependencies:{"@types/express":"^5.0.0","@types/jest":"^30.0.0","@types/node":"^26.1.0","@typescript-eslint/eslint-plugin":"^8.68.0","@typescript-eslint/parser":"^8.68.0","@visa-cli/tools":"workspace:*","@visa/agent-mail":"workspace:*","@visa/crypto":"workspace:*","@visa/financial-core":"workspace:*","@visa/identity":"workspace:*","@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa/shared":"workspace:*","@visa/wallet":"workspace:*","@visa/wallet-tools":"workspace:*",esbuild:"^0.28.1",eslint:"^10.0.2",express:"^4.21.0",jest:"^30.3.0",mppx:"^0.11.0",prettier:"^3.9.6","ts-jest":"^29.4.12",typescript:"^5.7.0",viem:"^2.56.0"},engines:{node:">=20.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","server.json","README.md","native/bin/*/visa-runtime-signer*"]}});async function Nue(e,t){let r=t?.timeoutMs??3e4,n=new AbortController,o=setTimeout(()=>n.abort(),r);try{let{timeoutMs:i,...s}=t??{};return await fetch(e,{...s,signal:n.signal})}finally{clearTimeout(o)}}var Cue=R(()=>{"use strict"});var GR,JT,$R,KR,WR,xue=R(()=>{"use strict";GR=class extends Error{code="ATTESTATION_KEY_DRIFT";kind="attestation";nextAction="visa disconnect --all";fix="Run `visa disconnect --all` to clear the stale device credential, then `visa connect` to enroll again.";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}},JT=class extends Error{code="session_required";kind="session";nextAction="visa connect";fix="visa connect";status;constructor(t,r){super(t),this.name="SessionRequiredError",this.status=r}},$R=class extends Error{code="server_unavailable";kind="server";nextAction=void 0;fix;status;retryable;constructor(t,r=503,n=!0){super(t),this.name="ServerUnavailableError",this.status=r,this.retryable=n,this.fix=n?"Wait a moment and retry. If the outage persists check https://visacli.sh for status.":"Do not retry this request automatically; inspect the server error and reconcile the existing attempt."}},KR=class extends Error{code="surface_disabled";kind="server";nextAction=void 0;fix="This surface is disabled or not configured on the server (kill switch or missing config). Escalate to a human \u2014 retrying will not help.";status;disabledSurface;flag;correlationId;constructor(t,r={}){super(t),this.name="SurfaceDisabledError",this.status=r.status??503,this.disabledSurface=r.disabledSurface,this.flag=r.flag,this.correlationId=r.correlationId}},WR=class extends Error{constructor(r,n){super(r);this.retryAfterSeconds=n;this.name="RateLimitError",this.nextAction=void 0,this.fix=`Wait ${n}s before retrying.`}retryAfterSeconds;code="rate_limited";kind="rate_limit";fix;status=429;nextAction=void 0}});function ast(){return Object.fromEntries(ist.map(e=>[e,sst]))}function RB(e){if(!e||typeof e!="object")return null;let t=e,n=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return typeof n=="string"&&n.length>0?n:null}function YR(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=RB(e);return r&&Mue[r]?Mue[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 ist,sst,Mue,OB=R(()=>{"use strict";ist=["UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_UNTRUSTED"],sst="This machine does not trust the certificate offered for the Visa CLI server, so the request never left it. The server is not down, and neither retrying nor signing in again can help. A network that inspects TLS traffic does this: point Node at its root certificate with NODE_EXTRA_CA_CERTS=/path/to/root.pem, or use a network that does not inspect. Do not disable certificate verification.";Mue={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.",...ast(),ERR_TLS_CERT_ALTNAME_INVALID:"The certificate offered for the Visa CLI server is for a different hostname. Check the auth.serverUrl setting. Do not disable certificate verification.",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 Lue(){return`Run ${cst} or call ${ust}, open the printed URL, enter the code at ${dst}, approve the device and its limits, then pay with the pay tool. Do not retry the retired command; nothing was signed, paired, or paid.`}var cst,ust,dst,YUr,JUr,zUr,Due=R(()=>{"use strict";cst="visa connect",ust="agent_enroll",dst="/agent/enroll/protected-agent",YUr=Object.freeze(["setup_start","setup_status","setup_resume","setup_cancel","setup_agent","enroll_agent","agent_pairing_cancel","agent_handoff_claim","agent_connect","agent_connect_cancel","agent_connect_poll","feedback"]),JUr=Object.freeze(["create","verify","enroll-claim","pair","claim","pairing-resume","cancel","handoff-claim","connect","grant-wallet","grant-card","grant-activate","grant-claim","grants","grant-cancel","grant-batch"]),zUr=Object.freeze(["setup","agent","wallet","find","inspect","receipt","connections","keys","security","checkout","mandate","logout","capabilities","feedback","status","pay","purchase","limits","fund","activity"])});var zR,NB,kue,JR,Uue=R(()=>{"use strict";zR=j(require("fs")),NB=j(require("path")),kue=j(require("os")),JR=class{static ensureConfigDir(){let t=this.getConfigDir();zR.existsSync(t)||zR.mkdirSync(t,{recursive:!0,mode:448})}static getConfigDir(){let t=process.env.VISA_CLI_HOME;return typeof t=="string"&&t.trim().length>0?NB.join(t,".visa-mcp"):NB.join(kue.homedir(),".visa-mcp")}}});function fst(){Ii.existsSync(xB)||Ii.mkdirSync(xB,{recursive:!0,mode:448})}function pst(){if(!CB){if(fst(),Ii.existsSync(zT)&&Ii.statSync(zT).size>lst){let t=zT+".1";Ii.existsSync(t)&&Ii.unlinkSync(t),Ii.renameSync(zT,t)}CB=Ii.createWriteStream(zT,{flags:"a"})}return CB}function _st(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"}function XR(e,...t){let r=new Date().toISOString(),n=t.map(i=>typeof i=="string"?i:JSON.stringify(i,null,2)).join(" "),o=`[${r}] [${e}] ${n}
3
+ `),o=[],i=null,s=null;for(let a of n){a.includes("keychain:")&&(i===t&&s&&!o.includes(s)&&o.push(s),i=null,s=null);let c=a.match(/"svce"<blob>="([^"]+)"/);c&&(i=c[1]);let u=a.match(/"acct"<blob>="([^"]+)"/);u&&(s=u[1])}return i===t&&s&&!o.includes(s)&&o.push(s),o}catch{return[]}}static async listStoredCredentials(t={}){let r=t.env??process.env,n=[];if(process.platform==="darwin"&&await xa())for(let a of["visa-cli","visa-mcp"]){let c=await this.listKeychainItems(a);for(let u of c)n.push({service:a,account:u,backend:"keychain"})}let o=bc(r);Rn.existsSync(o)&&n.push({service:"visa-cli",account:Yu,backend:"file",path:o});let i=Hl(r);for(let a of i){let c=ql(a,r);Rn.existsSync(c)&&n.push({service:"visa-cli",account:ER(a),backend:"file",path:c})}let s=Hh(r);return Rn.existsSync(s)&&n.push({service:"visa-cli",account:Wu,backend:"file",path:s}),n}static async purgeAll(t={}){let r=t.env??process.env,n=[];if(process.platform==="darwin"&&await xa())for(let a of["visa-cli","visa-mcp"]){let c=await this.listKeychainItems(a);for(let u of c)try{await bi("security",["delete-generic-password","-s",a,"-a",u],{timeout:5e3}),n.push({service:a,account:u,backend:"keychain"})}catch{}}let o=bc(r);if(Rn.existsSync(o))try{Rn.unlinkSync(o),n.push({service:"visa-cli",account:Yu,backend:"file",path:o})}catch{}let i=Hh(r);if(Rn.existsSync(i))try{Rn.unlinkSync(i),n.push({service:"visa-cli",account:Wu,backend:"file",path:i})}catch{}let s=Hl(r);for(let a of s){let c=ql(a,r);if(Rn.existsSync(c))try{Rn.unlinkSync(c),n.push({service:"visa-cli",account:ER(a),backend:"file",path:c})}catch{}}try{ece(r)}catch{}return await oot(s),n}static async clearAll(t=process.env){for(let r of Hl(t))await this.deleteProfileSessionToken(r,t);await this.deleteLegacySessionToken(t),await this.deleteRcAccessToken(t)}}});function sce(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let{approvalId:t,url:r,expiresAt:n}=e;if(typeof t!="string"||!got.test(t)||typeof n!="string"||!Number.isFinite(Date.parse(n))||typeof r!="string")return null;let o;try{o=new URL(r)}catch{return null}return o.protocol!=="https:"&&o.protocol!=="http:"||o.username||o.password||o.search||o.hash||o.pathname!==`/agent/enroll/approvals/wallet/${t}`?null:{approvalId:t,url:o.toString(),expiresAt:new Date(n).toISOString()}}var got,ace=R(()=>{"use strict";got=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i});function jT(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(aB,e)}function hot(e){return e.remedy?{remedyPath:e.remedy.path,remedyLabel:e.remedy.label}:{}}function bo(e,t={}){let r=aB[e],n=t.fix!==void 0?t.fix:r.fix;if(r.kind==="platform"&&r.escalation!=="awaiting_human"&&n!==null)throw new Error(`agent-contract: ${r.escalation} code "${e}" cannot carry a fix \u2014 no command resolves it`);return{code:e,kind:r.kind,fix:n,nextAction:t.nextAction??r.nextAction,...t.agentId?{agentId:t.agentId}:{},...hot(r)}}function Ac(e){if(e instanceof Xt)return e.diagnostic;if(e&&typeof e=="object"){let t=e,r=typeof t.agentId=="string"?t.agentId:t.details&&typeof t.details=="object"&&typeof t.details.agentId=="string"?t.details.agentId:void 0,n=r?{agentId:r}:{},o=e.underlying;if(o instanceof Xt)return o.diagnostic;let i=o?.code;if(i==="agent_paused"||i==="agent_revoked"||i==="device_key_replaced"||i==="grant_expired")return bo(i,n);let s=e.code??e.errorCode;if(jT(s))return bo(s,n);if(typeof s=="string"){let c=s.toLowerCase();if(jT(c))return bo(c,n)}let a=e.message;return jT(a)?bo(a,n):bo("unspecified_error",n)}return bo("unspecified_error")}function cce(e){if(!(e instanceof Xt)||!e.details)return;let t=e.details,r={};if(Number.isInteger(t.upstreamStatus)&&Number(t.upstreamStatus)>=100&&Number(t.upstreamStatus)<=599&&(r.upstreamStatus=t.upstreamStatus),jT(t.reason)&&t.reason===e.code&&(r.reason=t.reason),e.code==="terms_conflict"&&typeof t.purchaseId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t.purchaseId)&&(r.purchaseId=t.purchaseId),e.code==="purchase_transport_uncertain"&&(t.transportReason==="timeout"||t.transportReason==="network"||t.transportReason==="response")&&(r.transportReason=t.transportReason),e.code==="wallet_owner_approval_required"){let n=sce(t.approval);n&&(r.approval=n)}return Object.keys(r).length?r:void 0}var aB,sUr,Xt,vc=R(()=>{"use strict";ace();aB={update_required:{kind:"caller",fix:"npm install -g @visa/cli@rc",nextAction:"Upgrade Visa CLI to the minimum compatible version or newer, then retry the command."},session_required:{kind:"caller",fix:"agent_enroll",nextAction:"Run visa connect (shell) or call agent_enroll (MCP) and complete the browser sign-in. Both resume where they left off. Retry the original command after that."},identity_required:{kind:"caller",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Call agent_enroll or run visa connect, open the printed URL, enter the code at /agent/enroll/protected-agent, and have the owner approve the device and its limits. Both entrances use the same protected enrollment implementation."},legacy_door_removed:{kind:"caller",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Call agent_enroll or run visa connect, open the printed URL, enter the code at /agent/enroll/protected-agent, approve the device and its limits, then pay with the pay tool. Do not retry the retired command; nothing was signed, paired, or paid."},agent_selection_required:{kind:"caller",fix:null,nextAction:"Retry the command with one exact agent id from the executable choices in the error."},invalid_argument:{kind:"caller",fix:null,nextAction:"Correct the invalid argument named in the error, then retry the command once. Do not escalate this as a platform incident."},rate_limited:{kind:"caller",fix:"sleep <retry-after-seconds>",nextAction:"Wait the exact Retry-After duration named in the error, then retry the same request once. Do not retry sooner or switch agents to bypass the limit."},activity_entry_not_found:{kind:"caller",fix:"history",nextAction:"Call history for the same agent and find the entry by its exact id in that list, or read the visa://receipt/<id> resource."},wallet_network_mismatch:{kind:"caller",fix:"discover",nextAction:"The unpaid challenge offered no Tempo USDC.e payment this wallet can make. Nothing was reserved, signed, or paid. Choose a service that accepts Tempo; do not retry the same challenge unchanged."},agent_operations_cli_upgrade_required:{kind:"caller",fix:null,nextAction:"Use a reviewed CLI build at or above the minimum version named by the server, restart the agent session, and retry once. The payment was not sent."},agent_operation_forbidden:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This owner, agent, runtime, rail, or rollout state is not admitted to the universal payment route. Ask the owner to inspect the selected agent; do not retry through a legacy path."},runtime_context_not_found:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The server cannot find a current managed runtime contract for this exact agent and device. Ask the owner to inspect or renew that runtime before retrying."},product_policy_not_active:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet setup did not install its server-owned spend policy. Resume the owner-approved wallet setup for this agent; do not retry the payment unchanged."},runtime_spend_session_not_active:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet setup has no active runtime spend session. Resume the owner-approved wallet setup for this agent; do not retry the payment unchanged."},runtime_spend_attenuation_not_active:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet runtime spend limits are not bound to the active owner policy. Resume the owner-approved wallet setup for this agent; do not retry the payment unchanged."},runtime_revoked:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This exact runtime has been revoked. Do not reuse it; ask the owner to certify a new runtime for the same agent if access should continue.",remedy:{path:"/agent/enroll/agents",label:"Check the agent in the Console"}},certified_runtime_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This payment requires an owner-certified runtime. Ask the owner to approve the wallet runtime certificate, then retry once."},runtime_certificate_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet runtime certificate is invalid, expired, or no longer current. Ask the owner to renew it; do not retry unchanged."},runtime_delegation_missing:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This runtime has no active owner delegation for short signing leases. Ask the owner to finish secure wallet setup before retrying.",remedy:{path:"/agent/enroll/agents",label:"Finish the agent's wallet setup"}},runtime_delegation_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This runtime owner delegation has expired. Ask the owner to renew secure wallet authority before retrying.",remedy:{path:"/agent/enroll/agents",label:"Renew the agent's approval"}},runtime_authority_unavailable:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"The server could not verify runtime authority. Surface the outage to an operator and do not retry or fall back until authority health is restored."},universal_required_managed_only:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The universal route requires a fully managed TVC wallet for this agent. Ask the owner to finish managed wallet setup before retrying."},wallet_authority_cli_upgrade_required:{kind:"caller",fix:null,nextAction:"Upgrade the CLI to the minimum version named by the server, restart this agent session, and retry once. Nothing was signed or paid."},tap_signature_required:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"Escalate to a human. A TAP identity signer is available on this runtime but could not sign, so the paid request was not sent unsigned and nothing was paid. Do not retry the payment unsigned. Probe remains unsigned."},wallet_owner_approval_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was paid. Show the owner the approval link in details.approval.url, bare, and ask them to approve this exact payment before details.approval.expiresAt. Then call pay again with the SAME target, max, body and economicIntentId: until they sign, the retry returns this same refusal (safe to repeat every 15-30 seconds); once they sign, the identical authorization resumes. Do not change the payment or start a new one. If the approval expires first, the retry says so and nothing is paid: stop then."},wallet_owner_approval_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was paid. The owner's approval for this exact payment can no longer be used (it expired before the payment completed). Stop: do not call pay again with this economicIntentId, it will keep answering this. Tell the owner; only if they still want it, start a NEW payment with a NEW economicIntentId, which asks them to approve again."},attestation_key_drift:{kind:"caller",fix:"visa connect",nextAction:"This device holds a credential the server does not recognize (machine swap, keychain wipe, restored backup). Clear the stale local credential, enroll a fresh protected agent with visa connect, then retry."},rc_access_required:{kind:"platform",escalation:"awaiting_human",fix:"export VISA_RC_CODE=<access code>",nextAction:"This is a release-candidate build restricted to Visa employees. Set VISA_RC_CODE in this process, then retry. Ask your team lead or Visa Crypto Labs for the code \u2014 do not guess it."},early_access_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Escalate to a human: an admin must enable this tool for the account. Do not retry until they confirm."},capability_attach_pending_approval:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner to finish the approval already open in their browser at /agent/enroll/protected-agent \u2014 the device and its limits are approved there. Do not start a second ceremony; wait for the owner, then retry the original command."},card_checkout_not_on_pay:{kind:"caller",fix:"purchase_create",nextAction:"Nothing was probed further, created or charged. This URL answered no payment challenge, so it is an ordinary merchant checkout and `pay` cannot do it: `pay` spends from the agent wallet only. Card checkouts are the `purchase` resource (`purchase_create`, then `purchase_retrieve`), where Visa issues the credential and YOUR runtime drives the browser. Do not retry this target on `pay`."},card_draw_not_live:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Escalate to a human now. The card-draw surface is not live on this build (it is opt-in server-side), so no local configuration change makes this command work. Do not retry."},checkout_review_refused:{kind:"caller",fix:null,nextAction:"Nothing was charged. This checkout needs a supported card-field adapter. Choose another supported checkout, or give the merchant and adapter details to the product team; do not retry unchanged."},checkout_action_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was charged and no payment credential was requested. Ask the human to complete the named verification step, then retry the review once."},checkout_mandate_blocked:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was charged. Ask the owner to approve a mandate that covers the exact merchant, amount, and currency, then start a new review. Do not widen authority yourself."},card_mandate_activation_uncertain:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The owner approved the budget but the card network did not confirm its activation. No budget is usable and nothing was charged. Do not start another approval while this one is valid: ask the owner to review the budget in the Visa Console and, once the approval has expired or been revoked there, approve a fresh budget. Quote the request id when reporting it."},ucp_platform_profile_unavailable:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Do not retry this checkout. Escalate to the Visa deployment owner: the exact UCP platform profile advertised to merchants must serve a valid HTTPS JSON profile without redirects before checkout handoff can work."},wallet_capability_unavailable:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Escalate to a human now. The wallet capability is not served by this build. Do not retry."},surface_disabled:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Escalate to a human now. The server reports this surface disabled or not configured (kill switch or missing server config \u2014 see the flag and correlation_id in the error). No retry or local change resolves it."},wallet_grant_required:{kind:"platform",escalation:"awaiting_human",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"The Turnkey wallet is delegated by the human owner, not self-minted here. Call agent_enroll or ask the owner to run visa connect and approve the device and its limits at /agent/enroll/protected-agent, then retry.",remedy:{path:"/agent/enroll/agents",label:"Approve this agent in the Console"}},wallet_credential_required:{kind:"platform",escalation:"awaiting_human",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Call agent_enroll or ask the owner to run visa connect for the intended agent and approve the device and its limits at /agent/enroll/protected-agent, then retry. Identity alone does not grant spend authority.",remedy:{path:"/agent/enroll/agents",label:"Approve this agent in the Console"}},grant_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was reserved, signed, or charged. The owner's spending approval for this agent has expired. Ask the owner to renew it in the Visa Console at /agent/enroll/limits?agent=<agent-id> (the same limits are pre-filled), then retry the same payment once. Do not create a new agent or reconnect.",remedy:{path:"/agent/enroll/limits",label:"Renew the agent's approval"}},managed_limits_owner_controlled:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. Managed wallet limits are owner-set on the server. Read them with get_status, then ask the owner to change them in the Visa Console at /agent/enroll/limits?agent=<agent-id>.",remedy:{path:"/agent/enroll/limits",label:"Change the agent's limits"}},agent_paused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner to resume this exact agent in the Visa Console (Agents). Retry only after get_status reports it ready; do not create a replacement credential while the agent is paused.",remedy:{path:"/agent/enroll/agents",label:"Resume the agent in the Console"}},owner_declined:{kind:"caller",fix:null,nextAction:"The owner declined this payment; don't retry it. Nothing was charged. Tell the owner and move on; only if they ask for it again, start a new payment (a new economicIntentId or a new purchase), which asks them again."},owner_withdrawal_pending:{kind:"caller",fix:null,nextAction:"Nothing was signed or paid. The owner is withdrawing from this wallet and that transfer is still settling (at most about ten minutes). Retry the same payment in a minute; the budget is unchanged."},kill_switch_engaged:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Visa has paused payments on this rail (card, wallet or Tempo), or could not confirm they are open. Nothing was paid. Tell the owner, and try the same purchase again later; do not loop, switch rails to get around it, or create a replacement."},agent_revoked:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This agent is permanently revoked. Do not retry or reuse its credentials; ask the owner whether to pair a new agent identity.",remedy:{path:"/agent/enroll/agents",label:"Connect a new agent in the Console"}},device_key_replaced:{kind:"platform",escalation:"awaiting_human",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Nothing was paid. This computer's keys for the agent were replaced on another computer, which now is the agent. Do not retry here. To use this computer too, call agent_enroll (or have the owner run visa connect) and approve it as a new agent."},agent_stale:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The server cannot prove this agent is currently usable. Ask the owner to inspect its lifecycle and reauthorize it before retrying.",remedy:{path:"/agent/enroll/agents",label:"Check the agent in the Console"}},agent_lifecycle_unknown:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"The lifecycle state is unknown. Surface the full preflight result to a human and do not retry a money operation until the server reports active."},wallet_delivery_required:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"The approved wallet runtime was not delivered completely. Ask the owner to re-run visa connect and re-approve the device and its limits before paying; do not self-mint a mainnet wallet.",remedy:{path:"/agent/enroll/agents",label:"Reconnect this agent in the Console"}},wallet_authority_revoked:{kind:"caller",fix:"get_status",nextAction:"This wallet is preserved for recovery only. Inspect its balance and receipts with get_status or history; do not retry a payment or policy change until the owner approves a new wallet grant."},wallet_authority_replacement_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This compatibility error came from an older single-wallet runtime. Upgrade the CLI and re-run the wallet grant; current builds isolate wallet authority per agent."},wallet_policy_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed. Ask the owner to set per-purchase and daily spend caps in the Visa Console at /agent/enroll/limits?agent=<agent-id>, then retry once. Caps are enforced before anything is signed.",remedy:{path:"/agent/enroll/limits",label:"Set spending caps in the Console"}},wallet_funding_required:{kind:"caller",fix:"get_status",nextAction:"Ask the owner to add USDC.e on Tempo to their wallet before paying: the Visa Console shows the wallet's address and balance under Payments.",remedy:{path:"/agent/enroll/payments",label:"Add funds to the wallet"}},wallet_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner to finish wallet setup in the Visa console (their account has no usable wallet yet), then re-run the grant. Do not keep polling: the ceremony cannot complete until the wallet exists.",remedy:{path:"/agent/enroll/payments",label:"Finish wallet setup"}},checkout_agent_access_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Escalate to a human: this account is not enabled for agent checkout, so grant ceremonies are refused server-side. Do not retry until an admin confirms the account has access."},unknown_tool:{kind:"caller",fix:null,nextAction:"Call tools/list and dispatch one of the served names. The tool you asked for is not registered on this runtime."},handoff_not_found:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The Console claim code was not found or was mistyped. Ask the human for a fresh claim code from the Visa Console; do not retry this code."},handoff_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This Console claim code has expired. Ask the human to create a new setup code in the Visa Console."},handoff_already_redeemed:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This Console claim code has already been redeemed. Ask the human to create a new setup code in the Visa Console."},no_paired_agent:{kind:"caller",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"No protected agent on this device. Call agent_enroll or run visa connect and complete the owner ceremony at /agent/enroll/protected-agent first."},agent_id_required:{kind:"caller",fix:null,nextAction:"Pass the agentId to identify which agent ceremony to operate on."},already_terminal:{kind:"caller",fix:null,nextAction:"This ceremony is already terminal or cancelled. No further action needed."},purchase_transport_uncertain:{kind:"caller",fix:null,nextAction:"Wait briefly, then repeat the identical Visa purchase call with the same arguments, request key and purchase ID. The original request may have succeeded; its journal recovers the same attempt. Do not cancel, create a replacement or submit Pay at the merchant again. Escalate repeated transport failures."},purchase_refused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The authority refused this purchase request. Use the recorded upstream status and error to resolve the refusal before trying again. Preserve the original purchase and request key; a refusal is not permission to mint a replacement or repeat merchant payment."},recovery_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Inspect the original purchase and checkout with the owner or support. Preserve the purchase ID and request key. Do not create a replacement, release uncertain liability or submit Pay again."},card_recovery_unconfigured:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Card recovery is not configured. Ask support to restore the protected recovery worker before retrying the same Visa request. Preserve the purchase ID; do not create another purchase or click merchant Pay again."},card_recovery_original_not_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The original credential attempt is still live. Retrieve the same purchase without include:card and follow its continuation; do not force recovery, create another purchase or click merchant Pay again."},card_recovery_liability_present:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The original attempt still has liability. Ask support to reconcile that attempt and inspect the existing checkout. Do not release funds, issue replacement credentials or click merchant Pay again."},card_recovery_issuance_conflict:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Recovery found conflicting issuance evidence. Stop and ask support to reconcile the original purchase and attempt. Do not create another purchase or click merchant Pay again."},card_recovery_proof_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The recovery proof could not be verified. Ask support to repair recovery for the existing device and purchase; do not replay the invalid proof, replace the identity or click merchant Pay again."},card_purchase_quarantined:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This purchase is quarantined for reconciliation. Ask support to inspect its original attempt and the existing checkout. Do not create another purchase, release its liability or click merchant Pay again."},card_credential_not_available:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Credentials are not available for this purchase state. Retrieve the same purchase without include:card and follow its continuation. Do not recreate the purchase or click merchant Pay again."},purchase_submission_observed:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Submission was already reported for this purchase. Inspect the existing merchant checkout and report its current state on the same purchase. Do not request replacement credentials or click merchant Pay again."},protected_card_request_invalid:{kind:"caller",fix:null,nextAction:"The card executor refused the saved delivery request, usually because its admission has expired. Retrieve the same purchase and follow its continuation; if it reads expired, run purchase create again with the same request file. Do not create a replacement purchase by hand."},protected_card_delivery_conflict:{kind:"caller",fix:null,nextAction:"The saved delivery request differs from the one already in progress for this attempt. Retrieve the same purchase and follow its continuation; do not alter or replay edited request bytes."},protected_card_authority_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The card authority did not answer the executor. Nothing was issued. Wait a moment and retrieve the same purchase; recovery continues server-side."},purchase_cancelled:{kind:"caller",fix:null,nextAction:"This purchase was cancelled; it accepts no new credential. Create a new purchase for a fresh checkout if the buyer still wants it. Do not click merchant Pay."},card_intent_unobserved:{kind:"caller",fix:null,nextAction:"The owner's card allowance for this agent is not active yet. Follow next.open_url so the owner finishes card setup, then retry the same checkout."},card_intent_mandate_exists:{kind:"caller",fix:null,nextAction:"The owner's current approval already has a card allowance in progress. Wait for it to finish (or ask the owner to check the limits page), then retry the same checkout."},card_intent_conflict:{kind:"caller",fix:null,nextAction:"A different card allowance request already exists under this id. Retrieve current status instead of resending edited request bytes."},card_vic_provider_refused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The provider refused credential issuance. Ask the owner or support to inspect the original purchase and provider refusal before retrying; an HTTP error does not prove its reservation was released. Do not create a replacement purchase or click merchant Pay again."},terms_conflict:{kind:"caller",fix:null,nextAction:"The request conflicts with the existing checkout commitment or quote bound. Retrieve the original purchase and compare the exact final terms. Do not change the request key or checkout ID to bypass the conflict; resolve it under the checkout replacement rules."},card_checkout_expired:{kind:"caller",fix:null,nextAction:"The exact checkout quote expired. Inspect the original purchase before obtaining a new final quote. Do not reuse stale terms or bypass checkout replacement rules by changing the request key or checkout ID."},card_mandate_expired:{kind:"caller",fix:null,nextAction:"The owner's card allowance for this agent lapsed (the provider limits each one to 7 days) while the approval itself is still valid; Visa is issuing a replacement under that approval. Wait afterMs and run the same purchase create again. Do not involve the owner or create a replacement purchase."},card_allowance_preparing:{kind:"caller",fix:null,nextAction:"Visa is issuing this agent's card allowance under the owner's existing approval. Wait afterMs and run the same purchase create again; the wait loop does this for you. Do not involve the owner or create a replacement purchase."},protected_card_instrument_inactive:{kind:"platform",escalation:"awaiting_human",fix:"purchase_create",nextAction:"This agent's card connection points at a saved-card record the owner has since replaced (re-verifying the card) or removed. Call purchase_create again with the saved resumeId: it returns one open_url that reconnects this agent to the owner's current saved card. The owner opens it once, then the same saved purchase resumes. Do not ask for card details, create another agent or purchase, or click merchant Pay again."},card_reservation_expired:{kind:"caller",fix:null,nextAction:"Retrieve the same purchase to resolve its expired reservation. Follow its current continuation; do not replay stale admission bytes or create a replacement to hide an unresolved attempt."},card_merchant_country_mismatch:{kind:"caller",fix:null,nextAction:"Use the actual merchant country consistently in the signed checkout terms and settlement envelope. Preserve the existing purchase commitment; do not change keys to bypass a terms conflict."},protected_grant_proof_mismatch:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner or support to verify the current grant and runtime proof for this existing agent. Do not retry an unchanged invalid proof or create replacement authority."},purchase_resume_invalid:{kind:"caller",fix:null,nextAction:"Use the exact saved purchase resume reference by itself; do not combine it with a new request. Preserve the original purchase and merchant checkout."},purchase_draft_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The saved purchase request is damaged or changed. Stop and ask support to recover the original draft; do not overwrite it, invent new terms or click merchant Pay again."},purchase_draft_not_found:{kind:"caller",fix:null,nextAction:"Use the original device and exact saved resume reference. Locate the existing draft before continuing; do not recreate the request or click merchant Pay again."},purchase_draft_agent_invalid:{kind:"caller",fix:null,nextAction:"Select the existing protected agent by its exact UUID and resume the original draft. Do not create a replacement identity or purchase."},purchase_draft_agent_mismatch:{kind:"caller",fix:null,nextAction:"Resume this draft with the same protected agent it already selected. Do not switch agents, replace the draft or click merchant Pay again."},purchase_draft_owner_mismatch:{kind:"caller",fix:null,nextAction:"Sign in as the owner who started this draft on the original device, then resume that same draft. Do not transfer it to another owner or create a replacement purchase."},purchase_draft_owner_required:{kind:"caller",fix:null,nextAction:"Complete the returned owner sign-in step, then resume the same saved draft. Do not start another identity enrollment or purchase."},purchase_draft_busy:{kind:"caller",fix:null,nextAction:"Wait for the current Visa purchase call to finish, then repeat the same resume reference. Do not run concurrent purchase calls, create a replacement or click merchant Pay again."},purchase_not_found:{kind:"caller",fix:null,nextAction:"Check the original purchase ID and selected agent. Recover the existing purchase record; do not mint a replacement merely because a read could not find it."},invalid_contract:{kind:"caller",fix:null,nextAction:"Correct the request using the declared tool schema, then retry only with valid input. Never fabricate facts or change existing payment identifiers to bypass their commitment."},invalid_amount:{kind:"caller",fix:null,nextAction:"Supply a positive canonical amount in the units required by the selected tool. Follow its total and precision constraints; never change identifiers to bypass an existing payment commitment."},invalid_currency:{kind:"caller",fix:null,nextAction:"Use the currency required by the selected payment profile. Do not infer merchant country from currency."},unsupported_version:{kind:"caller",fix:null,nextAction:"Use a supported protocol version and profile. Check the current tool schema or update Visa CLI, then retry the same logical operation without bypassing its existing commitment."},native_runtime_signer_not_installed:{kind:"platform",escalation:"awaiting_human",fix:"npm i -g @visa/cli@rc",nextAction:"The Visa CLI install on this machine has no native signer for this platform, so no wallet key can be proven. Ask the owner to reinstall Visa CLI; do not retry."},native_runtime_signer_not_executable:{kind:"platform",escalation:"awaiting_human",fix:"npm i -g @visa/cli@rc",nextAction:"The native signer is present but this machine will not run it, and Visa CLI could not repair its file mode. Ask the owner to reinstall Visa CLI, or to run chmod 755 on the path in the error; do not retry."},native_runtime_platform_unsupported:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Visa CLI ships no native signer for this operating system and CPU, so wallet keys cannot be held here. Surface this to the owner; do not retry."},native_runtime_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The native signer could not be started. The error names why (EACCES is the executable bit; ENOENT is a missing binary). Surface it to the owner; do not retry."},native_runtime_closed:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The native signer exited before answering. The error carries its exit code and its last output. Surface it to the owner; do not retry."},native_runtime_response_invalid:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"The native signer answered with something Visa CLI could not read, which usually means the CLI and its signer are from different builds. Ask the owner to reinstall Visa CLI; do not retry."},keychain_not_found:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This Mac user has no default keychain, so no agent key was stored or read and no system dialog was opened. Ask the owner to restore or create their login keychain in Keychain Access, then retry. On a server with no keychain, the owner can choose file custody explicitly with VISA_RUNTIME_CUSTODY_PROFILE=headless."},custody_store_unreadable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The agent key store on this machine could not be read (its permissions or the disk), so nothing was signed and nothing was changed. Ask the owner to restore read access to Visa CLI's agent-keys directory, then retry. Do not re-enroll: the key may still be there."},keychain_locked_or_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The macOS login keychain is locked or refused, so this agent's key could not be read. Nothing was signed or sent, and no new key was made. Ask the owner to unlock the login keychain (log in to the Mac, or open Keychain Access), then retry once."},custody_unavailable:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"This agent's key is not on this computer: it was set up by an older Visa CLI or on another computer. Nothing was signed or sent. Ask the owner to update Visa CLI (npm i -g @visa/cli@rc) and run visa connect on this computer, then approve the new agent in the browser."},protected_card_enrollment_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The owner must verify a payment card once for this account. Ask the owner to sign in at /agent/enroll and complete the Verify your card step, then retry the original command once.",remedy:{path:"/agent/enroll?enrollCard=1",label:"Verify a payment card"}},financial_rollout_approval_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The owner account is not approved for protected payments yet. Surface this to the owner; do not retry until they confirm access was granted."},key_purpose_mismatch:{kind:"platform",escalation:"awaiting_human",fix:"npm i -g @visa/cli@rc",nextAction:"The native signer refused to sign because this device key is bound to a different purpose (wallet, card, or identity) than the operation asked of it. Nothing was signed or sent. This is a Visa CLI defect or a CLI/signer version mismatch, not something a retry changes: ask the owner to update Visa CLI, then retry once. If it persists on the latest build, report it."},legacy_custody_profile_required:{kind:"platform",escalation:"awaiting_human",fix:"npm i -g @visa/cli@rc",nextAction:"The native signer refused to sign a wallet or card proof with an identity key. Nothing was signed or sent. This is a Visa CLI defect or a CLI/signer version mismatch: ask the owner to update Visa CLI, then retry once. If it persists on the latest build, report it."},identity_binding_mismatch:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The native signer refused because the request named a different agent or runtime than the device key is bound to. Nothing was signed or sent. Read get_status, then retry once with that agent's id; if it repeats, surface it to the owner rather than retrying."},proof_time_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The native signer refused a proof whose timestamp is outside its one-minute window, which means this machine's clock is wrong. Nothing was signed or sent. Ask the owner to sync the system clock, then retry once."},secret_service_locked_or_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The Linux Secret Service (the desktop keyring) is locked or refused Visa CLI, so the agent's key could not be read. Ask the owner to unlock the login keyring; on a machine without a desktop session (SSH, WSL, a server), set VISA_RUNTIME_CUSTODY_PROFILE=headless and run visa connect instead. Do not retry on your own."},secret_service_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"No Linux Secret Service is reachable (no desktop session: SSH, WSL, a container, or a server), so the agent's key could not be read. On such a machine, set VISA_RUNTIME_CUSTODY_PROFILE=headless (an owner-only key file) and run visa connect; in a desktop session, unlock the keyring (gnome-keyring or KWallet). Do not retry on your own."},secret_service_timeout:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The Linux Secret Service did not answer Visa CLI in time, usually because an unlock prompt is waiting. Ask the owner to answer or unlock the keyring, then retry once."},dpapi_locked_or_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Windows data protection (DPAPI) refused to open the agent key, usually because this is a different Windows user or profile than the one that set the agent up. Ask the owner to run Visa CLI as that user; do not retry on your own."},enrollment_device_approval_pending:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"This computer's agent setup is waiting for the owner's device approval, and starting another would strand it. Nothing was changed. Run visa connect (without --restart) to reopen the same approval, ask the owner to approve it, and only then use visa connect --restart if a replacement is still wanted."},enrollment_owner_mismatch:{kind:"platform",escalation:"awaiting_human",fix:"visa connect --restart (keep the signed-in account) or visa disconnect --all, then visa connect (switch accounts)",nextAction:"The agent approved for this terminal belongs to a different Visa account than the one this terminal is signed in to (the error names it), so nothing was connected. Let the owner choose. To keep the signed-in account: run visa connect --restart and open the new link while signed in to that account. To switch to the other account: visa disconnect --all signs this terminal out, but it also removes the Visa MCP server from every AI client, the spend HUD and any local card-delivery files, so run it only with the owner's say-so; then run visa connect and the owner signs in with the other account. Never approve for them."},wallet_key_setup_pending:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"This agent is connected but cannot pay yet: its key on the owner's Tempo wallet is not set up. The owner's open approval page finishes it on its own (it asks for USDC.e first if the wallet has none); if that page was closed, opening the Visa Console finishes it the same way. Then run visa connect (or call get_status) to confirm. Do not run visa connect --restart, and do not try a payment until it reports the key ready.",remedy:{path:"/agent/enroll/payments",label:"Finish the wallet in Payments"}},unspecified_error:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"This failure could not be classified, so it is reported as platform to avoid a silent retry loop. Surface the human-readable error to a human rather than retrying."},tempo_over_max:{kind:"caller",fix:null,nextAction:"Nothing was signed or paid. The charge costs more than max: raise max only if the human agreed to that price, otherwise stop."},tempo_budget_refused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The owner's spending budget or per-payment limit does not allow this payment. Ask the human to raise it in the Visa Console; do not retry until they have.",remedy:{path:"/agent/enroll/limits",label:"Change the agent's limits"}},tempo_chain_limit:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The wallet's weekly on-chain safety limit for this agent is used up; it refills on its weekly schedule, shown with the agent's limits in the Visa Console. Do not retry before then; tell the human if the purchase cannot wait.",remedy:{path:"/agent/enroll/limits",label:"Change the agent's limits"}},tempo_charge_expired:{kind:"caller",fix:"pay",nextAction:"Nothing was paid. The merchant charge expired before it was signed. Call pay again for the same target to get a fresh charge."},tempo_payment_unclear:{kind:"caller",fix:"pay",nextAction:"The payment may have gone through (charged: null). Do not start a new purchase. Call pay again with the SAME economicIntentId in about a minute: it reports whether the earlier payment landed and pays only if it provably did not. history shows it too."},tempo_payment_in_progress:{kind:"caller",fix:"pay",nextAction:"Another call is paying this exact purchase right now. Do not pay again; call pay again with the same economicIntentId in a minute to read its outcome."},tempo_payment_refused:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"Nothing was signed or paid. Visa refused this Tempo payment before signing. Tell the human and stop; do not retry."},tempo_charge_mismatch:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The merchant's Tempo charge does not match what this payment allows (payee, currency or paying account), checked on this machine. Do not retry; tell the human."},tempo_not_enabled:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was paid. This agent's wallet setup is not finished. Ask the owner to open Payments in the Visa Console (/agent/enroll/payments): the wallet finishes setting up there once it has funds. Then call pay again with the same economicIntentId.",remedy:{path:"/agent/enroll/payments",label:"Finish the wallet in Payments"}},tempo_unavailable:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Nothing was paid. Visa has wallet payments switched off right now. Tell the human; do not retry until Visa turns them on, and do not look for another way to pay this merchant."},merchant_not_supported:{kind:"caller",fix:null,nextAction:"Nothing was charged. This merchant does not accept Visa wallet payments (MPP on Tempo). Do not retry it on `pay`; pay a merchant that accepts Tempo, or tell the human."},merchant_unreachable:{kind:"caller",fix:null,nextAction:"Nothing was charged. The merchant URL could not be reached to read its price. Check the URL, then call pay again with the same economicIntentId."},purchase_on_retired_rail:{kind:"caller",fix:null,nextAction:"Nothing was paid. This purchase was started with the earlier wallet, before Visa moved wallet payments to Tempo. Do not pay it again: check `history` for its outcome, and use a new economicIntentId only for a genuinely new purchase."},tempo_owner_approval_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:`Nothing was paid. The owner chose "Ask me each time" for this agent's wallet payments, and this Tempo payment could not be sent to them for approval. Call pay again with the same economicIntentId: it asks the owner (the answer then carries the approval link). If it keeps failing, ask the human.`}},sUr=Object.keys(aB);Xt=class extends Error{diagnostic;details;constructor(t,r,n={}){super(t),this.name="AgentContractError";let o=n.agentId??(typeof n.details?.agentId=="string"?n.details.agentId:void 0);this.diagnostic=bo(r,{...n,...o?{agentId:o}:{}}),this.details=n.details}get code(){return this.diagnostic.code}}});var bR=_(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.CanonicalJsonError=_n.CANONICAL_OPAQUE_ID_MAX_BYTES=_n.CANONICAL_OPAQUE_ID_RE=_n.CANONICAL_OPAQUE_ID_PATTERN=void 0;_n.utf8ByteLength=dB;_n.isCanonicalText=uce;_n.compareCanonicalKeys=dce;_n.isCanonicalOpaqueId=lce;_n.assertCanonicalOpaqueId=yot;_n.canonicalJsonExact=uB;_n.CANONICAL_OPAQUE_ID_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$";_n.CANONICAL_OPAQUE_ID_RE=new RegExp(_n.CANONICAL_OPAQUE_ID_PATTERN);_n.CANONICAL_OPAQUE_ID_MAX_BYTES=128;var Eot=/[\u0000-\u001f\u007f\u2028\u2029]/,cB=new TextEncoder;function dB(e){return cB.encode(e).length}function uce(e,t){return typeof e=="string"&&e.length>0&&dB(e)<=t&&e.trim()===e&&e.normalize("NFC")===e&&!Eot.test(e)}function dce(e,t){let r=cB.encode(e),n=cB.encode(t),o=Math.min(r.length,n.length);for(let i=0;i<o;i+=1)if(r[i]!==n[i])return r[i]-n[i];return r.length-n.length}function lce(e){return typeof e=="string"&&dB(e)<=_n.CANONICAL_OPAQUE_ID_MAX_BYTES&&_n.CANONICAL_OPAQUE_ID_RE.test(e)}function yot(e,t="value"){if(!lce(e))throw new Error(`${t} must be a canonical opaque id (max 128 ASCII bytes)`)}var Sot=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,Ic=class extends Error{constructor(t){super(t),this.name="CanonicalJsonError"}};_n.CanonicalJsonError=Ic;function uB(e,t=0){if(t>16)throw new Ic("nesting is deeper than 16");if(e===null||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="string"){if(Sot.test(e))throw new Ic("text is not valid Unicode");return JSON.stringify(e)}if(typeof e=="number"){if(!Number.isSafeInteger(e)||Object.is(e,-0))throw new Ic("numbers must be whole and at most 2^53 - 1; put amounts and decimals in strings");return JSON.stringify(e)}if(Array.isArray(e)){if(e.length>1024)throw new Ic("an array has more than 1024 items");return`[${e.map(n=>uB(n,t+1)).join(",")}]`}if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new Ic("only JSON objects, arrays, strings, whole numbers and booleans");let r=Object.keys(e);if(r.length>512)throw new Ic("an object has more than 512 keys");for(let n of r)if(!uce(n,128))throw new Ic("keys must be non-empty trimmed NFC text of at most 128 bytes");return`{${r.sort(dce).map(n=>`${JSON.stringify(n)}:${uB(e[n],t+1)}`).join(",")}}`}});var Fl=_(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.AgentOperationContractError=Ma.AGENT_OPERATION_CONTRACT_ERROR_CODES=void 0;Ma.record=pce;Ma.bounded=_ce;Ma.canonicalJsonValue=mce;Ma.canonicalJson=Tot;Ma.canonicalEnvelopeJson=bot;var fce=bR();Ma.AGENT_OPERATION_CONTRACT_ERROR_CODES=["commitment_mismatch","intent_mismatch","invalid_amount","invalid_contract","invalid_currency","invalid_effect","invalid_evidence","invalid_principal","invalid_window","settlement_amount_invalid","unsupported_version"];var Ju=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="AgentOperationContractError"}};Ma.AgentOperationContractError=Ju;function pce(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new Ju("invalid_contract",`${t} must be an object`);return e}function _ce(e,t,r=4096){if(!(0,fce.isCanonicalText)(e,r))throw new Ju("invalid_contract",`${t} is not bounded canonical text`);return e}function mce(e,t=0){return AR(e,t,16)}function AR(e,t,r){if(t>r)throw new Ju("invalid_contract","payload nesting is too deep");if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isSafeInteger(e)&&!Object.is(e,-0))return e;if(typeof e=="number")throw new Ju("invalid_contract","JSON numbers must be safe canonical integers; use strings for larger or decimal values");if(Array.isArray(e)){if(e.length>1024)throw new Ju("invalid_contract","payload array is too large");return e.map(i=>AR(i,t+1,r))}let n=pce(e,"payload"),o=Object.entries(n);if(o.length>512)throw new Ju("invalid_contract","payload object is too large");return Object.fromEntries(o.sort(([i],[s])=>(0,fce.compareCanonicalKeys)(i,s)).map(([i,s])=>[_ce(i,"payload key",128),AR(s,t+1,r)]))}function Tot(e){return JSON.stringify(mce(e))}function bot(e){return JSON.stringify(AR(e,0,64))}});var zu=_(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.AGENT_OPERATION_TRANSITION_SQL_PREDICATE=be.AGENT_OPERATION_TERMINAL_SQL_LIST=be.AGENT_OPERATION_RESUMABLE_SQL_LIST=be.AGENT_OPERATION_TERMINAL_STATES=be.AGENT_OPERATION_EVIDENCE_ELIGIBLE_STATES=be.AGENT_OPERATION_RESUMABLE_STATES=be.AGENT_OPERATION_ALLOWED_TRANSITIONS=be.AGENT_OPERATION_STATES=be.EXECUTOR_BINDING_VERSION=be.EXECUTION_EVIDENCE_VERSION=be.AGENT_OPERATION_RESULT_VERSION=be.AGENT_OPERATION_VERSION=be.canonicalJsonValue=be.canonicalJson=be.AgentOperationContractError=be.AGENT_OPERATION_CONTRACT_ERROR_CODES=be.canonicalEnvelopeJson=void 0;be.isAgentOperationTransitionAllowed=wot;be.agentOperationIntentPreimage=Rot;be.parseAgentMoneyEconomics=Ece;be.parseAgentOperationStructure=yce;be.parseExecutionEvidence=Cot;be.parsePreparedAgentOperationStructure=xot;be.agentOperationPopSigningInput=Mot;var Se=Fl(),BT=Fl();Object.defineProperty(be,"canonicalEnvelopeJson",{enumerable:!0,get:function(){return BT.canonicalEnvelopeJson}});Object.defineProperty(be,"AGENT_OPERATION_CONTRACT_ERROR_CODES",{enumerable:!0,get:function(){return BT.AGENT_OPERATION_CONTRACT_ERROR_CODES}});Object.defineProperty(be,"AgentOperationContractError",{enumerable:!0,get:function(){return BT.AgentOperationContractError}});Object.defineProperty(be,"canonicalJson",{enumerable:!0,get:function(){return BT.canonicalJson}});Object.defineProperty(be,"canonicalJsonValue",{enumerable:!0,get:function(){return BT.canonicalJsonValue}});be.AGENT_OPERATION_VERSION=1;be.AGENT_OPERATION_RESULT_VERSION=1;be.EXECUTION_EVIDENCE_VERSION=1;be.EXECUTOR_BINDING_VERSION=1;var Aot=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,vot=/^[A-Za-z0-9_-]{43}$/,Iot=/^[a-z][a-z0-9]*(?:[._:-][a-z0-9]+)*$/,Pot=/^[A-Z][A-Z0-9]{2,11}$/,hce=96*1024,lB=9223372036854775807n;be.AGENT_OPERATION_STATES=["claimed","reserved","dispatched","authorized","settling","committed","released","indeterminate","denied"];be.AGENT_OPERATION_ALLOWED_TRANSITIONS={claimed:["reserved","denied"],reserved:["dispatched","released","indeterminate","settling"],dispatched:["authorized","released","indeterminate","settling"],authorized:["settling","indeterminate"],settling:["committed","released","indeterminate"],committed:[],released:[],indeterminate:["settling"],denied:[]};be.AGENT_OPERATION_RESUMABLE_STATES=["claimed","reserved","dispatched"];be.AGENT_OPERATION_EVIDENCE_ELIGIBLE_STATES=["reserved","dispatched","authorized","indeterminate"];be.AGENT_OPERATION_TERMINAL_STATES=["committed","released","denied"];function wot(e,t){return e===t||be.AGENT_OPERATION_ALLOWED_TRANSITIONS[e].includes(t)}function fB(e){return e.map(t=>`'${t}'`).join(", ")}be.AGENT_OPERATION_RESUMABLE_SQL_LIST=fB(be.AGENT_OPERATION_RESUMABLE_STATES);be.AGENT_OPERATION_TERMINAL_SQL_LIST=fB(be.AGENT_OPERATION_TERMINAL_STATES);be.AGENT_OPERATION_TRANSITION_SQL_PREDICATE=["NEW.state = OLD.state",...be.AGENT_OPERATION_STATES.filter(e=>be.AGENT_OPERATION_ALLOWED_TRANSITIONS[e].length>0).map(e=>`(OLD.state = '${e}' AND NEW.state IN (${fB(be.AGENT_OPERATION_ALLOWED_TRANSITIONS[e])}))`)].join(`
4
+ OR `);function xs(e,t,r=[]){let n=new Set([...t,...r]);if(t.some(o=>!(o in e))||Object.keys(e).some(o=>!n.has(o)))throw new Se.AgentOperationContractError("invalid_contract","contract contains missing or unknown fields")}function Fh(e,t){let r=(0,Se.bounded)(e,t,36).toLowerCase();if(!Aot.test(r))throw new Se.AgentOperationContractError("invalid_contract",`${t} must be a UUID`);return r}function Pc(e,t){let r=(0,Se.bounded)(e,t,43);if(!vot.test(r)||!/[AEIMQUYcgkosw048]$/.test(r))throw new Se.AgentOperationContractError("invalid_contract",`${t} must be a canonical 32-byte hash`);return r}function vR(e,t){let r=(0,Se.bounded)(e,t,128);if(!Iot.test(r))throw new Se.AgentOperationContractError("invalid_contract",`${t} must be a stable lowercase token`);return r}function gce(e,t){let r=(0,Se.bounded)(e,t,32),n=Date.parse(r);if(!Number.isFinite(n)||new Date(n).toISOString()!==r)throw new Se.AgentOperationContractError("invalid_contract",`${t} must be canonical ISO-8601`);return r}function Rot(e){let t={domain:"visa.agent-operation-intent.v1",operationId:e.operationId,idempotencyKey:e.idempotencyKey,agentId:e.agentId,runtimeId:e.runtimeId,rail:e.rail,effect:e.effect,execution:{adapter:e.execution.adapter,commitment:e.execution.commitment,payloadHash:e.execution.payloadHash},createdAt:e.createdAt,expiresAt:e.expiresAt};return(0,Se.canonicalJson)(t)}function Oot(e){let t=(0,Se.record)(e,"principal");if(t.kind==="identity_pop")return xs(t,["kind","popJwt","keyJkt"]),{kind:t.kind,popJwt:(0,Se.bounded)(t.popJwt,"popJwt",16384),keyJkt:Pc(t.keyJkt,"keyJkt")};if(t.kind==="certified_runtime_pop")return xs(t,["kind","popJwt","runtimeCertificate","rootJkt","childJkt"]),{kind:t.kind,popJwt:(0,Se.bounded)(t.popJwt,"popJwt",16384),runtimeCertificate:(0,Se.bounded)(t.runtimeCertificate,"runtimeCertificate",32768),rootJkt:Pc(t.rootJkt,"rootJkt"),childJkt:Pc(t.childJkt,"childJkt")};if(t.kind==="delegated_runtime_lease_pop"){if(xs(t,["kind","v","popJwt","delegation","lease","rootJkt","runtimeJkt"]),t.v!==2)throw new Se.AgentOperationContractError("invalid_principal","delegated runtime lease principal must use version 2");return{kind:t.kind,v:t.v,popJwt:(0,Se.bounded)(t.popJwt,"popJwt",16384),delegation:(0,Se.bounded)(t.delegation,"delegation",32768),lease:(0,Se.bounded)(t.lease,"lease",32768),rootJkt:Pc(t.rootJkt,"rootJkt"),runtimeJkt:Pc(t.runtimeJkt,"runtimeJkt")}}if(t.kind==="tap_signature")return xs(t,["kind","signature","runtimeCertificate","signedPayload"]),{kind:t.kind,signature:(0,Se.bounded)(t.signature,"signature",2048),runtimeCertificate:(0,Se.bounded)(t.runtimeCertificate,"runtimeCertificate",32768),signedPayload:Pc(t.signedPayload,"signedPayload")};throw new Se.AgentOperationContractError("invalid_principal","unsupported principal proof kind")}function Ece(e){let t=(0,Se.record)(e,"money economics");xs(t,["amountMicros","currency","merchant"]);let r=(0,Se.bounded)(t.amountMicros,"amountMicros",40);if(!/^[1-9][0-9]*$/.test(r)||BigInt(r)>lB)throw new Se.AgentOperationContractError("invalid_amount","amountMicros must be positive and canonical");let n=(0,Se.bounded)(t.currency,"currency",12);if(!Pot.test(n))throw new Se.AgentOperationContractError("invalid_currency","currency must be canonical");let o=(0,Se.record)(t.merchant,"merchant");return xs(o,["id"],["name","url"]),{amountMicros:r,currency:n,merchant:{id:(0,Se.bounded)(o.id,"merchant.id",512),...o.name===void 0?{}:{name:(0,Se.bounded)(o.name,"merchant.name",255)},...o.url===void 0?{}:{url:(0,Se.bounded)(o.url,"merchant.url",2048)}}}}function Not(e){let t=(0,Se.record)(e,"effect");if(t.kind==="money"){xs(t,["kind","amountMicros","currency","merchant","grantId","budgetEpochId"],["maxAmountMicros"]);let r=Ece({amountMicros:t.amountMicros,currency:t.currency,merchant:t.merchant}),n;if(t.maxAmountMicros!==void 0&&(n=(0,Se.bounded)(t.maxAmountMicros,"maxAmountMicros",40),!/^[1-9][0-9]*$/.test(n)||BigInt(n)>lB))throw new Se.AgentOperationContractError("invalid_amount","maxAmountMicros must be positive and canonical");return{kind:t.kind,...r,grantId:Fh(t.grantId,"grantId"),budgetEpochId:Fh(t.budgetEpochId,"budgetEpochId"),...n===void 0?{}:{maxAmountMicros:n}}}if(t.kind==="resource")return xs(t,["kind","resource","action","audience"]),{kind:t.kind,resource:(0,Se.bounded)(t.resource,"resource",4096),action:vR(t.action,"action"),audience:(0,Se.bounded)(t.audience,"audience",255)};throw new Se.AgentOperationContractError("invalid_effect","unsupported operation effect")}function yce(e,t=Date.now()){let r=(0,Se.record)(e,"operation");if(xs(r,["v","operationId","idempotencyKey","agentId","runtimeId","rail","intentHash","principal","effect","execution","createdAt","expiresAt"]),r.v!==be.AGENT_OPERATION_VERSION)throw new Se.AgentOperationContractError("unsupported_version","unsupported operation version");let n=(0,Se.record)(r.execution,"execution");xs(n,["adapter","commitment","payloadHash","payload"]);let o=(0,Se.canonicalJsonValue)(n.payload);if(new TextEncoder().encode(JSON.stringify(o)).length>hce)throw new Se.AgentOperationContractError("invalid_contract","execution payload is too large");let i=Pc(n.commitment,"execution.commitment"),s=Pc(n.payloadHash,"execution.payloadHash"),a=gce(r.createdAt,"createdAt"),c=gce(r.expiresAt,"expiresAt");if(!Number.isFinite(t)||Date.parse(a)>t+3e4||Date.parse(a)<t-5*6e4||Date.parse(c)<=t||Date.parse(c)<=Date.parse(a)||Date.parse(c)-Date.parse(a)>10*6e4)throw new Se.AgentOperationContractError("invalid_window","operation validity window is not currently usable");let u={v:be.AGENT_OPERATION_VERSION,operationId:Fh(r.operationId,"operationId"),idempotencyKey:(0,Se.bounded)(r.idempotencyKey,"idempotencyKey",255),agentId:Fh(r.agentId,"agentId"),runtimeId:Fh(r.runtimeId,"runtimeId"),rail:vR(r.rail,"rail"),intentHash:Pc(r.intentHash,"intentHash"),principal:Oot(r.principal),effect:Not(r.effect),execution:{adapter:vR(n.adapter,"execution.adapter"),commitment:i,payloadHash:s,payload:o},createdAt:a,expiresAt:c};if(u.rail==="wallet:x402"&&u.effect.kind==="money"&&u.effect.merchant.url===void 0)throw new Se.AgentOperationContractError("invalid_contract","merchant.url is required for wallet:x402 operations");if(u.principal.kind==="tap_signature"&&u.principal.signedPayload!==u.intentHash)throw new Se.AgentOperationContractError("intent_mismatch","TAP signedPayload must equal the universal operation intentHash");return u}function Cot(e){let t=(0,Se.record)(e,"evidence");if(xs(t,["v","operationId","adapter","outcome","artifactHash","providerReference","proof"],["settledMicros"]),t.v!==be.EXECUTION_EVIDENCE_VERSION||t.outcome!=="committed"&&t.outcome!=="released")throw new Se.AgentOperationContractError("invalid_evidence","unsupported evidence version or outcome");let r;if(t.settledMicros!==void 0){if(r=(0,Se.bounded)(t.settledMicros,"settledMicros",40),!/^(?:0|[1-9][0-9]*)$/.test(r)||BigInt(r)>lB)throw new Se.AgentOperationContractError("invalid_evidence","settledMicros is not canonical");if(t.outcome==="released"&&r!=="0")throw new Se.AgentOperationContractError("settlement_amount_invalid","released evidence must settle zero")}let n=(0,Se.canonicalJsonValue)(t.proof);if(new TextEncoder().encode(JSON.stringify(n)).length>hce)throw new Se.AgentOperationContractError("invalid_evidence","evidence proof is too large");return{v:be.EXECUTION_EVIDENCE_VERSION,operationId:Fh(t.operationId,"operationId"),adapter:vR(t.adapter,"adapter"),outcome:t.outcome,artifactHash:Pc(t.artifactHash,"artifactHash"),...r===void 0?{}:{settledMicros:r},providerReference:(0,Se.bounded)(t.providerReference,"providerReference",255),proof:n}}function xot(e,t=Date.now()){let r=(0,Se.record)(e,"prepared operation");xs(r,["operationId","idempotencyKey","agentId","runtimeId","rail","intentHash","effect","execution","createdAt","expiresAt"]);let{v:n,principal:o,...i}=yce({...r,v:1,principal:{kind:"identity_pop",popJwt:"unsigned",keyJkt:"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}},t);return i}function Mot(e){let t=r=>btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(r)))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return`${t({alg:"EdDSA",kid:e.childJkt,typ:"visa-agent-pop+jwt"})}.${t({cnf:{jwk:{kty:e.childPublicJwk.kty,crv:e.childPublicJwk.crv,x:e.childPublicJwk.x}},nonce:e.operationId,aud:"visa-agent-operations:v1",iat:e.issuedAtSec,int:e.intentHash,...e.runtimeCertificate?{rkc:e.runtimeCertificate}:{}})}`}});var PR=_(IR=>{"use strict";Object.defineProperty(IR,"__esModule",{value:!0});IR.parsePurchaseTerms=Sce;IR.purchaseTermsPreimage=kot;var Et=Fl(),Lot=zu();function Gh(e,t){if(Object.keys(e).sort().join(",")!==[...t].sort().join(","))throw new Et.AgentOperationContractError("invalid_contract","purchase terms fields are not canonical")}function Sce(e){let t=(0,Et.record)(e,"purchase terms"),r=t.profile==="exact_card_checkout_v1";if(Gh(t,["v","profile","alternatives",...r?["checkout","disclosureMode",...t.merchantCountryCode===void 0?[]:["merchantCountryCode"]]:[]]),t.v!==1||typeof t.profile!="string"||!["url_resource_v1","approved_x402_request_v1","exact_card_checkout_v1"].includes(String(t.profile)))throw new Et.AgentOperationContractError("unsupported_version","unsupported purchase terms profile");if(!Array.isArray(t.alternatives)||t.alternatives.length<1||t.alternatives.length>2)throw new Et.AgentOperationContractError("invalid_contract","purchase requires one or two exact rail alternatives");let n=t.profile==="approved_x402_request_v1";if(n&&t.alternatives.length!==1)throw new Et.AgentOperationContractError("invalid_contract","request-bound purchase requires one wallet alternative");let o=t.alternatives.map(i=>{let s=(0,Et.record)(i,"purchase alternative"),a=(0,Lot.parseAgentMoneyEconomics)(s.economics),c=(0,Et.bounded)(a.merchant.url,"purchase resource URL",2048),u;try{u=new URL(c)}catch{throw new Et.AgentOperationContractError("invalid_contract","purchase resource URL is invalid")}if(u.protocol!=="https:"||u.username||u.password||u.hash)throw new Et.AgentOperationContractError("invalid_contract","purchase requires an HTTPS resource without credentials or fragment");if(s.rail==="wallet:x402"){Gh(s,["rail","economics","network","asset","payee",...n?["requestHash"]:[]]);let d=n?(0,Et.bounded)(s.requestHash,"request hash",43):void 0;if(d!==void 0&&!/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(d))throw new Et.AgentOperationContractError("invalid_contract","invalid request hash");let l=(0,Et.bounded)(s.network,"network",64),p=(0,Et.bounded)(s.asset,"asset",128),f=(0,Et.bounded)(s.payee,"payee",42);if(!/^eip155:[1-9][0-9]{0,15}$/.test(l)||!new RegExp(`^${l}/erc20:0x[0-9a-f]{40}$`).test(p)||!/^0x[0-9a-f]{40}$/.test(f)||a.currency!=="USDC")throw new Et.AgentOperationContractError("invalid_contract","invalid exact wallet economic coordinates");return{rail:s.rail,economics:a,network:l,asset:p,payee:f,...d?{requestHash:d}:{}}}if(s.rail==="card:vic"&&!n){if(Gh(s,["rail","economics","processorAction","captureMode"]),s.processorAction!=="charge_and_capture"||s.captureMode!=="exact"||a.currency!=="USD"||BigInt(a.amountMicros)%10000n!==0n)throw new Et.AgentOperationContractError("invalid_contract","purchase card profile requires exact whole-cent capture");return{rail:s.rail,economics:a,processorAction:"charge_and_capture",captureMode:"exact"}}throw new Et.AgentOperationContractError("invalid_contract","unsupported purchase rail")});if(new Set(o.map(i=>i.rail)).size!==o.length)throw new Et.AgentOperationContractError("invalid_contract","purchase rail alternatives must be unique");if(o.sort((i,s)=>i.rail<s.rail?-1:i.rail>s.rail?1:0),r){if(o.length!==1||o[0].rail!=="card:vic"||!o[0].economics.merchant.name)throw new Et.AgentOperationContractError("invalid_contract","exact checkout requires one card alternative");if(t.disclosureMode!=="private"&&t.disclosureMode!=="agent_history")throw new Et.AgentOperationContractError("invalid_contract","unsupported card disclosure mode");if(t.merchantCountryCode!==void 0&&(typeof t.merchantCountryCode!="string"||!/^[A-Z]{2}$/.test(t.merchantCountryCode)))throw new Et.AgentOperationContractError("invalid_contract","invalid merchant country");return{v:1,profile:"exact_card_checkout_v1",...t.merchantCountryCode===void 0?{}:{merchantCountryCode:t.merchantCountryCode},alternatives:o,checkout:Dot(t.checkout,o[0].economics.amountMicros),disclosureMode:t.disclosureMode}}return{v:1,profile:t.profile,alternatives:o}}function Dot(e,t){let r=(0,Et.record)(e,"checkout");Gh(r,["id","revision","source","expiresAt","items","taxMicros","shippingMicros","discountMicros","fulfillment","customerHash"]);let n=()=>{throw new Et.AgentOperationContractError("invalid_contract","invalid exact card checkout")},o=l=>((typeof l!="string"||!/^(0|[1-9][0-9]{0,17})$/.test(l)||BigInt(l)%10000n!==0n)&&n(),l),i=l=>((typeof l!="string"||!/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(l))&&n(),l);(r.source!=="runtime_observed"||typeof r.expiresAt!="string"||!Number.isFinite(Date.parse(r.expiresAt))||new Date(r.expiresAt).toISOString()!==r.expiresAt||!Array.isArray(r.items)||r.items.length<1||r.items.length>100)&&n();let s=r.items.map(l=>{let p=(0,Et.record)(l,"checkout item");return Gh(p,["id","name","quantity","totalMicros"]),(!Number.isSafeInteger(p.quantity)||Number(p.quantity)<1||Number(p.quantity)>1e6)&&n(),{id:(0,Et.bounded)(p.id,"checkout item ID",256),name:(0,Et.bounded)(p.name,"checkout item name",512),quantity:p.quantity,totalMicros:o(p.totalMicros)}});new Set(s.map(l=>l.id)).size!==s.length&&n();let a=o(r.taxMicros),c=o(r.shippingMicros),u=o(r.discountMicros);s.reduce((l,p)=>l+BigInt(p.totalMicros),0n)+BigInt(a)+BigInt(c)-BigInt(u)!==BigInt(t)&&n();let d=(0,Et.record)(r.fulfillment,"checkout fulfillment");return Gh(d,["method","detailsHash"]),{id:(0,Et.bounded)(r.id,"checkout ID",256),revision:(0,Et.bounded)(r.revision,"checkout revision",256),source:"runtime_observed",expiresAt:r.expiresAt,items:s,taxMicros:a,shippingMicros:c,discountMicros:u,fulfillment:{method:(0,Et.bounded)(d.method,"fulfillment method",256),detailsHash:i(d.detailsHash)},customerHash:i(r.customerHash)}}function kot(e){return(0,Et.canonicalJson)({domain:"visa.purchase-terms.v1",terms:Sce(e)})}});var pB=_(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.ACCOUNT_OPERATION_EVIDENCE_TYPES=Qn.ACCOUNT_OPERATION_PROOF_LEVELS=Qn.ACCOUNT_OPERATION_OUTCOMES=Qn.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=void 0;Qn.cardProofLevel=Uot;Qn.cardStatusClaimsProcessorTruth=jot;Qn.parseAccountOperationReceipt=qot;Qn.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=1;Qn.ACCOUNT_OPERATION_OUTCOMES=["pending","completed","failed","uncertain","released","reversed","disputed"];Qn.ACCOUNT_OPERATION_PROOF_LEVELS=["none","platform_observed","merchant_reported","owner_attested","processor_confirmed","network_verified","settled"];var Tce={sale_accepted:"merchant_reported",auth_held:"merchant_reported",capture_pending:"merchant_reported",captured:"processor_confirmed",voided:"processor_confirmed",refunded:"processor_confirmed",partially_refunded:"processor_confirmed",refund_pending:"processor_confirmed",chargeback_open:"processor_confirmed",chargeback_lost:"processor_confirmed",chargeback_won:"processor_confirmed",pending:"platform_observed",needs_reconciliation:"platform_observed"};function Uot(e,t){let r=Tce[e]??"platform_observed";return r==="processor_confirmed"&&!t?"merchant_reported":r}function jot(e){return Tce[e]==="processor_confirmed"}Qn.ACCOUNT_OPERATION_EVIDENCE_TYPES=["platform_activity","merchant_confirmation","card_lifecycle","onchain_transaction"];function Gl(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Xu(e){return e===null||typeof e=="string"}function HT(e){return typeof e=="string"&&e.length>0&&!Number.isNaN(Date.parse(e))}function $l(e,t){let r=Object.keys(e).sort(),n=[...t].sort();return r.length===n.length&&r.every((o,i)=>o===n[i])}function Bot(e){return Gl(e)?$l(e,["type","source","observedAt","reference","url"])&&typeof e.type=="string"&&Qn.ACCOUNT_OPERATION_EVIDENCE_TYPES.includes(e.type)&&typeof e.source=="string"&&HT(e.observedAt)&&Xu(e.reference)&&Xu(e.url):!1}function Hot(e){return Gl(e)?$l(e,["type","at"])&&typeof e.type=="string"&&e.type.length>0&&HT(e.at):!1}function qot(e){if(!Gl(e)||!$l(e,["schemaVersion","operationId","activityId","payment","route","party","authority","outcome","evidence","timeline","dataCompleteness"])||e.schemaVersion!==Qn.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION||typeof e.operationId!="string"||typeof e.activityId!="string"||e.dataCompleteness!=="complete"&&e.dataCompleteness!=="partial"||!Array.isArray(e.evidence)||!e.evidence.every(Bot)||!Array.isArray(e.timeline)||!e.timeline.every(Hot))return null;let t=e.payment,r=e.route,n=e.party,o=e.authority,i=e.outcome;return!Gl(t)||!$l(t,["amountAtomic","decimals","currency","merchant","description","createdAt"])||typeof t.amountAtomic!="string"||!/^\d+$/.test(t.amountAtomic)||typeof t.decimals!="number"||!Number.isInteger(t.decimals)||t.decimals<0||t.decimals>18||typeof t.currency!="string"||typeof t.merchant!="string"||typeof t.description!="string"||!HT(t.createdAt)||!Gl(r)||!$l(r,["rail","protocol","network","cardLast4"])||r.rail!=="wallet"&&r.rail!=="card"||!(r.protocol===null||r.protocol==="x402"||r.protocol==="mpp"||r.protocol==="vic"||r.protocol==="virtual_card")||!Xu(r.network)||!Xu(r.cardLast4)||!Gl(n)||!$l(n,["agentId","agentName"])||!Xu(n.agentId)||!Xu(n.agentName)||!Gl(o)||!$l(o,["grantId","mandateId","drawId"])||!Xu(o.grantId)||!Xu(o.mandateId)||!Xu(o.drawId)||!Gl(i)||!$l(i,["status","proofLevel","final","updatedAt","finalizesBy"])||typeof i.status!="string"||!Qn.ACCOUNT_OPERATION_OUTCOMES.includes(i.status)||typeof i.proofLevel!="string"||!Qn.ACCOUNT_OPERATION_PROOF_LEVELS.includes(i.proofLevel)||typeof i.final!="boolean"||!HT(i.updatedAt)||!(i.finalizesBy===null||HT(i.finalizesBy))?null:e}});var vce=_(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.PURCHASE_RESOURCE_AUDIENCE=is.PURCHASE_OBSERVATIONS=void 0;is.parsePurchaseReceipt=Got;is.parsePurchaseResourceRequest=Ace;is.purchaseResourceRequestHash=$ot;var Vot=require("node:crypto"),wc=Fl(),Fot=PR(),bce=pB();is.PURCHASE_OBSERVATIONS=["credential_delivered","submission_started","buyer_action_required","order_reported","submission_failed"];function Got(e,t){let r=(0,wc.record)(e,"purchase receipt"),n=(0,wc.record)(r.outcome,"purchase outcome");if(!t||r.operationId!==t||typeof r.credentialIssued!="boolean"||!bce.ACCOUNT_OPERATION_OUTCOMES.includes(n.status)||!bce.ACCOUNT_OPERATION_PROOF_LEVELS.includes(n.proofLevel)||typeof n.final!="boolean"||!Array.isArray(r.observations)||r.observations.length>is.PURCHASE_OBSERVATIONS.length||r.observations.some(i=>!is.PURCHASE_OBSERVATIONS.includes(i))||new Set(r.observations).size!==r.observations.length)throw new wc.AgentOperationContractError("invalid_contract","invalid purchase receipt");let o=r.refusal===void 0?void 0:(0,wc.record)(r.refusal,"refusal");if(o!==void 0&&(!Number.isSafeInteger(o.providerStatus)||Number(o.providerStatus)<100||Number(o.providerStatus)>999||typeof o.providerCode!="string"||!/^[a-z0-9_]{1,64}$/.test(o.providerCode)||n.status!=="failed"||n.final!==!0||r.credentialIssued!==!1))throw new wc.AgentOperationContractError("invalid_contract","invalid purchase refusal");return{operationId:t,credentialIssued:r.credentialIssued,outcome:{status:n.status,proofLevel:n.proofLevel,final:n.final},observations:r.observations,...o?{refusal:{providerStatus:Number(o.providerStatus),providerCode:o.providerCode}}:{}}}is.PURCHASE_RESOURCE_AUDIENCE="visa:purchase-resource:v1";function Ace(e){let t=(0,wc.record)(e,"purchase request"),r=()=>{throw new wc.AgentOperationContractError("invalid_contract","invalid purchase request")};(t.v!==1||typeof t.action!="string"||!["create","retrieve","cancel"].includes(t.action))&&r();let n=["v","action","requestId","agentId","runtimeId",...t.action==="create"?["requestKey","terms"]:["purchaseId"],...t.action==="retrieve"&&t.include!==void 0?["include"]:[],...t.action==="retrieve"&&t.observation!==void 0?["observation"]:[]];Object.keys(t).sort().join(",")!==n.sort().join(",")&&r(),t.include!==void 0&&t.include!=="card"&&r();let o;if(t.observation!==void 0){t.include!==void 0&&r();let s=(0,wc.record)(t.observation,"purchase observation");(Object.keys(s).sort().join(",")!=="attemptId,kind,termsHash"||!is.PURCHASE_OBSERVATIONS.includes(s.kind)||typeof s.attemptId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(s.attemptId)||typeof s.termsHash!="string"||!/^[A-Za-z0-9_-]{43}$/.test(s.termsHash))&&r(),o=s}for(let s of["requestId","agentId","runtimeId",...t.action==="create"?[]:["purchaseId"]])(typeof t[s]!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t[s]))&&r();let i={v:1,requestId:t.requestId,agentId:t.agentId,runtimeId:t.runtimeId};if(t.action==="create"){let s=(0,Fot.parsePurchaseTerms)(t.terms);return(s.profile!=="exact_card_checkout_v1"||s.alternatives.length!==1||s.alternatives[0].rail!=="card:vic")&&r(),{...i,action:"create",requestKey:(0,wc.bounded)(t.requestKey,"purchase request key",256),terms:s}}return{...i,action:t.action,purchaseId:t.purchaseId,...t.action==="retrieve"&&t.include==="card"?{include:"card"}:{},...o?{observation:o}:{}}}function $ot(e){return(0,Vot.createHash)("sha256").update((0,wc.canonicalJson)({domain:is.PURCHASE_RESOURCE_AUDIENCE,request:Ace(e)})).digest("base64url")}});var hB=_(Ot=>{"use strict";var Kot=Ot&&Ot.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),_B=Ot&&Ot.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Kot(t,e,r)};Object.defineProperty(Ot,"__esModule",{value:!0});Ot.CARD_ADMISSION_RECOVERY_AUDIENCE=void 0;Ot.cardAdmissionRecoveryRequestHash=Wot;Ot.agentOperationIntentHash=mB;Ot.agentExecutionCommitment=gB;Ot.purchaseTermsHash=Yot;Ot.purchaseAlternativeFromOperation=Jot;Ot.x402ResourceCommitment=zot;Ot.agentOperationIdempotencyKey=Pce;Ot.purchaseAttemptIdempotencyKey=Xot;Ot.agentOperationTermsFingerprint=wce;Ot.legacyAgentOperationEnvelopeFingerprint=Rce;Ot.persistedAgentOperationMatchesTerms=Zot;Ot.artifactHash=Qot;Ot.prepareAgentOperationV1=Oce;Ot.finalizeAgentOperationV1=Nce;Ot.createAgentOperationV1=tit;Ot.parseHistoricalAgentOperation=rit;Ot.parseAgentOperation=qT;var Rc=require("node:crypto"),wr=Fl(),Ice=PR();_B(PR(),Ot);_B(vce(),Ot);var wR=zu();_B(zu(),Ot);Ot.CARD_ADMISSION_RECOVERY_AUDIENCE="visa:card-admission-recovery:v1";function Wot(e,t){return(0,Rc.createHash)("sha256").update("visa:card-admission-recovery:v1\0","utf8").update((0,wr.canonicalJson)({original:e,replacement:t}),"utf8").digest("base64url")}function mB(e){return(0,Rc.createHash)("sha256").update((0,wR.agentOperationIntentPreimage)(e)).digest("base64url")}function gB(e){return(0,Rc.createHash)("sha256").update((0,wr.canonicalJson)(e)).digest("base64url")}function Yot(e){return(0,Rc.createHash)("sha256").update((0,Ice.purchaseTermsPreimage)(e)).digest("base64url")}function Jot(e,t=Date.now()){let r=qT(e,t);if(r.effect.kind!=="money")throw new wr.AgentOperationContractError("invalid_effect","purchase requires financial economics");let{amountMicros:n,currency:o,merchant:i}=r.effect,s={amountMicros:n,currency:o,merchant:i},a=(0,wr.record)(r.execution.payload,"purchase native payload"),c=r.rail==="wallet:x402"?["scheme","network","asset","payer","typedData","nonce","keyRef",...a.walletBinding===void 0?[]:["walletBinding"],...a.approvedRequest===void 0&&a.requestHash===void 0?[]:["approvedRequest","requestHash"]]:["mandateId","tokenId","processorIntentId","processorAction","captureMode"];if(Object.keys(a).sort().join(",")!==c.sort().join(","))throw new wr.AgentOperationContractError("invalid_contract","purchase producer has unrepresented native fields");let u;if(r.rail==="wallet:x402"&&r.execution.adapter==="wallet.eip3009"){let d=(0,wr.record)(a.typedData,"wallet typed data"),l=(0,wr.record)(d.message,"wallet message");if(a.scheme!=="exact"||l.value!==n)throw new wr.AgentOperationContractError("invalid_amount","wallet value differs from purchase amount");u={rail:r.rail,economics:s,network:a.network,asset:a.asset,payee:l.to,...a.approvedRequest===void 0&&a.requestHash===void 0?{}:{requestHash:a.requestHash}}}else if(r.rail==="card:vic"&&r.execution.adapter==="card.vic")u={rail:r.rail,economics:s,processorAction:a.processorAction,captureMode:a.captureMode};else throw new wr.AgentOperationContractError("invalid_contract","unsupported purchase producer profile");if(a.requestHash!==void 0&&(0,Rc.createHash)("sha256").update((0,wr.canonicalJson)(a.approvedRequest)).digest("base64url")!==a.requestHash)throw new wr.AgentOperationContractError("invalid_contract","purchase request hash mismatch");return(0,Ice.parsePurchaseTerms)({v:1,profile:a.requestHash===void 0?"url_resource_v1":"approved_x402_request_v1",alternatives:[u]}).alternatives[0]}function zot(e){let t=(0,wr.bounded)(e,"x402 resource",2048);return(0,Rc.createHash)("sha256").update(`visa-x402-resource:v1:${t}`,"utf8").digest("base64url")}function Pce(e){return`economic:${(0,Rc.createHash)("sha256").update((0,wr.canonicalJson)({domain:"visa.agent-operation-idempotency.v1",agentId:e.agentId,economicIntentId:e.economicIntentId})).digest("base64url")}`}function Xot(e){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;for(let r of["agentId","purchaseId","attemptId"])if(typeof e[r]!="string"||!t.test(e[r]))throw new wr.AgentOperationContractError("invalid_contract",`${r} must be a canonical UUID`);if(typeof e.termsHash!="string"||!/^[A-Za-z0-9_-]{43}$/.test(e.termsHash)||Buffer.from(e.termsHash,"base64url").toString("base64url")!==e.termsHash)throw new wr.AgentOperationContractError("invalid_contract","termsHash must be canonical SHA-256");return Pce({agentId:e.agentId,economicIntentId:`purchase:${e.purchaseId}:attempt:${e.attemptId}:terms:${e.termsHash}`})}function wce(e){return(0,Rc.createHash)("sha256").update((0,wr.canonicalJson)({domain:"visa.agent-operation-terms.v1",operationId:e.operationId,idempotencyKey:e.idempotencyKey,agentId:e.agentId,runtimeId:e.runtimeId,rail:e.rail,effect:e.effect,execution:e.execution})).digest("base64url")}function Rce(e){return(0,Rc.createHash)("sha256").update((0,wr.canonicalJson)(e)).digest("base64url")}function Zot(e,t,r){return t===r?!0:wce(e)!==r?!1:t===Rce(e)}function Qot(e){return(0,Rc.createHash)("sha256").update((0,wr.canonicalJson)(e)).digest("base64url")}var eit={kind:"identity_pop",popJwt:"unsigned",keyJkt:Buffer.alloc(32).toString("base64url")};function Oce(e,t=Date.now()){let r={v:wR.AGENT_OPERATION_VERSION,...e,principal:eit,intentHash:Buffer.alloc(32).toString("base64url"),execution:{...e.execution,payloadHash:gB(e.execution.payload)}};r.intentHash=mB(r);let n=qT(r,t),{v:o,principal:i,...s}=n;return s}function Nce(e,t,r=Date.now()){return qT({v:wR.AGENT_OPERATION_VERSION,...e,principal:t},r)}function tit(e,t=Date.now()){let{principal:r,...n}=e;return Nce(Oce(n,t),r,t)}function rit(e){let t=(0,wr.record)(e,"historical operation");if(typeof t.createdAt!="string")throw new wr.AgentOperationContractError("invalid_window","historical operation creation time is missing");return qT(e,Date.parse(t.createdAt))}function qT(e,t=Date.now()){let r=(0,wR.parseAgentOperationStructure)(e,t);if(gB(r.execution.payload)!==r.execution.payloadHash)throw new wr.AgentOperationContractError("commitment_mismatch","execution payload does not match its commitment");if(mB(r)!==r.intentHash)throw new wr.AgentOperationContractError("intent_mismatch","intentHash does not bind the exact operation effect and execution commitment");return r}});var $h=_((IUr,oit)=>{oit.exports={name:"@visa/cli",version:"5.0.0-rc.402",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","visa-runtime-converge":"./dist/managed-runtime/resolve-and-update.mjs"},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",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:packed":"node scripts/packed-cli-smoke.mjs","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","coinbase:onramp":"pnpm exec tsx tests/e2e/coinbase-onramp-harness/run.ts","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/ext-apps":"1.7.5","@modelcontextprotocol/server":"2.0.0","@ucp-js/sdk":"0.4.4",commander:"^12.1.0",punycode:"^2.3.1",toml:"^4.3.0",yaml:"^2.9.0",zod:"^3.25.76"},devDependencies:{"@types/express":"^5.0.0","@types/jest":"^30.0.0","@types/node":"^26.1.0","@typescript-eslint/eslint-plugin":"^8.68.0","@typescript-eslint/parser":"^8.68.0","@visa-cli/tools":"workspace:*","@visa/agent-mail":"workspace:*","@visa/crypto":"workspace:*","@visa/financial-core":"workspace:*","@visa/identity":"workspace:*","@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa/shared":"workspace:*","@visa/wallet":"workspace:*","@visa/wallet-tools":"workspace:*",esbuild:"^0.28.1",eslint:"^10.0.2",express:"^4.21.0",jest:"^30.3.0",mppx:"^0.11.0",prettier:"^3.9.6","ts-jest":"^29.4.12",typescript:"^5.7.0",viem:"^2.56.0"},engines:{node:">=20.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","server.json","README.md","native/bin/*/visa-runtime-signer*"]}});async function Nue(e,t,r){let{timeoutMs:n=3e4,...o}=t??{},i=o.signal===void 0&&e instanceof Request?e.signal:o.signal;i?.throwIfAborted();let s=new AbortController,{signal:a}=s,c=()=>s.abort(i?.reason);i?.addEventListener("abort",c,{once:!0});let u,d=new Promise((p,f)=>{u=()=>f(a.reason),a.addEventListener("abort",u,{once:!0})}),l=setTimeout(()=>s.abort(),n);try{return await Promise.race([(async()=>{let p=await fetch(e,{...o,signal:a});a.throwIfAborted();let f=await r(p,a);return a.throwIfAborted(),f})(),d])}finally{clearTimeout(l),i?.removeEventListener("abort",c),a.removeEventListener("abort",u)}}var Cue=R(()=>{"use strict"});var GR,JT,$R,KR,WR,xue=R(()=>{"use strict";GR=class extends Error{code="ATTESTATION_KEY_DRIFT";kind="attestation";nextAction="visa disconnect --all";fix="Run `visa disconnect --all` to clear the stale device credential, then `visa connect` to enroll again.";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}},JT=class extends Error{code="session_required";kind="session";nextAction="visa connect";fix="visa connect";status;constructor(t,r){super(t),this.name="SessionRequiredError",this.status=r}},$R=class extends Error{code="server_unavailable";kind="server";nextAction=void 0;fix;status;retryable;constructor(t,r=503,n=!0){super(t),this.name="ServerUnavailableError",this.status=r,this.retryable=n,this.fix=n?"Wait a moment and retry. If the outage persists check https://visacli.sh for status.":"Do not retry this request automatically; inspect the server error and reconcile the existing attempt."}},KR=class extends Error{code="surface_disabled";kind="server";nextAction=void 0;fix="This surface is disabled or not configured on the server (kill switch or missing config). Escalate to a human \u2014 retrying will not help.";status;disabledSurface;flag;correlationId;constructor(t,r={}){super(t),this.name="SurfaceDisabledError",this.status=r.status??503,this.disabledSurface=r.disabledSurface,this.flag=r.flag,this.correlationId=r.correlationId}},WR=class extends Error{constructor(r,n){super(r);this.retryAfterSeconds=n;this.name="RateLimitError",this.nextAction=void 0,this.fix=`Wait ${n}s before retrying.`}retryAfterSeconds;code="rate_limited";kind="rate_limit";fix;status=429;nextAction=void 0}});function ast(){return Object.fromEntries(ist.map(e=>[e,sst]))}function RB(e){if(!e||typeof e!="object")return null;let t=e,n=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return typeof n=="string"&&n.length>0?n:null}function YR(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=RB(e);return r&&Mue[r]?Mue[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 ist,sst,Mue,OB=R(()=>{"use strict";ist=["UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_UNTRUSTED"],sst="This machine does not trust the certificate offered for the Visa CLI server, so the request never left it. The server is not down, and neither retrying nor signing in again can help. A network that inspects TLS traffic does this: point Node at its root certificate with NODE_EXTRA_CA_CERTS=/path/to/root.pem, or use a network that does not inspect. Do not disable certificate verification.";Mue={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.",...ast(),ERR_TLS_CERT_ALTNAME_INVALID:"The certificate offered for the Visa CLI server is for a different hostname. Check the auth.serverUrl setting. Do not disable certificate verification.",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 Lue(){return`Run ${cst} or call ${ust}, open the printed URL, enter the code at ${dst}, approve the device and its limits, then pay with the pay tool. Do not retry the retired command; nothing was signed, paired, or paid.`}var cst,ust,dst,YUr,JUr,zUr,Due=R(()=>{"use strict";cst="visa connect",ust="agent_enroll",dst="/agent/enroll/protected-agent",YUr=Object.freeze(["setup_start","setup_status","setup_resume","setup_cancel","setup_agent","enroll_agent","agent_pairing_cancel","agent_handoff_claim","agent_connect","agent_connect_cancel","agent_connect_poll","feedback"]),JUr=Object.freeze(["create","verify","enroll-claim","pair","claim","pairing-resume","cancel","handoff-claim","connect","grant-wallet","grant-card","grant-activate","grant-claim","grants","grant-cancel","grant-batch"]),zUr=Object.freeze(["setup","agent","wallet","find","inspect","receipt","connections","keys","security","checkout","mandate","logout","capabilities","feedback","status","pay","purchase","limits","fund","activity"])});var zR,NB,kue,JR,Uue=R(()=>{"use strict";zR=j(require("fs")),NB=j(require("path")),kue=j(require("os")),JR=class{static ensureConfigDir(){let t=this.getConfigDir();zR.existsSync(t)||zR.mkdirSync(t,{recursive:!0,mode:448})}static getConfigDir(){let t=process.env.VISA_CLI_HOME;return typeof t=="string"&&t.trim().length>0?NB.join(t,".visa-mcp"):NB.join(kue.homedir(),".visa-mcp")}}});function fst(){Ii.existsSync(xB)||Ii.mkdirSync(xB,{recursive:!0,mode:448})}function pst(){if(!CB){if(fst(),Ii.existsSync(zT)&&Ii.statSync(zT).size>lst){let t=zT+".1";Ii.existsSync(t)&&Ii.unlinkSync(t),Ii.renameSync(zT,t)}CB=Ii.createWriteStream(zT,{flags:"a"})}return CB}function _st(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"}function XR(e,...t){let r=new Date().toISOString(),n=t.map(i=>typeof i=="string"?i:JSON.stringify(i,null,2)).join(" "),o=`[${r}] [${e}] ${n}
5
5
  `;_st(e)&&process.stderr.write(o),pst().write(o)}var Ii,MB,jue,xB,zT,lst,CB,Me,Ms=R(()=>{"use strict";Ii=j(require("fs")),MB=j(require("path")),jue=j(require("os")),xB=MB.join(jue.homedir(),".visa-mcp"),zT=MB.join(xB,"mcp-server.log"),lst=5*1024*1024,CB=null;Me={debug:(...e)=>XR("DEBUG",...e),info:(...e)=>XR("INFO",...e),warn:(...e)=>XR("WARN",...e),error:(...e)=>XR("ERROR",...e)}});function Bue(e){let t=que.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function hst(){return Vue.join(JR.getConfigDir(),mst)}function Fue(e){if((0,LB.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Est(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 o=[r>>8&255,r&255,n>>8&255,n&255].join(".");return Fue(o)}function yst(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,LB.isIP)(t);return r===4?Fue(t):r===6?t==="::1"||Est(t):!1}function Hue(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:"&&yst(r.hostname)))throw new Error(`${t} ${gst}`)}function Gue(){let e=hst();if(!Jh.existsSync(e))return{};try{let t=Jh.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Me.warn("settings:corrupt",{path:Bue(e),reason:"not_object"}),{}):r}catch(t){return Me.warn("settings:corrupt",{path:Bue(e),error:t?.message||String(t)}),{}}}function DB(e){let t=Gue()[e];return typeof t=="string"?t:void 0}function Sst(e){let t=Gue()[e];return typeof t=="boolean"?t:void 0}function bst(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Ast(){try{let e=$h();return bst(e.version)}catch{return!1}}function vst(e){return e.envVar!==void 0&&e.envVar!==""?(Hue(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Hue(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?kB:Tst}function Yl(){return vst({envVar:process.env.VISA_AUTH_URL,settingValue:DB("auth.serverUrl"),isPrerelease:Ast()})}function $ue(e=process.env){let t=[e.VISA_SUPPRESS_BROWSER,e.VISA_CLI_NO_BROWSER,e.CHECKOUT_SKIP_BROWSER_OPEN];return t.some(r=>r==="true"||r==="1")?!0:t.some(r=>r!==void 0)?!1:Sst("ui.suppressBrowser")??!1}var Jh,LB,que,Vue,mst,gst,Tst,kB,B_=R(()=>{"use strict";Jh=j(require("fs")),LB=require("node:net"),que=j(require("os")),Vue=j(require("path"));Uue();Ms();mst="settings.json",gst="must use https unless it points at localhost/loopback for local development";Tst="https://auth.visacli.sh",kB="https://auth-visa-code-preview.up.railway.app"});function XT(e){return UB(e)!==null}function jB(e,t){let r=UB(e),n=UB(t);if(!r||!n)return!1;for(let o=0;o<3;o++)if(r.main[o]!==n.main[o])return r.main[o]>n.main[o];return r.pre&&!n.pre?!1:!r.pre&&n.pre?!0:!r.pre&&!n.pre?!1:Pst(r.pre,n.pre)>0}function UB(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(Ist);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function Pst(e,t){let r=e.split("."),n=t.split("."),o=Math.max(r.length,n.length);for(let i=0;i<o;i++){if(i>=r.length)return-1;if(i>=n.length)return 1;let s=r[i],a=n[i],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 Ist,ZR=R(()=>{"use strict";Ist=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/});function QR(e,t,r){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},o=e<200||e>=300||n.ok===!1||n.success===!1;if(e!==426&&!(o&&[n.error,n.code,n.error_code,n.errorCode].includes("update_required")))return null;let i=(s,a)=>typeof s=="string"&&s.length<=64&&!/[^0-9A-Za-z.+-]/.test(s)&&XT(s)?s.replace(/^v/,""):a;return new ZT(i(n.runningVersion,r),i(n.minCompatibleVersion,BB))}function Kue(e){let t=e||Yl();return process.env.VISA_ENVIRONMENT==="staging"||t.includes("staging")||t.includes("up.railway.app")||t.includes("preview")?"staging":process.env.VISA_ENVIRONMENT==="production"||t.includes("auth.visacli.sh")?"production":"development"}var BB,ZT,QT=R(()=>{"use strict";B_();ZR();BB="4.1.0-rc.70",ZT=class extends Error{code="update_required";errorCode="update_required";runningVersion;minCompatibleVersion;updateCommand;constructor(t,r,n){let o=`CLI/MCP update required${n?` for ${n}`:""}: running v${t}, minimum compatible version is v${r}. Run: npm install -g @visa/cli@rc`;super(o),this.name="UpdateRequiredError",this.runningVersion=t,this.minCompatibleVersion=r,this.updateCommand="npm install -g @visa/cli@rc"}toJSON(){return{success:!1,error_code:this.errorCode,error:this.message,runningVersion:this.runningVersion,minCompatibleVersion:this.minCompatibleVersion,updateCommand:this.updateCommand}}}});function zh(){return!!(Wue(process.env.VISA_CLI_NO_UPDATE_CHECK)||Wue(process.env.CI)||process.env.NODE_ENV==="test")}function Wue(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var eO=R(()=>{"use strict"});function wst(){return qB||(qB=`ms_${(0,Jue.randomUUID)().replace(/-/g,"")}`),qB}function Rst(){return HB?Yue?`${HB}/${Yue}`.slice(0,96):HB:null}function Xh(){let e={"X-Visa-MCP-Session":wst()},t=Rst();return t&&(e["X-Visa-MCP-Client"]=t),e}var Jue,HB,Yue,qB,tO=R(()=>{"use strict";Jue=require("node:crypto"),HB=null,Yue=null,qB=null});function xst(e){if(e===null||!/^\d{1,4}$/.test(e))return 3;let t=Number(e);return Number.isSafeInteger(t)&&t>=1&&t<=3600?t:3}function Lst(e,t){if(e===410&&(t?.code==="route_retired"||t?.error==="route_retired"))return new Xt(typeof t?.message=="string"&&t.message.length>0?t.message:"This legacy agent setup route was removed.","legacy_door_removed",{nextAction:Lue(),details:{stage:"retired_door",...typeof t?.replacement=="string"?{replacement:t.replacement}:{}}});if(t?.error==="capability_attach_state_conflict"&&t?.attachId){let c=t.expiresAt?` (expires ${t.expiresAt})`:"",u=t.state?` in state '${t.state}'`:"";return new Tr(`A pending capability-attach ceremony (${t.attachId}) is already${u}${c}. Cancel it in the Visa Console, or wait for it to expire.`,e,"capability_attach_state_conflict",void 0,!1)}if((t?.reason==="policy_step_up_required"||t?.error==="spend_policy_step_up_required")&&typeof t?.stepUp?.reviewUrl=="string")return new Tr(`Owner confirmation required before this payment. Ask the owner to review it at ${t.stepUp.reviewUrl}. Nothing was paid.`,e,typeof t?.error=="string"?t.error:void 0,"policy_step_up_required",!1);if(t?.error==="owner_approval_required"&&t?.approval&&typeof t.approval=="object"&&!Array.isArray(t.approval))return new Tr(typeof t?.message=="string"&&t.message?t.message:"owner_approval_required",e,"owner_approval_required",void 0,!1,{approval:t.approval});let r=typeof t?.error=="string"?t.error:typeof t?.code=="string"&&Mst.has(t.code)?t.code:void 0,n=typeof t?.reason=="string"?t.reason:void 0,o=typeof t?.retryable=="boolean"?t.retryable:void 0,i=typeof t?.message=="string"&&t.message||n||r||"";if(i)return new Tr(i,e,r,n,o);let s=e>=500||e===408||e===425||e===429;return o??s?new Tr(`Request failed (${e}). Try again.`,e,void 0,void 0,o):e===404?new Tr(`Request failed (${e}) \u2014 not found; check the identifier or slug.`,e,void 0,void 0,o):new Tr(`Request failed (${e}).`,e,void 0,void 0,o)}function Da(e){return typeof e=="string"?e.trim():""}function kst(e){let t=Da(e.error_code)||Da(e.error);return t?t==="SURFACE_DISABLED"||/(_disabled|_not_configured)$/.test(t):!1}function Ust(e){let t=e&&typeof e=="object"?e:{},r=Da(t.error)||Da(t.message);if(!r)return Dst;let n=Da(t.error_code),o=[["surface",Da(t.disabled_surface)],["flag",Da(t.flag)],["correlation_id",Da(t.correlation_id)]].filter(([,s])=>s).map(([s,a])=>`${s}=${a}`),i=o.length?` (${o.join(" ")})`:"";return n?`503 [${n}] ${r}${i}`:`503 ${r}${i}`}function jst(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&&(Nst.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("Run `visa connect` to sign in and connect this device session."),t===!1&&r.push("Complete sign-in in a normal terminal with `visa connect`, then restart the MCP client."),r.join(`
6
- `)}function ed(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Zu(e){return e===null||typeof e=="string"}function Qu(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function Bst(e){if(!ed(e))throw new Error("account activity returned a malformed entry");let t=e.rail;if(t!=="card"&&t!=="x402")throw new Error("account activity entry is missing a valid rail label");let r=e.amountUsd,n={id:e.id,operationId:e.operationId,merchant:e.merchant,description:e.description,currency:e.currency,status:e.status,createdAt:e.createdAt};for(let[o,i]of Object.entries(n))if(typeof i!="string"||i.length===0)throw new Error(`account activity entry is missing ${o}`);if(typeof r!="number"||!Number.isFinite(r))throw new Error("account activity entry is missing a numeric amount");return{id:n.id,operationId:n.operationId,merchant:n.merchant,description:n.description,amountUsd:r,currency:n.currency,status:n.status,rail:t,createdAt:n.createdAt,...Qu(e,"failurePhase")?{failurePhase:e.failurePhase}:{},...Qu(e,"finalizesBy")?{finalizesBy:e.finalizesBy}:{},...Qu(e,"agentId")?{agentId:e.agentId}:{},...Qu(e,"agentName")?{agentName:e.agentName}:{},...Qu(e,"grantId")?{grantId:e.grantId}:{},...Qu(e,"mandateId")?{mandateId:e.mandateId}:{},...Qu(e,"drawId")?{drawId:e.drawId}:{},...Qu(e,"transactionHash")?{transactionHash:e.transactionHash}:{},...Qu(e,"transactionNetwork")?{transactionNetwork:e.transactionNetwork}:{}}}function Hst(e){if(!ed(e))return null;let{payment:t,route:r,party:n,authority:o,outcome:i}=e;return e.schemaVersion!==1||typeof e.operationId!="string"||typeof e.activityId!="string"||!ed(t)||typeof t.amountAtomic!="string"||typeof t.decimals!="number"||!Number.isSafeInteger(t.decimals)||t.decimals<0||typeof t.currency!="string"||typeof t.merchant!="string"||typeof t.description!="string"||typeof t.createdAt!="string"||!ed(r)||r.rail!=="wallet"&&r.rail!=="card"||!Zu(r.protocol)||!Zu(r.network)||!Zu(r.cardLast4)||!ed(n)||!Zu(n.agentId)||!Zu(n.agentName)||!ed(o)||!Zu(o.grantId)||!Zu(o.mandateId)||!Zu(o.drawId)||!ed(i)||typeof i.status!="string"||typeof i.proofLevel!="string"||typeof i.final!="boolean"||typeof i.updatedAt!="string"||!Zu(i.finalizesBy)||!Array.isArray(e.evidence)||!e.evidence.every(ed)||!Array.isArray(e.timeline)||!e.timeline.every(ed)||e.dataCompleteness!=="complete"&&e.dataCompleteness!=="partial"?null:e}var eb,Ost,Nst,Cst,Tr,rO,Mst,Dst,Ls,td=R(()=>{"use strict";Cue();xue();OB();vc();Due();QT();ZR();eO();B_();tO();eb="5.0.0-rc.401",Ost="1",Nst=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/,Cst=5e3,Tr=class extends Error{constructor(r,n,o,i,s,a){super(r);this.status=n;this.code=o;this.detail=i;this.serverRetryable=s;this.details=a;this.name="ApiHttpError"}status;code;detail;serverRetryable;details;get retryable(){return this.serverRetryable??(this.status>=500||this.status===408||this.status===425||this.status===429)}};rO=class extends Error{constructor(r){super("Failed to retrieve task: Task not found");this.taskId=r;this.name="McpTaskNotFoundError"}taskId;rpcCode=-32602},Mst=new Set(["agent_paused","agent_revoked","device_key_replaced","grant_expired","owner_withdrawal_pending"]);Dst="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";Ls=class{constructor(t){this.getSessionToken=t;this.baseUrl=Yl()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!zh()){let r=t.headers.get("X-Latest-Version");r&&jB(r,eb)&&(this.lastSignals.updateAvailable={currentVersion:eb,latestVersion:r})}}getClientVersion(){return eb}getAuthServerOrigin(){return this.baseUrl}async signUcpRequest(t){let r=await this.request("POST","/v4/ucp/sign",t,15e3);if(!r||typeof r!="object"||Array.isArray(r)||!r.headers||typeof r.headers!="object"||Array.isArray(r.headers))throw new Error("UCP signing service returned a malformed response");let n=r.headers,o=Object.keys(n).sort(),i=["content-digest","signature","signature-input"];if(o.length!==i.length||o.some((s,a)=>s!==i[a])||i.some(s=>typeof n[s]!="string"||n[s].length===0||n[s].length>16384||/[\r\n]/.test(n[s])))throw new Error("UCP signing service returned invalid signature headers");return n}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new GR(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{}let n=Ust(r),o=r&&typeof r=="object"?r:{};throw kst(o)?new KR(n,{status:t.status,disabledSurface:Da(o.disabled_surface)||void 0,flag:Da(o.flag)||void 0,correlationId:Da(o.correlation_id)||void 0}):new $R(n,t.status,typeof o.retryable=="boolean"?o.retryable:!0)}async financialRuntimeRequest(t,r){return this.request("POST",`/v1/financial-runtime/${t}`,r,2e4)}async identityDeviceRequest(t,r){return this.request("POST",`/v1/identity-device/${t}`,r,2e4)}async request(t,r,n,o,i){let s=await this.getSessionToken();if(!s)throw new JT(jst());let a={Authorization:`Bearer ${s}`};i&&(t==="GET"?a["X-User-Context"]=encodeURIComponent(i.replace(/[\r\n\0]/g," ").slice(0,1e3)):n={...n||{},user_context:i}),n&&(a["Content-Type"]="application/json");let c;try{c=await Nue(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":eb,"X-Visa-Agent-Operations-Version":Ost,"X-Source":"cli",...Xh()},body:n?JSON.stringify(n):void 0,timeoutMs:o})}catch(d){let l=new Error(YR(d)),p=RB(d);throw p&&(l.code=p),l}if(this.parseServerSignals(c),c.status===401)throw new JT("Your device session has expired. Run `visa connect` to refresh it (the device is already enrolled).",c.status);if(c.status===429){let d=xst(c.headers.get("Retry-After"));throw new WR(`Rate limited \u2014 wait ${d}s, then retry.`,d)}c.status===503&&await this.throwServerUnavailable(c);let u;try{u=await c.json()}catch{if(c.status===500)throw new Tr(`Server error on ${r}. Try again or check https://visacli.sh for status.`,c.status);if(!c.ok){let d=c.status>=500||c.status===429||t==="GET"&&(c.status===408||c.status===425);throw new Tr(d?`Unexpected response from ${r}. Try again.`:`Unexpected response from ${r} (${c.status}).`,c.status,void 0,void 0,d)}throw new Error(`Unexpected response from ${r}.`)}if(!c.ok){if(c.status===426||u?.error==="update_required"||u?.error_code==="update_required"||u?.errorCode==="update_required"){let d=typeof u?.runningVersion=="string"?u.runningVersion:eb,l=typeof u?.minCompatibleVersion=="string"?u.minCompatibleVersion:BB;throw new ZT(d,l,r)}if(c.status===500){let d=typeof u?.retryable=="boolean"?u.retryable:void 0;throw new Tr(d===!1?`Server error on ${r}. Inspect the server error and reconcile the existing attempt.`:`Server error on ${r}. Try again or check https://visacli.sh for status.`,c.status,typeof u?.error=="string"?u.error:void 0,typeof u?.reason=="string"?u.reason:void 0,d)}throw this.throwIfAttestationDrift(u),Lst(c.status,u)}return u}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t},Cst)}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),t.verify&&n.set("verify",t.verify),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 merchantDirectoryCertified(t){return this.request("GET","/v1/merchant-directory/certified",void 0,void 0,t)}async getAccountActivity(t,r){let n=new URLSearchParams;t!==void 0&&n.set("limit",String(t)),r!==void 0&&n.set("agentId",r);let o=n.size>0?`?${n.toString()}`:"",i=await this.request("GET",`/v4/account/activity${o}`);if(!i||!Array.isArray(i.activity))throw new Error("account activity service returned an invalid response");return i.activity.map(Bst)}async getAccountActivityReceipt(t){let r;try{r=await this.request("GET",`/v4/account/activity/${encodeURIComponent(t)}`)}catch(o){throw o instanceof Tr&&o.status===404?new Xt(`account activity entry not found: ${t}`,"activity_entry_not_found"):o}let n=Hst(r);if(!n)throw new Error("account receipt service returned an invalid or unsupported response");return n}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 listAccountAgents(){try{let t=await this.request("GET","/v4/account/agents");return!t||!Array.isArray(t.agents)?null:t.agents.flatMap(r=>{if(!r||typeof r!="object")return[];let n=r,o=typeof n.agentId=="string"&&n.agentId.length>0?n.agentId:null,i=typeof n.agentJkt=="string"&&n.agentJkt.length>0?n.agentJkt:null;if(o===null&&i===null)return[];let s=n.approvedAuthority,a=s&&typeof s=="object"&&typeof s.grantId=="string"&&typeof s.status=="string"&&typeof s.totalMicros=="string"&&typeof s.perTransactionMicros=="string"&&typeof s.spentMicros=="string"&&typeof s.reservedMicros=="string"&&Array.isArray(s.scopes)?(()=>{let f=s;return{grantId:f.grantId,status:f.status,totalMicros:f.totalMicros,perTransactionMicros:f.perTransactionMicros,spentMicros:f.spentMicros,reservedMicros:f.reservedMicros,scopes:f.scopes.filter(m=>typeof m=="string"),...typeof f.expiresAt=="string"?{expiresAt:f.expiresAt}:{}}})():void 0,c=f=>typeof n[f]=="string"&&n[f].length>0?n[f]:void 0,u=n.executionReadiness,d=u&&typeof u=="object"&&!Array.isArray(u)?(()=>{let f=u,m=["shared","card","wallet"];if(Object.keys(f).some(E=>!m.includes(E))||Object.values(f).some(E=>typeof E!="string"))return;let h=Object.fromEntries(m.filter(E=>E in f).map(E=>[E,f[E]]));return Object.keys(h).length>0?h:void 0})():void 0,l=n.wallet,p=l&&typeof l=="object"&&!Array.isArray(l)?(()=>{let f=l,m=b=>typeof f[b]=="string"?{[b]:f[b]}:{},h=b=>typeof f[b]=="number"&&Number.isFinite(f[b])?{[b]:f[b]}:{},E={...m("walletAddress"),...m("network"),...typeof f.provisioned=="boolean"?{provisioned:f.provisioned}:{},...h("totalLimitCents").totalLimitCents!==void 0?h("totalLimitCents"):typeof f.dailyLimitCents=="number"&&Number.isFinite(f.dailyLimitCents)?{totalLimitCents:f.dailyLimitCents}:{},...h("perTransactionLimitCents")};return Object.keys(E).length>0?E:void 0})():void 0;return[{agentId:o,agentJkt:i,name:typeof n.name=="string"?n.name:"",revoked:n.revoked===!0,paused:n.paused===!0,...a?{approvedAuthority:a}:{},...c("executionStatus")?{executionStatus:c("executionStatus")}:{},...c("executionStatusReason")?{executionStatusReason:c("executionStatusReason")}:{},...d?{executionReadiness:d}:{},...c("identityKeyStatus")?{identityKeyStatus:c("identityKeyStatus")}:{},...c("tapStatus")?{tapStatus:c("tapStatus")}:{},...p?{wallet:p}:{}}]})}catch{return null}}async listAccountCardMandates(){try{let t=await this.request("GET","/v4/account/card-mandates?includeInactive=1&limit=200");return!t||!Array.isArray(t.mandates)?null:t.mandates.flatMap(r=>{if(!r||typeof r!="object")return[];let n=r;return typeof n.mandateId!="string"||n.mandateId.length===0?[]:[{mandateId:n.mandateId,revokedAt:typeof n.revokedAt=="string"?n.revokedAt:null,expiresAt:typeof n.expiresAt=="string"?n.expiresAt:null}]})}catch{return null}}async revokeAccountCardMandate(t){try{return await this.request("POST",`/v4/account/card-mandates/${encodeURIComponent(t)}/revoke`)}catch{return null}}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async logout(t,r){return this.request("POST","/v4/logout",t,void 0,r)}async putMcpTask(t,r){return this.request("PUT",`/v1/mcp-tasks/${encodeURIComponent(t)}`,r)}async getMcpTask(t){try{return await this.request("GET",`/v1/mcp-tasks/${encodeURIComponent(t)}`)}catch(r){throw r instanceof rO?r:r instanceof Tr&&r.status===404?new rO(t):r}}async revokeSpendingAuthority(t){let r=await this.request("POST",`/v4/agents/${encodeURIComponent(t)}/spending-authority/revoke`,{});if(typeof r?.revoked!="boolean")throw new Error("spending authority revoke service returned an invalid response");return{revoked:r.revoked}}async claimAgentForApp(t,r,n){return{claimed:(await this.request("POST","/v4/account/agent-apps",{agentId:t,harnessId:r,...n?{deviceName:n}:{}}))?.claimed===!0}}async signTurnkeyTapPayload(t,r){let n=await this.request("POST",`/v4/account/agents/${encodeURIComponent(t)}/keychain/tap-sign`,{signatureBase:r});if(typeof n.signature!="string"||typeof n.keyId!="string")throw new Error("TAP signing service returned an invalid response");return{signature:n.signature,keyId:n.keyId}}}});var NO=_((Gjr,rfe)=>{"use strict";var Vat=Object.create,TO=Object.defineProperty,Fat=Object.getOwnPropertyDescriptor,tle=Object.getOwnPropertyNames,Gat=Object.getPrototypeOf,$at=Object.prototype.hasOwnProperty,Kat=(e,t)=>function(){try{return t||(0,e[tle(e)[0]])((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Wat=(e,t)=>{for(var r in t)TO(e,r,{get:t[r],enumerable:!0})},rle=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of tle(t))!$at.call(e,o)&&o!==r&&TO(e,o,{get:()=>t[o],enumerable:!(n=Fat(t,o))||n.enumerable});return e},nle=(e,t,r)=>(r=e!=null?Vat(Gat(e)):{},rle(t||!e||!e.__esModule?TO(r,"default",{value:e,enumerable:!0}):r,e)),Yat=e=>rle(TO({},"__esModule",{value:!0}),e),Jat=Kat({"../shared/dist/canonical-contract.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CanonicalJsonError=e.CANONICAL_OPAQUE_ID_MAX_BYTES=e.CANONICAL_OPAQUE_ID_RE=e.CANONICAL_OPAQUE_ID_PATTERN=void 0,e.utf8ByteLength=n,e.isCanonicalText=o,e.compareCanonicalKeys=i,e.isCanonicalOpaqueId=s,e.assertCanonicalOpaqueId=a,e.canonicalJsonExact=d,e.CANONICAL_OPAQUE_ID_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$",e.CANONICAL_OPAQUE_ID_RE=new RegExp(e.CANONICAL_OPAQUE_ID_PATTERN),e.CANONICAL_OPAQUE_ID_MAX_BYTES=128;var t=/[\u0000-\u001f\u007f\u2028\u2029]/,r=new TextEncoder;function n(l){return r.encode(l).length}function o(l,p){return typeof l=="string"&&l.length>0&&n(l)<=p&&l.trim()===l&&l.normalize("NFC")===l&&!t.test(l)}function i(l,p){let f=r.encode(l),m=r.encode(p),h=Math.min(f.length,m.length);for(let E=0;E<h;E+=1)if(f[E]!==m[E])return f[E]-m[E];return f.length-m.length}function s(l){return typeof l=="string"&&n(l)<=e.CANONICAL_OPAQUE_ID_MAX_BYTES&&e.CANONICAL_OPAQUE_ID_RE.test(l)}function a(l,p="value"){if(!s(l))throw new Error(`${p} must be a canonical opaque id (max 128 ASCII bytes)`)}var c=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,u=class extends Error{constructor(l){super(l),this.name="CanonicalJsonError"}};e.CanonicalJsonError=u;function d(l,p=0){if(p>16)throw new u("nesting is deeper than 16");if(l===null||typeof l=="boolean")return JSON.stringify(l);if(typeof l=="string"){if(c.test(l))throw new u("text is not valid Unicode");return JSON.stringify(l)}if(typeof l=="number"){if(!Number.isSafeInteger(l)||Object.is(l,-0))throw new u("numbers must be whole and at most 2^53 - 1; put amounts and decimals in strings");return JSON.stringify(l)}if(Array.isArray(l)){if(l.length>1024)throw new u("an array has more than 1024 items");return`[${l.map(m=>d(m,p+1)).join(",")}]`}if(typeof l!="object"||Object.getPrototypeOf(l)!==Object.prototype)throw new u("only JSON objects, arrays, strings, whole numbers and booleans");let f=Object.keys(l);if(f.length>512)throw new u("an object has more than 512 keys");for(let m of f)if(!o(m,128))throw new u("keys must be non-empty trimmed NFC text of at most 128 bytes");return`{${f.sort(i).map(m=>`${JSON.stringify(m)}:${d(l[m],p+1)}`).join(",")}}`}}}),ole={};Wat(ole,{AGENT_AUTHORITY_VALUATION_POLICY:()=>mO,AGENT_AUTHORITY_VERSION:()=>sd,AGENT_AUTHORIZATION_SCOPES:()=>K_,AGENT_BUDGET_EPOCH_MODES:()=>Lle,AGENT_CAPABILITY_ATTACH_CAPABILITIES:()=>$le,AGENT_CHANNEL_ASSURANCES:()=>jle,AGENT_CHANNEL_KINDS:()=>kle,AGENT_CHANNEL_STATUSES:()=>Ule,AGENT_EXECUTION_READINESS_REASONS:()=>out,AGENT_HANDOFF_AUTHORITIES:()=>but,AGENT_HANDOFF_COMPOUND_AUTHORITY:()=>RH,AGENT_KEY_CUSTODIES:()=>iut,AGENT_KEY_STATUSES:()=>sut,AGENT_PAIRING_CODE_ALPHABET:()=>aE,AGENT_PAIRING_CODE_LENGTH:()=>lb,AGENT_PAIRING_PROTOCOL_VERSION:()=>vut,AGENT_PAIRING_PROTOCOL_VERSION_V2:()=>yO,AGENT_PAYMENT_MODE_NAMES:()=>rut,AGENT_PAYMENT_RAILS:()=>lH,AGENT_PAYMENT_SURFACES:()=>dH,DOMAINS:()=>Vct,USD_MICROS_PER_CENT:()=>AH,VIC_PROCESSOR_ACTIONS:()=>tut,WALLET_GRANT_SCOPE:()=>Dle,agentAuthorityGrantHash:()=>Sut,agentMailCredentialClaimMessageV2:()=>Zut,authorizationScopeFacts:()=>hut,base64ToBytes:()=>Rle,base64UrlToBytes:()=>IO,bytesToBase64:()=>wle,bytesToBase64Url:()=>ad,bytesToHex:()=>Ple,canonicalAgentAuthorityGrant:()=>PH,canonicalAgentChannelDescriptor:()=>yut,canonicalFormAgent:()=>Fct,canonicalPairingDeliveryArtifactV2:()=>tfe,canonicalPairingTerms:()=>Xle,canonicalPairingTermsV2:()=>xH,canonicalPayWithinBudget:()=>Fle,canonicalSpendAuthorizationIntent:()=>wH,centsToUsdMicros:()=>mut,computeJkt:()=>xle,concatBytes:()=>bH,defaultPayWithinBudget:()=>nut,extractEd25519Seed:()=>eut,formatPairingCode:()=>OO,generateKeyPair:()=>kct,generateSeed:()=>vle,getPublicKey:()=>vO,grantPaymentRails:()=>vH,handoffAuthorityCapabilities:()=>Aut,hexToBytes:()=>TH,isCanonicalBase64Url32:()=>us,isValidPairingCode:()=>Jle,jwkToKeyPair:()=>Wct,jwkToPublicKey:()=>Kct,jwkToSeed:()=>Cle,keyPairFromSeed:()=>Ile,keyRotationClaimHashV2:()=>Xut,keyRotationClaimMessageV2:()=>efe,normalizePairingCode:()=>RO,pairingActivationMessage:()=>Yut,pairingActivationMessageV2:()=>zut,pairingArtifactHash:()=>edt,pairingClaimHashV2:()=>Jut,pairingClaimMessage:()=>Wut,pairingClaimMessageV2:()=>Qle,pairingClaimTokenHash:()=>zle,pairingCodeFromClaimToken:()=>Gut,pairingCodeHash:()=>Vut,pairingConfirmationCode:()=>$ut,pairingDeliveryArtifactV2Hash:()=>Qut,pairingInstrumentCommitment:()=>Uut,pairingSha256:()=>Lc,pairingTermsHash:()=>Kut,pairingTermsV2Hash:()=>Zle,pairingVerifierChallenge:()=>Hut,pkcs8ToSeed:()=>Zct,publicKeyToJwk:()=>$ct,publicKeyToSpki:()=>Xct,randomPairingClaimToken:()=>Fut,randomPairingCode:()=>qut,randomPairingId:()=>jut,randomPairingVerifier:()=>But,seedToJwk:()=>Gct,seedToPkcs8:()=>zct,sign:()=>Uct,signAsync:()=>Bct,spendAuthorizationIntentHash:()=>Gle,spkiToPublicKey:()=>Qct,subwayAgentMsgV1:()=>Ole,usdcAtomicToUsdMicros:()=>gut,verify:()=>jct,verifyAsync:()=>Hct,walletAuthorizationRequestHash:()=>Tut});rfe.exports=Yat(ole);var bO=Object.freeze,sE=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,gO=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,pO=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,aH=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,cH=0x6666666666666666666666666666666666666666666666666666666666666658n,_O=sE-1n,zat=bO({p:sE,n:gO,h:8n,a:_O,d:pO,Gx:aH,Gy:cH}),Zl=32,Ude=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,cs=(e,t,r="")=>{if(Ude(e)&&(t===void 0||e.length===t))return e;let n=Ude(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=(r?`"${r}" `:"")+"expected Uint8Array"+o+", got "+i;throw n?new RangeError(s):new TypeError(s)},AO=(e,t="",r)=>Uint8Array.from(cs(e,r,t)),ile=(e,t)=>e.toString(16).padStart(t,"0"),_H=e=>{let t="";for(let r of cs(e))t+=ile(r,2);return t},mH=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let r=new Uint8Array(e.length/2);for(let n=0,o=0;n<r.length;n++,o+=2){let i=e.charCodeAt(o),s=e.charCodeAt(o+1);r[n]=((i&15)+(i>>6)*9)*16+(s&15)+(s>>6)*9}return r},J_=(...e)=>{let t=0;for(let o of e)t+=cs(o).length;let r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r},sle=(e=Zl)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},V_=(e,t,r,n="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},er=(e,t=sE)=>(e%=t)>=0n?e:t+e,jde=(1n<<255n)-1n,ce=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&jde);return t=(t>>255n)*19n+(t&jde),t%sE},ale=e=>er(e,gO),cle=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let r=er(e,t),n=t,o=0n,i=1n;for(;r!==0n;){let a=n/r,c=n-r*a,u=o-i*a;n=r,r=c,o=i,i=u}if(n!==1n)throw new Error("invert: does not exist");return er(o,t)},ule=e=>{let t=Ele[e];if(typeof t!="function")throw new Error("hashes."+e+" not set");return t},gH=(e,...t)=>cs(ule(e)(J_(...t)),64,"digest"),hH=async(e,...t)=>cs(await ule(e)(J_(...t)),64,"digest"),iH=e=>{if(e instanceof z_)return e;throw new TypeError("Point expected")},dle=2n**256n,z_=class F_{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,o){let i=dle;this.X=V_(t,0n,i),this.Y=V_(r,0n,i),this.Z=V_(n,1n,i),this.T=V_(o,0n,i),bO(this)}static CURVE(){return zat}static fromAffine(t){return new F_(t.x,t.y,1n,ce(t.x*t.y))}static fromBytes(t,r=!1){let n=AO(t,"point",Zl),o=n[31];n[31]=o&-129;let i=EH(n);r||V_(i,0n,sE);let s=ce(i*i),a=er(s-1n),c=ce(pO*s+1n),{isValid:u,value:d}=Zat(a,c);if(!u)throw new Error("bad point: y not sqrt");let l=!!(o&128);if(!r&&d===0n&&l)throw new Error("bad point: x==0, isLastByteOdd");return l!==!!(d&1n)&&(d=er(-d)),new F_(d,i,1n,ce(d*i))}static fromHex(t,r){return F_.fromBytes(mH(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=_O,r=pO,n=this;if(n.is0())throw new Error("bad point: ZERO");let{X:o,Y:i,Z:s,T:a}=n,c=ce(o*o),u=ce(i*i),d=ce(s*s),l=ce(d*d),p=ce(c*t),f=ce(d*(p+u)),m=er(l+ce(r*ce(c*u)));if(f!==m)throw new Error("bad point: equation left != right (1)");let h=ce(o*i),E=ce(s*a);if(h!==E)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:r,Y:n,Z:o}=this,{X:i,Y:s,Z:a}=iH(t);return ce(r*a)===ce(i*o)&&ce(n*a)===ce(s*o)}is0(){return this.equals(G_)}negate(){return new F_(er(-this.X),this.Y,this.Z,er(-this.T))}double(){let{X:t,Y:r,Z:n}=this,o=_O,i=ce(t*t),s=ce(r*r),a=ce(2n*n*n),c=ce(o*i),u=er(t+r),d=er(ce(u*u)-i-s),l=er(c+s),p=er(l-a),f=er(c-s),m=ce(d*p),h=ce(l*f),E=ce(d*f),b=ce(p*l);return new F_(m,h,b,E)}add(t){let{X:r,Y:n,Z:o,T:i}=this,{X:s,Y:a,Z:c,T:u}=iH(t),d=_O,l=pO,p=ce(r*s),f=ce(n*a),m=ce(ce(i*l)*u),h=ce(o*c),E=er(ce(er(r+n)*er(s+a))-p-f),b=er(h-m),A=er(h+m),S=er(f-ce(d*p)),T=ce(E*b),v=ce(A*S),I=ce(E*S),w=ce(b*A);return new F_(T,v,w,I)}subtract(t){return this.add(iH(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(V_(t,1n,gO),!r&&this.is0()))return G_;if(t===1n)return this;if(this.equals(Ql))return cct(t).p;let n=G_,o=Ql,i=this;for(let s=0;r?s<256:t>0n;s++)t&1n?n=n.add(i):r&&(o=o.add(i)),i=i.double(),t>>=1n;return n}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:n}=this;if(this.equals(G_))return{x:0n,y:1n};let o=cle(n,sE);if(ce(n*o)!==1n)throw new Error("invalid inverse");return{x:ce(t*o),y:ce(r*o)}}toBytes(){let{x:t,y:r}=this.toAffine(),n=lle(r);return n[31]|=t&1n?128:0,n}toHex(){return _H(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(gO/2n,!1).double().add(this).is0()}},Ql=new z_(aH,cH,1n,er(aH*cH)),G_=new z_(0n,1n,1n,0n);z_.BASE=Ql;z_.ZERO=G_;var lle=e=>mH(ile(V_(e,0n,dle),64)).reverse(),EH=e=>BigInt("0x"+_H(Uint8Array.from(cs(e)).reverse())),Nc=(e,t)=>{let r=e;for(;t-- >0;)r=ce(r*r);return r},Xat=e=>{let t=ce(e*e),r=ce(t*e),n=ce(Nc(r,2)*r),o=ce(Nc(n,1)*e),i=ce(Nc(o,5)*o),s=ce(Nc(i,10)*i),a=ce(Nc(s,20)*s),c=ce(Nc(a,40)*a),u=ce(Nc(c,80)*c),d=ce(Nc(u,80)*c),l=ce(Nc(d,10)*i);return ce(Nc(l,2)*e)},Bde=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Zat=(e,t)=>{let r=ce(t*ce(t*t)),n=ce(ce(r*r)*t),o=Xat(ce(e*n)),i=ce(e*ce(r*o)),s=ce(t*ce(i*i)),a=i,c=ce(i*Bde),u=s===e,d=s===er(-e),l=s===er(-e*Bde);return u&&(i=a),(d||l)&&(i=c),(er(i)&1n)===1n&&(i=er(-i)),{isValid:u||d,value:i}},hO=e=>ale(EH(e)),fle=e=>{let t=AO(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32),o=hO(r),i=Ql.multiply(o),s=i.toBytes();return{head:r,prefix:n,scalar:o,point:i,pointBytes:s}},ple=e=>hH("sha512Async",cs(e,Zl,"secretKey")).then(fle),yH=e=>fle(gH("sha512",cs(e,Zl,"secretKey"))),Qat=e=>yH(e).pointBytes,_le=async e=>e[1](await hH("sha512Async",e[0])),mle=e=>e[1](gH("sha512",e[0])),gle=(e,t,r)=>{let{pointBytes:n,scalar:o}=e,i=hO(t),s=Ql.multiply(i).toBytes();return[J_(s,n,r),u=>{let d=ale(i+hO(u)*o);return cs(J_(s,lle(d)),64)}]},ect=async(e,t)=>{let r=AO(e,"message"),n=await ple(t);return _le(gle(n,await hH("sha512Async",n.prefix,r),r))},tct=(e,t)=>{let r=AO(e,"message"),n=yH(t);return mle(gle(n,gH("sha512",n.prefix,r),r))},rct=e=>{if(e===null||typeof e!="object")throw new TypeError("expected valid options object");return e.zip215??!0},hle=(e,t,r,n)=>{e=cs(e,64,"signature"),t=cs(t,void 0,"message"),r=cs(r,Zl,"publicKey");let o=rct(n),i=e.subarray(0,Zl),s=EH(e.subarray(Zl,64)),a,c,u,d=Uint8Array.of(),l=!1;try{a=z_.fromBytes(r,o),c=z_.fromBytes(i,o),u=Ql.multiply(s,!1),d=J_(i,r,t),l=!0}catch{}return[d,f=>{if(!l||!o&&a.isSmallOrder())return!1;let m=hO(f);return c.add(a.multiply(m,!1)).subtract(u).clearCofactor().is0()}]},nct=async(e,t,r,n={})=>_le(hle(e,t,r,n)),oct=(e,t,r,n={})=>mle(hle(e,t,r,n)),SH=bO({bytesToHex:_H,hexToBytes:mH,concatBytes:J_,mod:er,invert:cle,randomBytes:sle}),Ele={sha512Async:async e=>{let t=globalThis?.crypto?.subtle;if(!t)throw new Error("crypto.subtle must be defined, consider polyfill");return new Uint8Array(await t.digest("SHA-512",J_(e)))},sha512:void 0},ict=e=>cs(e===void 0?sle():e,Zl,"seed"),sct=bO({getExtendedPublicKeyAsync:ple,getExtendedPublicKey:yH,randomSecretKey:ict}),act=()=>{let e=[],t=Ql,r;for(let n=0;n<33;n++){r=t,e.push(r);for(let o=1;o<128;o++)r=r.add(t),e.push(r);t=r.double()}return e},Hde=void 0,qde=(e,t)=>{let r=t.negate();return e?r:t},cct=e=>{let t=Hde||(Hde=act()),r=G_,n=Ql;for(let o=0;o<33;o++){let i=Number(e&255n);e>>=8n,i>128&&(i-=256,e+=1n);let s=o*128,a=s+Math.abs(i)-1,c=o%2!==0,u=i<0;i===0?n=n.add(qde(c,t[s])):r=r.add(qde(u,t[a]))}if(e!==0n)throw new Error("invalid wnaf");return{p:r,f:n}},dO=BigInt(2**32-1),Vde=BigInt(32);function uct(e,t=!1){return t?{h:Number(e&dO),l:Number(e>>Vde&dO)}:{h:Number(e>>Vde&dO)|0,l:Number(e&dO)|0}}function dct(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=uct(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var lct=e=>e/2**32|0,fct=e=>e>>>0;function pct(e,t,r,n){let o=lct(r),i=fct(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}var Fde=(e,t,r)=>e>>>r,Gde=(e,t,r)=>e<<32-r|t>>>r,nE=(e,t,r)=>e>>>r|t<<32-r,oE=(e,t,r)=>e<<32-r|t>>>r,lO=(e,t,r)=>e<<64-r|t>>>r-32,fO=(e,t,r)=>e>>>r-32|t<<64-r;function id(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var _ct=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),mct=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,gct=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),hct=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,Ect=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),yct=(e,t,r,n,o,i)=>t+r+n+o+i+(e/2**32|0)|0;function $de(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var uH=e=>e?`"${e}" `:"";function Sct(e,t=""){if(typeof e!="number")throw new TypeError(uH(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(uH(t)+"expected integer >= 0, got "+e);return e}function yle(e,t,r=""){if($de(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Sct(t,"length");let n=$de(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=uH(r)+"expected Uint8Array"+o+", got "+i;throw n?new RangeError(s):new TypeError(s)}var Tct=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Kde=(e,t)=>{Tct(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Wde(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function bct(e,t){yle(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw new RangeError('"output" expected length >= '+r)}function EO(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function sH(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Cc(e,t){return e<<32-t|e>>>t}function Act(e,t,r="opts"){return Kde(e,"defaults"),t!==void 0&&Kde(t,r),Object.assign(Object.create(null),e,t)}function Sle(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Act({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>e(o),Object.assign(r,t),Object.freeze(r)}var Tle=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function vct(e,t,r){return e&t^~e&r}function Ict(e,t,r){return e&t^e&r^t&r}var ble=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=sH(this.buffer)}update(e){Wde(this),yle(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length,i=!1;for(let s=0;s<o;){let a=Math.min(n-this.pos,o-s);if(a===n){let c=sH(e);for(;n<=o-s;s+=n)this.process(c,s);i=!0;continue}r.set(s===0&&a===o?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Wde(this),bct(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>n-i&&(this.process(r,0),t.fill(0)),pct(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:sH(e),a=this.outputLen,c=a/4,u=this.get();if(a%4||c>u.length)throw new Error("invalid outputLen");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=n,e.length=r,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Pct=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),wct=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Rct=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jl=new Uint32Array(64),Oct=class extends ble{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)Jl[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=Jl[d-15],p=Jl[d-2],f=Cc(l,7)^Cc(l,18)^l>>>3,m=Cc(p,17)^Cc(p,19)^p>>>10;Jl[d]=m+Jl[d-7]+f+Jl[d-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let l=Cc(s,6)^Cc(s,11)^Cc(s,25),p=u+l+vct(s,a,c)+Rct[d]+Jl[d]|0,m=(Cc(r,2)^Cc(r,13)^Cc(r,22))+Ict(r,n,o)|0;u=c,c=a,a=s,s=i+p|0,i=o,o=n,n=r,r=p+m|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,o,i,s,a,c,u)}roundClean(){EO(Jl)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),EO(this.buffer)}},Nct=class extends Oct{constructor(){super(32,Pct)}},Ale=dct(["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))),Cct=Ale[0],xct=Ale[1],zl=new Uint32Array(80),Xl=new Uint32Array(80),Mct=class extends ble{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:o,Cl:i,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,o,i,s,a,c,u,d,l,p,f,m,h]}set(e,t,r,n,o,i,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=o|0,this.Cl=i|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}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let A=0;A<16;A++,t+=4)zl[A]=e.getUint32(t),Xl[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let S=zl[A-15]|0,T=Xl[A-15]|0,v=nE(S,T,1)^nE(S,T,8)^Fde(S,T,7),I=oE(S,T,1)^oE(S,T,8)^Gde(S,T,7),w=zl[A-2]|0,N=Xl[A-2]|0,L=nE(w,N,19)^lO(w,N,61)^Fde(w,N,6),x=oE(w,N,19)^fO(w,N,61)^Gde(w,N,6),D=gct(I,x,Xl[A-7],Xl[A-16]),k=hct(D,v,L,zl[A-7],zl[A-16]);zl[A]=k|0,Xl[A]=D|0}let{Ah:r,Al:n,Bh:o,Bl:i,Ch:s,Cl:a,Dh:c,Dl:u,Eh:d,El:l,Fh:p,Fl:f,Gh:m,Gl:h,Hh:E,Hl:b}=this;for(let A=0;A<80;A++){let S=nE(d,l,14)^nE(d,l,18)^lO(d,l,41),T=oE(d,l,14)^oE(d,l,18)^fO(d,l,41),v=d&p^~d&m,I=l&f^~l&h,w=Ect(b,T,I,xct[A],Xl[A]),N=yct(w,E,S,v,Cct[A],zl[A]),L=w|0,x=nE(r,n,28)^lO(r,n,34)^lO(r,n,39),D=oE(r,n,28)^fO(r,n,34)^fO(r,n,39),k=r&o^r&s^o&s,H=n&i^n&a^i&a;E=m|0,b=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=id(c|0,u|0,N|0,L|0),c=s|0,u=a|0,s=o|0,a=i|0,o=r|0,i=n|0;let B=_ct(L,D,H);r=mct(B,N,x,k),n=B|0}({h:r,l:n}=id(this.Ah|0,this.Al|0,r|0,n|0)),{h:o,l:i}=id(this.Bh|0,this.Bl|0,o|0,i|0),{h:s,l:a}=id(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=id(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=id(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=id(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=id(this.Gh|0,this.Gl|0,m|0,h|0),{h:E,l:b}=id(this.Hh|0,this.Hl|0,E|0,b|0),this.set(r,n,o,i,s,a,c,u,d,l,p,f,m,h,E,b)}roundClean(){EO(zl,Xl)}destroy(){this.destroyed=!0,EO(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Lct=class extends Mct{constructor(){super(64,wct)}},fb=Sle(()=>new Nct,Tle(1)),Dct=Sle(()=>new Lct,Tle(3)),Yde=Ele;Yde.sha512||(Yde.sha512=e=>Dct(e));var Jde=32;function vle(){return sct.randomSecretKey()}function vO(e){return Qat(e)}function kct(){let e=vle();return{secretKey:e,publicKey:vO(e)}}function Ile(e){if(e.length!==Jde)throw new Error(`Ed25519 seed must be ${Jde} bytes, got ${e.length}`);return{secretKey:e,publicKey:vO(e)}}function Uct(e,t){return tct(t,e)}function jct(e,t,r){return oct(t,r,e)}function Bct(e,t){return ect(t,e)}function Hct(e,t,r){return nct(t,r,e)}var Ple=SH.bytesToHex,TH=SH.hexToBytes,bH=SH.concatBytes;function wle(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Rle(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 ad(e){return wle(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function IO(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return Rle(r)}var qct=new TextEncoder,Vct={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};function Ole(e){let t=Ple(fb(e.payload)),r=`${e.messageId}
6
+ `)}function ed(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Zu(e){return e===null||typeof e=="string"}function Qu(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function Bst(e){if(!ed(e))throw new Error("account activity returned a malformed entry");let t=e.rail;if(t!=="card"&&t!=="x402")throw new Error("account activity entry is missing a valid rail label");let r=e.amountUsd,n={id:e.id,operationId:e.operationId,merchant:e.merchant,description:e.description,currency:e.currency,status:e.status,createdAt:e.createdAt};for(let[o,i]of Object.entries(n))if(typeof i!="string"||i.length===0)throw new Error(`account activity entry is missing ${o}`);if(typeof r!="number"||!Number.isFinite(r))throw new Error("account activity entry is missing a numeric amount");return{id:n.id,operationId:n.operationId,merchant:n.merchant,description:n.description,amountUsd:r,currency:n.currency,status:n.status,rail:t,createdAt:n.createdAt,...Qu(e,"failurePhase")?{failurePhase:e.failurePhase}:{},...Qu(e,"finalizesBy")?{finalizesBy:e.finalizesBy}:{},...Qu(e,"agentId")?{agentId:e.agentId}:{},...Qu(e,"agentName")?{agentName:e.agentName}:{},...Qu(e,"grantId")?{grantId:e.grantId}:{},...Qu(e,"mandateId")?{mandateId:e.mandateId}:{},...Qu(e,"drawId")?{drawId:e.drawId}:{},...Qu(e,"transactionHash")?{transactionHash:e.transactionHash}:{},...Qu(e,"transactionNetwork")?{transactionNetwork:e.transactionNetwork}:{}}}function Hst(e){if(!ed(e))return null;let{payment:t,route:r,party:n,authority:o,outcome:i}=e;return e.schemaVersion!==1||typeof e.operationId!="string"||typeof e.activityId!="string"||!ed(t)||typeof t.amountAtomic!="string"||typeof t.decimals!="number"||!Number.isSafeInteger(t.decimals)||t.decimals<0||typeof t.currency!="string"||typeof t.merchant!="string"||typeof t.description!="string"||typeof t.createdAt!="string"||!ed(r)||r.rail!=="wallet"&&r.rail!=="card"||!Zu(r.protocol)||!Zu(r.network)||!Zu(r.cardLast4)||!ed(n)||!Zu(n.agentId)||!Zu(n.agentName)||!ed(o)||!Zu(o.grantId)||!Zu(o.mandateId)||!Zu(o.drawId)||!ed(i)||typeof i.status!="string"||typeof i.proofLevel!="string"||typeof i.final!="boolean"||typeof i.updatedAt!="string"||!Zu(i.finalizesBy)||!Array.isArray(e.evidence)||!e.evidence.every(ed)||!Array.isArray(e.timeline)||!e.timeline.every(ed)||e.dataCompleteness!=="complete"&&e.dataCompleteness!=="partial"?null:e}var eb,Ost,Nst,Cst,Tr,rO,Mst,Dst,Ls,td=R(()=>{"use strict";Cue();xue();OB();vc();Due();QT();ZR();eO();B_();tO();eb="5.0.0-rc.402",Ost="1",Nst=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/,Cst=5e3,Tr=class extends Error{constructor(r,n,o,i,s,a){super(r);this.status=n;this.code=o;this.detail=i;this.serverRetryable=s;this.details=a;this.name="ApiHttpError"}status;code;detail;serverRetryable;details;get retryable(){return this.serverRetryable??(this.status>=500||this.status===408||this.status===425||this.status===429)}};rO=class extends Error{constructor(r){super("Failed to retrieve task: Task not found");this.taskId=r;this.name="McpTaskNotFoundError"}taskId;rpcCode=-32602},Mst=new Set(["agent_paused","agent_revoked","device_key_replaced","grant_expired","owner_withdrawal_pending"]);Dst="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";Ls=class{constructor(t){this.getSessionToken=t;this.baseUrl=Yl()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!zh()){let r=t.headers.get("X-Latest-Version");r&&jB(r,eb)&&(this.lastSignals.updateAvailable={currentVersion:eb,latestVersion:r})}}getClientVersion(){return eb}getAuthServerOrigin(){return this.baseUrl}async signUcpRequest(t){let r=await this.request("POST","/v4/ucp/sign",t,15e3);if(!r||typeof r!="object"||Array.isArray(r)||!r.headers||typeof r.headers!="object"||Array.isArray(r.headers))throw new Error("UCP signing service returned a malformed response");let n=r.headers,o=Object.keys(n).sort(),i=["content-digest","signature","signature-input"];if(o.length!==i.length||o.some((s,a)=>s!==i[a])||i.some(s=>typeof n[s]!="string"||n[s].length===0||n[s].length>16384||/[\r\n]/.test(n[s])))throw new Error("UCP signing service returned invalid signature headers");return n}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new GR(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t,r){let n=null;try{n=await t.json()}catch{r.throwIfAborted()}let o=Ust(n),i=n&&typeof n=="object"?n:{};throw kst(i)?new KR(o,{status:t.status,disabledSurface:Da(i.disabled_surface)||void 0,flag:Da(i.flag)||void 0,correlationId:Da(i.correlation_id)||void 0}):new $R(o,t.status,typeof i.retryable=="boolean"?i.retryable:!0)}async financialRuntimeRequest(t,r){return this.request("POST",`/v1/financial-runtime/${t}`,r,2e4)}async identityDeviceRequest(t,r){return this.request("POST",`/v1/identity-device/${t}`,r,2e4)}async request(t,r,n,o,i){let s=await this.getSessionToken();if(!s)throw new JT(jst());let a={Authorization:`Bearer ${s}`};i&&(t==="GET"?a["X-User-Context"]=encodeURIComponent(i.replace(/[\r\n\0]/g," ").slice(0,1e3)):n={...n||{},user_context:i}),n&&(a["Content-Type"]="application/json");let c;try{return await Nue(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":eb,"X-Visa-Agent-Operations-Version":Ost,"X-Source":"cli",...Xh()},body:n?JSON.stringify(n):void 0,timeoutMs:o},(u,d)=>(c=d,this.consumeResponse(u,d,t,r)))}catch(u){if(c&&!c.aborted)throw u;let d=new Error(YR(u)),l=RB(u);throw l&&(d.code=l),d}}async consumeResponse(t,r,n,o){if(this.parseServerSignals(t),t.status===401)throw new JT("Your device session has expired. Run `visa connect` to refresh it (the device is already enrolled).",t.status);if(t.status===429){let s=xst(t.headers.get("Retry-After"));throw new WR(`Rate limited \u2014 wait ${s}s, then retry.`,s)}t.status===503&&await this.throwServerUnavailable(t,r);let i;try{i=await t.json()}catch{if(r.throwIfAborted(),t.status===500)throw new Tr(`Server error on ${o}. Try again or check https://visacli.sh for status.`,t.status);if(!t.ok){let s=t.status>=500||t.status===429||n==="GET"&&(t.status===408||t.status===425);throw new Tr(s?`Unexpected response from ${o}. Try again.`:`Unexpected response from ${o} (${t.status}).`,t.status,void 0,void 0,s)}throw new Error(`Unexpected response from ${o}.`)}if(!t.ok){if(t.status===426||i?.error==="update_required"||i?.error_code==="update_required"||i?.errorCode==="update_required"){let s=typeof i?.runningVersion=="string"?i.runningVersion:eb,a=typeof i?.minCompatibleVersion=="string"?i.minCompatibleVersion:BB;throw new ZT(s,a,o)}if(t.status===500){let s=typeof i?.retryable=="boolean"?i.retryable:void 0;throw new Tr(s===!1?`Server error on ${o}. Inspect the server error and reconcile the existing attempt.`:`Server error on ${o}. Try again or check https://visacli.sh for status.`,t.status,typeof i?.error=="string"?i.error:void 0,typeof i?.reason=="string"?i.reason:void 0,s)}throw this.throwIfAttestationDrift(i),Lst(t.status,i)}return i}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t},Cst)}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),t.verify&&n.set("verify",t.verify),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 merchantDirectoryCertified(t){return this.request("GET","/v1/merchant-directory/certified",void 0,void 0,t)}async getAccountActivity(t,r){let n=new URLSearchParams;t!==void 0&&n.set("limit",String(t)),r!==void 0&&n.set("agentId",r);let o=n.size>0?`?${n.toString()}`:"",i=await this.request("GET",`/v4/account/activity${o}`);if(!i||!Array.isArray(i.activity))throw new Error("account activity service returned an invalid response");return i.activity.map(Bst)}async getAccountActivityReceipt(t){let r;try{r=await this.request("GET",`/v4/account/activity/${encodeURIComponent(t)}`)}catch(o){throw o instanceof Tr&&o.status===404?new Xt(`account activity entry not found: ${t}`,"activity_entry_not_found"):o}let n=Hst(r);if(!n)throw new Error("account receipt service returned an invalid or unsupported response");return n}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 listAccountAgents(){try{let t=await this.request("GET","/v4/account/agents");return!t||!Array.isArray(t.agents)?null:t.agents.flatMap(r=>{if(!r||typeof r!="object")return[];let n=r,o=typeof n.agentId=="string"&&n.agentId.length>0?n.agentId:null,i=typeof n.agentJkt=="string"&&n.agentJkt.length>0?n.agentJkt:null;if(o===null&&i===null)return[];let s=n.approvedAuthority,a=s&&typeof s=="object"&&typeof s.grantId=="string"&&typeof s.status=="string"&&typeof s.totalMicros=="string"&&typeof s.perTransactionMicros=="string"&&typeof s.spentMicros=="string"&&typeof s.reservedMicros=="string"&&Array.isArray(s.scopes)?(()=>{let f=s;return{grantId:f.grantId,status:f.status,totalMicros:f.totalMicros,perTransactionMicros:f.perTransactionMicros,spentMicros:f.spentMicros,reservedMicros:f.reservedMicros,scopes:f.scopes.filter(m=>typeof m=="string"),...typeof f.expiresAt=="string"?{expiresAt:f.expiresAt}:{}}})():void 0,c=f=>typeof n[f]=="string"&&n[f].length>0?n[f]:void 0,u=n.executionReadiness,d=u&&typeof u=="object"&&!Array.isArray(u)?(()=>{let f=u,m=["shared","card","wallet"];if(Object.keys(f).some(E=>!m.includes(E))||Object.values(f).some(E=>typeof E!="string"))return;let h=Object.fromEntries(m.filter(E=>E in f).map(E=>[E,f[E]]));return Object.keys(h).length>0?h:void 0})():void 0,l=n.wallet,p=l&&typeof l=="object"&&!Array.isArray(l)?(()=>{let f=l,m=b=>typeof f[b]=="string"?{[b]:f[b]}:{},h=b=>typeof f[b]=="number"&&Number.isFinite(f[b])?{[b]:f[b]}:{},E={...m("walletAddress"),...m("network"),...typeof f.provisioned=="boolean"?{provisioned:f.provisioned}:{},...h("totalLimitCents").totalLimitCents!==void 0?h("totalLimitCents"):typeof f.dailyLimitCents=="number"&&Number.isFinite(f.dailyLimitCents)?{totalLimitCents:f.dailyLimitCents}:{},...h("perTransactionLimitCents")};return Object.keys(E).length>0?E:void 0})():void 0;return[{agentId:o,agentJkt:i,name:typeof n.name=="string"?n.name:"",revoked:n.revoked===!0,paused:n.paused===!0,...a?{approvedAuthority:a}:{},...c("executionStatus")?{executionStatus:c("executionStatus")}:{},...c("executionStatusReason")?{executionStatusReason:c("executionStatusReason")}:{},...d?{executionReadiness:d}:{},...c("identityKeyStatus")?{identityKeyStatus:c("identityKeyStatus")}:{},...c("tapStatus")?{tapStatus:c("tapStatus")}:{},...p?{wallet:p}:{}}]})}catch{return null}}async listAccountCardMandates(){try{let t=await this.request("GET","/v4/account/card-mandates?includeInactive=1&limit=200");return!t||!Array.isArray(t.mandates)?null:t.mandates.flatMap(r=>{if(!r||typeof r!="object")return[];let n=r;return typeof n.mandateId!="string"||n.mandateId.length===0?[]:[{mandateId:n.mandateId,revokedAt:typeof n.revokedAt=="string"?n.revokedAt:null,expiresAt:typeof n.expiresAt=="string"?n.expiresAt:null}]})}catch{return null}}async revokeAccountCardMandate(t){try{return await this.request("POST",`/v4/account/card-mandates/${encodeURIComponent(t)}/revoke`)}catch{return null}}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async logout(t,r){return this.request("POST","/v4/logout",t,void 0,r)}async putMcpTask(t,r){return this.request("PUT",`/v1/mcp-tasks/${encodeURIComponent(t)}`,r)}async getMcpTask(t){try{return await this.request("GET",`/v1/mcp-tasks/${encodeURIComponent(t)}`)}catch(r){throw r instanceof rO?r:r instanceof Tr&&r.status===404?new rO(t):r}}async revokeSpendingAuthority(t){let r=await this.request("POST",`/v4/agents/${encodeURIComponent(t)}/spending-authority/revoke`,{});if(typeof r?.revoked!="boolean")throw new Error("spending authority revoke service returned an invalid response");return{revoked:r.revoked}}async claimAgentForApp(t,r,n){return{claimed:(await this.request("POST","/v4/account/agent-apps",{agentId:t,harnessId:r,...n?{deviceName:n}:{}}))?.claimed===!0}}async signTurnkeyTapPayload(t,r){let n=await this.request("POST",`/v4/account/agents/${encodeURIComponent(t)}/keychain/tap-sign`,{signatureBase:r});if(typeof n.signature!="string"||typeof n.keyId!="string")throw new Error("TAP signing service returned an invalid response");return{signature:n.signature,keyId:n.keyId}}}});var NO=_((Gjr,rfe)=>{"use strict";var Vat=Object.create,TO=Object.defineProperty,Fat=Object.getOwnPropertyDescriptor,tle=Object.getOwnPropertyNames,Gat=Object.getPrototypeOf,$at=Object.prototype.hasOwnProperty,Kat=(e,t)=>function(){try{return t||(0,e[tle(e)[0]])((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Wat=(e,t)=>{for(var r in t)TO(e,r,{get:t[r],enumerable:!0})},rle=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of tle(t))!$at.call(e,o)&&o!==r&&TO(e,o,{get:()=>t[o],enumerable:!(n=Fat(t,o))||n.enumerable});return e},nle=(e,t,r)=>(r=e!=null?Vat(Gat(e)):{},rle(t||!e||!e.__esModule?TO(r,"default",{value:e,enumerable:!0}):r,e)),Yat=e=>rle(TO({},"__esModule",{value:!0}),e),Jat=Kat({"../shared/dist/canonical-contract.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CanonicalJsonError=e.CANONICAL_OPAQUE_ID_MAX_BYTES=e.CANONICAL_OPAQUE_ID_RE=e.CANONICAL_OPAQUE_ID_PATTERN=void 0,e.utf8ByteLength=n,e.isCanonicalText=o,e.compareCanonicalKeys=i,e.isCanonicalOpaqueId=s,e.assertCanonicalOpaqueId=a,e.canonicalJsonExact=d,e.CANONICAL_OPAQUE_ID_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$",e.CANONICAL_OPAQUE_ID_RE=new RegExp(e.CANONICAL_OPAQUE_ID_PATTERN),e.CANONICAL_OPAQUE_ID_MAX_BYTES=128;var t=/[\u0000-\u001f\u007f\u2028\u2029]/,r=new TextEncoder;function n(l){return r.encode(l).length}function o(l,p){return typeof l=="string"&&l.length>0&&n(l)<=p&&l.trim()===l&&l.normalize("NFC")===l&&!t.test(l)}function i(l,p){let f=r.encode(l),m=r.encode(p),h=Math.min(f.length,m.length);for(let E=0;E<h;E+=1)if(f[E]!==m[E])return f[E]-m[E];return f.length-m.length}function s(l){return typeof l=="string"&&n(l)<=e.CANONICAL_OPAQUE_ID_MAX_BYTES&&e.CANONICAL_OPAQUE_ID_RE.test(l)}function a(l,p="value"){if(!s(l))throw new Error(`${p} must be a canonical opaque id (max 128 ASCII bytes)`)}var c=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,u=class extends Error{constructor(l){super(l),this.name="CanonicalJsonError"}};e.CanonicalJsonError=u;function d(l,p=0){if(p>16)throw new u("nesting is deeper than 16");if(l===null||typeof l=="boolean")return JSON.stringify(l);if(typeof l=="string"){if(c.test(l))throw new u("text is not valid Unicode");return JSON.stringify(l)}if(typeof l=="number"){if(!Number.isSafeInteger(l)||Object.is(l,-0))throw new u("numbers must be whole and at most 2^53 - 1; put amounts and decimals in strings");return JSON.stringify(l)}if(Array.isArray(l)){if(l.length>1024)throw new u("an array has more than 1024 items");return`[${l.map(m=>d(m,p+1)).join(",")}]`}if(typeof l!="object"||Object.getPrototypeOf(l)!==Object.prototype)throw new u("only JSON objects, arrays, strings, whole numbers and booleans");let f=Object.keys(l);if(f.length>512)throw new u("an object has more than 512 keys");for(let m of f)if(!o(m,128))throw new u("keys must be non-empty trimmed NFC text of at most 128 bytes");return`{${f.sort(i).map(m=>`${JSON.stringify(m)}:${d(l[m],p+1)}`).join(",")}}`}}}),ole={};Wat(ole,{AGENT_AUTHORITY_VALUATION_POLICY:()=>mO,AGENT_AUTHORITY_VERSION:()=>sd,AGENT_AUTHORIZATION_SCOPES:()=>K_,AGENT_BUDGET_EPOCH_MODES:()=>Lle,AGENT_CAPABILITY_ATTACH_CAPABILITIES:()=>$le,AGENT_CHANNEL_ASSURANCES:()=>jle,AGENT_CHANNEL_KINDS:()=>kle,AGENT_CHANNEL_STATUSES:()=>Ule,AGENT_EXECUTION_READINESS_REASONS:()=>out,AGENT_HANDOFF_AUTHORITIES:()=>but,AGENT_HANDOFF_COMPOUND_AUTHORITY:()=>RH,AGENT_KEY_CUSTODIES:()=>iut,AGENT_KEY_STATUSES:()=>sut,AGENT_PAIRING_CODE_ALPHABET:()=>aE,AGENT_PAIRING_CODE_LENGTH:()=>lb,AGENT_PAIRING_PROTOCOL_VERSION:()=>vut,AGENT_PAIRING_PROTOCOL_VERSION_V2:()=>yO,AGENT_PAYMENT_MODE_NAMES:()=>rut,AGENT_PAYMENT_RAILS:()=>lH,AGENT_PAYMENT_SURFACES:()=>dH,DOMAINS:()=>Vct,USD_MICROS_PER_CENT:()=>AH,VIC_PROCESSOR_ACTIONS:()=>tut,WALLET_GRANT_SCOPE:()=>Dle,agentAuthorityGrantHash:()=>Sut,agentMailCredentialClaimMessageV2:()=>Zut,authorizationScopeFacts:()=>hut,base64ToBytes:()=>Rle,base64UrlToBytes:()=>IO,bytesToBase64:()=>wle,bytesToBase64Url:()=>ad,bytesToHex:()=>Ple,canonicalAgentAuthorityGrant:()=>PH,canonicalAgentChannelDescriptor:()=>yut,canonicalFormAgent:()=>Fct,canonicalPairingDeliveryArtifactV2:()=>tfe,canonicalPairingTerms:()=>Xle,canonicalPairingTermsV2:()=>xH,canonicalPayWithinBudget:()=>Fle,canonicalSpendAuthorizationIntent:()=>wH,centsToUsdMicros:()=>mut,computeJkt:()=>xle,concatBytes:()=>bH,defaultPayWithinBudget:()=>nut,extractEd25519Seed:()=>eut,formatPairingCode:()=>OO,generateKeyPair:()=>kct,generateSeed:()=>vle,getPublicKey:()=>vO,grantPaymentRails:()=>vH,handoffAuthorityCapabilities:()=>Aut,hexToBytes:()=>TH,isCanonicalBase64Url32:()=>us,isValidPairingCode:()=>Jle,jwkToKeyPair:()=>Wct,jwkToPublicKey:()=>Kct,jwkToSeed:()=>Cle,keyPairFromSeed:()=>Ile,keyRotationClaimHashV2:()=>Xut,keyRotationClaimMessageV2:()=>efe,normalizePairingCode:()=>RO,pairingActivationMessage:()=>Yut,pairingActivationMessageV2:()=>zut,pairingArtifactHash:()=>edt,pairingClaimHashV2:()=>Jut,pairingClaimMessage:()=>Wut,pairingClaimMessageV2:()=>Qle,pairingClaimTokenHash:()=>zle,pairingCodeFromClaimToken:()=>Gut,pairingCodeHash:()=>Vut,pairingConfirmationCode:()=>$ut,pairingDeliveryArtifactV2Hash:()=>Qut,pairingInstrumentCommitment:()=>Uut,pairingSha256:()=>Lc,pairingTermsHash:()=>Kut,pairingTermsV2Hash:()=>Zle,pairingVerifierChallenge:()=>Hut,pkcs8ToSeed:()=>Zct,publicKeyToJwk:()=>$ct,publicKeyToSpki:()=>Xct,randomPairingClaimToken:()=>Fut,randomPairingCode:()=>qut,randomPairingId:()=>jut,randomPairingVerifier:()=>But,seedToJwk:()=>Gct,seedToPkcs8:()=>zct,sign:()=>Uct,signAsync:()=>Bct,spendAuthorizationIntentHash:()=>Gle,spkiToPublicKey:()=>Qct,subwayAgentMsgV1:()=>Ole,usdcAtomicToUsdMicros:()=>gut,verify:()=>jct,verifyAsync:()=>Hct,walletAuthorizationRequestHash:()=>Tut});rfe.exports=Yat(ole);var bO=Object.freeze,sE=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,gO=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,pO=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,aH=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,cH=0x6666666666666666666666666666666666666666666666666666666666666658n,_O=sE-1n,zat=bO({p:sE,n:gO,h:8n,a:_O,d:pO,Gx:aH,Gy:cH}),Zl=32,Ude=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,cs=(e,t,r="")=>{if(Ude(e)&&(t===void 0||e.length===t))return e;let n=Ude(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=(r?`"${r}" `:"")+"expected Uint8Array"+o+", got "+i;throw n?new RangeError(s):new TypeError(s)},AO=(e,t="",r)=>Uint8Array.from(cs(e,r,t)),ile=(e,t)=>e.toString(16).padStart(t,"0"),_H=e=>{let t="";for(let r of cs(e))t+=ile(r,2);return t},mH=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let r=new Uint8Array(e.length/2);for(let n=0,o=0;n<r.length;n++,o+=2){let i=e.charCodeAt(o),s=e.charCodeAt(o+1);r[n]=((i&15)+(i>>6)*9)*16+(s&15)+(s>>6)*9}return r},J_=(...e)=>{let t=0;for(let o of e)t+=cs(o).length;let r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r},sle=(e=Zl)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},V_=(e,t,r,n="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},er=(e,t=sE)=>(e%=t)>=0n?e:t+e,jde=(1n<<255n)-1n,ce=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&jde);return t=(t>>255n)*19n+(t&jde),t%sE},ale=e=>er(e,gO),cle=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let r=er(e,t),n=t,o=0n,i=1n;for(;r!==0n;){let a=n/r,c=n-r*a,u=o-i*a;n=r,r=c,o=i,i=u}if(n!==1n)throw new Error("invert: does not exist");return er(o,t)},ule=e=>{let t=Ele[e];if(typeof t!="function")throw new Error("hashes."+e+" not set");return t},gH=(e,...t)=>cs(ule(e)(J_(...t)),64,"digest"),hH=async(e,...t)=>cs(await ule(e)(J_(...t)),64,"digest"),iH=e=>{if(e instanceof z_)return e;throw new TypeError("Point expected")},dle=2n**256n,z_=class F_{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,o){let i=dle;this.X=V_(t,0n,i),this.Y=V_(r,0n,i),this.Z=V_(n,1n,i),this.T=V_(o,0n,i),bO(this)}static CURVE(){return zat}static fromAffine(t){return new F_(t.x,t.y,1n,ce(t.x*t.y))}static fromBytes(t,r=!1){let n=AO(t,"point",Zl),o=n[31];n[31]=o&-129;let i=EH(n);r||V_(i,0n,sE);let s=ce(i*i),a=er(s-1n),c=ce(pO*s+1n),{isValid:u,value:d}=Zat(a,c);if(!u)throw new Error("bad point: y not sqrt");let l=!!(o&128);if(!r&&d===0n&&l)throw new Error("bad point: x==0, isLastByteOdd");return l!==!!(d&1n)&&(d=er(-d)),new F_(d,i,1n,ce(d*i))}static fromHex(t,r){return F_.fromBytes(mH(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=_O,r=pO,n=this;if(n.is0())throw new Error("bad point: ZERO");let{X:o,Y:i,Z:s,T:a}=n,c=ce(o*o),u=ce(i*i),d=ce(s*s),l=ce(d*d),p=ce(c*t),f=ce(d*(p+u)),m=er(l+ce(r*ce(c*u)));if(f!==m)throw new Error("bad point: equation left != right (1)");let h=ce(o*i),E=ce(s*a);if(h!==E)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:r,Y:n,Z:o}=this,{X:i,Y:s,Z:a}=iH(t);return ce(r*a)===ce(i*o)&&ce(n*a)===ce(s*o)}is0(){return this.equals(G_)}negate(){return new F_(er(-this.X),this.Y,this.Z,er(-this.T))}double(){let{X:t,Y:r,Z:n}=this,o=_O,i=ce(t*t),s=ce(r*r),a=ce(2n*n*n),c=ce(o*i),u=er(t+r),d=er(ce(u*u)-i-s),l=er(c+s),p=er(l-a),f=er(c-s),m=ce(d*p),h=ce(l*f),E=ce(d*f),b=ce(p*l);return new F_(m,h,b,E)}add(t){let{X:r,Y:n,Z:o,T:i}=this,{X:s,Y:a,Z:c,T:u}=iH(t),d=_O,l=pO,p=ce(r*s),f=ce(n*a),m=ce(ce(i*l)*u),h=ce(o*c),E=er(ce(er(r+n)*er(s+a))-p-f),b=er(h-m),A=er(h+m),S=er(f-ce(d*p)),T=ce(E*b),v=ce(A*S),I=ce(E*S),w=ce(b*A);return new F_(T,v,w,I)}subtract(t){return this.add(iH(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(V_(t,1n,gO),!r&&this.is0()))return G_;if(t===1n)return this;if(this.equals(Ql))return cct(t).p;let n=G_,o=Ql,i=this;for(let s=0;r?s<256:t>0n;s++)t&1n?n=n.add(i):r&&(o=o.add(i)),i=i.double(),t>>=1n;return n}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:n}=this;if(this.equals(G_))return{x:0n,y:1n};let o=cle(n,sE);if(ce(n*o)!==1n)throw new Error("invalid inverse");return{x:ce(t*o),y:ce(r*o)}}toBytes(){let{x:t,y:r}=this.toAffine(),n=lle(r);return n[31]|=t&1n?128:0,n}toHex(){return _H(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(gO/2n,!1).double().add(this).is0()}},Ql=new z_(aH,cH,1n,er(aH*cH)),G_=new z_(0n,1n,1n,0n);z_.BASE=Ql;z_.ZERO=G_;var lle=e=>mH(ile(V_(e,0n,dle),64)).reverse(),EH=e=>BigInt("0x"+_H(Uint8Array.from(cs(e)).reverse())),Nc=(e,t)=>{let r=e;for(;t-- >0;)r=ce(r*r);return r},Xat=e=>{let t=ce(e*e),r=ce(t*e),n=ce(Nc(r,2)*r),o=ce(Nc(n,1)*e),i=ce(Nc(o,5)*o),s=ce(Nc(i,10)*i),a=ce(Nc(s,20)*s),c=ce(Nc(a,40)*a),u=ce(Nc(c,80)*c),d=ce(Nc(u,80)*c),l=ce(Nc(d,10)*i);return ce(Nc(l,2)*e)},Bde=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Zat=(e,t)=>{let r=ce(t*ce(t*t)),n=ce(ce(r*r)*t),o=Xat(ce(e*n)),i=ce(e*ce(r*o)),s=ce(t*ce(i*i)),a=i,c=ce(i*Bde),u=s===e,d=s===er(-e),l=s===er(-e*Bde);return u&&(i=a),(d||l)&&(i=c),(er(i)&1n)===1n&&(i=er(-i)),{isValid:u||d,value:i}},hO=e=>ale(EH(e)),fle=e=>{let t=AO(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32),o=hO(r),i=Ql.multiply(o),s=i.toBytes();return{head:r,prefix:n,scalar:o,point:i,pointBytes:s}},ple=e=>hH("sha512Async",cs(e,Zl,"secretKey")).then(fle),yH=e=>fle(gH("sha512",cs(e,Zl,"secretKey"))),Qat=e=>yH(e).pointBytes,_le=async e=>e[1](await hH("sha512Async",e[0])),mle=e=>e[1](gH("sha512",e[0])),gle=(e,t,r)=>{let{pointBytes:n,scalar:o}=e,i=hO(t),s=Ql.multiply(i).toBytes();return[J_(s,n,r),u=>{let d=ale(i+hO(u)*o);return cs(J_(s,lle(d)),64)}]},ect=async(e,t)=>{let r=AO(e,"message"),n=await ple(t);return _le(gle(n,await hH("sha512Async",n.prefix,r),r))},tct=(e,t)=>{let r=AO(e,"message"),n=yH(t);return mle(gle(n,gH("sha512",n.prefix,r),r))},rct=e=>{if(e===null||typeof e!="object")throw new TypeError("expected valid options object");return e.zip215??!0},hle=(e,t,r,n)=>{e=cs(e,64,"signature"),t=cs(t,void 0,"message"),r=cs(r,Zl,"publicKey");let o=rct(n),i=e.subarray(0,Zl),s=EH(e.subarray(Zl,64)),a,c,u,d=Uint8Array.of(),l=!1;try{a=z_.fromBytes(r,o),c=z_.fromBytes(i,o),u=Ql.multiply(s,!1),d=J_(i,r,t),l=!0}catch{}return[d,f=>{if(!l||!o&&a.isSmallOrder())return!1;let m=hO(f);return c.add(a.multiply(m,!1)).subtract(u).clearCofactor().is0()}]},nct=async(e,t,r,n={})=>_le(hle(e,t,r,n)),oct=(e,t,r,n={})=>mle(hle(e,t,r,n)),SH=bO({bytesToHex:_H,hexToBytes:mH,concatBytes:J_,mod:er,invert:cle,randomBytes:sle}),Ele={sha512Async:async e=>{let t=globalThis?.crypto?.subtle;if(!t)throw new Error("crypto.subtle must be defined, consider polyfill");return new Uint8Array(await t.digest("SHA-512",J_(e)))},sha512:void 0},ict=e=>cs(e===void 0?sle():e,Zl,"seed"),sct=bO({getExtendedPublicKeyAsync:ple,getExtendedPublicKey:yH,randomSecretKey:ict}),act=()=>{let e=[],t=Ql,r;for(let n=0;n<33;n++){r=t,e.push(r);for(let o=1;o<128;o++)r=r.add(t),e.push(r);t=r.double()}return e},Hde=void 0,qde=(e,t)=>{let r=t.negate();return e?r:t},cct=e=>{let t=Hde||(Hde=act()),r=G_,n=Ql;for(let o=0;o<33;o++){let i=Number(e&255n);e>>=8n,i>128&&(i-=256,e+=1n);let s=o*128,a=s+Math.abs(i)-1,c=o%2!==0,u=i<0;i===0?n=n.add(qde(c,t[s])):r=r.add(qde(u,t[a]))}if(e!==0n)throw new Error("invalid wnaf");return{p:r,f:n}},dO=BigInt(2**32-1),Vde=BigInt(32);function uct(e,t=!1){return t?{h:Number(e&dO),l:Number(e>>Vde&dO)}:{h:Number(e>>Vde&dO)|0,l:Number(e&dO)|0}}function dct(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=uct(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var lct=e=>e/2**32|0,fct=e=>e>>>0;function pct(e,t,r,n){let o=lct(r),i=fct(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}var Fde=(e,t,r)=>e>>>r,Gde=(e,t,r)=>e<<32-r|t>>>r,nE=(e,t,r)=>e>>>r|t<<32-r,oE=(e,t,r)=>e<<32-r|t>>>r,lO=(e,t,r)=>e<<64-r|t>>>r-32,fO=(e,t,r)=>e>>>r-32|t<<64-r;function id(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var _ct=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),mct=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,gct=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),hct=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,Ect=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),yct=(e,t,r,n,o,i)=>t+r+n+o+i+(e/2**32|0)|0;function $de(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var uH=e=>e?`"${e}" `:"";function Sct(e,t=""){if(typeof e!="number")throw new TypeError(uH(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(uH(t)+"expected integer >= 0, got "+e);return e}function yle(e,t,r=""){if($de(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Sct(t,"length");let n=$de(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=uH(r)+"expected Uint8Array"+o+", got "+i;throw n?new RangeError(s):new TypeError(s)}var Tct=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Kde=(e,t)=>{Tct(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Wde(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function bct(e,t){yle(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw new RangeError('"output" expected length >= '+r)}function EO(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function sH(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Cc(e,t){return e<<32-t|e>>>t}function Act(e,t,r="opts"){return Kde(e,"defaults"),t!==void 0&&Kde(t,r),Object.assign(Object.create(null),e,t)}function Sle(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Act({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>e(o),Object.assign(r,t),Object.freeze(r)}var Tle=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function vct(e,t,r){return e&t^~e&r}function Ict(e,t,r){return e&t^e&r^t&r}var ble=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=sH(this.buffer)}update(e){Wde(this),yle(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length,i=!1;for(let s=0;s<o;){let a=Math.min(n-this.pos,o-s);if(a===n){let c=sH(e);for(;n<=o-s;s+=n)this.process(c,s);i=!0;continue}r.set(s===0&&a===o?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Wde(this),bct(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>n-i&&(this.process(r,0),t.fill(0)),pct(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:sH(e),a=this.outputLen,c=a/4,u=this.get();if(a%4||c>u.length)throw new Error("invalid outputLen");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=n,e.length=r,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Pct=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),wct=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Rct=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jl=new Uint32Array(64),Oct=class extends ble{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)Jl[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=Jl[d-15],p=Jl[d-2],f=Cc(l,7)^Cc(l,18)^l>>>3,m=Cc(p,17)^Cc(p,19)^p>>>10;Jl[d]=m+Jl[d-7]+f+Jl[d-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let l=Cc(s,6)^Cc(s,11)^Cc(s,25),p=u+l+vct(s,a,c)+Rct[d]+Jl[d]|0,m=(Cc(r,2)^Cc(r,13)^Cc(r,22))+Ict(r,n,o)|0;u=c,c=a,a=s,s=i+p|0,i=o,o=n,n=r,r=p+m|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,o,i,s,a,c,u)}roundClean(){EO(Jl)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),EO(this.buffer)}},Nct=class extends Oct{constructor(){super(32,Pct)}},Ale=dct(["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))),Cct=Ale[0],xct=Ale[1],zl=new Uint32Array(80),Xl=new Uint32Array(80),Mct=class extends ble{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:o,Cl:i,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,o,i,s,a,c,u,d,l,p,f,m,h]}set(e,t,r,n,o,i,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=o|0,this.Cl=i|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}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let A=0;A<16;A++,t+=4)zl[A]=e.getUint32(t),Xl[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let S=zl[A-15]|0,T=Xl[A-15]|0,v=nE(S,T,1)^nE(S,T,8)^Fde(S,T,7),I=oE(S,T,1)^oE(S,T,8)^Gde(S,T,7),w=zl[A-2]|0,N=Xl[A-2]|0,L=nE(w,N,19)^lO(w,N,61)^Fde(w,N,6),x=oE(w,N,19)^fO(w,N,61)^Gde(w,N,6),D=gct(I,x,Xl[A-7],Xl[A-16]),k=hct(D,v,L,zl[A-7],zl[A-16]);zl[A]=k|0,Xl[A]=D|0}let{Ah:r,Al:n,Bh:o,Bl:i,Ch:s,Cl:a,Dh:c,Dl:u,Eh:d,El:l,Fh:p,Fl:f,Gh:m,Gl:h,Hh:E,Hl:b}=this;for(let A=0;A<80;A++){let S=nE(d,l,14)^nE(d,l,18)^lO(d,l,41),T=oE(d,l,14)^oE(d,l,18)^fO(d,l,41),v=d&p^~d&m,I=l&f^~l&h,w=Ect(b,T,I,xct[A],Xl[A]),N=yct(w,E,S,v,Cct[A],zl[A]),L=w|0,x=nE(r,n,28)^lO(r,n,34)^lO(r,n,39),D=oE(r,n,28)^fO(r,n,34)^fO(r,n,39),k=r&o^r&s^o&s,H=n&i^n&a^i&a;E=m|0,b=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=id(c|0,u|0,N|0,L|0),c=s|0,u=a|0,s=o|0,a=i|0,o=r|0,i=n|0;let B=_ct(L,D,H);r=mct(B,N,x,k),n=B|0}({h:r,l:n}=id(this.Ah|0,this.Al|0,r|0,n|0)),{h:o,l:i}=id(this.Bh|0,this.Bl|0,o|0,i|0),{h:s,l:a}=id(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=id(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=id(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=id(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=id(this.Gh|0,this.Gl|0,m|0,h|0),{h:E,l:b}=id(this.Hh|0,this.Hl|0,E|0,b|0),this.set(r,n,o,i,s,a,c,u,d,l,p,f,m,h,E,b)}roundClean(){EO(zl,Xl)}destroy(){this.destroyed=!0,EO(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Lct=class extends Mct{constructor(){super(64,wct)}},fb=Sle(()=>new Nct,Tle(1)),Dct=Sle(()=>new Lct,Tle(3)),Yde=Ele;Yde.sha512||(Yde.sha512=e=>Dct(e));var Jde=32;function vle(){return sct.randomSecretKey()}function vO(e){return Qat(e)}function kct(){let e=vle();return{secretKey:e,publicKey:vO(e)}}function Ile(e){if(e.length!==Jde)throw new Error(`Ed25519 seed must be ${Jde} bytes, got ${e.length}`);return{secretKey:e,publicKey:vO(e)}}function Uct(e,t){return tct(t,e)}function jct(e,t,r){return oct(t,r,e)}function Bct(e,t){return ect(t,e)}function Hct(e,t,r){return nct(t,r,e)}var Ple=SH.bytesToHex,TH=SH.hexToBytes,bH=SH.concatBytes;function wle(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Rle(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 ad(e){return wle(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function IO(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return Rle(r)}var qct=new TextEncoder,Vct={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};function Ole(e){let t=Ple(fb(e.payload)),r=`${e.messageId}
7
7
  ${e.senderPeerId}
8
8
  ${e.senderName}
9
9
  ${e.timestampMs}
@@ -168,7 +168,7 @@ Mongoose Error Code: ${t.code}`:""}`})}function Hse(e,t,r,n=void 0){r&&(0,sLr.sa
168
168
  `),KT(cue(),n+`
169
169
  `),Git()}catch{}}function Eue(e){try{let t=YT();if(!t)return;let r=Math.max(Date.now(),t.renderedAt+1),n={...t,refreshFailedAt:r,refreshErrorReason:jR(e).slice(0,200)};KT(LR(),JSON.stringify(n)+`
170
170
  `)}catch{}}function $T(){try{ut.unlinkSync(uue())}catch{}}function YT(){let e=LR();if(!ut.existsSync(e))return null;try{return JSON.parse(ut.readFileSync(e,"utf-8"))}catch{return null}}function yue(){return YT()?.status??null}function Wit(){if(process.env.JEST_WORKER_ID)return;let e=uue();try{if(ut.mkdirSync(jt.dirname(e),{recursive:!0}),!Xit(e))return;let t=process.argv[1]?jt.resolve(process.argv[1]):"";if(!t){$T();return}let r=xR(),n=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),o=r==="no-color"||n==="light"||n==="dark"?{}:{VISA_CLI_HUD_THEME:r};Fit(Date.now());let i=(0,iue.spawn)(process.execPath,[t,...aue],{detached:!0,stdio:"ignore",env:{...process.env,...o,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});i.once("error",$T),i.unref()}catch{$T()}}function jR(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 Yit=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function Jit(e){let t=[],r=`__VISA_CLI_HUD_SGR_${(0,AB.randomBytes)(8).toString("hex")}_`,n=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,i=>{if(!Yit.test(i))return"";let s=`${r}${t.length}__`;return t.push(i),s}),o=new RegExp(`${r}(\\d+)__`,"g");return jR(n).replace(o,(i,s)=>t[Number(s)]??"")}var Rr={get reset(){return eo().reset},get visaBlue(){return eo().visaBlue},get visaBlueSoft(){return eo().visaBlueSoft},get visaGold(){return eo().visaGold},get green(){return eo().green},get muted(){return eo().muted},get chrome(){return eo().chrome}};function qr(e,t){return e.length===0||process.env.NO_COLOR||MR()?e:`${t}${e}${Rr.reset}`}function nue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zit(){let e=WT.homedir();if(!e||!jt.isAbsolute(e))throw new Error("unable to determine a valid home directory");return jt.resolve(e)}function Xit(e){for(let t=0;t<2;t+=1){let r;try{return r=ut.openSync(e,"wx"),ut.writeFileSync(r,String(Date.now())),!0}catch(n){if(n?.code!=="EEXIST")return!1;try{let o=ut.statSync(e);if(Date.now()-o.mtimeMs<=Nit)return!1;ut.unlinkSync(e)}catch{}}finally{r!==void 0&&ut.closeSync(r)}}return!1}function oue(e){return e instanceof Error?e.message:"unknown file system error"}function KT(e,t){ut.mkdirSync(jt.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${(0,AB.randomBytes)(8).toString("hex")}.tmp`;try{ut.writeFileSync(r,t),ut.renameSync(r,e)}catch(n){try{ut.unlinkSync(r)}catch{}throw n}}var Zit=1440*60*1e3;function HR(e,t){Nn.mkdirSync(Zo.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${bue.randomBytes(8).toString("hex")}.tmp`;try{Nn.writeFileSync(r,JSON.stringify(t,null,2)+`
171
- `),Nn.renameSync(r,e)}catch(n){try{Nn.unlinkSync(r)}catch{}throw n}}function Sue(e){return`'${e.replace(/'/g,"'\\''")}'`}var PB="# visa-cli-hud-v1";function qR(e,t){if(!e&&!t&&Qit())return`visa-cli config statusline ${PB}`;let r=e??process.execPath,n=t??process.argv[1]??"",o=n?Zo.resolve(n):"";return`${o?`${Sue(r)} ${Sue(o)} config statusline`:"visa-cli config statusline"} ${PB}`}function Qit(){try{return(0,Aue.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function wB(e){return typeof e!="string"?!1:e.includes(PB)?!0:e.includes("visa-cli")&&e.includes("statusline")}function est(){return"5.0.0-rc.401"}function VR(e){let t=Zo.dirname(Zo.resolve(e));return Zo.basename(t)===".claude"?Zo.dirname(t):vue.homedir()}function BR(e,t){let r=Zo.relative(t,e);return!r.startsWith("..")&&!Zo.isAbsolute(r)?`~/${r}`:e}function tst(e){return Zo.join(VR(e),".visa-cli","hud-self-heal.json")}function rst(e,t,r,n){try{if(!Nn.existsSync(e))return!1;let o=JSON.parse(Nn.readFileSync(e,"utf-8"));return o.version===t&&typeof o.checkedAt=="number"&&r-o.checkedAt<n}catch{return!1}}function IB(e,t,r){try{HR(e,{version:t,checkedAt:r})}catch{}}function nst(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function FR(e,t={}){let r=t.now??Date.now(),n=t.version??est(),o=t.stampPath??tst(e),i=t.minIntervalMs??Zit,s=[],a=!1,c=!1;if(!t.force&&rst(o,n,r,i))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:s,skippedReason:"recently checked"};try{if(!Nn.existsSync(e))return IB(o,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s};let u=JSON.parse(Nn.readFileSync(e,"utf-8")),d=u.statusLine,l=d&&typeof d=="object"&&!Array.isArray(d)?d.command:"";if(!wB(l))return IB(o,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s};let p=(t.getCommand??qR)();if(l!==p&&(u.statusLine=nst(d,p),HR(e,u),a=!0,s.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!Iue()){let f=VR(e);if(UR(f).length>0){let h=vB(null,f);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let E=h.rcPaths.map(b=>BR(b,f)).join(", ");c=!0,s.push(`Cleaned legacy shell-prompt HUD block from ${E}.`)}}}return IB(o,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 connect claude
171
+ `),Nn.renameSync(r,e)}catch(n){try{Nn.unlinkSync(r)}catch{}throw n}}function Sue(e){return`'${e.replace(/'/g,"'\\''")}'`}var PB="# visa-cli-hud-v1";function qR(e,t){if(!e&&!t&&Qit())return`visa-cli config statusline ${PB}`;let r=e??process.execPath,n=t??process.argv[1]??"",o=n?Zo.resolve(n):"";return`${o?`${Sue(r)} ${Sue(o)} config statusline`:"visa-cli config statusline"} ${PB}`}function Qit(){try{return(0,Aue.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function wB(e){return typeof e!="string"?!1:e.includes(PB)?!0:e.includes("visa-cli")&&e.includes("statusline")}function est(){return"5.0.0-rc.402"}function VR(e){let t=Zo.dirname(Zo.resolve(e));return Zo.basename(t)===".claude"?Zo.dirname(t):vue.homedir()}function BR(e,t){let r=Zo.relative(t,e);return!r.startsWith("..")&&!Zo.isAbsolute(r)?`~/${r}`:e}function tst(e){return Zo.join(VR(e),".visa-cli","hud-self-heal.json")}function rst(e,t,r,n){try{if(!Nn.existsSync(e))return!1;let o=JSON.parse(Nn.readFileSync(e,"utf-8"));return o.version===t&&typeof o.checkedAt=="number"&&r-o.checkedAt<n}catch{return!1}}function IB(e,t,r){try{HR(e,{version:t,checkedAt:r})}catch{}}function nst(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function FR(e,t={}){let r=t.now??Date.now(),n=t.version??est(),o=t.stampPath??tst(e),i=t.minIntervalMs??Zit,s=[],a=!1,c=!1;if(!t.force&&rst(o,n,r,i))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:s,skippedReason:"recently checked"};try{if(!Nn.existsSync(e))return IB(o,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s};let u=JSON.parse(Nn.readFileSync(e,"utf-8")),d=u.statusLine,l=d&&typeof d=="object"&&!Array.isArray(d)?d.command:"";if(!wB(l))return IB(o,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s};let p=(t.getCommand??qR)();if(l!==p&&(u.statusLine=nst(d,p),HR(e,u),a=!0,s.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!Iue()){let f=VR(e);if(UR(f).length>0){let h=vB(null,f);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let E=h.rcPaths.map(b=>BR(b,f)).join(", ");c=!0,s.push(`Cleaned legacy shell-prompt HUD block from ${E}.`)}}}return IB(o,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 connect claude
172
172
  `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s}}}function ost(e,t){let r=VR(t),n=UR(r);if(n.length===0)return e;let o=n.map(i=>BR(i,r)).join(", ");return`${e}
173
173
  Note: a shell-prompt HUD block was detected in ${o}. If it is unintended, delete the lines between '# >>> visa-cli shell hud v2 >>>' and '# <<< visa-cli shell hud v2 <<<' in ${o}`}function Iue(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 Tue(e,t){let r=VR(t),n=UR(r);if(n.length===0)return e;let o=n.map(s=>BR(s,r)).join(", ");if(Iue())return`${e}
174
174
  Note: a legacy shell-prompt HUD block was detected in ${o}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. To remove it, unset VISA_HUD_KEEP_SHELL and run visa connect claude again, or delete the lines between '# >>> visa-cli shell hud v2 >>>' and '# <<< visa-cli shell hud v2 <<<' in ${o}`;let i=vB(null,r);if(i.removed&&i.rcPaths&&i.rcPaths.length>0){let s=i.rcPaths.map(a=>BR(a,r)).join(", ");return`${e}
@@ -206,7 +206,7 @@ Note: a legacy shell-prompt HUD block was detected in ${o} but could not be auto
206
206
 
207
207
  `)}function lde(e,t="global"){let r=t==="project"?Ue.join(process.cwd(),".mcp.json"):WB(e);try{let n=Ue.dirname(r);bt.existsSync(n)||bt.mkdirSync(n,{recursive:!0});let o=JB(e,t),i=iat();if(o==="toml"){let s=bt.existsSync(r)?bt.readFileSync(r,"utf-8"):"",a=aat(s,"visa-cli",i);bt.writeFileSync(r,a)}else if(o==="yaml"){let s=bt.existsSync(r)?bt.readFileSync(r,"utf-8"):"",a=lat(s,"visa-cli",i);bt.writeFileSync(r,a)}else{let s={};if(bt.existsSync(r))try{s=JSON.parse(bt.readFileSync(r,"utf-8"))}catch{s={}}for(let[c,u]of Object.entries(e.seedConfig??{}))c in s||(s[c]=u);let a=sat(s,e.configKey);a["visa-cli"]=e.buildEntry?e.buildEntry(i):i,bt.writeFileSync(r,JSON.stringify(s,null,2)+`
208
208
  `)}}catch(n){throw tat(n)?new KB(e,r,n):n}return{installed:!0,configPath:r,message:e.postInstallHint}}function fde(e,t="global"){let r=t==="project"?Ue.join(process.cwd(),".mcp.json"):WB(e);if(!bt.existsSync(r))return{removed:!1,configPath:r};let n=JB(e,t);if(n==="toml"){let s=bt.readFileSync(r,"utf-8");return cde(s,"visa-cli")?(bt.writeFileSync(r,cat(s,"visa-cli")),{removed:!0,configPath:r}):{removed:!1,configPath:r}}if(n==="yaml"){let s=bt.readFileSync(r,"utf-8");return dde(s,"visa-cli")?(bt.writeFileSync(r,fat(s,"visa-cli")),{removed:!0,configPath:r}):{removed:!1,configPath:r}}let o;try{o=JSON.parse(bt.readFileSync(r,"utf-8"))}catch{return{removed:!1,configPath:r}}let i=sde(o,e.configKey);return!i||!i["visa-cli"]?{removed:!1,configPath:r}:(delete i["visa-cli"],bt.writeFileSync(r,JSON.stringify(o,null,2)+`
209
- `),{removed:!0,configPath:r})}function ZB(e,t="global"){let r=t==="project"?Ue.join(process.cwd(),".mcp.json"):WB(e);if(!bt.existsSync(r))return!1;let n=JB(e,t);if(n==="toml")try{let o=bt.readFileSync(r,"utf-8");return!!cde(o,"visa-cli")}catch{return!1}if(n==="yaml")try{let o=bt.readFileSync(r,"utf-8");return!!dde(o,"visa-cli")}catch{return!1}try{let o=JSON.parse(bt.readFileSync(r,"utf-8"));return!!sde(o,e.configKey)?.["visa-cli"]}catch{return!1}}var Qh=require("node:crypto"),rd=j(require("node:fs")),eH=j(require("node:path"));Vl();Bh();jl();Xo();var pat=15*6e4;function nd(e=process.env){return eH.join(Tt(e),"session-recovery")}var _at="pending.json",QB=/^[A-Za-z0-9_-]{43}$/,pde="ABCDEFGHJKMNPQRSTUVWXYZ23456789",mat=6,gat=512,hat=2048,mde=2147483647;function H_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function iO(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Eat(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 Qo(e){if(typeof e!="string"||e.length===0||e.length>hat)throw new Error("v4 sign-in URL must be a bounded web origin");let t;try{t=new URL(e)}catch{throw new Error("v4 sign-in URL must be a bounded web origin")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.pathname!==""&&t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&Eat(t.hostname)))throw new Error("v4 sign-in URL must use an HTTPS origin (or HTTP loopback)");return t.origin}function od(e){let t=(0,Qh.createHash)("sha256").update(`${e}:visa-cli-handoff-confirm`,"utf8").digest(),r="";for(let n=0;n<mat;n+=1)r+=pde[t[n]%pde.length];return r}function nb(e=nd()){return eH.join(e,_at)}function yat(e){rd.mkdirSync(e,{recursive:!0,mode:448});let t=rd.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("login recovery directory must be a real directory, not a symlink");rd.chmodSync(e,448),So(e)}function Sat(e){if(!H_(e)||!iO(e,["verifier","challenge","baseUrl","createdAt","expiresAt","serverSkewMs"])||typeof e.verifier!="string"||!QB.test(e.verifier)||typeof e.challenge!="string"||!QB.test(e.challenge)||typeof e.baseUrl!="string"||!Number.isSafeInteger(e.createdAt)||e.createdAt<0||e.expiresAt!==void 0&&(!Number.isSafeInteger(e.expiresAt)||e.expiresAt<0)||e.serverSkewMs!==void 0&&!Number.isSafeInteger(e.serverSkewMs))return!1;try{return Qo(e.baseUrl)===e.baseUrl&&(0,Qh.createHash)("sha256").update(e.verifier,"utf8").digest("base64url")===e.challenge}catch{return!1}}function gde(e=nd()){let t=To(nb(e),{maxBytes:8192});if(t===null)return null;let r;try{r=JSON.parse(t)}catch{throw new Error("local login recovery state contains invalid JSON")}if(!Sat(r))throw new Error("local login recovery state is invalid");return r}function tH(e){return e.expiresAt!==void 0?{deadline:e.expiresAt,skewMs:e.serverSkewMs??0,source:"server"}:{deadline:e.createdAt+pat,skewMs:0,source:"local"}}function eE(e=Date.now(),t=nd()){let r=gde(t);if(!r)return null;let n=od(r.verifier),{deadline:o,skewMs:i,source:s}=tH(r),a=Math.max(0,o-(e+i)),c=Math.floor(a/1e3),u=yde(r,e);return{verifier:r.verifier,challenge:r.challenge,confirmCode:n,baseUrl:r.baseUrl,createdAt:r.createdAt,expiresAt:new Date(o-i).toISOString(),remainingSeconds:c,likelyExpired:u,expirySource:s}}function _de(e=nd()){So(e)&&rd.rmSync(nb(e),{force:!0})}var Tat="/api/vgs/cli-handoff/announce",hde="This Visa server has no terminal sign-in endpoint, so sign-in cannot finish. This is a server problem, not something you did. Please report it.";function Ede(e){return!H_(e)||typeof e.error!="string"&&e.ok===void 0}async function bat(e,t,r,n){try{let o=await r(`${e.baseUrl}${Tat}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({challenge:e.challenge}),signal:AbortSignal.timeout(n),redirect:"error"}),i=await o.json().catch(()=>null);if(o.status===404&&Ede(i))return"route_missing";if(!o.ok||!H_(i)||i.ok!==!0)return null;let s=typeof i.serverTime=="string"?Date.parse(i.serverTime):NaN,a=i.ttlMs;return!Number.isSafeInteger(s)||s<0||typeof a!="number"||!Number.isSafeInteger(a)||a<=0||a>mde?null:{expiresAt:s+a,skewMs:s-t}}catch{return null}}async function sO(e,t=Date.now(),r=nd(),n={}){if(!Number.isSafeInteger(t)||t<0)throw new Error("login handoff time is invalid");let o=Qo(e),i=rb(n.requestTimeoutMs,5e3,"login announce timeout"),s=n.fetchImpl??fetch;if(n.verifier!==void 0&&!QB.test(n.verifier))throw new Error("login handoff verifier is invalid");let a=n.verifier??(0,Qh.randomBytes)(32).toString("base64url"),c=(0,Qh.createHash)("sha256").update(a,"utf8").digest("base64url"),u={verifier:a,challenge:c,baseUrl:o,createdAt:t};yat(r),Pn(nb(r),JSON.stringify(u,null,2));let d=await bat(u,t,s,i);if(d==="route_missing")throw rd.rmSync(nb(r),{force:!0}),new Error(hde);d&&(u.expiresAt=d.expiresAt,u.serverSkewMs=d.skewMs,Pn(nb(r),JSON.stringify(u,null,2)));let{deadline:l,skewMs:p,source:f}=tH(u);return{challenge:c,confirmCode:od(a),expiresAt:new Date(l-p).toISOString(),expirySource:f}}function rb(e,t,r){let n=e??t;if(!Number.isSafeInteger(n)||n<=0||n>mde)throw new Error(`${r} must be a positive integer within the supported range`);return n}function yde(e,t=Date.now()){let{deadline:r,skewMs:n}=tH(e);return t+n>r}function Aat(e){if(!H_(e)||!iO(e,["payload"])||!H_(e.payload)||!iO(e.payload,["cliSessionToken","ownerProfile"]))return null;let t=e.payload.cliSessionToken,r=e.payload.ownerProfile;return typeof t!="string"||!t.trim()||t.length>gat||!H_(r)||!iO(r,["ownerPublicId","loginLabel","authOrigin"])||typeof r.ownerPublicId!="string"||typeof r.loginLabel!="string"||typeof r.authOrigin!="string"?null:{sessionToken:t,ownerProfile:{ownerPublicId:r.ownerPublicId,loginLabel:r.loginLabel,authOrigin:r.authOrigin}}}async function tE(e,t={}){let r=t.loginDir??nd(),n;try{n=gde(r)}catch(b){return{status:"error",message:b instanceof Error?b.message:String(b)}}if(!n)return{status:"no_pending"};if(e!==void 0){let b;try{b=Qo(e)}catch(A){return{status:"error",message:A instanceof Error?A.message:String(A)}}if(b!==n.baseUrl)return{status:"error",message:"V4 sign-in origin does not match the pending handoff. Run agent login again."}}let o,i,s,a;try{o=rb(t.attempts,1,"login claim attempts"),i=rb(t.delayMs,1e3,"login claim interval"),s=rb(t.requestTimeoutMs,1e4,"login claim request timeout"),a=t.overallTimeoutMs===void 0?void 0:rb(t.overallTimeoutMs,1,"login claim overall timeout")}catch(b){return{status:"error",message:b instanceof Error?b.message:String(b)}}let c=t.fetchImpl??fetch,u=t.sleep??(b=>new Promise(A=>setTimeout(A,b))),d=t.now??Date.now,l=a===void 0?void 0:d()+a,p=`${n.baseUrl}/api/vgs/cli-handoff/claim`,f=null,m=n,h=m.expiresAt!==void 0,E=()=>f==="expired"||f==="unknown"&&h?{status:"not_ready",likelyExpired:!0,expirySource:"server"}:f==="pending"?{status:"not_ready",likelyExpired:!1,expirySource:"server"}:{status:"not_ready",likelyExpired:yde(m,d()),expirySource:"local"};for(let b=0;b<o;b+=1){let A=l===void 0?s:l-d();if(A<=0)return E();let S,T=AbortSignal.timeout(Math.max(1,Math.min(s,A)));try{S=await c(p,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({verifier:n.verifier}),signal:T,redirect:"error"})}catch(I){if(T.aborted||H_(I)&&I.name==="TimeoutError"){if(l!==void 0&&d()>=l)return E();if(b+1<o){let w=l===void 0?i:l-d();if(w<=0)return E();await u(Math.min(i,w));continue}return{status:"error",message:"V4 sign-in claim request timed out."}}if(b+1<o){let w=l===void 0?i:l-d();if(w<=0)return E();await u(Math.min(i,w));continue}return{status:"error",message:`Could not reach the v4 sign-in service: ${I instanceof Error?I.message:String(I)}`}}if(S.ok){let I=await S.json().catch(()=>null),w=Aat(I);if(!w)return{status:"error",message:"Sign-in response was not a session-only handoff. Restart with visa agent login --restart."};try{let N=Zae(w.ownerProfile);await ct.saveProfileSessionToken(N,w.sessionToken,{preserveLegacy:!0}),Qae(N),await ct.retireLegacySessionToken()}catch{return{status:"error",message:"The session reached this device but could not be saved. Fix local credential storage, then restart with visa agent login --restart."}}return _de(r),{status:"claimed"}}if(S.status===404){let I=await S.json().catch(()=>null);if(Ede(I))return{status:"error",message:hde};let w=typeof I?.serverTime=="string"&&typeof I.error=="string"?I.error:null;if(w==="expired"?f="expired":w==="unknown_handoff"?f="unknown":w==="not_ready"&&(f="pending"),f==="expired"||f==="unknown"&&h)return E();if(b+1<o){let N=l===void 0?i:l-d();if(N<=0)return E();await u(Math.min(i,N))}continue}if(S.status===409)return{status:"confirm_mismatch",confirmCode:od(n.verifier)};if(S.status===422)return _de(r),{status:"error",message:"Sign-in pickup was not login-only. Run agent login again."};if(S.status===429)return E();let v=await S.json().catch(()=>null);return{status:"error",message:typeof v?.error=="string"&&v.error.length<=512?v.error:`V4 sign-in claim failed (${S.status}).`}}return E()}B_();var vat="5.0.0-rc.401",Iat="https://app.visacli.sh",Sde="https://web-visa-code-preview.up.railway.app",Pat="/agent/enroll";function wat(e=vat){return/-(?:rc|alpha|beta)\./i.test(e)}function rH(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Rat(e=process.env){let t=e.VISA_AUTH_URL?.trim()||DB("auth.serverUrl");if(!t)return!1;try{return new URL(t).origin===new URL(kB).origin}catch{return!1}}function ka(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return t?rH(t):Rat(e)||wat()?Sde:Iat}function aO(e){return`${rH(e)}${Pat}`}var Tde="one-code-terminal-sign-in";async function cO(e,t){let r=t?.fetchImpl??fetch,n=t?.maxAttempts??3,o=t?.timeoutMs??5e3,i=t?.sleep??(d=>new Promise(l=>setTimeout(l,d))),s=`${rH(e)}/api/agent-enroll/health`,a=null,c=null;for(let d=1;d<=n;d++){t?.onProgress?.(d,n,s);try{if(c=await r(s,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(o)}),c.ok||c.status<500)break;d<n&&await i(d*100)}catch(l){c=null,a=l,d<n&&await i(d*100)}}if(!c){let d=a instanceof Error?a.message:String(a??"network error");return{ready:!1,kind:"network",warning:`Could not reach ${s}: ${d} \u2014 the link may not work yet.`,healthUrl:s}}if(!c.ok)return c.status<500?{ready:!1,kind:"client",warning:`V4 sign-in is unavailable on this deployment (${c.status} at ${s}); refusing to open the retired GitHub flow.`,healthUrl:s}:{ready:!1,kind:"server",warning:`V4 sign-in readiness check failed (${c.status}) at ${s} \u2014 the link may not work yet.`,healthUrl:s};let u=await c.json().catch(()=>null);return u?.clients?.auth!=="turnkey"?{ready:!1,kind:"auth_mode_mismatch",warning:`V4 sign-in is not enabled on this deployment (${e}); refusing to open the retired GitHub flow.`,healthUrl:s}:{ready:!0,healthUrl:s,features:Array.isArray(u.features)?u.features.filter(d=>typeof d=="string"):[]}}function bde(e,t=process.env,r){let{remedyPath:n,...o}=e;if(!n)return o;let i=r?.agentId??e.agentId,s=n;if(s==="/agent/enroll/limits")if(i){let a=e.code==="grant_expired"?"&renew=1":"";s=`/agent/enroll/limits?agent=${encodeURIComponent(i)}${a}`}else s="/agent/enroll/agents";return{...o,remedyUrl:`${ka(t)}${s}`}}vc();function nH(e,t={}){let r={success:!0,command:e,ts:new Date().toISOString()};for(let[n,o]of Object.entries(t))o!==void 0&&(r[n]=o);return r}function ob(e,t,r={}){let{code:n,cause:o,fix:i,nextAction:s,agentId:a,...c}=r,u=o!==void 0?Ac(o):void 0,d=a??u?.agentId,l=n?bo(n,d?{agentId:d}:{}):u??bo("unspecified_error"),p=bde(bo(l.code,{...i!==void 0?{fix:i}:{fix:l.fix},nextAction:s??l.nextAction,agentId:d}),process.env,d?{agentId:d}:void 0),f=cce(o),m={success:!1,command:e,ts:new Date().toISOString(),error:t,code:p.code,kind:p.kind,fix:p.fix,nextAction:p.nextAction,...p.remedyUrl?{remedyUrl:p.remedyUrl,remedyLabel:p.remedyLabel}:{},...f?{details:f}:{}};for(let[h,E]of Object.entries(c))E!==void 0&&(m[h]=E);return m}var ib=require("process"),Oat=["json","yaml","tsv","table"];function vde(e){return Oat.includes(e)}function q_(e,t){switch(t){case"json":ib.stdout.write(JSON.stringify(e)+`
209
+ `),{removed:!0,configPath:r})}function ZB(e,t="global"){let r=t==="project"?Ue.join(process.cwd(),".mcp.json"):WB(e);if(!bt.existsSync(r))return!1;let n=JB(e,t);if(n==="toml")try{let o=bt.readFileSync(r,"utf-8");return!!cde(o,"visa-cli")}catch{return!1}if(n==="yaml")try{let o=bt.readFileSync(r,"utf-8");return!!dde(o,"visa-cli")}catch{return!1}try{let o=JSON.parse(bt.readFileSync(r,"utf-8"));return!!sde(o,e.configKey)?.["visa-cli"]}catch{return!1}}var Qh=require("node:crypto"),rd=j(require("node:fs")),eH=j(require("node:path"));Vl();Bh();jl();Xo();var pat=15*6e4;function nd(e=process.env){return eH.join(Tt(e),"session-recovery")}var _at="pending.json",QB=/^[A-Za-z0-9_-]{43}$/,pde="ABCDEFGHJKMNPQRSTUVWXYZ23456789",mat=6,gat=512,hat=2048,mde=2147483647;function H_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function iO(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Eat(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 Qo(e){if(typeof e!="string"||e.length===0||e.length>hat)throw new Error("v4 sign-in URL must be a bounded web origin");let t;try{t=new URL(e)}catch{throw new Error("v4 sign-in URL must be a bounded web origin")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.pathname!==""&&t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&Eat(t.hostname)))throw new Error("v4 sign-in URL must use an HTTPS origin (or HTTP loopback)");return t.origin}function od(e){let t=(0,Qh.createHash)("sha256").update(`${e}:visa-cli-handoff-confirm`,"utf8").digest(),r="";for(let n=0;n<mat;n+=1)r+=pde[t[n]%pde.length];return r}function nb(e=nd()){return eH.join(e,_at)}function yat(e){rd.mkdirSync(e,{recursive:!0,mode:448});let t=rd.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("login recovery directory must be a real directory, not a symlink");rd.chmodSync(e,448),So(e)}function Sat(e){if(!H_(e)||!iO(e,["verifier","challenge","baseUrl","createdAt","expiresAt","serverSkewMs"])||typeof e.verifier!="string"||!QB.test(e.verifier)||typeof e.challenge!="string"||!QB.test(e.challenge)||typeof e.baseUrl!="string"||!Number.isSafeInteger(e.createdAt)||e.createdAt<0||e.expiresAt!==void 0&&(!Number.isSafeInteger(e.expiresAt)||e.expiresAt<0)||e.serverSkewMs!==void 0&&!Number.isSafeInteger(e.serverSkewMs))return!1;try{return Qo(e.baseUrl)===e.baseUrl&&(0,Qh.createHash)("sha256").update(e.verifier,"utf8").digest("base64url")===e.challenge}catch{return!1}}function gde(e=nd()){let t=To(nb(e),{maxBytes:8192});if(t===null)return null;let r;try{r=JSON.parse(t)}catch{throw new Error("local login recovery state contains invalid JSON")}if(!Sat(r))throw new Error("local login recovery state is invalid");return r}function tH(e){return e.expiresAt!==void 0?{deadline:e.expiresAt,skewMs:e.serverSkewMs??0,source:"server"}:{deadline:e.createdAt+pat,skewMs:0,source:"local"}}function eE(e=Date.now(),t=nd()){let r=gde(t);if(!r)return null;let n=od(r.verifier),{deadline:o,skewMs:i,source:s}=tH(r),a=Math.max(0,o-(e+i)),c=Math.floor(a/1e3),u=yde(r,e);return{verifier:r.verifier,challenge:r.challenge,confirmCode:n,baseUrl:r.baseUrl,createdAt:r.createdAt,expiresAt:new Date(o-i).toISOString(),remainingSeconds:c,likelyExpired:u,expirySource:s}}function _de(e=nd()){So(e)&&rd.rmSync(nb(e),{force:!0})}var Tat="/api/vgs/cli-handoff/announce",hde="This Visa server has no terminal sign-in endpoint, so sign-in cannot finish. This is a server problem, not something you did. Please report it.";function Ede(e){return!H_(e)||typeof e.error!="string"&&e.ok===void 0}async function bat(e,t,r,n){try{let o=await r(`${e.baseUrl}${Tat}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({challenge:e.challenge}),signal:AbortSignal.timeout(n),redirect:"error"}),i=await o.json().catch(()=>null);if(o.status===404&&Ede(i))return"route_missing";if(!o.ok||!H_(i)||i.ok!==!0)return null;let s=typeof i.serverTime=="string"?Date.parse(i.serverTime):NaN,a=i.ttlMs;return!Number.isSafeInteger(s)||s<0||typeof a!="number"||!Number.isSafeInteger(a)||a<=0||a>mde?null:{expiresAt:s+a,skewMs:s-t}}catch{return null}}async function sO(e,t=Date.now(),r=nd(),n={}){if(!Number.isSafeInteger(t)||t<0)throw new Error("login handoff time is invalid");let o=Qo(e),i=rb(n.requestTimeoutMs,5e3,"login announce timeout"),s=n.fetchImpl??fetch;if(n.verifier!==void 0&&!QB.test(n.verifier))throw new Error("login handoff verifier is invalid");let a=n.verifier??(0,Qh.randomBytes)(32).toString("base64url"),c=(0,Qh.createHash)("sha256").update(a,"utf8").digest("base64url"),u={verifier:a,challenge:c,baseUrl:o,createdAt:t};yat(r),Pn(nb(r),JSON.stringify(u,null,2));let d=await bat(u,t,s,i);if(d==="route_missing")throw rd.rmSync(nb(r),{force:!0}),new Error(hde);d&&(u.expiresAt=d.expiresAt,u.serverSkewMs=d.skewMs,Pn(nb(r),JSON.stringify(u,null,2)));let{deadline:l,skewMs:p,source:f}=tH(u);return{challenge:c,confirmCode:od(a),expiresAt:new Date(l-p).toISOString(),expirySource:f}}function rb(e,t,r){let n=e??t;if(!Number.isSafeInteger(n)||n<=0||n>mde)throw new Error(`${r} must be a positive integer within the supported range`);return n}function yde(e,t=Date.now()){let{deadline:r,skewMs:n}=tH(e);return t+n>r}function Aat(e){if(!H_(e)||!iO(e,["payload"])||!H_(e.payload)||!iO(e.payload,["cliSessionToken","ownerProfile"]))return null;let t=e.payload.cliSessionToken,r=e.payload.ownerProfile;return typeof t!="string"||!t.trim()||t.length>gat||!H_(r)||!iO(r,["ownerPublicId","loginLabel","authOrigin"])||typeof r.ownerPublicId!="string"||typeof r.loginLabel!="string"||typeof r.authOrigin!="string"?null:{sessionToken:t,ownerProfile:{ownerPublicId:r.ownerPublicId,loginLabel:r.loginLabel,authOrigin:r.authOrigin}}}async function tE(e,t={}){let r=t.loginDir??nd(),n;try{n=gde(r)}catch(b){return{status:"error",message:b instanceof Error?b.message:String(b)}}if(!n)return{status:"no_pending"};if(e!==void 0){let b;try{b=Qo(e)}catch(A){return{status:"error",message:A instanceof Error?A.message:String(A)}}if(b!==n.baseUrl)return{status:"error",message:"V4 sign-in origin does not match the pending handoff. Run agent login again."}}let o,i,s,a;try{o=rb(t.attempts,1,"login claim attempts"),i=rb(t.delayMs,1e3,"login claim interval"),s=rb(t.requestTimeoutMs,1e4,"login claim request timeout"),a=t.overallTimeoutMs===void 0?void 0:rb(t.overallTimeoutMs,1,"login claim overall timeout")}catch(b){return{status:"error",message:b instanceof Error?b.message:String(b)}}let c=t.fetchImpl??fetch,u=t.sleep??(b=>new Promise(A=>setTimeout(A,b))),d=t.now??Date.now,l=a===void 0?void 0:d()+a,p=`${n.baseUrl}/api/vgs/cli-handoff/claim`,f=null,m=n,h=m.expiresAt!==void 0,E=()=>f==="expired"||f==="unknown"&&h?{status:"not_ready",likelyExpired:!0,expirySource:"server"}:f==="pending"?{status:"not_ready",likelyExpired:!1,expirySource:"server"}:{status:"not_ready",likelyExpired:yde(m,d()),expirySource:"local"};for(let b=0;b<o;b+=1){let A=l===void 0?s:l-d();if(A<=0)return E();let S,T=AbortSignal.timeout(Math.max(1,Math.min(s,A)));try{S=await c(p,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({verifier:n.verifier}),signal:T,redirect:"error"})}catch(I){if(T.aborted||H_(I)&&I.name==="TimeoutError"){if(l!==void 0&&d()>=l)return E();if(b+1<o){let w=l===void 0?i:l-d();if(w<=0)return E();await u(Math.min(i,w));continue}return{status:"error",message:"V4 sign-in claim request timed out."}}if(b+1<o){let w=l===void 0?i:l-d();if(w<=0)return E();await u(Math.min(i,w));continue}return{status:"error",message:`Could not reach the v4 sign-in service: ${I instanceof Error?I.message:String(I)}`}}if(S.ok){let I=await S.json().catch(()=>null),w=Aat(I);if(!w)return{status:"error",message:"Sign-in response was not a session-only handoff. Restart with visa agent login --restart."};try{let N=Zae(w.ownerProfile);await ct.saveProfileSessionToken(N,w.sessionToken,{preserveLegacy:!0}),Qae(N),await ct.retireLegacySessionToken()}catch{return{status:"error",message:"The session reached this device but could not be saved. Fix local credential storage, then restart with visa agent login --restart."}}return _de(r),{status:"claimed"}}if(S.status===404){let I=await S.json().catch(()=>null);if(Ede(I))return{status:"error",message:hde};let w=typeof I?.serverTime=="string"&&typeof I.error=="string"?I.error:null;if(w==="expired"?f="expired":w==="unknown_handoff"?f="unknown":w==="not_ready"&&(f="pending"),f==="expired"||f==="unknown"&&h)return E();if(b+1<o){let N=l===void 0?i:l-d();if(N<=0)return E();await u(Math.min(i,N))}continue}if(S.status===409)return{status:"confirm_mismatch",confirmCode:od(n.verifier)};if(S.status===422)return _de(r),{status:"error",message:"Sign-in pickup was not login-only. Run agent login again."};if(S.status===429)return E();let v=await S.json().catch(()=>null);return{status:"error",message:typeof v?.error=="string"&&v.error.length<=512?v.error:`V4 sign-in claim failed (${S.status}).`}}return E()}B_();var vat="5.0.0-rc.402",Iat="https://app.visacli.sh",Sde="https://web-visa-code-preview.up.railway.app",Pat="/agent/enroll";function wat(e=vat){return/-(?:rc|alpha|beta)\./i.test(e)}function rH(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Rat(e=process.env){let t=e.VISA_AUTH_URL?.trim()||DB("auth.serverUrl");if(!t)return!1;try{return new URL(t).origin===new URL(kB).origin}catch{return!1}}function ka(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return t?rH(t):Rat(e)||wat()?Sde:Iat}function aO(e){return`${rH(e)}${Pat}`}var Tde="one-code-terminal-sign-in";async function cO(e,t){let r=t?.fetchImpl??fetch,n=t?.maxAttempts??3,o=t?.timeoutMs??5e3,i=t?.sleep??(d=>new Promise(l=>setTimeout(l,d))),s=`${rH(e)}/api/agent-enroll/health`,a=null,c=null;for(let d=1;d<=n;d++){t?.onProgress?.(d,n,s);try{if(c=await r(s,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(o)}),c.ok||c.status<500)break;d<n&&await i(d*100)}catch(l){c=null,a=l,d<n&&await i(d*100)}}if(!c){let d=a instanceof Error?a.message:String(a??"network error");return{ready:!1,kind:"network",warning:`Could not reach ${s}: ${d} \u2014 the link may not work yet.`,healthUrl:s}}if(!c.ok)return c.status<500?{ready:!1,kind:"client",warning:`V4 sign-in is unavailable on this deployment (${c.status} at ${s}); refusing to open the retired GitHub flow.`,healthUrl:s}:{ready:!1,kind:"server",warning:`V4 sign-in readiness check failed (${c.status}) at ${s} \u2014 the link may not work yet.`,healthUrl:s};let u=await c.json().catch(()=>null);return u?.clients?.auth!=="turnkey"?{ready:!1,kind:"auth_mode_mismatch",warning:`V4 sign-in is not enabled on this deployment (${e}); refusing to open the retired GitHub flow.`,healthUrl:s}:{ready:!0,healthUrl:s,features:Array.isArray(u.features)?u.features.filter(d=>typeof d=="string"):[]}}function bde(e,t=process.env,r){let{remedyPath:n,...o}=e;if(!n)return o;let i=r?.agentId??e.agentId,s=n;if(s==="/agent/enroll/limits")if(i){let a=e.code==="grant_expired"?"&renew=1":"";s=`/agent/enroll/limits?agent=${encodeURIComponent(i)}${a}`}else s="/agent/enroll/agents";return{...o,remedyUrl:`${ka(t)}${s}`}}vc();function nH(e,t={}){let r={success:!0,command:e,ts:new Date().toISOString()};for(let[n,o]of Object.entries(t))o!==void 0&&(r[n]=o);return r}function ob(e,t,r={}){let{code:n,cause:o,fix:i,nextAction:s,agentId:a,...c}=r,u=o!==void 0?Ac(o):void 0,d=a??u?.agentId,l=n?bo(n,d?{agentId:d}:{}):u??bo("unspecified_error"),p=bde(bo(l.code,{...i!==void 0?{fix:i}:{fix:l.fix},nextAction:s??l.nextAction,agentId:d}),process.env,d?{agentId:d}:void 0),f=cce(o),m={success:!1,command:e,ts:new Date().toISOString(),error:t,code:p.code,kind:p.kind,fix:p.fix,nextAction:p.nextAction,...p.remedyUrl?{remedyUrl:p.remedyUrl,remedyLabel:p.remedyLabel}:{},...f?{details:f}:{}};for(let[h,E]of Object.entries(c))E!==void 0&&(m[h]=E);return m}var ib=require("process"),Oat=["json","yaml","tsv","table"];function vde(e){return Oat.includes(e)}function q_(e,t){switch(t){case"json":ib.stdout.write(JSON.stringify(e)+`
210
210
  `);return;case"yaml":ib.stdout.write(Nat(e)+`
211
211
  `);return;case"tsv":ib.stdout.write(Cat(e)+`
212
212
  `);return;case"table":ib.stdout.write(xat(e)+`
@@ -214,10 +214,10 @@ Note: a legacy shell-prompt HUD block was detected in ${o} but could not be auto
214
214
  `)}function Ade(e){if(e===null)return"null";if(typeof e=="boolean"||typeof e=="number")return String(e);let t=String(e);return t===""?'""':/^[-?:,\[\]{}#&*!|>'"%@`]/.test(t)||/:\s|\s#/.test(t)||/^\s|\s$/.test(t)?JSON.stringify(t):t}function Cat(e){let t=[];for(let[r,n]of Object.entries(e)){if(n===void 0)continue;let o=Array.isArray(n)||n!==null&&typeof n=="object"?JSON.stringify(n):String(n);t.push(`${r} ${o}`)}return t.join(`
215
215
  `)}function xat(e){let t=[];for(let[n,o]of Object.entries(e)){if(o===void 0)continue;let i=Array.isArray(o)||o!==null&&typeof o=="object"?JSON.stringify(o):String(o);t.push([n,i])}let r=Math.max(...t.map(([n])=>n.length),1);return t.map(([n,o])=>`${n.padEnd(r)} ${o}`).join(`
216
216
  `)}Ms();var Ide=j(require("fs")),Pde=j(require("os")),rE=j(require("path"));function Mat(e){return[["openclaw",rE.join(e,".openclaw")],["hermes",rE.join(e,".hermes")],["claude-code",rE.join(e,".claude")],["codex",rE.join(e,".codex")],["gemini",rE.join(e,".gemini")]]}function oH(e=process.env,t={}){if(e.VISA_CLI_RUNTIME&&e.VISA_CLI_RUNTIME.trim().length>0)return e.VISA_CLI_RUNTIME.trim();if(e.AGENT_RUNTIME&&e.AGENT_RUNTIME.trim().length>0)return e.AGENT_RUNTIME.trim();let r=s=>Object.entries(e).some(([a,c])=>a.startsWith(s)&&typeof c=="string"&&c.trim()!==""),n=new Set;if(r("CODEX_")&&n.add("codex"),(typeof e.CLAUDECODE=="string"&&e.CLAUDECODE.trim()!==""||r("CLAUDE_CODE_")||typeof e.CLAUDE_PROJECT_DIR=="string"&&e.CLAUDE_PROJECT_DIR.trim()!=="")&&n.add("claude-code"),r("OPENCLAW_")&&n.add("openclaw"),r("HERMES_")&&n.add("hermes"),(r("ANTIGRAVITY_")||r("GEMINI_"))&&n.add("gemini"),n.size>0)return n.size===1?n.values().next().value:void 0;let o=t.home??Pde.homedir(),i=Mat(o).filter(([,s])=>Ide.existsSync(s));return i.length===1?i[0][0]:void 0}function uO(e=process.env,t={}){switch(oH(e,t)){case"claude-code":return"claude";case"codex":return"codex";case"openclaw":return"openclaw";case"hermes":return"hermes";case"gemini":return"gemini";default:return"claude"}}var Cde=require("crypto"),Qt=j(require("fs")),xde=j(require("os")),qt=j(require("path"));var wde={skills:[{name:"pair-visa-agent",sourcePackage:"visa-cli-openclaw"},{name:"visa-shopify-checkout",sourcePackage:"visa-cli-openclaw"},{name:"visa-ucp-shopping",sourcePackage:"visa-cli-openclaw"}]};var sb="pair-visa-agent",Rde=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Dat(e){let t=new Set;for(let r of e){if(!Rde.test(r.name)||!Rde.test(r.sourcePackage))throw new Error(`bundled skill ${JSON.stringify(r.name)} must use non-empty, path-safe name and sourcePackage segments`);if(t.has(r.name))throw new Error(`duplicate bundled skill name ${JSON.stringify(r.name)}`);t.add(r.name)}return e}var kat=Object.freeze(Dat(wde.skills.map(e=>Object.freeze({...e}))));function Mde(e){return kat.find(t=>t.name===e)??null}function Uat(e,t){let r=qt.join(e,".hermes","profiles"),n=t.HERMES_PROFILE?.trim();if(n)return qt.join(r,n,"skills");let o=[];try{o=Qt.readdirSync(r,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name).sort()}catch{return qt.join(e,".hermes","skills")}if(o.length===1)return qt.join(r,o[0],"skills");if(o.length>1)throw new Error(`this Hermes install has ${o.length} profiles (${o.join(", ")}) and skills load per profile \u2014 set HERMES_PROFILE to choose one, then run visa connect hermes again.`);return qt.join(e,".hermes","skills")}function jat(e,t={}){let r=t.home??xde.homedir();switch(e){case"openclaw":return qt.join(r,".openclaw","skills");case"hermes":return Uat(r,t.env??process.env);case"claude":case"claude-code":return qt.join(r,".claude","skills");case"codex":return qt.join(r,".codex","skills");default:return null}}function Bat(e,t=sb){let r=Mde(t);if(!r)return null;let n=[qt.join(e,"skills",r.name),qt.join(e,"..","skills",r.name),qt.join(e,"..","..",r.sourcePackage,"skills",r.name),qt.join(e,"..","..","..",r.sourcePackage,"skills",r.name)];for(let o of n)if(Qt.existsSync(qt.join(o,"SKILL.md")))return o;return null}function Hat(e){let{bundledDir:t,base:r,force:n}=e,o=e.skillName??sb;if(!Mde(o))throw new Error(`unknown bundled skill "${o}"`);if(!Qt.existsSync(qt.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t} (no SKILL.md)`);let i=qt.join(r,o),s=Qt.existsSync(i)&&Qt.readdirSync(i).length>0;if(s&&!n){if(e.acceptIdentical&&qat(t,i))return Ode(r,o,i),{installedDir:i,files:ab(i),overwrote:!1,unchanged:!0};if(!Nde(r,o,i))throw new Error(`${i} differs from this release and is not an unmodified Visa-managed install \u2014 preserve local edits, or run "visa connect --force-skill" to back it up and replace it.`)}if(Qt.mkdirSync(r,{recursive:!0}),s)if(Nde(r,o,i))Qt.rmSync(i,{recursive:!0,force:!0});else{let a=qt.join(r,".visa-cli-managed","backups");Qt.mkdirSync(a,{recursive:!0,mode:448});let c=new Date().toISOString().replace(/[:.]/g,"-");Qt.renameSync(i,qt.join(a,`${o}-${c}`))}return Qt.cpSync(t,i,{recursive:!0}),Ode(r,o,i),{installedDir:i,files:ab(i),overwrote:s,unchanged:!1}}function ab(e){let t=[],r=(n,o)=>{for(let i of Qt.readdirSync(n,{withFileTypes:!0})){let s=o?qt.join(o,i.name):i.name;i.isDirectory()?r(qt.join(n,i.name),s):t.push(s)}};return r(e,""),t.sort()}function qat(e,t){let r=ab(e),n=ab(t);if(r.length!==n.length)return!1;for(let o=0;o<r.length;o++)if(r[o]!==n[o]||!Qt.readFileSync(qt.join(e,r[o])).equals(Qt.readFileSync(qt.join(t,n[o]))))return!1;return!0}function Lde(e,t){return qt.join(e,".visa-cli-managed",`${t}.json`)}function Dde(e){return Object.fromEntries(ab(e).map(t=>[t,(0,Cde.createHash)("sha256").update(Qt.readFileSync(qt.join(e,t))).digest("hex")]))}function Ode(e,t,r){let n=Lde(e,t);Qt.mkdirSync(qt.dirname(n),{recursive:!0,mode:448}),Qt.writeFileSync(n,`${JSON.stringify({schema:1,skill:t,files:Dde(r)})}
217
- `,{mode:384})}function Nde(e,t,r){try{let n=JSON.parse(Qt.readFileSync(Lde(e,t),"utf8"));return n.schema===1&&n.skill===t&&JSON.stringify(n.files)===JSON.stringify(Dde(r))}catch{return!1}}function kde(e,t={}){let r;try{r=jat(e,t)}catch(o){return{status:"failed",detail:o instanceof Error?o.message:String(o)}}if(!r)return{status:"not-applicable",detail:"this client reads no skills directory"};let n=Bat(__dirname);if(!n)return{status:"failed",detail:`bundled ${sb} skill not found in this install`};try{let o=Hat({bundledDir:n,base:r,acceptIdentical:!0,force:t.force??!1});return o.unchanged?{status:"already",detail:`${sb} is already current in ${r}`}:{status:"planted",detail:`Planted ${sb} in ${o.installedDir}`}}catch(o){return{status:"failed",detail:o instanceof Error?o.message:String(o)}}}var GD=require("node:fs"),MI=require("node:path"),xg=require("node:crypto"),iQ=j(mp()),Qd=j(zu()),Mg=j(tQ());Xo();var FD=j(mp());async function rQ(e){let{key:t,approved:r,result:n}=e;if(!n.certificate.startsWith(r.preparedCertificate.signingInput+".")||!n.delegation.startsWith(r.preparedDelegation.signingInput+"."))throw new Error("financial_device_owner_result_invalid");let o={keys:[{...e.rootPublicJwk,kid:e.rootKid}]},i=Math.floor((e.nowMs??Date.now())/1e3),s=await(0,FD.verifyRuntimeCertificate)(n.certificate,{jwks:o,nowSec:e.certificateAsOfIssue?r.preparedCertificate.claims.iat:i,expectedAgentId:t.binding.agentId,expectedRootJkt:t.binding.rootJkt,expectedRuntimeId:t.runtimeId,expectedRuntimeJkt:t.jkt,requiredPurpose:"wallet:x402"}),a=await(0,FD.verifyRuntimeDelegation)(n.delegation,{ownerJwks:o,nowSec:i,expectedRootKid:e.rootKid,expectedRootJkt:t.binding.rootJkt,expectedAgentId:t.binding.agentId,expectedRuntimeId:t.runtimeId,expectedRuntimeJkt:t.jkt,expectedNetwork:"eip155:8453",expectedLeaseIssuerJkt:r.preparedDelegation.claims.leaseIssuerJkt,expectedDelegationId:r.preparedDelegation.claims.jti});if(!a.ok&&a.reason==="delegation_expired")throw new Error("runtime_delegation_expired");if(n.v!==1||n.runtimeId!==t.runtimeId||n.childJkt!==t.jkt||!s.ok||!a.ok||a.delegation.custody==="gate")throw new Error("financial_device_owner_result_invalid");return n}Ms();function ES(e,t){if(!/^[0-9a-f-]{36}$/.test(e))throw new Error("financial_device_agent_invalid");let r=(0,MI.join)(Tt(t),"financial-device");return(0,GD.mkdirSync)(r,{recursive:!0,mode:448}),(0,MI.join)(r,e+".pending.json")}function yS(e,t){let r=ss(ES(e,t));if(r===null)return null;On(r);let n=JSON.parse(r);if((0,Mg.financialDeviceProposalHash)(n.proposal),n.cardProposal&&(0,Mg.assertFinancialDevicePair)(n.proposal,n.cardProposal),n.v===1&&!Object.prototype.hasOwnProperty.call(n,"ceremony")){let o=ES(e,t),i=o.replace(".pending.json",`.outdated.${n.proposal.requestId}.json`);throw(0,GD.renameSync)(o,i),new Error(`financial_device_record_outdated: this device's wallet approval was started by an older Visa CLI and cannot be resumed (kept as ${(0,MI.basename)(i)}). Re-enroll: run \`visa connect\` again.`)}if(n.v!==1||!n.ceremony||typeof n.ceremony!="object"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(n.ceremony.ceremonyId)||!/^[A-Za-z0-9_-]{43}$/.test(n.ceremony.challenge)||!/^[A-Za-z0-9_-]{43}$/.test(n.ceremony.verifier)||(0,xg.createHash)("sha256").update(n.ceremony.verifier).digest("base64url")!==n.ceremony.challenge||n.proposal.agentId!==e||n.runtimeKey.binding.agentId!==e||n.runtimeKey.runtimeId!==n.proposal.runtimeId||n.runtimeKey.binding.rootJkt!==n.proposal.rootJkt||(0,iQ.computeJkt)(n.rootPublicJwk)!==n.proposal.rootJkt)throw new Error("financial_device_record_invalid");return n}function nQ(e,t){let r=JSON.stringify(e);On(r),vi(ES(e.proposal.agentId,t),r)}async function LI(e){let t=yS(e.agentId,e.env);if(t){if((0,Qd.canonicalJson)(t.ceremony)!==(0,Qd.canonicalJson)(e.ceremony))throw new Error("financial_device_ceremony_changed");let s=await e.api.financialRuntimeRequest("device-handoff-create",{requestId:t.proposal.requestId,proposal:t.proposal,ceremony:t.ceremony,...t.cardProposal?{cardProposal:t.cardProposal}:{}}),a=Math.floor(Date.now()/1e3),c=s.prepared?.status==="active",u=f=>{if(typeof f!="string")throw new Error("financial_device_record_invalid");let m=JSON.parse(Buffer.from(f.split(".")[1]??"","base64url").toString()).exp;if(!Number.isSafeInteger(m))throw new Error("financial_device_record_invalid");return m>a},d=c&&u(s.prepared?.certificate)&&u(s.prepared?.delegation),l=!s.prepared||s.prepared.status==="pending"&&s.prepared.challenge.expiresAt>a;if(d||!c&&!s.expired&&l)return t;let p={v:1,ceremony:t.ceremony,proposal:{...t.proposal,requestId:(0,xg.randomUUID)()},runtimeKey:t.runtimeKey,rootKid:t.rootKid,rootPublicJwk:t.rootPublicJwk,...t.cardProposal?{cardProposal:t.cardProposal}:{}};try{await e.api.financialRuntimeRequest("device-handoff-create",{requestId:p.proposal.requestId,proposal:p.proposal,ceremony:p.ceremony,...p.cardProposal?{cardProposal:p.cardProposal}:{}})}catch(f){let m=h1e(f)?await E1e(e.agentId,e.env,t.proposal.requestId):null;if(m)return m;throw f}return vi(ES(e.agentId,e.env).replace(".pending.json",`.expired.${t.proposal.requestId}.json`),JSON.stringify(t)),nQ(p,e.env),p}let r=await e.api.financialRuntimeRequest("device-context",{requestId:(0,xg.randomUUID)(),agentId:e.agentId});if(r.agentId!==e.agentId||(0,iQ.computeJkt)(r.rootPublicJwk)!==r.rootJkt)throw new Error("financial_device_context_invalid");if(e.ownerPublicId!==void 0&&typeof r.ownerPublicId=="string"&&r.ownerPublicId!==e.ownerPublicId)throw new Error("Protected wallet owner differs from the active profile");let n=await e.signer.create({profile:"legacy-root-certified-v1",purpose:"wallet:x402",agentId:e.agentId,rootJkt:r.rootJkt}),o={v:1,purpose:"financial.runtime.device.proposal",requestId:(0,xg.randomUUID)(),associationId:r.associationId,associationVersion:r.associationVersion,agentId:e.agentId,runtimeId:n.runtimeId,rootJkt:r.rootJkt,publicJwk:n.publicJwk};(0,Mg.financialDeviceProposalHash)(o),e.cardProposal&&(0,Mg.assertFinancialDevicePair)(o,e.cardProposal);let i={v:1,ceremony:e.ceremony,proposal:o,...e.cardProposal?{cardProposal:e.cardProposal}:{},runtimeKey:n,rootKid:r.rootKid,rootPublicJwk:r.rootPublicJwk};return nQ(i,e.env),i}var hS=class extends Error{constructor(r=!1){super(r?ZJt:"This enrollment ceremony expired. Start a fresh enrollment; this expired proposal cannot be approved.");this.stopped=r;this.name="FinancialDeviceExpiredError"}stopped},ZJt="The owner stopped this device approval (the agent was removed), so visa connect did not renew it. Nothing was connected. Run visa connect again once the owner wants this agent connected.";function h1e(e){return e instanceof Error&&e.name==="ProtectedAuthorityRefusedError"&&Number(e.status)<500&&!oQ(e)}async function E1e(e,t,r){for(let n=0;;n++){let o=yS(e,t);if(o&&o.proposal.requestId!==r)return o;if(n>=QJt)return null;await new Promise(i=>setTimeout(i,e7t))}}var QJt=20,e7t=50;function oQ(e){return e instanceof Error&&e.name==="ProtectedAuthorityRefusedError"&&e.code==="agent_revoked"}async function SS(e){let t=e.pending,r=t.proposal,n=await e.signer.describe(t.runtimeKey.handle);if((0,Qd.canonicalJson)(n)!==(0,Qd.canonicalJson)(t.runtimeKey)||n.binding.profile!=="legacy-root-certified-v1"||n.binding.purpose!=="wallet:x402")throw new Error("financial_device_handle_changed");let o=async(c,u={})=>e.api.financialRuntimeRequest(c,{requestId:r.requestId,proposal:r,...c==="device-handoff-create"?{ceremony:t.ceremony,...t.cardProposal?{cardProposal:t.cardProposal}:{}}:{},...u}),i=await o("device-handoff-create");if(i.expired&&i.prepared?.status!=="active")throw new hS(i.prepared?.status==="revoked");if((0,Qd.canonicalJson)(i.proposal)!==(0,Qd.canonicalJson)(r))throw new Error("financial_device_proposal_mismatch");let s=i.evidence?.owner_signatures,a=i.prepared;if(s&&a&&!i.evidence?.device_proof){if(await rQ({key:n,rootKid:t.rootKid,rootPublicJwk:t.rootPublicJwk,approved:a.challenge,result:{v:1,runtimeId:r.runtimeId,childJkt:n.jkt,...s}}),t.challenge&&(0,Qd.canonicalJson)(t.challenge)!==(0,Qd.canonicalJson)(a.challenge))throw new Error("financial_device_challenge_changed");t.childPop||(t.challenge=a.challenge,t.childPop=await e.signer.financialEnrollmentProof(n.handle,a.challenge),nQ(t,e.env)),i=await o("device-handoff-proof",{childPop:t.childPop})}return i}function Lg(e,t){let r=ss(ES(e,t).replace(".pending.json",".active.json"));if(r===null)return null;On(r);let n=JSON.parse(r);if((0,Mg.financialDeviceProposalHash)(n.proposal),n.v!==1||n.proposal.agentId!==e||n.runtimeKey.binding.agentId!==e||n.runtimeKey.binding.profile!=="legacy-root-certified-v1"||n.runtimeKey.binding.purpose!=="wallet:x402"||!n.challenge||!n.certificate||!n.delegation)throw new Error("financial_device_record_invalid");return n}async function t7t(e){let t=await SS(e);return e.onView?.(t),sQ({...e,view:t})}async function sQ(e){let t=e.pending,r=t.proposal,n=e.view;if(n?.prepared?.status!=="active")return null;let o=await e.signer.describe(t.runtimeKey.handle),i=await rQ({key:o,rootKid:t.rootKid,rootPublicJwk:t.rootPublicJwk,approved:n.prepared.challenge,result:{v:1,runtimeId:r.runtimeId,childJkt:o.jkt,certificate:n.prepared.certificate,delegation:n.prepared.delegation}}),s=await e.api.financialRuntimeRequest("device-context",{requestId:(0,xg.randomUUID)(),agentId:r.agentId});if(s.associationId!==r.associationId||s.associationVersion!==r.associationVersion||s.rootJkt!==r.rootJkt||typeof s.grantId!="string"||!Number.isSafeInteger(s.grantVersion)||s.grantVersion<1||typeof s.ownerPublicId!="string")throw new Error("financial_device_activation_changed");let a={...t,challenge:n.prepared.challenge,certificate:i.certificate,delegation:i.delegation,organizationId:s.organizationId,ownerPublicId:s.ownerPublicId,grantId:s.grantId,grantVersion:s.grantVersion},c=JSON.stringify(a);return On(c),vi(ES(r.agentId,e.env).replace(".pending.json",".active.json"),c),a}async function y1e(e){try{return{active:await t7t(e),pending:e.pending,renewed:!1}}catch(t){if(oQ(t))throw new hS(!0);let r=e.pending.ceremony&&h1e(t)?await E1e(e.pending.proposal.agentId,e.env,e.pending.proposal.requestId):null;if(r)return{active:null,pending:r,renewed:!0};if(!(t instanceof hS)||!e.pending.ceremony||t.stopped)throw t;let n=e.pending.proposal.requestId,o;try{o=await LI({api:e.api,signer:e.signer,agentId:e.pending.proposal.agentId,ceremony:e.pending.ceremony,env:e.env}),e.onView?.(await SS({...e,pending:o}))}catch(i){let s=i instanceof Error&&i.name==="ProtectedAuthorityRefusedError"&&i.status<500;throw Me.warn("agent:device_approval_renewal_refused",{agentId:e.pending.proposal.agentId,expiredRequestId:n,refused:s,error:i instanceof Error?i.message:String(i)}),oQ(i)?new hS(!0):s?t:i}return Me.info("agent:device_approval_renewed",{agentId:o.proposal.agentId,expiredRequestId:n,requestId:o.proposal.requestId}),{active:null,pending:o,renewed:!0}}}var DI=require("node:crypto"),fu=require("node:fs"),qn=require("node:path");var S1e=/^[A-Za-z0-9_-]{43}$/,r7t=/^[0-9a-f]{64}$/,n7t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function aQ(e,t){let r=e;return!!r&&typeof r=="object"&&r7t.test(r.handle)&&n7t.test(r.runtimeId)&&r.purpose===t&&S1e.test(r.jkt)&&!!r.publicJwk&&r.publicJwk.kty==="OKP"&&r.publicJwk.crv==="Ed25519"&&S1e.test(r.publicJwk.x)}function cQ(e){let t=e;if(!t||t.v!==2||!aQ(t.wallet,"wallet:x402")||!aQ(t.card,"card:vic")||!aQ(t.tap,"tap")||new Set([t.wallet.jkt,t.card.jkt,t.tap.jkt]).size!==3)throw new Error("device_key_reservation_invalid");return t}async function T1e(e){return{v:2,wallet:await e.reserve("wallet:x402"),card:await e.reserve("card:vic"),tap:await e.reserve("tap")}}function uQ(e){return`${e.wallet.jkt}.${e.card.jkt}.${e.tap.jkt}`}function b1e(e,t){let r={"wallet:x402":t.wallet,"card:vic":t.card,tap:t.tap};return{create:(n,o)=>e.adopt(r[n.purpose].handle,n,o),describe:n=>e.describe(n),delete:n=>e.delete(n),enrollmentProof:(n,o)=>e.enrollmentProof(n,o),handoffProof:(n,o)=>e.handoffProof(n,o),leaseProof:(n,o)=>e.leaseProof(n,o),tapProof:(n,o,i)=>e.tapProof(n,o,i),financialEnrollmentProof:(n,o)=>e.financialEnrollmentProof(n,o),cardEnrollmentProof:(n,o)=>e.cardEnrollmentProof(n,o),legacyProof:(n,o)=>e.legacyProof(n,o),legacyLeaseProof:(n,o)=>e.legacyLeaseProof(n,o),proofKey:n=>e.proofKey(n),close:()=>e.close()}}var I1e=j(mp()),bS=j(zu());Bh();jl();B_();Ms();vc();Xo();tO();QT();var A1e="5.0.0-rc.401",TS=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,kI=/^[A-Za-z0-9_-]{43}$/,P1e=e=>(0,DI.createHash)("sha256").update(e).digest("base64url");function Dg(e){let t=Qo(e);if(new URL(t).protocol!=="https:")throw new Error("Protected enrollment requires the HTTPS Auth origin");return t}function kg(e){let t=(0,qn.join)(Tt(e),"protected-enrollment");return(0,fu.mkdirSync)(t,{recursive:!0,mode:448}),So(t),t}function lQ(e,t,r){if(!e||e.status!=="active"||e.v!==1||!TS.test(e.ceremonyId)||e.challenge!==t||e.confirmCode!==r||!kI.test(t)||!/^[ABCDEFGHJKMNPQRSTUVWXYZ23456789]{6}$/.test(r)||!TS.test(e.agentId)||!TS.test(e.ownerPublicId)||!TS.test(e.associationId)||!Number.isSafeInteger(e.associationVersion)||e.associationVersion<1||typeof e.rootKid!="string"||!e.rootKid||typeof e.organizationId!="string"||!e.organizationId||(0,I1e.computeJkt)(e.rootPublicJwk)!==e.rootJkt)throw new Error("Protected enrollment result does not match this terminal")}function Ep(e){let t=To((0,qn.join)(kg(e),"pending.json"));if(t===null)return null;let r=JSON.parse(t);if(r.v!==1||!kI.test(r.verifier)||P1e(r.verifier)!==r.challenge||Dg(r.authorityOrigin)!==r.authorityOrigin||Dg(r.executionOrigin)!==r.executionOrigin||Qo(r.webOrigin)!==r.webOrigin||!Number.isSafeInteger(r.createdAt)||!(/^(?:ca_[A-Za-z0-9_-]{24})$/.test(r.ceremonyId)||TS.test(r.ceremonyId))||r.signIn!==void 0&&r.signIn!==!0)throw new Error("Protected enrollment pending state or transport profile changed");if(r.transportProfileId!==(wn(e)?.profileId??null)&&!fQ(r,e))throw new Error("Protected enrollment pending state or transport profile changed");if(r.binding&&(lQ(r.binding,r.challenge,od(r.verifier)),r.ceremonyId!==r.binding.ceremonyId))throw new Error("Protected enrollment ceremony changed");if(r.deviceKeys!==void 0&&cQ(r.deviceKeys),r.webStartKey!==void 0&&!kI.test(r.webStartKey))throw new Error("Protected enrollment pending state or transport profile changed");return r}var w1e=kI;function fQ(e,t){let r=wn(t);return e.signIn!==!0||e.binding||e.transportProfileId!==null||!r?!1:(e.transportProfileId=r.profileId,Pn((0,qn.join)(kg(t),"pending.json"),JSON.stringify(e)),!0)}function AS(e){return e.signIn===!0&&e.transportProfileId===null&&!e.binding}async function R1e(e,t,r){return e.deviceKeys?cQ(e.deviceKeys):(e.deviceKeys=await T1e(t),Pn((0,qn.join)(kg(r),"pending.json"),JSON.stringify(e)),e.deviceKeys)}function O1e(e,t){let r;try{r=Ep(t)}catch{return null}return r?.challenge===e&&r.deviceKeys?uQ(r.deviceKeys):null}var UI=9e5;function o7t(e,t){if(!e.binding)return!1;try{return Lg(e.binding.agentId,t)?.ceremony?.challenge===e.challenge}catch{return!1}}function i7t(e){try{return Ep(e)}catch(t){return Me.warn("agent:protected_enrollment_pending_replaced",{reason:t instanceof Error?t.message:"pending record could not be read"}),null}}function N1e(e){let t=Dg(Yl()),r=Qo(e.webOrigin);if(e.webStartKey!==void 0&&!kI.test(e.webStartKey))throw new Xt("That setup key is not one Visa issued. Copy the whole `visa connect --setup` line from the page that started the setup.","invalid_argument");let n=i7t(e.env),o=e.restart===!0||e.webStartKey!==void 0&&n?.webStartKey!==e.webStartKey,i=n!==null&&Date.now()-n.createdAt<UI;if(n&&i&&!o){if(n.authorityOrigin!==t||n.webOrigin!==r||n.executionOrigin!==t)throw new Error("Resume requires the original protected authority and browser origins");return n}if(n?.binding&&i&&o&&!o7t(n,e.env))throw new Xt("This enrollment is already bound. Resume its device approval before starting another agent.","enrollment_device_approval_pending");let s=(0,DI.randomBytes)(32).toString("base64url"),a={v:1,verifier:s,challenge:P1e(s),authorityOrigin:t,executionOrigin:t,webOrigin:r,transportProfileId:wn(e.env)?.profileId??null,createdAt:Date.now(),ceremonyId:"ca_"+(0,DI.randomBytes)(18).toString("base64url"),...e.webStartKey!==void 0?{webStartKey:e.webStartKey}:{},...e.signIn&&!wn(e.env)?{signIn:!0}:{}};return Pn((0,qn.join)(kg(e.env),"pending.json"),JSON.stringify(a)),a}var dQ={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes",gemini:"gemini",antigravity:"gemini","gemini-cli":"gemini"};function pQ(e=process.env,t){let r=(t??"").trim().toLowerCase().replace(/[\s_]+/g,"-");if(r&&dQ[r])return dQ[r];let n=oH(e);return n&&dQ[n]||null}var s7t="/api/vgs/cli-handoff/enrollment-code";async function C1e(e,t=fetch,r=5e3){if(e.binding)return!1;try{return(await t(`${e.webOrigin}${s7t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({challenge:e.challenge,confirm:od(e.verifier)}),redirect:"error",signal:AbortSignal.timeout(r)})).ok}catch{return!1}}function x1e(e,t){let r=new URL("/agent/enroll/protected-agent",e.webOrigin);return r.searchParams.set("cliChallenge",e.challenge),e.deviceKeys&&r.searchParams.set("keys",uQ(e.deviceKeys)),e.webStartKey&&r.searchParams.set("start",e.webStartKey),t&&r.searchParams.set("app",t),AS(e)&&r.searchParams.set("signin","1"),r.toString()}var a7t=2e4;var lu=class extends Error{constructor(r,n,o){super(n==="timeout"?`${r} timed out after ${Math.round(o/1e3)} s`:n==="response"?`${r} answered, but the answer could not be read`:`${r} could not be reached`);this.reason=n;this.name="ProtectedAuthorityTransportError"}reason},Yi=class extends Error{constructor(r,n,o,i=null,s=null,a=null){super(`${r} refused this request (HTTP ${n}${o?`, ${o}`:""})`);this.status=n;this.code=o;this.reason=i;this.purchaseId=s;this.approval=a;this.name="ProtectedAuthorityRefusedError"}status;code;reason;purchaseId;approval};function jI(e){let t=e&&typeof e=="object"?e.name:void 0;return typeof t=="string"?t:""}var c7t=/^[a-z][a-z0-9_]{0,63}$/;function u7t(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=o=>typeof o=="string"&&c7t.test(o)?o:null,n=r(t.code);return{code:n,reason:r(t.reason),approval:n==="owner_approval_required"?d7t(t.approval):null,purchaseId:t.reason==="terms_conflict"&&typeof t.purchaseId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t.purchaseId)?t.purchaseId:null}}function d7t(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let{approvalId:t,url:r,expiresAt:n}=e;return typeof t!="string"||t.length>64||typeof r!="string"||r.length>2048||typeof n!="string"||n.length>64?null:{approvalId:t,url:r,expiresAt:n}}async function M1e(e,t,r,n,o="Protected authority",i=a7t,s={}){let a;try{a=await n(Dg(e)+t,{method:"POST",headers:{...s,"content-type":"application/json","X-Source":"cli","X-Visa-CLI-Version":A1e,...Xh()},body:(0,bS.canonicalJson)(JSON.parse(JSON.stringify(r))),redirect:"error",signal:AbortSignal.timeout(i)})}catch(u){let d=jI(u);throw new lu(o,d==="TimeoutError"||d==="AbortError"?"timeout":"network",i)}if(!a.ok){let u;try{let p=await a.text();p.length<=262144&&(u=JSON.parse(p))}catch{}let d=QR(a.status,u,A1e);if(d)throw d;let l=u7t(u);throw new Yi(o,a.status,l.code,l.reason,l.purchaseId,l.approval)}let c;try{c=await a.text()}catch{throw new lu(o,"response",i)}if(c.length>262144)throw new lu(o,"response",i);try{return JSON.parse(c)}catch{throw new lu(o,"response",i)}}function l7t(e,t=fetch){return Dg(e),{financialRuntimeRequest:(r,n)=>M1e(e,`/v1/financial-runtime/${r}`,n,t)}}function f7t(e){return`This agent belongs to a different Visa account than ${e}, the account this terminal is signed in to, so nothing was connected. To use ${e}: run \`visa connect --restart\` and open the new link while signed in to ${e}. To use the other account instead: run \`visa disconnect --all\` to sign this terminal out, then \`visa connect\` and sign in with that account. \`visa disconnect --all\` also removes the Visa MCP server from every AI client, the spend HUD and any local card-delivery files; \`visa connect\` puts the server and HUD back for the client it runs for. Nothing is revoked on the server.`}async function L1e(e,t,r=fetch){if(e.transportProfileId!==(wn(t)?.profileId??null))throw new Error("Protected enrollment transport profile changed");if(e.binding)return v1e(e,e.binding,t),e.binding;if(AS(e))return null;let n=await M1e(e.executionOrigin,"/v1/enrollment/cli-claim",{verifier:e.verifier},r);if(n?.ok!==!0)throw new Error("Protected authority refused enrollment pickup");if(n.result?.status==="pending")return null;let o=n.result;lQ(o,e.challenge,od(e.verifier));let i=wn(t);if(i&&o.ownerPublicId!==i.ownerPublicId)throw new Xt(f7t(i.loginLabel),"enrollment_owner_mismatch");return e.ceremonyId=o.ceremonyId,e.binding=o,Pn((0,qn.join)(kg(t),"pending.json"),JSON.stringify(e)),v1e(e,o,t),o}function p7t(e,t){let r=Tt(t);if((0,fu.existsSync)((0,qn.join)(r,"financial-device",`${e}.active.json`)))return!0;try{let n=To((0,qn.join)(r,"card-device",`${e}.json`));if(n&&JSON.parse(n)?.certificate)return!0}catch{}return!1}function v1e(e,t,r){let n={v:1,authorityOrigin:e.authorityOrigin,executionOrigin:e.executionOrigin,transportProfileId:e.transportProfileId,binding:t},o=(0,qn.join)(kg(r),`${t.agentId}.json`),i=To(o);if(i!==null&&(0,bS.canonicalJson)(JSON.parse(i))!==(0,bS.canonicalJson)(n)){let s=null;try{s=JSON.parse(i)}catch{}if(!(s!==null&&_7t(s,n)||!p7t(t.agentId,r)))throw new Error("Protected agent selection changed");m7t(t.agentId,r)}Pn(o,JSON.stringify(n))}function _7t(e,t){let r=e?.binding,n=t.binding;return e?.v===1&&!!r&&r.agentId===n.agentId&&r.associationId===n.associationId&&r.ownerPublicId===n.ownerPublicId&&r.organizationId===n.organizationId&&r.rootJkt===n.rootJkt&&e.authorityOrigin===t.authorityOrigin&&e.executionOrigin===t.executionOrigin&&e.transportProfileId===t.transportProfileId&&r.challenge!==n.challenge&&Number.isSafeInteger(r.associationVersion)&&n.associationVersion>=r.associationVersion}function m7t(e,t){if(!/^[0-9a-f-]{36}$/.test(e))throw new Error("Protected agent id is invalid");let r=`.replaced-${new Date().toISOString().replace(/[:.]/g,"-")}`,n=Tt(t),o=i=>(i===`${e}.json`||i.startsWith(`${e}.`))&&i.endsWith(".json")&&!i.includes(".replaced-")&&!i.includes(".bak");for(let i of[(0,qn.join)(n,"protected-enrollment"),(0,qn.join)(n,"protected-enrollment","retired"),(0,qn.join)(n,"card-device"),(0,qn.join)(n,"financial-device"),(0,qn.join)(n,"financial-device-presence")])if((0,fu.existsSync)(i))for(let s of(0,fu.readdirSync)(i))o(s)&&(0,fu.renameSync)((0,qn.join)(i,s),(0,qn.join)(i,s+r));Me.info("protected-enrollment:replaced-agent-records-archived",{agentId:e})}function pu(e,t=fetch){let r=l7t(e.executionOrigin,t);return{financialRuntimeRequest:async(n,o)=>{let i=await r.financialRuntimeRequest(n,o);if(n==="device-context"){let s=e.binding;if(i.agentId!==s.agentId||i.ownerPublicId!==s.ownerPublicId||i.associationId!==s.associationId||i.associationVersion!==s.associationVersion||i.rootJkt!==s.rootJkt||i.rootKid!==s.rootKid||i.organizationId!==s.organizationId||(0,bS.canonicalJson)(i.rootPublicJwk)!==(0,bS.canonicalJson)(s.rootPublicJwk))throw new Error("Protected device context differs from the independently claimed owner")}return i}}}function _Q(e){let t=kg(e);return(0,fu.readdirSync)(t).filter(r=>TS.test(r.replace(/\.json$/,""))&&r.endsWith(".json")).flatMap(r=>{let n=To((0,qn.join)(t,r));if(n===null)return[];let o=JSON.parse(n);if(o.v!==1||Dg(o.authorityOrigin)!==o.authorityOrigin||Dg(o.executionOrigin)!==o.executionOrigin||o.binding.agentId+".json"!==r)throw new Error("Protected selection is invalid");return lQ(o.binding,o.binding.challenge,o.binding.confirmCode),[o]})}function Ug(e){let t=wn(e)?.profileId??null;return _Q(e).filter(r=>r.transportProfileId===t)}function D1e(e,t){let r=Ug(t).find(o=>o.binding.agentId===e.agentId&&o.binding.ownerPublicId===e.ownerPublicId&&o.authorityOrigin===e.authUrl);if(!r||!e.financialDeviceRuntimeId)return;let n=Lg(e.agentId,t);if(!n||n.runtimeKey.runtimeId!==e.financialDeviceRuntimeId||n.ownerPublicId!==r.binding.ownerPublicId||n.proposal.associationId!==r.binding.associationId||n.proposal.associationVersion!==r.binding.associationVersion||n.proposal.rootJkt!==r.binding.rootJkt||n.rootKid!==r.binding.rootKid)throw new Error("Protected wallet installation differs from its independently claimed owner");return r}var WD=j(require("node:fs")),H1e=j(require("node:path"));var ua=j(require("node:fs")),k1e=j(require("node:os")),el=j(require("node:path"));Xo();var U1e=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,g7t=U1e;function _u(e=process.env){if(e.VISA_V4_HOME)return e.VISA_V4_HOME;let t=e.VISA_CLI_HOME;return typeof t=="string"&&t.trim().length>0?el.join(t,".visa-v4"):el.join(k1e.homedir(),".visa-v4")}function j1e(e=_u()){return el.join(e,"owners")}function mQ(e=_u(),t){if(t!==void 0){if(!g7t.test(t))throw new Error("wallet owner id must be a canonical UUID");return el.join(j1e(e),t.toLowerCase(),"agents")}return el.join(e,"agents")}function vS(e,t=_u(),r){if(!U1e.test(e))throw new Error("wallet agent id must be a canonical UUID");return el.join(mQ(t,r),e.toLowerCase())}function $D(e){try{let t=ua.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`wallet runtime path is not a private directory: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t;ua.mkdirSync(e,{mode:448})}ua.chmodSync(e,448)}function B1e(e,t=_u(),r){if(ua.mkdirSync(t,{recursive:!0,mode:448}),r!==void 0){let i=j1e(t);$D(i),$D(el.dirname(mQ(t,r)))}let n=mQ(t,r);$D(n);let o=vS(e,t,r);return $D(o),o}Ms();jl();var h7t=/^0x[0-9a-f]{40}$/i,E7t=/^eip155:[1-9][0-9]{0,18}$/,KD=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,y7t="wallet-authority.json";function gQ(e=process.env){return _u(e)}function hQ(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&(t.financialDeviceRuntimeId===void 0||typeof t.financialDeviceRuntimeId=="string"&&KD.test(t.financialDeviceRuntimeId))&&(t.executionMode===void 0||t.executionMode==="direct_runtime"||t.executionMode==="managed")&&(t.walletBinding===void 0||/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t.walletBinding)&&t.walletBinding.length<=32*1024)&&(t.managedWallet===void 0||typeof t.managedWallet=="object"&&t.managedWallet!==null&&typeof t.managedWallet.organizationId=="string"&&t.managedWallet.organizationId.length>0&&typeof t.managedWallet.walletId=="string"&&t.managedWallet.walletId.length>0&&typeof t.managedWallet.address=="string"&&h7t.test(t.managedWallet.address)&&typeof t.managedWallet.network=="string"&&E7t.test(t.managedWallet.network))&&(t.activationState===void 0||t.activationState==="pending"||t.activationState==="active")&&(t.executionState===void 0||t.executionState==="active"||t.executionState==="recovery_only")&&typeof t.agentId=="string"&&KD.test(t.agentId)&&typeof t.agentName=="string"&&t.agentName.length>0&&t.agentName.length<=120&&(t.ownerPublicId===void 0||KD.test(t.ownerPublicId))&&typeof t.grantId=="string"&&KD.test(t.grantId)&&Number.isSafeInteger(t.grantVersion)&&t.grantVersion>0&&t.rail==="wallet:x402"&&typeof t.authUrl=="string"&&S7t(t.authUrl)&&typeof t.activatedAt=="string"&&Number.isFinite(Date.parse(t.activatedAt))}function S7t(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&t.username===""&&t.password===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&e===t.origin}catch{return!1}}function q1e(e=gQ()){return H1e.join(e,y7t)}function T7t(e,t){if(!hQ(e))throw new jg("wallet authority binding is invalid");WD.mkdirSync(t,{recursive:!0,mode:448}),WD.chmodSync(t,448),So(t),Pn(q1e(t),`${JSON.stringify(e,null,2)}
217
+ `,{mode:384})}function Nde(e,t,r){try{let n=JSON.parse(Qt.readFileSync(Lde(e,t),"utf8"));return n.schema===1&&n.skill===t&&JSON.stringify(n.files)===JSON.stringify(Dde(r))}catch{return!1}}function kde(e,t={}){let r;try{r=jat(e,t)}catch(o){return{status:"failed",detail:o instanceof Error?o.message:String(o)}}if(!r)return{status:"not-applicable",detail:"this client reads no skills directory"};let n=Bat(__dirname);if(!n)return{status:"failed",detail:`bundled ${sb} skill not found in this install`};try{let o=Hat({bundledDir:n,base:r,acceptIdentical:!0,force:t.force??!1});return o.unchanged?{status:"already",detail:`${sb} is already current in ${r}`}:{status:"planted",detail:`Planted ${sb} in ${o.installedDir}`}}catch(o){return{status:"failed",detail:o instanceof Error?o.message:String(o)}}}var GD=require("node:fs"),MI=require("node:path"),xg=require("node:crypto"),iQ=j(mp()),Qd=j(zu()),Mg=j(tQ());Xo();var FD=j(mp());async function rQ(e){let{key:t,approved:r,result:n}=e;if(!n.certificate.startsWith(r.preparedCertificate.signingInput+".")||!n.delegation.startsWith(r.preparedDelegation.signingInput+"."))throw new Error("financial_device_owner_result_invalid");let o={keys:[{...e.rootPublicJwk,kid:e.rootKid}]},i=Math.floor((e.nowMs??Date.now())/1e3),s=await(0,FD.verifyRuntimeCertificate)(n.certificate,{jwks:o,nowSec:e.certificateAsOfIssue?r.preparedCertificate.claims.iat:i,expectedAgentId:t.binding.agentId,expectedRootJkt:t.binding.rootJkt,expectedRuntimeId:t.runtimeId,expectedRuntimeJkt:t.jkt,requiredPurpose:"wallet:x402"}),a=await(0,FD.verifyRuntimeDelegation)(n.delegation,{ownerJwks:o,nowSec:i,expectedRootKid:e.rootKid,expectedRootJkt:t.binding.rootJkt,expectedAgentId:t.binding.agentId,expectedRuntimeId:t.runtimeId,expectedRuntimeJkt:t.jkt,expectedNetwork:"eip155:8453",expectedLeaseIssuerJkt:r.preparedDelegation.claims.leaseIssuerJkt,expectedDelegationId:r.preparedDelegation.claims.jti});if(!a.ok&&a.reason==="delegation_expired")throw new Error("runtime_delegation_expired");if(n.v!==1||n.runtimeId!==t.runtimeId||n.childJkt!==t.jkt||!s.ok||!a.ok||a.delegation.custody==="gate")throw new Error("financial_device_owner_result_invalid");return n}Ms();function ES(e,t){if(!/^[0-9a-f-]{36}$/.test(e))throw new Error("financial_device_agent_invalid");let r=(0,MI.join)(Tt(t),"financial-device");return(0,GD.mkdirSync)(r,{recursive:!0,mode:448}),(0,MI.join)(r,e+".pending.json")}function yS(e,t){let r=ss(ES(e,t));if(r===null)return null;On(r);let n=JSON.parse(r);if((0,Mg.financialDeviceProposalHash)(n.proposal),n.cardProposal&&(0,Mg.assertFinancialDevicePair)(n.proposal,n.cardProposal),n.v===1&&!Object.prototype.hasOwnProperty.call(n,"ceremony")){let o=ES(e,t),i=o.replace(".pending.json",`.outdated.${n.proposal.requestId}.json`);throw(0,GD.renameSync)(o,i),new Error(`financial_device_record_outdated: this device's wallet approval was started by an older Visa CLI and cannot be resumed (kept as ${(0,MI.basename)(i)}). Re-enroll: run \`visa connect\` again.`)}if(n.v!==1||!n.ceremony||typeof n.ceremony!="object"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(n.ceremony.ceremonyId)||!/^[A-Za-z0-9_-]{43}$/.test(n.ceremony.challenge)||!/^[A-Za-z0-9_-]{43}$/.test(n.ceremony.verifier)||(0,xg.createHash)("sha256").update(n.ceremony.verifier).digest("base64url")!==n.ceremony.challenge||n.proposal.agentId!==e||n.runtimeKey.binding.agentId!==e||n.runtimeKey.runtimeId!==n.proposal.runtimeId||n.runtimeKey.binding.rootJkt!==n.proposal.rootJkt||(0,iQ.computeJkt)(n.rootPublicJwk)!==n.proposal.rootJkt)throw new Error("financial_device_record_invalid");return n}function nQ(e,t){let r=JSON.stringify(e);On(r),vi(ES(e.proposal.agentId,t),r)}async function LI(e){let t=yS(e.agentId,e.env);if(t){if((0,Qd.canonicalJson)(t.ceremony)!==(0,Qd.canonicalJson)(e.ceremony))throw new Error("financial_device_ceremony_changed");let s=await e.api.financialRuntimeRequest("device-handoff-create",{requestId:t.proposal.requestId,proposal:t.proposal,ceremony:t.ceremony,...t.cardProposal?{cardProposal:t.cardProposal}:{}}),a=Math.floor(Date.now()/1e3),c=s.prepared?.status==="active",u=f=>{if(typeof f!="string")throw new Error("financial_device_record_invalid");let m=JSON.parse(Buffer.from(f.split(".")[1]??"","base64url").toString()).exp;if(!Number.isSafeInteger(m))throw new Error("financial_device_record_invalid");return m>a},d=c&&u(s.prepared?.certificate)&&u(s.prepared?.delegation),l=!s.prepared||s.prepared.status==="pending"&&s.prepared.challenge.expiresAt>a;if(d||!c&&!s.expired&&l)return t;let p={v:1,ceremony:t.ceremony,proposal:{...t.proposal,requestId:(0,xg.randomUUID)()},runtimeKey:t.runtimeKey,rootKid:t.rootKid,rootPublicJwk:t.rootPublicJwk,...t.cardProposal?{cardProposal:t.cardProposal}:{}};try{await e.api.financialRuntimeRequest("device-handoff-create",{requestId:p.proposal.requestId,proposal:p.proposal,ceremony:p.ceremony,...p.cardProposal?{cardProposal:p.cardProposal}:{}})}catch(f){let m=h1e(f)?await E1e(e.agentId,e.env,t.proposal.requestId):null;if(m)return m;throw f}return vi(ES(e.agentId,e.env).replace(".pending.json",`.expired.${t.proposal.requestId}.json`),JSON.stringify(t)),nQ(p,e.env),p}let r=await e.api.financialRuntimeRequest("device-context",{requestId:(0,xg.randomUUID)(),agentId:e.agentId});if(r.agentId!==e.agentId||(0,iQ.computeJkt)(r.rootPublicJwk)!==r.rootJkt)throw new Error("financial_device_context_invalid");if(e.ownerPublicId!==void 0&&typeof r.ownerPublicId=="string"&&r.ownerPublicId!==e.ownerPublicId)throw new Error("Protected wallet owner differs from the active profile");let n=await e.signer.create({profile:"legacy-root-certified-v1",purpose:"wallet:x402",agentId:e.agentId,rootJkt:r.rootJkt}),o={v:1,purpose:"financial.runtime.device.proposal",requestId:(0,xg.randomUUID)(),associationId:r.associationId,associationVersion:r.associationVersion,agentId:e.agentId,runtimeId:n.runtimeId,rootJkt:r.rootJkt,publicJwk:n.publicJwk};(0,Mg.financialDeviceProposalHash)(o),e.cardProposal&&(0,Mg.assertFinancialDevicePair)(o,e.cardProposal);let i={v:1,ceremony:e.ceremony,proposal:o,...e.cardProposal?{cardProposal:e.cardProposal}:{},runtimeKey:n,rootKid:r.rootKid,rootPublicJwk:r.rootPublicJwk};return nQ(i,e.env),i}var hS=class extends Error{constructor(r=!1){super(r?ZJt:"This enrollment ceremony expired. Start a fresh enrollment; this expired proposal cannot be approved.");this.stopped=r;this.name="FinancialDeviceExpiredError"}stopped},ZJt="The owner stopped this device approval (the agent was removed), so visa connect did not renew it. Nothing was connected. Run visa connect again once the owner wants this agent connected.";function h1e(e){return e instanceof Error&&e.name==="ProtectedAuthorityRefusedError"&&Number(e.status)<500&&!oQ(e)}async function E1e(e,t,r){for(let n=0;;n++){let o=yS(e,t);if(o&&o.proposal.requestId!==r)return o;if(n>=QJt)return null;await new Promise(i=>setTimeout(i,e7t))}}var QJt=20,e7t=50;function oQ(e){return e instanceof Error&&e.name==="ProtectedAuthorityRefusedError"&&e.code==="agent_revoked"}async function SS(e){let t=e.pending,r=t.proposal,n=await e.signer.describe(t.runtimeKey.handle);if((0,Qd.canonicalJson)(n)!==(0,Qd.canonicalJson)(t.runtimeKey)||n.binding.profile!=="legacy-root-certified-v1"||n.binding.purpose!=="wallet:x402")throw new Error("financial_device_handle_changed");let o=async(c,u={})=>e.api.financialRuntimeRequest(c,{requestId:r.requestId,proposal:r,...c==="device-handoff-create"?{ceremony:t.ceremony,...t.cardProposal?{cardProposal:t.cardProposal}:{}}:{},...u}),i=await o("device-handoff-create");if(i.expired&&i.prepared?.status!=="active")throw new hS(i.prepared?.status==="revoked");if((0,Qd.canonicalJson)(i.proposal)!==(0,Qd.canonicalJson)(r))throw new Error("financial_device_proposal_mismatch");let s=i.evidence?.owner_signatures,a=i.prepared;if(s&&a&&!i.evidence?.device_proof){if(await rQ({key:n,rootKid:t.rootKid,rootPublicJwk:t.rootPublicJwk,approved:a.challenge,result:{v:1,runtimeId:r.runtimeId,childJkt:n.jkt,...s}}),t.challenge&&(0,Qd.canonicalJson)(t.challenge)!==(0,Qd.canonicalJson)(a.challenge))throw new Error("financial_device_challenge_changed");t.childPop||(t.challenge=a.challenge,t.childPop=await e.signer.financialEnrollmentProof(n.handle,a.challenge),nQ(t,e.env)),i=await o("device-handoff-proof",{childPop:t.childPop})}return i}function Lg(e,t){let r=ss(ES(e,t).replace(".pending.json",".active.json"));if(r===null)return null;On(r);let n=JSON.parse(r);if((0,Mg.financialDeviceProposalHash)(n.proposal),n.v!==1||n.proposal.agentId!==e||n.runtimeKey.binding.agentId!==e||n.runtimeKey.binding.profile!=="legacy-root-certified-v1"||n.runtimeKey.binding.purpose!=="wallet:x402"||!n.challenge||!n.certificate||!n.delegation)throw new Error("financial_device_record_invalid");return n}async function t7t(e){let t=await SS(e);return e.onView?.(t),sQ({...e,view:t})}async function sQ(e){let t=e.pending,r=t.proposal,n=e.view;if(n?.prepared?.status!=="active")return null;let o=await e.signer.describe(t.runtimeKey.handle),i=await rQ({key:o,rootKid:t.rootKid,rootPublicJwk:t.rootPublicJwk,approved:n.prepared.challenge,result:{v:1,runtimeId:r.runtimeId,childJkt:o.jkt,certificate:n.prepared.certificate,delegation:n.prepared.delegation}}),s=await e.api.financialRuntimeRequest("device-context",{requestId:(0,xg.randomUUID)(),agentId:r.agentId});if(s.associationId!==r.associationId||s.associationVersion!==r.associationVersion||s.rootJkt!==r.rootJkt||typeof s.grantId!="string"||!Number.isSafeInteger(s.grantVersion)||s.grantVersion<1||typeof s.ownerPublicId!="string")throw new Error("financial_device_activation_changed");let a={...t,challenge:n.prepared.challenge,certificate:i.certificate,delegation:i.delegation,organizationId:s.organizationId,ownerPublicId:s.ownerPublicId,grantId:s.grantId,grantVersion:s.grantVersion},c=JSON.stringify(a);return On(c),vi(ES(r.agentId,e.env).replace(".pending.json",".active.json"),c),a}async function y1e(e){try{return{active:await t7t(e),pending:e.pending,renewed:!1}}catch(t){if(oQ(t))throw new hS(!0);let r=e.pending.ceremony&&h1e(t)?await E1e(e.pending.proposal.agentId,e.env,e.pending.proposal.requestId):null;if(r)return{active:null,pending:r,renewed:!0};if(!(t instanceof hS)||!e.pending.ceremony||t.stopped)throw t;let n=e.pending.proposal.requestId,o;try{o=await LI({api:e.api,signer:e.signer,agentId:e.pending.proposal.agentId,ceremony:e.pending.ceremony,env:e.env}),e.onView?.(await SS({...e,pending:o}))}catch(i){let s=i instanceof Error&&i.name==="ProtectedAuthorityRefusedError"&&i.status<500;throw Me.warn("agent:device_approval_renewal_refused",{agentId:e.pending.proposal.agentId,expiredRequestId:n,refused:s,error:i instanceof Error?i.message:String(i)}),oQ(i)?new hS(!0):s?t:i}return Me.info("agent:device_approval_renewed",{agentId:o.proposal.agentId,expiredRequestId:n,requestId:o.proposal.requestId}),{active:null,pending:o,renewed:!0}}}var DI=require("node:crypto"),fu=require("node:fs"),qn=require("node:path");var S1e=/^[A-Za-z0-9_-]{43}$/,r7t=/^[0-9a-f]{64}$/,n7t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function aQ(e,t){let r=e;return!!r&&typeof r=="object"&&r7t.test(r.handle)&&n7t.test(r.runtimeId)&&r.purpose===t&&S1e.test(r.jkt)&&!!r.publicJwk&&r.publicJwk.kty==="OKP"&&r.publicJwk.crv==="Ed25519"&&S1e.test(r.publicJwk.x)}function cQ(e){let t=e;if(!t||t.v!==2||!aQ(t.wallet,"wallet:x402")||!aQ(t.card,"card:vic")||!aQ(t.tap,"tap")||new Set([t.wallet.jkt,t.card.jkt,t.tap.jkt]).size!==3)throw new Error("device_key_reservation_invalid");return t}async function T1e(e){return{v:2,wallet:await e.reserve("wallet:x402"),card:await e.reserve("card:vic"),tap:await e.reserve("tap")}}function uQ(e){return`${e.wallet.jkt}.${e.card.jkt}.${e.tap.jkt}`}function b1e(e,t){let r={"wallet:x402":t.wallet,"card:vic":t.card,tap:t.tap};return{create:(n,o)=>e.adopt(r[n.purpose].handle,n,o),describe:n=>e.describe(n),delete:n=>e.delete(n),enrollmentProof:(n,o)=>e.enrollmentProof(n,o),handoffProof:(n,o)=>e.handoffProof(n,o),leaseProof:(n,o)=>e.leaseProof(n,o),tapProof:(n,o,i)=>e.tapProof(n,o,i),financialEnrollmentProof:(n,o)=>e.financialEnrollmentProof(n,o),cardEnrollmentProof:(n,o)=>e.cardEnrollmentProof(n,o),legacyProof:(n,o)=>e.legacyProof(n,o),legacyLeaseProof:(n,o)=>e.legacyLeaseProof(n,o),proofKey:n=>e.proofKey(n),close:()=>e.close()}}var I1e=j(mp()),bS=j(zu());Bh();jl();B_();Ms();vc();Xo();tO();QT();var A1e="5.0.0-rc.402",TS=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,kI=/^[A-Za-z0-9_-]{43}$/,P1e=e=>(0,DI.createHash)("sha256").update(e).digest("base64url");function Dg(e){let t=Qo(e);if(new URL(t).protocol!=="https:")throw new Error("Protected enrollment requires the HTTPS Auth origin");return t}function kg(e){let t=(0,qn.join)(Tt(e),"protected-enrollment");return(0,fu.mkdirSync)(t,{recursive:!0,mode:448}),So(t),t}function lQ(e,t,r){if(!e||e.status!=="active"||e.v!==1||!TS.test(e.ceremonyId)||e.challenge!==t||e.confirmCode!==r||!kI.test(t)||!/^[ABCDEFGHJKMNPQRSTUVWXYZ23456789]{6}$/.test(r)||!TS.test(e.agentId)||!TS.test(e.ownerPublicId)||!TS.test(e.associationId)||!Number.isSafeInteger(e.associationVersion)||e.associationVersion<1||typeof e.rootKid!="string"||!e.rootKid||typeof e.organizationId!="string"||!e.organizationId||(0,I1e.computeJkt)(e.rootPublicJwk)!==e.rootJkt)throw new Error("Protected enrollment result does not match this terminal")}function Ep(e){let t=To((0,qn.join)(kg(e),"pending.json"));if(t===null)return null;let r=JSON.parse(t);if(r.v!==1||!kI.test(r.verifier)||P1e(r.verifier)!==r.challenge||Dg(r.authorityOrigin)!==r.authorityOrigin||Dg(r.executionOrigin)!==r.executionOrigin||Qo(r.webOrigin)!==r.webOrigin||!Number.isSafeInteger(r.createdAt)||!(/^(?:ca_[A-Za-z0-9_-]{24})$/.test(r.ceremonyId)||TS.test(r.ceremonyId))||r.signIn!==void 0&&r.signIn!==!0)throw new Error("Protected enrollment pending state or transport profile changed");if(r.transportProfileId!==(wn(e)?.profileId??null)&&!fQ(r,e))throw new Error("Protected enrollment pending state or transport profile changed");if(r.binding&&(lQ(r.binding,r.challenge,od(r.verifier)),r.ceremonyId!==r.binding.ceremonyId))throw new Error("Protected enrollment ceremony changed");if(r.deviceKeys!==void 0&&cQ(r.deviceKeys),r.webStartKey!==void 0&&!kI.test(r.webStartKey))throw new Error("Protected enrollment pending state or transport profile changed");return r}var w1e=kI;function fQ(e,t){let r=wn(t);return e.signIn!==!0||e.binding||e.transportProfileId!==null||!r?!1:(e.transportProfileId=r.profileId,Pn((0,qn.join)(kg(t),"pending.json"),JSON.stringify(e)),!0)}function AS(e){return e.signIn===!0&&e.transportProfileId===null&&!e.binding}async function R1e(e,t,r){return e.deviceKeys?cQ(e.deviceKeys):(e.deviceKeys=await T1e(t),Pn((0,qn.join)(kg(r),"pending.json"),JSON.stringify(e)),e.deviceKeys)}function O1e(e,t){let r;try{r=Ep(t)}catch{return null}return r?.challenge===e&&r.deviceKeys?uQ(r.deviceKeys):null}var UI=9e5;function o7t(e,t){if(!e.binding)return!1;try{return Lg(e.binding.agentId,t)?.ceremony?.challenge===e.challenge}catch{return!1}}function i7t(e){try{return Ep(e)}catch(t){return Me.warn("agent:protected_enrollment_pending_replaced",{reason:t instanceof Error?t.message:"pending record could not be read"}),null}}function N1e(e){let t=Dg(Yl()),r=Qo(e.webOrigin);if(e.webStartKey!==void 0&&!kI.test(e.webStartKey))throw new Xt("That setup key is not one Visa issued. Copy the whole `visa connect --setup` line from the page that started the setup.","invalid_argument");let n=i7t(e.env),o=e.restart===!0||e.webStartKey!==void 0&&n?.webStartKey!==e.webStartKey,i=n!==null&&Date.now()-n.createdAt<UI;if(n&&i&&!o){if(n.authorityOrigin!==t||n.webOrigin!==r||n.executionOrigin!==t)throw new Error("Resume requires the original protected authority and browser origins");return n}if(n?.binding&&i&&o&&!o7t(n,e.env))throw new Xt("This enrollment is already bound. Resume its device approval before starting another agent.","enrollment_device_approval_pending");let s=(0,DI.randomBytes)(32).toString("base64url"),a={v:1,verifier:s,challenge:P1e(s),authorityOrigin:t,executionOrigin:t,webOrigin:r,transportProfileId:wn(e.env)?.profileId??null,createdAt:Date.now(),ceremonyId:"ca_"+(0,DI.randomBytes)(18).toString("base64url"),...e.webStartKey!==void 0?{webStartKey:e.webStartKey}:{},...e.signIn&&!wn(e.env)?{signIn:!0}:{}};return Pn((0,qn.join)(kg(e.env),"pending.json"),JSON.stringify(a)),a}var dQ={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes",gemini:"gemini",antigravity:"gemini","gemini-cli":"gemini"};function pQ(e=process.env,t){let r=(t??"").trim().toLowerCase().replace(/[\s_]+/g,"-");if(r&&dQ[r])return dQ[r];let n=oH(e);return n&&dQ[n]||null}var s7t="/api/vgs/cli-handoff/enrollment-code";async function C1e(e,t=fetch,r=5e3){if(e.binding)return!1;try{return(await t(`${e.webOrigin}${s7t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({challenge:e.challenge,confirm:od(e.verifier)}),redirect:"error",signal:AbortSignal.timeout(r)})).ok}catch{return!1}}function x1e(e,t){let r=new URL("/agent/enroll/protected-agent",e.webOrigin);return r.searchParams.set("cliChallenge",e.challenge),e.deviceKeys&&r.searchParams.set("keys",uQ(e.deviceKeys)),e.webStartKey&&r.searchParams.set("start",e.webStartKey),t&&r.searchParams.set("app",t),AS(e)&&r.searchParams.set("signin","1"),r.toString()}var a7t=2e4;var lu=class extends Error{constructor(r,n,o){super(n==="timeout"?`${r} timed out after ${Math.round(o/1e3)} s`:n==="response"?`${r} answered, but the answer could not be read`:`${r} could not be reached`);this.reason=n;this.name="ProtectedAuthorityTransportError"}reason},Yi=class extends Error{constructor(r,n,o,i=null,s=null,a=null){super(`${r} refused this request (HTTP ${n}${o?`, ${o}`:""})`);this.status=n;this.code=o;this.reason=i;this.purchaseId=s;this.approval=a;this.name="ProtectedAuthorityRefusedError"}status;code;reason;purchaseId;approval};function jI(e){let t=e&&typeof e=="object"?e.name:void 0;return typeof t=="string"?t:""}var c7t=/^[a-z][a-z0-9_]{0,63}$/;function u7t(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=o=>typeof o=="string"&&c7t.test(o)?o:null,n=r(t.code);return{code:n,reason:r(t.reason),approval:n==="owner_approval_required"?d7t(t.approval):null,purchaseId:t.reason==="terms_conflict"&&typeof t.purchaseId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t.purchaseId)?t.purchaseId:null}}function d7t(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let{approvalId:t,url:r,expiresAt:n}=e;return typeof t!="string"||t.length>64||typeof r!="string"||r.length>2048||typeof n!="string"||n.length>64?null:{approvalId:t,url:r,expiresAt:n}}async function M1e(e,t,r,n,o="Protected authority",i=a7t,s={}){let a;try{a=await n(Dg(e)+t,{method:"POST",headers:{...s,"content-type":"application/json","X-Source":"cli","X-Visa-CLI-Version":A1e,...Xh()},body:(0,bS.canonicalJson)(JSON.parse(JSON.stringify(r))),redirect:"error",signal:AbortSignal.timeout(i)})}catch(u){let d=jI(u);throw new lu(o,d==="TimeoutError"||d==="AbortError"?"timeout":"network",i)}if(!a.ok){let u;try{let p=await a.text();p.length<=262144&&(u=JSON.parse(p))}catch{}let d=QR(a.status,u,A1e);if(d)throw d;let l=u7t(u);throw new Yi(o,a.status,l.code,l.reason,l.purchaseId,l.approval)}let c;try{c=await a.text()}catch{throw new lu(o,"response",i)}if(c.length>262144)throw new lu(o,"response",i);try{return JSON.parse(c)}catch{throw new lu(o,"response",i)}}function l7t(e,t=fetch){return Dg(e),{financialRuntimeRequest:(r,n)=>M1e(e,`/v1/financial-runtime/${r}`,n,t)}}function f7t(e){return`This agent belongs to a different Visa account than ${e}, the account this terminal is signed in to, so nothing was connected. To use ${e}: run \`visa connect --restart\` and open the new link while signed in to ${e}. To use the other account instead: run \`visa disconnect --all\` to sign this terminal out, then \`visa connect\` and sign in with that account. \`visa disconnect --all\` also removes the Visa MCP server from every AI client, the spend HUD and any local card-delivery files; \`visa connect\` puts the server and HUD back for the client it runs for. Nothing is revoked on the server.`}async function L1e(e,t,r=fetch){if(e.transportProfileId!==(wn(t)?.profileId??null))throw new Error("Protected enrollment transport profile changed");if(e.binding)return v1e(e,e.binding,t),e.binding;if(AS(e))return null;let n=await M1e(e.executionOrigin,"/v1/enrollment/cli-claim",{verifier:e.verifier},r);if(n?.ok!==!0)throw new Error("Protected authority refused enrollment pickup");if(n.result?.status==="pending")return null;let o=n.result;lQ(o,e.challenge,od(e.verifier));let i=wn(t);if(i&&o.ownerPublicId!==i.ownerPublicId)throw new Xt(f7t(i.loginLabel),"enrollment_owner_mismatch");return e.ceremonyId=o.ceremonyId,e.binding=o,Pn((0,qn.join)(kg(t),"pending.json"),JSON.stringify(e)),v1e(e,o,t),o}function p7t(e,t){let r=Tt(t);if((0,fu.existsSync)((0,qn.join)(r,"financial-device",`${e}.active.json`)))return!0;try{let n=To((0,qn.join)(r,"card-device",`${e}.json`));if(n&&JSON.parse(n)?.certificate)return!0}catch{}return!1}function v1e(e,t,r){let n={v:1,authorityOrigin:e.authorityOrigin,executionOrigin:e.executionOrigin,transportProfileId:e.transportProfileId,binding:t},o=(0,qn.join)(kg(r),`${t.agentId}.json`),i=To(o);if(i!==null&&(0,bS.canonicalJson)(JSON.parse(i))!==(0,bS.canonicalJson)(n)){let s=null;try{s=JSON.parse(i)}catch{}if(!(s!==null&&_7t(s,n)||!p7t(t.agentId,r)))throw new Error("Protected agent selection changed");m7t(t.agentId,r)}Pn(o,JSON.stringify(n))}function _7t(e,t){let r=e?.binding,n=t.binding;return e?.v===1&&!!r&&r.agentId===n.agentId&&r.associationId===n.associationId&&r.ownerPublicId===n.ownerPublicId&&r.organizationId===n.organizationId&&r.rootJkt===n.rootJkt&&e.authorityOrigin===t.authorityOrigin&&e.executionOrigin===t.executionOrigin&&e.transportProfileId===t.transportProfileId&&r.challenge!==n.challenge&&Number.isSafeInteger(r.associationVersion)&&n.associationVersion>=r.associationVersion}function m7t(e,t){if(!/^[0-9a-f-]{36}$/.test(e))throw new Error("Protected agent id is invalid");let r=`.replaced-${new Date().toISOString().replace(/[:.]/g,"-")}`,n=Tt(t),o=i=>(i===`${e}.json`||i.startsWith(`${e}.`))&&i.endsWith(".json")&&!i.includes(".replaced-")&&!i.includes(".bak");for(let i of[(0,qn.join)(n,"protected-enrollment"),(0,qn.join)(n,"protected-enrollment","retired"),(0,qn.join)(n,"card-device"),(0,qn.join)(n,"financial-device"),(0,qn.join)(n,"financial-device-presence")])if((0,fu.existsSync)(i))for(let s of(0,fu.readdirSync)(i))o(s)&&(0,fu.renameSync)((0,qn.join)(i,s),(0,qn.join)(i,s+r));Me.info("protected-enrollment:replaced-agent-records-archived",{agentId:e})}function pu(e,t=fetch){let r=l7t(e.executionOrigin,t);return{financialRuntimeRequest:async(n,o)=>{let i=await r.financialRuntimeRequest(n,o);if(n==="device-context"){let s=e.binding;if(i.agentId!==s.agentId||i.ownerPublicId!==s.ownerPublicId||i.associationId!==s.associationId||i.associationVersion!==s.associationVersion||i.rootJkt!==s.rootJkt||i.rootKid!==s.rootKid||i.organizationId!==s.organizationId||(0,bS.canonicalJson)(i.rootPublicJwk)!==(0,bS.canonicalJson)(s.rootPublicJwk))throw new Error("Protected device context differs from the independently claimed owner")}return i}}}function _Q(e){let t=kg(e);return(0,fu.readdirSync)(t).filter(r=>TS.test(r.replace(/\.json$/,""))&&r.endsWith(".json")).flatMap(r=>{let n=To((0,qn.join)(t,r));if(n===null)return[];let o=JSON.parse(n);if(o.v!==1||Dg(o.authorityOrigin)!==o.authorityOrigin||Dg(o.executionOrigin)!==o.executionOrigin||o.binding.agentId+".json"!==r)throw new Error("Protected selection is invalid");return lQ(o.binding,o.binding.challenge,o.binding.confirmCode),[o]})}function Ug(e){let t=wn(e)?.profileId??null;return _Q(e).filter(r=>r.transportProfileId===t)}function D1e(e,t){let r=Ug(t).find(o=>o.binding.agentId===e.agentId&&o.binding.ownerPublicId===e.ownerPublicId&&o.authorityOrigin===e.authUrl);if(!r||!e.financialDeviceRuntimeId)return;let n=Lg(e.agentId,t);if(!n||n.runtimeKey.runtimeId!==e.financialDeviceRuntimeId||n.ownerPublicId!==r.binding.ownerPublicId||n.proposal.associationId!==r.binding.associationId||n.proposal.associationVersion!==r.binding.associationVersion||n.proposal.rootJkt!==r.binding.rootJkt||n.rootKid!==r.binding.rootKid)throw new Error("Protected wallet installation differs from its independently claimed owner");return r}var WD=j(require("node:fs")),H1e=j(require("node:path"));var ua=j(require("node:fs")),k1e=j(require("node:os")),el=j(require("node:path"));Xo();var U1e=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,g7t=U1e;function _u(e=process.env){if(e.VISA_V4_HOME)return e.VISA_V4_HOME;let t=e.VISA_CLI_HOME;return typeof t=="string"&&t.trim().length>0?el.join(t,".visa-v4"):el.join(k1e.homedir(),".visa-v4")}function j1e(e=_u()){return el.join(e,"owners")}function mQ(e=_u(),t){if(t!==void 0){if(!g7t.test(t))throw new Error("wallet owner id must be a canonical UUID");return el.join(j1e(e),t.toLowerCase(),"agents")}return el.join(e,"agents")}function vS(e,t=_u(),r){if(!U1e.test(e))throw new Error("wallet agent id must be a canonical UUID");return el.join(mQ(t,r),e.toLowerCase())}function $D(e){try{let t=ua.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`wallet runtime path is not a private directory: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t;ua.mkdirSync(e,{mode:448})}ua.chmodSync(e,448)}function B1e(e,t=_u(),r){if(ua.mkdirSync(t,{recursive:!0,mode:448}),r!==void 0){let i=j1e(t);$D(i),$D(el.dirname(mQ(t,r)))}let n=mQ(t,r);$D(n);let o=vS(e,t,r);return $D(o),o}Ms();jl();var h7t=/^0x[0-9a-f]{40}$/i,E7t=/^eip155:[1-9][0-9]{0,18}$/,KD=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,y7t="wallet-authority.json";function gQ(e=process.env){return _u(e)}function hQ(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&(t.financialDeviceRuntimeId===void 0||typeof t.financialDeviceRuntimeId=="string"&&KD.test(t.financialDeviceRuntimeId))&&(t.executionMode===void 0||t.executionMode==="direct_runtime"||t.executionMode==="managed")&&(t.walletBinding===void 0||/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t.walletBinding)&&t.walletBinding.length<=32*1024)&&(t.managedWallet===void 0||typeof t.managedWallet=="object"&&t.managedWallet!==null&&typeof t.managedWallet.organizationId=="string"&&t.managedWallet.organizationId.length>0&&typeof t.managedWallet.walletId=="string"&&t.managedWallet.walletId.length>0&&typeof t.managedWallet.address=="string"&&h7t.test(t.managedWallet.address)&&typeof t.managedWallet.network=="string"&&E7t.test(t.managedWallet.network))&&(t.activationState===void 0||t.activationState==="pending"||t.activationState==="active")&&(t.executionState===void 0||t.executionState==="active"||t.executionState==="recovery_only")&&typeof t.agentId=="string"&&KD.test(t.agentId)&&typeof t.agentName=="string"&&t.agentName.length>0&&t.agentName.length<=120&&(t.ownerPublicId===void 0||KD.test(t.ownerPublicId))&&typeof t.grantId=="string"&&KD.test(t.grantId)&&Number.isSafeInteger(t.grantVersion)&&t.grantVersion>0&&t.rail==="wallet:x402"&&typeof t.authUrl=="string"&&S7t(t.authUrl)&&typeof t.activatedAt=="string"&&Number.isFinite(Date.parse(t.activatedAt))}function S7t(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&t.username===""&&t.password===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&e===t.origin}catch{return!1}}function q1e(e=gQ()){return H1e.join(e,y7t)}function T7t(e,t){if(!hQ(e))throw new jg("wallet authority binding is invalid");WD.mkdirSync(t,{recursive:!0,mode:448}),WD.chmodSync(t,448),So(t),Pn(q1e(t),`${JSON.stringify(e,null,2)}
218
218
  `)}function V1e(e=gQ()){let t=To(q1e(e));if(t===null)return null;try{let r=JSON.parse(t);if(!hQ(r))throw new jg("wallet authority binding is malformed");return r}catch(r){throw r instanceof jg?r:new jg("wallet authority binding is malformed")}}var jg=class extends Error{code="wallet_delivery_required";constructor(t){super(`wallet delivery unusable: ${t}`),this.name="WalletDeliveryRequiredError"}};function F1e(e){let t={...e.authorityBinding,executionMode:"managed",activationState:"active"};if(!t.financialDeviceRuntimeId||!hQ(t))throw new jg("wallet authority binding is invalid");let r=e.homeDir??B1e(t.agentId,gQ(),t.ownerPublicId);T7t(t,r),Me.info("wallet-delivery: device authority binding installed",{agentId:t.agentId,runtimeId:t.financialDeviceRuntimeId})}var b7t=60*6e4,K1e=6e4,EQ=1e3,G1e=15e3,$1e=1e3;function A7t(e){let t=typeof e?.expiresAt=="string"?Date.parse(e.expiresAt):NaN,r=e?.prepared?.status==="pending"&&typeof e.prepared.challenge?.expiresAt=="number"?e.prepared.challenge.expiresAt*1e3:NaN,n=[t,r].filter(o=>Number.isFinite(o));return n.length?Math.min(...n):null}function v7t(e){let t=EQ;if(e.now-e.fastSince>=K1e){let r=Math.min(EQ*2**Math.min(e.slowTicks,10),G1e);t=Math.min(Math.round(r*(.8+.4*e.random())),G1e)}return e.closesAt!==null&&e.closesAt+$1e>e.now&&(t=Math.min(t,e.closesAt+$1e-e.now)),Math.max(EQ,Math.min(t,e.deadline-e.now))}async function W1e(e){let t=e.sleep??(m=>new Promise(h=>setTimeout(h,m))),r=e.now??(()=>Date.now()),n=e.random??Math.random,o=null,i=m=>{o=A7t(m)},s=await LI(e);i(await SS({...e,pending:s})),await e.onProposalPublished?.(s);let a=r(),c=0,u=async()=>{let m=await y1e({...e,pending:s,onView:i});return m.renewed&&(s=m.pending,await e.onProposalPublished?.(s)),m.active},d=await u(),l=d?yQ(e,d):null,p=d?.grantId,f=s.cardProposal?await e.advanceCompanion?.()===!0:!0;if(await e.advanceTap?.(),!d||!f){let m=r()+b7t;for(;(!d||!f)&&r()<m;){let h=r();h-a>=K1e&&c++,await t(v7t({now:h,fastSince:a,slowTicks:c,closesAt:o,deadline:m,random:n})),d=await u(),d&&(!l||d.grantId!==p)&&(l=yQ(e,d),p=d.grantId),f=s.cardProposal?await e.advanceCompanion?.()===!0:!0,await e.advanceTap?.()}}if(!d||!f||!l)throw new Error("Device approval is still pending. Keep this enrollment command running; the native key and owner request are preserved.");return l}async function Y1e(e){let t=await sQ(e);return t?yQ(e,t):!1}function yQ(e,t){if(t.ownerPublicId!==e.ownerPublicId)throw new Error("Protected wallet owner differs from the active profile");return F1e({authorityBinding:{version:1,agentId:e.agentId,ownerPublicId:e.ownerPublicId,agentName:e.agentName,grantId:t.grantId,grantVersion:t.grantVersion,rail:"wallet:x402",authUrl:new URL(e.authUrl).origin,activatedAt:new Date().toISOString(),financialDeviceRuntimeId:t.runtimeKey.runtimeId},homeDir:e.walletHomeDir}),!0}var nl=require("node:fs"),ek=require("node:path"),ol=require("node:crypto"),li=j(zu()),ok=j(mp()),ik=j(tQ());var Lr=require("node:fs"),yp=require("node:crypto"),HI=require("node:path"),rl=j(sa()),zD=j(mp());Ms();Xo();var BI=require("node:crypto"),Bg=j(sa()),YD=j(mp());function J1e(e,t){let r=t.tapPublicMaterial;if(!t.gateEnrollment||!r||r.associationId!==e.proposal.associationId||r.associationVersion!==e.proposal.associationVersion||r.agentId!==e.proposal.agentId||r.rootJkt!==e.proposal.rootJkt||!Number.isSafeInteger(r.tapKeyEpoch)||r.tapKeyEpoch<0||(0,YD.computeJkt)(r.tapKey.jwk)!==r.tapKey.jkt||r.custody!==void 0&&!["root-via-gate","runtime"].includes(r.custody)||typeof r.observation!="string"||!Number.isSafeInteger(r.expiresAt)||r.expiresAt<=Math.floor(Date.now()/1e3))throw new Error("identity_device_public_material_invalid");return{...r,custody:r.custody??"root-via-gate"}}function z1e(e){if(e?.ok!==!0||!e.result||typeof e.result!="object")throw new Error("identity_device_response_invalid");return e.result}async function SQ(e){let t=z1e(await e.api.identityDeviceRequest("association",{agentId:e.agentId}));if(t.agentId!==e.agentId||t.rootJkt!==e.expectedRootJkt||t.associationId!==e.associationId)throw new Error("identity_device_owner_root_mismatch");let r=await e.native.describe(e.key.handle);if((0,Bg.canonicalJson)(r)!==(0,Bg.canonicalJson)(e.key)||r.binding.profile!=="identity-tap-v1"||r.binding.purpose!=="tap"||r.binding.associationId!==t.associationId||r.binding.agentId!==e.agentId||r.binding.rootJkt!==e.expectedRootJkt)throw new Error("identity_device_tap_key_binding_mismatch");let n={v:1,handoffId:(0,BI.randomUUID)(),runtimeKey:r,proposal:{...t,runtimeId:r.runtimeId,runtimeJkt:r.jkt,runtimePublicJwk:r.publicJwk}};return(0,YD.identityDeviceProposalSha256)(n.proposal),await e.persist(n),await tl(e.api,e.native,n,"create"),n}async function tl(e,t,r,n,o,i,s){let a=await t.describe(r.runtimeKey.handle);if((0,Bg.canonicalJson)(a)!==(0,Bg.canonicalJson)(r.runtimeKey)||a.jkt!==r.proposal.runtimeJkt||a.runtimeId!==r.proposal.runtimeId)throw new Error("native_runtime_handle_mismatch");let c=n==="cancel"?{v:1,operation:n,requestId:(0,BI.randomUUID)(),handoffId:r.handoffId,proposal:r.proposal,body:{enrollmentRequestId:i??null,generation:s??null}}:n==="proof"?{v:1,operation:n,requestId:(0,BI.randomUUID)(),handoffId:r.handoffId,proposal:r.proposal,body:{enrollmentRequestId:i,runtimeProof:o}}:{v:1,operation:n,requestId:n==="create"?r.handoffId:(0,BI.randomUUID)(),handoffId:r.handoffId,proposal:r.proposal,body:{}},u=await t.handoffProof(a.handle,c),d=z1e(await e.identityDeviceRequest("handoff",{request:c,runtimeProof:u}));if(d.handoffId!==r.handoffId||(0,Bg.canonicalJson)(d.proposal)!==(0,Bg.canonicalJson)(r.proposal)||!Number.isSafeInteger(d.expiresAt)||!["proposed","pending","active","expired","retired","revoked","cancelled"].includes(d.status))throw new Error("identity_device_response_invalid");return d}async function JD(e,t,r){let n=await tl(e,t,r,"read");if(n.status==="pending"&&!n.runtimeProof){if(!n.challenge||n.enrollmentRequestId!==n.challenge.requestId)throw new Error("identity_device_response_invalid");let o=await t.enrollmentProof(r.runtimeKey.handle,n.challenge);return tl(e,t,r,"proof",o,n.enrollmentRequestId)}return n}function X1e(e,t,r={}){let n=`?device=${encodeURIComponent(t.handoffId)}&association=${encodeURIComponent(t.proposal.associationId)}&tap=${encodeURIComponent(t.proposal.runtimeJkt)}`+(r.revoke?"&deviceAction=revoke":"");return`${e}${r.revoke?"":"/protected-agent"}${n}`}var XD=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e),I7t=600*1e3;function P7t(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!!(t&&typeof t=="object"&&t.code==="EPERM")}}function Hg(e){if(!XD(e.agentId))throw new Error("identity_device_agent_invalid");let t=(0,HI.join)(Tt(e.env),"identity-runtime-renewal-locks");(0,Lr.mkdirSync)(t,{recursive:!0,mode:448}),(0,Lr.chmodSync)(t,448);let r=(0,HI.join)(t,`${e.agentId}.${e.purpose??"tap"}.lock`),n=e.now??new Date,o=e.staleMs??I7t;for(let i=0;i<2;i+=1){let s=(0,yp.randomUUID)(),a={version:1,pid:process.pid,token:s,createdAt:n.toISOString()};try{let c=(0,Lr.openSync)(r,"wx",384);try{(0,Lr.writeFileSync)(c,JSON.stringify(a),"utf8"),(0,Lr.fsyncSync)(c)}finally{(0,Lr.closeSync)(c)}return()=>{try{JSON.parse((0,Lr.readFileSync)(r,"utf8")).token===s&&(0,Lr.unlinkSync)(r)}catch{}}}catch(c){if(!c||typeof c!="object"||c.code!=="EEXIST")throw c;let u=!1;try{let d=JSON.parse((0,Lr.readFileSync)(r,"utf8")),l=typeof d.createdAt=="string"?Date.parse(d.createdAt):NaN;if(d.version===1&&Number.isSafeInteger(d.pid)&&(d.pid??0)>0&&typeof d.token=="string"&&d.token.length>0&&Number.isFinite(l))u=!P7t(d.pid);else{let f=Number.isFinite(l)?l:(0,Lr.statSync)(r).mtimeMs;u=n.getTime()-f>=o}}catch{try{u=n.getTime()-(0,Lr.statSync)(r).mtimeMs>=o}catch{u=!0}}if(!u)return null;try{(0,Lr.unlinkSync)(r)}catch(d){if(!d||typeof d!="object"||d.code!=="ENOENT")return null}}}return null}function qI(e,t){if(!XD(e))throw new Error("identity_device_agent_invalid");let r=(0,HI.join)(Tt(t),"financial-device-presence");return(0,Lr.mkdirSync)(r,{recursive:!0,mode:448}),(0,HI.join)(r,`${e}.pending.json`)}function IS(e,t){let r=ss(qI(e,t));if(r===null)return null;On(r);let n=JSON.parse(r);if(n.v!==1||n.proposal?.agentId!==e||!XD(n.handoffId)||!n.runtimeKey?.handle)throw new Error("identity_device_record_invalid");return n}function ZD(e,t){On(JSON.stringify(e));let r=qI(e.proposal.agentId,t),n=ss(r);if(n){let o=JSON.parse(n);o.handoffId!==e.handoffId&&vi(r.replace(".pending.json",`.${o.handoffId}.history.json`),n)}vi(r,JSON.stringify(e))}async function VI(e){let{pending:t,view:r}=e,n=Math.floor(Date.now()/1e3);if(r.handoffId!==t.handoffId||r.status!=="active"||!r.authorizationId||!XD(r.authorizationId)||!Number.isSafeInteger(r.authorizationVersion)||Number(r.authorizationVersion)<1||!r.certificate||!r.delegation||!r.gateAuthorization||(0,rl.canonicalJson)(r.proposal)!==(0,rl.canonicalJson)(t.proposal))throw new Error("identity_device_activation_invalid");J1e(t,r);let o=r.challenge;if(!o||o.runtimeId!==t.proposal.runtimeId||o.runtimeJkt!==t.proposal.runtimeJkt||o.associationId!==t.proposal.associationId||o.associationVersion!==t.proposal.associationVersion)throw new Error("identity_device_challenge_invalid");for(let[l,p]of[[r.certificate,o.certificateSha256],[r.delegation,o.delegationSha256],[r.gateAuthorization,o.gateAuthorizationSha256]])if((0,yp.createHash)("sha256").update(l.split(".").slice(0,2).join(".")).digest("base64url")!==p)throw new Error("identity_device_signed_preparation_mismatch");if(!(await(0,zD.verifyRuntimeCertificate)(r.certificate,{jwks:{keys:[{...e.rootPublicJwk,kid:e.rootKid}]},expectedAgentId:t.proposal.agentId,expectedRootJkt:t.proposal.rootJkt,expectedRuntimeJkt:t.proposal.runtimeJkt,expectedRuntimeId:t.proposal.runtimeId,requiredPurpose:"tap",nowSec:e.collectedRenewal?JSON.parse(Buffer.from(r.certificate.split(".")[1],"base64url").toString("utf8")).iat:n})).ok)throw new Error("identity_device_certificate_invalid");let s=JSON.parse(Buffer.from(r.delegation.split(".")[1],"base64url").toString("utf8"));await(0,zD.verifyIdentityTapDelegation)(r.delegation,{ownerJwks:{keys:[{...e.rootPublicJwk,kid:e.rootKid}]},expectedRootKid:e.rootKid,expectedRootJkt:t.proposal.rootJkt,expectedAgentId:t.proposal.agentId,expectedRuntimeId:t.proposal.runtimeId,expectedRuntimeJkt:t.proposal.runtimeJkt,expectedLeaseIssuerJkt:s.leaseIssuerJkt,expectedNetwork:s.network,expectedDelegationId:s.jti,nowSec:n});let a=r.gateAuthorization.split("."),c={ok:a.length===3&&(0,yp.verify)(null,Buffer.from(a.slice(0,2).join(".")),(0,yp.createPublicKey)({key:e.rootPublicJwk,format:"jwk"}),Buffer.from(a[2],"base64url")),header:JSON.parse(Buffer.from(a[0],"base64url").toString("utf8")),claims:JSON.parse(Buffer.from(a[1],"base64url").toString("utf8"))};if(!c.ok||c.header.alg!=="EdDSA"||c.header.kid!==e.rootKid||c.header.typ!=="visa-agent-identity-gate-authorization+jwt"||c.claims.iss!==t.proposal.rootJkt||c.claims.sub!==t.proposal.agentId||c.claims.aud!=="urn:visa:tvc:identity-gate"||c.claims.generation!==r.challenge?.generation||!Number.isSafeInteger(c.claims.exp)||Number(c.claims.exp)<=n||!Number.isSafeInteger(c.claims.nbf)||Number(c.claims.nbf)>n||(0,rl.canonicalJson)(c.claims.purposes)!==(0,rl.canonicalJson)(["tap_signature_base"]))throw new Error("identity_device_gate_authorization_invalid");let u=await e.native.describe(t.runtimeKey.handle);if((0,rl.canonicalJson)(u)!==(0,rl.canonicalJson)(t.runtimeKey))throw new Error("native_runtime_handle_mismatch");let d={...t,active:r,rootPublicJwk:e.rootPublicJwk,rootKid:e.rootKid};return On(JSON.stringify(d)),vi(qI(t.proposal.agentId,e.env).replace(".pending.json",`.${t.proposal.runtimeId}.active.json`),JSON.stringify(d)),vi(qI(t.proposal.agentId,e.env).replace(".pending.json",".selected.json"),JSON.stringify(d)),Me.info("identity_device_selected",{agentId:t.proposal.agentId,handoffId:t.handoffId}),d}function w7t(e){let t=e.runtimeKey?.binding;return t?t.profile==="identity-tap-v1"?t.purpose==="tap"&&t.associationId===e.proposal?.associationId:t.profile==="legacy-root-certified-v1"&&t.purpose==="wallet:x402":!1}function TQ(e){return e.runtimeKey.binding.profile==="legacy-root-certified-v1"}function Qa(e,t){let r=ss(qI(e,t).replace(".pending.json",".selected.json"));if(r===null)return null;On(r);let n=JSON.parse(r);if(n.v!==1||n.revoked!==void 0&&n.revoked!==!0||n.proposal?.agentId!==e||!w7t(n)||n.active?.status!=="active"||n.active.handoffId!==n.handoffId||!n.rootKid||!n.rootPublicJwk||(0,rl.canonicalJson)(n.active.proposal)!==(0,rl.canonicalJson)(n.proposal))throw new Error("identity_device_selected_invalid");return n}Xo();function R7t(e,t){return e?e.ceremonyId===t.binding.ceremonyId&&e.challenge===t.binding.challenge&&/^[A-Za-z0-9_-]{43}$/.test(e.verifier)&&(0,ol.createHash)("sha256").update(e.verifier).digest("base64url")===e.challenge:!0}function AQ(e,t){if(e&&(e.ceremonyId!==t.binding.ceremonyId||e.challenge!==t.binding.challenge||!/^[A-Za-z0-9_-]{43}$/.test(e.verifier)||(0,ol.createHash)("sha256").update(e.verifier).digest("base64url")!==e.challenge))throw new Error("card_device_ceremony_changed")}function FI(e,t){if(!/^[0-9a-f-]{36}$/.test(e))throw new Error("card_device_agent_invalid");let r=(0,ek.join)(Tt(t),"card-device");return(0,nl.mkdirSync)(r,{recursive:!0,mode:448}),(0,ek.join)(r,`${e}.json`)}function QD(e,t){let r=JSON.stringify(e);On(r),vi(FI(e.proposal.agentId,t),r)}function tk(e,t){return FI(e,t).replace(/\.json$/,".renewal.json")}function Z1e(e,t){let r=JSON.stringify(e);On(r),vi(tk(e.proposal.agentId,t),r)}function tNe(e,t){let r=ss(e);if(r===null)return null;On(r);let n=JSON.parse(r),o=n.proposal,i=t.binding,s=n.runtimeKey;if((0,ik.financialDeviceProposalHash)(o),!n.certificate&&(!R7t(n.ceremony,t)||o.associationId!==i.associationId||o.associationVersion!==i.associationVersion||o.rootJkt!==i.rootJkt)){let c=e.replace(".json",`.${o?.requestId??(0,ol.randomUUID)()}.superseded.json`);return(0,nl.renameSync)(e,c),null}if(AQ(n.ceremony,t),n.v!==1||n.initialConnection!==void 0&&n.initialConnection!==!0||o.v!==2||o.agentId!==i.agentId||o.associationId!==i.associationId||o.associationVersion!==i.associationVersion||o.rootJkt!==i.rootJkt||s.binding.profile!=="legacy-root-certified-v1"||s.binding.purpose!=="card:vic"||s.binding.agentId!==i.agentId||s.binding.rootJkt!==i.rootJkt||s.runtimeId!==o.runtimeId||s.jkt!==(0,ok.computeJkt)(o.publicJwk)||(0,li.canonicalJson)(s.publicJwk)!==(0,li.canonicalJson)(o.publicJwk))throw new Error("card_device_record_invalid");return n}function qg(e,t){return tNe(FI(e.binding.agentId,t),e)}function bQ(e,t,r){let n=tNe(tk(e.binding.agentId,r),e);if(n&&(n.ceremony||n.initialConnection))throw new Error("card_device_record_invalid");return n&&(0,li.canonicalJson)(n.runtimeKey)===(0,li.canonicalJson)(t.runtimeKey)?n:null}function rNe(e,t,r,n){let o=Qo(e);if(new URL(o).protocol!=="https:")throw new Error("card_connection_https_required");(0,ik.financialDeviceProposalHash)(t.proposal);let i=new URL("/agent/enroll/protected-agent",o);if(t.ceremony){i.searchParams.set("cliChallenge",t.ceremony.challenge);let s=O1e(t.ceremony.challenge,n);s&&i.searchParams.set("keys",s)}else i.searchParams.set("cardDevice",Buffer.from((0,li.canonicalJson)(t.proposal)).toString("base64url"));return r&&i.searchParams.set("app",r),i.toString()}async function rk(e,t,r,n=Math.floor(Date.now()/1e3)){let o=e.challenge,i=e.proposal;if(!o||o.v!==1||o.audience!=="visa:financial:card-actor-enrollment:v1"||o.requestId!==i.requestId||o.associationId!==i.associationId||o.associationVersion!==i.associationVersion||o.runtimeId!==i.runtimeId||o.childJkt!==e.runtimeKey.jkt||o.generation!==1||!Number.isSafeInteger(o.expiresAt)||!r.startsWith(o.preparedCertificate.signingInput+"."))throw new Error("card_device_certificate_changed");let s=await(0,ok.verifyRuntimeCertificate)(r,{jwks:{keys:[{...t.binding.rootPublicJwk,kid:t.binding.rootKid}]},nowSec:n,expectedAgentId:e.proposal.agentId,expectedRootJkt:e.proposal.rootJkt,expectedRuntimeId:e.proposal.runtimeId,expectedRuntimeJkt:e.runtimeKey.jkt,requiredPurpose:"card:vic"});if(!s.ok||(0,li.canonicalJson)(s.claims.purposes)!=='["card:vic"]')throw new Error("card_device_certificate_invalid");return s.claims}async function nNe(e){let{selection:t,signer:r,env:n}=e,o=qg(t,n);if(!o){let i=await r.create({profile:"legacy-root-certified-v1",purpose:"card:vic",agentId:t.binding.agentId,rootJkt:t.binding.rootJkt});o={v:1,runtimeKey:i,ceremony:e.ceremony,...e.initialConnection?{initialConnection:!0}:{},proposal:{v:2,rail:"card:vic",purpose:"financial.runtime.device.proposal",requestId:(0,ol.randomUUID)(),agentId:t.binding.agentId,associationId:t.binding.associationId,associationVersion:t.binding.associationVersion,rootJkt:t.binding.rootJkt,runtimeId:i.runtimeId,publicJwk:i.publicJwk}},QD(o,n)}return o}async function oNe(e){AQ(e.ceremony,e.selection);let t=Hg({agentId:e.selection.binding.agentId,purpose:"card",env:e.env});if(!t)throw new Error("card_device_busy");try{let r=await nNe(e);if((0,li.canonicalJson)(await e.signer.describe(r.runtimeKey.handle))!==(0,li.canonicalJson)(r.runtimeKey))throw new Error("card_device_handle_changed");return r}finally{t()}}async function Q1e(e,t,r,n){let{selection:o,signer:i,api:s,env:a}=r,c=e.proposal,u;try{u=await s.financialRuntimeRequest("device-handoff-read",{requestId:c.requestId,proposal:c})}catch(p){if(!(p instanceof Yi)||p.status!==400||p.code!=="financial_runtime_refused")throw p;u={proposal:c,published:!1,prepared:null,expired:!1,evidence:{}}}if(u.published===!1&&e.ceremony)try{u=await s.financialRuntimeRequest("device-handoff-create",{requestId:c.requestId,proposal:c,ceremony:e.ceremony})}catch(p){if(!(p instanceof Yi)||p.status!==400||p.code!=="financial_runtime_refused")throw p;delete e.ceremony,n(e)}if((0,li.canonicalJson)(u.proposal)!==(0,li.canonicalJson)(c))throw new Error("card_device_proposal_changed");let d=u.prepared?.challenge,l=u.evidence?.owner_signatures?.certificate;if(u.prepared?.status==="revoked"||u.prepared?.status==="expired")throw new Error("card_device_connection_revoked");if(u.expired&&u.prepared?.status!=="active"){vi(FI(c.agentId,a).replace(".json",`.${c.requestId}.expired.json`),JSON.stringify(e));let p=e.ceremony||u.prepared?.kind==="enroll"?await i.create(t.binding):t;return n({v:1,runtimeKey:p,ceremony:e.ceremony,proposal:{...c,requestId:(0,ol.randomUUID)(),runtimeId:p.runtimeId,publicJwk:p.publicJwk}}),{status:"retry"}}if(d&&typeof l=="string"){if(e.challenge&&(0,li.canonicalJson)(e.challenge)!==(0,li.canonicalJson)(d))throw new Error("card_device_challenge_changed");e.challenge=d;let p=await rk(e,o,l,u.prepared?.status==="active"?d.preparedCertificate.claims.iat:void 0);if(!u.evidence?.device_proof&&u.prepared?.status!=="active"&&(e.childPop||(e.childPop=await i.cardEnrollmentProof(t.handle,d),n(e)),u=await s.financialRuntimeRequest("device-handoff-proof",{requestId:c.requestId,proposal:c,childPop:e.childPop})),u.prepared?.status==="active"){if(u.prepared.certificate!==l)throw new Error("card_device_certificate_changed");return e.certificate=l,n(e),p.exp<=Math.floor(Date.now()/1e3)+30?{status:"retry"}:{status:"active",record:e}}}if(u.expired)throw new Error("card_device_preparation_expired");return{status:"awaiting_owner",proposal:c,hash:(0,ik.financialDeviceProposalHash)(c),published:u.published!==!1}}function eNe(e,t){vi(FI(e.proposal.agentId,t).replace(".json",`.${e.proposal.requestId}.completed.json`),JSON.stringify(e))}async function GI(e){let{selection:t,signer:r,env:n}=e;AQ(e.ceremony,t);let o=Hg({agentId:t.binding.agentId,purpose:"card",env:n});if(!o)return{status:"busy"};try{let i=await nNe(e),s=await r.describe(i.runtimeKey.handle);if((0,li.canonicalJson)(s)!==(0,li.canonicalJson)(i.runtimeKey))throw new Error("card_device_handle_changed");if(i.certificate){let a=JSON.parse(Buffer.from(i.certificate.split(".")[1]??"","base64url").toString());await rk(i,t,i.certificate,a.iat);let c=Math.floor(Date.now()/1e3);if(a.exp>c+30){await rk(i,t,i.certificate);let d=e.renewWithinSeconds===void 0?null:bQ(t,i,n);if(!d&&a.exp>c+(e.renewWithinSeconds??0))return{status:"active",record:i};let l=d??{v:1,proposal:{...i.proposal,requestId:(0,ol.randomUUID)()},runtimeKey:i.runtimeKey};d||Z1e(l,n);let p=await Q1e(l,s,e,f=>Z1e(f,n));return p.status!=="active"||(eNe(i,n),QD(p.record,n),(0,nl.rmSync)(tk(t.binding.agentId,n),{force:!0})),p}eNe(i,n);let u=bQ(t,i,n);i=u??{v:1,proposal:{...i.proposal,requestId:(0,ol.randomUUID)()},runtimeKey:i.runtimeKey},QD(i,n),u&&(0,nl.rmSync)(tk(t.binding.agentId,n),{force:!0})}return await Q1e(i,s,e,a=>QD(a,n))}finally{o()}}var nk=720*60*60;async function vQ(e,t,r=Math.floor(Date.now()/1e3)){let n={state:"none",renew:!1},o=e.binding.agentId,i;try{i=qg(e,t)}catch{return n}if(!i)return n;if(!i.certificate){let a=!1;try{a=(0,nl.readdirSync)((0,ek.join)(Tt(t),"card-device")).some(c=>c.startsWith(`${o}.`)&&c.endsWith(".completed.json"))}catch{a=!1}return a&&!i.ceremony&&!i.initialConnection?{state:"renewing",renew:!0}:n}let s;try{s=JSON.parse(Buffer.from(i.certificate.split(".")[1]??"","base64url").toString()),await rk(i,e,i.certificate,s.iat)}catch{return n}try{if(bQ(e,i,t))return{state:"renewing",renew:!0}}catch{}return s.exp<=r+30?{state:"expired",renew:!0}:s.exp-r<nk?{state:"renew_due",renew:s.exp-s.iat>=nk}:{state:"live",renew:!1}}var fo=require("node:crypto"),ec=j(sa()),ck=j(mp()),O7t={"wallet:x402":["visa-agent-operations:v1","visa-wallet-authority:local-v1","visa:financial:wallet-device-handoff:v1","visa:financial:device-operations:v1","visa-tempo-mpp-payment:v1","visa-tempo-mpp-report:v1","visa-tempo-mpp-history:v1"],"card:vic":["visa-agent-operations:v1","visa-auth-card-draw","visa:purchase-resource:v1","visa:financial:card-device-handoff:v1","visa:card-admission-recovery:v1"]},cNe=Number.MAX_SAFE_INTEGER,N7t=Buffer.from("302e020100300506032b657004220420","hex");function Q(e){throw new Error(e)}var C7t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,yr=e=>typeof e=="string"&&C7t.test(e);function KI(e){if(!/^[A-Za-z0-9_-]*$/.test(e))return null;let t=Buffer.from(e,"base64url");return t.toString("base64url")===e?t:null}var Sp=e=>typeof e=="string"&&KI(e)?.length===32,il=e=>(0,fo.createHash)("sha256").update(e).digest("base64url");function Tp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sn(e,t){return Tp(e)||Q("request_invalid"),(Object.keys(e).filter(n=>e[n]!==void 0).length!==t.length||t.some(n=>!Object.hasOwn(e,n)))&&Q("request_invalid"),e}function z(e,t){let r=e[t];return typeof r!="string"&&Q("request_invalid"),r}function at(e,t){let r=e[t];return(typeof r!="number"||!Number.isSafeInteger(r)||r<0||r>cNe)&&Q("request_invalid"),r}function mu(e,t){try{return(0,ec.canonicalJson)(e)===(0,ec.canonicalJson)(t)}catch{return!1}}function iNe(e){let t=KI(e);t||Q("request_invalid");try{return JSON.parse(t.toString("utf8"))}catch{Q("request_invalid")}}var PS=class{constructor(t,r,n){this.binding=r;this.runtimeId=n;let o=Buffer.concat([N7t,t]);try{this.#e=(0,fo.createPrivateKey)({key:o,format:"der",type:"pkcs8"})}finally{o.fill(0)}let i=(0,fo.createPublicKey)(this.#e).export({format:"jwk"}).x;typeof i!="string"&&Q("custody_record_invalid"),this.publicJwk={kty:"OKP",crv:"Ed25519",x:i},this.jkt=il((0,ec.canonicalJson)(this.publicJwk))}binding;runtimeId;publicJwk;jkt;#e;signature(t){return(0,fo.sign)(null,Buffer.from(t),this.#e)}signer(){return{kid:this.jkt,publicJwk:this.publicJwk,sign:async t=>new Uint8Array(this.signature(t))}}};function IQ(e){Tp(e)||Q("identity_binding_invalid");let t=["profile","associationId","agentId","rootJkt","purpose"];Object.keys(e).some(u=>!t.includes(u))&&Q("identity_binding_invalid");let{profile:r,associationId:n,agentId:o,rootJkt:i,purpose:s}=e,a=r==="identity-tap-v1"&&s==="tap"&&yr(n),c=r==="legacy-root-certified-v1"&&n===void 0&&(s==="wallet:x402"||s==="card:vic");return(!yr(o)||!Sp(i)||!(a||c))&&Q("identity_binding_invalid"),a?{profile:"identity-tap-v1",associationId:n,agentId:o,rootJkt:i,purpose:"tap"}:{profile:"legacy-root-certified-v1",agentId:o,rootJkt:i,purpose:s}}function x7t(e){let t={agentId:"00000000-0000-4000-8000-000000000000",rootJkt:"A".repeat(43)};return e==="tap"?{profile:"identity-tap-v1",associationId:"00000000-0000-4000-8000-000000000000",...t,purpose:e}:{profile:"legacy-root-certified-v1",...t,purpose:e}}function $I(e){return e.binding.profile==="identity-tap-v1"&&e.binding.purpose==="tap"||e.binding.profile==="legacy-root-certified-v1"&&e.binding.purpose==="wallet:x402"}function PQ(e,t){e.binding.purpose!==t&&Q("key_purpose_mismatch")}function sk(e){e.binding.profile!=="legacy-root-certified-v1"&&Q("legacy_custody_profile_required")}function sNe(e,t){let r=z(t,"associationId"),n=e.binding.profile==="identity-tap-v1"?e.binding.associationId:void 0;(!(n!==void 0?n===r:$I(e)&&yr(r))||z(t,"agentId")!==e.binding.agentId||z(t,"runtimeId")!==e.runtimeId)&&Q("identity_binding_mismatch"),(at(t,"associationVersion")===0||at(t,"generation")===0)&&Q("request_invalid")}function wQ(e,t){let r=sn(e,["claims","signingInput"]),n=z(r,"signingInput");n.length>16384&&Q("request_invalid");let o=n.split(".");o.length!==2&&Q("request_invalid");let i=sn(iNe(o[0]),["alg","kid","typ"]),s=z(i,"kid");return(z(i,"alg")!=="EdDSA"||z(i,"typ")!==t||s.length===0||s.length>256||!/^[A-Za-z0-9._:@/-]+$/.test(s)||!mu(iNe(o[1]),r.claims))&&Q("request_invalid"),Tp(r.claims)||Q("request_invalid"),{claims:r.claims,kid:s}}var uNe=["v","iss","sub","jti","runtimeId","runtimeJkt","leaseIssuerJkt","purpose","network","signingModes","maxLeaseTtlSeconds","iat","nbf","exp"],M7t=[...uNe,"custody","rails"],aNe=["v","iss","sub","jti","runtimeId","cnf","purposes","iat","nbf","exp"],ak=class{#e;#r;constructor(t,r={}){this.#e=t,this.#r=r.nowSec??(()=>Math.floor(Date.now()/1e3))}async holds(t){try{return await this.load(t),"held"}catch(r){return r.message==="custody_unavailable"?"missing":"unknown"}}async load(t){/^[0-9a-f]{64}$/.test(t)||Q("custody_handle_invalid");let r=await this.#e.read(t),n;try{n=JSON.parse(Buffer.from(r).toString("utf8"))}catch{Q("custody_record_invalid")}finally{r.fill(0)}(!Tp(n)||n.v!==1||typeof n.seed!="string")&&Q("custody_record_invalid"),n.reservation!==void 0&&Q("custody_record_unbound");let o=KI(n.seed);(!o||o.length!==32||!yr(n.runtimeId))&&Q("custody_record_invalid");let i;try{i=IQ(n.binding)}catch{Q("custody_record_invalid")}try{return new PS(o,i,n.runtimeId)}finally{o.fill(0)}}describeKey(t,r){return{v:1,handle:t,runtimeId:r.runtimeId,binding:r.binding,publicJwk:r.publicJwk,jkt:r.jkt}}async create(t,r){let n=IQ(t);(r!==void 0&&!yr(r)||n.profile==="identity-tap-v1"&&r!==void 0)&&Q("identity_binding_invalid");let o=(0,fo.randomBytes)(32),i=(0,fo.randomBytes)(32).toString("hex"),s={v:1,seed:o.toString("base64url"),binding:n,runtimeId:r??(0,fo.randomUUID)()},a=Buffer.from(JSON.stringify(s),"utf8");try{await this.#e.create(i,a);let c=await this.#e.read(i);try{Buffer.from(c).equals(a)||Q("custody_readback_failed")}finally{c.fill(0)}let u=new PS(o,n,s.runtimeId);return this.describeKey(i,u)}finally{o.fill(0),a.fill(0)}}async reserve(t){t!=="wallet:x402"&&t!=="card:vic"&&t!=="tap"&&Q("identity_binding_invalid");let r=(0,fo.randomBytes)(32),n=(0,fo.randomBytes)(32).toString("hex"),o={v:1,seed:r.toString("base64url"),runtimeId:(0,fo.randomUUID)(),reservation:t==="tap"?{profile:"identity-tap-v1",purpose:t}:{profile:"legacy-root-certified-v1",purpose:t}},i=Buffer.from(JSON.stringify(o),"utf8");try{await this.#e.create(n,i);let s=await this.#e.read(n);Buffer.from(s).equals(i)||Q("custody_readback_failed");let a=new PS(r,x7t(t),o.runtimeId);return{handle:n,runtimeId:o.runtimeId,purpose:t,publicJwk:a.publicJwk,jkt:a.jkt}}finally{r.fill(0),i.fill(0)}}async adopt(t,r,n){/^[0-9a-f]{64}$/.test(t)||Q("custody_handle_invalid");let o=IQ(r),i=(0,fo.createHash)("sha256").update("visa-agent-key-adopt:v1\0").update(t).update("\0").update((0,ec.canonicalJson)(o)).digest("hex"),s=null;try{s=JSON.parse(Buffer.from(await this.#e.read(t)).toString("utf8"))}catch(d){if(d.message!=="custody_unavailable")throw d;let l=await this.describe(i);return n!==void 0&&l.runtimeId!==n&&Q("identity_binding_invalid"),l}(!Tp(s)||s.v!==1||!Tp(s.reservation)||s.reservation.profile!==o.profile||s.reservation.purpose!==o.purpose||!yr(s.runtimeId)||n!==void 0&&n!==s.runtimeId)&&Q("identity_binding_invalid");let a=KI(s.seed);(!a||a.length!==32)&&Q("custody_record_invalid");let c={v:1,seed:s.seed,binding:o,runtimeId:s.runtimeId},u=Buffer.from(JSON.stringify(c),"utf8");try{try{await this.#e.create(i,u)}catch(p){if(p.message!=="custody_handle_exists")throw p}let d=await this.#e.read(i);Buffer.from(d).equals(u)||Q("custody_readback_failed");let l=new PS(a,o,c.runtimeId);return await this.#e.delete(t),this.describeKey(i,l)}finally{a.fill(0),u.fill(0)}}async describe(t){return this.describeKey(t,await this.load(t))}async delete(t){/^[0-9a-f]{64}$/.test(t)||Q("custody_handle_invalid"),await this.#e.delete(t)}pop(t,r,n,o,i,s){(!(yr(r)||Sp(r))||!Sp(o))&&Q("request_invalid");let a={nonce:r,audience:n,nowSec:i,intentHash:o,...s===void 0?{}:{runtimeCertificate:s}};return(0,ck.createPopProofWithSigner)(t.signer(),a)}async enrollmentProof(t,r){let n=await this.load(t);$I(n)||Q("protected_association_required");let o=sn(r,["v","profile","associationId","associationVersion","agentId","runtimeId","generation","requestId","runtimePublicJwk","runtimeJkt","rootJkt","certificateSha256","delegationSha256","gateAuthorizationSha256","iat","exp"]);sNe(n,o),(at(o,"v")!==1||z(o,"profile")!=="identity-tap-v1"||!yr(z(o,"requestId"))||!mu(o.runtimePublicJwk,n.publicJwk)||z(o,"runtimeJkt")!==n.jkt||z(o,"rootJkt")!==n.binding.rootJkt||!Sp(z(o,"certificateSha256"))||!Sp(z(o,"delegationSha256"))||!Sp(z(o,"gateAuthorizationSha256")))&&Q("identity_binding_mismatch");let i=at(o,"iat"),s=at(o,"exp"),a=this.#r();return(i>a+5||s<=a||s<=i||s-i>600)&&Q("challenge_expired"),n.signature((0,ck.identityDeviceEnrollmentPreimage)(r)).toString("base64url")}async handoffProof(t,r){let n=await this.load(t);$I(n)||Q("protected_association_required");let o=sn(r,["v","operation","requestId","handoffId","proposal","body"]),i=sn(o.proposal,["associationId","associationVersion","agentId","rootJkt","runtimeId","runtimePublicJwk","runtimeJkt"]),s=n.binding.profile==="identity-tap-v1"?n.binding.associationId:void 0;(at(o,"v")!==1||!yr(z(o,"requestId"))||!yr(z(o,"handoffId"))||(s!==void 0?z(i,"associationId")!==s:!yr(z(i,"associationId")))||z(i,"agentId")!==n.binding.agentId||z(i,"rootJkt")!==n.binding.rootJkt||z(i,"runtimeId")!==n.runtimeId||at(i,"associationVersion")===0||!mu(i.runtimePublicJwk,n.publicJwk)||z(i,"runtimeJkt")!==n.jkt)&&Q("identity_binding_mismatch");let a=o.body,c=z(o,"operation");if(c==="create")sn(a,[]),z(o,"requestId")!==z(o,"handoffId")&&Q("request_invalid");else if(c==="read")sn(a,[]);else if(c==="cancel"){let l=sn(a,["enrollmentRequestId","generation"]);!(l.enrollmentRequestId===null&&l.generation===null)&&(!yr(z(l,"enrollmentRequestId"))||at(l,"generation")===0||at(l,"generation")>cNe)&&Q("request_invalid")}else if(c==="proof"){let l=sn(a,["enrollmentRequestId","runtimeProof"]),p=z(l,"runtimeProof");(!yr(z(l,"enrollmentRequestId"))||p.length!==86||KI(p)?.length!==64)&&Q("request_invalid")}else Q("request_invalid");let u=il((0,ec.canonicalJson)({v:1,operation:c,handoffId:z(o,"handoffId"),proposalSha256:il((0,ec.canonicalJson)(i)),bodySha256:il((0,ec.canonicalJson)(a))})),d=z(o,"requestId");return yr(d)||Q("request_invalid"),this.pop(n,d,"visa-device-handoff:v1",u,this.#r())}async leaseProof(t,r){let n=await this.load(t);$I(n)||Q("protected_association_required");let o=sn(r,["v","profile","associationId","associationVersion","agentId","runtimeId","generation","authorizationId","authorizationVersion","requestId","signingMode"]);sNe(n,o),(at(o,"v")!==1||z(o,"profile")!=="identity-tap-v1"||z(o,"signingMode")!=="tap"||!yr(z(o,"authorizationId"))||at(o,"authorizationVersion")===0)&&Q("request_invalid");let i=z(o,"requestId");return yr(i)||Q("request_invalid"),this.pop(n,i,"visa-identity-lease-requests:v1",il((0,ec.canonicalJson)(o)),this.#r())}async tapProof(t,r,n){let o=await this.load(t);$I(o)||Q("protected_association_required"),Tp(n)||Q("request_invalid");let i=["kind","method","authority","path","coveredComponents","paymentHeaderName","paymentHeaderValue","created","expires","keyId","nonce","tag","signatureBase"];n.contentDigest!==void 0&&i.push("contentDigest");let s=sn(n,i);(z(s,"kind")!=="tap_signature_base"||z(s,"tag")!=="agent-payer-auth"||!Sp(z(s,"keyId")))&&Q("request_invalid");let a=at(s,"created"),c=at(s,"expires"),u=this.#r();(a>u+30||c<=u||c<=a||c-a>480)&&Q("tap_expired");let d=z(s,"method"),l=z(s,"authority"),p=z(s,"path"),f=z(s,"paymentHeaderName"),m=z(s,"paymentHeaderValue"),h=N=>N.length>0&&Buffer.byteLength(N)<=8192&&!/[\0\r\n]/.test(N);(d.length===0||d.length>16||!/^[A-Z]+$/.test(d)||!h(l)||!h(p)||!p.startsWith("/")||!h(m)||!["payment-signature","x-payment","authorization"].includes(f)||f==="authorization"&&!/^payment \S/i.test(m))&&Q("tap_payload_invalid");let E=z(s,"nonce"),b=/^[A-Za-z0-9+/]*={0,2}$/.test(E)?Buffer.from(E,"base64"):null;(!b||b.length!==32||b.toString("base64")!==E)&&Q("tap_payload_invalid");let A=s.coveredComponents;(!Array.isArray(A)||A.length<4||A.length>5)&&Q("tap_payload_invalid");let S=new Set,T=[],v=[];for(let N of A){(typeof N!="string"||S.has(N))&&Q("tap_payload_invalid"),S.add(N);let L;if(N==="@method")L=d;else if(N==="@authority")L=l;else if(N==="@path")L=p;else if(N==="content-digest"){let x=z(s,"contentDigest");(!h(x)||!x.startsWith("sha-256=:"))&&Q("tap_payload_invalid"),L=x}else N===f?L=m:Q("tap_payload_invalid");v.push(`"${N}"`),T.push(`"${N}": ${L}`)}(!["@method","@authority","@path",f].every(N=>S.has(N))||S.has("content-digest")!==(s.contentDigest!==void 0))&&Q("tap_payload_invalid");let I=`(${v.join(" ")});created=${a};expires=${c};keyid="${z(s,"keyId")}";alg="Ed25519";nonce="${E}";tag="agent-payer-auth"`;T.push(`"@signature-params": ${I}`);let w=z(s,"signatureBase");return T.join(`
219
219
  `)!==w&&Q("tap_payload_invalid"),yr(r)||Q("request_invalid"),this.pop(o,r,"urn:visa:tvc:identity-gate",il(w),u)}async financialEnrollmentProof(t,r){let n=await this.load(t);sk(n),PQ(n,"wallet:x402");let o=sn(r,["v","purpose","requestId","associationId","associationVersion","runtimeId","runtimeGeneration","childJkt","preparedCertificate","preparedDelegation","expiresAt"]);(at(o,"v")!==1||z(o,"purpose")!=="financial.runtime.device.enroll"||!yr(z(o,"requestId"))||!yr(z(o,"associationId"))||at(o,"associationVersion")===0||at(o,"runtimeGeneration")===0)&&Q("request_invalid"),(z(o,"runtimeId")!==n.runtimeId||z(o,"childJkt")!==n.jkt||n.binding.rootJkt===n.jkt)&&Q("identity_binding_mismatch");let i=wQ(o.preparedCertificate,"visa-agent-runtime-cert+jwt"),s=wQ(o.preparedDelegation,"visa-agent-runtime-delegation+jwt");sn(i.claims,aNe);let a=sn(i.claims.cnf,["jwk","jkt"]),c="custody"in s.claims||"rails"in s.claims;sn(s.claims,c?M7t:uNe);let u=c?2:1;(at(s.claims,"v")!==u||c&&(z(s.claims,"custody")!=="device"||!(mu(s.claims.rails,["tempo","x402"])||mu(s.claims.rails,["x402"]))))&&Q("identity_binding_mismatch");let d=z(s.claims,"leaseIssuerJkt");(i.kid!==s.kid||!mu(a.jwk,n.publicJwk)||z(a,"jkt")!==n.jkt||!mu(i.claims.purposes,["wallet:x402"])||z(s.claims,"runtimeJkt")!==n.jkt||z(s.claims,"purpose")!=="wallet:x402"||z(s.claims,"network")!=="eip155:8453"||!mu(s.claims.signingModes,["eip3009:exact"])||at(s.claims,"maxLeaseTtlSeconds")!==300||!Sp(d)||d===n.jkt||d===n.binding.rootJkt)&&Q("identity_binding_mismatch");let l=this.#r(),p=at(i.claims,"iat"),f=at(o,"expiresAt");(f!==p+300||f<=l||f>l+330)&&Q("challenge_expired");for(let[m,h,E]of[[i.claims,86400,1],[s.claims,366*86400,u]]){(at(m,"v")!==E||z(m,"iss")!==n.binding.rootJkt||z(m,"sub")!==n.binding.agentId||z(m,"runtimeId")!==n.runtimeId||!yr(z(m,"jti")))&&Q("identity_binding_mismatch");let b=at(m,"exp");(at(m,"iat")!==p||at(m,"nbf")!==p||b<f||b<=p||b-p>h)&&Q("challenge_expired")}return this.pop(n,z(o,"requestId"),"visa:financial:device-enrollment:v1",il((0,ec.canonicalJson)(o)),l)}async cardEnrollmentProof(t,r){let n=await this.load(t);sk(n),PQ(n,"card:vic");let o=sn(r,["v","audience","requestId","associationId","associationVersion","instrumentId","runtimeId","generation","childJkt","preparedCertificate","expiresAt"]);(at(o,"v")!==1||z(o,"audience")!=="visa:financial:card-actor-enrollment:v1"||!yr(z(o,"requestId"))||!yr(z(o,"associationId"))||!yr(z(o,"instrumentId"))||at(o,"associationVersion")===0||at(o,"generation")===0)&&Q("request_invalid");let i=wQ(o.preparedCertificate,"visa-agent-runtime-cert+jwt");sn(i.claims,aNe);let s=sn(i.claims.cnf,["jwk","jkt"]);(z(o,"runtimeId")!==n.runtimeId||z(o,"childJkt")!==n.jkt||n.binding.rootJkt===n.jkt||at(i.claims,"v")!==1||z(i.claims,"iss")!==n.binding.rootJkt||z(i.claims,"sub")!==n.binding.agentId||z(i.claims,"runtimeId")!==n.runtimeId||!yr(z(i.claims,"jti"))||!mu(s.jwk,n.publicJwk)||z(s,"jkt")!==n.jkt||!mu(i.claims.purposes,["card:vic"]))&&Q("identity_binding_mismatch");let a=this.#r(),c=at(i.claims,"iat"),u=at(o,"expiresAt"),d=at(i.claims,"exp");return(u!==c+300||u<=a||u>a+330||at(i.claims,"nbf")!==c||d<u||d<=c||d-c>366*86400)&&Q("challenge_expired"),this.pop(n,z(o,"requestId"),z(o,"audience"),il((0,ec.canonicalJson)(o)),a)}async legacyProof(t,r){let n=await this.load(t);sk(n);let o=["nonce","audience","nowSec","intentHash"];Tp(r)&&r.runtimeCertificate!==void 0&&o.push("runtimeCertificate");let i=sn(r,o),s=z(i,"audience");(O7t[n.binding.purpose]??[]).includes(s)||Q("key_purpose_mismatch");let a=i.runtimeCertificate===void 0?void 0:z(i,"runtimeCertificate");return a!==void 0&&(a.length>16384||a.split(".").length!==3)&&Q("runtime_certificate_invalid"),this.pop(n,z(i,"nonce"),s,z(i,"intentHash"),this.proofTime(i),a)}async legacyLeaseProof(t,r){let n=await this.load(t);sk(n),PQ(n,"wallet:x402");let o=sn(r,["agentId","runtimeId","requestId","signingMode","nowSec"]);(z(o,"agentId")!==n.binding.agentId||z(o,"runtimeId")!==n.runtimeId)&&Q("identity_binding_mismatch");let i=z(o,"signingMode");i!=="eip3009:exact"&&i!=="permit2:upto"&&Q("key_purpose_mismatch");let s=z(o,"requestId"),a=il(JSON.stringify({v:1,agentId:n.binding.agentId,runtimeId:n.runtimeId,requestId:s,signingMode:i}));return this.pop(n,s,"visa-runtime-lease-requests:v1",a,this.proofTime(o))}proofTime(t){let r=at(t,"nowSec"),n=this.#r();return(r>n+30||r+60<n)&&Q("proof_time_invalid"),r}async proofKey(t){let r=await this.describe(t);return(r.binding.profile!=="legacy-root-certified-v1"||!["wallet:x402","card:vic"].includes(r.binding.purpose))&&Q("key_purpose_mismatch"),{jkt:r.jkt,publicJwk:r.publicJwk,createProof:n=>this.legacyProof(t,n),createLeaseProof:n=>this.legacyLeaseProof(t,n)}}close(){}};var pNe=require("node:child_process"),Bt=require("node:fs"),fk=require("node:path");Xo();var dk="com.visacli.agent-key.v2",wS=16384,L7t=/^[0-9a-f]{64}$/;function sl(e){if(!L7t.test(e))throw new Error("custody_handle_invalid")}function pk(e){if(e.length===0||e.length>wS)throw new Error("custody_record_too_large")}var dNe=null;var MQ=(e,t,r,n)=>dNe!==null?Promise.reject(new Error(dNe)):D7t(e,t,r,n),D7t=(e,t,r,n)=>new Promise(o=>{let i="",s="",a=!1,c=(0,pNe.spawn)(e,[...t],{stdio:["pipe","pipe","pipe"],windowsHide:!0}),u=l=>{a||(a=!0,clearTimeout(d),o(l))},d=setTimeout(()=>{c.kill(),u({status:null,stdout:i,stderr:s,error:"timeout"})},n);d.unref(),c.stdout.setEncoding("utf8").on("data",l=>{i+=l}),c.stderr.setEncoding("utf8").on("data",l=>{s+=l}),c.on("error",l=>u({status:null,stdout:i,stderr:s,error:l.code==="ENOENT"?"missing":"failed"})),c.on("close",l=>u({status:l,stdout:i,stderr:s})),c.stdin.on("error",()=>{}),c.stdin.end(r)}),uk="/usr/bin/security",lNe=44,k7t=45,OQ=class{#e;#r;#o=!1;constructor(t={}){if(t.keychain!==void 0&&/["\n\r]/.test(t.keychain))throw new Error("custody_directory_invalid");this.#e=t.keychain,this.#r=t.run??MQ}target(){return this.#e===void 0?[]:[this.#e]}refused(){return new Error("keychain_locked_or_unavailable")}async requireKeychain(){if(this.#o)return;let t=this.#e;if(t===void 0){let r=await this.#r(uk,["default-keychain","-d","user"],"",5e3);if(t=r.stdout.trim().replace(/^"(.*)"$/,"$1"),r.status!==0||r.error||!t)throw new Error("keychain_not_found")}if(!(0,Bt.existsSync)(t))throw new Error("keychain_not_found");this.#o=!0}async create(t,r){sl(t),pk(r),await this.requireKeychain();let n=this.#e===void 0?"":` "${this.#e}"`,o=Buffer.from(r).toString("base64"),i=await this.#r(uk,["-i"],`add-generic-password -s ${dk} -a ${t} -l visa-cli-agent-key -w ${o}${n}
220
- `,1e4);if(!(i.status===0&&!i.error))throw i.status===k7t?new Error("custody_handle_exists"):this.refused()}async read(t){sl(t),await this.requireKeychain();let r=await this.#r(uk,["find-generic-password","-s",dk,"-a",t,"-w",...this.target()],"",1e4);if(r.status===lNe)throw new Error("custody_unavailable");if(r.status!==0||r.error)throw this.refused();let n=r.stdout.trim(),o=/^[A-Za-z0-9+/]+={0,2}$/.test(n)?Buffer.from(n,"base64"):null;if(!o||o.toString("base64")!==n||o.length>wS)throw new Error("custody_record_invalid");return o}async delete(t){sl(t),await this.requireKeychain();let r=await this.#r(uk,["delete-generic-password","-s",dk,"-a",t,...this.target()],"",1e4);if(!(r.status===0||r.status===lNe))throw this.refused()}},RQ="secret-tool",NQ=class{#e;constructor(t={}){this.#e=t.run??MQ}attributes(t){return["service",dk,"handle",t]}refused(t){return t.error==="missing"?new Error("secret_service_unavailable"):/d-?bus|DBUS_SESSION_BUS_ADDRESS|\$DISPLAY|Could not connect/i.test(t.stderr)?new Error("secret_service_unavailable"):t.error==="timeout"?new Error("secret_service_timeout"):new Error("secret_service_locked_or_unavailable")}async lookup(t){let r=await this.#e(RQ,["lookup",...this.attributes(t)],"",1e4);if(r.status===0&&!r.error)return r.stdout;if(r.status===1&&!r.error&&r.stderr.trim()==="")return null;throw this.refused(r)}async create(t,r){if(sl(t),pk(r),await this.lookup(t)!==null)throw new Error("custody_handle_exists");let n=await this.#e(RQ,["store","--label=Visa CLI agent key",...this.attributes(t)],Buffer.from(r).toString("base64"),1e4);if(n.status!==0||n.error)throw this.refused(n)}async read(t){sl(t);let r=await this.lookup(t);if(r===null)throw new Error("custody_unavailable");let n=r.trim(),o=/^[A-Za-z0-9+/]+={0,2}$/.test(n)?Buffer.from(n,"base64"):null;if(!o||o.toString("base64")!==n||o.length>wS)throw new Error("custody_record_invalid");return o}async delete(t){sl(t);let r=await this.#e(RQ,["clear",...this.attributes(t)],"",1e4);if(!(r.status===1&&!r.error&&r.stderr.trim()==="")&&(r.status!==0||r.error))throw this.refused(r)}};function _Ne(e){if(!(0,Bt.existsSync)(e)){(0,Bt.mkdirSync)(e,{recursive:!0,mode:448}),process.platform!=="win32"&&(0,Bt.chmodSync)(e,448);return}let t=(0,Bt.lstatSync)(e);if(!t.isDirectory())throw new Error("custody_directory_invalid");if(process.platform!=="win32"&&(t.mode&63)!==0)throw new Error("custody_directory_not_private")}function mNe(e,t){let r;try{r=(0,Bt.openSync)(e,"wx",384)}catch(o){throw o.code==="EEXIST"?new Error("custody_handle_exists"):new Error("custody_create_failed")}let n=0;try{for(;n<t.length;)n+=(0,Bt.writeSync)(r,t,n)}catch{throw(0,Bt.closeSync)(r),(0,Bt.rmSync)(e,{force:!0}),new Error("custody_create_failed")}(0,Bt.closeSync)(r)}function fNe(e){return new Error(e?.code==="ENOENT"?"custody_unavailable":"custody_store_unreadable")}function gNe(e){let t;try{t=(0,Bt.lstatSync)(e)}catch(r){throw fNe(r)}if(!t.isFile()||t.size>wS*2)throw new Error("custody_file_invalid");try{return(0,Bt.readFileSync)(e)}catch(r){throw fNe(r)}}var CQ=class{constructor(t){this.directory=t}directory;path(t){return sl(t),(0,fk.join)(this.directory,`${t}.key`)}async create(t,r){let n=this.path(t);pk(r),_Ne(this.directory),mNe(n,r)}async read(t){let r=this.path(t);if(process.platform!=="win32"&&(0,Bt.existsSync)(this.directory)){let o=(0,Bt.lstatSync)(this.directory);if(!o.isDirectory()||(o.mode&63)!==0)throw new Error("custody_directory_not_private")}let n=gNe(r);if(process.platform!=="win32"&&((0,Bt.lstatSync)(r).mode&63)!==0)throw new Error("custody_file_invalid");if(n.length===0||n.length>wS)throw new Error("custody_file_invalid");return n}async delete(t){(0,Bt.rmSync)(this.path(t),{force:!0})}},U7t="powershell.exe";function j7t(e,t){return sl(t),["$ErrorActionPreference = 'Stop'","Add-Type -AssemblyName System.Security","$payload = [Convert]::FromBase64String([Console]::In.ReadToEnd().Trim())",`$entropy = [Text.Encoding]::UTF8.GetBytes('visa-agent-key:${t}')`,`$result = [System.Security.Cryptography.ProtectedData]::${e}($payload, $entropy, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)`,"[Console]::Out.Write([Convert]::ToBase64String($result))"].join("; ")}var xQ=class{constructor(t,r={}){this.directory=t;this.#e=r.run??MQ}directory;#e;path(t){return sl(t),(0,fk.join)(this.directory,`${t}.dpapi`)}async call(t,r,n){let o=await this.#e(U7t,["-NoProfile","-NonInteractive","-Command",j7t(t,r)],Buffer.from(n).toString("base64"),3e4),i=o.stdout.trim();if(o.status!==0||o.error||!/^[A-Za-z0-9+/]+={0,2}$/.test(i))throw new Error("dpapi_locked_or_unavailable");return Buffer.from(i,"base64")}async create(t,r){let n=this.path(t);if(pk(r),_Ne(this.directory),(0,Bt.existsSync)(n))throw new Error("custody_handle_exists");mNe(n,await this.call("Protect",t,r))}async read(t){let r=gNe(this.path(t)),n=await this.call("Unprotect",t,r);if(n.length===0||n.length>wS)throw new Error("custody_record_invalid");return n}async delete(t){(0,Bt.rmSync)(this.path(t),{force:!0})}};function lk(e=process.env){return(0,fk.join)(Tt(e),"agent-keys")}function hNe(e=process.env,t=process.platform){let r=e.VISA_RUNTIME_CUSTODY_PROFILE??"os";if(r==="headless")return new CQ(lk(e));if(r!=="os")throw new Error("native_runtime_custody_profile_invalid");if(t==="darwin")return new OQ;if(t==="win32")return new xQ(lk(e));if(t==="linux")return new NQ;throw new Error("custody_platform_unsupported")}var _k=new Map;function Vg(e=process.env){let t=`${e.VISA_RUNTIME_CUSTODY_PROFILE??"os"}\0${lk(e)}`,r=_k.get(t);return r||(r=new ak(hNe(e)),_k.set(t,r)),r}function B7t(){for(let e of _k.values())e.close();_k.clear()}process.once("exit",B7t);var WI=require("node:crypto");td();Ms();var LQ=new Set(["retired","revoked"]);async function ENe(e){let{binding:t,signer:r,api:n,env:o}=e,i=Qa(t.agentId,o);if(i&&!i.revoked)return"connected";let s=Hg({agentId:t.agentId,env:o});if(!s)return"pending";try{let a=await r.create({profile:"identity-tap-v1",associationId:t.associationId,agentId:t.agentId,rootJkt:t.rootJkt,purpose:"tap"}),c=IS(t.agentId,o),u=async f=>ZD(f,o),d=c&&c.runtimeKey.handle===a.handle?c:await SQ({api:n,native:r,key:a,agentId:t.agentId,associationId:t.associationId,expectedRootJkt:t.rootJkt,persist:u}),l=async()=>(d={...d,handoffId:(0,WI.randomUUID)()},await u(d),await tl(n,r,d,"create"),"pending"),p;try{p=await JD(n,r,d)}catch(f){if(f instanceof Tr&&f.code==="device_handoff_expired")return l();throw f}return p.status==="active"?(await VI({pending:d,view:p,native:r,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:o}),"connected"):LQ.has(p.status)?"stopped":p.status==="expired"||p.status==="cancelled"?l():"pending"}finally{s()}}async function yNe(e){let{binding:t,native:r,api:n,env:o}=e,i=Qa(t.agentId,o);if(i&&!i.revoked)return"connected";let s=IS(t.agentId,o);if(!s||s.runtimeKey.binding.profile!=="identity-tap-v1"||s.proposal.associationId!==t.associationId||s.proposal.rootJkt!==t.rootJkt)return"absent";let a=Hg({agentId:t.agentId,env:o});if(!a)return"pending";try{let c=async()=>{let d={...s,handoffId:(0,WI.randomUUID)()};return ZD(d,o),await tl(n,r,d,"create"),"pending"},u;try{u=await JD(n,r,s)}catch(d){if(d instanceof Tr&&d.code==="device_handoff_expired")return c();throw d}return u.status==="active"?(await VI({pending:s,view:u,native:r,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:o}),"connected"):LQ.has(u.status)?"stopped":u.status==="expired"||u.status==="cancelled"?c():"pending"}finally{a()}}var H7t=720*60*60;function q7t(e){if(typeof e!="string"||e.split(".").length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(".")[1],"base64url").toString("utf8")).exp;return Number.isSafeInteger(t)?t:null}catch{return null}}function YI(e,t,r=Math.floor(Date.now()/1e3)){let n;try{n=Qa(e,t)}catch{return"missing"}if(!n||n.revoked||n.runtimeKey.binding.profile!=="identity-tap-v1")return"missing";let o=[n.active.delegation,n.active.gateAuthorization].map(q7t);if(o.some(s=>s===null))return"missing";let i=Math.min(...o);return i<=r?"expired":i-r<H7t?"renew_due":"live"}async function V7t(e){let{binding:t,native:r,api:n,env:o}=e,i;try{i=Qa(t.agentId,o)}catch{return!1}if(!i||i.revoked||i.runtimeKey.binding.profile!=="identity-tap-v1")return!1;let s=await tl(n,r,i,"read"),a=Number(i.active.challenge?.generation??0);return s.status!=="active"||!(Number(s.challenge?.generation??0)>a)?!1:(await VI({pending:i,view:s,native:r,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:o,collectedRenewal:!0}),Me.info("identity_device_tap_renewal_collected",{agentId:t.agentId,generation:s.challenge?.generation}),!0)}async function DQ(e){let{binding:t,native:r,api:n,env:o}=e,i=YI(t.agentId,o,e.nowSec);if(i==="live")return{state:"connected"};if(i!=="missing")return await V7t({binding:t,native:r,api:n,env:o})?{state:"renewed"}:{state:"owner_renews"};let s=Hg({agentId:t.agentId,env:o});if(!s){let a=IS(t.agentId,o);return a?{state:"pending",pending:a}:{state:"connected"}}try{let a=IS(t.agentId,o),c=async l=>ZD(l,o),u=a&&a.runtimeKey.binding.profile==="identity-tap-v1"&&a.proposal.associationId===t.associationId&&a.proposal.rootJkt===t.rootJkt?a:null;if(!u){let l=await r.create({profile:"identity-tap-v1",associationId:t.associationId,agentId:t.agentId,rootJkt:t.rootJkt,purpose:"tap"});return u=await SQ({api:n,native:r,key:l,agentId:t.agentId,associationId:t.associationId,expectedRootJkt:t.rootJkt,persist:c}),Me.info("identity_device_tap_key_proposed",{agentId:t.agentId}),{state:"pending",pending:u}}let d;try{d=await JD(n,r,u)}catch(l){if(!(l instanceof Tr)||l.code!=="device_handoff_expired")throw l;return u={...u,handoffId:(0,WI.randomUUID)()},await c(u),await tl(n,r,u,"create"),{state:"pending",pending:u}}return d.status==="active"?(await VI({pending:u,view:d,native:r,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:o}),Me.info("identity_device_tap_connected",{agentId:t.agentId}),{state:"connected"}):LQ.has(d.status)?{state:"stopped"}:((d.status==="expired"||d.status==="cancelled")&&(u={...u,handoffId:(0,WI.randomUUID)()},await c(u),await tl(n,r,u,"create")),{state:"pending",pending:u})}finally{s()}}function SNe(e,t){try{let r=IS(e,t);if(!r||r.runtimeKey.binding.profile!=="identity-tap-v1")return!1;let n;try{n=Qa(e,t)}catch{n=null}return r.handoffId!==n?.handoffId}catch{return!1}}td();B_();OB();QT();tO();var TNe="5.0.0-rc.401",F7t=["association","handoff","lease","tap-sign"],bNe=262144,G7t=2e4;function RS(e={}){let t=(e.origin??Yl()).replace(/\/+$/,""),r=e.fetch;return{async identityDeviceRequest(n,o){if(!F7t.includes(n))throw new Error("identity_device_action_invalid");let i=JSON.stringify(o);if(Buffer.byteLength(i)>bNe)throw new Error("identity_device_request_too_large");let s=`${t}/v1/identity-device/${n}`,a={method:"POST",headers:{"Content-Type":"application/json","X-Visa-CLI-Version":TNe,"X-Source":"cli",...Xh()},body:i},c;try{c=await(r??fetch)(s,{...a,signal:AbortSignal.timeout(G7t)})}catch(l){throw new Error(YR(l))}let u;try{let l=Buffer.from(await c.arrayBuffer());if(l.byteLength>bNe)throw new Error("response_too_large");u=JSON.parse(l.toString("utf8"))}catch{u=void 0}let d=QR(c.status,u,TNe);if(d)throw d;if(typeof u?.ok!="boolean")throw new Tr(`Identity device relay returned an invalid response for ${n} (${c.status}).`,c.status,"identity_device_response_invalid",void 0,!1);if(!c.ok||u.ok!==!0){let l=typeof u.code=="string"?u.code:void 0,p=typeof u.retryable=="boolean"?u.retryable:void 0;throw new Tr(`Identity device ${n} refused (${c.status}${l?` ${l}`:""}).`,c.status,l,void 0,p)}return u}}}var vNe=require("node:child_process"),INe=j(require("node:os")),$7t=64,K7t={platform:process.platform,computerName:()=>{try{return(0,vNe.execFileSync)("scutil",["--get","ComputerName"],{encoding:"utf8",timeout:1e3,stdio:["ignore","pipe","ignore"]})}catch{return null}},hostname:()=>INe.default.hostname()};function PNe(e=K7t){let t=e.platform==="darwin"?[e.computerName(),ANe(e)]:[ANe(e)];for(let r of t){let n=W7t(r);if(n)return n}return null}function ANe(e){try{return e.hostname().replace(/\.local\.?$/i,"")}catch{return null}}function W7t(e){if(typeof e!="string")return null;let t=e.normalize("NFC").replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu," ").replace(/\s+/gu," ").trim();return t&&Array.from(t).slice(0,$7t).join("").trim()||null}td();Vl();Bh();Ms();vc();var wNe=require("node:crypto");var I9r=30*1e3,Y7t=new Map;function J7t(){Y7t.clear()}function z7t(e){let t=V1e(e.homeDir),r=t?.financialDeviceRuntimeId;if(!t||t.agentId!==e.agentId||!r)return null;let n=Lg(e.agentId,e.env);if(!n||n.runtimeKey.runtimeId!==r)return null;let o=D1e(t,e.env),i=o?pu(o):e.api;return{runtimeId:r,active:n,api:i}}async function X7t(e,t,r){return await e.financialRuntimeRequest("tempo-context",{requestId:(0,wNe.randomUUID)(),agentId:t,runtimeId:r})}function kQ(e){let t=e?.code;return t==="agent_revoked"||t==="device_key_replaced"}async function mk(e){let t;try{t=z7t(e)}catch{return"unknown"}if(!t)return"unknown";let r;try{r=await X7t(t.api,e.agentId,t.runtimeId)}catch(n){if(kQ(n))throw n;return"unknown"}return r?.v!==1||typeof r.enrolled!="boolean"?"unknown":r.available===!1?"switched_off":(r.enrolled&&J7t(),r.enrolled?"enrolled":"setup_pending")}var UQ={begin:async(e,t,r)=>{let n=nd(r),o=eE(Date.now(),n);o&&o.verifier===t&&!o.likelyExpired||await sO(e,Date.now(),n,{verifier:t})},claim:(e,t)=>tE(e,{loginDir:nd(t),attempts:1}),revert:async(e=process.env)=>{let t=wn(e);if(t)try{await ct.deleteProfileSessionToken(t,e)}finally{hR(t.profileId,e)}}};async function RNe(e=process.env,t=cO){try{if(_Q(e).length!==0)return null}catch{return null}let r=Qo(ka(e));try{let o=Ep(e);if(o&&AS(o))return{baseUrl:r}}catch{}let n=await t(r);return n.ready&&n.features.includes(Tde)?{baseUrl:r}:null}var ONe={start:N1e,claim:L1e,bindApi:pu,custody:Vg,beginDevice:LI,advanceDevice:SS,connectDevice:W1e,finishDevice:Y1e,beginCard:oNe,advanceCard:GI,advanceTap:ENe,identityDevice:RS,walletHomeForAgent:vS,walletStateRoot:_u,claimApp:(e,t,r)=>new Ls(()=>ct.getSessionToken()).claimAgentForApp(e,t,r),deviceName:()=>PNe(),tempoKey:mk,sleep:e=>new Promise(t=>setTimeout(t,e)),now:()=>Date.now(),signIn:UQ,announceCode:e=>C1e(e)},Z7t=new Set(["identity_authority_not_configured"]);function jQ(e){return e instanceof lu?!0:e instanceof Yi?!(e.code!==null&&Z7t.has(e.code))&&(e.status>=500||e.status===429):jI(e)==="ProtectedAuthorityTransportError"}var Q7t=12e4,ezt=12e4,tzt=3,BQ=1e3,rzt=15e3,nzt=1800*1e3;function ozt(e){return Math.min(BQ*2**Math.max(0,e-1),rzt)}function HQ(e){if(!/^\d+(?:\.\d{1,2})?$/.test(e))throw new Error("Limits must be positive dollar amounts with at most two decimal places");let t=Math.round(Number(e)*100);if(!Number.isSafeInteger(t)||t<=0)throw new Error("Limits must be positive dollar amounts");return t}async function izt(e,t,r){let n=t.app??pQ(t.env);if(!n)return;let o=null;try{o=e.deviceName?e.deviceName():null}catch{o=null}try{let i=await e.claimApp(r,n,o);Me.info("agent:protected_enrollment_app_stamped",{agentId:r,harnessId:n,claimed:i.claimed,deviceReported:o!==null})}catch(i){Me.warn("agent:protected_enrollment_app_stamp_failed",{agentId:r,harnessId:n,error:i instanceof Error?i.message:"request refused"})}}async function szt(e,t=ONe){if(!Number.isSafeInteger(e.attempts)||e.attempts<1||e.attempts>900)throw new Error("Attempts must be between 1 and 900");let r=t.start({webOrigin:e.webOrigin,restart:e.restart,env:e.env,...e.webStartKey!==void 0?{webStartKey:e.webStartKey}:{},...e.signIn?{signIn:!0}:{}});await R1e(r,t.custody(e.env),e.env);let n=e.signIn&&AS(r)?e.signIn:null,o=n?t.signIn??UQ:null;n&&o&&await o.begin(n.baseUrl,r.verifier,e.env),await t.announceCode?.(r);let i=x1e(r,e.app??pQ(e.env)),s=od(r.verifier);r.binding||await e.announce({kind:"owner_enrollment",url:i,confirmCode:s});let a=null,c=0,u=null,d=t.now??(()=>Date.now()),l=d();for(let p=0;p<e.attempts;p++){if(d()-l>=nzt){Me.warn("agent:protected_enrollment_pickup_deadline",{attempt:p+1,waitedMs:d()-l});break}p>0&&await t.sleep(c>0?ozt(c):BQ);try{if(n&&o&&AS(r)){let f=await o.claim(n.baseUrl,e.env);if(f.status==="confirm_mismatch")throw new Error("The code entered in the browser does not match this terminal, so it was not signed in. Run `visa connect --restart` and enter the code this terminal shows.");if(f.status==="error")throw new lu("Visa sign-in","network",0);if(f.status!=="claimed"||!fQ(r,e.env))continue}try{a=await t.claim(r,e.env)}catch(f){if(r.signIn===!0&&f instanceof Xt&&f.code==="enrollment_owner_mismatch")try{await(t.signIn??UQ).revert(e.env)}catch(m){Me.warn("agent:protected_enrollment_sign_in_revert_failed",{reason:m instanceof Error?m.name:typeof m})}throw f}}catch(f){if(!jQ(f))throw f;c++,u=f,Me.warn("agent:protected_enrollment_pickup_retry",{attempt:p+1,consecutiveFailures:c,status:f instanceof Yi?f.status:null,reason:f instanceof lu?f.reason:null});continue}if(c=0,u=null,a)break}return a?{status:"identity_active",pending:r,binding:a,enrollmentUrl:i}:{status:"awaiting_owner_enrollment",browserUrl:i,confirmCode:s,...u?{lastPickupFailure:u instanceof Error?u.message:"Authority unavailable"}:{}}}async function NNe(e,t=ONe){if(e.perTransactionLimitCents>e.dailyLimitCents)throw new Xt("Per-purchase limit exceeds daily limit","invalid_argument");if(!Number.isSafeInteger(e.attempts)||e.attempts<1||e.attempts>900)throw new Xt("Attempts must be between 1 and 900","invalid_argument");let r=await szt(e,t);if(r.status!=="identity_active")return r;let{pending:n,binding:o,enrollmentUrl:i}=r,s={v:1,authorityOrigin:n.authorityOrigin,executionOrigin:n.executionOrigin,transportProfileId:n.transportProfileId,binding:o},a=t.bindApi(s),c=b1e(t.custody(e.env),n.deviceKeys),u={api:a,signer:c,selection:s,env:e.env,ceremony:{ceremonyId:o.ceremonyId,challenge:n.challenge,verifier:n.verifier}},d=t.identityDevice({origin:n.executionOrigin}),l="pending",p,f,m=!1,h=async()=>{if(!(l==="connected"||l==="stopped"||m))try{l=await t.advanceTap({binding:o,signer:c,api:d,env:e.env}),p=void 0,f=void 0}catch(k){l="failed",m=!jQ(k),p=k instanceof Error?k.message:"TAP connection refused",f=Ac(k),Me.warn("agent:protected_enrollment_tap_pending",{agentId:o.agentId,errorName:jI(k),code:f.code,...k instanceof Yi?{status:k.status}:{}})}},E=await t.beginCard({...u,initialConnection:!0});await h();let b=async()=>{try{return(await t.advanceCard(u)).status==="active"}catch(k){if(!jQ(k))throw k;return Me.warn("agent:protected_card_connection_pending",{agentId:o.agentId,errorName:jI(k),...k instanceof Yi?{status:k.status}:{}}),!1}},A=()=>t.walletHomeForAgent(o.agentId,t.walletStateRoot(e.env),o.ownerPublicId),S=async k=>t.tempoKey?t.tempoKey({api:a,agentId:o.agentId,homeDir:k,env:e.env}):"enrolled",T=async k=>(k!=="enrolled"&&Me.warn("agent:protected_enrollment_wallet_key_owed",{agentId:o.agentId,walletKey:k}),Me.info("agent:protected_enrollment_connected",{agentId:o.agentId,tap:l,walletKey:k,wait:e.wait}),await izt(t,e,o.agentId),{status:"connected",agentId:o.agentId,tap:l,...l==="failed"&&p?{tapError:p}:{},...l==="failed"&&f?{tapDiagnostic:f}:{},walletKey:k});if(!e.wait){let k=await t.beginDevice({api:a,signer:c,agentId:o.agentId,ownerPublicId:o.ownerPublicId,cardProposal:E.proposal,ceremony:{ceremonyId:o.ceremonyId,challenge:n.challenge,verifier:n.verifier},env:e.env}),H=await t.advanceDevice({api:a,signer:c,pending:k,env:e.env}),B=k.cardProposal?await b():!0;await h();let q=l==="failed"?{tap:l,tapError:p,tapDiagnostic:f}:{};if(!(H?.prepared?.status==="active"||!!H?.evidence?.owner_signatures))return{status:"awaiting_owner_device_approval",browserUrl:i,agentId:o.agentId,...q};let G=A();return B&&await t.finishDevice({api:a,signer:c,agentId:o.agentId,ownerPublicId:o.ownerPublicId,agentName:"Protected agent",authUrl:n.authorityOrigin,walletHomeDir:G,pending:k,view:H,env:e.env})?T(await S(G)):(Me.info("agent:protected_enrollment_device_finishing",{agentId:o.agentId,active:H?.prepared?.status==="active",companionReady:B}),{status:"finishing_device_setup",browserUrl:i,agentId:o.agentId,...q})}let v=A();await t.connectDevice({api:a,signer:c,agentId:o.agentId,ownerPublicId:o.ownerPublicId,cardProposal:E.proposal,advanceCompanion:b,advanceTap:async()=>{l==="failed"&&!m&&(l="pending"),await h()},ceremony:{ceremonyId:o.ceremonyId,challenge:n.challenge,verifier:n.verifier},agentName:"Protected agent",authUrl:n.authorityOrigin,walletHomeDir:v,env:e.env});let I=t.now??(()=>Date.now()),w=I()+Q7t,N=I()+ezt,L=await S(v),x=()=>(l==="pending"||l==="failed")&&!m,D=()=>L==="setup_pending"||L==="unknown";for(let k=1;;k++){let H=x()&&I()<w,B=D()&&I()<N;if(!H&&!B)break;await t.sleep(BQ),H&&(l==="failed"&&(l="pending"),await h()),B&&k%tzt===0&&(L=await S(v))}return T(L)}var Fg=require("node:fs"),OS=require("node:path"),DNe=require("node:crypto");jl();Xo();var MNe=require("node:crypto");var CNe=require("node:path");Xo();function azt(e,t){return Qa(e,t),(0,CNe.join)(Tt(t),"financial-device-presence",`${e}.revocation.json`)}function gk(e,t){let r=ss(azt(e,t));if(r===null)return null;On(r);let n=JSON.parse(r);if(n.v!==1||n.selected?.proposal.agentId!==e||!Array.isArray(n.keys)||!n.keys.length||!["awaiting_owner","revocation_verified","complete"].includes(n.phase)||n.keys.some(({record:i})=>i.proposal.agentId!==e||i.proposal.runtimeId!==n.selected.proposal.runtimeId||i.proposal.associationId!==n.selected.proposal.associationId))throw new Error("identity_device_revocation_invalid");if(Qa(e,t)?.handoffId!==n.selected.handoffId){if(n.phase==="complete")return null;throw new Error("identity_device_selection_changed")}return n}var xNe=e=>e instanceof Error&&e.message?e.message:String(e);function al(e,t){try{let r=gk(e,t);if(r&&r.phase!=="complete"&&TQ(r.selected))return{state:"revoking"};let n=Qa(e,t);if(n?.revoked&&TQ(n))return{state:"revoked"}}catch(r){return{state:"unreadable",detail:`presence: ${xNe(r)}`}}try{let r=Lg(e,t);if(r)return{state:"installed",runtimeId:r.runtimeKey.runtimeId,record:r};let n=yS(e,t);if(n)return{state:"wallet_setup_pending",runtimeId:n.runtimeKey.runtimeId}}catch(r){return{state:"unreadable",detail:xNe(r)}}return{state:"missing"}}function czt(e){let t=e?.deviceWalletAuthority;return t==="live"||t==="expired"||t==="absent"?t:"unreachable"}async function LNe(e,t=(r,n)=>pu(e).financialRuntimeRequest(r,n)){try{return czt(await t("device-context",{requestId:(0,MNe.randomUUID)(),agentId:e.binding.agentId}))}catch(r){if(qQ(r)||kQ(r))throw r;return"unreachable"}}function qQ(e){return e instanceof Error&&/independently claimed owner/.test(e.message)}td();Ms();var uzt=["revoked","key_not_held","replaced","superseded"],VQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function JI(e){let t=(0,OS.join)(Tt(e),"protected-enrollment","retired");return(0,Fg.mkdirSync)(t,{recursive:!0,mode:448}),So(t),t}function FQ(e,t,r,n=()=>new Date){if(!VQ.test(e))throw new Error("retired_agent_id_invalid");let o=(0,OS.join)(JI(r),`${e}.json`),i=kNe(o);if(i)return i;let s={v:1,agentId:e,reason:t,retiredAt:n().toISOString()};return Pn(o,JSON.stringify(s)),s}function kNe(e){let t=To(e);if(t===null)return null;let r=JSON.parse(t);if(r?.v!==1||!VQ.test(r.agentId)||!uzt.includes(r.reason)||typeof r.retiredAt!="string")throw new Error("retired_agent_record_invalid");return r}function UNe(e){let t=new Map,r;try{r=(0,Fg.readdirSync)(JI(e))}catch{return t}for(let n of r)if(!(!n.endsWith(".json")||!VQ.test(n.slice(0,-5))))try{let o=kNe((0,OS.join)(JI(e),n));o&&`${o.agentId}.json`===n&&t.set(o.agentId,o)}catch{}return t}function zI(e){let t=UNe(e);return Ug(e).filter(r=>!t.has(r.binding.agentId))}async function jNe(e,t){let r=e.binding.agentId,n=[],o=null,i=al(r,t.env);i.state==="installed"&&(n.push(i.record.runtimeKey.handle),o=i.record.runtimeKey.runtimeId);try{let s=qg(e,t.env);s?.certificate&&n.push(s.runtimeKey.handle)}catch{}if(n.length>0&&(await Promise.all(n.map(a=>t.holds(a)))).every(a=>a==="missing")&&Me.warn("agent:held_agent_keys_not_in_this_store",{agentId:r}),o)try{await t.api(e).financialRuntimeRequest("tempo-context",{requestId:(0,DNe.randomUUID)(),agentId:r,runtimeId:o})}catch(s){if(s instanceof Yi&&s.code==="agent_revoked")return{agentId:r,verdict:"retire",reason:"revoked"};if(s instanceof Yi&&s.code==="device_key_replaced")return{agentId:r,verdict:"retire",reason:"replaced"}}if((t.resumable??hk)(e,t.env))return{agentId:r,verdict:"usable"};try{if(await t.association?.(e)==="revoked")return{agentId:r,verdict:"retire",reason:"revoked"}}catch{}return{agentId:r,verdict:"usable"}}async function dzt(e){let t=[],r,n;try{r=UNe(e.env),n=Ug(e.env)}catch{return t}for(let o of n){let i=o.binding.agentId;if(r.get(i)?.reason==="key_not_held")try{if((await jNe(o,e)).verdict==="retire"){(0,Fg.rmSync)((0,OS.join)(JI(e.env),`${i}.json`),{force:!0}),FQ(i,"revoked",e.env);continue}(0,Fg.rmSync)((0,OS.join)(JI(e.env),`${i}.json`),{force:!0}),Me.info("agent:held_agent_restored",{agentId:i}),t.push(i)}catch(s){Me.warn("agent:held_agent_restore_failed",{agentId:i,error:s instanceof Error?s.message:String(s)})}}return t}async function BNe(e){let t;try{t=zI(e.env)}catch{return[]}await dzt(e);try{t=zI(e.env)}catch{return[]}let r=[];for(let n of t)try{let o=await jNe(n,e);if(o.verdict!=="retire")continue;let i=FQ(o.agentId,o.reason,e.env);Me.warn("agent:held_agent_retired",{agentId:i.agentId,reason:i.reason}),r.push(i)}catch(o){Me.warn("agent:held_agent_judge_failed",{agentId:n.binding.agentId,error:o instanceof Error?o.message:String(o)})}return r}function GQ(e){return e.reason==="revoked"?`Agent ${e.agentId} was revoked, so it can no longer pay; connecting a new agent`:e.reason==="replaced"?`Agent ${e.agentId} now runs on another computer that replaced its keys, so this one can no longer pay for it; connecting a new agent`:e.reason==="superseded"?`Agent ${e.agentId} was an earlier setup on this computer that never finished; a later setup replaced it, so it is set aside (its records are kept)`:`Agent ${e.agentId} was set up by an older Visa CLI whose keys this version cannot use; connecting a new agent`}function $Q(e){let t;try{t=zI(e)}catch{return[]}let r=new Map(t.map(o=>{try{return[o.binding.agentId,KQ(o,e)]}catch{return[o.binding.agentId,null]}}));if(![...r.values()].includes("installed"))return[];let n=[];for(let o of t){let i=o.binding.agentId;if(r.get(i)!=="unfinished"||hk(o,e))continue;let s=al(i,e);if(s.state!=="wallet_setup_pending"&&s.state!=="missing"){s.state==="unreadable"&&Me.warn("agent:held_agent_setup_unreadable",{agentId:i,detail:s.detail});continue}try{if(qg(o,e)?.certificate)continue}catch{Me.warn("agent:held_agent_setup_unreadable",{agentId:i,detail:"card record"});continue}try{let a=FQ(i,"superseded",e);Me.warn("agent:held_agent_retired",{agentId:i,reason:a.reason}),n.push(a)}catch(a){Me.warn("agent:held_agent_retire_failed",{agentId:i,error:a instanceof Error?a.message:String(a)})}}return n}async function HNe(e){try{return await RS({origin:e.executionOrigin}).identityDeviceRequest("association",{agentId:e.binding.agentId}),"active"}catch(t){return t instanceof Tr&&(t.code==="association_inactive"||t.code==="agent_revoked")?"revoked":"unknown"}}function KQ(e,t){if(al(e.binding.agentId,t).state!=="installed")return"unfinished";try{let r=qg(e,t);if(r&&!r.certificate)return"unfinished"}catch{}return"installed"}function hk(e,t){let r;try{r=Ep(t)}catch{return!1}return!!(r?.binding&&r.binding.agentId===e.binding.agentId&&r.binding.associationId===e.binding.associationId&&Date.now()-r.createdAt<UI)}async function qNe(e,t,r){let n=[],o=al(e.binding.agentId,r);o.state==="installed"&&n.push(o.record.runtimeKey.handle);try{let s=qg(e,r);s?.certificate&&n.push(s.runtimeKey.handle)}catch{}return n.length===0?"readable":(await Promise.all(n.map(s=>t(s).catch(()=>"unknown")))).every(s=>s==="missing")?"unreadable":"readable"}vc();Vl();td();var lzt=new Set(["registered","removal_pending","pending","blocked","not_requested","deactivated","contact_required","unavailable"]);function fzt(e){return typeof e=="string"&&lzt.has(e)?e:"unknown"}function pzt(e,t,r){return{key:YI(e,r),directory:fzt(t?.find(n=>n.agentId===e)?.tapStatus)}}async function VNe(e,t,r){let n=null;try{n=await t()}catch{n=null}return pzt(e,n,r)}function FNe(e){return VNe(e,()=>new Ls(()=>ct.getSessionToken()).listAccountAgents())}async function _zt(e){try{if(await ct.getSessionToken())return"already"}catch{}try{let t=eE();if(!t||t.likelyExpired||e===!0)return null;let r=Qo(ka());return(await tE(r,{attempts:1})).status==="claimed"?"claimed":null}catch{return null}}var GNe=e=>e==="setup_pending"?"finish_wallet_key":e==="switched_off"?"wallet_switched_off":e==="unknown"?"confirm_wallet_key":"none";async function mzt(e){try{return await mk({api:pu(e),agentId:e.binding.agentId,homeDir:vS(e.binding.agentId,_u(),e.binding.ownerPublicId)})}catch{return"unknown"}}async function gzt(e){let t=e.binding,r=al(t.agentId);if(r.state==="installed"){try{await LNe(e)}catch(s){if(qQ(s))throw s}let i=r.record;if(i.ownerPublicId!==t.ownerPublicId||i.organizationId!==t.organizationId||i.proposal.associationId!==t.associationId||i.proposal.associationVersion!==t.associationVersion||i.proposal.rootJkt!==t.rootJkt||i.rootKid!==t.rootKid)throw new Error("Protected wallet installation differs from its independently claimed owner");return}let n;try{n=yS(t.agentId)}catch{return}if(!n)return;let o=Ep();if(o?.binding?.agentId!==t.agentId||o.binding.ceremonyId!==t.ceremonyId||o.executionOrigin!==e.executionOrigin||o.authorityOrigin!==e.authorityOrigin||Date.now()-o.createdAt>=UI||n.ceremony.ceremonyId!==o.ceremonyId||n.ceremony.challenge!==o.challenge||n.ceremony.verifier!==o.verifier||n.proposal.associationId!==t.associationId||n.proposal.associationVersion!==t.associationVersion||n.proposal.rootJkt!==t.rootJkt)throw new Error("Existing wallet setup cannot resume this identity; call get_status before restarting enrollment")}async function hzt(e,t,r){let n=e.binding.agentId,o=al(n).state,i=o==="revoking"||o==="revoked";try{let a=gk(n);i||=!!(a&&a.phase!=="complete")}catch{}if(i)return{state:"revoking"};let s={binding:e.binding,native:Vg(),api:RS({origin:e.executionOrigin})};try{let a=await yNe(s);if(a==="stopped")return{state:"stopped"};let c=a==="pending";if(!c)try{c=SNe(n)||YI(n)!=="live"}catch{c=!0}if(!c)return{state:"live"};let u=Date.now()+Math.max(1,r)*1e3,d=await DQ(s);for(;d.state==="pending"&&t&&Date.now()<u;)await new Promise(l=>setTimeout(l,1e3)),d=await DQ(s);return d.state!=="pending"?{state:d.state}:{state:"awaiting_owner",url:X1e(aO(ka()),d.pending),fingerprint:d.pending.proposal.runtimeJkt}}catch(a){return{state:"failed",error:a}}}async function Ezt(e,t,r){let n=await vQ(e);if(!t||!n.renew)return{card:{state:"untouched"},cardKey:n.state};try{let o={api:pu(e),signer:Vg(),selection:e,renewWithinSeconds:nk},i=await GI(o);return i.status==="retry"&&(i=await GI(o)),i.status==="active"?{card:{state:"renewed"},cardKey:(await vQ(e)).state}:i.status==="awaiting_owner"?{card:{state:"awaiting_owner",url:rNe(ka({...process.env,VISA_AUTH_URL:e.authorityOrigin}),{proposal:i.proposal},r)},cardKey:"renewing"}:{card:{state:"busy"},cardKey:"renewing"}}catch(o){return{card:{state:"failed",error:o},cardKey:n.state}}}function WQ(e){if(e!==void 0&&!w1e.test(e))throw new Xt("That setup key is not one Visa issued. Copy the whole `visa connect --setup` line from the page that started the setup.","invalid_argument")}async function $Ne(e){WQ(e.webStartKey);let t=[],r=[],n=await _zt(e.restart);n==="already"&&e.verifySession&&await e.verifySession()===!1&&(n=null);let o=n?null:await RNe();if(o&&(n="one_code"),!n){let l=await e.signIn();if(!l.done)return{leg:"signin",pending:l.pending,signIn:"pending",retired:t,superseded:r,nextAction:"sign_in"};n="interactive"}let i={signIn:n,retired:t,superseded:r},s=null;if(!e.restart){t.push(...await BNe({holds:async p=>Vg().holds(p),api:p=>pu(p),association:HNe}),...$Q());let l=e.webStartKey===void 0?zI()[0]:void 0;if(l){let p=l.binding.agentId;if(await gzt(l),KQ(l)==="unfinished"){if(!hk(l))return{...i,leg:"unfinished_expired",agentId:p,nextAction:"restart_to_replace"};s=p}else{if(await qNe(l,async f=>Vg().holds(f))==="unreadable")return{...i,leg:"unreadable_keys",agentId:p,nextAction:"restart_new_agent"};{let f=await hzt(l,e.tapWait,e.attempts),m=f.state==="awaiting_owner"?null:await mzt(l),h;try{h=al(p).state!=="missing"}catch{h=!0}let E=GNe(m),b=E!=="none"&&(h||E!=="confirm_wallet_key"),A=f.state==="awaiting_owner"?"approve_device":f.state==="failed"?Ac(f.error).code==="update_required"?"update_cli":"retry_tap":b?E:f.state==="owner_renews"?"owner_renews_tap":"none",{card:S,cardKey:T}=await Ezt(l,A==="none",e.app),v=A!=="none"?A:S.state==="awaiting_owner"?"approve_card":S.state==="failed"||S.state==="busy"?"retry_card":E;return{...i,leg:"held",agentId:p,tap:f,walletKey:m,tapStatus:await FNe(p),card:S,cardKey:T,nextAction:v}}}}}let a=null,c=await NNe({webOrigin:ka(),...o?{signIn:o}:{},...e.app!==void 0?{app:e.app}:{},restart:e.restart,...e.webStartKey!==void 0?{webStartKey:e.webStartKey}:{},wait:e.wait,attempts:e.attempts,dailyLimitCents:e.dailyLimitCents,perTransactionLimitCents:e.perTransactionLimitCents,announce:async l=>{a=l,await e.announce?.(l,o!==null)}});c.status!=="awaiting_owner_enrollment"&&r.push(...$Q());let u=c.status==="awaiting_owner_enrollment"?"approve":c.status==="awaiting_owner_device_approval"?"approve_device":c.status==="finishing_device_setup"?"finish_device":GNe(c.walletKey),d=c.status==="awaiting_owner_enrollment"?null:await FNe(c.agentId);return{...i,leg:"enroll",resumed:s,result:c,announcement:a,tapStatus:d,nextAction:u}}Vl();Bh();var WNe=require("child_process");B_();function yzt(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.VISA_SUPPRESS_BROWSER==="1"||e.VISA_SUPPRESS_BROWSER==="true"?{headless:!0,reason:"VISA_SUPPRESS_BROWSER is set"}:e.CHECKOUT_SKIP_BROWSER_OPEN==="1"||e.CHECKOUT_SKIP_BROWSER_OPEN==="true"?{headless:!0,reason:"CHECKOUT_SKIP_BROWSER_OPEN is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.JEST_WORKER_ID!==void 0||e.VITEST!==void 0||e.NODE_ENV==="test"?{headless:!0,reason:"test runner 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 Szt(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(`
220
+ `,1e4);if(!(i.status===0&&!i.error))throw i.status===k7t?new Error("custody_handle_exists"):this.refused()}async read(t){sl(t),await this.requireKeychain();let r=await this.#r(uk,["find-generic-password","-s",dk,"-a",t,"-w",...this.target()],"",1e4);if(r.status===lNe)throw new Error("custody_unavailable");if(r.status!==0||r.error)throw this.refused();let n=r.stdout.trim(),o=/^[A-Za-z0-9+/]+={0,2}$/.test(n)?Buffer.from(n,"base64"):null;if(!o||o.toString("base64")!==n||o.length>wS)throw new Error("custody_record_invalid");return o}async delete(t){sl(t),await this.requireKeychain();let r=await this.#r(uk,["delete-generic-password","-s",dk,"-a",t,...this.target()],"",1e4);if(!(r.status===0||r.status===lNe))throw this.refused()}},RQ="secret-tool",NQ=class{#e;constructor(t={}){this.#e=t.run??MQ}attributes(t){return["service",dk,"handle",t]}refused(t){return t.error==="missing"?new Error("secret_service_unavailable"):/d-?bus|DBUS_SESSION_BUS_ADDRESS|\$DISPLAY|Could not connect/i.test(t.stderr)?new Error("secret_service_unavailable"):t.error==="timeout"?new Error("secret_service_timeout"):new Error("secret_service_locked_or_unavailable")}async lookup(t){let r=await this.#e(RQ,["lookup",...this.attributes(t)],"",1e4);if(r.status===0&&!r.error)return r.stdout;if(r.status===1&&!r.error&&r.stderr.trim()==="")return null;throw this.refused(r)}async create(t,r){if(sl(t),pk(r),await this.lookup(t)!==null)throw new Error("custody_handle_exists");let n=await this.#e(RQ,["store","--label=Visa CLI agent key",...this.attributes(t)],Buffer.from(r).toString("base64"),1e4);if(n.status!==0||n.error)throw this.refused(n)}async read(t){sl(t);let r=await this.lookup(t);if(r===null)throw new Error("custody_unavailable");let n=r.trim(),o=/^[A-Za-z0-9+/]+={0,2}$/.test(n)?Buffer.from(n,"base64"):null;if(!o||o.toString("base64")!==n||o.length>wS)throw new Error("custody_record_invalid");return o}async delete(t){sl(t);let r=await this.#e(RQ,["clear",...this.attributes(t)],"",1e4);if(!(r.status===1&&!r.error&&r.stderr.trim()==="")&&(r.status!==0||r.error))throw this.refused(r)}};function _Ne(e){if(!(0,Bt.existsSync)(e)){(0,Bt.mkdirSync)(e,{recursive:!0,mode:448}),process.platform!=="win32"&&(0,Bt.chmodSync)(e,448);return}let t=(0,Bt.lstatSync)(e);if(!t.isDirectory())throw new Error("custody_directory_invalid");if(process.platform!=="win32"&&(t.mode&63)!==0)throw new Error("custody_directory_not_private")}function mNe(e,t){let r;try{r=(0,Bt.openSync)(e,"wx",384)}catch(o){throw o.code==="EEXIST"?new Error("custody_handle_exists"):new Error("custody_create_failed")}let n=0;try{for(;n<t.length;)n+=(0,Bt.writeSync)(r,t,n)}catch{throw(0,Bt.closeSync)(r),(0,Bt.rmSync)(e,{force:!0}),new Error("custody_create_failed")}(0,Bt.closeSync)(r)}function fNe(e){return new Error(e?.code==="ENOENT"?"custody_unavailable":"custody_store_unreadable")}function gNe(e){let t;try{t=(0,Bt.lstatSync)(e)}catch(r){throw fNe(r)}if(!t.isFile()||t.size>wS*2)throw new Error("custody_file_invalid");try{return(0,Bt.readFileSync)(e)}catch(r){throw fNe(r)}}var CQ=class{constructor(t){this.directory=t}directory;path(t){return sl(t),(0,fk.join)(this.directory,`${t}.key`)}async create(t,r){let n=this.path(t);pk(r),_Ne(this.directory),mNe(n,r)}async read(t){let r=this.path(t);if(process.platform!=="win32"&&(0,Bt.existsSync)(this.directory)){let o=(0,Bt.lstatSync)(this.directory);if(!o.isDirectory()||(o.mode&63)!==0)throw new Error("custody_directory_not_private")}let n=gNe(r);if(process.platform!=="win32"&&((0,Bt.lstatSync)(r).mode&63)!==0)throw new Error("custody_file_invalid");if(n.length===0||n.length>wS)throw new Error("custody_file_invalid");return n}async delete(t){(0,Bt.rmSync)(this.path(t),{force:!0})}},U7t="powershell.exe";function j7t(e,t){return sl(t),["$ErrorActionPreference = 'Stop'","Add-Type -AssemblyName System.Security","$payload = [Convert]::FromBase64String([Console]::In.ReadToEnd().Trim())",`$entropy = [Text.Encoding]::UTF8.GetBytes('visa-agent-key:${t}')`,`$result = [System.Security.Cryptography.ProtectedData]::${e}($payload, $entropy, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)`,"[Console]::Out.Write([Convert]::ToBase64String($result))"].join("; ")}var xQ=class{constructor(t,r={}){this.directory=t;this.#e=r.run??MQ}directory;#e;path(t){return sl(t),(0,fk.join)(this.directory,`${t}.dpapi`)}async call(t,r,n){let o=await this.#e(U7t,["-NoProfile","-NonInteractive","-Command",j7t(t,r)],Buffer.from(n).toString("base64"),3e4),i=o.stdout.trim();if(o.status!==0||o.error||!/^[A-Za-z0-9+/]+={0,2}$/.test(i))throw new Error("dpapi_locked_or_unavailable");return Buffer.from(i,"base64")}async create(t,r){let n=this.path(t);if(pk(r),_Ne(this.directory),(0,Bt.existsSync)(n))throw new Error("custody_handle_exists");mNe(n,await this.call("Protect",t,r))}async read(t){let r=gNe(this.path(t)),n=await this.call("Unprotect",t,r);if(n.length===0||n.length>wS)throw new Error("custody_record_invalid");return n}async delete(t){(0,Bt.rmSync)(this.path(t),{force:!0})}};function lk(e=process.env){return(0,fk.join)(Tt(e),"agent-keys")}function hNe(e=process.env,t=process.platform){let r=e.VISA_RUNTIME_CUSTODY_PROFILE??"os";if(r==="headless")return new CQ(lk(e));if(r!=="os")throw new Error("native_runtime_custody_profile_invalid");if(t==="darwin")return new OQ;if(t==="win32")return new xQ(lk(e));if(t==="linux")return new NQ;throw new Error("custody_platform_unsupported")}var _k=new Map;function Vg(e=process.env){let t=`${e.VISA_RUNTIME_CUSTODY_PROFILE??"os"}\0${lk(e)}`,r=_k.get(t);return r||(r=new ak(hNe(e)),_k.set(t,r)),r}function B7t(){for(let e of _k.values())e.close();_k.clear()}process.once("exit",B7t);var WI=require("node:crypto");td();Ms();var LQ=new Set(["retired","revoked"]);async function ENe(e){let{binding:t,signer:r,api:n,env:o}=e,i=Qa(t.agentId,o);if(i&&!i.revoked)return"connected";let s=Hg({agentId:t.agentId,env:o});if(!s)return"pending";try{let a=await r.create({profile:"identity-tap-v1",associationId:t.associationId,agentId:t.agentId,rootJkt:t.rootJkt,purpose:"tap"}),c=IS(t.agentId,o),u=async f=>ZD(f,o),d=c&&c.runtimeKey.handle===a.handle?c:await SQ({api:n,native:r,key:a,agentId:t.agentId,associationId:t.associationId,expectedRootJkt:t.rootJkt,persist:u}),l=async()=>(d={...d,handoffId:(0,WI.randomUUID)()},await u(d),await tl(n,r,d,"create"),"pending"),p;try{p=await JD(n,r,d)}catch(f){if(f instanceof Tr&&f.code==="device_handoff_expired")return l();throw f}return p.status==="active"?(await VI({pending:d,view:p,native:r,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:o}),"connected"):LQ.has(p.status)?"stopped":p.status==="expired"||p.status==="cancelled"?l():"pending"}finally{s()}}async function yNe(e){let{binding:t,native:r,api:n,env:o}=e,i=Qa(t.agentId,o);if(i&&!i.revoked)return"connected";let s=IS(t.agentId,o);if(!s||s.runtimeKey.binding.profile!=="identity-tap-v1"||s.proposal.associationId!==t.associationId||s.proposal.rootJkt!==t.rootJkt)return"absent";let a=Hg({agentId:t.agentId,env:o});if(!a)return"pending";try{let c=async()=>{let d={...s,handoffId:(0,WI.randomUUID)()};return ZD(d,o),await tl(n,r,d,"create"),"pending"},u;try{u=await JD(n,r,s)}catch(d){if(d instanceof Tr&&d.code==="device_handoff_expired")return c();throw d}return u.status==="active"?(await VI({pending:s,view:u,native:r,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:o}),"connected"):LQ.has(u.status)?"stopped":u.status==="expired"||u.status==="cancelled"?c():"pending"}finally{a()}}var H7t=720*60*60;function q7t(e){if(typeof e!="string"||e.split(".").length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(".")[1],"base64url").toString("utf8")).exp;return Number.isSafeInteger(t)?t:null}catch{return null}}function YI(e,t,r=Math.floor(Date.now()/1e3)){let n;try{n=Qa(e,t)}catch{return"missing"}if(!n||n.revoked||n.runtimeKey.binding.profile!=="identity-tap-v1")return"missing";let o=[n.active.delegation,n.active.gateAuthorization].map(q7t);if(o.some(s=>s===null))return"missing";let i=Math.min(...o);return i<=r?"expired":i-r<H7t?"renew_due":"live"}async function V7t(e){let{binding:t,native:r,api:n,env:o}=e,i;try{i=Qa(t.agentId,o)}catch{return!1}if(!i||i.revoked||i.runtimeKey.binding.profile!=="identity-tap-v1")return!1;let s=await tl(n,r,i,"read"),a=Number(i.active.challenge?.generation??0);return s.status!=="active"||!(Number(s.challenge?.generation??0)>a)?!1:(await VI({pending:i,view:s,native:r,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:o,collectedRenewal:!0}),Me.info("identity_device_tap_renewal_collected",{agentId:t.agentId,generation:s.challenge?.generation}),!0)}async function DQ(e){let{binding:t,native:r,api:n,env:o}=e,i=YI(t.agentId,o,e.nowSec);if(i==="live")return{state:"connected"};if(i!=="missing")return await V7t({binding:t,native:r,api:n,env:o})?{state:"renewed"}:{state:"owner_renews"};let s=Hg({agentId:t.agentId,env:o});if(!s){let a=IS(t.agentId,o);return a?{state:"pending",pending:a}:{state:"connected"}}try{let a=IS(t.agentId,o),c=async l=>ZD(l,o),u=a&&a.runtimeKey.binding.profile==="identity-tap-v1"&&a.proposal.associationId===t.associationId&&a.proposal.rootJkt===t.rootJkt?a:null;if(!u){let l=await r.create({profile:"identity-tap-v1",associationId:t.associationId,agentId:t.agentId,rootJkt:t.rootJkt,purpose:"tap"});return u=await SQ({api:n,native:r,key:l,agentId:t.agentId,associationId:t.associationId,expectedRootJkt:t.rootJkt,persist:c}),Me.info("identity_device_tap_key_proposed",{agentId:t.agentId}),{state:"pending",pending:u}}let d;try{d=await JD(n,r,u)}catch(l){if(!(l instanceof Tr)||l.code!=="device_handoff_expired")throw l;return u={...u,handoffId:(0,WI.randomUUID)()},await c(u),await tl(n,r,u,"create"),{state:"pending",pending:u}}return d.status==="active"?(await VI({pending:u,view:d,native:r,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:o}),Me.info("identity_device_tap_connected",{agentId:t.agentId}),{state:"connected"}):LQ.has(d.status)?{state:"stopped"}:((d.status==="expired"||d.status==="cancelled")&&(u={...u,handoffId:(0,WI.randomUUID)()},await c(u),await tl(n,r,u,"create")),{state:"pending",pending:u})}finally{s()}}function SNe(e,t){try{let r=IS(e,t);if(!r||r.runtimeKey.binding.profile!=="identity-tap-v1")return!1;let n;try{n=Qa(e,t)}catch{n=null}return r.handoffId!==n?.handoffId}catch{return!1}}td();B_();OB();QT();tO();var TNe="5.0.0-rc.402",F7t=["association","handoff","lease","tap-sign"],bNe=262144,G7t=2e4;function RS(e={}){let t=(e.origin??Yl()).replace(/\/+$/,""),r=e.fetch;return{async identityDeviceRequest(n,o){if(!F7t.includes(n))throw new Error("identity_device_action_invalid");let i=JSON.stringify(o);if(Buffer.byteLength(i)>bNe)throw new Error("identity_device_request_too_large");let s=`${t}/v1/identity-device/${n}`,a={method:"POST",headers:{"Content-Type":"application/json","X-Visa-CLI-Version":TNe,"X-Source":"cli",...Xh()},body:i},c;try{c=await(r??fetch)(s,{...a,signal:AbortSignal.timeout(G7t)})}catch(l){throw new Error(YR(l))}let u;try{let l=Buffer.from(await c.arrayBuffer());if(l.byteLength>bNe)throw new Error("response_too_large");u=JSON.parse(l.toString("utf8"))}catch{u=void 0}let d=QR(c.status,u,TNe);if(d)throw d;if(typeof u?.ok!="boolean")throw new Tr(`Identity device relay returned an invalid response for ${n} (${c.status}).`,c.status,"identity_device_response_invalid",void 0,!1);if(!c.ok||u.ok!==!0){let l=typeof u.code=="string"?u.code:void 0,p=typeof u.retryable=="boolean"?u.retryable:void 0;throw new Tr(`Identity device ${n} refused (${c.status}${l?` ${l}`:""}).`,c.status,l,void 0,p)}return u}}}var vNe=require("node:child_process"),INe=j(require("node:os")),$7t=64,K7t={platform:process.platform,computerName:()=>{try{return(0,vNe.execFileSync)("scutil",["--get","ComputerName"],{encoding:"utf8",timeout:1e3,stdio:["ignore","pipe","ignore"]})}catch{return null}},hostname:()=>INe.default.hostname()};function PNe(e=K7t){let t=e.platform==="darwin"?[e.computerName(),ANe(e)]:[ANe(e)];for(let r of t){let n=W7t(r);if(n)return n}return null}function ANe(e){try{return e.hostname().replace(/\.local\.?$/i,"")}catch{return null}}function W7t(e){if(typeof e!="string")return null;let t=e.normalize("NFC").replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu," ").replace(/\s+/gu," ").trim();return t&&Array.from(t).slice(0,$7t).join("").trim()||null}td();Vl();Bh();Ms();vc();var wNe=require("node:crypto");var I9r=30*1e3,Y7t=new Map;function J7t(){Y7t.clear()}function z7t(e){let t=V1e(e.homeDir),r=t?.financialDeviceRuntimeId;if(!t||t.agentId!==e.agentId||!r)return null;let n=Lg(e.agentId,e.env);if(!n||n.runtimeKey.runtimeId!==r)return null;let o=D1e(t,e.env),i=o?pu(o):e.api;return{runtimeId:r,active:n,api:i}}async function X7t(e,t,r){return await e.financialRuntimeRequest("tempo-context",{requestId:(0,wNe.randomUUID)(),agentId:t,runtimeId:r})}function kQ(e){let t=e?.code;return t==="agent_revoked"||t==="device_key_replaced"}async function mk(e){let t;try{t=z7t(e)}catch{return"unknown"}if(!t)return"unknown";let r;try{r=await X7t(t.api,e.agentId,t.runtimeId)}catch(n){if(kQ(n))throw n;return"unknown"}return r?.v!==1||typeof r.enrolled!="boolean"?"unknown":r.available===!1?"switched_off":(r.enrolled&&J7t(),r.enrolled?"enrolled":"setup_pending")}var UQ={begin:async(e,t,r)=>{let n=nd(r),o=eE(Date.now(),n);o&&o.verifier===t&&!o.likelyExpired||await sO(e,Date.now(),n,{verifier:t})},claim:(e,t)=>tE(e,{loginDir:nd(t),attempts:1}),revert:async(e=process.env)=>{let t=wn(e);if(t)try{await ct.deleteProfileSessionToken(t,e)}finally{hR(t.profileId,e)}}};async function RNe(e=process.env,t=cO){try{if(_Q(e).length!==0)return null}catch{return null}let r=Qo(ka(e));try{let o=Ep(e);if(o&&AS(o))return{baseUrl:r}}catch{}let n=await t(r);return n.ready&&n.features.includes(Tde)?{baseUrl:r}:null}var ONe={start:N1e,claim:L1e,bindApi:pu,custody:Vg,beginDevice:LI,advanceDevice:SS,connectDevice:W1e,finishDevice:Y1e,beginCard:oNe,advanceCard:GI,advanceTap:ENe,identityDevice:RS,walletHomeForAgent:vS,walletStateRoot:_u,claimApp:(e,t,r)=>new Ls(()=>ct.getSessionToken()).claimAgentForApp(e,t,r),deviceName:()=>PNe(),tempoKey:mk,sleep:e=>new Promise(t=>setTimeout(t,e)),now:()=>Date.now(),signIn:UQ,announceCode:e=>C1e(e)},Z7t=new Set(["identity_authority_not_configured"]);function jQ(e){return e instanceof lu?!0:e instanceof Yi?!(e.code!==null&&Z7t.has(e.code))&&(e.status>=500||e.status===429):jI(e)==="ProtectedAuthorityTransportError"}var Q7t=12e4,ezt=12e4,tzt=3,BQ=1e3,rzt=15e3,nzt=1800*1e3;function ozt(e){return Math.min(BQ*2**Math.max(0,e-1),rzt)}function HQ(e){if(!/^\d+(?:\.\d{1,2})?$/.test(e))throw new Error("Limits must be positive dollar amounts with at most two decimal places");let t=Math.round(Number(e)*100);if(!Number.isSafeInteger(t)||t<=0)throw new Error("Limits must be positive dollar amounts");return t}async function izt(e,t,r){let n=t.app??pQ(t.env);if(!n)return;let o=null;try{o=e.deviceName?e.deviceName():null}catch{o=null}try{let i=await e.claimApp(r,n,o);Me.info("agent:protected_enrollment_app_stamped",{agentId:r,harnessId:n,claimed:i.claimed,deviceReported:o!==null})}catch(i){Me.warn("agent:protected_enrollment_app_stamp_failed",{agentId:r,harnessId:n,error:i instanceof Error?i.message:"request refused"})}}async function szt(e,t=ONe){if(!Number.isSafeInteger(e.attempts)||e.attempts<1||e.attempts>900)throw new Error("Attempts must be between 1 and 900");let r=t.start({webOrigin:e.webOrigin,restart:e.restart,env:e.env,...e.webStartKey!==void 0?{webStartKey:e.webStartKey}:{},...e.signIn?{signIn:!0}:{}});await R1e(r,t.custody(e.env),e.env);let n=e.signIn&&AS(r)?e.signIn:null,o=n?t.signIn??UQ:null;n&&o&&await o.begin(n.baseUrl,r.verifier,e.env),await t.announceCode?.(r);let i=x1e(r,e.app??pQ(e.env)),s=od(r.verifier);r.binding||await e.announce({kind:"owner_enrollment",url:i,confirmCode:s});let a=null,c=0,u=null,d=t.now??(()=>Date.now()),l=d();for(let p=0;p<e.attempts;p++){if(d()-l>=nzt){Me.warn("agent:protected_enrollment_pickup_deadline",{attempt:p+1,waitedMs:d()-l});break}p>0&&await t.sleep(c>0?ozt(c):BQ);try{if(n&&o&&AS(r)){let f=await o.claim(n.baseUrl,e.env);if(f.status==="confirm_mismatch")throw new Error("The code entered in the browser does not match this terminal, so it was not signed in. Run `visa connect --restart` and enter the code this terminal shows.");if(f.status==="error")throw new lu("Visa sign-in","network",0);if(f.status!=="claimed"||!fQ(r,e.env))continue}try{a=await t.claim(r,e.env)}catch(f){if(r.signIn===!0&&f instanceof Xt&&f.code==="enrollment_owner_mismatch")try{await(t.signIn??UQ).revert(e.env)}catch(m){Me.warn("agent:protected_enrollment_sign_in_revert_failed",{reason:m instanceof Error?m.name:typeof m})}throw f}}catch(f){if(!jQ(f))throw f;c++,u=f,Me.warn("agent:protected_enrollment_pickup_retry",{attempt:p+1,consecutiveFailures:c,status:f instanceof Yi?f.status:null,reason:f instanceof lu?f.reason:null});continue}if(c=0,u=null,a)break}return a?{status:"identity_active",pending:r,binding:a,enrollmentUrl:i}:{status:"awaiting_owner_enrollment",browserUrl:i,confirmCode:s,...u?{lastPickupFailure:u instanceof Error?u.message:"Authority unavailable"}:{}}}async function NNe(e,t=ONe){if(e.perTransactionLimitCents>e.dailyLimitCents)throw new Xt("Per-purchase limit exceeds daily limit","invalid_argument");if(!Number.isSafeInteger(e.attempts)||e.attempts<1||e.attempts>900)throw new Xt("Attempts must be between 1 and 900","invalid_argument");let r=await szt(e,t);if(r.status!=="identity_active")return r;let{pending:n,binding:o,enrollmentUrl:i}=r,s={v:1,authorityOrigin:n.authorityOrigin,executionOrigin:n.executionOrigin,transportProfileId:n.transportProfileId,binding:o},a=t.bindApi(s),c=b1e(t.custody(e.env),n.deviceKeys),u={api:a,signer:c,selection:s,env:e.env,ceremony:{ceremonyId:o.ceremonyId,challenge:n.challenge,verifier:n.verifier}},d=t.identityDevice({origin:n.executionOrigin}),l="pending",p,f,m=!1,h=async()=>{if(!(l==="connected"||l==="stopped"||m))try{l=await t.advanceTap({binding:o,signer:c,api:d,env:e.env}),p=void 0,f=void 0}catch(k){l="failed",m=!jQ(k),p=k instanceof Error?k.message:"TAP connection refused",f=Ac(k),Me.warn("agent:protected_enrollment_tap_pending",{agentId:o.agentId,errorName:jI(k),code:f.code,...k instanceof Yi?{status:k.status}:{}})}},E=await t.beginCard({...u,initialConnection:!0});await h();let b=async()=>{try{return(await t.advanceCard(u)).status==="active"}catch(k){if(!jQ(k))throw k;return Me.warn("agent:protected_card_connection_pending",{agentId:o.agentId,errorName:jI(k),...k instanceof Yi?{status:k.status}:{}}),!1}},A=()=>t.walletHomeForAgent(o.agentId,t.walletStateRoot(e.env),o.ownerPublicId),S=async k=>t.tempoKey?t.tempoKey({api:a,agentId:o.agentId,homeDir:k,env:e.env}):"enrolled",T=async k=>(k!=="enrolled"&&Me.warn("agent:protected_enrollment_wallet_key_owed",{agentId:o.agentId,walletKey:k}),Me.info("agent:protected_enrollment_connected",{agentId:o.agentId,tap:l,walletKey:k,wait:e.wait}),await izt(t,e,o.agentId),{status:"connected",agentId:o.agentId,tap:l,...l==="failed"&&p?{tapError:p}:{},...l==="failed"&&f?{tapDiagnostic:f}:{},walletKey:k});if(!e.wait){let k=await t.beginDevice({api:a,signer:c,agentId:o.agentId,ownerPublicId:o.ownerPublicId,cardProposal:E.proposal,ceremony:{ceremonyId:o.ceremonyId,challenge:n.challenge,verifier:n.verifier},env:e.env}),H=await t.advanceDevice({api:a,signer:c,pending:k,env:e.env}),B=k.cardProposal?await b():!0;await h();let q=l==="failed"?{tap:l,tapError:p,tapDiagnostic:f}:{};if(!(H?.prepared?.status==="active"||!!H?.evidence?.owner_signatures))return{status:"awaiting_owner_device_approval",browserUrl:i,agentId:o.agentId,...q};let G=A();return B&&await t.finishDevice({api:a,signer:c,agentId:o.agentId,ownerPublicId:o.ownerPublicId,agentName:"Protected agent",authUrl:n.authorityOrigin,walletHomeDir:G,pending:k,view:H,env:e.env})?T(await S(G)):(Me.info("agent:protected_enrollment_device_finishing",{agentId:o.agentId,active:H?.prepared?.status==="active",companionReady:B}),{status:"finishing_device_setup",browserUrl:i,agentId:o.agentId,...q})}let v=A();await t.connectDevice({api:a,signer:c,agentId:o.agentId,ownerPublicId:o.ownerPublicId,cardProposal:E.proposal,advanceCompanion:b,advanceTap:async()=>{l==="failed"&&!m&&(l="pending"),await h()},ceremony:{ceremonyId:o.ceremonyId,challenge:n.challenge,verifier:n.verifier},agentName:"Protected agent",authUrl:n.authorityOrigin,walletHomeDir:v,env:e.env});let I=t.now??(()=>Date.now()),w=I()+Q7t,N=I()+ezt,L=await S(v),x=()=>(l==="pending"||l==="failed")&&!m,D=()=>L==="setup_pending"||L==="unknown";for(let k=1;;k++){let H=x()&&I()<w,B=D()&&I()<N;if(!H&&!B)break;await t.sleep(BQ),H&&(l==="failed"&&(l="pending"),await h()),B&&k%tzt===0&&(L=await S(v))}return T(L)}var Fg=require("node:fs"),OS=require("node:path"),DNe=require("node:crypto");jl();Xo();var MNe=require("node:crypto");var CNe=require("node:path");Xo();function azt(e,t){return Qa(e,t),(0,CNe.join)(Tt(t),"financial-device-presence",`${e}.revocation.json`)}function gk(e,t){let r=ss(azt(e,t));if(r===null)return null;On(r);let n=JSON.parse(r);if(n.v!==1||n.selected?.proposal.agentId!==e||!Array.isArray(n.keys)||!n.keys.length||!["awaiting_owner","revocation_verified","complete"].includes(n.phase)||n.keys.some(({record:i})=>i.proposal.agentId!==e||i.proposal.runtimeId!==n.selected.proposal.runtimeId||i.proposal.associationId!==n.selected.proposal.associationId))throw new Error("identity_device_revocation_invalid");if(Qa(e,t)?.handoffId!==n.selected.handoffId){if(n.phase==="complete")return null;throw new Error("identity_device_selection_changed")}return n}var xNe=e=>e instanceof Error&&e.message?e.message:String(e);function al(e,t){try{let r=gk(e,t);if(r&&r.phase!=="complete"&&TQ(r.selected))return{state:"revoking"};let n=Qa(e,t);if(n?.revoked&&TQ(n))return{state:"revoked"}}catch(r){return{state:"unreadable",detail:`presence: ${xNe(r)}`}}try{let r=Lg(e,t);if(r)return{state:"installed",runtimeId:r.runtimeKey.runtimeId,record:r};let n=yS(e,t);if(n)return{state:"wallet_setup_pending",runtimeId:n.runtimeKey.runtimeId}}catch(r){return{state:"unreadable",detail:xNe(r)}}return{state:"missing"}}function czt(e){let t=e?.deviceWalletAuthority;return t==="live"||t==="expired"||t==="absent"?t:"unreachable"}async function LNe(e,t=(r,n)=>pu(e).financialRuntimeRequest(r,n)){try{return czt(await t("device-context",{requestId:(0,MNe.randomUUID)(),agentId:e.binding.agentId}))}catch(r){if(qQ(r)||kQ(r))throw r;return"unreachable"}}function qQ(e){return e instanceof Error&&/independently claimed owner/.test(e.message)}td();Ms();var uzt=["revoked","key_not_held","replaced","superseded"],VQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function JI(e){let t=(0,OS.join)(Tt(e),"protected-enrollment","retired");return(0,Fg.mkdirSync)(t,{recursive:!0,mode:448}),So(t),t}function FQ(e,t,r,n=()=>new Date){if(!VQ.test(e))throw new Error("retired_agent_id_invalid");let o=(0,OS.join)(JI(r),`${e}.json`),i=kNe(o);if(i)return i;let s={v:1,agentId:e,reason:t,retiredAt:n().toISOString()};return Pn(o,JSON.stringify(s)),s}function kNe(e){let t=To(e);if(t===null)return null;let r=JSON.parse(t);if(r?.v!==1||!VQ.test(r.agentId)||!uzt.includes(r.reason)||typeof r.retiredAt!="string")throw new Error("retired_agent_record_invalid");return r}function UNe(e){let t=new Map,r;try{r=(0,Fg.readdirSync)(JI(e))}catch{return t}for(let n of r)if(!(!n.endsWith(".json")||!VQ.test(n.slice(0,-5))))try{let o=kNe((0,OS.join)(JI(e),n));o&&`${o.agentId}.json`===n&&t.set(o.agentId,o)}catch{}return t}function zI(e){let t=UNe(e);return Ug(e).filter(r=>!t.has(r.binding.agentId))}async function jNe(e,t){let r=e.binding.agentId,n=[],o=null,i=al(r,t.env);i.state==="installed"&&(n.push(i.record.runtimeKey.handle),o=i.record.runtimeKey.runtimeId);try{let s=qg(e,t.env);s?.certificate&&n.push(s.runtimeKey.handle)}catch{}if(n.length>0&&(await Promise.all(n.map(a=>t.holds(a)))).every(a=>a==="missing")&&Me.warn("agent:held_agent_keys_not_in_this_store",{agentId:r}),o)try{await t.api(e).financialRuntimeRequest("tempo-context",{requestId:(0,DNe.randomUUID)(),agentId:r,runtimeId:o})}catch(s){if(s instanceof Yi&&s.code==="agent_revoked")return{agentId:r,verdict:"retire",reason:"revoked"};if(s instanceof Yi&&s.code==="device_key_replaced")return{agentId:r,verdict:"retire",reason:"replaced"}}if((t.resumable??hk)(e,t.env))return{agentId:r,verdict:"usable"};try{if(await t.association?.(e)==="revoked")return{agentId:r,verdict:"retire",reason:"revoked"}}catch{}return{agentId:r,verdict:"usable"}}async function dzt(e){let t=[],r,n;try{r=UNe(e.env),n=Ug(e.env)}catch{return t}for(let o of n){let i=o.binding.agentId;if(r.get(i)?.reason==="key_not_held")try{if((await jNe(o,e)).verdict==="retire"){(0,Fg.rmSync)((0,OS.join)(JI(e.env),`${i}.json`),{force:!0}),FQ(i,"revoked",e.env);continue}(0,Fg.rmSync)((0,OS.join)(JI(e.env),`${i}.json`),{force:!0}),Me.info("agent:held_agent_restored",{agentId:i}),t.push(i)}catch(s){Me.warn("agent:held_agent_restore_failed",{agentId:i,error:s instanceof Error?s.message:String(s)})}}return t}async function BNe(e){let t;try{t=zI(e.env)}catch{return[]}await dzt(e);try{t=zI(e.env)}catch{return[]}let r=[];for(let n of t)try{let o=await jNe(n,e);if(o.verdict!=="retire")continue;let i=FQ(o.agentId,o.reason,e.env);Me.warn("agent:held_agent_retired",{agentId:i.agentId,reason:i.reason}),r.push(i)}catch(o){Me.warn("agent:held_agent_judge_failed",{agentId:n.binding.agentId,error:o instanceof Error?o.message:String(o)})}return r}function GQ(e){return e.reason==="revoked"?`Agent ${e.agentId} was revoked, so it can no longer pay; connecting a new agent`:e.reason==="replaced"?`Agent ${e.agentId} now runs on another computer that replaced its keys, so this one can no longer pay for it; connecting a new agent`:e.reason==="superseded"?`Agent ${e.agentId} was an earlier setup on this computer that never finished; a later setup replaced it, so it is set aside (its records are kept)`:`Agent ${e.agentId} was set up by an older Visa CLI whose keys this version cannot use; connecting a new agent`}function $Q(e){let t;try{t=zI(e)}catch{return[]}let r=new Map(t.map(o=>{try{return[o.binding.agentId,KQ(o,e)]}catch{return[o.binding.agentId,null]}}));if(![...r.values()].includes("installed"))return[];let n=[];for(let o of t){let i=o.binding.agentId;if(r.get(i)!=="unfinished"||hk(o,e))continue;let s=al(i,e);if(s.state!=="wallet_setup_pending"&&s.state!=="missing"){s.state==="unreadable"&&Me.warn("agent:held_agent_setup_unreadable",{agentId:i,detail:s.detail});continue}try{if(qg(o,e)?.certificate)continue}catch{Me.warn("agent:held_agent_setup_unreadable",{agentId:i,detail:"card record"});continue}try{let a=FQ(i,"superseded",e);Me.warn("agent:held_agent_retired",{agentId:i,reason:a.reason}),n.push(a)}catch(a){Me.warn("agent:held_agent_retire_failed",{agentId:i,error:a instanceof Error?a.message:String(a)})}}return n}async function HNe(e){try{return await RS({origin:e.executionOrigin}).identityDeviceRequest("association",{agentId:e.binding.agentId}),"active"}catch(t){return t instanceof Tr&&(t.code==="association_inactive"||t.code==="agent_revoked")?"revoked":"unknown"}}function KQ(e,t){if(al(e.binding.agentId,t).state!=="installed")return"unfinished";try{let r=qg(e,t);if(r&&!r.certificate)return"unfinished"}catch{}return"installed"}function hk(e,t){let r;try{r=Ep(t)}catch{return!1}return!!(r?.binding&&r.binding.agentId===e.binding.agentId&&r.binding.associationId===e.binding.associationId&&Date.now()-r.createdAt<UI)}async function qNe(e,t,r){let n=[],o=al(e.binding.agentId,r);o.state==="installed"&&n.push(o.record.runtimeKey.handle);try{let s=qg(e,r);s?.certificate&&n.push(s.runtimeKey.handle)}catch{}return n.length===0?"readable":(await Promise.all(n.map(s=>t(s).catch(()=>"unknown")))).every(s=>s==="missing")?"unreadable":"readable"}vc();Vl();td();var lzt=new Set(["registered","removal_pending","pending","blocked","not_requested","deactivated","contact_required","unavailable"]);function fzt(e){return typeof e=="string"&&lzt.has(e)?e:"unknown"}function pzt(e,t,r){return{key:YI(e,r),directory:fzt(t?.find(n=>n.agentId===e)?.tapStatus)}}async function VNe(e,t,r){let n=null;try{n=await t()}catch{n=null}return pzt(e,n,r)}function FNe(e){return VNe(e,()=>new Ls(()=>ct.getSessionToken()).listAccountAgents())}async function _zt(e){try{if(await ct.getSessionToken())return"already"}catch{}try{let t=eE();if(!t||t.likelyExpired||e===!0)return null;let r=Qo(ka());return(await tE(r,{attempts:1})).status==="claimed"?"claimed":null}catch{return null}}var GNe=e=>e==="setup_pending"?"finish_wallet_key":e==="switched_off"?"wallet_switched_off":e==="unknown"?"confirm_wallet_key":"none";async function mzt(e){try{return await mk({api:pu(e),agentId:e.binding.agentId,homeDir:vS(e.binding.agentId,_u(),e.binding.ownerPublicId)})}catch{return"unknown"}}async function gzt(e){let t=e.binding,r=al(t.agentId);if(r.state==="installed"){try{await LNe(e)}catch(s){if(qQ(s))throw s}let i=r.record;if(i.ownerPublicId!==t.ownerPublicId||i.organizationId!==t.organizationId||i.proposal.associationId!==t.associationId||i.proposal.associationVersion!==t.associationVersion||i.proposal.rootJkt!==t.rootJkt||i.rootKid!==t.rootKid)throw new Error("Protected wallet installation differs from its independently claimed owner");return}let n;try{n=yS(t.agentId)}catch{return}if(!n)return;let o=Ep();if(o?.binding?.agentId!==t.agentId||o.binding.ceremonyId!==t.ceremonyId||o.executionOrigin!==e.executionOrigin||o.authorityOrigin!==e.authorityOrigin||Date.now()-o.createdAt>=UI||n.ceremony.ceremonyId!==o.ceremonyId||n.ceremony.challenge!==o.challenge||n.ceremony.verifier!==o.verifier||n.proposal.associationId!==t.associationId||n.proposal.associationVersion!==t.associationVersion||n.proposal.rootJkt!==t.rootJkt)throw new Error("Existing wallet setup cannot resume this identity; call get_status before restarting enrollment")}async function hzt(e,t,r){let n=e.binding.agentId,o=al(n).state,i=o==="revoking"||o==="revoked";try{let a=gk(n);i||=!!(a&&a.phase!=="complete")}catch{}if(i)return{state:"revoking"};let s={binding:e.binding,native:Vg(),api:RS({origin:e.executionOrigin})};try{let a=await yNe(s);if(a==="stopped")return{state:"stopped"};let c=a==="pending";if(!c)try{c=SNe(n)||YI(n)!=="live"}catch{c=!0}if(!c)return{state:"live"};let u=Date.now()+Math.max(1,r)*1e3,d=await DQ(s);for(;d.state==="pending"&&t&&Date.now()<u;)await new Promise(l=>setTimeout(l,1e3)),d=await DQ(s);return d.state!=="pending"?{state:d.state}:{state:"awaiting_owner",url:X1e(aO(ka()),d.pending),fingerprint:d.pending.proposal.runtimeJkt}}catch(a){return{state:"failed",error:a}}}async function Ezt(e,t,r){let n=await vQ(e);if(!t||!n.renew)return{card:{state:"untouched"},cardKey:n.state};try{let o={api:pu(e),signer:Vg(),selection:e,renewWithinSeconds:nk},i=await GI(o);return i.status==="retry"&&(i=await GI(o)),i.status==="active"?{card:{state:"renewed"},cardKey:(await vQ(e)).state}:i.status==="awaiting_owner"?{card:{state:"awaiting_owner",url:rNe(ka({...process.env,VISA_AUTH_URL:e.authorityOrigin}),{proposal:i.proposal},r)},cardKey:"renewing"}:{card:{state:"busy"},cardKey:"renewing"}}catch(o){return{card:{state:"failed",error:o},cardKey:n.state}}}function WQ(e){if(e!==void 0&&!w1e.test(e))throw new Xt("That setup key is not one Visa issued. Copy the whole `visa connect --setup` line from the page that started the setup.","invalid_argument")}async function $Ne(e){WQ(e.webStartKey);let t=[],r=[],n=await _zt(e.restart);n==="already"&&e.verifySession&&await e.verifySession()===!1&&(n=null);let o=n?null:await RNe();if(o&&(n="one_code"),!n){let l=await e.signIn();if(!l.done)return{leg:"signin",pending:l.pending,signIn:"pending",retired:t,superseded:r,nextAction:"sign_in"};n="interactive"}let i={signIn:n,retired:t,superseded:r},s=null;if(!e.restart){t.push(...await BNe({holds:async p=>Vg().holds(p),api:p=>pu(p),association:HNe}),...$Q());let l=e.webStartKey===void 0?zI()[0]:void 0;if(l){let p=l.binding.agentId;if(await gzt(l),KQ(l)==="unfinished"){if(!hk(l))return{...i,leg:"unfinished_expired",agentId:p,nextAction:"restart_to_replace"};s=p}else{if(await qNe(l,async f=>Vg().holds(f))==="unreadable")return{...i,leg:"unreadable_keys",agentId:p,nextAction:"restart_new_agent"};{let f=await hzt(l,e.tapWait,e.attempts),m=f.state==="awaiting_owner"?null:await mzt(l),h;try{h=al(p).state!=="missing"}catch{h=!0}let E=GNe(m),b=E!=="none"&&(h||E!=="confirm_wallet_key"),A=f.state==="awaiting_owner"?"approve_device":f.state==="failed"?Ac(f.error).code==="update_required"?"update_cli":"retry_tap":b?E:f.state==="owner_renews"?"owner_renews_tap":"none",{card:S,cardKey:T}=await Ezt(l,A==="none",e.app),v=A!=="none"?A:S.state==="awaiting_owner"?"approve_card":S.state==="failed"||S.state==="busy"?"retry_card":E;return{...i,leg:"held",agentId:p,tap:f,walletKey:m,tapStatus:await FNe(p),card:S,cardKey:T,nextAction:v}}}}}let a=null,c=await NNe({webOrigin:ka(),...o?{signIn:o}:{},...e.app!==void 0?{app:e.app}:{},restart:e.restart,...e.webStartKey!==void 0?{webStartKey:e.webStartKey}:{},wait:e.wait,attempts:e.attempts,dailyLimitCents:e.dailyLimitCents,perTransactionLimitCents:e.perTransactionLimitCents,announce:async l=>{a=l,await e.announce?.(l,o!==null)}});c.status!=="awaiting_owner_enrollment"&&r.push(...$Q());let u=c.status==="awaiting_owner_enrollment"?"approve":c.status==="awaiting_owner_device_approval"?"approve_device":c.status==="finishing_device_setup"?"finish_device":GNe(c.walletKey),d=c.status==="awaiting_owner_enrollment"?null:await FNe(c.agentId);return{...i,leg:"enroll",resumed:s,result:c,announcement:a,tapStatus:d,nextAction:u}}Vl();Bh();var WNe=require("child_process");B_();function yzt(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.VISA_SUPPRESS_BROWSER==="1"||e.VISA_SUPPRESS_BROWSER==="true"?{headless:!0,reason:"VISA_SUPPRESS_BROWSER is set"}:e.CHECKOUT_SKIP_BROWSER_OPEN==="1"||e.CHECKOUT_SKIP_BROWSER_OPEN==="true"?{headless:!0,reason:"CHECKOUT_SKIP_BROWSER_OPEN is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.JEST_WORKER_ID!==void 0||e.VITEST!==void 0||e.NODE_ENV==="test"?{headless:!0,reason:"test runner 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 Szt(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(`
221
221
  `)}function Tzt(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 bzt(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 KNe(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function YQ(e,t={}){let r=t.log??(u=>console.log(u)),n=t.env??process.env,o=t.platform??process.platform,i=Tzt(e),s=t.spawn??((u,d,l)=>{(0,WNe.execFile)(u,d,p=>l(p))});r(""),r(` ${t.heading??"Sign in to Visa CLI by opening this URL in your browser:"}`),r("");for(let u of Szt(i??e).split(`
222
222
  `))r(` ${u}`);if(r(""),t.suppressed??$ue())return r(" (Browser auto-open is suppressed \u2014 open the URL above to continue.)"),r(""),{opened:!1,reason:"suppressed"};if(!i)return 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(""),{opened:!1,reason:"invalid_url"};let a=yzt(n,o);if(a.headless)return 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(""),{opened:!1,reason:"headless",detail:a.reason};let c=bzt(i,o);return c?new Promise(u=>{let d=l=>{l?(KNe(r,l),u({opened:!1,reason:"launch_failed",detail:l.message})):(r(" Opened browser. Waiting for you to sign in..."),r(""),u({opened:!0}))};try{s(c.cmd,c.args,d)}catch(l){let p=l instanceof Error?l:new Error(String(l));KNe(r,p),u({opened:!1,reason:"launch_failed",detail:p.message})}}):(r(` No known browser-open command for platform "${o}".`),r(" Open the URL above manually to continue."),r(""),{opened:!1,reason:"unsupported_platform",detail:o})}var cl=require("node:fs"),XI=require("node:path");jl();Ms();Xo();var Azt=1440*60*1e3;function YNe(e={}){let t=e.platform??process.platform;vzt(t);let r=(0,XI.resolve)(Tt(e.env),"purchase-deliveries"),n={removed:0,skipped:0};try{if(!So(r,{platform:t}))return n;for(let o of(0,cl.readdirSync)(r,{withFileTypes:!0}))if(/^delivery-[A-Za-z0-9]+$/.test(o.name))try{if(!o.isDirectory()){n.skipped++;continue}let i=(0,XI.join)(r,o.name);if(!So(i,{platform:t}))continue;let s=(0,XI.join)(i,"card.json"),a=Q5(s,{platform:t});if(!a)continue;let c=JSON.parse(a.contents);if(c?.v!==1||c?.card?.kind!=="network_token_cryptogram"||typeof c.purchaseId!="string"){n.skipped++;continue}let u=Date.parse(c.card.cryptogramExpiresAt),d=Math.min(a.mtimeMs+Azt,Number.isFinite(u)?u:1/0);if(!e.all&&(e.now??Date.now())<d)continue;(0,cl.unlinkSync)(s),n.removed++;try{(0,cl.rmdirSync)(i)}catch{}}catch{n.skipped++}try{Me.info("purchase_file_cleanup",n)}catch{}return n}catch{throw new Error("purchase_file_cleanup_failed")}}function vzt(e=process.platform){try{_R(e)}catch{throw new Error("purchase_file_delivery_unavailable")}}function JNe(e=""){process.stdout.write(`${e}
223
223
  `)}function NS(e,t){e==="table"?process.stdout.write(`${t}