@visa/cli 1.9.0-rc.1 → 1.9.1-rc.1

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,8 +1,8 @@
1
- "use strict";var Rr=Object.create;var zt=Object.defineProperty;var Ar=Object.getOwnPropertyDescriptor;var Ir=Object.getOwnPropertyNames;var Lr=Object.getPrototypeOf,Nr=Object.prototype.hasOwnProperty;var Or=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Dr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ir(t))!Nr.call(e,s)&&s!==n&&zt(e,s,{get:()=>t[s],enumerable:!(r=Ar(t,s))||r.enumerable});return e};var h=(e,t,n)=>(n=e!=null?Rr(Lr(e)):{},Dr(t||!e||!e.__esModule?zt(n,"default",{value:e,enumerable:!0}):n,e));var ut=Or((yo,zr)=>{zr.exports={name:"@visa/cli",version:"1.9.0-rc.1",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.0","@typescript-eslint/parser":"^8.59.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var _r=require("commander"),nt=h(require("crypto")),Cr=h(require("fs")),U=h(require("os")),oe=h(require("path")),kr=h(require("readline")),xr=require("child_process"),$r=require("util");var Te=require("child_process"),Yt=require("util"),Q=h(require("fs")),Re=h(require("os")),at=h(require("path")),q=(0,Yt.promisify)(Te.execFile),ct=at.join(Re.homedir(),".visa-mcp"),ge=at.join(ct,"session-token"),H="visa-cli",Z="session-token",Ee="rc-access",Ur=5e3,Pe=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Mr(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
- `)}function Xt(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Mr(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function jr(){try{let{stdout:e}=await q("security",["find-generic-password","-s",H,"-a",Z,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Xt(e))throw new Pe("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 Hr(e){try{try{await q("security",["delete-generic-password","-s",H,"-a",Z],{timeout:5e3})}catch{}return await q("security",["add-generic-password","-s",H,"-a",Z,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Vr(){try{await q("security",["delete-generic-password","-s",H,"-a",Z],{timeout:5e3})}catch{}}async function Fr(){if(!lt())return null;try{let{stdout:e}=await q("secret-tool",["lookup","service",H,"account",Z],{timeout:5e3});return e.trim()||null}catch{return null}}async function Br(e){if(!lt())return!1;try{let t=(0,Te.execFile)("secret-tool",["store","--label",`${H} ${Z}`,"service",H,"account",Z]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",s=>s===0?n():r(new Error(`secret-tool exited ${s}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},Ur))]),!0):!1}catch{return!1}}async function Kr(){if(lt())try{await q("secret-tool",["clear","service",H,"account",Z],{timeout:5e3})}catch{}}function lt(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function qr(){try{let{stdout:e}=await q("security",["find-generic-password","-s",H,"-a",Ee,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Wr(e){try{try{await q("security",["delete-generic-password","-s",H,"-a",Ee],{timeout:5e3})}catch{}await q("security",["add-generic-password","-s",H,"-a",Ee,"-w",e],{timeout:5e3})}catch{}}async function Gr(){try{await q("security",["delete-generic-password","-s",H,"-a",Ee],{timeout:5e3})}catch{}}function ot(){try{return Q.readFileSync(ge,"utf-8").trim()||null}catch(e){if(Xt(e))throw new Pe(`Unable to read Visa CLI credentials from ${ge}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Zt(e){Q.mkdirSync(ct,{recursive:!0,mode:448}),Q.writeFileSync(ge,e,{mode:384}),process.platform==="win32"&&Jr(ge)}function it(){try{Q.unlinkSync(ge)}catch{}}function Jr(e){try{let t=Re.userInfo().username;(0,Te.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},n=>{n&&console.error(`[visa-cli] icacls ACL restriction failed: ${n.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function st(){switch(process.platform){case"darwin":return{get:jr,store:Hr,delete:Vr};case"linux":return{get:Fr,store:Br,delete:Kr};default:return{get:async()=>ot(),store:async e=>{try{return Zt(e),!0}catch{return!1}},delete:async()=>it(),storesInSessionFile:!0}}}var $=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let t=st(),n=await t.get();if(n)return n;let r=ot();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=st();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||it();return}await n.delete()}if(Zt(t),ot()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${ct} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":qr()}static async saveRcAccessToken(t){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await Wr(t)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await st().delete(),it()}static async clearAll(){await this.deleteSessionToken(),await Gr()}};var Ae=h(require("crypto")),Ie=h(require("tty")),Le=h(require("fs"));var ne="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";function Yr(e){return/-rc\.|-beta\./.test(e)}function dt(e){return Ae.createHash("sha256").update(e.trim()).digest("hex")}function Qt(e){return ne==="SKIP"?!0:Ae.timingSafeEqual(Buffer.from(dt(e)),Buffer.from(ne))}function Xr(e){return new Promise((t,n)=>{let r=Le.openSync("/dev/tty","r+"),s=new Ie.ReadStream(r),o=new Ie.WriteStream(r),i=()=>{try{s.destroy()}catch{}try{o.destroy()}catch{}try{Le.closeSync(r)}catch{}};o.write(e),s.setRawMode(!0),s.resume(),s.setEncoding("utf8");let a="";s.on("data",c=>{c==="\r"||c===`
1
+ "use strict";var Ar=Object.create;var zt=Object.defineProperty;var Ir=Object.getOwnPropertyDescriptor;var Lr=Object.getOwnPropertyNames;var Nr=Object.getPrototypeOf,Or=Object.prototype.hasOwnProperty;var Dr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ur=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Lr(t))!Or.call(e,s)&&s!==n&&zt(e,s,{get:()=>t[s],enumerable:!(r=Ir(t,s))||r.enumerable});return e};var h=(e,t,n)=>(n=e!=null?Ar(Nr(e)):{},Ur(t||!e||!e.__esModule?zt(n,"default",{value:e,enumerable:!0}):n,e));var ut=Dr((bo,Yr)=>{Yr.exports={name:"@visa/cli",version:"1.9.1-rc.1",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.0","@typescript-eslint/parser":"^8.59.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var _r=require("commander"),nt=h(require("crypto")),Cr=h(require("fs")),j=h(require("os")),oe=h(require("path")),kr=h(require("readline")),xr=require("child_process"),$r=require("util");var Re=require("child_process"),Yt=require("util"),Q=h(require("fs")),Ae=h(require("os")),at=h(require("path")),q=(0,Yt.promisify)(Re.execFile),ct=at.join(Ae.homedir(),".visa-mcp"),ge=at.join(ct,"session-token"),V="visa-cli",Z="session-token",Pe="rc-access",Mr=5e3,Te=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function jr(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
+ `)}function Xt(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=jr(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function Hr(){try{let{stdout:e}=await q("security",["find-generic-password","-s",V,"-a",Z,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Xt(e))throw new Te("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 Vr(e){try{try{await q("security",["delete-generic-password","-s",V,"-a",Z],{timeout:5e3})}catch{}return await q("security",["add-generic-password","-s",V,"-a",Z,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Fr(){try{await q("security",["delete-generic-password","-s",V,"-a",Z],{timeout:5e3})}catch{}}async function Br(){if(!lt())return null;try{let{stdout:e}=await q("secret-tool",["lookup","service",V,"account",Z],{timeout:5e3});return e.trim()||null}catch{return null}}async function Kr(e){if(!lt())return!1;try{let t=(0,Re.execFile)("secret-tool",["store","--label",`${V} ${Z}`,"service",V,"account",Z]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",s=>s===0?n():r(new Error(`secret-tool exited ${s}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},Mr))]),!0):!1}catch{return!1}}async function qr(){if(lt())try{await q("secret-tool",["clear","service",V,"account",Z],{timeout:5e3})}catch{}}function lt(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Gr(){try{let{stdout:e}=await q("security",["find-generic-password","-s",V,"-a",Pe,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Wr(e){try{try{await q("security",["delete-generic-password","-s",V,"-a",Pe],{timeout:5e3})}catch{}await q("security",["add-generic-password","-s",V,"-a",Pe,"-w",e],{timeout:5e3})}catch{}}async function Jr(){try{await q("security",["delete-generic-password","-s",V,"-a",Pe],{timeout:5e3})}catch{}}function ot(){try{return Q.readFileSync(ge,"utf-8").trim()||null}catch(e){if(Xt(e))throw new Te(`Unable to read Visa CLI credentials from ${ge}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Zt(e){Q.mkdirSync(ct,{recursive:!0,mode:448}),Q.writeFileSync(ge,e,{mode:384}),process.platform==="win32"&&zr(ge)}function it(){try{Q.unlinkSync(ge)}catch{}}function zr(e){try{let t=Ae.userInfo().username;(0,Re.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},n=>{n&&console.error(`[visa-cli] icacls ACL restriction failed: ${n.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function st(){switch(process.platform){case"darwin":return{get:Hr,store:Vr,delete:Fr};case"linux":return{get:Br,store:Kr,delete:qr};default:return{get:async()=>ot(),store:async e=>{try{return Zt(e),!0}catch{return!1}},delete:async()=>it(),storesInSessionFile:!0}}}var $=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let t=st(),n=await t.get();if(n)return n;let r=ot();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=st();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||it();return}await n.delete()}if(Zt(t),ot()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${ct} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":Gr()}static async saveRcAccessToken(t){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await Wr(t)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await st().delete(),it()}static async clearAll(){await this.deleteSessionToken(),await Jr()}};var Ie=h(require("crypto")),Le=h(require("tty")),Ne=h(require("fs"));var ne="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";function Xr(e){return/-rc\.|-beta\./.test(e)}function dt(e){return Ie.createHash("sha256").update(e.trim()).digest("hex")}function Qt(e){return ne==="SKIP"?!0:Ie.timingSafeEqual(Buffer.from(dt(e)),Buffer.from(ne))}function Zr(e){return new Promise((t,n)=>{let r=Ne.openSync("/dev/tty","r+"),s=new Le.ReadStream(r),o=new Le.WriteStream(r),i=()=>{try{s.destroy()}catch{}try{o.destroy()}catch{}try{Ne.closeSync(r)}catch{}};o.write(e),s.setRawMode(!0),s.resume(),s.setEncoding("utf8");let a="";s.on("data",c=>{c==="\r"||c===`
3
3
  `?(o.write(`
4
4
  `),i(),t(a)):c===""?(o.write(`
5
- `),i(),n(new Error("Cancelled"))):c==="\x7F"||c==="\b"?a.length>0&&(a=a.slice(0,-1),o.write("\b \b")):(a+=c,o.write("\u2022"))})})}var Zr=`
5
+ `),i(),n(new Error("Cancelled"))):c==="\x7F"||c==="\b"?a.length>0&&(a=a.slice(0,-1),o.write("\b \b")):(a+=c,o.write("\u2022"))})})}var Qr=`
6
6
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
7
7
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
8
8
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551
@@ -11,31 +11,31 @@
11
11
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
12
12
 
13
13
  This is a Release Candidate build. Access is restricted to Visa employees.
14
- `;async function en(e={}){let t=e.version??ut().version;if(!Yr(t))return;let n=process.env.VISA_RC_CODE;if(n&&Qt(n)){await $.saveRcAccessToken(dt(n));return}if(e.isMcp??!1){let i=await $.getRcAccessToken();if(i&&(ne==="SKIP"||i===ne))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
- `),process.exit(1)}let s=await $.getRcAccessToken();if(s&&(ne==="SKIP"||s===ne))return;console.log(Zr);let o=3;for(let i=1;i<=o;i++){let a;try{a=await Xr(" Enter RC access code: ")}catch{process.exit(1)}if(Qt(a)){await $.saveRcAccessToken(dt(a)),console.log(`
14
+ `;async function en(e={}){let t=e.version??ut().version;if(!Xr(t))return;let n=process.env.VISA_RC_CODE;if(n&&Qt(n)){await $.saveRcAccessToken(dt(n));return}if(e.isMcp??!1){let i=await $.getRcAccessToken();if(i&&(ne==="SKIP"||i===ne))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
+ `),process.exit(1)}let s=await $.getRcAccessToken();if(s&&(ne==="SKIP"||s===ne))return;console.log(Qr);let o=3;for(let i=1;i<=o;i++){let a;try{a=await Zr(" Enter RC access code: ")}catch{process.exit(1)}if(Qt(a)){await $.saveRcAccessToken(dt(a)),console.log(`
16
16
  Access granted. Welcome.
17
17
  `);return}i<o&&console.log(`
18
18
  Invalid code. ${o-i} attempt(s) remaining.
19
19
  `)}console.log(`
20
20
  Invalid code. Contact your team lead.
21
- `),process.exit(1)}var tn=require("child_process");function Qr(e=process.env,t=process.platform){return e.VISA_CLI_NO_BROWSER==="1"||e.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.SSH_CONNECTION||e.SSH_TTY?{headless:!0,reason:"SSH session detected"}:t==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function es(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
22
- `)}function ts(e,t=process.platform){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"cmd",args:["/c","start","",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}async function nn(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,s=t.platform??process.platform,o=t.spawn??((c,l,u)=>{(0,tn.execFile)(c,l,d=>u(d))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of es(e).split(`
23
- `))n(` ${c}`);n("");let i=Qr(r,s);if(i.headless){n(` (${i.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let a=ts(e,s);if(!a){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{o(a.cmd,a.args,l=>{l?(n(` Could not open browser automatically (${l.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()})})}var sn=h(require("crypto")),L=h(require("fs")),Ne=h(require("path"));function on(e,t){L.mkdirSync(Ne.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${sn.randomBytes(8).toString("hex")}.tmp`;try{L.writeFileSync(n,JSON.stringify(t,null,2)+`
24
- `),L.renameSync(n,e)}catch(r){try{L.unlinkSync(n)}catch{}throw r}}function rn(e){return`'${e.replace(/'/g,"'\\''")}'`}var an="# visa-cli-hud-v1";function ns(e,t){let n=e??process.execPath,r=t??process.argv[1]??"",s=r?Ne.resolve(r):"";return`${s?`${rn(n)} ${rn(s)} statusline`:"visa-cli statusline"} ${an}`}function cn(e){return typeof e!="string"?!1:e.includes(an)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Oe(e,t=ns){let n={},r=!1;if(L.existsSync(e)){r=!0;try{n=JSON.parse(L.readFileSync(e,"utf-8"))}catch(s){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${s.message}). Fix the file manually, then run: visa-cli hud enable`}}}if(n.statusLine){let s=typeof n.statusLine=="object"?n.statusLine.command:"";return cn(s)?{installed:"already-visa",message:"Visa HUD already registered in ~/.claude/settings.json."}:{installed:"other-hud-present",message:"Another HUD is already configured (keeping it). To switch to Visa HUD, edit ~/.claude/settings.json \u2192 statusLine.command"}}try{return n.statusLine={type:"command",command:t()},on(e,n),{installed:"new",message:`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`}}catch(s){return{installed:"error",message:`Failed to write settings: ${s.message}. Enable manually later with: visa-cli hud enable`}}}function ft(e){if(!L.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(L.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";return cn(n)?(delete t.statusLine,on(e,t),{removed:!0,message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}):{removed:!1,message:"statusLine is owned by another tool \u2014 leaving it alone."}}var J=h(require("fs")),z=h(require("path")),rs=1,re={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},ss=["claude","claude-code","codex","all"];function yt(e){let t=e.toLowerCase();return ss.includes(t)?t:null}var os=50,is=64*1024,ln=10,pt=80;function as(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var mt=as(),p={reset:"\x1B[0m",visaBlue:mt?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:mt?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:mt?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function m(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${p.reset}`}function un(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function mn(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,s=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(l)},o=u=>{r||(r=!0,s(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return o(null);try{let d=JSON.parse(u);o(d&&typeof d=="object"?d:null)}catch{o(null)}},c=()=>o(null),l=setTimeout(()=>{n.length>0?a():o(null)},os);e.on("data",i),e.on("end",a),e.on("error",c)})}function De(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${m(r||"",p.visaBlueSoft)}${m(s||"",p.dim)}`}function gt(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function cs(e){if(vs(e))return ls(e);let t=` ${m("\u2502",p.dim)} `,n=ht(e)||"claude",r=e.cwd?T(z.basename(e.cwd)):"",s=St(e.workspace),o=r||s,i=s&&s!==o?` ${m(`@${s}`,p.visaBlueSoft)}`:"",a=[m(`[${n}]`,p.visaBlueSoft)];o&&a.push(`${m(o,p.visaGold)}${i}`);let c=a.join(t),l=Number(e.context_window?.context_window_size??0),u=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,d=e.context_window?.current_usage,v=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(P=>typeof P=="number"&&Number.isFinite(P)),w=v.length>0?v.reduce((P,X)=>P+X,0):null,C=Number(e.context_window?.total_input_tokens??w??d?.input_tokens??0),f=u!==null?Math.max(0,Math.min(1,u/100)):l>0?Math.max(0,Math.min(1,C/l)):0,b=u!==null&&l>0?Math.round(f*l):C,_;if(l>0||u!==null){let P=`${String(Math.round(f*100)).padStart(2," ")}%`,X=l>0?` ${m(`(${gt(b)}/${gt(l)})`,p.dim)}`:"";_=`${m("Context",p.dim)} ${De(f)} ${m(P,p.green)}${X}`}else _=`${m("Context",p.dim)} ${m("-",p.dim)}`;let E=ds(e.rate_limits),R=[_];E&&R.push(E);let Y=R.join(t);return`${c}
25
- ${Y}`}function ls(e){let t=` ${m("\u2502",p.dim)} `,n=wn(e),r=n.model||"codex",s=[m(`[${r}]`,p.visaBlueSoft)];n.project&&s.push(m(n.project,p.visaGold)),n.gitBranch&&s.push(`${m("git",p.dim)} ${m(n.gitBranch,p.visaGold)}`);let o=s.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${m("Context",p.dim)} ${De(c)} ${m(`${Math.round(n.contextUsedPercent)}%`,p.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let c=100-n.contextRemainingPercent,l=Math.max(0,Math.min(1,c/100));i.push(`${m("Context",p.dim)} ${De(l)} ${m(`${Math.round(c)}%`,p.green)}`)}typeof n.usedTokens=="number"&&i.push(`${m("Tokens",p.dim)} ${gt(n.usedTokens)}`),n.status&&i.push(`${m("Status",p.dim)} ${m(n.status,p.visaBlueSoft)}`),n.threadTitle&&i.push(`${m("Thread",p.dim)} ${m(n.threadTitle,p.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${m("Context",p.dim)} ${m("-",p.dim)}`;return`${o}
26
- ${a}`}function us(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),s=Math.floor(r/60),o=r%60;return s>0?`${s}h ${o}m`:`${o}m`}function dn(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,s=De(r),o=n>=90?"\x1B[38;5;196m":n>=70?p.visaGold:p.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=us(e.resets_at),c=a?` ${m(`(${a} / ${t})`,p.dim)}`:` ${m(`(${t})`,p.dim)}`;return`${s} ${m(i,o)}${c}`}function ds(e){if(!e)return null;let t=dn(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?dn(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${m("\u2502",p.dim)} `,o=[t,r].filter(Boolean);return`${m("Usage",p.dim)} ${o.join(s)}`}function fs(e){let t;try{let n=J.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,is),o=r-s;t=J.openSync(e,"r");let i=Buffer.alloc(s);J.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(J.readSync(t,c,0,1,o-1),c[0]!==10){let l=a.indexOf(`
27
- `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{J.closeSync(t)}catch{}}}function ps(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=z.basename(z.dirname(s)),i=z.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function ms(e){let t=e.split(`
28
- `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<ln*3;s-=1){let o=t[s].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let c=i.message;if(!c||typeof c!="object")continue;let l=c.content;if(Array.isArray(l))for(let u of l){if(!u||typeof u!="object")continue;let d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let v=typeof d.id=="string"?d.id:"",w=v.length>0?!r.has(v):!1;n.push({name:d.name,target:ps(d.input),running:w})}}}return n.reverse(),n.slice(Math.max(0,n.length-ln))}function gs(e){let t=[];for(let n of e){let r=t[t.length-1];r&&!r.running&&!n.running&&r.name===n.name&&r.target===void 0&&n.target===void 0?r.count+=1:t.push({...n,count:1})}return t}function hs(e){let t=e.running?m("\u25D0",p.visaGold):m("\u2713",p.green),n=e.running?p.visaGold:p.visaBlueSoft,r=m(T(e.name),n),s=e.target?T(e.target):"",o=s?`${m(":",p.dim)} ${m(s,p.dim)}`:"",i=e.count>1?` ${m(`\xD7${e.count}`,p.dim)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function ys(e){let t=` ${m("\u2502",p.dim)} `,n=un(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(un(c)<=pt)return c;r=r.slice(1)}if(e.length===0)return"";let s="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>pt-n-1?i.slice(0,pt-n-1)+s:i;return`${m(s,p.dim)}${t}${a}`}async function Ss(e){if(!e||typeof e!="string")return null;let t=fs(e);if(!t)return null;let n;try{n=ms(t)}catch{return null}if(n.length===0)return null;let s=gs(n).map(hs);return ys(s)||null}async function gn(e,t){return(await hn(e,t)).join(`
29
- `)}async function hn(e,t){let n=[e];if(t){let r=cs(t);if(r&&n.push(...r.split(`
30
- `)),t.transcript_path){let s=await Ss(t.transcript_path);s&&n.push(...s.split(`
21
+ `),process.exit(1)}var tn=require("child_process");function es(e=process.env,t=process.platform){return e.VISA_CLI_NO_BROWSER==="1"||e.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.SSH_CONNECTION||e.SSH_TTY?{headless:!0,reason:"SSH session detected"}:t==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function ts(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
22
+ `)}function ns(e,t=process.platform){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"cmd",args:["/c","start","",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}async function nn(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,s=t.platform??process.platform,o=t.spawn??((c,l,u)=>{(0,tn.execFile)(c,l,d=>u(d))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of ts(e).split(`
23
+ `))n(` ${c}`);n("");let i=es(r,s);if(i.headless){n(` (${i.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let a=ns(e,s);if(!a){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{o(a.cmd,a.args,l=>{l?(n(` Could not open browser automatically (${l.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()})})}var sn=h(require("crypto")),N=h(require("fs")),Oe=h(require("path"));function on(e,t){N.mkdirSync(Oe.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${sn.randomBytes(8).toString("hex")}.tmp`;try{N.writeFileSync(n,JSON.stringify(t,null,2)+`
24
+ `),N.renameSync(n,e)}catch(r){try{N.unlinkSync(n)}catch{}throw r}}function rn(e){return`'${e.replace(/'/g,"'\\''")}'`}var an="# visa-cli-hud-v1";function rs(e,t){let n=e??process.execPath,r=t??process.argv[1]??"",s=r?Oe.resolve(r):"";return`${s?`${rn(n)} ${rn(s)} statusline`:"visa-cli statusline"} ${an}`}function cn(e){return typeof e!="string"?!1:e.includes(an)?!0:e.includes("visa-cli")&&e.includes("statusline")}function De(e,t=rs){let n={},r=!1;if(N.existsSync(e)){r=!0;try{n=JSON.parse(N.readFileSync(e,"utf-8"))}catch(s){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${s.message}). Fix the file manually, then run: visa-cli hud enable`}}}if(n.statusLine){let s=typeof n.statusLine=="object"?n.statusLine.command:"";return cn(s)?{installed:"already-visa",message:"Visa HUD already registered in ~/.claude/settings.json."}:{installed:"other-hud-present",message:"Another HUD is already configured (keeping it). To switch to Visa HUD, edit ~/.claude/settings.json \u2192 statusLine.command"}}try{return n.statusLine={type:"command",command:t()},on(e,n),{installed:"new",message:`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`}}catch(s){return{installed:"error",message:`Failed to write settings: ${s.message}. Enable manually later with: visa-cli hud enable`}}}function ft(e){if(!N.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(N.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";return cn(n)?(delete t.statusLine,on(e,t),{removed:!0,message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}):{removed:!1,message:"statusLine is owned by another tool \u2014 leaving it alone."}}var z=h(require("fs")),Y=h(require("path")),ss=1,re={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},os=["claude","claude-code","codex","all"];function yt(e){let t=e.toLowerCase();return os.includes(t)?t:null}var is=50,as=64*1024,ln=10,pt=80;function cs(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var mt=cs(),p={reset:"\x1B[0m",visaBlue:mt?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:mt?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:mt?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function m(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${p.reset}`}function un(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function mn(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,s=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(l)},o=u=>{r||(r=!0,s(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return o(null);try{let d=JSON.parse(u);o(d&&typeof d=="object"?d:null)}catch{o(null)}},c=()=>o(null),l=setTimeout(()=>{n.length>0?a():o(null)},is);e.on("data",i),e.on("end",a),e.on("error",c)})}function Ue(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${m(r||"",p.visaBlueSoft)}${m(s||"",p.dim)}`}function gt(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function ls(e){if(bs(e))return us(e);let t=` ${m("\u2502",p.dim)} `,n=ht(e)||"claude",r=e.cwd?E(Y.basename(e.cwd)):"",s=St(e.workspace),o=r||s,i=s&&s!==o?` ${m(`@${s}`,p.visaBlueSoft)}`:"",a=[m(`[${n}]`,p.visaBlueSoft)];o&&a.push(`${m(o,p.visaGold)}${i}`);let c=a.join(t),l=Number(e.context_window?.context_window_size??0),u=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,d=e.context_window?.current_usage,S=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(L=>typeof L=="number"&&Number.isFinite(L)),w=S.length>0?S.reduce((L,X)=>L+X,0):null,C=Number(e.context_window?.total_input_tokens??w??d?.input_tokens??0),f=u!==null?Math.max(0,Math.min(1,u/100)):l>0?Math.max(0,Math.min(1,C/l)):0,_=u!==null&&l>0?Math.round(f*l):C,b;if(l>0||u!==null){let L=`${String(Math.round(f*100)).padStart(2," ")}%`,X=l>0?` ${m(`(${gt(_)}/${gt(l)})`,p.dim)}`:"";b=`${m("Context",p.dim)} ${Ue(f)} ${m(L,p.green)}${X}`}else b=`${m("Context",p.dim)} ${m("-",p.dim)}`;let I=fs(e.rate_limits),P=[b];I&&P.push(I);let J=P.join(t);return`${c}
25
+ ${J}`}function us(e){let t=` ${m("\u2502",p.dim)} `,n=wn(e),r=n.model||"codex",s=[m(`[${r}]`,p.visaBlueSoft)];n.project&&s.push(m(n.project,p.visaGold)),n.gitBranch&&s.push(`${m("git",p.dim)} ${m(n.gitBranch,p.visaGold)}`);let o=s.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${m("Context",p.dim)} ${Ue(c)} ${m(`${Math.round(n.contextUsedPercent)}%`,p.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let c=100-n.contextRemainingPercent,l=Math.max(0,Math.min(1,c/100));i.push(`${m("Context",p.dim)} ${Ue(l)} ${m(`${Math.round(c)}%`,p.green)}`)}typeof n.usedTokens=="number"&&i.push(`${m("Tokens",p.dim)} ${gt(n.usedTokens)}`),n.status&&i.push(`${m("Status",p.dim)} ${m(n.status,p.visaBlueSoft)}`),n.threadTitle&&i.push(`${m("Thread",p.dim)} ${m(n.threadTitle,p.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${m("Context",p.dim)} ${m("-",p.dim)}`;return`${o}
26
+ ${a}`}function ds(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),s=Math.floor(r/60),o=r%60;return s>0?`${s}h ${o}m`:`${o}m`}function dn(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,s=Ue(r),o=n>=90?"\x1B[38;5;196m":n>=70?p.visaGold:p.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=ds(e.resets_at),c=a?` ${m(`(${a} / ${t})`,p.dim)}`:` ${m(`(${t})`,p.dim)}`;return`${s} ${m(i,o)}${c}`}function fs(e){if(!e)return null;let t=dn(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?dn(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${m("\u2502",p.dim)} `,o=[t,r].filter(Boolean);return`${m("Usage",p.dim)} ${o.join(s)}`}function ps(e){let t;try{let n=z.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,as),o=r-s;t=z.openSync(e,"r");let i=Buffer.alloc(s);z.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(z.readSync(t,c,0,1,o-1),c[0]!==10){let l=a.indexOf(`
27
+ `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{z.closeSync(t)}catch{}}}function ms(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=Y.basename(Y.dirname(s)),i=Y.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function gs(e){let t=e.split(`
28
+ `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<ln*3;s-=1){let o=t[s].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let c=i.message;if(!c||typeof c!="object")continue;let l=c.content;if(Array.isArray(l))for(let u of l){if(!u||typeof u!="object")continue;let d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let S=typeof d.id=="string"?d.id:"",w=S.length>0?!r.has(S):!1;n.push({name:d.name,target:ms(d.input),running:w})}}}return n.reverse(),n.slice(Math.max(0,n.length-ln))}function hs(e){let t=[];for(let n of e){let r=t[t.length-1];r&&!r.running&&!n.running&&r.name===n.name&&r.target===void 0&&n.target===void 0?r.count+=1:t.push({...n,count:1})}return t}function ys(e){let t=e.running?m("\u25D0",p.visaGold):m("\u2713",p.green),n=e.running?p.visaGold:p.visaBlueSoft,r=m(E(e.name),n),s=e.target?E(e.target):"",o=s?`${m(":",p.dim)} ${m(s,p.dim)}`:"",i=e.count>1?` ${m(`\xD7${e.count}`,p.dim)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function Ss(e){let t=` ${m("\u2502",p.dim)} `,n=un(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(un(c)<=pt)return c;r=r.slice(1)}if(e.length===0)return"";let s="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>pt-n-1?i.slice(0,pt-n-1)+s:i;return`${m(s,p.dim)}${t}${a}`}async function vs(e){if(!e||typeof e!="string")return null;let t=ps(e);if(!t)return null;let n;try{n=gs(t)}catch{return null}if(n.length===0)return null;let s=hs(n).map(ys);return Ss(s)||null}async function gn(e,t){return(await hn(e,t)).join(`
29
+ `)}async function hn(e,t){let n=[e];if(t){let r=ls(t);if(r&&n.push(...r.split(`
30
+ `)),t.transcript_path){let s=await vs(t.transcript_path);s&&n.push(...s.split(`
31
31
  `))}}return n}async function yn(e,t){let n=await hn(e,t),r=n.join(`
32
- `);return{schemaVersion:rs,client:t?bn(t):re.UNKNOWN,rendered:r,lines:n.map(pn),visa:{spendLine:pn(e)},context:t?wn(t):{}}}function T(e){return e?e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function St(e){if(typeof e=="string")return T(z.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return T(t?z.basename(t):e.name)}function Sn(e){return T(e.app_name??e.appName??e.app??e.client)}function ht(e){return T(e.model?.display_name??e.model_name??e.modelName)}function vn(e){return T(e.cwd??e.current_dir??e.project_root)}function fn(e){let t=T(e.project);if(t)return t;let n=vn(e);if(n)return T(z.basename(n));let r=St(e.workspace);return r||""}function F(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function bn(e){let t=Sn(e).toLowerCase();return t.includes("codex")?re.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?re.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||F(e.context_used)!==void 0?re.CODEX:re.UNKNOWN}function vs(e){return bn(e)===re.CODEX}function wn(e){let t=Sn(e),n=vn(e),r=St(e.workspace),s=F(e.context_used)??F(e.context_window?.used_percentage??void 0),o=F(e.context_remaining)??F(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...ht(e)?{model:ht(e)}:{},...fn(e)?{project:fn(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...T(e.git_branch??e.branch)?{gitBranch:T(e.git_branch??e.branch)}:{},...T(e.status??e.run_state??e.runState)?{status:T(e.status??e.run_state??e.runState)}:{},...T(e.thread_title??e.threadTitle)?{threadTitle:T(e.thread_title??e.threadTitle)}:{},...s!==void 0?{contextUsedPercent:s}:{},...o!==void 0?{contextRemainingPercent:o}:{},...F(e.used_tokens)!==void 0?{usedTokens:F(e.used_tokens)}:{},...F(e.total_input_tokens)!==void 0?{totalInputTokens:F(e.total_input_tokens)}:{},...F(e.total_output_tokens)!==void 0?{totalOutputTokens:F(e.total_output_tokens)}:{}}}function pn(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}async function _n(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var bs=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function kn(e,t){let n=Cn(e),r=Cn(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:ws(n.pre,r.pre)>0}function Cn(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(bs);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function ws(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function W(){return!!(xn(process.env.VISA_CLI_NO_UPDATE_CHECK)||xn(process.env.CI)||process.env.NODE_ENV==="test")}function xn(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var ee=h(require("fs")),Pn=h(require("path"));var Ue=h(require("fs")),$n=h(require("path")),En=h(require("os"));var vt=$n.join(En.homedir(),".visa-mcp"),he=class{static ensureConfigDir(){Ue.existsSync(vt)||Ue.mkdirSync(vt,{recursive:!0,mode:448})}static getConfigDir(){return vt}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!0,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!0,query_onchain_prices_card:!0,generate_music_tempo_card:!0,check_music_status_tempo_card:!0,generate_image_fast_card:!0,pxlwall_card:!1,generate_video_tempo_card:!0};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let t=new Set;for(let[n,r]of Object.entries(this.TOOL_STATES))r||t.add(n);return t}static isToolDisabled(t){return this.TOOL_STATES[t]===!1}};var _s="settings.json";function Me(){return Pn.join(he.getConfigDir(),_s)}var ye={"auth.serverUrl":{type:"string",description:"Auth server base URL. Override for staging / self-hosted backends.",requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("auth.serverUrl must be a string");let t;try{t=new URL(e)}catch{throw new Error(`auth.serverUrl must be a valid URL (got: ${JSON.stringify(e)})`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw new Error(`auth.serverUrl must use http or https (got: ${t.protocol})`)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_music, ...). Restart required.",requiresRestart:!0},"tools.specific":{type:"boolean",description:"Show hardcoded per-merchant tools (generate_image_card, query_onchain_prices_card, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0}};function je(){let e=Me();if(!ee.existsSync(e))return{};try{let t=ee.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?{}:n}catch{return{}}}function Tn(e){he.ensureConfigDir();let t=Me(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
33
- `;ee.writeFileSync(n,r,{mode:384}),ee.renameSync(n,t)}function bt(e){let t=je()[e];return typeof t=="string"?t:void 0}function Rn(e){let t=je()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}var ce=class extends Error{constructor(t){let n=Object.keys(ye).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${n}. For server-controlled values (biometric.*, spending.*) use the dedicated tools (biometric_on/off, update_spending_controls).`),this.name="UnknownSettingKeyError"}},le=class extends Error{constructor(t){let n="";t.startsWith("biometric.")?n="biometric_on / biometric_off":t.startsWith("spending.")?n="update_spending_controls":t.startsWith("cards.")?n="add_card / remove_card / set_default_card":t.startsWith("account.")&&(n="login / reset"),super(`"${t}" is a server-controlled value and cannot be set via config set. `+(n?`Use ${n} instead.`:"No client-side override is supported.")),this.name="ServerOnlySettingError"}},An=["biometric.","spending.","account.","cards.","biometric"];function In(e,t){if(An.some(o=>e.startsWith(o)))throw new le(e);let n=ye[e];if(!n)throw new ce(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")r=!0;else if(o==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let s=je();return s[e]=r,Tn(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Me()}}function Ln(e){if(An.some(s=>e.startsWith(s)))throw new le(e);let t=ye[e];if(!t)throw new ce(e);let n=je(),r=e in n;return r&&(delete n[e],Tn(n)),{key:e,removed:r,requiresRestart:r&&!!t.requiresRestart,path:Me()}}var Cs="https://auth.visacli.sh";function Nn(){let e=process.env.VISA_AUTH_URL;if(e!==void 0&&e!=="")return e;let t=bt("auth.serverUrl");return t!==void 0?t:Cs}var wt="1.9.0-rc.1",ue=class{constructor(t){this.getSessionToken=t;this.baseUrl=Nn()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!W()){let r=t.headers.get("X-Latest-Version"),s=t.headers.get("X-Update-Message");r&&kn(r,wt)&&(this.lastSignals.updateAvailable={version:r,message:s||`Update available: v${r}. Run: npm install -g @visa/cli && visa-cli setup`})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return wt}async request(t,n,r,s,o){let i=await this.getSessionToken();if(!i)throw new Error("Not logged in. Sign up at https://visacli.sh or run: visa-cli setup");let a={Authorization:`Bearer ${i}`};o&&(t==="GET"?a["X-User-Context"]=o.replace(/[\r\n\0]/g," ").slice(0,1e3):r={...r||{},user_context:o}),r&&(a["Content-Type"]="application/json");let c;try{c=await _n(`${this.baseUrl}${n}`,{method:t,headers:{...a,"X-Visa-CLI-Version":wt},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(u){throw u.name==="AbortError"||u.message?.includes("aborted")?new Error("The request timed out. The server may be under heavy load. Please try again."):new Error("Cannot reach the Visa CLI server. Check your internet connection and try again.")}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let u=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${u}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let l;try{l=await c.json()}catch{throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(l?.error||`Request failed (${c.status}). Try again.`);return l}async pay(t,n){return this.request("POST","/v1/pay",t,void 0,n)}async shortcut(t,n,r,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s)}async batch(t,n,r){return this.request("POST","/v1/batch",t,n,r)}async catalogSearch(t,n){let r=new URLSearchParams;t&&r.set("q",t),n&&r.set("category",n);let s=r.toString();return this.request("GET",`/v1/catalog${s?`?${s}`:""}`)}async catalogTool(t){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`)}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getTransactions(t){return this.request("GET","/v1/transactions",void 0,void 0,t)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t){return this.request("POST","/v1/attestation-key",{publicKey:t})}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var $t=require("child_process"),Hn=require("util"),Vn=h(require("crypto")),A=h(require("fs")),Fn=h(require("os")),G=h(require("path"));var N=h(require("fs")),kt=h(require("path")),On=h(require("os")),Ct=kt.join(On.homedir(),".visa-mcp"),Se=kt.join(Ct,"mcp-server.log"),ks=5*1024*1024,_t=null;function xs(){N.existsSync(Ct)||N.mkdirSync(Ct,{recursive:!0,mode:448})}function $s(){if(!_t){if(xs(),N.existsSync(Se)&&N.statSync(Se).size>ks){let t=Se+".1";N.existsSync(t)&&N.unlinkSync(t),N.renameSync(Se,t)}_t=N.createWriteStream(Se,{flags:"a"})}return _t}function He(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
34
- `;process.stderr.write(s),$s().write(s)}var de={debug:(...e)=>He("DEBUG",...e),info:(...e)=>He("INFO",...e),warn:(...e)=>He("WARN",...e),error:(...e)=>He("ERROR",...e)};var fe=(0,Hn.promisify)($t.execFile),Be=G.join(Fn.homedir(),".visa-mcp","bin"),se=G.join(Be,"Visa CLI"),Es=G.join(__dirname,"..","native"),Dn="5",Un=G.join(Be,"visa-keychain.version"),Mn=G.join(Be,"visa-keychain.sha256");function jn(e){let t=A.readFileSync(e);return Vn.createHash("sha256").update(t).digest("hex")}async function Bn(){try{if(A.readFileSync(Un,"utf-8").trim()===Dn&&A.existsSync(se)){let r=A.readFileSync(Mn,"utf-8").trim();if(jn(se)!==r)de.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),A.unlinkSync(se);else return se}}catch{}let e=G.join(Es,"visa-keychain.m");if(A.existsSync(e)||(e=G.resolve(__dirname,"..","..","native","visa-keychain.m")),A.existsSync(e)||(e=G.resolve(__dirname,"..","native","visa-keychain.m")),!A.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");A.mkdirSync(Be,{recursive:!0,mode:448});try{await fe("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",se,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=jn(se);return A.writeFileSync(Mn,t,{mode:384}),A.writeFileSync(Un,Dn,{mode:384}),se}async function Kn(e){let t=await Bn(),n;try{n=(await fe(t,e,{timeout:6e4})).stdout}catch(o){n=o.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(o.stderr?.trim()||o.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let s=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(s)}var xt=null;function O(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:xt!==null?xt:(xt=!0,!0)}var Ve="visa-cli",Fe="attestation-key";async function Ps(e){try{await fe("security",["delete-generic-password","-s",Ve,"-a",Fe],{timeout:5e3})}catch{}await fe("security",["add-generic-password","-s",Ve,"-a",Fe,"-w",e],{timeout:5e3})}async function Ts(){try{let{stdout:e}=await fe("security",["find-generic-password","-s",Ve,"-a",Fe,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Ke(){let e=await Kn(["generate-key"]);if(!e)throw new Error("Key generation returned no output");let t=e.indexOf(":");if(t<0)throw new Error("Unexpected generate-key output format");let n=e.slice(0,t),r=e.slice(t+1);return await Ps(n),r}async function Et(e,t){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await Ts();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Bn(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,$t.execFile)(r,s,{timeout:6e4},(c,l)=>{let u=(l||"").trim();if(c){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}u.startsWith("OK:")?o(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function qn(){try{await fe("security",["delete-generic-password","-s",Ve,"-a",Fe],{timeout:5e3})}catch{}try{await Kn(["delete-key"])}catch{}}function Wn(e,t=process.stderr){if(W()||!e?.updateAvailable)return!1;let{message:n}=e.updateAvailable;return n?(t.write(`
32
+ `);return{schemaVersion:ss,client:t?bn(t):re.UNKNOWN,rendered:r,lines:n.map(pn),visa:{spendLine:pn(e)},context:t?wn(t):{}}}function E(e){return e?e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function St(e){if(typeof e=="string")return E(Y.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return E(t?Y.basename(t):e.name)}function Sn(e){return E(e.app_name??e.appName??e.app??e.client)}function ht(e){return E(e.model?.display_name??e.model_name??e.modelName)}function vn(e){return E(e.cwd??e.current_dir??e.project_root)}function fn(e){let t=E(e.project);if(t)return t;let n=vn(e);if(n)return E(Y.basename(n));let r=St(e.workspace);return r||""}function F(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function bn(e){let t=Sn(e).toLowerCase();return t.includes("codex")?re.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?re.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||F(e.context_used)!==void 0?re.CODEX:re.UNKNOWN}function bs(e){return bn(e)===re.CODEX}function wn(e){let t=Sn(e),n=vn(e),r=St(e.workspace),s=F(e.context_used)??F(e.context_window?.used_percentage??void 0),o=F(e.context_remaining)??F(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...ht(e)?{model:ht(e)}:{},...fn(e)?{project:fn(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...E(e.git_branch??e.branch)?{gitBranch:E(e.git_branch??e.branch)}:{},...E(e.status??e.run_state??e.runState)?{status:E(e.status??e.run_state??e.runState)}:{},...E(e.thread_title??e.threadTitle)?{threadTitle:E(e.thread_title??e.threadTitle)}:{},...s!==void 0?{contextUsedPercent:s}:{},...o!==void 0?{contextRemainingPercent:o}:{},...F(e.used_tokens)!==void 0?{usedTokens:F(e.used_tokens)}:{},...F(e.total_input_tokens)!==void 0?{totalInputTokens:F(e.total_input_tokens)}:{},...F(e.total_output_tokens)!==void 0?{totalOutputTokens:F(e.total_output_tokens)}:{}}}function pn(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}async function _n(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var ws=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function kn(e,t){let n=Cn(e),r=Cn(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:_s(n.pre,r.pre)>0}function Cn(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(ws);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function _s(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function G(){return!!(xn(process.env.VISA_CLI_NO_UPDATE_CHECK)||xn(process.env.CI)||process.env.NODE_ENV==="test")}function xn(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var ee=h(require("fs")),Pn=h(require("path"));var Me=h(require("fs")),$n=h(require("path")),En=h(require("os"));var vt=$n.join(En.homedir(),".visa-mcp"),he=class{static ensureConfigDir(){Me.existsSync(vt)||Me.mkdirSync(vt,{recursive:!0,mode:448})}static getConfigDir(){return vt}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!0,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!0,query_onchain_prices_card:!0,generate_music_tempo_card:!0,check_music_status_tempo_card:!0,generate_image_fast_card:!0,pxlwall_card:!1,generate_video_tempo_card:!0};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let t=new Set;for(let[n,r]of Object.entries(this.TOOL_STATES))r||t.add(n);return t}static isToolDisabled(t){return this.TOOL_STATES[t]===!1}};var Cs="settings.json";function je(){return Pn.join(he.getConfigDir(),Cs)}var ye={"auth.serverUrl":{type:"string",description:"Auth server base URL. Override for staging / self-hosted backends.",requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("auth.serverUrl must be a string");let t;try{t=new URL(e)}catch{throw new Error(`auth.serverUrl must be a valid URL (got: ${JSON.stringify(e)})`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw new Error(`auth.serverUrl must use http or https (got: ${t.protocol})`)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_music, ...). Restart required.",requiresRestart:!0},"tools.specific":{type:"boolean",description:"Show hardcoded per-merchant tools (generate_image_card, query_onchain_prices_card, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0}};function He(){let e=je();if(!ee.existsSync(e))return{};try{let t=ee.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?{}:n}catch{return{}}}function Tn(e){he.ensureConfigDir();let t=je(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
33
+ `;ee.writeFileSync(n,r,{mode:384}),ee.renameSync(n,t)}function bt(e){let t=He()[e];return typeof t=="string"?t:void 0}function Rn(e){let t=He()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}var ce=class extends Error{constructor(t){let n=Object.keys(ye).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${n}. For server-controlled values (biometric.*, spending.*) use the dedicated tools (biometric_on/off, update_spending_controls).`),this.name="UnknownSettingKeyError"}},le=class extends Error{constructor(t){let n="";t.startsWith("biometric.")?n="biometric_on / biometric_off":t.startsWith("spending.")?n="update_spending_controls":t.startsWith("cards.")?n="add_card / remove_card / set_default_card":t.startsWith("account.")&&(n="login / reset"),super(`"${t}" is a server-controlled value and cannot be set via config set. `+(n?`Use ${n} instead.`:"No client-side override is supported.")),this.name="ServerOnlySettingError"}},An=["biometric.","spending.","account.","cards.","biometric"];function In(e,t){if(An.some(o=>e.startsWith(o)))throw new le(e);let n=ye[e];if(!n)throw new ce(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")r=!0;else if(o==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let s=He();return s[e]=r,Tn(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:je()}}function Ln(e){if(An.some(s=>e.startsWith(s)))throw new le(e);let t=ye[e];if(!t)throw new ce(e);let n=He(),r=e in n;return r&&(delete n[e],Tn(n)),{key:e,removed:r,requiresRestart:r&&!!t.requiresRestart,path:je()}}var ks="https://auth.visacli.sh";function Nn(){let e=process.env.VISA_AUTH_URL;if(e!==void 0&&e!=="")return e;let t=bt("auth.serverUrl");return t!==void 0?t:ks}var wt="1.9.1-rc.1",ue=class{constructor(t){this.getSessionToken=t;this.baseUrl=Nn()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!G()){let r=t.headers.get("X-Latest-Version"),s=t.headers.get("X-Update-Message");r&&kn(r,wt)&&(this.lastSignals.updateAvailable={version:r,message:s||`Update available: v${r}. Run: npm install -g @visa/cli && visa-cli setup`})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return wt}async request(t,n,r,s,o){let i=await this.getSessionToken();if(!i)throw new Error("Not logged in. Sign up at https://visacli.sh or run: visa-cli setup");let a={Authorization:`Bearer ${i}`};o&&(t==="GET"?a["X-User-Context"]=o.replace(/[\r\n\0]/g," ").slice(0,1e3):r={...r||{},user_context:o}),r&&(a["Content-Type"]="application/json");let c;try{c=await _n(`${this.baseUrl}${n}`,{method:t,headers:{...a,"X-Visa-CLI-Version":wt},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(u){throw u.name==="AbortError"||u.message?.includes("aborted")?new Error("The request timed out. The server may be under heavy load. Please try again."):new Error("Cannot reach the Visa CLI server. Check your internet connection and try again.")}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let u=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${u}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let l;try{l=await c.json()}catch{throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(l?.error||`Request failed (${c.status}). Try again.`);return l}async pay(t,n){return this.request("POST","/v1/pay",t,void 0,n)}async shortcut(t,n,r,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s)}async batch(t,n,r){return this.request("POST","/v1/batch",t,n,r)}async catalogSearch(t,n){let r=new URLSearchParams;t&&r.set("q",t),n&&r.set("category",n);let s=r.toString();return this.request("GET",`/v1/catalog${s?`?${s}`:""}`)}async catalogTool(t){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`)}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getTransactions(t){return this.request("GET","/v1/transactions",void 0,void 0,t)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t){return this.request("POST","/v1/attestation-key",{publicKey:t})}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var $t=require("child_process"),Hn=require("util"),Vn=h(require("crypto")),T=h(require("fs")),Fn=h(require("os")),W=h(require("path"));var O=h(require("fs")),kt=h(require("path")),On=h(require("os")),Ct=kt.join(On.homedir(),".visa-mcp"),Se=kt.join(Ct,"mcp-server.log"),xs=5*1024*1024,_t=null;function $s(){O.existsSync(Ct)||O.mkdirSync(Ct,{recursive:!0,mode:448})}function Es(){if(!_t){if($s(),O.existsSync(Se)&&O.statSync(Se).size>xs){let t=Se+".1";O.existsSync(t)&&O.unlinkSync(t),O.renameSync(Se,t)}_t=O.createWriteStream(Se,{flags:"a"})}return _t}function Ve(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
34
+ `;process.stderr.write(s),Es().write(s)}var de={debug:(...e)=>Ve("DEBUG",...e),info:(...e)=>Ve("INFO",...e),warn:(...e)=>Ve("WARN",...e),error:(...e)=>Ve("ERROR",...e)};var fe=(0,Hn.promisify)($t.execFile),Ke=W.join(Fn.homedir(),".visa-mcp","bin"),se=W.join(Ke,"Visa CLI"),Ps=W.join(__dirname,"..","native"),Dn="5",Un=W.join(Ke,"visa-keychain.version"),Mn=W.join(Ke,"visa-keychain.sha256");function jn(e){let t=T.readFileSync(e);return Vn.createHash("sha256").update(t).digest("hex")}async function Bn(){try{if(T.readFileSync(Un,"utf-8").trim()===Dn&&T.existsSync(se)){let r=T.readFileSync(Mn,"utf-8").trim();if(jn(se)!==r)de.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),T.unlinkSync(se);else return se}}catch{}let e=W.join(Ps,"visa-keychain.m");if(T.existsSync(e)||(e=W.resolve(__dirname,"..","..","native","visa-keychain.m")),T.existsSync(e)||(e=W.resolve(__dirname,"..","native","visa-keychain.m")),!T.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");T.mkdirSync(Ke,{recursive:!0,mode:448});try{await fe("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",se,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=jn(se);return T.writeFileSync(Mn,t,{mode:384}),T.writeFileSync(Un,Dn,{mode:384}),se}async function Kn(e){let t=await Bn(),n;try{n=(await fe(t,e,{timeout:6e4})).stdout}catch(o){n=o.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(o.stderr?.trim()||o.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let s=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(s)}var xt=null;function D(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:xt!==null?xt:(xt=!0,!0)}var Fe="visa-cli",Be="attestation-key";async function Ts(e){try{await fe("security",["delete-generic-password","-s",Fe,"-a",Be],{timeout:5e3})}catch{}await fe("security",["add-generic-password","-s",Fe,"-a",Be,"-w",e],{timeout:5e3})}async function Rs(){try{let{stdout:e}=await fe("security",["find-generic-password","-s",Fe,"-a",Be,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function qe(){let e=await Kn(["generate-key"]);if(!e)throw new Error("Key generation returned no output");let t=e.indexOf(":");if(t<0)throw new Error("Unexpected generate-key output format");let n=e.slice(0,t),r=e.slice(t+1);return await Ts(n),r}async function Et(e,t){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await Rs();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Bn(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,$t.execFile)(r,s,{timeout:6e4},(c,l)=>{let u=(l||"").trim();if(c){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}u.startsWith("OK:")?o(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function qn(){try{await fe("security",["delete-generic-password","-s",Fe,"-a",Be],{timeout:5e3})}catch{}try{await Kn(["delete-key"])}catch{}}function Gn(e,t=process.stderr){if(G()||!e?.updateAvailable)return!1;let{message:n}=e.updateAvailable;return n?(t.write(`
35
35
  \x1B[33m\u2191 ${n}\x1B[0m
36
- `),!0):!1}function Jn(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=Ds(e.spendingControls).dailyLimit,a=Math.max(0,ve(e.dailySpent)),c=i>0?Math.min(i,Math.max(0,ve(e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(Is),v=d.slice(0,3),w=Ls(d,3),C=(e.cards??[]).slice(0,3),f=r.latestVersion?Tt(r.latestVersion):"",b=r.updateCheckDisabled?"update checks disabled":f?`update available: v${f}`:"up to date",_=Math.round(l*100),E=te(e.status,e.enrolled?"approved":"not enrolled"),Y=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${E} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${b}`,`Spend meter: ${Gn(l)} ${String(_).padStart(3," ")}% | remaining ${pe(c)}/day | daily cap ${pe(i)}`,"","Spend",` Remaining ${pe(c)} / ${pe(i)}`,` Usage ${Gn(l)} ${_}%`,` Spent today ${pe(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...C.length>0?C.map(P=>` ${Os(P)}`):[" No cards enrolled"],"","Last 3 services",...w.length>0?w.map((P,X)=>` ${X+1}. ${P}`):[" No paid services yet"],"","Recent receipts",...v.length>0?v.map(P=>` ${Ns(P)}`):[" No receipts yet"]];return r.updateMessage&&Y.push("",`Update: ${Tt(r.updateMessage)}`),`${Y.join(`
36
+ `),!0):!1}function Jn(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=Us(e.spendingControls).dailyLimit,a=Math.max(0,ve(e.dailySpent)),c=i>0?Math.min(i,Math.max(0,ve(e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(Ls),S=d.slice(0,3),w=Ns(d,3),C=(e.cards??[]).slice(0,3),f=r.latestVersion?Tt(r.latestVersion):"",_=r.updateCheckDisabled?"update checks disabled":f?`update ready: v${f}`:"up to date",b=Math.round(l*100),I=te(e.status,e.enrolled?"approved":"not enrolled"),J=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${I} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${_}`,`Spend meter: ${Wn(l)} ${String(b).padStart(3," ")}% | remaining ${pe(c)}/day | daily cap ${pe(i)}`,"","Spend",` Remaining ${pe(c)} / ${pe(i)}`,` Usage ${Wn(l)} ${b}%`,` Spent today ${pe(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...C.length>0?C.map(L=>` ${Ds(L)}`):[" No cards enrolled"],"","Last 3 services",...w.length>0?w.map((L,X)=>` ${X+1}. ${L}`):[" No paid services yet"],"","Recent receipts",...S.length>0?S.map(L=>` ${Os(L)}`):[" No receipts yet"]];return r.updateMessage&&J.push("",`Update: ${Tt(r.updateMessage)}`),`${J.join(`
37
37
  `)}
38
- `}function Rs(e){return e.tool_name!=null}function As(e){return ve(e.amount)===0&&e.status==="failed"}function Is(e){return Rs(e)&&!As(e)}function Ls(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=te(s.merchant_name,"Unknown merchant"),i=te(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function Ns(e){let t=te(e.merchant_name,"Unknown merchant"),n=te(e.tool_name,"unknown_tool"),r=pe(ve(e.amount)),s=te(e.status,"unknown"),o=Us(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function Os(e){let t=te(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${Number.isInteger(e.id)?`#${e.id} `:""}${t} ****${e.last4}${n}`}function Ds(e){return{dailyLimit:ve(e?.daily_limit??e?.dailyLimit??0)}}function ve(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function pe(e){return`$${e.toFixed(2)}`}function Gn(e,t=20){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function te(e,t){let n=Tt(e??"").trim();return n.length>0?n:t}function Us(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?te(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function Tt(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ")}var S=h(require("fs")),ze=h(require("os")),x=h(require("path")),Yn=require("child_process"),Ms=2,qe="# >>> visa-cli shell hud v2 >>>",We="# <<< visa-cli shell hud v2 <<<",js="# >>> visa-cli shell hud >>>",Hs="# <<< visa-cli shell hud <<<",Xn=3e4,Vs=3e4;function Lt(){try{return x.join(nr(),".visa-cli")}catch{return x.join(ze.tmpdir(),".visa-cli")}}function we(){return x.join(Lt(),"shell-hud.json")}function Ye(){return x.join(Lt(),"shell-hud.line")}function Zn(){return x.join(Lt(),"shell-hud.lock")}function Xe(e){let t=e??process.env.SHELL;if(!t)return null;let n=x.basename(t.replace(/\\/g,"/")).toLowerCase();return n==="zsh"?"zsh":n==="bash"?"bash":n==="pwsh"||n==="pwsh.exe"||n==="powershell"||n==="powershell.exe"?"powershell":null}function Ze(e){let t=nr();if(e==="zsh")return x.join(t,".zshrc");if(e==="bash")return x.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return x.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Fs(e){let t="$HOME/.visa-cli/shell-hud.line",n=Js(e),r=zs(e);if(e==="zsh")return`${qe}
38
+ `}function As(e){return e.tool_name!=null}function Is(e){return ve(e.amount)===0&&e.status==="failed"}function Ls(e){return As(e)&&!Is(e)}function Ns(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=te(s.merchant_name,"Unknown merchant"),i=te(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function Os(e){let t=te(e.merchant_name,"Unknown merchant"),n=te(e.tool_name,"unknown_tool"),r=pe(ve(e.amount)),s=te(e.status,"unknown"),o=Ms(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function Ds(e){let t=te(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${Number.isInteger(e.id)?`#${e.id} `:""}${t} ****${e.last4}${n}`}function Us(e){return{dailyLimit:ve(e?.daily_limit??e?.dailyLimit??0)}}function ve(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function pe(e){return`$${e.toFixed(2)}`}function Wn(e,t=20){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function te(e,t){let n=Tt(e??"").trim();return n.length>0?n:t}function Ms(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?te(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function Tt(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ")}var v=h(require("fs")),ze=h(require("os")),x=h(require("path")),Yn=require("child_process"),js=2,Ge="# >>> visa-cli shell hud v2 >>>",We="# <<< visa-cli shell hud v2 <<<",Hs="# >>> visa-cli shell hud >>>",Vs="# <<< visa-cli shell hud <<<",Xn=3e4,Fs=3e4;function Lt(){try{return x.join(nr(),".visa-cli")}catch{return x.join(ze.tmpdir(),".visa-cli")}}function we(){return x.join(Lt(),"shell-hud.json")}function Ye(){return x.join(Lt(),"shell-hud.line")}function Zn(){return x.join(Lt(),"shell-hud.lock")}function Xe(e){let t=e??process.env.SHELL;if(!t)return null;let n=x.basename(t.replace(/\\/g,"/")).toLowerCase();return n==="zsh"?"zsh":n==="bash"?"bash":n==="pwsh"||n==="pwsh.exe"||n==="powershell"||n==="powershell.exe"?"powershell":null}function Ze(e){let t=nr();if(e==="zsh")return x.join(t,".zshrc");if(e==="bash")return x.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return x.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Bs(e){let t="$HOME/.visa-cli/shell-hud.line",n=Ys(e),r=Xs(e);if(e==="zsh")return`${Ge}
39
39
  _visa_cli_shell_hud_precmd() {
40
40
  setopt localoptions no_bg_nice
41
41
  if [[ -f "${t}" ]]; then
@@ -52,7 +52,7 @@ autoload -Uz add-zsh-hook
52
52
  if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
53
53
  add-zsh-hook precmd _visa_cli_shell_hud_precmd
54
54
  fi
55
- ${We}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${qe}
55
+ ${We}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${Ge}
56
56
  if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
57
57
  $function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
58
58
  }
@@ -71,7 +71,7 @@ function global:prompt {
71
71
  }
72
72
  & $function:global:__visa_cli_original_prompt
73
73
  }
74
- ${We}`}return`${qe}
74
+ ${We}`}return`${Ge}
75
75
  __visa_cli_shell_hud_precmd() {
76
76
  if [ -f "${t}" ]; then
77
77
  cat "${t}"
@@ -88,18 +88,18 @@ case ";$PROMPT_COMMAND;" in
88
88
  *";__visa_cli_shell_hud_precmd;"*) ;;
89
89
  *) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
90
90
  esac
91
- ${We}`}function Qn(e){let t=e;for(let[n,r]of[[qe,We],[js,Hs]])t=t.replace(new RegExp(`\\n?${zn(n)}[\\s\\S]*?${zn(r)}\\n?`,"g"),"");return t.trimEnd()}function Bs(e,t){let n=Qn(e).trimEnd(),r=Fs(t);return n.length>0?`${n}
91
+ ${We}`}function Qn(e){let t=e;for(let[n,r]of[[Ge,We],[Hs,Vs]])t=t.replace(new RegExp(`\\n?${zn(n)}[\\s\\S]*?${zn(r)}\\n?`,"g"),"");return t.trimEnd()}function Ks(e,t){let n=Qn(e).trimEnd(),r=Bs(t);return n.length>0?`${n}
92
92
 
93
93
  ${r}
94
94
  `:`${r}
95
- `}function Nt(e=Xe()){if(!e)return{installed:!1,changed:!1,shell:null,message:"Shell HUD auto-install skipped: supported shells are zsh, bash, and PowerShell."};let t;try{t=Ze(e);let n=S.existsSync(t)?S.readFileSync(t,"utf-8"):"",r=Bs(n,e),s=r!==n;return s&&Je(t,r),{installed:!0,changed:s,shell:e,rcPath:t,message:s?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${rr(n)}`}}}function Ot(e=Xe()){if(!e)return{removed:!1,shell:null,message:"Shell HUD uninstall skipped: supported shells are zsh, bash, and PowerShell."};let t;try{if(t=Ze(e),!S.existsSync(t))return{removed:!1,shell:e,rcPath:t,message:`No ${e} rc file found at ${t}.`};let n=S.readFileSync(t,"utf-8"),r=Qn(n);return r===n.trimEnd()?{removed:!1,shell:e,rcPath:t,message:`Persistent shell HUD was not installed in ${t}.`}:(Je(t,r.length>0?`${r}
96
- `:""),{removed:!0,shell:e,rcPath:t,message:`Removed persistent shell HUD from ${t}.`})}catch(n){return{removed:!1,shell:e,rcPath:t,message:`Failed to remove persistent shell HUD from ${t}: ${rr(n)}`}}}function Dt(e,t){let n=t.currentVersion==="0.0.0"&&e.version?e.version:t.currentVersion,r=Ge(n),s=` ${V("\u2502",M.dim)} `;if(!e.enrolled)return`${V("VISA CLI",M.visaBlue)} ${V(`v${r}`,M.visaBlueSoft)}${s}${V("setup needed",M.visaGold)}`;let o=Rt(e.spendingControls?.daily_limit??e.spendingControls?.dailyLimit),i=Math.max(0,Rt(e.dailySpent)),a=o>0?Math.min(o,Math.max(0,Rt(e.dailyRemaining??o-i))):0,c=o>0?Math.max(0,Math.min(1,i/o)):0,l=Ws(e),u=o>0?`${qs(c)} ${V(`${At(a)} left today`,M.green)} ${V(`(${At(i)}/${At(o)}/day)`,M.dim)}`:V("no spend limit",M.dim);return`${V("VISA CLI",M.visaBlue)} ${V(`v${r}`,M.visaBlueSoft)}${s}${V(l,M.visaGold)}${s}${u}`}function er(){let e=tr();return!!e&&Date.now()-e.renderedAt<=Xn}function Ut(){let e=tr();if(e&&Date.now()-e.renderedAt<=Xn||(Ks(),e?.line))return e.line;try{let t=Ye();if(S.existsSync(t))return S.readFileSync(t,"utf-8").trimEnd()}catch{}return"VISA | loading spend HUD\u2026"}function Mt(e){try{let t=x.dirname(we());S.mkdirSync(t,{recursive:!0});let n=Ge(e),r={hudVersion:Ms,renderedAt:Date.now(),line:n};Je(we(),JSON.stringify(r)+`
95
+ `}function Nt(e=Xe()){if(!e)return{installed:!1,changed:!1,shell:null,message:"Shell HUD auto-install skipped: supported shells are zsh, bash, and PowerShell."};let t;try{t=Ze(e);let n=v.existsSync(t)?v.readFileSync(t,"utf-8"):"",r=Ks(n,e),s=r!==n;return s&&Je(t,r),{installed:!0,changed:s,shell:e,rcPath:t,message:s?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${rr(n)}`}}}function Ot(e=Xe()){if(!e)return{removed:!1,shell:null,message:"Shell HUD uninstall skipped: supported shells are zsh, bash, and PowerShell."};let t;try{if(t=Ze(e),!v.existsSync(t))return{removed:!1,shell:e,rcPath:t,message:`No ${e} rc file found at ${t}.`};let n=v.readFileSync(t,"utf-8"),r=Qn(n);return r===n.trimEnd()?{removed:!1,shell:e,rcPath:t,message:`Persistent shell HUD was not installed in ${t}.`}:(Je(t,r.length>0?`${r}
96
+ `:""),{removed:!0,shell:e,rcPath:t,message:`Removed persistent shell HUD from ${t}.`})}catch(n){return{removed:!1,shell:e,rcPath:t,message:`Failed to remove persistent shell HUD from ${t}: ${rr(n)}`}}}function Dt(e,t){let n=t.currentVersion==="0.0.0"&&e.version?e.version:t.currentVersion,r=_e(n),s=` ${U("\u2502",A.dim)} `,o=qs(t);if(!e.enrolled)return[`${U("VISA CLI",A.visaBlue)} ${U(`v${r}`,A.visaBlueSoft)}`,U("setup needed",A.visaGold),o].filter(Boolean).join(s);let i=Rt(e.spendingControls?.daily_limit??e.spendingControls?.dailyLimit),a=Math.max(0,Rt(e.dailySpent)),c=i>0?Math.min(i,Math.max(0,Rt(e.dailyRemaining??i-a))):0,l=i>0?Math.max(0,Math.min(1,a/i)):0,u=Js(e),d=i>0?`${Ws(l)} ${U(`${At(c)} left today`,A.green)} ${U(`(${At(a)}/${At(i)}/day)`,A.dim)}`:U("no spend limit",A.dim);return[`${U("VISA CLI",A.visaBlue)} ${U(`v${r}`,A.visaBlueSoft)}`,U(u,A.visaGold),d,o].filter(Boolean).join(s)}function qs(e){let t=e.latestVersion?_e(e.latestVersion):"";return t?U(`update ready v${t}`,A.visaGold):e.updateMessage?U("update ready",A.visaGold):null}function er(){let e=tr();return!!e&&Date.now()-e.renderedAt<=Xn}function Ut(){let e=tr();if(e&&Date.now()-e.renderedAt<=Xn||(Gs(),e?.line))return e.line;try{let t=Ye();if(v.existsSync(t))return v.readFileSync(t,"utf-8").trimEnd()}catch{}return"VISA | loading spend HUD\u2026"}function Mt(e){try{let t=x.dirname(we());v.mkdirSync(t,{recursive:!0});let n=_e(e),r={hudVersion:js,renderedAt:Date.now(),line:n};Je(we(),JSON.stringify(r)+`
97
97
  `),Je(Ye(),n+`
98
- `)}catch{}}function be(){try{S.unlinkSync(Zn())}catch{}}function tr(){let e=we();if(!S.existsSync(e))return null;try{return JSON.parse(S.readFileSync(e,"utf-8"))}catch{return null}}function Ks(){if(process.env.JEST_WORKER_ID)return;let e=Zn();try{if(S.mkdirSync(x.dirname(e),{recursive:!0}),!Ys(e))return;let t=process.argv[1]?x.resolve(process.argv[1]):"";if(!t){be();return}let n=(0,Yn.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",be),n.unref()}catch{be()}}function Rt(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Ge(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()}function qs(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${V(r||"",M.green)}${V(s||"",M.dim)}`}function At(e){return`$${e.toFixed(2)}`}function Ws(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=Ge(n.toUpperCase()),o=Ge(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function Gs(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var It=Gs(),M={reset:"\x1B[0m",visaBlue:It?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:It?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:It?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function V(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${M.reset}`}function zn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nr(){let e=ze.homedir();if(!e||!x.isAbsolute(e))throw new Error("unable to determine a valid home directory");return x.resolve(e)}function Js(e){return e==="powershell"?"& visa-cli shell-hud refresh":"visa-cli shell-hud refresh"}function zs(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Ys(e){for(let t=0;t<2;t+=1){let n;try{return n=S.openSync(e,"wx"),S.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=S.statSync(e);if(Date.now()-s.mtimeMs<=Vs)return!1;S.unlinkSync(e)}catch{}}finally{n!==void 0&&S.closeSync(n)}}return!1}function rr(e){return e instanceof Error?e.message:"unknown file system error"}function Je(e,t){S.mkdirSync(x.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;S.writeFileSync(n,t),S.renameSync(n,e)}async function jt(e,t){try{return await t()}catch(n){if(n.message==="Invalid signature"&&O()){de.warn("attestation:key-mismatch",{action:"reregistering"});try{let r=await Ke();await e.registerAttestationKey(r),de.info("attestation:key-reregistered")}catch(r){throw de.error("attestation:reregister-failure",{error:r.message}),n}return await t()}throw n}}var sr="1.9.0-rc.1";function Ht(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Xs(e,t,n){let r=process.env[e];if(r!==void 0&&r!=="")return{value:r,source:{kind:"env",var:e}};let s=bt(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n,source:{kind:"default"}}}function _e(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=Rn(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function j(e){return e==null?"\u2014":e?"yes":"no"}function Qe(e){return e==null?"\u2014":`$${e.toFixed(2)}`}async function or(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(_){n=_?.message||"unknown error"}let r=[],s=Xs("VISA_AUTH_URL","auth.serverUrl","https://auth.visacli.sh");r.push({key:"auth.serverUrl",value:s.value,formatted:s.value,source:s.source,hint:s.source.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:j(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}});let o=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:o,formatted:j(o),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:o===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:j(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:O(),formatted:j(O()),source:{kind:"device"}});let i=t?.spendingControls,a=i?i.max_transaction_amount??i.maxTransactionAmount??null:null,c=i?i.daily_limit??i.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:a,formatted:Qe(a),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:c,formatted:Qe(c),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Qe(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Qe(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let l=t?.cards?.find(_=>_.isDefault)??t?.cards?.[0];l&&r.push({key:"cards.default",value:{brand:l.brand??null,last4:l.last4},formatted:`${l.brand||"card"} \u2022\u2022\u2022\u2022 ${l.last4}`,source:{kind:"server"}});let u=_e("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:u.value,formatted:j(u.value),source:u.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let d=_e("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:d.value,formatted:j(d.value),source:d.source});let v=W(),w;process.env.VISA_CLI_NO_UPDATE_CHECK?w={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?w={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?w={kind:"env",var:"NODE_ENV"}:w={kind:"default"},r.push({key:"ui.updateCheck",value:!v,formatted:j(!v),source:w});let C=_e("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:C.value,formatted:j(C.value),source:C.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let f=_e("VISA_SPECIFIC_TOOLS","tools.specific","opt-out");r.push({key:"tools.specific",value:f.value,formatted:j(f.value),source:f.source});let b=_e("VISA_DISCOVER_TOOLS","tools.discover","opt-out");if(r.push({key:"tools.discover",value:b.value,formatted:j(b.value),source:b.source}),r.push({key:"client.version",value:sr,formatted:sr,source:{kind:"default"}}),e.includeDev){let _=process.env.VISA_MOCK_KEYCHAIN;r.push({key:"dev.mockKeychain",value:_==="true",formatted:j(_==="true"),source:Ht("VISA_MOCK_KEYCHAIN",!!_)});let E=process.env.VISA_MOCK_TOUCHID;r.push({key:"dev.mockTouchid",value:E==="true",formatted:j(E==="true"),source:Ht("VISA_MOCK_TOUCHID",!!E)});let R=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!R,formatted:j(!!R),source:Ht("VISA_CLI_DEBUG",!!R)})}return{entries:r,statusError:n}}function Zs(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"settings":return"settings.json";case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function ir(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${Zs(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
99
- `)}function ar(e){return JSON.stringify({config:e.entries.map(t=>({key:t.key,value:t.value,source:t.source,hint:t.hint})),statusError:e.statusError},null,2)}var D=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},cr=["GET","POST"];function lr(e){let t;try{t=new URL(e)}catch{throw new D(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new D(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}function ur(e){let t=(e??"GET").toUpperCase();if(!cr.includes(t))throw new D(`Unsupported HTTP method "${e}". Supported: ${cr.join(", ")}.`);return t}function dr(e){if(e!==void 0){try{JSON.parse(e)}catch(t){throw new D(`--body is not valid JSON: ${t?.message??"parse error"}`)}return e}}function fr(e){if(!e||typeof e!="object")throw new D("Merchant returned no payment preview.");let t=e;if(typeof t.amount!="number"||!Number.isFinite(t.amount)||t.amount<=0)throw new D("Could not determine payment amount from merchant.");if(typeof t.merchantName!="string"||t.merchantName.trim().length===0)throw new D("Merchant returned an empty merchant name.");if(t.merchantName.length>200)throw new D(`Merchant name too long (${t.merchantName.length} chars).`);if(typeof t.currency!="string"||t.currency.trim().length===0)throw new D("Merchant returned an empty currency.");if(t.currency.length>10)throw new D(`Currency code too long (${t.currency.length} chars).`);return{amount:t.amount,currency:t.currency,merchantName:t.merchantName}}var y=h(require("fs")),g=h(require("path")),pr=h(require("os")),k=pr.homedir(),Qs=["Claude_","Anthropic.ClaudeDesktop_"],me=class extends Error{constructor(n,r,s){super(to(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function mr(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
100
- `)}function eo(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=mr(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function to(e,t,n){let r=t.replace(k,"~"),s=mr(n).split(`
101
- `).find(Boolean),o=s?` (${s})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${o}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${o}.`}function gr(){return process.env.APPDATA||g.join(k,"AppData","Roaming")}function no(){return process.env.LOCALAPPDATA||g.join(k,"AppData","Local")}function hr(){if(process.platform!=="win32")return;let e=g.join(no(),"Packages");if(y.existsSync(e))try{let t=y.readdirSync(e,"utf-8");for(let n of Qs){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return g.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function yr(){if(process.platform==="win32"){let e=hr();return e?g.join(e,"claude_desktop_config.json"):g.join(gr(),"Claude","claude_desktop_config.json")}return g.join(k,"Library","Application Support","Claude","claude_desktop_config.json")}function Sr(){if(process.platform!=="win32")return[g.join(k,"Library","Application Support","Claude")];let e=[g.join(gr(),"Claude")],t=hr();return t&&e.push(t),e}function et(e){return e.id==="claude-desktop"?yr():e.globalConfigPath}function ro(e){return e.id==="claude-desktop"?Sr():e.detectPaths}var B=[{id:"claude",displayName:"Claude Code",globalConfigPath:g.join(k,".claude.json"),configKey:"mcpServers",detectPaths:[g.join(k,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:yr(),configKey:"mcpServers",detectPaths:Sr(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:g.join(k,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[g.join(k,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:g.join(k,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[g.join(k,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:g.join(k,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[g.join(k,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:g.join(k,".config","Roo","mcp_settings.json"),configKey:"mcpServers",detectPaths:[g.join(k,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:g.join(k,".vscode","mcp.json"),configKey:"servers",detectPaths:[g.join(k,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:g.join(k,".config","zed","settings.json"),configKey:"context_servers",detectPaths:[g.join(k,".config","zed")],postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:g.join(k,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[g.join(k,".codex")],postInstallHint:"Restart Codex to connect. For the terminal HUD, run: visa-cli hud enable codex"}];function Vt(e){return B.find(t=>t.id===e)}function Ce(e){return ro(e).some(t=>{if(t.includes("*")){let n=g.dirname(t),r=g.basename(t).replaceAll("*","");if(!y.existsSync(n))return!1;try{return y.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return y.existsSync(t)})}function vr(){return{command:"node",args:[g.resolve(__dirname,"mcp-server/index.js")]}}function Ft(e,t){return t==="project"?"json":e.configFormat??"json"}function so(e){if(e=e.trim(),e==="true")return!0;if(e==="false")return!1;if(e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);if(e.startsWith("[")&&e.endsWith("]")){let n=e.slice(1,-1).trim();return n.length===0?[]:n.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r)}let t=Number(e);return isNaN(t)?e:t}function Bt(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(o=>o.trim()===n);if(r===-1)return;let s=r+1;for(;s<e.length&&!e[s].trim().startsWith("[");)s++;return{start:r,end:s}}function Kt(e,t){let n=e.split(`
102
- `),r=Bt(n,t);if(!r)return;let s={};for(let o=r.start+1;o<r.end;o++){let i=n[o].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(s[i[1]]=so(i[2]))}return Object.keys(s).length>0?s:void 0}function oo(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
98
+ `)}catch{}}function be(){try{v.unlinkSync(Zn())}catch{}}function tr(){let e=we();if(!v.existsSync(e))return null;try{return JSON.parse(v.readFileSync(e,"utf-8"))}catch{return null}}function Gs(){if(process.env.JEST_WORKER_ID)return;let e=Zn();try{if(v.mkdirSync(x.dirname(e),{recursive:!0}),!Zs(e))return;let t=process.argv[1]?x.resolve(process.argv[1]):"";if(!t){be();return}let n=(0,Yn.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",be),n.unref()}catch{be()}}function Rt(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function _e(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()}function Ws(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${U(r||"",A.green)}${U(s||"",A.dim)}`}function At(e){return`$${e.toFixed(2)}`}function Js(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=_e(n.toUpperCase()),o=_e(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function zs(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var It=zs(),A={reset:"\x1B[0m",visaBlue:It?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:It?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:It?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function U(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${A.reset}`}function zn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nr(){let e=ze.homedir();if(!e||!x.isAbsolute(e))throw new Error("unable to determine a valid home directory");return x.resolve(e)}function Ys(e){return e==="powershell"?"& visa-cli shell-hud refresh":"visa-cli shell-hud refresh"}function Xs(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Zs(e){for(let t=0;t<2;t+=1){let n;try{return n=v.openSync(e,"wx"),v.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=v.statSync(e);if(Date.now()-s.mtimeMs<=Fs)return!1;v.unlinkSync(e)}catch{}}finally{n!==void 0&&v.closeSync(n)}}return!1}function rr(e){return e instanceof Error?e.message:"unknown file system error"}function Je(e,t){v.mkdirSync(x.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;v.writeFileSync(n,t),v.renameSync(n,e)}async function jt(e,t){try{return await t()}catch(n){if(n.message==="Invalid signature"&&D()){de.warn("attestation:key-mismatch",{action:"reregistering"});try{let r=await qe();await e.registerAttestationKey(r),de.info("attestation:key-reregistered")}catch(r){throw de.error("attestation:reregister-failure",{error:r.message}),n}return await t()}throw n}}var sr="1.9.1-rc.1";function Ht(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Qs(e,t,n){let r=process.env[e];if(r!==void 0&&r!=="")return{value:r,source:{kind:"env",var:e}};let s=bt(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n,source:{kind:"default"}}}function Ce(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=Rn(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function H(e){return e==null?"\u2014":e?"yes":"no"}function Qe(e){return e==null?"\u2014":`$${e.toFixed(2)}`}async function or(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(b){n=b?.message||"unknown error"}let r=[],s=Qs("VISA_AUTH_URL","auth.serverUrl","https://auth.visacli.sh");r.push({key:"auth.serverUrl",value:s.value,formatted:s.value,source:s.source,hint:s.source.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:H(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}});let o=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:o,formatted:H(o),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:o===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:H(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:D(),formatted:H(D()),source:{kind:"device"}});let i=t?.spendingControls,a=i?i.max_transaction_amount??i.maxTransactionAmount??null:null,c=i?i.daily_limit??i.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:a,formatted:Qe(a),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:c,formatted:Qe(c),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Qe(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Qe(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let l=t?.cards?.find(b=>b.isDefault)??t?.cards?.[0];l&&r.push({key:"cards.default",value:{brand:l.brand??null,last4:l.last4},formatted:`${l.brand||"card"} \u2022\u2022\u2022\u2022 ${l.last4}`,source:{kind:"server"}});let u=Ce("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:u.value,formatted:H(u.value),source:u.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let d=Ce("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:d.value,formatted:H(d.value),source:d.source});let S=G(),w;process.env.VISA_CLI_NO_UPDATE_CHECK?w={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?w={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?w={kind:"env",var:"NODE_ENV"}:w={kind:"default"},r.push({key:"ui.updateCheck",value:!S,formatted:H(!S),source:w});let C=Ce("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:C.value,formatted:H(C.value),source:C.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let f=Ce("VISA_SPECIFIC_TOOLS","tools.specific","opt-out");r.push({key:"tools.specific",value:f.value,formatted:H(f.value),source:f.source});let _=Ce("VISA_DISCOVER_TOOLS","tools.discover","opt-out");if(r.push({key:"tools.discover",value:_.value,formatted:H(_.value),source:_.source}),r.push({key:"client.version",value:sr,formatted:sr,source:{kind:"default"}}),e.includeDev){let b=process.env.VISA_MOCK_KEYCHAIN;r.push({key:"dev.mockKeychain",value:b==="true",formatted:H(b==="true"),source:Ht("VISA_MOCK_KEYCHAIN",!!b)});let I=process.env.VISA_MOCK_TOUCHID;r.push({key:"dev.mockTouchid",value:I==="true",formatted:H(I==="true"),source:Ht("VISA_MOCK_TOUCHID",!!I)});let P=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!P,formatted:H(!!P),source:Ht("VISA_CLI_DEBUG",!!P)})}return{entries:r,statusError:n}}function eo(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"settings":return"settings.json";case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function ir(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${eo(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
99
+ `)}function ar(e){return JSON.stringify({config:e.entries.map(t=>({key:t.key,value:t.value,source:t.source,hint:t.hint})),statusError:e.statusError},null,2)}var M=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},cr=["GET","POST"];function lr(e){let t;try{t=new URL(e)}catch{throw new M(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new M(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}function ur(e){let t=(e??"GET").toUpperCase();if(!cr.includes(t))throw new M(`Unsupported HTTP method "${e}". Supported: ${cr.join(", ")}.`);return t}function dr(e){if(e!==void 0){try{JSON.parse(e)}catch(t){throw new M(`--body is not valid JSON: ${t?.message??"parse error"}`)}return e}}function fr(e){if(!e||typeof e!="object")throw new M("Merchant returned no payment preview.");let t=e;if(typeof t.amount!="number"||!Number.isFinite(t.amount)||t.amount<=0)throw new M("Could not determine payment amount from merchant.");if(typeof t.merchantName!="string"||t.merchantName.trim().length===0)throw new M("Merchant returned an empty merchant name.");if(t.merchantName.length>200)throw new M(`Merchant name too long (${t.merchantName.length} chars).`);if(typeof t.currency!="string"||t.currency.trim().length===0)throw new M("Merchant returned an empty currency.");if(t.currency.length>10)throw new M(`Currency code too long (${t.currency.length} chars).`);return{amount:t.amount,currency:t.currency,merchantName:t.merchantName}}var y=h(require("fs")),g=h(require("path")),pr=h(require("os")),k=pr.homedir(),to=["Claude_","Anthropic.ClaudeDesktop_"],me=class extends Error{constructor(n,r,s){super(ro(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function mr(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
100
+ `)}function no(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=mr(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function ro(e,t,n){let r=t.replace(k,"~"),s=mr(n).split(`
101
+ `).find(Boolean),o=s?` (${s})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${o}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${o}.`}function gr(){return process.env.APPDATA||g.join(k,"AppData","Roaming")}function so(){return process.env.LOCALAPPDATA||g.join(k,"AppData","Local")}function hr(){if(process.platform!=="win32")return;let e=g.join(so(),"Packages");if(y.existsSync(e))try{let t=y.readdirSync(e,"utf-8");for(let n of to){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return g.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function yr(){if(process.platform==="win32"){let e=hr();return e?g.join(e,"claude_desktop_config.json"):g.join(gr(),"Claude","claude_desktop_config.json")}return g.join(k,"Library","Application Support","Claude","claude_desktop_config.json")}function Sr(){if(process.platform!=="win32")return[g.join(k,"Library","Application Support","Claude")];let e=[g.join(gr(),"Claude")],t=hr();return t&&e.push(t),e}function et(e){return e.id==="claude-desktop"?yr():e.globalConfigPath}function oo(e){return e.id==="claude-desktop"?Sr():e.detectPaths}var B=[{id:"claude",displayName:"Claude Code",globalConfigPath:g.join(k,".claude.json"),configKey:"mcpServers",detectPaths:[g.join(k,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:yr(),configKey:"mcpServers",detectPaths:Sr(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:g.join(k,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[g.join(k,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:g.join(k,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[g.join(k,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:g.join(k,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[g.join(k,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:g.join(k,".config","Roo","mcp_settings.json"),configKey:"mcpServers",detectPaths:[g.join(k,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:g.join(k,".vscode","mcp.json"),configKey:"servers",detectPaths:[g.join(k,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:g.join(k,".config","zed","settings.json"),configKey:"context_servers",detectPaths:[g.join(k,".config","zed")],postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:g.join(k,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[g.join(k,".codex")],postInstallHint:"Restart Codex to connect. For the terminal HUD, run: visa-cli hud enable codex"}];function Vt(e){return B.find(t=>t.id===e)}function ke(e){return oo(e).some(t=>{if(t.includes("*")){let n=g.dirname(t),r=g.basename(t).replaceAll("*","");if(!y.existsSync(n))return!1;try{return y.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return y.existsSync(t)})}function vr(){return{command:"node",args:[g.resolve(__dirname,"mcp-server/index.js")]}}function Ft(e,t){return t==="project"?"json":e.configFormat??"json"}function io(e){if(e=e.trim(),e==="true")return!0;if(e==="false")return!1;if(e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);if(e.startsWith("[")&&e.endsWith("]")){let n=e.slice(1,-1).trim();return n.length===0?[]:n.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r)}let t=Number(e);return isNaN(t)?e:t}function Bt(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(o=>o.trim()===n);if(r===-1)return;let s=r+1;for(;s<e.length&&!e[s].trim().startsWith("[");)s++;return{start:r,end:s}}function Kt(e,t){let n=e.split(`
102
+ `),r=Bt(n,t);if(!r)return;let s={};for(let o=r.start+1;o<r.end;o++){let i=n[o].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(s[i[1]]=io(i[2]))}return Object.keys(s).length>0?s:void 0}function ao(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
103
103
  `),i=Bt(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
104
104
  `);return c.endsWith(`
105
105
  `)?c:c+`
@@ -107,18 +107,21 @@ ${r}
107
107
 
108
108
  `:"")+s.join(`
109
109
  `)+`
110
- `}function io(e,t){let n=e.split(`
110
+ `}function co(e,t){let n=e.split(`
111
111
  `),r=Bt(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
112
112
  `).replace(/\n{3,}/g,`
113
113
 
114
- `)):e}function ke(e,t="global"){let n=t==="project"?g.join(process.cwd(),".mcp.json"):et(e);try{let r=g.dirname(n);y.existsSync(r)||y.mkdirSync(r,{recursive:!0});let s=Ft(e,t),o=vr();if(s==="toml"){let i=y.existsSync(n)?y.readFileSync(n,"utf-8"):"",a=oo(i,"visa-cli",o);y.writeFileSync(n,a)}else{let i={};if(y.existsSync(n))try{i=JSON.parse(y.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,y.writeFileSync(n,JSON.stringify(i,null,2)+`
115
- `)}}catch(r){throw eo(r)?new me(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function qt(e,t="global"){let n=t==="project"?g.join(process.cwd(),".mcp.json"):et(e);if(!y.existsSync(n))return{removed:!1,configPath:n};if(Ft(e,t)==="toml"){let i=y.readFileSync(n,"utf-8");return Kt(i,"visa-cli")?(y.writeFileSync(n,io(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(y.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=s[e.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],y.writeFileSync(n,JSON.stringify(s,null,2)+`
116
- `),{removed:!0,configPath:n})}function br(e,t="global"){let n=t==="project"?g.join(process.cwd(),".mcp.json"):et(e);if(!y.existsSync(n))return!1;if(Ft(e,t)==="toml")try{let s=y.readFileSync(n,"utf-8");return!!Kt(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(y.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function ao(e){if(!e||typeof e!="object")return;let t=e;if(t.command!=="node"||!Array.isArray(t.args)||t.args.length===0)return;let n=t.args[t.args.length-1];if(!(typeof n!="string"||n.length===0))return n}function co(e,t){if(e===t)return!0;let n=g.resolve(e),r=g.resolve(t);if(n===r)return!0;try{let s=y.realpathSync(n),o=y.realpathSync(r);return s===o}catch{return!1}}function xe(){let e=vr(),t=e.args[e.args.length-1],n=[];for(let r of B){let s=et(r);if(!y.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let l=y.readFileSync(s,"utf-8");i=Kt(l,"visa-cli")}catch{continue}else{let l;try{l=JSON.parse(y.readFileSync(s,"utf-8"))}catch{continue}i=l?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=ao(i);if(!a||co(a,t))continue;let c=y.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:c})}return n}function Wt(e){return{configPath:ke(e.client,"global").configPath}}var lo=(0,$r.promisify)(xr.execFile);function uo(e,t){return process.stdin.isTTY?new Promise(n=>{let r=kr.createInterface({input:process.stdin,output:process.stdout});r.question(e,s=>{r.close();let o=s.trim().toLowerCase();if(o===""){n(t);return}n(o==="y"||o==="yes")})}):Promise.resolve(t)}function fo(e){let t=U.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
117
- ${r}: ${n(e.currentPath)}`}function Er(e,t){if(e.length===0){console.log(`${t} \u2713 All MCP client configs are up to date.`);return}console.log(`${t} Found ${e.length} stale MCP config ${e.length===1?"entry":"entries"}:`);for(let n of e)console.log(fo(n))}function wr(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}var I=new _r.Command,tt=null,$e=!1;function K(){return tt=new ue(()=>$.getSessionToken()),tt}I.name("visa-cli").description("Visa CLI - AI payment orchestration").version(ut().version);I.hook("preAction",async()=>{await en()});I.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept all prompts (enable HUD etc) without asking \u2014 for CI/agent use").option("--no-hud","Skip the HUD install prompt (default: ask)").action(async e=>{try{if(e.check){let f=xe();Er(f,"MCP config check:"),f.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),process.exit(1));return}console.log("Step 1: Registering MCP server...");let t=xe(),n=new Map(t.map(f=>[f.client.id,f])),r=new Set,s=new Set,o=new Set;for(let f of B)if(Ce(f)){let b;try{b=ke(f)}catch(R){if(R instanceof me){wr(R),s.add(f.displayName),o.add(f.id);continue}throw R}let _=n.get(f.id),E=_?` \u2014 repaired stale ${_.staleReason} entry`:"";console.log(` \u2713 ${f.displayName} (${b.configPath.replace(U.homedir(),"~")})${E}`),_&&r.add(f.id)}let i=t.filter(f=>!r.has(f.client.id)&&!o.has(f.client.id)),a=0;for(let f of i){try{Wt(f)}catch(b){if(b instanceof me){wr(b),s.add(f.client.displayName),o.add(f.client.id);continue}throw b}console.log(` \u2713 ${f.client.displayName} (${f.configPath.replace(U.homedir(),"~")}) \u2014 repaired stale ${f.staleReason} entry`),a++}let c=r.size+a;c===0&&s.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):c>0&&console.log(` \u2713 Repaired ${c} stale MCP config ${c===1?"entry":"entries"}.`),s.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(s).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
118
- Step 2: Checking authentication...`);let l=await $.getSessionToken();if(l)try{await new ue(()=>Promise.resolve(l)).getStatus(),console.log(" Already authenticated.")}catch(f){let b=f instanceof Error?f.message:"";b.includes("session has expired")||b.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await $.clearAll(),l=null):console.log(` Couldn't verify session (${b||"unknown error"}) \u2014 continuing with existing token.`)}if(l||(console.log(" No session found. Opening browser for GitHub login..."),l=await new Promise(async(f,b)=>{let _=nt.randomBytes(16).toString("hex"),E=`https://auth.visacli.sh/login?state=${_}`;await nn(E);let R=3e4,Y=300*1e3,P=Date.now()+Y;for(;Date.now()<P;)try{let X=await globalThis.fetch("https://auth.visacli.sh/v1/auth-status",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:_,timeout:R}),signal:AbortSignal.timeout(R+5e3)});if(!X.ok)continue;let ae=await X.json();if(ae.status==="pending")continue;if(ae.status==="expired"){b(new Error("Session expired. Please run setup again."));return}if(ae.status==="complete"&&ae.sessionToken){console.log(` Signed in as ${ae.user}.`),f(ae.sessionToken);return}}catch{}b(new Error("Login timed out after 5 minutes. Please run setup again."))}),await $.saveSessionToken(l),console.log(" Session token saved.")),console.log(`
119
- Step 3: Setting up authentication...`),!O())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await lo("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}try{let f=await Ke();console.log(" Attestation key generated."),await K().registerAttestationKey(f),console.log(" Attestation key registered with server.")}catch(f){console.log(` Skipped: ${f.message}`)}}let u=oe.join(U.homedir(),".claude","settings.json"),d=Cr.existsSync(oe.join(U.homedir(),".claude.json")),v=e.hud===!1;if(d&&!v){console.log(`
120
- Step 4: Enable the Visa spend HUD?`),console.log(" Pins your spend + card info below the Claude Code input, so"),console.log(" you can see your spend, card, and session usage in real time.");let f;if(e.yes?(f=!0,console.log(" (--yes) Enabling Visa HUD.")):process.stdin.isTTY?f=await uo(" Enable Visa HUD? [Y/n] ",!0):(f=!1,console.log(" Non-interactive shell \u2014 skipping prompt. Enable with: visa-cli hud enable")),f){let b=Oe(u),_=b.installed==="new"||b.installed==="already-visa"||b.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${_}${b.message}`);try{let E=K(),R=await E.getStatus(),Y={currentVersion:E.getClientVersion(),latestVersion:E.lastSignals?.updateAvailable?.version,updateMessage:E.lastSignals?.updateAvailable?.message,updateCheckDisabled:W()},P=Dt(R,Y);Mt(P),console.log(` Preview: ${P.split(`
121
- `)[0]}`)}catch{}}else(e.yes===!1||process.stdin.isTTY)&&console.log(" Skipped. Enable any time with: visa-cli hud enable")}let w="\x1B[1m",C="\x1B[0m";console.log(`
114
+ `)):e}function xe(e,t="global"){let n=t==="project"?g.join(process.cwd(),".mcp.json"):et(e);try{let r=g.dirname(n);y.existsSync(r)||y.mkdirSync(r,{recursive:!0});let s=Ft(e,t),o=vr();if(s==="toml"){let i=y.existsSync(n)?y.readFileSync(n,"utf-8"):"",a=ao(i,"visa-cli",o);y.writeFileSync(n,a)}else{let i={};if(y.existsSync(n))try{i=JSON.parse(y.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,y.writeFileSync(n,JSON.stringify(i,null,2)+`
115
+ `)}}catch(r){throw no(r)?new me(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function qt(e,t="global"){let n=t==="project"?g.join(process.cwd(),".mcp.json"):et(e);if(!y.existsSync(n))return{removed:!1,configPath:n};if(Ft(e,t)==="toml"){let i=y.readFileSync(n,"utf-8");return Kt(i,"visa-cli")?(y.writeFileSync(n,co(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(y.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=s[e.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],y.writeFileSync(n,JSON.stringify(s,null,2)+`
116
+ `),{removed:!0,configPath:n})}function br(e,t="global"){let n=t==="project"?g.join(process.cwd(),".mcp.json"):et(e);if(!y.existsSync(n))return!1;if(Ft(e,t)==="toml")try{let s=y.readFileSync(n,"utf-8");return!!Kt(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(y.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function lo(e){if(!e||typeof e!="object")return;let t=e;if(t.command!=="node"||!Array.isArray(t.args)||t.args.length===0)return;let n=t.args[t.args.length-1];if(!(typeof n!="string"||n.length===0))return n}function uo(e,t){if(e===t)return!0;let n=g.resolve(e),r=g.resolve(t);if(n===r)return!0;try{let s=y.realpathSync(n),o=y.realpathSync(r);return s===o}catch{return!1}}function $e(){let e=vr(),t=e.args[e.args.length-1],n=[];for(let r of B){let s=et(r);if(!y.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let l=y.readFileSync(s,"utf-8");i=Kt(l,"visa-cli")}catch{continue}else{let l;try{l=JSON.parse(y.readFileSync(s,"utf-8"))}catch{continue}i=l?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=lo(i);if(!a||uo(a,t))continue;let c=y.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:c})}return n}function Gt(e){return{configPath:xe(e.client,"global").configPath}}var fo=(0,$r.promisify)(xr.execFile);function po(e,t){let n=e.trim().toLowerCase();return n===""?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:null}function Er(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function mo(e,t){return Er()?new Promise(n=>{let r=kr.createInterface({input:process.stdin,output:process.stdout}),s=!1,o=()=>{process.removeListener("SIGINT",a),process.removeListener("SIGTERM",a),r.removeListener("error",c),process.stdin.removeListener("error",c),process.stdout.removeListener("error",c),r.close()},i=u=>{s||(s=!0,o(),n(u))},a=()=>{o(),process.exit(1)},c=()=>i(t),l=()=>{r.question(e,u=>{let d=po(u,t);if(d===null){r.write(` Please answer y or n.
117
+ `),l();return}i(d)})};process.once("SIGINT",a),process.once("SIGTERM",a),r.once("error",c),process.stdin.once("error",c),process.stdout.once("error",c),l()}):Promise.resolve(t)}function go(e){let t=j.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
118
+ ${r}: ${n(e.currentPath)}`}function Pr(e,t){if(e.length===0){console.log(`${t} \u2713 All MCP client configs are up to date.`);return}console.log(`${t} Found ${e.length} stale MCP config ${e.length===1?"entry":"entries"}:`);for(let n of e)console.log(go(n))}function wr(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}var R=new _r.Command,tt=null,Ee=!1;function K(){return tt=new ue(()=>$.getSessionToken()),tt}R.name("visa-cli").description("Visa CLI - AI payment orchestration").version(ut().version);R.hook("preAction",async()=>{await en()});R.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking \u2014 for CI/agent use").option("--hud","Also enable the Claude Code HUD during setup").option("--no-hud","Do not install the HUD during setup (default)").action(async e=>{try{if(e.check){let f=$e();Pr(f,"MCP config check:"),f.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),process.exit(1));return}console.log("Step 1: Registering MCP server...");let t=$e(),n=new Map(t.map(f=>[f.client.id,f])),r=new Set,s=new Set,o=new Set;for(let f of B)if(ke(f)){let _;try{_=xe(f)}catch(P){if(P instanceof me){wr(P),s.add(f.displayName),o.add(f.id);continue}throw P}let b=n.get(f.id),I=b?` \u2014 repaired stale ${b.staleReason} entry`:"";console.log(` \u2713 ${f.displayName} (${_.configPath.replace(j.homedir(),"~")})${I}`),b&&r.add(f.id)}let i=t.filter(f=>!r.has(f.client.id)&&!o.has(f.client.id)),a=0;for(let f of i){try{Gt(f)}catch(_){if(_ instanceof me){wr(_),s.add(f.client.displayName),o.add(f.client.id);continue}throw _}console.log(` \u2713 ${f.client.displayName} (${f.configPath.replace(j.homedir(),"~")}) \u2014 repaired stale ${f.staleReason} entry`),a++}let c=r.size+a;c===0&&s.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):c>0&&console.log(` \u2713 Repaired ${c} stale MCP config ${c===1?"entry":"entries"}.`),s.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(s).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
119
+ Step 2: Checking authentication...`);let l=await $.getSessionToken();if(l)try{await new ue(()=>Promise.resolve(l)).getStatus(),console.log(" Already authenticated.")}catch(f){let _=f instanceof Error?f.message:"";_.includes("session has expired")||_.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await $.clearAll(),l=null):console.log(` Couldn't verify session (${_||"unknown error"}) \u2014 continuing with existing token.`)}if(l||(console.log(" No session found. Opening browser for GitHub login..."),l=await new Promise(async(f,_)=>{let b=nt.randomBytes(16).toString("hex"),I=`https://auth.visacli.sh/login?state=${b}`;await nn(I);let P=3e4,J=300*1e3,L=Date.now()+J;for(;Date.now()<L;)try{let X=await globalThis.fetch("https://auth.visacli.sh/v1/auth-status",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:b,timeout:P}),signal:AbortSignal.timeout(P+5e3)});if(!X.ok)continue;let ae=await X.json();if(ae.status==="pending")continue;if(ae.status==="expired"){_(new Error("Session expired. Please run setup again."));return}if(ae.status==="complete"&&ae.sessionToken){console.log(` Signed in as ${ae.user}.`),f(ae.sessionToken);return}}catch{}_(new Error("Login timed out after 5 minutes. Please run setup again."))}),await $.saveSessionToken(l),console.log(" Session token saved.")),console.log(`
120
+ Step 3: Setting up authentication...`),!D())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await fo("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}try{let f=await qe();console.log(" Attestation key generated."),await K().registerAttestationKey(f),console.log(" Attestation key registered with server.")}catch(f){console.log(` Skipped: ${f.message}`)}}let u=oe.join(j.homedir(),".claude","settings.json"),d=Cr.existsSync(oe.join(j.homedir(),".claude.json")),S=e.hud===!0;if(!S&&e.hud!==!1&&d&&!e.yes&&Er()&&(console.log(`
121
+ Step 4: Optional Visa HUD`),console.log(" Add a small live line so you can keep an eye on what your agents"),console.log(" are doing, which workspace they are in, and Visa CLI spend at a glance."),S=await mo(" Enable the HUD? [y/N] ",!1)),S)if(!d)console.log(`
122
+ Step 4: HUD requested, but Claude Code config was not detected.`),console.log(" Skipped. Enable later with: visa-cli hud enable");else{console.log(`
123
+ Step 4: Enabling the Visa spend HUD...`);let f=De(u),_=f.installed==="new"||f.installed==="already-visa"||f.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${_}${f.message}`);try{let b=K(),I=await b.getStatus(),P={currentVersion:b.getClientVersion(),latestVersion:b.lastSignals?.updateAvailable?.version,updateMessage:b.lastSignals?.updateAvailable?.message,updateCheckDisabled:G()},J=Dt(I,P);Mt(J),console.log(` Preview: ${J.split(`
124
+ `)[0]}`)}catch{}}let w="\x1B[1m",C="\x1B[0m";console.log(`
122
125
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
123
126
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
124
127
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551
@@ -134,26 +137,26 @@ Step 4: Enable the Visa spend HUD?`),console.log(" Pins your spend + card info
134
137
  \u2022 Or run: visa-cli pay <merchant-url>
135
138
 
136
139
  ${w}Verify:${C} visa-cli status
137
- ${w}HUD:${C} Restart Claude Code to see your spend pinned below the input
140
+ ${w}HUD:${C} visa-cli hud enable (agent activity, workspace, spend at a glance)
138
141
  ${w}Docs:${C} https://visacli.sh
139
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});I.command("install [client]").description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let o=xe();Er(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=xe();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)Wt(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(U.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
142
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});R.command("install [client]").description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let o=$e();Pr(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=$e();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)Gt(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(j.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
140
143
  Repaired ${o.length} stale MCP config ${o.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
141
144
  \x1B[1mSupported MCP Clients\x1B[0m
142
- `),console.log(` ${"Client".padEnd(18)} ${"Detected".padEnd(10)} ${"Installed".padEnd(11)} Config Path`),console.log(` ${"\u2500".repeat(18)} ${"\u2500".repeat(10)} ${"\u2500".repeat(11)} ${"\u2500".repeat(40)}`);for(let a of B){let c=Ce(a),l=br(a),u=c?"Yes":"No",d=l?"Yes":"No",v=a.globalConfigPath.replace(U.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${v}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of B){if(!Ce(a)){i.push(a.displayName);continue}ke(a,n),o.push(a.displayName)}o.length>0&&console.log(`Installed for: ${o.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),o.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
143
- Supported clients: ${B.map(o=>o.id).join(", ")}`),process.exit(1));let r=Vt(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${B.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!Ce(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=ke(r,n);console.log(`Registered visa-cli MCP server in ${s.configPath}`),console.log(s.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});I.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let o=[];for(let i of B)qt(i,n).removed&&o.push(i.displayName);o.length>0?console.log(`Removed visa-cli from: ${o.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
144
- Supported clients: ${B.map(o=>o.id).join(", ")}`),process.exit(1));let r=Vt(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${B.map(o=>o.id).join(", ")}`),process.exit(1));let s=qt(r,n);s.removed?console.log(`Removed visa-cli from ${s.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});I.command("pay <url>").description("Pay a merchant URL (amount auto-detected from HTTP 402 response)").option("-m, --method <method>","HTTP method (GET or POST)","GET").option("-b, --body <json>","JSON request body for POST endpoints").action(async(e,t)=>{try{lr(e);let n=ur(t.method),r=dr(t.body),s=new ue(()=>$.getSessionToken());console.log(`Checking payment for ${e}...`);let o=fr(await s.paymentPreview({url:e}));console.log(` Merchant: ${o.merchantName}`),console.log(` Amount: $${o.amount.toFixed(2)} ${o.currency}`),console.log(` Rail: auto-detected
145
- `);let a=(await s.getStatus()).attestationRequired!==!1;a&&!O()&&console.warn("Warning: Touch ID unavailable on this system \u2014 payment will proceed without biometric attestation.");let c=nt.randomUUID(),l=await jt(s,async()=>{let u;if(a&&O())try{let{nonce:d}=await s.getAttestationChallenge(),v=Buffer.from(JSON.stringify({nonce:d,amount:o.amount,merchant:o.merchantName,context:e})).toString("base64");u={signature:await Et(v,`pay $${o.amount.toFixed(2)} to ${o.merchantName}`),nonce:d,amount:o.amount,merchant:o.merchantName}}catch(d){throw new Error(`Touch ID confirmation failed: ${d?.message||"user cancelled or biometric error"}`)}return s.pay({url:e,method:n,body:r,attestation:u,idempotencyKey:c})});if(l.success){if(console.log(`Payment complete: $${(l.amount??o.amount).toFixed(2)} \u2192 ${l.merchantName??o.merchantName}`),l.receipt?.urls?.length){console.log(`
146
- Result URLs:`);for(let u of l.receipt.urls)console.log(` ${u}`)}}else console.error(`Payment failed: ${l.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof D?console.error(`Error: ${n.message}`):console.error("Error:",n.message),process.exit(1)}});I.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{$e=!1;try{let e=K(),t=await e.getStatus(),n={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.version,updateMessage:e.lastSignals.updateAvailable?.message,updateCheckDisabled:W()},r=await e.getTransactions().catch(s=>{if(process.env.VISA_CLI_DEBUG){let o=s instanceof Error?s.message:String(s);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${o}
147
- `)}return{transactions:[]}});process.stdout.write(Jn(t,Array.isArray(r?.transactions)?r.transactions:[],O(),n)),$e=!0}catch(e){$e=!1,console.error("Error:",e.message),process.exit(1)}});I.command("reset").description("Log out and clear all credentials").action(async()=>{try{console.log(`Resetting Visa CLI...
148
- `);try{await K().logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await $.clearAll(),console.log(" Keychain credentials cleared."),O())try{await qn(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
149
- Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}});I.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(async e=>{(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await $.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await K().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}});var Gt=I.command("config").description("Inspect the CLI configuration");Gt.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=K(),n=await or({api:t,includeDev:!!e.dev});if(e.json){console.log(ar(n));return}n.statusError&&(console.error(`Warning: could not reach auth server (${n.statusError}).`),console.error("Server-sourced entries show '\u2014'. Log in with `visa-cli setup` if you expected values here."),console.error("")),console.log(ir(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});function po(){return Object.entries(ye).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
150
- `)}Gt.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
145
+ `),console.log(` ${"Client".padEnd(18)} ${"Detected".padEnd(10)} ${"Installed".padEnd(11)} Config Path`),console.log(` ${"\u2500".repeat(18)} ${"\u2500".repeat(10)} ${"\u2500".repeat(11)} ${"\u2500".repeat(40)}`);for(let a of B){let c=ke(a),l=br(a),u=c?"Yes":"No",d=l?"Yes":"No",S=a.globalConfigPath.replace(j.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${S}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of B){if(!ke(a)){i.push(a.displayName);continue}xe(a,n),o.push(a.displayName)}o.length>0&&console.log(`Installed for: ${o.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),o.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
146
+ Supported clients: ${B.map(o=>o.id).join(", ")}`),process.exit(1));let r=Vt(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${B.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!ke(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=xe(r,n);console.log(`Registered visa-cli MCP server in ${s.configPath}`),console.log(s.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});R.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let o=[];for(let i of B)qt(i,n).removed&&o.push(i.displayName);o.length>0?console.log(`Removed visa-cli from: ${o.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
147
+ Supported clients: ${B.map(o=>o.id).join(", ")}`),process.exit(1));let r=Vt(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${B.map(o=>o.id).join(", ")}`),process.exit(1));let s=qt(r,n);s.removed?console.log(`Removed visa-cli from ${s.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});R.command("pay <url>").description("Pay a merchant URL (amount auto-detected from HTTP 402 response)").option("-m, --method <method>","HTTP method (GET or POST)","GET").option("-b, --body <json>","JSON request body for POST endpoints").action(async(e,t)=>{try{lr(e);let n=ur(t.method),r=dr(t.body),s=new ue(()=>$.getSessionToken());console.log(`Checking payment for ${e}...`);let o=fr(await s.paymentPreview({url:e}));console.log(` Merchant: ${o.merchantName}`),console.log(` Amount: $${o.amount.toFixed(2)} ${o.currency}`),console.log(` Rail: auto-detected
148
+ `);let a=(await s.getStatus()).attestationRequired!==!1;a&&!D()&&console.warn("Warning: Touch ID unavailable on this system \u2014 payment will proceed without biometric attestation.");let c=nt.randomUUID(),l=await jt(s,async()=>{let u;if(a&&D())try{let{nonce:d}=await s.getAttestationChallenge(),S=Buffer.from(JSON.stringify({nonce:d,amount:o.amount,merchant:o.merchantName,context:e})).toString("base64");u={signature:await Et(S,`pay $${o.amount.toFixed(2)} to ${o.merchantName}`),nonce:d,amount:o.amount,merchant:o.merchantName}}catch(d){throw new Error(`Touch ID confirmation failed: ${d?.message||"user cancelled or biometric error"}`)}return s.pay({url:e,method:n,body:r,attestation:u,idempotencyKey:c})});if(l.success){if(console.log(`Payment complete: $${(l.amount??o.amount).toFixed(2)} \u2192 ${l.merchantName??o.merchantName}`),l.receipt?.urls?.length){console.log(`
149
+ Result URLs:`);for(let u of l.receipt.urls)console.log(` ${u}`)}}else console.error(`Payment failed: ${l.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof M?console.error(`Error: ${n.message}`):console.error("Error:",n.message),process.exit(1)}});R.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Ee=!1;try{let e=K(),t=await e.getStatus(),n={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.version,updateMessage:e.lastSignals.updateAvailable?.message,updateCheckDisabled:G()},r=await e.getTransactions().catch(s=>{if(process.env.VISA_CLI_DEBUG){let o=s instanceof Error?s.message:String(s);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${o}
150
+ `)}return{transactions:[]}});process.stdout.write(Jn(t,Array.isArray(r?.transactions)?r.transactions:[],D(),n)),Ee=!0}catch(e){Ee=!1,console.error("Error:",e.message),process.exit(1)}});R.command("reset").description("Log out and clear all credentials").action(async()=>{try{console.log(`Resetting Visa CLI...
151
+ `);try{await K().logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await $.clearAll(),console.log(" Keychain credentials cleared."),D())try{await qn(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
152
+ Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}});R.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(async e=>{(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await $.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await K().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}});var Wt=R.command("config").description("Inspect the CLI configuration");Wt.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=K(),n=await or({api:t,includeDev:!!e.dev});if(e.json){console.log(ar(n));return}n.statusError&&(console.error(`Warning: could not reach auth server (${n.statusError}).`),console.error("Server-sourced entries show '\u2014'. Log in with `visa-cli setup` if you expected values here."),console.error("")),console.log(ir(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});function ho(){return Object.entries(ye).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
153
+ `)}Wt.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
151
154
  Settable keys:
152
- ${po()}`).action((e,t)=>{try{let n=In(e,t);console.log(`Saved ${n.key}=${JSON.stringify(n.value)} \u2192 ${n.path}`),n.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")}catch(n){n instanceof ce||n instanceof le?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Gt.command("unset <key>").description("Remove a CLI setting from ~/.visa-mcp/settings.json (falls back to env var or default)").action(e=>{try{let t=Ln(e);t.removed?(console.log(`Removed ${t.key} from ${t.path}`),t.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")):console.log(`No-op: ${t.key} was not set in ${t.path}.`)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}});var Jt=I.command("biometric").description("Manage Touch ID / biometric attestation enforcement");Jt.command("status").description("Show current biometric enforcement state").action(async()=>{try{await $.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await K().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=O();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${s?"yes":"no"}`),console.log(`Touch ID available on this device: ${o?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});Jt.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await $.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=K(),n=await t.setBiometricPreference({required:!0});n.success||(console.error(`Failed: ${n.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments."),(await t.getStatus()).hasAttestationKey||console.warn("Note: no attestation key is registered yet. Run `visa-cli setup` to enroll Touch ID.")}catch(e){console.error("Error:",e.message),process.exit(1)}});Jt.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await $.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=K(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!O()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await jt(t,async()=>{let s;if(n.hasAttestationKey&&O())try{let{nonce:o}=await t.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:o,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");s={signature:await Et(c,"disable Touch ID requirement"),nonce:o,amount:i,merchant:a}}catch(o){throw new Error(`Touch ID confirmation failed: ${o?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:s})});r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var ie=I.command("shell-hud").description("Manage the persistent Visa HUD shown in your shell prompt");function Pr(){let e=Nt();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Tr(){let e=Ot();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}ie.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Pr);ie.command("enable").description("Enable the persistent shell HUD").action(Pr);ie.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Tr);ie.command("disable").description("Disable the persistent shell HUD").action(Tr);ie.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Ut()}
153
- `)});ie.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,v,w)=>{console.log(` ${v?"\u2713":"\u2717"} ${d}: ${w}`),v||(n=!1)};console.log(`Shell HUD Doctor
154
- `);let s=Xe();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let d=Ze(s),v=e(d);if(r("RC file exists",v,d.replace(U.homedir(),"~")),v){let C=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",C,C?"found in rc file":"missing \u2014 run: visa-cli shell-hud install")}}let o=we(),i=e(o);if(r("Cache file",i,i?o.replace(U.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(o,"utf-8")),v=Date.now()-(d.renderedAt??0),w=Math.round(v/1e3),C=w<=30;console.log(` ${C?"\u2713":"\u26A0"} Cache freshness: ${w}s old${C?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=Ye(),c=e(a),l="missing";if(c)try{l=t(a,"utf-8").trim().slice(0,80)}catch{l="unreadable"}r("Line file",c,l);let u=!1;try{u=!!await $.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await K().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let v=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,v)}console.log(n?`
155
+ ${ho()}`).action((e,t)=>{try{let n=In(e,t);console.log(`Saved ${n.key}=${JSON.stringify(n.value)} \u2192 ${n.path}`),n.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")}catch(n){n instanceof ce||n instanceof le?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Wt.command("unset <key>").description("Remove a CLI setting from ~/.visa-mcp/settings.json (falls back to env var or default)").action(e=>{try{let t=Ln(e);t.removed?(console.log(`Removed ${t.key} from ${t.path}`),t.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")):console.log(`No-op: ${t.key} was not set in ${t.path}.`)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}});var Jt=R.command("biometric").description("Manage Touch ID / biometric attestation enforcement");Jt.command("status").description("Show current biometric enforcement state").action(async()=>{try{await $.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await K().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=D();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${s?"yes":"no"}`),console.log(`Touch ID available on this device: ${o?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});Jt.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await $.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=K(),n=await t.setBiometricPreference({required:!0});n.success||(console.error(`Failed: ${n.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments."),(await t.getStatus()).hasAttestationKey||console.warn("Note: no attestation key is registered yet. Run `visa-cli setup` to enroll Touch ID.")}catch(e){console.error("Error:",e.message),process.exit(1)}});Jt.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await $.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=K(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!D()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await jt(t,async()=>{let s;if(n.hasAttestationKey&&D())try{let{nonce:o}=await t.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:o,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");s={signature:await Et(c,"disable Touch ID requirement"),nonce:o,amount:i,merchant:a}}catch(o){throw new Error(`Touch ID confirmation failed: ${o?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:s})});r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var ie=R.command("shell-hud").description("Manage the persistent Visa HUD shown in your shell prompt");function Tr(){let e=Nt();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Rr(){let e=Ot();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}ie.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Tr);ie.command("enable").description("Enable the persistent shell HUD").action(Tr);ie.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Rr);ie.command("disable").description("Disable the persistent shell HUD").action(Rr);ie.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Ut()}
156
+ `)});ie.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,S,w)=>{console.log(` ${S?"\u2713":"\u2717"} ${d}: ${w}`),S||(n=!1)};console.log(`Shell HUD Doctor
157
+ `);let s=Xe();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let d=Ze(s),S=e(d);if(r("RC file exists",S,d.replace(j.homedir(),"~")),S){let C=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",C,C?"found in rc file":"missing \u2014 run: visa-cli shell-hud install")}}let o=we(),i=e(o);if(r("Cache file",i,i?o.replace(j.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(o,"utf-8")),S=Date.now()-(d.renderedAt??0),w=Math.round(S/1e3),C=w<=30;console.log(` ${C?"\u2713":"\u26A0"} Cache freshness: ${w}s old${C?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=Ye(),c=e(a),l="missing";if(c)try{l=t(a,"utf-8").trim().slice(0,80)}catch{l="unreadable"}r("Line file",c,l);let u=!1;try{u=!!await $.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await K().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let S=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,S)}console.log(n?`
155
158
  All checks passed.`:`
156
- Some checks failed \u2014 see above.`),n||process.exit(1)});ie.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(async e=>{if(!(!e.force&&er()))try{let t=K(),n=await t.getStatus(),r={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.version,updateMessage:t.lastSignals.updateAvailable?.message,updateCheckDisabled:W()},s=Dt(n,r);Mt(s)}catch{}finally{be()}});I.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(async e=>{try{let t=await mn(),r=Ut().split(`
159
+ Some checks failed \u2014 see above.`),n||process.exit(1)});ie.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(async e=>{if(!(!e.force&&er()))try{let t=K(),n=await t.getStatus(),r={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.version,updateMessage:t.lastSignals.updateAvailable?.message,updateCheckDisabled:G()},s=Dt(n,r);Mt(s)}catch{}finally{be()}});R.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(async e=>{try{let t=await mn(),r=Ut().split(`
157
160
  `)[0];if(e.json){let o=await yn(r,t);process.stdout.write(`${JSON.stringify(o,null,2)}
158
161
  `);return}let s=await gn(r,t);process.stdout.write(`${s}
159
- `)}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}});var rt=I.command("hud").description("Manage the Visa HUD for supported agent terminals");rt.command("enable").description("Register Visa HUD for Claude Code or Codex").argument("[client]","Agent client to enable: claude, codex, or all","claude").action(e=>{let t=yt(e);if(t||(console.error(`Unknown HUD client: ${e}`),console.error("Supported clients: claude, codex, all"),process.exit(1)),t==="claude"||t==="claude-code"||t==="all"){let n=oe.join(U.homedir(),".claude","settings.json"),r=Oe(n);console.log(r.message),(r.installed==="error"||r.installed==="malformed-json")&&process.exit(1)}if(t==="codex"||t==="all"){let n=Nt();console.log(n.message),console.log("Codex structured HUD payload is available with: visa-cli statusline --json"),console.log("Codex does not currently expose a Claude-style command statusLine install path, so this enables the terminal HUD fallback."),n.installed||process.exit(1)}});rt.command("disable").description("Remove Visa HUD from Claude Code or Codex terminal surfaces").argument("[client]","Agent client to disable: claude, codex, or all","claude").action(e=>{let t=yt(e);t||(console.error(`Unknown HUD client: ${e}`),console.error("Supported clients: claude, codex, all"),process.exit(1));let n=!1;if(t==="claude"||t==="claude-code"||t==="all"){let r=oe.join(U.homedir(),".claude","settings.json"),s=ft(r);console.log(s.message),s.removed||(n=!0)}if(t==="codex"||t==="all"){let r=Ot();console.log(r.message),r.removed||(n=!0)}n&&process.exit(1)});rt.command("enable-claude").description("Register Visa HUD as the Claude Code statusLine").action(()=>{let e=oe.join(U.homedir(),".claude","settings.json"),t=Oe(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});rt.command("disable-claude").description("Remove Visa HUD from Claude Code statusLine (leaves other tools untouched)").action(()=>{let e=oe.join(U.homedir(),".claude","settings.json"),t=ft(e);console.log(t.message),t.removed||process.exit(1)});I.hook("postAction",()=>{if($e){$e=!1;return}tt&&Wn(tt.lastSignals)});I.parse();
162
+ `)}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}});var rt=R.command("hud").description("Manage the Visa HUD for supported agent terminals");rt.command("enable").description("Register Visa HUD for Claude Code or Codex").argument("[client]","Agent client to enable: claude, codex, or all","claude").action(e=>{let t=yt(e);if(t||(console.error(`Unknown HUD client: ${e}`),console.error("Supported clients: claude, codex, all"),process.exit(1)),t==="claude"||t==="claude-code"||t==="all"){let n=oe.join(j.homedir(),".claude","settings.json"),r=De(n);console.log(r.message),(r.installed==="error"||r.installed==="malformed-json")&&process.exit(1)}if(t==="codex"||t==="all"){let n=Nt();console.log(n.message),console.log("Codex structured HUD payload is available with: visa-cli statusline --json"),console.log("Codex does not currently expose a Claude-style command statusLine install path, so this enables the terminal HUD fallback."),n.installed||process.exit(1)}});rt.command("disable").description("Remove Visa HUD from Claude Code or Codex terminal surfaces").argument("[client]","Agent client to disable: claude, codex, or all","claude").action(e=>{let t=yt(e);t||(console.error(`Unknown HUD client: ${e}`),console.error("Supported clients: claude, codex, all"),process.exit(1));let n=!1,r=!1;if(t==="claude"||t==="claude-code"||t==="all"){let s=oe.join(j.homedir(),".claude","settings.json"),o=ft(s);console.log(o.message),o.removed&&(r=!0),!o.removed&&t!=="all"&&(n=!0)}if(t==="codex"||t==="all"){let s=Ot();console.log(s.message),s.removed&&(r=!0),!s.removed&&t!=="all"&&(n=!0)}t==="all"&&!r&&(n=!0),n&&process.exit(1)});rt.command("enable-claude").description("Register Visa HUD as the Claude Code statusLine").action(()=>{let e=oe.join(j.homedir(),".claude","settings.json"),t=De(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});rt.command("disable-claude").description("Remove Visa HUD from Claude Code statusLine (leaves other tools untouched)").action(()=>{let e=oe.join(j.homedir(),".claude","settings.json"),t=ft(e);console.log(t.message),t.removed||process.exit(1)});R.hook("postAction",()=>{if(Ee){Ee=!1;return}tt&&Gn(tt.lastSignals)});R.parse();