@visa/cli 1.6.0-rc.1 → 1.6.0-rc.3
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 +53 -53
- package/dist/mcp-server/index.js +21 -21
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var On=Object.create;var bt=Object.defineProperty;var jn=Object.getOwnPropertyDescriptor;var Un=Object.getOwnPropertyNames;var Hn=Object.getPrototypeOf,Vn=Object.prototype.hasOwnProperty;var Fn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Bn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Un(t))!Vn.call(e,s)&&s!==n&&bt(e,s,{get:()=>t[s],enumerable:!(r=jn(t,s))||r.enumerable});return e};var g=(e,t,n)=>(n=e!=null?On(Hn(e)):{},Bn(t||!e||!e.__esModule?bt(n,"default",{value:e,enumerable:!0}):n,e));var qe=Fn((fs,tr)=>{tr.exports={name:"@visa/cli",version:"1.6.0-rc.3",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.30.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 En=require("commander"),Oe=g(require("crypto")),Tn=g(require("fs")),N=g(require("os")),pe=g(require("path")),Rn=g(require("readline")),An=require("child_process"),In=require("util");var he=require("child_process"),vt=require("util"),W=g(require("fs")),ye=g(require("os")),Fe=g(require("path")),O=(0,vt.promisify)(he.execFile),Be=Fe.join(ye.homedir(),".visa-mcp"),me=Fe.join(Be,"session-token"),I="visa-cli",G="session-token",ge="rc-access",Kn=5e3;async function qn(){try{let{stdout:e}=await O("security",["find-generic-password","-s",I,"-a",G,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Gn(e){try{try{await O("security",["delete-generic-password","-s",I,"-a",G],{timeout:5e3})}catch{}return await O("security",["add-generic-password","-s",I,"-a",G,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Wn(){try{await O("security",["delete-generic-password","-s",I,"-a",G],{timeout:5e3})}catch{}}async function Jn(){if(!Ke())return null;try{let{stdout:e}=await O("secret-tool",["lookup","service",I,"account",G],{timeout:5e3});return e.trim()||null}catch{return null}}async function zn(e){if(!Ke())return!1;try{let t=(0,he.execFile)("secret-tool",["store","--label",`${I} ${G}`,"service",I,"account",G]);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"))},Kn))]),!0):!1}catch{return!1}}async function Yn(){if(Ke())try{await O("secret-tool",["clear","service",I,"account",G],{timeout:5e3})}catch{}}function Ke(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Xn(){try{let{stdout:e}=await O("security",["find-generic-password","-s",I,"-a",ge,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Zn(e){try{try{await O("security",["delete-generic-password","-s",I,"-a",ge],{timeout:5e3})}catch{}await O("security",["add-generic-password","-s",I,"-a",ge,"-w",e],{timeout:5e3})}catch{}}async function Qn(){try{await O("security",["delete-generic-password","-s",I,"-a",ge],{timeout:5e3})}catch{}}function He(){try{return W.readFileSync(me,"utf-8").trim()||null}catch{return null}}function wt(e){W.mkdirSync(Be,{recursive:!0,mode:448}),W.writeFileSync(me,e,{mode:384}),process.platform==="win32"&&er(me)}function Ve(){try{W.unlinkSync(me)}catch{}}function er(e){try{let t=ye.userInfo().username;(0,he.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 Ue(){switch(process.platform){case"darwin":return{get:qn,store:Gn,delete:Wn};case"linux":return{get:Jn,store:zn,delete:Yn};default:return{get:async()=>He(),store:async e=>{try{return wt(e),!0}catch{return!1}},delete:async()=>Ve()}}}var $=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let t=Ue(),n=await t.get();if(n)return n;let r=He();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=Ue();if(await n.store(t)){if(await n.get()===t){Ve();return}await n.delete()}if(wt(t),He()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Be} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":Xn()}static async saveRcAccessToken(t){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await Zn(t)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Ue().delete(),Ve()}static async clearAll(){await this.deleteSessionToken(),await Qn()}};var Se=g(require("crypto")),be=g(require("tty")),ve=g(require("fs"));var X="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";function nr(e){return/-rc\.|-beta\./.test(e)}function Ge(e){return Se.createHash("sha256").update(e.trim()).digest("hex")}function _t(e){return X==="SKIP"?!0:Se.timingSafeEqual(Buffer.from(Ge(e)),Buffer.from(X))}function rr(e){return new Promise((t,n)=>{let r=ve.openSync("/dev/tty","r+"),s=new be.ReadStream(r),o=new be.WriteStream(r),i=()=>{try{s.destroy()}catch{}try{o.destroy()}catch{}try{ve.closeSync(r)}catch{}};o.write(e),s.setRawMode(!0),s.resume(),s.setEncoding("utf8");let a="";s.on("data",c=>{c==="\r"||c===`
|
|
2
2
|
`?(o.write(`
|
|
3
3
|
`),i(),t(a)):c===""?(o.write(`
|
|
4
|
-
`),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
|
|
4
|
+
`),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 sr=`
|
|
5
5
|
\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
|
|
6
6
|
\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
|
|
7
7
|
\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
|
|
@@ -10,26 +10,26 @@
|
|
|
10
10
|
\u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
|
|
11
11
|
|
|
12
12
|
This is a Release Candidate build. Access is restricted to Visa employees.
|
|
13
|
-
`;async function
|
|
14
|
-
`),process.exit(1)}let s=await $.getRcAccessToken();if(s&&(X==="SKIP"||s===X))return;console.log(
|
|
13
|
+
`;async function $t(e={}){let t=e.version??qe().version;if(!nr(t))return;let n=process.env.VISA_RC_CODE;if(n&&_t(n)){await $.saveRcAccessToken(Ge(n));return}if(e.isMcp??!1){let i=await $.getRcAccessToken();if(i&&(X==="SKIP"||i===X))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
|
|
14
|
+
`),process.exit(1)}let s=await $.getRcAccessToken();if(s&&(X==="SKIP"||s===X))return;console.log(sr);let o=3;for(let i=1;i<=o;i++){let a;try{a=await rr(" Enter RC access code: ")}catch{process.exit(1)}if(_t(a)){await $.saveRcAccessToken(Ge(a)),console.log(`
|
|
15
15
|
Access granted. Welcome.
|
|
16
16
|
`);return}i<o&&console.log(`
|
|
17
17
|
Invalid code. ${o-i} attempt(s) remaining.
|
|
18
18
|
`)}console.log(`
|
|
19
19
|
Invalid code. Contact your team lead.
|
|
20
|
-
`),process.exit(1)}var
|
|
21
|
-
`)}function
|
|
22
|
-
`))n(` ${c}`);n("");let i=
|
|
23
|
-
`),E.renameSync(n,e)}catch(r){try{E.unlinkSync(n)}catch{}throw r}}function
|
|
24
|
-
${P}`}function
|
|
25
|
-
`);d>=0&&(a=a.slice(d+1))}}return a}catch{return null}finally{if(t!==void 0)try{
|
|
26
|
-
`),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<
|
|
27
|
-
`)}function Z(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
|
|
28
|
-
`;process.stderr.write(s),
|
|
20
|
+
`),process.exit(1)}var Ct=require("child_process");function or(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 ir(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(`
|
|
21
|
+
`)}function ar(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 xt(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,s=t.platform??process.platform,o=t.spawn??((c,d,u)=>{(0,Ct.execFile)(c,d,f=>u(f))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of ir(e).split(`
|
|
22
|
+
`))n(` ${c}`);n("");let i=or(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=ar(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,d=>{d?(n(` Could not open browser automatically (${d.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()})})}var Pt=g(require("crypto")),E=g(require("fs")),we=g(require("path"));function Et(e,t){E.mkdirSync(we.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Pt.randomBytes(8).toString("hex")}.tmp`;try{E.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
23
|
+
`),E.renameSync(n,e)}catch(r){try{E.unlinkSync(n)}catch{}throw r}}function kt(e){return`'${e.replace(/'/g,"'\\''")}'`}var Tt="# visa-cli-hud-v1";function cr(e,t){let n=e??process.execPath,r=t??process.argv[1]??"",s=r?we.resolve(r):"";return`${s?`${kt(n)} ${kt(s)} statusline`:"visa-cli statusline"} ${Tt}`}function Rt(e){return typeof e!="string"?!1:e.includes(Tt)?!0:e.includes("visa-cli")&&e.includes("statusline")}function We(e,t=cr){let n={},r=!1;if(E.existsSync(e)){r=!0;try{n=JSON.parse(E.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 Rt(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()},Et(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 At(e){if(!E.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(E.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 Rt(n)?(delete t.statusLine,Et(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 F=g(require("fs")),J=g(require("path")),lr=50,ur=64*1024,It=10,Je=80;function dr(){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 ze=dr(),S={reset:"\x1B[0m",visaBlue:ze?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:ze?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:ze?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function b(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${S.reset}`}function Lt(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Mt(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(d)},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 f=JSON.parse(u);o(f&&typeof f=="object"?f:null)}catch{o(null)}},c=()=>o(null),d=setTimeout(()=>{n.length>0?a():o(null)},lr);e.on("data",i),e.on("end",a),e.on("error",c)})}function Ot(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${b(r||"",S.visaBlueSoft)}${b(s||"",S.dim)}`}function Nt(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 fr(e){let t=` ${b("\u2502",S.dim)} `,n=Z(e.model?.display_name)||"claude",r=e.cwd?Z(J.basename(e.cwd)):"",s=_r(e.workspace),o=r||s,i=s&&s!==o?` ${b(`@${s}`,S.visaBlueSoft)}`:"",a=[b(`[${n}]`,S.visaBlueSoft)];o&&a.push(`${b(o,S.visaGold)}${i}`);let c=a.join(t),d=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,f=e.context_window?.current_usage,l=[f?.input_tokens,f?.output_tokens,f?.cache_creation_input_tokens,f?.cache_read_input_tokens].filter(q=>typeof q=="number"&&Number.isFinite(q)),h=l.length>0?l.reduce((q,je)=>q+je,0):null,v=Number(e.context_window?.total_input_tokens??h??f?.input_tokens??0),k=u!==null?Math.max(0,Math.min(1,u/100)):d>0?Math.max(0,Math.min(1,v/d)):0,H=u!==null&&d>0?Math.round(k*d):v,V;if(d>0||u!==null){let q=`${String(Math.round(k*100)).padStart(2," ")}%`,je=d>0?` ${b(`(${Nt(H)}/${Nt(d)})`,S.dim)}`:"";V=`${b("Context",S.dim)} ${Ot(k)} ${b(q,S.green)}${je}`}else V=`${b("Context",S.dim)} ${b("-",S.dim)}`;let B=mr(e.rate_limits),K=[V];B&&K.push(B);let P=K.join(t);return`${c}
|
|
24
|
+
${P}`}function pr(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 Dt(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=Ot(r),o=n>=90?"\x1B[38;5;196m":n>=70?S.visaGold:S.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=pr(e.resets_at),c=a?` ${b(`(${a} / ${t})`,S.dim)}`:` ${b(`(${t})`,S.dim)}`;return`${s} ${b(i,o)}${c}`}function mr(e){if(!e)return null;let t=Dt(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Dt(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${b("\u2502",S.dim)} `,o=[t,r].filter(Boolean);return`${b("Usage",S.dim)} ${o.join(s)}`}function gr(e){let t;try{let n=F.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,ur),o=r-s;t=F.openSync(e,"r");let i=Buffer.alloc(s);F.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(F.readSync(t,c,0,1,o-1),c[0]!==10){let d=a.indexOf(`
|
|
25
|
+
`);d>=0&&(a=a.slice(d+1))}}return a}catch{return null}finally{if(t!==void 0)try{F.closeSync(t)}catch{}}}function hr(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=J.basename(J.dirname(s)),i=J.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function yr(e){let t=e.split(`
|
|
26
|
+
`),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<It*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 d=c.content;if(Array.isArray(d))for(let u of d){if(!u||typeof u!="object")continue;let f=u;if(f.type==="tool_result"&&typeof f.tool_use_id=="string")r.add(f.tool_use_id);else if(f.type==="tool_use"&&typeof f.name=="string"){let l=typeof f.id=="string"?f.id:"",h=l.length>0?!r.has(l):!1;n.push({name:f.name,target:hr(f.input),running:h})}}}return n.reverse(),n.slice(Math.max(0,n.length-It))}function Sr(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 br(e){let t=e.running?b("\u25D0",S.visaGold):b("\u2713",S.green),n=e.running?S.visaGold:S.visaBlueSoft,r=b(Z(e.name),n),s=e.target?Z(e.target):"",o=s?`${b(":",S.dim)} ${b(s,S.dim)}`:"",i=e.count>1?` ${b(`\xD7${e.count}`,S.dim)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function vr(e){let t=` ${b("\u2502",S.dim)} `,n=Lt(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(Lt(c)<=Je)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>Je-n-1?i.slice(0,Je-n-1)+s:i;return`${b(s,S.dim)}${t}${a}`}async function wr(e){if(!e||typeof e!="string")return null;let t=gr(e);if(!t)return null;let n;try{n=yr(t)}catch{return null}if(n.length===0)return null;let s=Sr(n).map(br);return vr(s)||null}async function jt(e,t){let n=[e];if(t){let r=fr(t);if(r&&n.push(r),t.transcript_path){let s=await wr(t.transcript_path);s&&n.push(s)}}return n.join(`
|
|
27
|
+
`)}function Z(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 _r(e){if(typeof e=="string")return Z(J.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 Z(t?J.basename(t):e.name)}async function Ut(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 $r=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Vt(e,t){let n=Ht(e),r=Ht(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:Cr(n.pre,r.pre)>0}function Ht(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match($r);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Cr(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),d=/^\d+$/.test(a);if(c&&d){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(d)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function z(){return!!(Ft(process.env.VISA_CLI_NO_UPDATE_CHECK)||Ft(process.env.CI)||process.env.NODE_ENV==="test")}function Ft(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Ye="1.6.0-rc.3",te=class{constructor(t){this.getSessionToken=t;this.baseUrl=process.env.VISA_AUTH_URL||"https://auth.visacli.sh"}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!z()){let r=t.headers.get("X-Latest-Version"),s=t.headers.get("X-Update-Message");r&&Vt(r,Ye)&&(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 Ye}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 Ut(`${this.baseUrl}${n}`,{method:t,headers:{...a,"X-Visa-CLI-Version":Ye},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 d;try{d=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(d?.error||`Request failed (${c.status}). Try again.`);return d}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 tt=require("child_process"),Jt=require("util"),zt=g(require("crypto")),C=g(require("fs")),Yt=g(require("os")),j=g(require("path"));var T=g(require("fs")),Qe=g(require("path")),Bt=g(require("os")),Ze=Qe.join(Bt.homedir(),".visa-mcp"),oe=Qe.join(Ze,"mcp-server.log"),xr=5*1024*1024,Xe=null;function kr(){T.existsSync(Ze)||T.mkdirSync(Ze,{recursive:!0,mode:448})}function Pr(){if(!Xe){if(kr(),T.existsSync(oe)&&T.statSync(oe).size>xr){let t=oe+".1";T.existsSync(t)&&T.unlinkSync(t),T.renameSync(oe,t)}Xe=T.createWriteStream(oe,{flags:"a"})}return Xe}function _e(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}
|
|
28
|
+
`;process.stderr.write(s),Pr().write(s)}var ne={debug:(...e)=>_e("DEBUG",...e),info:(...e)=>_e("INFO",...e),warn:(...e)=>_e("WARN",...e),error:(...e)=>_e("ERROR",...e)};var re=(0,Jt.promisify)(tt.execFile),xe=j.join(Yt.homedir(),".visa-mcp","bin"),Q=j.join(xe,"Visa CLI"),Er=j.join(__dirname,"..","native"),Kt="5",qt=j.join(xe,"visa-keychain.version"),Gt=j.join(xe,"visa-keychain.sha256");function Wt(e){let t=C.readFileSync(e);return zt.createHash("sha256").update(t).digest("hex")}async function Xt(){try{if(C.readFileSync(qt,"utf-8").trim()===Kt&&C.existsSync(Q)){let r=C.readFileSync(Gt,"utf-8").trim();if(Wt(Q)!==r)ne.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),C.unlinkSync(Q);else return Q}}catch{}let e=j.join(Er,"visa-keychain.m");if(C.existsSync(e)||(e=j.resolve(__dirname,"..","..","native","visa-keychain.m")),C.existsSync(e)||(e=j.resolve(__dirname,"..","native","visa-keychain.m")),!C.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");C.mkdirSync(xe,{recursive:!0,mode:448});try{await re("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Q,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Wt(Q);return C.writeFileSync(Gt,t,{mode:384}),C.writeFileSync(qt,Kt,{mode:384}),Q}async function Zt(e){let t=await Xt(),n;try{n=(await re(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 et=null;function D(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:et!==null?et:(et=!0,!0)}var $e="visa-cli",Ce="attestation-key";async function Tr(e){try{await re("security",["delete-generic-password","-s",$e,"-a",Ce],{timeout:5e3})}catch{}await re("security",["add-generic-password","-s",$e,"-a",Ce,"-w",e],{timeout:5e3})}async function Rr(){try{let{stdout:e}=await re("security",["find-generic-password","-s",$e,"-a",Ce,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function ke(){let e=await Zt(["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 Tr(n),r}async function nt(e,t){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await Rr();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Xt(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,tt.execFile)(r,s,{timeout:6e4},(c,d)=>{let u=(d||"").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 Qt(){try{await re("security",["delete-generic-password","-s",$e,"-a",Ce],{timeout:5e3})}catch{}try{await Zt(["delete-key"])}catch{}}function tn(e,t=process.stderr){if(z()||!e?.updateAvailable)return!1;let{message:n}=e.updateAvailable;return n?(t.write(`
|
|
29
29
|
\x1B[33m\u2191 ${n}\x1B[0m
|
|
30
|
-
`),!0):!1}function
|
|
30
|
+
`),!0):!1}function rn(e,t,n,r){let o=Or(e.spendingControls).dailyLimit,i=Math.max(0,ie(e.dailySpent)),a=o>0?Math.min(o,Math.max(0,ie(e.dailyRemaining??o-i))):0,c=o>0?Math.min(1,i/o):0,u=(Array.isArray(t)?t:[]).filter(Lr),f=u.slice(0,3),l=Nr(u,3),h=(e.cards??[]).slice(0,3),v=r.latestVersion?rt(r.latestVersion):"",k=r.updateCheckDisabled?"update checks disabled":v?`update available: v${v}`:"up to date",H=Math.round(c*100),V=Y(e.status,e.enrolled?"approved":"not enrolled"),K=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${V} | touch id: ${n?"ready":"unavailable"}`,`Version: v${r.currentVersion} | ${k}`,`Spend meter: ${nn(c)} ${String(H).padStart(3," ")}% | remaining ${se(a)}/day | daily cap ${se(o)}`,"","Spend",` Remaining ${se(a)} / ${se(o)}`,` Usage ${nn(c)} ${H}%`,` Spent today ${se(i)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...h.length>0?h.map(P=>` ${Mr(P)}`):[" No cards enrolled"],"","Last 3 services",...l.length>0?l.map((P,q)=>` ${q+1}. ${P}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(P=>` ${Dr(P)}`):[" No receipts yet"]];return r.updateMessage&&K.push("",`Update: ${rt(r.updateMessage)}`),`${K.join(`
|
|
31
31
|
`)}
|
|
32
|
-
`}function
|
|
32
|
+
`}function Ar(e){return e.tool_name!=null}function Ir(e){return ie(e.amount)===0&&e.status==="failed"}function Lr(e){return Ar(e)&&!Ir(e)}function Nr(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=Y(s.merchant_name,"Unknown merchant"),i=Y(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function Dr(e){let t=Y(e.merchant_name,"Unknown merchant"),n=Y(e.tool_name,"unknown_tool"),r=se(ie(e.amount)),s=Y(e.status,"unknown"),o=jr(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function Mr(e){let t=Y(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${Number.isInteger(e.id)?`#${e.id} `:""}${t} ****${e.last4}${n}`}function Or(e){return{dailyLimit:ie(e?.daily_limit??e?.dailyLimit??0)}}function ie(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function se(e){return`$${e.toFixed(2)}`}function nn(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 Y(e,t){let n=rt(e??"").trim();return n.length>0?n:t}function jr(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Y(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function rt(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 y=g(require("fs")),Ae=g(require("os")),w=g(require("path")),on=require("child_process"),Ur=2,Pe="# >>> visa-cli shell hud v2 >>>",Ee="# <<< visa-cli shell hud v2 <<<",Hr="# >>> visa-cli shell hud >>>",Vr="# <<< visa-cli shell hud <<<",an=3e4,Fr=3e4;function at(){try{return w.join(mn(),".visa-cli")}catch{return w.join(Ae.tmpdir(),".visa-cli")}}function ce(){return w.join(at(),"shell-hud.json")}function Ie(){return w.join(at(),"shell-hud.line")}function cn(){return w.join(at(),"shell-hud.lock")}function Le(e){let t=e??process.env.SHELL;if(!t)return null;let n=w.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 Ne(e){let t=mn();if(e==="zsh")return w.join(t,".zshrc");if(e==="bash")return w.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return w.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Br(e){let t="$HOME/.visa-cli/shell-hud.line",n=zr(e),r=Yr(e);if(e==="zsh")return`${Pe}
|
|
33
33
|
_visa_cli_shell_hud_precmd() {
|
|
34
34
|
setopt localoptions no_bg_nice
|
|
35
35
|
if [[ -f "${t}" ]]; then
|
|
@@ -46,7 +46,7 @@ autoload -Uz add-zsh-hook
|
|
|
46
46
|
if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
|
|
47
47
|
add-zsh-hook precmd _visa_cli_shell_hud_precmd
|
|
48
48
|
fi
|
|
49
|
-
${
|
|
49
|
+
${Ee}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${Pe}
|
|
50
50
|
if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
|
|
51
51
|
$function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
|
|
52
52
|
}
|
|
@@ -65,7 +65,7 @@ function global:prompt {
|
|
|
65
65
|
}
|
|
66
66
|
& $function:global:__visa_cli_original_prompt
|
|
67
67
|
}
|
|
68
|
-
${
|
|
68
|
+
${Ee}`}return`${Pe}
|
|
69
69
|
__visa_cli_shell_hud_precmd() {
|
|
70
70
|
if [ -f "${t}" ]; then
|
|
71
71
|
cat "${t}"
|
|
@@ -82,34 +82,34 @@ case ";$PROMPT_COMMAND;" in
|
|
|
82
82
|
*";__visa_cli_shell_hud_precmd;"*) ;;
|
|
83
83
|
*) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
|
|
84
84
|
esac
|
|
85
|
-
${
|
|
85
|
+
${Ee}`}function ln(e){let t=e;for(let[n,r]of[[Pe,Ee],[Hr,Vr]])t=t.replace(new RegExp(`\\n?${sn(n)}[\\s\\S]*?${sn(r)}\\n?`,"g"),"");return t.trimEnd()}function Kr(e,t){let n=ln(e).trimEnd(),r=Br(t);return n.length>0?`${n}
|
|
86
86
|
|
|
87
87
|
${r}
|
|
88
88
|
`:`${r}
|
|
89
|
-
`}function
|
|
90
|
-
`:""),{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}: ${
|
|
91
|
-
`),
|
|
92
|
-
`)}catch{}}function
|
|
93
|
-
`),r=
|
|
94
|
-
`),i=
|
|
89
|
+
`}function un(e=Le()){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=Ne(e);let n=y.existsSync(t)?y.readFileSync(t,"utf-8"):"",r=Kr(n,e),s=r!==n;return s&&Re(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}: ${gn(n)}`}}}function dn(e=Le()){if(!e)return{removed:!1,shell:null,message:"Shell HUD uninstall skipped: supported shells are zsh, bash, and PowerShell."};let t;try{if(t=Ne(e),!y.existsSync(t))return{removed:!1,shell:e,rcPath:t,message:`No ${e} rc file found at ${t}.`};let n=y.readFileSync(t,"utf-8"),r=ln(n);return r===n.trimEnd()?{removed:!1,shell:e,rcPath:t,message:`Persistent shell HUD was not installed in ${t}.`}:(Re(t,r.length>0?`${r}
|
|
90
|
+
`:""),{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}: ${gn(n)}`}}}function ct(e,t){let n=Te(t.currentVersion),r=` ${L("\u2502",A.dim)} `;if(!e.enrolled)return`${L("VISA CLI",A.visaBlue)} ${L(`v${n}`,A.visaBlueSoft)}${r}${L("setup needed",A.visaGold)}`;let s=st(e.spendingControls?.daily_limit??e.spendingControls?.dailyLimit),o=Math.max(0,st(e.dailySpent)),i=s>0?Math.min(s,Math.max(0,st(e.dailyRemaining??s-o))):0,a=s>0?Math.max(0,Math.min(1,o/s)):0,c=Wr(e),d=s>0?`${Gr(a)} ${L(`${ot(i)} left today`,A.green)} ${L(`(${ot(o)}/${ot(s)}/day)`,A.dim)}`:L("no spend limit",A.dim);return`${L("VISA CLI",A.visaBlue)} ${L(`v${n}`,A.visaBlueSoft)}${r}${L(c,A.visaGold)}${r}${d}`}function fn(){let e=pn();return!!e&&Date.now()-e.renderedAt<=an}function lt(){let e=pn();if(e&&Date.now()-e.renderedAt<=an||(qr(),e?.line))return e.line;try{let t=Ie();if(y.existsSync(t))return y.readFileSync(t,"utf-8").trimEnd()}catch{}return"VISA | loading spend HUD\u2026"}function ut(e){try{let t=w.dirname(ce());y.mkdirSync(t,{recursive:!0});let n=Te(e),r={hudVersion:Ur,renderedAt:Date.now(),line:n};Re(ce(),JSON.stringify(r)+`
|
|
91
|
+
`),Re(Ie(),n+`
|
|
92
|
+
`)}catch{}}function ae(){try{y.unlinkSync(cn())}catch{}}function pn(){let e=ce();if(!y.existsSync(e))return null;try{return JSON.parse(y.readFileSync(e,"utf-8"))}catch{return null}}function qr(){let e=cn();try{if(y.mkdirSync(w.dirname(e),{recursive:!0}),!Xr(e))return;let t=process.argv[1]?w.resolve(process.argv[1]):"";if(!t){ae();return}let n=(0,on.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",ae),n.unref()}catch{ae()}}function st(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Te(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 Gr(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${L(r||"",A.green)}${L(s||"",A.dim)}`}function ot(e){return`$${e.toFixed(2)}`}function Wr(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=Te(n.toUpperCase()),o=Te(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function Jr(){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=Jr(),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 L(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${A.reset}`}function sn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mn(){let e=Ae.homedir();if(!e||!w.isAbsolute(e))throw new Error("unable to determine a valid home directory");return w.resolve(e)}function zr(e){return e==="powershell"?"& visa-cli shell-hud refresh":"visa-cli shell-hud refresh"}function Yr(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Xr(e){for(let t=0;t<2;t+=1){let n;try{return n=y.openSync(e,"wx"),y.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=y.statSync(e);if(Date.now()-s.mtimeMs<=Fr)return!1;y.unlinkSync(e)}catch{}}finally{n!==void 0&&y.closeSync(n)}}return!1}function gn(e){return e instanceof Error?e.message:"unknown file system error"}function Re(e,t){y.mkdirSync(w.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;y.writeFileSync(n,t),y.renameSync(n,e)}async function dt(e,t){try{return await t()}catch(n){if(n.message==="Invalid signature"&&D()){ne.warn("attestation:key-mismatch",{action:"reregistering"});try{let r=await ke();await e.registerAttestationKey(r),ne.info("attestation:key-reregistered")}catch(r){throw ne.error("attestation:reregister-failure",{error:r.message}),n}return await t()}throw n}}var R=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},hn=["GET","POST"];function yn(e){let t;try{t=new URL(e)}catch{throw new R(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new R(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}function Sn(e){let t=(e??"GET").toUpperCase();if(!hn.includes(t))throw new R(`Unsupported HTTP method "${e}". Supported: ${hn.join(", ")}.`);return t}function bn(e){if(e!==void 0){try{JSON.parse(e)}catch(t){throw new R(`--body is not valid JSON: ${t?.message??"parse error"}`)}return e}}function vn(e){if(!e||typeof e!="object")throw new R("Merchant returned no payment preview.");let t=e;if(typeof t.amount!="number"||!Number.isFinite(t.amount)||t.amount<=0)throw new R("Could not determine payment amount from merchant.");if(typeof t.merchantName!="string"||t.merchantName.trim().length===0)throw new R("Merchant returned an empty merchant name.");if(t.merchantName.length>200)throw new R(`Merchant name too long (${t.merchantName.length} chars).`);if(typeof t.currency!="string"||t.currency.trim().length===0)throw new R("Merchant returned an empty currency.");if(t.currency.length>10)throw new R(`Currency code too long (${t.currency.length} chars).`);return{amount:t.amount,currency:t.currency,merchantName:t.merchantName}}var m=g(require("fs")),p=g(require("path")),wn=g(require("os")),_=wn.homedir(),Zr=["Claude_","Anthropic.ClaudeDesktop_"];function _n(){return process.env.APPDATA||p.join(_,"AppData","Roaming")}function Qr(){return process.env.LOCALAPPDATA||p.join(_,"AppData","Local")}function $n(){if(process.platform!=="win32")return;let e=p.join(Qr(),"Packages");if(m.existsSync(e))try{let t=m.readdirSync(e,"utf-8");for(let n of Zr){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return p.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function Cn(){if(process.platform==="win32"){let e=$n();return e?p.join(e,"claude_desktop_config.json"):p.join(_n(),"Claude","claude_desktop_config.json")}return p.join(_,"Library","Application Support","Claude","claude_desktop_config.json")}function xn(){if(process.platform!=="win32")return[p.join(_,"Library","Application Support","Claude")];let e=[p.join(_n(),"Claude")],t=$n();return t&&e.push(t),e}function De(e){return e.id==="claude-desktop"?Cn():e.globalConfigPath}function es(e){return e.id==="claude-desktop"?xn():e.detectPaths}var M=[{id:"claude",displayName:"Claude Code",globalConfigPath:p.join(_,".claude.json"),configKey:"mcpServers",detectPaths:[p.join(_,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:Cn(),configKey:"mcpServers",detectPaths:xn(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:p.join(_,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[p.join(_,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:p.join(_,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[p.join(_,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:p.join(_,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[p.join(_,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:p.join(_,".config","Roo","mcp_settings.json"),configKey:"mcpServers",detectPaths:[p.join(_,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:p.join(_,".vscode","mcp.json"),configKey:"servers",detectPaths:[p.join(_,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:p.join(_,".config","zed","settings.json"),configKey:"context_servers",detectPaths:[p.join(_,".config","zed")],postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:p.join(_,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[p.join(_,".codex")],postInstallHint:"Restart Codex to connect."}];function ft(e){return M.find(t=>t.id===e)}function le(e){return es(e).some(t=>{if(t.includes("*")){let n=p.dirname(t),r=p.basename(t).replaceAll("*","");if(!m.existsSync(n))return!1;try{return m.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return m.existsSync(t)})}function kn(){return{command:"node",args:[p.resolve(__dirname,"mcp-server/index.js")]}}function pt(e,t){return t==="project"?"json":e.configFormat??"json"}function ts(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 mt(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 gt(e,t){let n=e.split(`
|
|
93
|
+
`),r=mt(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]]=ts(i[2]))}return Object.keys(s).length>0?s:void 0}function ns(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
|
|
94
|
+
`),i=mt(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
|
|
95
95
|
`);return c.endsWith(`
|
|
96
96
|
`)?c:c+`
|
|
97
97
|
`}let a=e.trimEnd();return a+(a.length>0?`
|
|
98
98
|
|
|
99
99
|
`:"")+s.join(`
|
|
100
100
|
`)+`
|
|
101
|
-
`}function
|
|
102
|
-
`),r=
|
|
101
|
+
`}function rs(e,t){let n=e.split(`
|
|
102
|
+
`),r=mt(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
|
|
103
103
|
`).replace(/\n{3,}/g,`
|
|
104
104
|
|
|
105
|
-
`)):e}function
|
|
106
|
-
`)}return{installed:!0,configPath:n,message:e.postInstallHint}}function
|
|
107
|
-
`),{removed:!0,configPath:n})}function
|
|
108
|
-
${r}: ${n(e.currentPath)}`}function
|
|
109
|
-
Step 2: Checking authentication...`);let i=await $.getSessionToken();if(i)try{await new te(()=>Promise.resolve(i)).getStatus(),console.log(" Already authenticated.")}catch(
|
|
110
|
-
Step 3: Setting up authentication...`),!
|
|
111
|
-
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
|
|
112
|
-
`)[0]}`)}catch{}}else(e.yes===!1||process.stdin.isTTY)&&console.log(" Skipped. Enable any time with: visa-cli hud enable")}let
|
|
105
|
+
`)):e}function ue(e,t="global"){let n=t==="project"?p.join(process.cwd(),".mcp.json"):De(e),r=p.dirname(n);m.existsSync(r)||m.mkdirSync(r,{recursive:!0});let s=pt(e,t),o=kn();if(s==="toml"){let i=m.existsSync(n)?m.readFileSync(n,"utf-8"):"",a=ns(i,"visa-cli",o);m.writeFileSync(n,a)}else{let i={};if(m.existsSync(n))try{i=JSON.parse(m.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,m.writeFileSync(n,JSON.stringify(i,null,2)+`
|
|
106
|
+
`)}return{installed:!0,configPath:n,message:e.postInstallHint}}function ht(e,t="global"){let n=t==="project"?p.join(process.cwd(),".mcp.json"):De(e);if(!m.existsSync(n))return{removed:!1,configPath:n};if(pt(e,t)==="toml"){let i=m.readFileSync(n,"utf-8");return gt(i,"visa-cli")?(m.writeFileSync(n,rs(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(m.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"],m.writeFileSync(n,JSON.stringify(s,null,2)+`
|
|
107
|
+
`),{removed:!0,configPath:n})}function Pn(e,t="global"){let n=t==="project"?p.join(process.cwd(),".mcp.json"):De(e);if(!m.existsSync(n))return!1;if(pt(e,t)==="toml")try{let s=m.readFileSync(n,"utf-8");return!!gt(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(m.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function ss(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 os(e,t){if(e===t)return!0;let n=p.resolve(e),r=p.resolve(t);if(n===r)return!0;try{let s=m.realpathSync(n),o=m.realpathSync(r);return s===o}catch{return!1}}function de(){let e=kn(),t=e.args[e.args.length-1],n=[];for(let r of M){let s=De(r);if(!m.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let d=m.readFileSync(s,"utf-8");i=gt(d,"visa-cli")}catch{continue}else{let d;try{d=JSON.parse(m.readFileSync(s,"utf-8"))}catch{continue}i=d?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=ss(i);if(!a||os(a,t))continue;let c=m.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:c})}return n}function yt(e){return{configPath:ue(e.client,"global").configPath}}var is=(0,In.promisify)(An.execFile);function as(e,t){return process.stdin.isTTY?new Promise(n=>{let r=Rn.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 cs(e){let t=N.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
|
|
108
|
+
${r}: ${n(e.currentPath)}`}function Ln(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(cs(n))}var x=new En.Command,Me=null,fe=!1;function U(){return Me=new te(()=>$.getSessionToken()),Me}x.name("visa-cli").description("Visa CLI - AI payment orchestration").version(qe().version);x.hook("preAction",async()=>{await $t()});x.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 l=de();Ln(l,"MCP config check:"),l.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=de(),n=new Map(t.map(l=>[l.client.id,l])),r=new Set;for(let l of M)if(le(l)){let h=ue(l),v=n.get(l.id),k=v?` \u2014 repaired stale ${v.staleReason} entry`:"";console.log(` \u2713 ${l.displayName} (${h.configPath.replace(N.homedir(),"~")})${k}`),v&&r.add(l.id)}let s=t.filter(l=>!r.has(l.client.id));for(let l of s)yt(l),console.log(` \u2713 ${l.client.displayName} (${l.configPath.replace(N.homedir(),"~")}) \u2014 repaired stale ${l.staleReason} entry`);let o=r.size+s.length;console.log(o===0?" \u2713 MCP config verified \u2014 nothing to repair.":` \u2713 Repaired ${o} stale MCP config ${o===1?"entry":"entries"}.`),console.log(`
|
|
109
|
+
Step 2: Checking authentication...`);let i=await $.getSessionToken();if(i)try{await new te(()=>Promise.resolve(i)).getStatus(),console.log(" Already authenticated.")}catch(l){let h=l instanceof Error?l.message:"";h.includes("session has expired")||h.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await $.clearAll(),i=null):console.log(` Couldn't verify session (${h||"unknown error"}) \u2014 continuing with existing token.`)}if(i||(console.log(" No session found. Opening browser for GitHub login..."),i=await new Promise(async(l,h)=>{let v=Oe.randomBytes(16).toString("hex"),k=`https://auth.visacli.sh/login?state=${v}`;await xt(k);let H=3e4,V=300*1e3,B=Date.now()+V;for(;Date.now()<B;)try{let K=await globalThis.fetch("https://auth.visacli.sh/v1/auth-status",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:v,timeout:H}),signal:AbortSignal.timeout(H+5e3)});if(!K.ok)continue;let P=await K.json();if(P.status==="pending")continue;if(P.status==="expired"){h(new Error("Session expired. Please run setup again."));return}if(P.status==="complete"&&P.sessionToken){console.log(` Signed in as ${P.user}.`),l(P.sessionToken);return}}catch{}h(new Error("Login timed out after 5 minutes. Please run setup again."))}),await $.saveSessionToken(i),console.log(" Session token saved.")),console.log(`
|
|
110
|
+
Step 3: Setting up authentication...`),!D())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await is("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 l=await ke();console.log(" Attestation key generated."),await U().registerAttestationKey(l),console.log(" Attestation key registered with server.")}catch(l){console.log(` Skipped: ${l.message}`)}}let a=pe.join(N.homedir(),".claude","settings.json"),c=Tn.existsSync(pe.join(N.homedir(),".claude.json")),d=e.hud===!1;if(c&&!d){console.log(`
|
|
111
|
+
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 l;if(e.yes?(l=!0,console.log(" (--yes) Enabling Visa HUD.")):process.stdin.isTTY?l=await as(" Enable Visa HUD? [Y/n] ",!0):(l=!1,console.log(" Non-interactive shell \u2014 skipping prompt. Enable with: visa-cli hud enable")),l){let h=We(a),v=h.installed==="new"||h.installed==="already-visa"||h.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${v}${h.message}`);try{let k=U(),H=await k.getStatus(),V={currentVersion:k.getClientVersion(),latestVersion:k.lastSignals?.updateAvailable?.version,updateMessage:k.lastSignals?.updateAvailable?.message,updateCheckDisabled:z()},B=ct(H,V);ut(B),console.log(` Preview: ${B.split(`
|
|
112
|
+
`)[0]}`)}catch{}}else(e.yes===!1||process.stdin.isTTY)&&console.log(" Skipped. Enable any time with: visa-cli hud enable")}let u="\x1B[1m",f="\x1B[0m";console.log(`
|
|
113
113
|
\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
|
|
114
114
|
\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
|
|
115
115
|
\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
|
|
@@ -117,30 +117,30 @@ Step 4: Enable the Visa spend HUD?`),console.log(" Pins your spend + card info
|
|
|
117
117
|
\u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551
|
|
118
118
|
\u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2588 CLI
|
|
119
119
|
|
|
120
|
-
${
|
|
120
|
+
${u}Setup complete.${f} Restart Claude Code or run /mcp to connect.
|
|
121
121
|
|
|
122
|
-
${
|
|
122
|
+
${u}Try it out:${f}
|
|
123
123
|
\u2022 Ask Claude: "Generate an image of a neon cityscape"
|
|
124
124
|
\u2022 Ask Claude: "What's the price of ETH on Base?"
|
|
125
125
|
\u2022 Or run: visa-cli pay <merchant-url>
|
|
126
126
|
|
|
127
|
-
${
|
|
128
|
-
${
|
|
129
|
-
${
|
|
130
|
-
`)}catch(t){console.error("Error:",t.message),process.exit(1)}});x.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=
|
|
127
|
+
${u}Verify:${f} visa-cli status
|
|
128
|
+
${u}HUD:${f} Restart Claude Code to see your spend pinned below the input
|
|
129
|
+
${u}Docs:${f} https://visacli.sh
|
|
130
|
+
`)}catch(t){console.error("Error:",t.message),process.exit(1)}});x.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=de();Ln(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=de();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)yt(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(N.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
|
|
131
131
|
Repaired ${o.length} stale MCP config ${o.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
|
|
132
132
|
\x1B[1mSupported MCP Clients\x1B[0m
|
|
133
|
-
`),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
|
|
134
|
-
Supported clients: ${
|
|
135
|
-
Supported clients: ${
|
|
136
|
-
`);let a=(await s.getStatus()).attestationRequired!==!1,
|
|
137
|
-
Result URLs:`);for(let
|
|
138
|
-
`)}return{transactions:[]}});process.stdout.write(
|
|
139
|
-
`);try{await
|
|
140
|
-
Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}});x.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
|
|
141
|
-
`)});ee.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(f,
|
|
142
|
-
`);let s=
|
|
133
|
+
`),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 M){let c=le(a),d=Pn(a),u=c?"Yes":"No",f=d?"Yes":"No",l=a.globalConfigPath.replace(N.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${f.padEnd(11)} ${l}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of M){if(!le(a)){i.push(a.displayName);continue}ue(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(`
|
|
134
|
+
Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let r=ft(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!le(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=ue(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)}});x.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 M)ht(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(`
|
|
135
|
+
Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let r=ft(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let s=ht(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)}});x.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{yn(e);let n=Sn(t.method),r=bn(t.body),s=new te(()=>$.getSessionToken());console.log(`Checking payment for ${e}...`);let o=vn(await s.paymentPreview({url:e}));console.log(` Merchant: ${o.merchantName}`),console.log(` Amount: $${o.amount.toFixed(2)} ${o.currency}`),console.log(` Rail: auto-detected
|
|
136
|
+
`);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=Oe.randomUUID(),d=await dt(s,async()=>{let u;if(a&&D())try{let{nonce:f}=await s.getAttestationChallenge(),l=Buffer.from(JSON.stringify({nonce:f,amount:o.amount,merchant:o.merchantName,context:e})).toString("base64");u={signature:await nt(l,`pay $${o.amount.toFixed(2)} to ${o.merchantName}`),nonce:f,amount:o.amount,merchant:o.merchantName}}catch(f){throw new Error(`Touch ID confirmation failed: ${f?.message||"user cancelled or biometric error"}`)}return s.pay({url:e,method:n,body:r,attestation:u,idempotencyKey:c})});if(d.success){if(console.log(`Payment complete: $${(d.amount??o.amount).toFixed(2)} \u2192 ${d.merchantName??o.merchantName}`),d.receipt?.urls?.length){console.log(`
|
|
137
|
+
Result URLs:`);for(let u of d.receipt.urls)console.log(` ${u}`)}}else console.error(`Payment failed: ${d.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof R?console.error(`Error: ${n.message}`):console.error("Error:",n.message),process.exit(1)}});x.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{fe=!1;try{let e=U(),t=await e.getStatus(),n={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.version,updateMessage:e.lastSignals.updateAvailable?.message,updateCheckDisabled:z()},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}
|
|
138
|
+
`)}return{transactions:[]}});process.stdout.write(rn(t,Array.isArray(r?.transactions)?r.transactions:[],D(),n)),fe=!0}catch(e){fe=!1,console.error("Error:",e.message),process.exit(1)}});x.command("reset").description("Log out and clear all credentials").action(async()=>{try{console.log(`Resetting Visa CLI...
|
|
139
|
+
`);try{await U().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 Qt(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
|
|
140
|
+
Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}});x.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 U().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}});var St=x.command("biometric").description("Manage Touch ID / biometric attestation enforcement");St.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 U().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)}});St.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=U(),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)}});St.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=U(),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 dt(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 nt(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 ee=x.command("shell-hud").description("Manage the persistent Visa HUD shown in your shell prompt");function Nn(){let e=un();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Dn(){let e=dn();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}ee.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Nn);ee.command("enable").description("Enable the persistent shell HUD").action(Nn);ee.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Dn);ee.command("disable").description("Disable the persistent shell HUD").action(Dn);ee.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${lt()}
|
|
141
|
+
`)});ee.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(f,l,h)=>{console.log(` ${l?"\u2713":"\u2717"} ${f}: ${h}`),l||(n=!1)};console.log(`Shell HUD Doctor
|
|
142
|
+
`);let s=Le();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let f=Ne(s),l=e(f);if(r("RC file exists",l,f.replace(N.homedir(),"~")),l){let v=t(f,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",v,v?"found in rc file":"missing \u2014 run: visa-cli shell-hud install")}}let o=ce(),i=e(o);if(r("Cache file",i,i?o.replace(N.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let f=JSON.parse(t(o,"utf-8")),l=Date.now()-(f.renderedAt??0),h=Math.round(l/1e3),v=h<=30;console.log(` ${v?"\u2713":"\u26A0"} Cache freshness: ${h}s old${v?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=Ie(),c=e(a),d="missing";if(c)try{d=t(a,"utf-8").trim().slice(0,80)}catch{d="unreadable"}r("Line file",c,d);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 U().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(f){let l=f instanceof Error?f.message:"unknown error";r("API connectivity",!1,l)}console.log(n?`
|
|
143
143
|
All checks passed.`:`
|
|
144
|
-
Some checks failed \u2014 see above.`),n||process.exit(1)});ee.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&&
|
|
145
|
-
`)[0],r=await
|
|
146
|
-
`)});var
|
|
144
|
+
Some checks failed \u2014 see above.`),n||process.exit(1)});ee.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&&fn()))try{let t=U(),n=await t.getStatus(),r={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.version,updateMessage:t.lastSignals.updateAvailable?.message,updateCheckDisabled:z()},s=ct(n,r);ut(s)}catch{}finally{ae()}});x.command("statusline").description("Output the multi-line Visa HUD for Claude Code statusLine integration").action(async()=>{let e=await Mt(),n=lt().split(`
|
|
145
|
+
`)[0],r=await jt(n,e);process.stdout.write(`${r}
|
|
146
|
+
`)});var Mn=x.command("hud").description("Manage the Visa HUD pinned below Claude Code input");Mn.command("enable").description("Register Visa HUD as the Claude Code statusLine").action(()=>{let e=pe.join(N.homedir(),".claude","settings.json"),t=We(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Mn.command("disable").description("Remove Visa HUD from Claude Code statusLine (leaves other tools untouched)").action(()=>{let e=pe.join(N.homedir(),".claude","settings.json"),t=At(e);console.log(t.message),t.removed||process.exit(1)});x.hook("postAction",()=>{if(fe){fe=!1;return}Me&&tn(Me.lastSignals)});x.parse();
|