@visa/cli 1.1.2 → 1.2.0-rc.0
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/README.md +19 -11
- package/dist/cli.js +40 -40
- package/dist/mcp-server/index.js +21 -21
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
# @visa/cli
|
|
2
2
|
|
|
3
|
-
AI-powered payments over MCP. Exposes Visa card payment tools as MCP (Model Context Protocol) tools so your AI assistant can pay for image generation, video, music, onchain data queries, and more — charged to a Visa card with
|
|
3
|
+
AI-powered payments over MCP. Exposes Visa card payment tools as MCP (Model Context Protocol) tools so your AI assistant can pay for image generation, video, music, onchain data queries, and more — charged to a Visa card with authentication confirmation at the point of invocation.
|
|
4
|
+
|
|
5
|
+
### Platform support
|
|
6
|
+
|
|
7
|
+
| Platform | Credential Storage | Payment Auth | Install |
|
|
8
|
+
|----------|-------------------|--------------|---------|
|
|
9
|
+
| **macOS** | Keychain | Touch ID / Secure Enclave | `bash <(curl -fsSL ...)` or `npm i -g @visa/cli` |
|
|
10
|
+
| **Windows** | ACL-restricted file | Server-verified (restricted limits) | `npm i -g @visa/cli` or PowerShell installer |
|
|
11
|
+
| **Linux** | libsecret (GNOME Keyring / KDE Wallet) | Server-verified (restricted limits) | `bash <(curl -fsSL ...)` or `npm i -g @visa/cli` |
|
|
4
12
|
|
|
5
13
|
## Install
|
|
6
14
|
|
|
@@ -58,13 +66,13 @@ Cards are tokenized via VGS — your raw card number never touches Visa servers.
|
|
|
58
66
|
visa-cli add-card
|
|
59
67
|
```
|
|
60
68
|
|
|
61
|
-
Multiple cards can be enrolled. The first becomes the default; you can switch defaults with `set_default_card` from within your assistant. To remove a card: `remove_card` (requires
|
|
69
|
+
Multiple cards can be enrolled. The first becomes the default; you can switch defaults with `set_default_card` from within your assistant. To remove a card: `remove_card` (requires authentication).
|
|
62
70
|
|
|
63
71
|
---
|
|
64
72
|
|
|
65
|
-
## Payments &
|
|
73
|
+
## Payments & Authentication
|
|
66
74
|
|
|
67
|
-
Every paid tool call requires Touch ID (or device password on
|
|
75
|
+
Every paid tool call requires authentication. On macOS, this is Touch ID (or device password); on Windows and Linux, payments are server-verified with restricted spending limits. Your assistant will show you the amount and merchant before prompting. If you cancel, the payment is aborted — nothing is charged.
|
|
68
76
|
|
|
69
77
|
You can set hard limits via the `update_spending_controls` tool, or check your current limits any time:
|
|
70
78
|
|
|
@@ -83,10 +91,10 @@ visa-cli status
|
|
|
83
91
|
| `login` | GitHub OAuth login — opens browser |
|
|
84
92
|
| `add_card` | Enroll a card via VGS tokenization |
|
|
85
93
|
| `get_cards` | List enrolled cards (masked) |
|
|
86
|
-
| `remove_card` | Remove an enrolled card (
|
|
87
|
-
| `set_default_card` | Change the default card (
|
|
94
|
+
| `remove_card` | Remove an enrolled card (authentication required) |
|
|
95
|
+
| `set_default_card` | Change the default card (authentication required) |
|
|
88
96
|
| `get_status` | Auth, card, spend limits, and budget summary |
|
|
89
|
-
| `update_spending_controls` | Set daily and per-transaction limits (
|
|
97
|
+
| `update_spending_controls` | Set daily and per-transaction limits (authentication required) |
|
|
90
98
|
| `transaction_history` | Recent transactions with amounts and media URLs |
|
|
91
99
|
| `feedback` | Submit feedback on a tool result |
|
|
92
100
|
| `reset` | Clear auth state and credentials |
|
|
@@ -119,7 +127,7 @@ visa-cli status
|
|
|
119
127
|
| Tool | Description |
|
|
120
128
|
|------|-------------|
|
|
121
129
|
| `pay` | Generic HTTP 402 payment endpoint |
|
|
122
|
-
| `batch` | Execute multiple paid tools in one
|
|
130
|
+
| `batch` | Execute multiple paid tools in one authentication approval |
|
|
123
131
|
| `discover_tools` | Search the dynamic tool catalog |
|
|
124
132
|
| `execute_tool` | Run a tool from the dynamic catalog by ID |
|
|
125
133
|
|
|
@@ -142,7 +150,7 @@ Daily limit — hard cap on total spend per day
|
|
|
142
150
|
Max per-transaction — hard cap per single tool call
|
|
143
151
|
```
|
|
144
152
|
|
|
145
|
-
Both limits are enforced server-side.
|
|
153
|
+
Both limits are enforced server-side. Authentication is always required per payment regardless of limits — this cannot be disabled. On macOS this means Touch ID; on other platforms, server-side verification with restricted spending limits applies.
|
|
146
154
|
|
|
147
155
|
---
|
|
148
156
|
|
|
@@ -158,8 +166,8 @@ Both limits are enforced server-side. Touch ID is always required per payment re
|
|
|
158
166
|
|
|
159
167
|
## Troubleshooting
|
|
160
168
|
|
|
161
|
-
**Touch ID prompt doesn't appear**
|
|
162
|
-
Make sure `visa-cli mcp` is running as a foreground process that has access to the macOS security framework. Running inside some sandboxed environments may prevent Touch ID.
|
|
169
|
+
**Touch ID prompt doesn't appear (macOS)**
|
|
170
|
+
Make sure `visa-cli mcp` is running as a foreground process that has access to the macOS security framework. Running inside some sandboxed environments may prevent Touch ID. On Windows and Linux, biometric prompts are not used — payments are server-verified.
|
|
163
171
|
|
|
164
172
|
**"Not logged in" after `visa-cli login`**
|
|
165
173
|
Restart the MCP server after logging in — your MCP client needs to reconnect to pick up the new session.
|
package/dist/cli.js
CHANGED
|
@@ -1,38 +1,40 @@
|
|
|
1
|
-
"use strict";var Zt=Object.create;var fe=Object.defineProperty;var Qt=Object.getOwnPropertyDescriptor;var en=Object.getOwnPropertyNames;var tn=Object.getPrototypeOf,nn=Object.prototype.hasOwnProperty;var f=(t,e)=>()=>(t&&(e=t(t=0)),e);var rn=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),on=(t,e)=>{for(var n in e)fe(t,n,{get:e[n],enumerable:!0})},sn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of en(e))!nn.call(t,o)&&o!==n&&fe(t,o,{get:()=>e[o],enumerable:!(r=Qt(e,o))||r.enumerable});return t};var p=(t,e,n)=>(n=t!=null?Zt(tn(t)):{},sn(e||!t||!t.__esModule?fe(n,"default",{value:t,enumerable:!0}):n,t));async function je(){try{let{stdout:t}=await R("security",["find-generic-password","-s",A,"-a",Z,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function qe(t){try{try{await R("security",["delete-generic-password","-s",A,"-a",Z],{timeout:5e3})}catch{}return await R("security",["add-generic-password","-s",A,"-a",Z,"-w",t],{timeout:5e3}),!0}catch{return!1}}async function Fe(){try{await R("security",["delete-generic-password","-s",A,"-a",Z],{timeout:5e3})}catch{}}async function an(){try{let{stdout:t}=await R("security",["find-generic-password","-s",A,"-a",Q,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function cn(t){try{try{await R("security",["delete-generic-password","-s",A,"-a",Q],{timeout:5e3})}catch{}await R("security",["add-generic-password","-s",A,"-a",Q,"-w",t],{timeout:5e3})}catch{}}async function ln(){try{await R("security",["delete-generic-password","-s",A,"-a",Q],{timeout:5e3})}catch{}}function un(t){C.mkdirSync(ye,{recursive:!0,mode:448}),C.writeFileSync(X,t,{mode:384})}function dn(){try{return C.readFileSync(X,"utf-8").trim()||null}catch{return null}}var De,Ve,C,He,he,R,ye,X,A,Z,Q,g,K=f(()=>{"use strict";De=require("child_process"),Ve=require("util"),C=p(require("fs")),He=p(require("os")),he=p(require("path")),R=(0,Ve.promisify)(De.execFile),ye=he.join(He.homedir(),".visa-mcp"),X=he.join(ye,"session-token"),A="visa-cli",Z="session-token",Q="rc-access";g=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let e=await je();if(e)return e;let n=dn();return n?(await qe(n),n):null}static async saveSessionToken(e){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;if(await qe(e)){if(await je()===e){try{C.unlinkSync(X)}catch{}return}await Fe()}if(un(e),await this.getSessionToken()!==e)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${ye} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":an()}static async saveRcAccessToken(e){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await cn(e)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN!=="true"){await Fe();try{C.unlinkSync(X)}catch{}}}static async clearAll(){await this.deleteSessionToken(),await ln()}}});var _e=rn((Gn,mn)=>{mn.exports={name:"@visa/cli",version:"1.1.2",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"},files:["bin/visa-cli.js","dist/","native/visa-keychain.m","README.md","LICENSE"]}});async function ze(t,e){let n=e?.timeoutMs??3e4,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let{timeoutMs:s,...a}=e??{};return await fetch(t,{...a,signal:r.signal})}finally{clearTimeout(o)}}var Ye=f(()=>{"use strict"});function Xe(t,e){let n=Je(t),r=Je(e);if(!n||!r)return!1;for(let o=0;o<3;o++)if(n.main[o]!==r.main[o])return n.main[o]>r.main[o];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Sn(n.pre,r.pre)>0}function Je(t){if(typeof t!="string")return null;let n=t.trim().replace(/^v/,"").match(wn);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Sn(t,e){let n=t.split("."),r=e.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let a=n[s],i=r[s],l=/^\d+$/.test(a),c=/^\d+$/.test(i);if(l&&c){let u=Number(a)-Number(i);if(u!==0)return u}else{if(l)return-1;if(c)return 1;if(a<i)return-1;if(a>i)return 1}}return 0}var wn,Ze=f(()=>{"use strict";wn=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/});function re(){return!!(Qe(process.env.VISA_CLI_NO_UPDATE_CHECK)||Qe(process.env.CI)||process.env.NODE_ENV==="test")}function Qe(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return!(e===""||e==="0"||e==="false"||e==="no"||e==="off")}var Se=f(()=>{"use strict"});var be,$,oe=f(()=>{"use strict";Ye();Ze();Se();be="1.1.2",$=class{constructor(e){this.getSessionToken=e;this.baseUrl=process.env.VISA_AUTH_URL||"https://auth.visacli.sh"}getSessionToken;baseUrl;lastSignals={};parseServerSignals(e){if(this.lastSignals={},!re()){let r=e.headers.get("X-Latest-Version"),o=e.headers.get("X-Update-Message");r&&Xe(r,be)&&(this.lastSignals.updateAvailable={version:r,message:o||`Update available: v${r}. Run: npm install -g @visa/cli && visa-cli setup`})}let n=e.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return be}async request(e,n,r,o,s){let a=await this.getSessionToken();if(!a)throw new Error("Not logged in. Sign up at https://visacli.sh or run: visa-cli setup");let i={Authorization:`Bearer ${a}`};s&&(e==="GET"?i["X-User-Context"]=s.replace(/[\r\n\0]/g," ").slice(0,1e3):r={...r||{},user_context:s}),r&&(i["Content-Type"]="application/json");let l;try{l=await ze(`${this.baseUrl}${n}`,{method:e,headers:{...i,"X-Visa-CLI-Version":be},body:r?JSON.stringify(r):void 0,timeoutMs:o})}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(l),l.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(l.status===429){let u=l.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(l.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let c;try{c=await l.json()}catch{throw l.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!l.ok)throw l.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(c?.error||`Request failed (${l.status}). Try again.`);return c}async pay(e,n){return this.request("POST","/v1/pay",e,void 0,n)}async shortcut(e,n,r,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(e)}`,n,r,o)}async batch(e,n,r){return this.request("POST","/v1/batch",e,n,r)}async catalogSearch(e,n){let r=new URLSearchParams;e&&r.set("q",e),n&&r.set("category",n);let o=r.toString();return this.request("GET",`/v1/catalog${o?`?${o}`:""}`)}async catalogTool(e){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(e)}`)}catch{return null}}async paymentPreview(e,n){return this.request("POST","/v1/payment-preview",e,void 0,n)}async getStatus(e){return this.request("GET","/v1/status",void 0,void 0,e)}async getTransactions(e){return this.request("GET","/v1/transactions",void 0,void 0,e)}async updateSpendingControls(e,n){return this.request("POST","/v1/spending-controls",e,void 0,n)}async removeCard(e,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(e))}`,n,void 0,r)}async setDefaultCard(e,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(e))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(e){return this.request("POST","/v1/attestation-key",{publicKey:e})}async logout(e,n){return this.request("POST","/v1/logout",e,void 0,n)}async feedback(e,n,r){return this.request("POST","/v1/feedback",{message:e,...n&&{transaction_id:n}},void 0,r)}async feedSubmit(e){return this.request("POST","/v1/feed",e)}async feedList(e){let n=new URLSearchParams;e?.tab&&n.set("tab",e.tab),e?.limit&&n.set("limit",String(e.limit)),e?.offset&&n.set("offset",String(e.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(e,n){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/vote`,{direction:n})}async feedApprove(e){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/approve`)}async feedDelete(e){return this.request("DELETE",`/v1/feed/${encodeURIComponent(e)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(e,n,r){return this.request("POST","/v1/feedback",{message:e,...n&&{transaction_id:n}},void 0,r)}async getFeedback(e,n){let r=new URLSearchParams;e&&r.set("limit",String(e));let o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(e){return this.request("POST","/v1/feedback",e)}}});function vn(){w.existsSync(xe)||w.mkdirSync(xe,{recursive:!0,mode:448})}function xn(){if(!ve){if(vn(),w.existsSync(B)&&w.statSync(B).size>bn){let e=B+".1";w.existsSync(e)&&w.unlinkSync(e),w.renameSync(B,e)}ve=w.createWriteStream(B,{flags:"a"})}return ve}function se(t,...e){let n=new Date().toISOString(),r=e.map(s=>typeof s=="string"?s:JSON.stringify(s,null,2)).join(" "),o=`[${n}] [${t}] ${r}
|
|
2
|
-
|
|
1
|
+
"use strict";var rn=Object.create;var ye=Object.defineProperty;var on=Object.getOwnPropertyDescriptor;var sn=Object.getOwnPropertyNames;var an=Object.getPrototypeOf,cn=Object.prototype.hasOwnProperty;var g=(t,e)=>()=>(t&&(e=t(t=0)),e);var ln=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),un=(t,e)=>{for(var n in e)ye(t,n,{get:e[n],enumerable:!0})},dn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sn(e))!cn.call(t,o)&&o!==n&&ye(t,o,{get:()=>e[o],enumerable:!(r=on(e,o))||r.enumerable});return t};var p=(t,e,n)=>(n=t!=null?rn(an(t)):{},dn(e||!t||!t.__esModule?ye(n,"default",{value:t,enumerable:!0}):n,t));async function pn(){try{let{stdout:t}=await $("security",["find-generic-password","-s",v,"-a",A,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function gn(t){try{try{await $("security",["delete-generic-password","-s",v,"-a",A],{timeout:5e3})}catch{}return await $("security",["add-generic-password","-s",v,"-a",A,"-w",t],{timeout:5e3}),!0}catch{return!1}}async function fn(){try{await $("security",["delete-generic-password","-s",v,"-a",A],{timeout:5e3})}catch{}}async function hn(){if(!xe())return null;try{let{stdout:t}=await $("secret-tool",["lookup","service",v,"account",A],{timeout:5e3});return t.trim()||null}catch{return null}}async function yn(t){if(!xe())return!1;try{let e=(0,ee.execFile)("secret-tool",["store","--label",`${v} ${A}`,"service",v,"account",A]);return e.stdin?(e.stdin.write(t),e.stdin.end(),await Promise.race([new Promise((n,r)=>{e.on("exit",o=>o===0?n():r(new Error(`secret-tool exited ${o}`))),e.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{e.kill(),r(new Error("secret-tool timed out"))},mn))]),!0):!1}catch{return!1}}async function _n(){if(xe())try{await $("secret-tool",["clear","service",v,"account",A],{timeout:5e3})}catch{}}function xe(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function wn(){try{let{stdout:t}=await $("security",["find-generic-password","-s",v,"-a",Q,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function bn(t){try{try{await $("security",["delete-generic-password","-s",v,"-a",Q],{timeout:5e3})}catch{}await $("security",["add-generic-password","-s",v,"-a",Q,"-w",t],{timeout:5e3})}catch{}}async function Sn(){try{await $("security",["delete-generic-password","-s",v,"-a",Q],{timeout:5e3})}catch{}}function we(){try{return M.readFileSync(Z,"utf-8").trim()||null}catch{return null}}function Ge(t){M.mkdirSync(ve,{recursive:!0,mode:448}),M.writeFileSync(Z,t,{mode:384}),process.platform==="win32"&&vn(Z)}function be(){try{M.unlinkSync(Z)}catch{}}function vn(t){try{let e=te.userInfo().username;(0,ee.execFile)("icacls",[t,"/inheritance:r","/grant:r",`${e}:F`],{timeout:5e3},n=>{n&&console.error(`[visa-cli] icacls ACL restriction failed: ${n.message}`)})}catch(e){console.error(`[visa-cli] Failed to invoke icacls: ${e instanceof Error?e.message:String(e)}`)}}function _e(){switch(process.platform){case"darwin":return{get:pn,store:gn,delete:fn};case"linux":return{get:hn,store:yn,delete:_n};default:return{get:async()=>we(),store:async t=>{try{return Ge(t),!0}catch{return!1}},delete:async()=>be()}}}var ee,Be,M,te,Se,$,ve,Z,v,A,Q,mn,f,B=g(()=>{"use strict";ee=require("child_process"),Be=require("util"),M=p(require("fs")),te=p(require("os")),Se=p(require("path")),$=(0,Be.promisify)(ee.execFile),ve=Se.join(te.homedir(),".visa-mcp"),Z=Se.join(ve,"session-token"),v="visa-cli",A="session-token",Q="rc-access",mn=5e3;f=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let e=_e(),n=await e.get();if(n)return n;let r=we();return r?(await e.store(r),r):null}static async saveSessionToken(e){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=_e();if(await n.store(e)){if(await n.get()===e){be();return}await n.delete()}if(Ge(e),we()!==e)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${ve} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":wn()}static async saveRcAccessToken(e){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await bn(e)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await _e().delete(),be()}static async clearAll(){await this.deleteSessionToken(),await Sn()}}});var Pe=ln((nr,xn)=>{xn.exports={name:"@visa/cli",version:"1.2.0-rc.0",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"},files:["bin/visa-cli.js","dist/","native/visa-keychain.m","README.md","LICENSE"]}});function Je(t=process.env,e=process.platform){return t.VISA_CLI_NO_BROWSER==="1"||t.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:t.CI==="true"||t.CI==="1"?{headless:!0,reason:"CI environment detected"}:t.SSH_CONNECTION||t.SSH_TTY?{headless:!0,reason:"SSH session detected"}:e==="linux"&&!t.DISPLAY&&!t.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function $n(t){let n=t.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${t}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
|
|
2
|
+
`)}function Xe(t,e=process.platform){return e==="darwin"?{cmd:"open",args:[t]}:e==="win32"?{cmd:"cmd",args:["/c","start","",t]}:e==="linux"?{cmd:"xdg-open",args:[t]}:null}async function Ze(t,e={}){let n=e.log??(l=>console.log(l)),r=e.env??process.env,o=e.platform??process.platform,s=e.spawn??((l,c,u)=>{(0,Ye.execFile)(l,c,_=>u(_))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let l of $n(t).split(`
|
|
3
|
+
`))n(` ${l}`);n("");let a=Je(r,o);if(a.headless){n(` (${a.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 i=Xe(t,o);if(!i){n(` No known browser-open command for platform "${o}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(l=>{s(i.cmd,i.args,c=>{c?(n(` Could not open browser automatically (${c.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()})})}var Ye,Te=g(()=>{"use strict";Ye=require("child_process")});async function Qe(t,e){let n=e?.timeoutMs??3e4,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let{timeoutMs:s,...a}=e??{};return await fetch(t,{...a,signal:r.signal})}finally{clearTimeout(o)}}var et=g(()=>{"use strict"});function nt(t,e){let n=tt(t),r=tt(e);if(!n||!r)return!1;for(let o=0;o<3;o++)if(n.main[o]!==r.main[o])return n.main[o]>r.main[o];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Cn(n.pre,r.pre)>0}function tt(t){if(typeof t!="string")return null;let n=t.trim().replace(/^v/,"").match(kn);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Cn(t,e){let n=t.split("."),r=e.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let a=n[s],i=r[s],l=/^\d+$/.test(a),c=/^\d+$/.test(i);if(l&&c){let u=Number(a)-Number(i);if(u!==0)return u}else{if(l)return-1;if(c)return 1;if(a<i)return-1;if(a>i)return 1}}return 0}var kn,rt=g(()=>{"use strict";kn=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/});function se(){return!!(ot(process.env.VISA_CLI_NO_UPDATE_CHECK)||ot(process.env.CI)||process.env.NODE_ENV==="test")}function ot(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return!(e===""||e==="0"||e==="false"||e==="no"||e==="off")}var $e=g(()=>{"use strict"});var ke,C,ie=g(()=>{"use strict";et();rt();$e();ke="1.2.0-rc.0",C=class{constructor(e){this.getSessionToken=e;this.baseUrl=process.env.VISA_AUTH_URL||"https://auth.visacli.sh"}getSessionToken;baseUrl;lastSignals={};parseServerSignals(e){if(this.lastSignals={},!se()){let r=e.headers.get("X-Latest-Version"),o=e.headers.get("X-Update-Message");r&&nt(r,ke)&&(this.lastSignals.updateAvailable={version:r,message:o||`Update available: v${r}. Run: npm install -g @visa/cli && visa-cli setup`})}let n=e.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return ke}async request(e,n,r,o,s){let a=await this.getSessionToken();if(!a)throw new Error("Not logged in. Sign up at https://visacli.sh or run: visa-cli setup");let i={Authorization:`Bearer ${a}`};s&&(e==="GET"?i["X-User-Context"]=s.replace(/[\r\n\0]/g," ").slice(0,1e3):r={...r||{},user_context:s}),r&&(i["Content-Type"]="application/json");let l;try{l=await Qe(`${this.baseUrl}${n}`,{method:e,headers:{...i,"X-Visa-CLI-Version":ke},body:r?JSON.stringify(r):void 0,timeoutMs:o})}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(l),l.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(l.status===429){let u=l.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(l.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let c;try{c=await l.json()}catch{throw l.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!l.ok)throw l.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(c?.error||`Request failed (${l.status}). Try again.`);return c}async pay(e,n){return this.request("POST","/v1/pay",e,void 0,n)}async shortcut(e,n,r,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(e)}`,n,r,o)}async batch(e,n,r){return this.request("POST","/v1/batch",e,n,r)}async catalogSearch(e,n){let r=new URLSearchParams;e&&r.set("q",e),n&&r.set("category",n);let o=r.toString();return this.request("GET",`/v1/catalog${o?`?${o}`:""}`)}async catalogTool(e){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(e)}`)}catch{return null}}async paymentPreview(e,n){return this.request("POST","/v1/payment-preview",e,void 0,n)}async getStatus(e){return this.request("GET","/v1/status",void 0,void 0,e)}async getTransactions(e){return this.request("GET","/v1/transactions",void 0,void 0,e)}async updateSpendingControls(e,n){return this.request("POST","/v1/spending-controls",e,void 0,n)}async removeCard(e,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(e))}`,n,void 0,r)}async setDefaultCard(e,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(e))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(e){return this.request("POST","/v1/attestation-key",{publicKey:e})}async logout(e,n){return this.request("POST","/v1/logout",e,void 0,n)}async feedback(e,n,r){return this.request("POST","/v1/feedback",{message:e,...n&&{transaction_id:n}},void 0,r)}async feedSubmit(e){return this.request("POST","/v1/feed",e)}async feedList(e){let n=new URLSearchParams;e?.tab&&n.set("tab",e.tab),e?.limit&&n.set("limit",String(e.limit)),e?.offset&&n.set("offset",String(e.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(e,n){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/vote`,{direction:n})}async feedApprove(e){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/approve`)}async feedDelete(e){return this.request("DELETE",`/v1/feed/${encodeURIComponent(e)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(e,n,r){return this.request("POST","/v1/feedback",{message:e,...n&&{transaction_id:n}},void 0,r)}async getFeedback(e,n){let r=new URLSearchParams;e&&r.set("limit",String(e));let o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(e){return this.request("POST","/v1/feedback",e)}}});function Rn(){w.existsSync(Ie)||w.mkdirSync(Ie,{recursive:!0,mode:448})}function An(){if(!Ce){if(Rn(),w.existsSync(G)&&w.statSync(G).size>In){let e=G+".1";w.existsSync(e)&&w.unlinkSync(e),w.renameSync(G,e)}Ce=w.createWriteStream(G,{flags:"a"})}return Ce}function ae(t,...e){let n=new Date().toISOString(),r=e.map(s=>typeof s=="string"?s:JSON.stringify(s,null,2)).join(" "),o=`[${n}] [${t}] ${r}
|
|
4
|
+
`;process.stderr.write(o),An().write(o)}var w,Re,st,Ie,G,In,Ce,N,Ae=g(()=>{"use strict";w=p(require("fs")),Re=p(require("path")),st=p(require("os")),Ie=Re.join(st.homedir(),".visa-mcp"),G=Re.join(Ie,"mcp-server.log"),In=5*1024*1024,Ce=null;N={debug:(...t)=>ae("DEBUG",...t),info:(...t)=>ae("INFO",...t),warn:(...t)=>ae("WARN",...t),error:(...t)=>ae("ERROR",...t)}});function lt(t){let e=h.readFileSync(t);return dt.createHash("sha256").update(e).digest("hex")}async function pt(){try{if(h.readFileSync(at,"utf-8").trim()===it&&h.existsSync(U)){let r=h.readFileSync(ct,"utf-8").trim();if(lt(U)!==r)N.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),h.unlinkSync(U);else return U}}catch{}let t=k.join(Mn,"visa-keychain.m");if(h.existsSync(t)||(t=k.resolve(__dirname,"..","..","native","visa-keychain.m")),h.existsSync(t)||(t=k.resolve(__dirname,"..","native","visa-keychain.m")),!h.existsSync(t))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");h.mkdirSync(ue,{recursive:!0,mode:448});try{await F("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",U,t],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let e=lt(U);return h.writeFileSync(ct,e,{mode:384}),h.writeFileSync(at,it,{mode:384}),U}async function gt(t){let e=await pt(),n;try{n=(await F(e,t,{timeout:6e4})).stdout}catch(s){n=s.stdout||"";let a=n.trim();throw a.startsWith("ERROR:")?new Error(a.slice(6)):new Error(s.stderr?.trim()||s.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let o=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(o)}function j(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:Me!==null?Me:(Me=!0,!0)}async function Nn(t){try{await F("security",["delete-generic-password","-s",ce,"-a",le],{timeout:5e3})}catch{}await F("security",["add-generic-password","-s",ce,"-a",le,"-w",t],{timeout:5e3})}async function On(){try{let{stdout:t}=await F("security",["find-generic-password","-s",ce,"-a",le,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function ft(){let t=await gt(["generate-key"]);if(!t)throw new Error("Key generation returned no output");let e=t.indexOf(":");if(e<0)throw new Error("Unexpected generate-key output format");let n=t.slice(0,e),r=t.slice(e+1);return await Nn(n),r}async function de(t,e){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await On();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await pt(),o=["sign",t];return e&&o.push(e),new Promise((s,a)=>{let i=(0,Ne.execFile)(r,o,{timeout:6e4},(l,c)=>{let u=(c||"").trim();if(l){u.startsWith("ERROR:")?a(new Error(u.slice(6))):a(new Error(l.stderr?.trim()||l.message||"Unknown error"));return}u.startsWith("OK:")?s(u.slice(3)):a(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});i.stdin.write(n),i.stdin.end()})}async function Oe(){try{await F("security",["delete-generic-password","-s",ce,"-a",le],{timeout:5e3})}catch{}try{await gt(["delete-key"])}catch{}}var Ne,ut,dt,h,mt,k,F,ue,U,Mn,it,at,ct,Me,ce,le,Le=g(()=>{"use strict";Ne=require("child_process"),ut=require("util"),dt=p(require("crypto")),h=p(require("fs")),mt=p(require("os")),k=p(require("path"));Ae();F=(0,ut.promisify)(Ne.execFile),ue=k.join(mt.homedir(),".visa-mcp","bin"),U=k.join(ue,"Visa CLI"),Mn=k.join(__dirname,"..","native"),it="5",at=k.join(ue,"visa-keychain.version"),ct=k.join(ue,"visa-keychain.sha256");Me=null;ce="visa-cli",le="attestation-key"});async function me(t){let{model:e,messages:n,tools:r,maxTokens:o=4096,temperature:s=.7,attestation:a,sessionBudgetId:i}=t;return await jn.shortcut(e,{prompt:"",messages:n,...r?.length?{tools:r}:{},max_tokens:o,temperature:s,...a?{attestation:a}:{},...i?{session_budget_id:i}:{}},12e4)}function Tt(t,e){let n={"or-claude-sonnet":{inPerM:3,outPerM:15},"or-gpt-4o":{inPerM:5,outPerM:15},"or-gpt-4o-mini":{inPerM:.15,outPerM:.6},"or-gemini-pro":{inPerM:.25,outPerM:1},"or-llama-70b":{inPerM:.59,outPerM:.79},"or-deepseek-chat":{inPerM:.27,outPerM:1.1},"or-deepseek-r1":{inPerM:.55,outPerM:2.19},"or-mistral-large":{inPerM:2,outPerM:6}},r=n[e]||n["or-gpt-4o-mini"],o=t.prompt_tokens/1e6*r.inPerM*100,s=t.completion_tokens/1e6*r.outPerM*100;return Math.ceil(o+s)}var jn,De=g(()=>{"use strict";ie();B();jn=new C(()=>f.getSessionToken())});function kt(t){let e=[];e.push(`You are an AI coding assistant powered by Visa CLI.
|
|
3
5
|
You can read, write, and edit files. You can run shell commands.
|
|
4
6
|
You can generate images, music, video, and query data \u2014 each costs money.
|
|
5
7
|
The user pays per-use via their Visa card. Show costs before expensive operations.
|
|
6
8
|
|
|
7
|
-
Working directory: ${t}`);let n=
|
|
9
|
+
Working directory: ${t}`);let n=Fe.join(t,"CLAUDE.md");if(H.existsSync(n)){let o=H.readFileSync(n,"utf-8");e.push(`
|
|
8
10
|
--- Project Context (CLAUDE.md) ---
|
|
9
|
-
${o.slice(0,4e3)}`)}let r=
|
|
11
|
+
${o.slice(0,4e3)}`)}let r=Fe.join(t,".env");if(H.existsSync(r)){let o=H.readFileSync(r,"utf-8").split(`
|
|
10
12
|
`).filter(s=>s.includes("=")&&!s.startsWith("#")).map(s=>s.split("=")[0]);o.length&&e.push(`
|
|
11
|
-
Environment variables present: ${o.join(", ")}`)}try{let o=(0
|
|
13
|
+
Environment variables present: ${o.join(", ")}`)}try{let o=(0,$t.execSync)("git branch --show-current",{cwd:t,encoding:"utf-8"}).trim();e.push(`
|
|
12
14
|
Git branch: ${o}`)}catch{}return e.join(`
|
|
13
|
-
`)}async function
|
|
14
|
-
`),l=(await
|
|
15
|
-
${l}`},{role:"assistant",content:"Understood. I have context from our previous conversation. How can I help?"},...o]}var
|
|
15
|
+
`)}async function Ct(t,e){let n=t[0],r=Math.max(1,t.length-6),o=t.slice(r),s=t.slice(1,r);if(s.length===0)return t;let a=s.filter(c=>c.role!=="tool").map(c=>`${c.role}: ${typeof c.content=="string"?c.content?.slice(0,200):"[tool call]"}`).join(`
|
|
16
|
+
`),l=(await me({model:e,messages:[{role:"system",content:"Summarize this conversation concisely. Focus on what was done, decisions made, and current state. Under 500 words."},{role:"user",content:a}],maxTokens:1024})).choices[0]?.message?.content||"Previous conversation context unavailable.";return[n,{role:"user",content:`[Previous conversation summary]
|
|
17
|
+
${l}`},{role:"assistant",content:"Understood. I have context from our previous conversation. How can I help?"},...o]}var H,Fe,$t,It=g(()=>{"use strict";H=p(require("fs")),Fe=p(require("path")),$t=require("child_process");De()});var x,I,He,Rt,At,Mt=g(()=>{"use strict";x=p(require("fs")),I=p(require("path")),He=require("child_process"),Rt=[{type:"function",function:{name:"read_file",description:"Read a file. Returns contents with line numbers.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd)"},offset:{type:"number",description:"Start line (0-indexed)"},limit:{type:"number",description:"Max lines to read"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Write full content to a file (create or overwrite).",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd)"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace a string in a file. old_string must be unique in the file.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_string:{type:"string",description:"Exact string to find"},new_string:{type:"string",description:"Replacement string"}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern (e.g. "**/*.ts")'},path:{type:"string",description:"Directory to search in"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern"},path:{type:"string",description:"Directory or file to search"},include:{type:"string",description:'Glob to filter files (e.g. "*.ts")'}},required:["pattern"]}}},{type:"function",function:{name:"list_dir",description:"List directory contents.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"}},required:["path"]}}}],At={read_file(t,e){let n=I.resolve(e,t.path),o=x.readFileSync(n,"utf-8").split(`
|
|
16
18
|
`),s=t.offset||0,a=t.limit||o.length;return{content:o.slice(s,s+a).map((c,u)=>`${s+u+1} ${c}`).join(`
|
|
17
|
-
`),isError:!1}},write_file(t,e){let n=
|
|
19
|
+
`),isError:!1}},write_file(t,e){let n=I.resolve(e,t.path),r=I.dirname(n);return x.existsSync(r)||x.mkdirSync(r,{recursive:!0}),x.writeFileSync(n,t.content),{content:`Wrote ${n}`,isError:!1}},edit_file(t,e){let n=I.resolve(e,t.path),r=x.readFileSync(n,"utf-8"),o=t.old_string,s=t.new_string,a=r.indexOf(o);return a===-1?{content:`old_string not found in ${n}`,isError:!0}:r.indexOf(o,a+1)!==-1?{content:`old_string is not unique in ${n}`,isError:!0}:(x.writeFileSync(n,r.replace(o,s)),{content:`Edited ${n}`,isError:!1})},glob(t,e){let n=t.path?I.resolve(e,t.path):e,r=t.pattern;try{return{content:(0,He.execFileSync)("find",[n,"-path",`*${r}`,"-not","-path","*/node_modules/*","-not","-path","*/.git/*"],{encoding:"utf-8",timeout:5e3}).split(`
|
|
18
20
|
`).filter(Boolean).slice(0,100).join(`
|
|
19
|
-
`)||"No matches",isError:!1}}catch{return{content:"No matches",isError:!1}}},grep(t,e){let n=t.path?
|
|
21
|
+
`)||"No matches",isError:!1}}catch{return{content:"No matches",isError:!1}}},grep(t,e){let n=t.path?I.resolve(e,t.path):e,r=t.pattern,o=t.include,s=["-rn",...o?["--include",o]:[],r,n];try{return{content:(0,He.execFileSync)("grep",s,{encoding:"utf-8",timeout:1e4}).split(`
|
|
20
22
|
`).filter(Boolean).slice(0,50).join(`
|
|
21
|
-
`)||"No matches",isError:!1}}catch{return{content:"No matches",isError:!1}}},list_dir(t,e){let n=
|
|
22
|
-
`),isError:!1}}}});var kt,In,It,Rt,At=f(()=>{"use strict";kt=require("child_process"),In=[/rm\s+-rf\s+\//,/mkfs/,/dd\s+if=/,/:()\{\s*:\|:&\s*\};:/,/>\s*\/dev\/sd/],It=[{type:"function",function:{name:"bash",description:"Run a bash command. Returns stdout + stderr.",parameters:{type:"object",properties:{command:{type:"string",description:"Bash command to execute"}},required:["command"]}}}],Rt={bash(t,e){let n=t.command;for(let r of In)if(r.test(n))return{content:"Blocked: dangerous command pattern",isError:!0};try{return{content:(0,kt.execSync)(n,{cwd:e,encoding:"utf-8",timeout:3e4,maxBuffer:1048576,stdio:["pipe","pipe","pipe"]}).slice(0,1e4),isError:!1}}catch(r){return{content:((r.stdout||"")+(r.stderr||"")).slice(0,1e4)||r.message,isError:!0}}}}});async function Nt(t,e,n){let r=Rn[t];if(!r)return{content:`Unknown tool: ${t}`,isError:!0};try{return r(e,n)}catch(o){return{content:o.message||String(o),isError:!0}}}var Mt,Rn,Ot=f(()=>{"use strict";$t();At();Mt=[...Et,...It],Rn={...Ct,...Rt}});async function Lt(t,e,n,r,o,s){let a=process.cwd(),i=[{role:"system",content:xt(a)}],l=Nn[t.model]||128e3;for(;t.turns<An;){let c=await n();if(c===null)break;if(!c.trim())continue;if(c.startsWith("/")){if(c.startsWith("/model ")){t.model=c.slice(7).trim(),r(`Switched to ${t.model}`);continue}if(c==="/budget"||c==="/cost"){r(`Spent: $${(t.spentCents/100).toFixed(2)} / $${(t.budgetCents/100).toFixed(2)}`);continue}if(c==="/quit"||c==="/exit")break}i.push({role:"user",content:c});let u=0,_=0;for(;;){if(t.turns++,t.spentCents>=t.budgetCents){r("Session budget exhausted. Run /budget to check or start a new session.");return}let T;try{T=await ue({model:t.model,messages:i,tools:Mt,maxTokens:4096,temperature:.7,...e?{attestation:e}:{}})}catch(b){r(`Error: ${b.message||b}`),i.pop();break}let Y=bt(T.usage,t.model);t.spentCents+=Y,t.inputTokens+=T.usage.prompt_tokens,t.outputTokens+=T.usage.completion_tokens,u+=Y;let H=T.choices[0];if(!H)break;let I=H.message;if(I.content&&r(I.content),i.push(I),!I.tool_calls?.length||H.finish_reason==="stop")break;for(let b of I.tool_calls){let Ue=b.function.name,J;try{J=JSON.parse(b.function.arguments)}catch{J={}}o(Ue,J);let{content:Xt}=await Nt(Ue,J,a);i.push({role:"tool",content:Xt.slice(0,1e4),tool_call_id:b.id})}}if(s(u,_),On(i)>l*Mn){let T=await Pt(i,t.model);i.length=0,i.push(...T)}}}function On(t){let e=0;for(let n of t)if(typeof n.content=="string"&&(e+=n.content.length),n.tool_calls)for(let r of n.tool_calls)e+=r.function.arguments.length+r.function.name.length;return Math.ceil(e/3.5)}var An,Mn,Nn,Ut=f(()=>{"use strict";Me();Tt();Ot();An=50,Mn=.7,Nn={"or-claude-sonnet":2e5,"or-gpt-4o":128e3,"or-gpt-4o-mini":128e3,"or-gemini-pro":1e6,"or-deepseek-r1":64e3}});var Ln,Er,jt=f(()=>{"use strict";Le();Ln={generate_image:{intro:"Generate an AI image.",tiers:{balanced:{toolId:"fal-flux-pro",priceCents:4,notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",priceCents:1,notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",priceCents:6,notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",priceCents:8,notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",priceCents:5,notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:"Generate an AI video from a text prompt.",tiers:{balanced:{toolId:"fal-minimax-video",priceCents:15,notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",priceCents:10,notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",priceCents:20,notes:"Kling \u2014 highest quality, cinematic"}},guidance:"Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate.",inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:"Generate an original music track from a prompt.",tiers:{suno:{toolId:"suno-music",priceCents:10,notes:"Suno v4 \u2014 songs with vocals, lyrics, full arrangement"}},guidance:"Takes ~60-90s. Returns an audio URL the user can play.",inputProperties:{prompt:{type:"string",description:"Musical style / mood / lyrics hint."},instrumental:{type:"boolean",description:"True for instrumental (no vocals), false for vocal track.",default:!1}},required:["prompt"]},generate_audio:{intro:"Generate speech or sound effects.",tiers:{tts:{toolId:"fal-metavoice",priceCents:3,notes:"MetaVoice \u2014 high-quality TTS from text"},sfx:{toolId:"fal-stable-audio",priceCents:4,notes:"Stable Audio \u2014 sound effects and ambient from a prompt"}},guidance:'Pick "tts" for spoken words, "sfx" for music-beds/effects/ambient.',inputProperties:{prompt:{type:"string",description:"Text to speak (tts) or description of sound (sfx)."}},required:["prompt"]},generate_3d:{intro:"Generate a 3D model from a text description.",tiers:{trellis:{toolId:"fal-trellis-3d",priceCents:8,notes:"Trellis \u2014 fast text-to-3D, returns a GLB mesh URL"}},guidance:"Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{prompt:{type:"string",description:"Description of the 3D object."}},required:["prompt"]},upscale_image:{intro:"Upscale an image to higher resolution.",tiers:{aura:{toolId:"fal-aura-sr",priceCents:3,notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:"Transcribe speech in an audio/video URL to text.",tiers:{whisper:{toolId:"fal-whisper",priceCents:2,notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through an LLM (OpenRouter). Token-metered \u2014 prices below are per 1M input/output tokens. Typical 500-in/500-out prompts cost 1\u20139\xA2 depending on model.",tiers:{fast:{toolId:"or-gpt-4o-mini",priceCents:1,notes:"GPT-4o Mini \u2014 $0.15/M in \xB7 $0.60/M out. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",priceCents:9,notes:"Claude 3.5 Sonnet \u2014 $3.00/M in \xB7 $15.00/M out. Strong reasoning, long-context. ~20x pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",priceCents:2,notes:"DeepSeek R1 \u2014 $0.55/M in \xB7 $2.19/M out. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",priceCents:1,notes:"Perplexity Sonar \u2014 $1.00/M in \xB7 $1.00/M out. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",priceCents:1,notes:"Llama 3.3 70B \u2014 $0.30/M in \xB7 $0.40/M out. Open-source large model."},coding:{toolId:"or-deepseek-chat",priceCents:1,notes:"DeepSeek Chat V3 \u2014 $0.30/M in \xB7 $0.88/M out. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis \u2014 WARN user it's ~$0.09/call), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}},Er=Object.keys(Ln)});async function qt(t,e,n,r){if(!U()){M.warn("attestation:unavailable",{context:t});return}M.info("attestation:attempt",{context:t,amount:e,merchant:n});try{let{nonce:o}=await Un.getAttestationChallenge(),s=Buffer.from(JSON.stringify({nonce:o,amount:e,merchant:n,context:t})).toString("base64");M.info("touchid:prompt",{context:t,amount:e,merchant:n});let a=await le(s,r);return M.info("attestation:success",{context:t,amount:e,merchant:n}),{signature:a,nonce:o,amount:e,merchant:n}}catch(o){throw M.error("attestation:failure",{context:t,amount:e,merchant:n,error:o.message}),o}}var Or,Un,jn,Lr,Ur,jr,Le=f(()=>{"use strict";oe();ke();K();Te();jt();Or=process.env.VISA_AUTH_URL||"https://auth.visacli.sh",Un=new $(()=>g.getSessionToken()),jn=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"],Lr=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my recent transactions" \u2192 transaction_history','\u2022 "Set my daily limit to $50" \u2192 update_spending_controls','\u2022 "Pay https://example.com/checkout" \u2192 pay','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Fast shortcuts:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image_card (~$0.06)','\u2022 "Make a fast thumbnail: minimalist cat logo" \u2192 generate_image_fast_card (~$0.04)','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video_tempo_card (~$0.30)','\u2022 "Make a song about coding late at night" \u2192 generate_music_tempo_card (~$0.10)','\u2022 "Check the status of my music job" \u2192 check_music_status_tempo_card','\u2022 "What is ETH on Base trading at?" \u2192 query_onchain_prices_card (~$0.02)','\u2022 "Explore stablecoin inflows on Base" \u2192 allium_explorer_card','\u2022 "Open the latest Allium result set" \u2192 allium_explorer_results_card','\u2022 "Show pxlwall campaign insights" \u2192 pxlwall_card',"","Category tools:",...jn.map(t=>`\u2022 "${t.replace(/_/g," ")}" \u2192 ${t}`),"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
|
|
23
|
-
`);
|
|
24
|
-
${
|
|
25
|
-
`):console.log(` ${
|
|
26
|
-
`);let r=
|
|
23
|
+
`)||"No matches",isError:!1}}catch{return{content:"No matches",isError:!1}}},list_dir(t,e){let n=I.resolve(e,t.path||".");return{content:x.readdirSync(n,{withFileTypes:!0}).map(s=>`${s.isDirectory()?"d":"f"} ${s.name}`).join(`
|
|
24
|
+
`),isError:!1}}}});var Nt,qn,Ot,Lt,Ut=g(()=>{"use strict";Nt=require("child_process"),qn=[/rm\s+-rf\s+\//,/mkfs/,/dd\s+if=/,/:()\{\s*:\|:&\s*\};:/,/>\s*\/dev\/sd/],Ot=[{type:"function",function:{name:"bash",description:"Run a bash command. Returns stdout + stderr.",parameters:{type:"object",properties:{command:{type:"string",description:"Bash command to execute"}},required:["command"]}}}],Lt={bash(t,e){let n=t.command;for(let r of qn)if(r.test(n))return{content:"Blocked: dangerous command pattern",isError:!0};try{return{content:(0,Nt.execSync)(n,{cwd:e,encoding:"utf-8",timeout:3e4,maxBuffer:1048576,stdio:["pipe","pipe","pipe"]}).slice(0,1e4),isError:!1}}catch(r){return{content:((r.stdout||"")+(r.stderr||"")).slice(0,1e4)||r.message,isError:!0}}}}});async function qt(t,e,n){let r=Dn[t];if(!r)return{content:`Unknown tool: ${t}`,isError:!0};try{return r(e,n)}catch(o){return{content:o.message||String(o),isError:!0}}}var jt,Dn,Dt=g(()=>{"use strict";Mt();Ut();jt=[...Rt,...Ot],Dn={...At,...Lt}});async function Ft(t,e,n,r,o,s){let a=process.cwd(),i=[{role:"system",content:kt(a)}],l=Vn[t.model]||128e3;for(;t.turns<Fn;){let c=await n();if(c===null)break;if(!c.trim())continue;if(c.startsWith("/")){if(c.startsWith("/model ")){t.model=c.slice(7).trim(),r(`Switched to ${t.model}`);continue}if(c==="/budget"||c==="/cost"){r(`Spent: $${(t.spentCents/100).toFixed(2)} / $${(t.budgetCents/100).toFixed(2)}`);continue}if(c==="/quit"||c==="/exit")break}i.push({role:"user",content:c});let u=0,_=0;for(;;){if(t.turns++,t.spentCents>=t.budgetCents){r("Session budget exhausted. Run /budget to check or start a new session.");return}let T;try{T=await me({model:t.model,messages:i,tools:jt,maxTokens:4096,temperature:.7,...e?{attestation:e}:{}})}catch(S){r(`Error: ${S.message||S}`),i.pop();break}let J=Tt(T.usage,t.model);t.spentCents+=J,t.inputTokens+=T.usage.prompt_tokens,t.outputTokens+=T.usage.completion_tokens,u+=J;let K=T.choices[0];if(!K)break;let R=K.message;if(R.content&&r(R.content),i.push(R),!R.tool_calls?.length||K.finish_reason==="stop")break;for(let S of R.tool_calls){let Ke=S.function.name,X;try{X=JSON.parse(S.function.arguments)}catch{X={}}o(Ke,X);let{content:nn}=await qt(Ke,X,a);i.push({role:"tool",content:nn.slice(0,1e4),tool_call_id:S.id})}}if(s(u,_),Kn(i)>l*Hn){let T=await Ct(i,t.model);i.length=0,i.push(...T)}}}function Kn(t){let e=0;for(let n of t)if(typeof n.content=="string"&&(e+=n.content.length),n.tool_calls)for(let r of n.tool_calls)e+=r.function.arguments.length+r.function.name.length;return Math.ceil(e/3.5)}var Fn,Hn,Vn,Ht=g(()=>{"use strict";De();It();Dt();Fn=50,Hn=.7,Vn={"or-claude-sonnet":2e5,"or-gpt-4o":128e3,"or-gpt-4o-mini":128e3,"or-gemini-pro":1e6,"or-deepseek-r1":64e3}});var Bn,Or,Vt=g(()=>{"use strict";Ve();Bn={generate_image:{intro:"Generate an AI image.",tiers:{balanced:{toolId:"fal-flux-pro",priceCents:4,notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",priceCents:1,notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",priceCents:6,notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",priceCents:8,notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",priceCents:5,notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:"Generate an AI video from a text prompt.",tiers:{balanced:{toolId:"fal-minimax-video",priceCents:15,notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",priceCents:10,notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",priceCents:20,notes:"Kling \u2014 highest quality, cinematic"}},guidance:"Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate.",inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:"Generate an original music track from a prompt.",tiers:{suno:{toolId:"suno-music",priceCents:10,notes:"Suno v4 \u2014 songs with vocals, lyrics, full arrangement"}},guidance:"Takes ~60-90s. Returns an audio URL the user can play.",inputProperties:{prompt:{type:"string",description:"Musical style / mood / lyrics hint."},instrumental:{type:"boolean",description:"True for instrumental (no vocals), false for vocal track.",default:!1}},required:["prompt"]},generate_audio:{intro:"Generate speech or sound effects.",tiers:{tts:{toolId:"fal-metavoice",priceCents:3,notes:"MetaVoice \u2014 high-quality TTS from text"},sfx:{toolId:"fal-stable-audio",priceCents:4,notes:"Stable Audio \u2014 sound effects and ambient from a prompt"}},guidance:'Pick "tts" for spoken words, "sfx" for music-beds/effects/ambient.',inputProperties:{prompt:{type:"string",description:"Text to speak (tts) or description of sound (sfx)."}},required:["prompt"]},generate_3d:{intro:"Generate a 3D model from a text description.",tiers:{trellis:{toolId:"fal-trellis-3d",priceCents:8,notes:"Trellis \u2014 fast text-to-3D, returns a GLB mesh URL"}},guidance:"Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{prompt:{type:"string",description:"Description of the 3D object."}},required:["prompt"]},upscale_image:{intro:"Upscale an image to higher resolution.",tiers:{aura:{toolId:"fal-aura-sr",priceCents:3,notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:"Transcribe speech in an audio/video URL to text.",tiers:{whisper:{toolId:"fal-whisper",priceCents:2,notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through an LLM (OpenRouter). Token-metered \u2014 prices below are per 1M input/output tokens. Typical 500-in/500-out prompts cost 1\u20139\xA2 depending on model.",tiers:{fast:{toolId:"or-gpt-4o-mini",priceCents:1,notes:"GPT-4o Mini \u2014 $0.15/M in \xB7 $0.60/M out. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",priceCents:9,notes:"Claude 3.5 Sonnet \u2014 $3.00/M in \xB7 $15.00/M out. Strong reasoning, long-context. ~20x pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",priceCents:2,notes:"DeepSeek R1 \u2014 $0.55/M in \xB7 $2.19/M out. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",priceCents:1,notes:"Perplexity Sonar \u2014 $1.00/M in \xB7 $1.00/M out. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",priceCents:1,notes:"Llama 3.3 70B \u2014 $0.30/M in \xB7 $0.40/M out. Open-source large model."},coding:{toolId:"or-deepseek-chat",priceCents:1,notes:"DeepSeek Chat V3 \u2014 $0.30/M in \xB7 $0.88/M out. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis \u2014 WARN user it's ~$0.09/call), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}},Or=Object.keys(Bn)});async function Kt(t,e,n,r){if(!j()){N.warn("attestation:unavailable",{context:t});return}N.info("attestation:attempt",{context:t,amount:e,merchant:n});try{let{nonce:o}=await Gn.getAttestationChallenge(),s=Buffer.from(JSON.stringify({nonce:o,amount:e,merchant:n,context:t})).toString("base64");N.info("touchid:prompt",{context:t,amount:e,merchant:n});let a=await de(s,r);return N.info("attestation:success",{context:t,amount:e,merchant:n}),{signature:a,nonce:o,amount:e,merchant:n}}catch(o){throw N.error("attestation:failure",{context:t,amount:e,merchant:n,error:o.message}),o}}var Br,Gn,Wn,Gr,Wr,zr,Ve=g(()=>{"use strict";ie();Le();B();Ae();Vt();Te();Br=process.env.VISA_AUTH_URL||"https://auth.visacli.sh",Gn=new C(()=>f.getSessionToken()),Wn=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"],Gr=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my recent transactions" \u2192 transaction_history','\u2022 "Set my daily limit to $50" \u2192 update_spending_controls','\u2022 "Pay https://example.com/checkout" \u2192 pay','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Fast shortcuts:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image_card (~$0.06)','\u2022 "Make a fast thumbnail: minimalist cat logo" \u2192 generate_image_fast_card (~$0.04)','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video_tempo_card (~$0.30)','\u2022 "Make a song about coding late at night" \u2192 generate_music_tempo_card (~$0.10)','\u2022 "Check the status of my music job" \u2192 check_music_status_tempo_card','\u2022 "What is ETH on Base trading at?" \u2192 query_onchain_prices_card (~$0.02)','\u2022 "Explore stablecoin inflows on Base" \u2192 allium_explorer_card','\u2022 "Open the latest Allium result set" \u2192 allium_explorer_results_card','\u2022 "Show pxlwall campaign insights" \u2192 pxlwall_card',"","Category tools:",...Wn.map(t=>`\u2022 "${t.replace(/_/g," ")}" \u2192 ${t}`),"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
|
|
25
|
+
`);Wr=16*1024,zr=50*1024*1024});function Gt(t="or-claude-sonnet"){return{model:t,budgetCents:Bt,spentCents:0,turns:0,inputTokens:0,outputTokens:0}}async function Wt(t=Bt){try{return{attestation:await Kt("visa-client-session",t/100,"Visa CLI",`Visa CLI session budget: $${(t/100).toFixed(2)}`)||void 0,budgetCents:t}}catch{return{attestation:void 0,budgetCents:t}}}function pe(t){let e=(t.budgetCents-t.spentCents)/100,n=t.spentCents/100;return`$${e.toFixed(2)} remaining ($${n.toFixed(2)} spent, ${t.turns} turns)`}var Bt,zt=g(()=>{"use strict";Ve();Bt=500});var Jt={};un(Jt,{startClient:()=>Jn});async function Jn(t={}){let e=Gt(t.model);console.log(Yn),console.log(`
|
|
26
|
+
${q}Model: ${e.model}${O}`),console.log(` ${q}Authorizing session budget: $${(e.budgetCents/100).toFixed(2)}${O}`);let n=await Wt(t.budget||e.budgetCents);e.budgetCents=n.budgetCents,n.attestation?console.log(` ${q}Touch ID authorized. ${pe(e)}${O}
|
|
27
|
+
`):console.log(` ${q}No attestation (Touch ID unavailable). ${pe(e)}${O}
|
|
28
|
+
`);let r=Yt.createInterface({input:process.stdin,output:process.stdout,prompt:`${zn}dove>${O} `}),o=()=>new Promise(l=>{r.prompt(),r.once("line",c=>l(c)),r.once("close",()=>l(null))}),s=l=>{console.log(`
|
|
27
29
|
${l.split(`
|
|
28
30
|
`).join(`
|
|
29
31
|
`)}
|
|
30
|
-
`)},a=(l,c)=>{let u=l==="bash"?c.command?.slice(0,60):c.path||"";console.log(` ${
|
|
31
|
-
${
|
|
32
|
-
`)});var
|
|
32
|
+
`)},a=(l,c)=>{let u=l==="bash"?c.command?.slice(0,60):c.path||"";console.log(` ${q}\u25B8 ${l}${O} ${u}`)},i=(l,c)=>{let u=l+c,_=[`$${(l/100).toFixed(3)} inference`];c>0&&_.push(`$${(c/100).toFixed(3)} tools`),console.log(` ${q}${_.join(" \xB7 ")} \xB7 $${(u/100).toFixed(3)} this turn${O}`)};await Ft(e,n.attestation,o,s,a,i),console.log(`
|
|
33
|
+
${q}Session ended. ${pe(e)}${O}`),r.close()}var Yt,O,zn,q,Yn,Xt=g(()=>{"use strict";Yt=p(require("readline"));Ht();zt();O="\x1B[0m",zn="\x1B[38;5;33m",q="\x1B[2m",Yn=[" \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28E4\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28FF\u2807\u28B0\u28F6\u28E6\u28E4\u28C0\u2840\u2812\u2802\u2824\u2824\u2884\u28C0\u28C0\u2840\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u285F\u2880\u28FF\u281F\u283F\u28BF\u28FF\u28FF\u28FF\u28FF\u28F6\u28F6\u28E4\u28C4\u28C9\u2841\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FE\u2801\u28F8\u28FF\u28F7\u28F6\u28E4\u28E4\u28C8\u2849\u281B\u283B\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u2876\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2880\u284F\u28A0\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F6\u28E6\u28E4\u28C4\u28C9\u28B9\u28FF\u2803\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2838\u2800\u28FE\u28FF\u28FF\u28FF\u28CF\u28D9\u281B\u283B\u283F\u28BF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u284F\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2802\u28B8\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28F6\u28E6\u28E4\u28F8\u28FF\u28FF\u28FF\u28FF\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28FF\u28FF\u287F\u280B\u28C1\u28E4\u2804\u2880\u2800\u2809\u283B\u28FF\u28FF\u28FF\u28FF\u28FF\u2807\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u28FC\u28FF\u280F\u28C0\u2818\u281B\u2801\u2830\u28FF\u2847\u28B8\u28E6\u2848\u28BF\u28FF\u28FF\u287F\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u28A0\u28FF\u284F\u28A0\u28FF\u28FF\u2803\u28F4\u28F6\u28E4\u2844\u2880\u28C9\u2803\u28B8\u28FF\u28FF\u2803\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u28FE\u28FF\u28C7\u2800\u28C4\u28C9\u2800\u281B\u283F\u283F\u2801\u28FC\u28FF\u2847\u28B8\u28FF\u284F\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28C4\u2819\u28BF\u2818\u28F7\u2876\u2800\u28E4\u28C8\u2849\u2881\u28FE\u28FF\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2819\u281B\u283F\u283F\u28FF\u28E6\u28C4\u2800\u2809\u2820\u281E\u281B\u28C9\u28F4\u28FF\u28FF\u2807\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2809\u281B\u2812\u2836\u28BF\u28FF\u28FF\u28FF\u287F\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800"].join(`
|
|
34
|
+
`)});var Zt=require("commander"),fe=p(require("crypto")),V=p(require("os")),Qt=require("child_process"),en=require("util");B();var ne=p(require("crypto")),re=p(require("tty")),oe=p(require("fs"));var L="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";B();function Pn(t){return/-rc\.|-beta\./.test(t)}function Ee(t){return ne.createHash("sha256").update(t.trim()).digest("hex")}function We(t){return L==="SKIP"?!0:ne.timingSafeEqual(Buffer.from(Ee(t)),Buffer.from(L))}function En(t){return new Promise((e,n)=>{let r=oe.openSync("/dev/tty","r+"),o=new re.ReadStream(r),s=new re.WriteStream(r),a=()=>{try{o.destroy()}catch{}try{s.destroy()}catch{}try{oe.closeSync(r)}catch{}};s.write(t),o.setRawMode(!0),o.resume(),o.setEncoding("utf8");let i="";o.on("data",l=>{l==="\r"||l===`
|
|
33
35
|
`?(s.write(`
|
|
34
36
|
`),a(),e(i)):l===""?(s.write(`
|
|
35
|
-
`),a(),n(new Error("Cancelled"))):l==="\x7F"||l==="\b"?i.length>0&&(i=i.slice(0,-1),s.write("\b \b")):(i+=l,s.write("\u2022"))})})}var
|
|
37
|
+
`),a(),n(new Error("Cancelled"))):l==="\x7F"||l==="\b"?i.length>0&&(i=i.slice(0,-1),s.write("\b \b")):(i+=l,s.write("\u2022"))})})}var Tn=`
|
|
36
38
|
\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
|
|
37
39
|
\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
|
|
38
40
|
\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
|
|
@@ -41,23 +43,21 @@ ${l}`},{role:"assistant",content:"Understood. I have context from our previous c
|
|
|
41
43
|
\u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
|
|
42
44
|
|
|
43
45
|
This is a Release Candidate build. Access is restricted to Visa employees.
|
|
44
|
-
`;async function
|
|
45
|
-
`),process.exit(1)}let o=await
|
|
46
|
+
`;async function ze(t={}){let e=t.version??Pe().version;if(!Pn(e))return;let n=process.env.VISA_RC_CODE;if(n&&We(n)){await f.saveRcAccessToken(Ee(n));return}if(t.isMcp??!1){let a=await f.getRcAccessToken();if(a&&(L==="SKIP"||a===L))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
|
|
47
|
+
`),process.exit(1)}let o=await f.getRcAccessToken();if(o&&(L==="SKIP"||o===L))return;console.log(Tn);let s=3;for(let a=1;a<=s;a++){let i;try{i=await En(" Enter RC access code: ")}catch{process.exit(1)}if(We(i)){await f.saveRcAccessToken(Ee(i)),console.log(`
|
|
46
48
|
Access granted. Welcome.
|
|
47
49
|
`);return}a<s&&console.log(`
|
|
48
50
|
Invalid code. ${s-a} attempt(s) remaining.
|
|
49
51
|
`)}console.log(`
|
|
50
52
|
Invalid code. Contact your team lead.
|
|
51
|
-
`),process.exit(1)}
|
|
52
|
-
`)}function _n(t,e=process.platform){return e==="darwin"?{cmd:"open",args:[t]}:e==="win32"?{cmd:"cmd",args:["/c","start","",t]}:e==="linux"?{cmd:"xdg-open",args:[t]}:null}async function Ge(t,e={}){let n=e.log??(l=>console.log(l)),r=e.env??process.env,o=e.platform??process.platform,s=e.spawn??((l,c,u)=>{(0,We.execFile)(l,c,_=>u(_))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let l of yn(t).split(`
|
|
53
|
-
`))n(` ${l}`);n("");let a=hn(r,o);if(a.headless){n(` (${a.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 i=_n(t,o);if(!i){n(` No known browser-open command for platform "${o}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(l=>{s(i.cmd,i.args,c=>{c?(n(` Could not open browser automatically (${c.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()})})}oe();ke();Se();function mt(t,e=process.stderr){if(re()||!t?.updateAvailable)return!1;let{message:n}=t.updateAvailable;return n?(e.write(`
|
|
53
|
+
`),process.exit(1)}Te();ie();Le();$e();function yt(t,e=process.stderr){if(se()||!t?.updateAvailable)return!1;let{message:n}=t.updateAvailable;return n?(e.write(`
|
|
54
54
|
\x1B[33m\u2191 ${n}\x1B[0m
|
|
55
|
-
`),!0):!1}var
|
|
56
|
-
`),{installed:!0,configPath:n,message:t.postInstallHint}}function
|
|
57
|
-
`),{removed:!0,configPath:n})}function
|
|
58
|
-
${r}: ${n(t.currentPath)}`}function
|
|
59
|
-
Step 2: Checking authentication...`);let a=await
|
|
60
|
-
Step 3: Setting up authentication...`),!
|
|
55
|
+
`),!0):!1}var b=class extends Error{constructor(e){super(e),this.name="PayValidationError"}},_t=["GET","POST"];function wt(t){let e;try{e=new URL(t)}catch{throw new b(`Invalid URL: ${t}. Expected a fully-qualified http(s) URL.`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new b(`Unsupported URL scheme "${e.protocol}". Only http and https are allowed.`);return e}function bt(t){let e=(t??"GET").toUpperCase();if(!_t.includes(e))throw new b(`Unsupported HTTP method "${t}". Supported: ${_t.join(", ")}.`);return e}function St(t){if(t!==void 0){try{JSON.parse(t)}catch(e){throw new b(`--body is not valid JSON: ${e?.message??"parse error"}`)}return t}}function vt(t){if(!t||typeof t!="object")throw new b("Merchant returned no payment preview.");let e=t;if(typeof e.amount!="number"||!Number.isFinite(e.amount)||e.amount<=0)throw new b("Could not determine payment amount from merchant.");if(typeof e.merchantName!="string"||e.merchantName.trim().length===0)throw new b("Merchant returned an empty merchant name.");if(e.merchantName.length>200)throw new b(`Merchant name too long (${e.merchantName.length} chars).`);if(typeof e.currency!="string"||e.currency.trim().length===0)throw new b("Merchant returned an empty currency.");if(e.currency.length>10)throw new b(`Currency code too long (${e.currency.length} chars).`);return{amount:e.amount,currency:e.currency,merchantName:e.merchantName}}var m=p(require("fs")),d=p(require("path")),xt=p(require("os")),y=xt.homedir(),E=[{id:"claude",displayName:"Claude Code",globalConfigPath:d.join(y,".claude.json"),configKey:"mcpServers",detectPaths:[d.join(y,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:d.join(y,"Library","Application Support","Claude","claude_desktop_config.json"),configKey:"mcpServers",detectPaths:[d.join(y,"Library","Application Support","Claude")],postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:d.join(y,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[d.join(y,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:d.join(y,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[d.join(y,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:d.join(y,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[d.join(y,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:d.join(y,".config","Roo","mcp_settings.json"),configKey:"mcpServers",detectPaths:[d.join(y,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:d.join(y,".vscode","mcp.json"),configKey:"servers",detectPaths:[d.join(y,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:d.join(y,".config","zed","settings.json"),configKey:"context_servers",detectPaths:[d.join(y,".config","zed")],postInstallHint:"Restart Zed to connect.",buildEntry:t=>({source:"custom",...t})}];function Ue(t){return E.find(e=>e.id===t)}function W(t){return t.detectPaths.some(e=>{if(e.includes("*")){let n=d.dirname(e),r=d.basename(e).replaceAll("*","");if(!m.existsSync(n))return!1;try{return m.readdirSync(n).some(o=>o.startsWith(r))}catch{return!1}}return m.existsSync(e)})}function Pt(){return{command:"node",args:[d.resolve(__dirname,"mcp-server/index.js")]}}function z(t,e="global"){let n=e==="project"?d.join(process.cwd(),".mcp.json"):t.globalConfigPath,r=d.dirname(n);m.existsSync(r)||m.mkdirSync(r,{recursive:!0});let o={};if(m.existsSync(n))try{o=JSON.parse(m.readFileSync(n,"utf-8"))}catch{o={}}o[t.configKey]=o[t.configKey]||{};let s=Pt();return o[t.configKey]["visa-cli"]=t.buildEntry?t.buildEntry(s):s,m.writeFileSync(n,JSON.stringify(o,null,2)+`
|
|
56
|
+
`),{installed:!0,configPath:n,message:t.postInstallHint}}function je(t,e="global"){let n=e==="project"?d.join(process.cwd(),".mcp.json"):t.globalConfigPath;if(!m.existsSync(n))return{removed:!1,configPath:n};let r;try{r=JSON.parse(m.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=r[t.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],m.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
57
|
+
`),{removed:!0,configPath:n})}function Et(t,e="global"){let n=e==="project"?d.join(process.cwd(),".mcp.json"):t.globalConfigPath;if(!m.existsSync(n))return!1;try{return!!JSON.parse(m.readFileSync(n,"utf-8"))?.[t.configKey]?.["visa-cli"]}catch{return!1}}function Ln(t){if(!t||typeof t!="object")return;let e=t;if(e.command!=="node"||!Array.isArray(e.args)||e.args.length===0)return;let n=e.args[e.args.length-1];if(!(typeof n!="string"||n.length===0))return n}function Un(t,e){if(t===e)return!0;let n=d.resolve(t),r=d.resolve(e);if(n===r)return!0;try{let o=m.realpathSync(n),s=m.realpathSync(r);return o===s}catch{return!1}}function Y(){let t=Pt(),e=t.args[t.args.length-1],n=[];for(let r of E){let o=r.globalConfigPath;if(!m.existsSync(o))continue;let s;try{s=JSON.parse(m.readFileSync(o,"utf-8"))}catch{continue}let a=s?.[r.configKey]?.["visa-cli"];if(!a)continue;let i=Ln(a);if(!i||Un(i,e))continue;let l=m.existsSync(i)?"mismatch":"missing";n.push({client:r,configPath:o,currentPath:i,expectedPath:e,staleReason:l})}return n}function qe(t){return{configPath:z(t.client,"global").configPath}}var Xn=(0,en.promisify)(Qt.execFile);function Zn(t){let e=V.homedir(),n=o=>o.replace(e,"~"),r=t.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${t.client.displayName} (${n(t.configPath)})
|
|
58
|
+
${r}: ${n(t.currentPath)}`}function tn(t,e){if(t.length===0){console.log(`${e} \u2713 All MCP client configs are up to date.`);return}console.log(`${e} Found ${t.length} stale MCP config ${t.length===1?"entry":"entries"}:`);for(let n of t)console.log(Zn(n))}var P=new Zt.Command,ge=null;function he(){return ge=new C(()=>f.getSessionToken()),ge}P.name("visa-cli").description("Visa CLI - AI payment orchestration").version(Pe().version);P.hook("preAction",async()=>{await ze()});P.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").action(async t=>{try{if(t.check){let c=Y();tn(c,"MCP config check:"),c.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 e=Y(),n=new Map(e.map(c=>[c.client.id,c])),r=new Set;for(let c of E)if(W(c)){let u=z(c),_=n.get(c.id),D=_?` \u2014 repaired stale ${_.staleReason} entry`:"";console.log(` \u2713 ${c.displayName} (${u.configPath.replace(V.homedir(),"~")})${D}`),_&&r.add(c.id)}let o=e.filter(c=>!r.has(c.client.id));for(let c of o)qe(c),console.log(` \u2713 ${c.client.displayName} (${c.configPath.replace(V.homedir(),"~")}) \u2014 repaired stale ${c.staleReason} entry`);let s=r.size+o.length;console.log(s===0?" \u2713 MCP config verified \u2014 nothing to repair.":` \u2713 Repaired ${s} stale MCP config ${s===1?"entry":"entries"}.`),console.log(`
|
|
59
|
+
Step 2: Checking authentication...`);let a=await f.getSessionToken();if(a?console.log(" Already authenticated."):(console.log(" No session found. Opening browser for GitHub login..."),a=await new Promise(async(c,u)=>{let _=fe.randomBytes(16).toString("hex"),D=`https://auth.visacli.sh/login?state=${_}`;await Ze(D);let T=3e4,J=300*1e3,K=Date.now()+J;for(;Date.now()<K;)try{let R=await globalThis.fetch("https://auth.visacli.sh/v1/auth-status",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:_,timeout:T}),signal:AbortSignal.timeout(T+5e3)});if(!R.ok)continue;let S=await R.json();if(S.status==="pending")continue;if(S.status==="expired"){u(new Error("Session expired. Please run setup again."));return}if(S.status==="complete"&&S.sessionToken){console.log(` Signed in as ${S.user}.`),c(S.sessionToken);return}}catch{}u(new Error("Login timed out after 5 minutes. Please run setup again."))}),await f.saveSessionToken(a),console.log(" Session token saved.")),console.log(`
|
|
60
|
+
Step 3: Setting up authentication...`),!j())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await Xn("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 c=await ft();console.log(" Attestation key generated."),await he().registerAttestationKey(c),console.log(" Attestation key registered with server.")}catch(c){console.log(` Skipped: ${c.message}`)}}let i="\x1B[1m",l="\x1B[0m";console.log(`
|
|
61
61
|
\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
|
|
62
62
|
\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
|
|
63
63
|
\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
|
|
@@ -74,17 +74,17 @@ Step 3: Setting up authentication...`),!U())console.log(" Not macOS \u2014 ski
|
|
|
74
74
|
|
|
75
75
|
${i}Verify:${l} visa-cli status
|
|
76
76
|
${i}Docs:${l} https://visacli.sh
|
|
77
|
-
`)}catch(e){console.error("Error:",e.message),process.exit(1)}});
|
|
77
|
+
`)}catch(e){console.error("Error:",e.message),process.exit(1)}});P.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(t,e)=>{try{if(e.check){let s=Y();tn(s,"MCP config check:"),s.length>0&&process.exit(1);return}if(e.repair){let s=Y();if(s.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let a of s)qe(a),console.log(` \u2713 ${a.client.displayName} (${a.configPath.replace(V.homedir(),"~")}) \u2014 repaired stale ${a.staleReason} entry`);console.log(`
|
|
78
78
|
Repaired ${s.length} stale MCP config ${s.length===1?"entry":"entries"}.`);return}if(e.list){console.log(`
|
|
79
79
|
\x1B[1mSupported MCP Clients\x1B[0m
|
|
80
|
-
`),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 i of
|
|
81
|
-
Supported clients: ${
|
|
82
|
-
Supported clients: ${
|
|
83
|
-
`);let a;if(
|
|
84
|
-
Result URLs:`);for(let l of i.receipt.urls)console.log(` ${l}`)}}else console.error(`Payment failed: ${i.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof
|
|
80
|
+
`),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 i of E){let l=W(i),c=Et(i),u=l?"Yes":"No",_=c?"Yes":"No",D=i.globalConfigPath.replace(V.homedir(),"~");console.log(` ${i.displayName.padEnd(18)} ${u.padEnd(10)} ${_.padEnd(11)} ${D}`)}console.log("");return}let n=e.scope==="project"?"project":"global";if(e.all){let s=[],a=[];for(let i of E){if(!W(i)){a.push(i.displayName);continue}z(i,n),s.push(i.displayName)}s.length>0&&console.log(`Installed for: ${s.join(", ")}.`),a.length>0&&console.log(`Skipped: ${a.map(i=>`${i} (not detected)`).join(", ")}.`),s.length===0&&a.length===0&&console.log("No supported clients found.");return}t||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
|
|
81
|
+
Supported clients: ${E.map(s=>s.id).join(", ")}`),process.exit(1));let r=Ue(t);r||(console.error(`Unknown client: ${t}`),console.error(`Supported clients: ${E.map(s=>s.id).join(", ")}`),process.exit(1)),n==="global"&&!W(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let o=z(r,n);console.log(`Registered visa-cli MCP server in ${o.configPath}`),console.log(o.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});P.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(t,e)=>{try{let n=e.scope==="project"?"project":"global";if(e.all){let s=[];for(let a of E)je(a,n).removed&&s.push(a.displayName);s.length>0?console.log(`Removed visa-cli from: ${s.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}t||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
|
|
82
|
+
Supported clients: ${E.map(s=>s.id).join(", ")}`),process.exit(1));let r=Ue(t);r||(console.error(`Unknown client: ${t}`),console.error(`Supported clients: ${E.map(s=>s.id).join(", ")}`),process.exit(1));let o=je(r,n);o.removed?console.log(`Removed visa-cli from ${o.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});P.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(t,e)=>{try{wt(t);let n=bt(e.method),r=St(e.body),o=new C(()=>f.getSessionToken());console.log(`Checking payment for ${t}...`);let s=vt(await o.paymentPreview({url:t}));console.log(` Merchant: ${s.merchantName}`),console.log(` Amount: $${s.amount.toFixed(2)} ${s.currency}`),console.log(` Rail: auto-detected
|
|
83
|
+
`);let a;if(j())try{let{nonce:l}=await o.getAttestationChallenge(),c=Buffer.from(JSON.stringify({nonce:l,amount:s.amount,merchant:s.merchantName,context:t})).toString("base64");a={signature:await de(c,`pay $${s.amount.toFixed(2)} to ${s.merchantName}`),nonce:l,amount:s.amount,merchant:s.merchantName}}catch(l){console.error(`Touch ID confirmation failed: ${l?.message||"user cancelled or biometric error"}`),process.exit(1)}else console.warn("Warning: Touch ID unavailable on this system \u2014 payment will proceed without biometric attestation.");let i=await o.pay({url:t,method:n,body:r,attestation:a,idempotencyKey:fe.randomUUID()});if(i.success){if(console.log(`Payment complete: $${(i.amount??s.amount).toFixed(2)} \u2192 ${i.merchantName??s.merchantName}`),i.receipt?.urls?.length){console.log(`
|
|
84
|
+
Result URLs:`);for(let l of i.receipt.urls)console.log(` ${l}`)}}else console.error(`Payment failed: ${i.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof b?console.error(`Error: ${n.message}`):console.error("Error:",n.message),process.exit(1)}});P.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{try{let e=await he().getStatus();if(console.log(`Visa CLI Status
|
|
85
85
|
`),console.log("Enrollment:"),console.log(` Enrolled: ${e.enrolled?"Yes":"No"}`),e.githubUser&&console.log(` GitHub: ${e.githubUser}`),console.log(` Cards: ${e.cardCount??0}`),e.cards&&e.cards.length>0){console.log(`
|
|
86
86
|
Cards:`);for(let n of e.cards){let r=n.isDefault?" (default)":"",o=Number.isInteger(n.id)?`#${n.id} `:"";console.log(` ${o}${n.brand?.toUpperCase()||"CARD"} ****${n.last4}${r}`)}}if(e.spendingControls){let n=e.spendingControls;console.log(`
|
|
87
87
|
Spending Controls:`),console.log(` Max per transaction: $${n.maxTransactionAmount}`),console.log(` Daily limit: $${n.dailyLimit}`),n.dailySpent!==void 0&&console.log(` Spent today: $${Number(n.dailySpent).toFixed(2)} / $${n.dailyLimit}`)}console.log(`
|
|
88
|
-
Touch ID:`),console.log(` Available: ${
|
|
89
|
-
`);try{await
|
|
90
|
-
Reset complete.`)}catch(t){console.error("Error:",t.message),process.exit(1)}});
|
|
88
|
+
Touch ID:`),console.log(` Available: ${j()?"Yes":"No"}`)}catch(t){console.error("Error:",t.message),process.exit(1)}});P.command("reset").description("Log out and clear all credentials").action(async()=>{try{console.log(`Resetting Visa CLI...
|
|
89
|
+
`);try{await he().logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await f.clearAll(),console.log(" Keychain credentials cleared."),j())try{await Oe(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
|
|
90
|
+
Reset complete.`)}catch(t){console.error("Error:",t.message),process.exit(1)}});P.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(async t=>{(!t||t.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await f.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await he().feedback(t.trim()),console.log("Feedback submitted. Thanks!")}catch(e){console.error("Error:",e.message),process.exit(1)}});P.command("dove").alias("d").description("Launch Visa Dove \u2014 AI coding agent").option("--model <model>","Model to use (e.g. or-claude-sonnet, or-gpt-4o-mini)").action(async t=>{let{startClient:e}=await Promise.resolve().then(()=>(Xt(),Jt));await e({model:t.model})});P.hook("postAction",()=>{ge&&yt(ge.lastSignals)});P.parse();
|