buoy-wallet 0.0.1 → 0.0.2

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 CHANGED
@@ -114,8 +114,9 @@ buoy mcp run the MCP server on stdio (what install registers)
114
114
  buoy status is it set up, and what are the budgets called
115
115
  buoy balance what it holds, and what is left to spend today
116
116
  buoy agents who can spend, by name
117
- buoy pay --to … --amount …
118
- buoy swap --in … --out … --amount … --min-out …
117
+ buoy pay --to … --amount 150 # 150 USDT0; 0.10 is ten cents. It asks the contract first
118
+ buoy swap --amount 10 --min-out 0.1 # 10 USDT0 for at least 0.1 WOKB
119
+ buoy owner withdraw --amount all # the owner's money back out, on a card in their own wallet
119
120
  buoy fetch <url> buy a 402-gated URL, drawing the exact price just in time
120
121
  buoy verify <txHash> replay the verdict offline
121
122
  buoy owner <action> prepare an owner action and open a sign-link
package/bin/buoy.mjs CHANGED
@@ -63,22 +63,45 @@ ${b("buoy")} — an AI agent's spending account on X Layer
63
63
  ${b("buoy status")} is the wallet set up, and what is it allowed to do
64
64
  ${b("buoy balance")} [--token 0x..] what it holds, and what is left to spend today
65
65
  ${b("buoy agents")} who can spend, by name
66
- ${b("buoy pay")} --to 0x.. --amount N pay, from --from <name> (default: vault)
67
- ${b("buoy swap")} --in 0x.. --out 0x.. --amount N --min-out N
66
+ ${b("buoy pay")} --to 0x.. --amount 150 pay 150 USDT0, from --from <name> (default: vault)
67
+ ${b("buoy swap")} --amount 10 --min-out 0.1 swap 10 USDT0 for at least 0.1 WOKB
68
68
  ${b("buoy verify")} <txHash> replay the verdict offline -> ${b("BIT-EXACT MATCH")}
69
69
  ${b("buoy fetch")} <url> buy a 402-gated URL, drawing the exact price just in time
70
70
  ${b("buoy owner")} <action> prepare an owner action and open a sign-link
71
- ${b("buoy install")} [-y] wire the MCP into Claude Code and Cursor
71
+ ${b("buoy install")} [-y] wire the MCP into Claude Code (every folder) and Cursor
72
72
  ${b("buoy mcp")} run the MCP server on stdio (what ${b("install")} registers)
73
73
 
74
74
  ${dim("Common flags: --json machine-readable --yes actually broadcast a payment")}
75
75
 
76
+ ${dim("Amounts are whole tokens, as you would write them: --amount 150 is 150 USDT0 and")}
77
+ ${dim("--amount 0.10 is ten cents. For exact base units use --amount-base-units (and")}
78
+ ${dim("--min-out-base-units). pay and swap ask the contract first and print its answer.")}
79
+
76
80
  ${dim("Addresses ship with the tool. Nothing to configure, no keys held: the agent signs")}
77
81
  ${dim("in OKX Agentic Wallet's TEE, and you sign owner actions in your own OKX Wallet.")}
78
82
  `;
79
83
 
80
84
  // ------------------------------------------------------------------ commands
81
85
 
86
+ /**
87
+ * One line, on every screen that is about money, when the vault being read is the deployment's
88
+ * and not one set up on this machine. `status` says it; a person who goes straight to `pay`
89
+ * must be told there too, because the figures themselves look like anybody's.
90
+ */
91
+ function sayWhose(m) {
92
+ if (m.wallet) return;
93
+ console.log(yellow(` reading the deployment's LAUNCH vault — not one set up on this machine`));
94
+ }
95
+
96
+ /** The contract's simulated answer, in one coloured phrase. The sentence is `simulation.say`. */
97
+ function verdictWord(sim) {
98
+ if (!sim) return dim("not asked");
99
+ if (sim.outcome === "allowed") return green("would allow it") + (sim.how === "preview" ? dim(" (the policy alone)") : "");
100
+ if (sim.outcome === "refused") return red("would REFUSE it") + dim(` reason ${sim.reason}, ${sim.reasonName}`);
101
+ if (sim.outcome === "reverts") return yellow("would revert") + dim(` ${sim.underfunded ? "the vault does not hold enough" : sim.error}`);
102
+ return dim("could not be asked");
103
+ }
104
+
82
105
  async function cmdStatus() {
83
106
  const { m, r } = connect();
84
107
  const s = await statusView(r);
@@ -86,7 +109,20 @@ async function cmdStatus() {
86
109
 
87
110
  console.log(`\n${b("Buoy")} — ${s.where}`);
88
111
  if (s.isRehearsal) console.log(yellow(" a local rehearsal: these addresses do not exist on X Layer"));
89
- console.log(` wallet ${dim(s.wallet)}`);
112
+ /* Whose vault, first: a person who set one up and is shown the launch vault instead sees real
113
+ budgets and a real owner, and nothing in the figures says they are somebody else's. */
114
+ console.log(
115
+ ` reading ${s.createdBy === "setup" ? green("your vault, set up on this machine") : yellow("the deployment's LAUNCH vault — not one set up on this machine")}`
116
+ );
117
+ if (s.walletFile) console.log(` ${dim(s.walletFile)}`);
118
+ if (s.walletIgnored) console.log(yellow(` ignored ${s.walletIgnored.path}\n ${s.walletIgnored.why}`));
119
+ if (s.pendingSetup) {
120
+ console.log(yellow(` pending a setup of "${s.pendingSetup.name}" started ${s.pendingSetup.startedAt.slice(0, 10)} was never recorded`));
121
+ console.log(dim(` if you approved it: buoy owner setup --finish <its transaction hash>`));
122
+ }
123
+ console.log(` vault ${s.vault} ${dim("← send USDT0 here to fund it")}`);
124
+ if (s.token) console.log(` token ${dim(s.token.address + " the USDT0 contract itself: never send funds to it")}`);
125
+ console.log(` wallet ${dim(s.wallet)} ${dim("(the gatekeeper that judges each request)")}`);
90
126
  console.log(` owner ${dim(s.owner)}`);
91
127
  console.log(` active ${s.active ? green("yes") : yellow("not yet — the owner must install the policy")}`);
92
128
  if (s.policy) {
@@ -109,7 +145,7 @@ async function cmdBalance() {
109
145
  const { r } = connect();
110
146
  const v = await balanceView(r, { token: flag("token") });
111
147
  if (JSON_OUT) return out(null, v);
112
- console.log(`\n${b("Buoy")} — ${v.token.symbol} ${dim(v.token.address)}\n`);
148
+ console.log(`\n${b("Buoy")} — ${v.token.symbol} ${dim("token contract " + v.token.address + " (never send funds to it)")}\n`);
113
149
  for (const a of v.accounts) {
114
150
  console.log(` ${(a.name ?? a.via).padEnd(20)} ${a.balance.padStart(16)} ${dim(a.remainingTodayUnits + " left today")}`);
115
151
  }
@@ -135,17 +171,22 @@ async function cmdPay() {
135
171
  const plan = await planPayment(r, {
136
172
  to: flag("to"),
137
173
  amount: flag("amount"),
174
+ amountBaseUnits: flag("amount-base-units"),
138
175
  token: flag("token"),
139
176
  from: flag("from"),
177
+ agent: flag("agent"),
140
178
  });
141
179
 
142
180
  if (JSON_OUT && !has("yes")) return out(null, plan);
143
181
  if (!JSON_OUT) {
144
182
  console.log(`\n${b("Buoy")} — payment`);
183
+ sayWhose(m);
145
184
  console.log(` from ${plan.from.name ?? plan.from.via}`);
146
185
  console.log(` to ${dim(plan.to)}`);
147
- console.log(` amount ${plan.amountHuman}`);
148
- console.log(`\n ${plan.expectation}\n`);
186
+ console.log(` amount ${plan.amountHuman} ${dim("(" + plan.amountBaseUnits + " base units)")}`);
187
+ console.log(` contract ${verdictWord(plan.simulation)}`);
188
+ console.log(`\n ${plan.simulation.say}\n`);
189
+ if (plan.note) console.log(yellow(` ${plan.note}\n`));
149
190
  }
150
191
 
151
192
  if (!has("yes")) {
@@ -158,7 +199,19 @@ async function cmdPay() {
158
199
  this file makes it obvious which commands can move money and which cannot. */
159
200
  const okx = await import("../ts/okx/signer.mjs");
160
201
  const run = okx.cliRunner();
161
- const presentation = okx.present({ run, submit: plan.submit, chain: String(m.chainId) });
202
+ let presentation;
203
+ try {
204
+ presentation = okx.present({ run, submit: plan.submit, chain: String(m.chainId) });
205
+ } catch (e) {
206
+ if (e.code !== "cli-not-installed") throw e;
207
+ /* No signing lane on this machine. That is not the contract's answer and must not read as
208
+ one: what the contract would say is the simulation above, which needed no key. */
209
+ console.error(red(`\n Not sent: onchainos is not installed, so there is nothing here to sign with.`));
210
+ console.error(dim(` ${e.message}`));
211
+ console.error(dim(` What the contract would answer is printed above. That was asked directly, and needs no key.\n`));
212
+ process.exitCode = 1;
213
+ return;
214
+ }
162
215
  if (!presentation.confirming) {
163
216
  console.error(red(`\n onchainos would not confirm this call.`));
164
217
  console.error(dim(` ${(presentation.raw.stderr || presentation.raw.stdout || "").trim().slice(0, 400)}\n`));
@@ -185,11 +238,19 @@ async function cmdSwap() {
185
238
  tokenOut: flag("out"),
186
239
  fee: Number(flag("fee", "500")),
187
240
  amountIn: flag("amount"),
241
+ amountInBaseUnits: flag("amount-base-units"),
188
242
  minAmountOut: flag("min-out"),
243
+ minAmountOutBaseUnits: flag("min-out-base-units"),
189
244
  from: flag("from"),
245
+ agent: flag("agent"),
190
246
  });
191
247
  if (JSON_OUT) return out(null, plan);
192
- console.log(`\n${b("Buoy")} — swap\n ${plan.say}\n`);
248
+ console.log(`\n${b("Buoy")} — swap`);
249
+ sayWhose(m);
250
+ console.log(` give ${plan.amountInHuman}`);
251
+ console.log(` get at least ${plan.minAmountOutHuman}`);
252
+ console.log(` contract ${verdictWord(plan.simulation)}`);
253
+ console.log(`\n ${plan.say}\n`);
193
254
  console.log(dim(` ${plan.howToSend}\n`));
194
255
  }
195
256
 
@@ -250,6 +311,7 @@ async function cmdFetch() {
250
311
 
251
312
  if (!JSON_OUT) {
252
313
  console.log(`\n${b("Buoy")} — ${url}`);
314
+ sayWhose(m);
253
315
  console.log(` price ${plan.draw.amountHuman} ${dim("to " + plan.offer.payTo)}`);
254
316
  console.log(` draw from ${plan.draw.from.name ?? plan.draw.from.via} into ${dim(plan.agentWallet)}`);
255
317
  console.log(`\n ${plan.draw.expectation}\n`);
@@ -330,7 +392,9 @@ async function cmdOwner() {
330
392
 
331
393
  async function cmdInstall() {
332
394
  const { install } = await import("../scripts/install-buoy.mjs");
333
- await install({ yes: has("yes") || has("y"), target: flag("target", "all"), print: console.log });
395
+ const res = await install({ yes: has("yes") || has("y"), target: flag("target", "all"), scope: flag("scope", "user"), print: console.log });
396
+ // Asked to write and could not: that is a failure, and a script running this must see one.
397
+ if (res.failed?.length) process.exitCode = 1;
334
398
  }
335
399
 
336
400
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "buoy-wallet",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "description": "Self-custodial agentic vault on X Layer with on-chain TapeOut circuit policies, gas-free OKX Agentic Wallet execution, and 1-click Fast Start.",
5
5
  "keywords": [
6
6
  "xlayer",
@@ -59,6 +59,9 @@
59
59
  "test:approve": "node ts/test/run-approve.mjs",
60
60
  "test:setup": "node ts/test/run-setup.mjs",
61
61
  "test:verify": "node ts/test/run-verify.mjs",
62
+ "test:pay": "node ts/test/run-pay.mjs",
63
+ "gen:pay-fixture": "node scripts/gen-pay-fixture.mjs",
64
+ "test:install": "node ts/test/run-install.mjs",
62
65
  "gen:verify-fixture": "node scripts/gen-verify-fixture.mjs",
63
66
  "test:setup-fork": "node ts/test/run-setup-fork.mjs",
64
67
  "test:cli": "node ts/test/run-buoy-cli.mjs",
@@ -66,7 +69,7 @@
66
69
  "test:mcp-server": "node ts/test/run-mcp-server.mjs",
67
70
  "redteam": "node scripts/redteam-demo.mjs",
68
71
  "test:on-fork": "npm run test:cli && npm run test:fetch402 && npm run test:integration && npm run redteam && npm run test:setup-fork",
69
- "test:node": "npm run coverage && npm run test:vectors && npm run test:own && npm run test:bindings && npm run test:results && npm run test:own5 && npm run test:evaluations && npm run test:own-tap02 && npm run test:metadata && npm run test:own-meta && npm run test:mcp && npm run test:mcp-chain && npm run test:verify && npm run test:okx && npm run test:approve && npm run test:setup && npm run test:mcp-server && npm run test:console",
72
+ "test:node": "npm run coverage && npm run test:vectors && npm run test:own && npm run test:bindings && npm run test:results && npm run test:own5 && npm run test:evaluations && npm run test:own-tap02 && npm run test:metadata && npm run test:own-meta && npm run test:mcp && npm run test:mcp-chain && npm run test:verify && npm run test:pay && npm run test:okx && npm run test:install && npm run test:approve && npm run test:setup && npm run test:mcp-server && npm run test:console",
70
73
  "test:okx": "node ts/test/run-okx.mjs",
71
74
  "test:own": "node ts/test/run-own.mjs",
72
75
  "test:own-meta": "node ts/test/run-own-metadata.mjs",
@@ -16,6 +16,13 @@
16
16
  // named by its path. An install from npm does not: under `npx` this folder is a cache entry that
17
17
  // the next release replaces, and a path into it would be a config that works until it silently
18
18
  // does not. There the agent is told to run the package instead -- `npx -y <name>@latest mcp`.
19
+ //
20
+ // WHERE it registers, for Claude Code, is the part that was wrong until 0.0.2. `claude mcp add`
21
+ // defaults to LOCAL scope: it files the server under the one folder it was run from, and every
22
+ // other folder answers "No MCP server found". This is run from wherever the agent happens to be,
23
+ // usually a temp folder under npx, so the default registered Buoy for a folder nobody opens again
24
+ // -- and reported it as added. It is now asked for at USER scope, and nothing is reported as done
25
+ // until the config has been read back and the entry is there. See ts/test/run-install.mjs.
19
26
 
20
27
  import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
21
28
  import { spawnSync } from "node:child_process";
@@ -23,12 +30,14 @@ import { homedir } from "node:os";
23
30
  import { join, dirname } from "node:path";
24
31
  import { pathToFileURL } from "node:url";
25
32
  import { resolveManifest, describe, PACKAGE_ROOT, isCheckout } from "../ts/mcp/manifest.mjs";
33
+ import { locateOnchainos, ONCHAINOS_INSTALL } from "../ts/okx/locate.mjs";
26
34
 
27
35
  const C = "\x1b[";
28
36
  const b = (s) => `${C}1m${s}${C}0m`;
29
37
  const dim = (s) => `${C}2m${s}${C}0m`;
30
38
  const green = (s) => `${C}32m${s}${C}0m`;
31
39
  const yellow = (s) => `${C}33m${s}${C}0m`;
40
+ const red = (s) => `${C}31m${s}${C}0m`;
32
41
 
33
42
  /**
34
43
  * The command an agent should run to start the server.
@@ -43,61 +52,176 @@ export function serverCommand({ checkout = isCheckout(), platform = process.plat
43
52
  return platform === "win32" ? { command: "cmd", args: ["/c", ...npx] } : { command: npx[0], args: npx.slice(1) };
44
53
  }
45
54
 
46
- const SERVER = serverCommand();
55
+ const homeOf = (env) => env.HOME || env.USERPROFILE || homedir();
56
+
57
+ /**
58
+ * The file Claude Code keeps its settings in: `.claude.json` in `CLAUDE_CONFIG_DIR`, or in the
59
+ * home folder. Its top-level `mcpServers` is USER scope, read from every folder; a server under
60
+ * `projects["<folder>"].mcpServers` is LOCAL scope and read from that folder alone.
61
+ */
62
+ export function claudeConfigPath(env = process.env) {
63
+ return join(env.CLAUDE_CONFIG_DIR ? env.CLAUDE_CONFIG_DIR : homeOf(env), ".claude.json");
64
+ }
65
+
66
+ const sameServer = (a, c) => !!a && a.command === c.command && JSON.stringify(a.args ?? []) === JSON.stringify(c.args);
47
67
 
48
- /** Merge one server into a JSON config without disturbing whatever else is in it. */
49
- function mergeConfig(path, name, server, print) {
68
+ /** One server out of a JSON config: absent, present, or a file that cannot be read as JSON. */
69
+ function readServer(path, name) {
70
+ if (!existsSync(path)) return { state: "absent", entry: null };
71
+ try {
72
+ const entry = JSON.parse(readFileSync(path, "utf8"))?.mcpServers?.[name] ?? null;
73
+ return { state: entry ? "present" : "absent", entry };
74
+ } catch {
75
+ return { state: "unreadable", entry: null };
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Merge one server into a JSON config without disturbing whatever else is in it. Returns false,
81
+ * having written nothing, when the file exists and is not valid JSON: it is the user's and
82
+ * probably holds other servers, and replacing it because we could not parse it would be the worst
83
+ * possible outcome.
84
+ */
85
+ function mergeConfig(path, name, server) {
50
86
  let cur = {};
51
87
  if (existsSync(path)) {
52
88
  try {
53
89
  cur = JSON.parse(readFileSync(path, "utf8"));
54
90
  } catch {
55
- /* Refuse rather than overwrite. This file is the user's and probably holds other servers;
56
- replacing it because we could not parse it would be the worst possible outcome. */
57
- print(` ${yellow("skipped")} ${path} ${dim("is not valid JSON — left untouched")}`);
58
91
  return false;
59
92
  }
60
93
  }
61
- const already = JSON.stringify(cur.mcpServers?.[name] ?? null) === JSON.stringify(server);
62
94
  cur.mcpServers = { ...(cur.mcpServers || {}), [name]: server };
63
95
  mkdirSync(dirname(path), { recursive: true });
64
96
  writeFileSync(path, JSON.stringify(cur, null, 2) + "\n");
65
- print(` ${green(already ? "already set" : "wrote")} ${dim(path)}`);
66
97
  return true;
67
98
  }
68
99
 
100
+ /** Quote one argument for cmd.exe. Nothing here is user text: a command, flags, and a path. */
101
+ const winQuote = (a) => (/^[A-Za-z0-9_\-/\\:.@=,+]+$/.test(a) ? a : `"${String(a).replace(/"/g, '\\"')}"`);
102
+
103
+ /**
104
+ * Run the `claude` CLI, if there is one.
105
+ *
106
+ * An argv ARRAY and no shell, first: a `--` separator handed to a PowerShell command line gets
107
+ * eaten, and the resulting "unknown option" comes from claude rather than from the shell, which
108
+ * points the eye at entirely the wrong place.
109
+ *
110
+ * On Windows that first attempt finds a native `claude.exe` and nothing else. Installed from npm,
111
+ * `claude` is `claude.cmd`, which cannot be spawned without a shell at all -- so that install,
112
+ * which is the common one, used to read as "no claude here". It is run through cmd.exe instead,
113
+ * with the line quoted by hand, because Node's own `shell: true` joins arguments unquoted and a
114
+ * checkout under a path with a space in it then arrives as two arguments.
115
+ *
116
+ * @returns a function from argv to `{ found: false }` or `{ found: true, status, said }`.
117
+ */
118
+ export function claudeRunner({ env = process.env, cwd = process.cwd(), platform = process.platform } = {}) {
119
+ return (args) => {
120
+ let r = spawnSync("claude", args, { encoding: "utf8", shell: false, env, cwd });
121
+ if (r.error && platform === "win32") {
122
+ const line = ["claude", ...args].map(winQuote).join(" ");
123
+ r = spawnSync(env.ComSpec || "cmd.exe", ["/d", "/s", "/c", `"${line}"`], {
124
+ encoding: "utf8",
125
+ shell: false,
126
+ env,
127
+ cwd,
128
+ windowsVerbatimArguments: true,
129
+ });
130
+ // cmd.exe itself started; whether it found a `claude` to run is in what it printed.
131
+ if (!r.error && r.status !== 0 && /is not recognized as an internal or external command/i.test(r.stderr ?? "")) {
132
+ return { found: false };
133
+ }
134
+ }
135
+ if (r.error) return { found: false };
136
+ return { found: true, status: r.status, said: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
137
+ };
138
+ }
139
+
69
140
  /**
70
- * Claude Code. `claude mcp add` is the supported path and merges safely, so try it first.
141
+ * Register the server with Claude Code, and say only what can be read back.
71
142
  *
72
- * spawnSync with shell:false and an argv ARRAY is deliberate: a `--` separator handed to a
73
- * PowerShell command line gets eaten, and the resulting "unknown option" comes from claude
74
- * rather than from the shell, which points the eye at entirely the wrong place.
143
+ * `claude mcp add --scope user` is tried first where there is a `claude`: it is the supported
144
+ * path and it takes Claude Code's own lock on the file. Whatever it prints, the config is then
145
+ * READ, and the server counts as registered only if the entry is there, at user scope, with this
146
+ * command. If it is not -- no CLI, a CLI that refused, a CLI that filed it somewhere else -- the
147
+ * same entry is merged in directly, and read back again.
75
148
  */
76
- function installClaude(print) {
77
- const probe = spawnSync("claude", ["--version"], { encoding: "utf8", shell: false });
78
- if (!probe.error) {
79
- const r = spawnSync("claude", ["mcp", "add", "buoy", "--", SERVER.command, ...SERVER.args], {
80
- encoding: "utf8",
81
- shell: false,
82
- });
83
- const said = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
84
- if (r.status === 0 || /already exists/i.test(said)) {
85
- print(` ${green(r.status === 0 ? "added" : "already added")} ${dim("claude mcp add buoy")}`);
149
+ function installClaude({ server, env, cwd, run, print }) {
150
+ const path = claudeConfigPath(env);
151
+ const byHand = `claude mcp add --scope user buoy -- ${[server.command, ...server.args].join(" ")}`;
152
+ let cur = readServer(path, "buoy");
153
+
154
+ if (cur.state === "present" && sameServer(cur.entry, server)) {
155
+ print(` ${green("already set")} ${dim("Claude Code, for every folder — " + path)}`);
156
+ return true;
157
+ }
158
+ if (cur.state === "unreadable") {
159
+ print(` ${red("not installed")} ${dim(path + " is not valid JSON, so it was left untouched")}`);
160
+ print(dim(` fix that file, or add the server yourself: ${byHand}`));
161
+ return false;
162
+ }
163
+
164
+ if (run(["--version"]).found) {
165
+ // A leftover from a checkout that has moved: same name, a command that no longer runs.
166
+ if (cur.state === "present") run(["mcp", "remove", "--scope", "user", "buoy"]);
167
+ const r = run(["mcp", "add", "--scope", "user", "buoy", "--", server.command, ...server.args]);
168
+ cur = readServer(path, "buoy");
169
+ if (cur.state === "present" && sameServer(cur.entry, server)) {
170
+ print(` ${green("added")} ${dim("Claude Code, for every folder (claude mcp add --scope user) — " + path)}`);
171
+ return true;
172
+ }
173
+ print(` ${yellow("claude mcp add did not register it")} ${dim((r.said ?? "").slice(0, 200))}`);
174
+ }
175
+
176
+ // No CLI, or one that did not leave the entry where every folder reads it: write it ourselves.
177
+ if (mergeConfig(path, "buoy", { type: "stdio", command: server.command, args: server.args, env: {} })) {
178
+ cur = readServer(path, "buoy");
179
+ if (cur.state === "present" && sameServer(cur.entry, server)) {
180
+ print(` ${green("wrote")} ${dim("Claude Code, for every folder — " + path)}`);
86
181
  return true;
87
182
  }
88
- print(` ${yellow("claude mcp add failed")} ${dim(said.slice(0, 200))}`);
89
183
  }
90
- // Fall back to the config file Claude Code reads, merged the same careful way.
91
- return mergeConfig(join(homedir(), ".claude.json"), "buoy", SERVER, print);
184
+ print(` ${red("not installed")} ${dim("Claude Code's config at " + path + " could not be updated")}`);
185
+ print(dim(` add the server yourself: ${byHand}`));
186
+ return false;
187
+ }
188
+
189
+ /** A config that is one JSON file with `mcpServers` in it: Cursor's, or a project's `.mcp.json`. */
190
+ function installFile({ path, server, label, print }) {
191
+ const before = readServer(path, "buoy");
192
+ if (before.state === "present" && sameServer(before.entry, server)) {
193
+ print(` ${green("already set")} ${dim(label + " — " + path)}`);
194
+ return true;
195
+ }
196
+ if (!mergeConfig(path, "buoy", server) || !sameServer(readServer(path, "buoy").entry, server)) {
197
+ print(` ${red("not installed")} ${dim(path + " is not valid JSON, so it was left untouched")}`);
198
+ return false;
199
+ }
200
+ print(` ${green("wrote")} ${dim(label + " — " + path)}`);
201
+ return true;
92
202
  }
93
203
 
94
- export async function install({ yes = false, target = "all", print = console.log } = {}) {
204
+ /**
205
+ * @param scope "user" (the default): Claude Code reads the server from every folder.
206
+ * "project": written to `.mcp.json` in `cwd`, for that project's collaborators;
207
+ * Claude Code asks each of them to approve it the first time.
208
+ */
209
+ export async function install({
210
+ yes = false,
211
+ target = "all",
212
+ scope = "user",
213
+ print = console.log,
214
+ env = process.env,
215
+ cwd = process.cwd(),
216
+ run,
217
+ server,
218
+ } = {}) {
219
+ const SERVER = server ?? serverCommand();
95
220
  print(`\n${b("Buoy")} — connecting your agent\n`);
96
221
 
97
222
  // 1. Is there a deployment to point at? Say so plainly rather than writing a dead config.
98
- let m = null;
99
223
  try {
100
- m = resolveManifest();
224
+ const m = resolveManifest();
101
225
  print(` deployment ${describe(m)}`);
102
226
  print(` manifest ${dim(m.path)}`);
103
227
  if (m.missing.length) print(` ${yellow("incomplete")} ${dim("missing: " + m.missing.join(", "))}`);
@@ -107,12 +231,16 @@ export async function install({ yes = false, target = "all", print = console.log
107
231
  }
108
232
 
109
233
  // 2. Is the agent's signing lane available? Buoy never holds the key, so this is OKX's job.
110
- const okx = spawnSync("onchainos", ["--version"], { encoding: "utf8", shell: false });
111
- if (okx.error) {
112
- print(` ${yellow("onchainos missing")} ${dim("agent payments need it; reads and verification do not")}`);
113
- print(dim(` install: npx -y @okxweb3/onchainos-installer install`));
234
+ const okx = locateOnchainos({ env });
235
+ if (okx.bin && okx.onPath) {
236
+ print(` signing ${green(okx.version)} ${dim("(keys stay in OKX's TEE)")}`);
237
+ } else if (okx.bin) {
238
+ print(` signing ${green(okx.version)} ${yellow("installed, but not on PATH")}`);
239
+ print(dim(` it is at ${okx.bin} — open a new terminal, or add that folder to PATH`));
114
240
  } else {
115
- print(` signing ${green((okx.stdout ?? "").trim() || "onchainos present")} ${dim("(keys stay in OKX's TEE)")}`);
241
+ print(` ${yellow("onchainos missing")} ${dim("agent payments need it; reads, simulations and verification do not")}`);
242
+ print(dim(` install: ${ONCHAINOS_INSTALL}`));
243
+ print(dim(` then: onchainos wallet login (see the skill: "The agent's wallet")`));
116
244
  }
117
245
 
118
246
  print("");
@@ -126,19 +254,37 @@ export async function install({ yes = false, target = "all", print = console.log
126
254
  }
127
255
 
128
256
  const done = [];
129
- if (show("claude")) if (installClaude(print)) done.push("claude");
130
- if (show("cursor")) if (mergeConfig(join(homedir(), ".cursor", "mcp.json"), "buoy", SERVER, print)) done.push("cursor");
257
+ const failed = [];
258
+ const note = (name, good) => (good ? done : failed).push(name);
259
+ if (show("claude")) {
260
+ if (scope === "project") {
261
+ note("claude", installFile({ path: join(cwd, ".mcp.json"), server: SERVER, label: "Claude Code, this project only", print }));
262
+ print(dim(` Claude Code asks each person to approve a project's server the first time they open it.`));
263
+ } else {
264
+ note("claude", installClaude({ server: SERVER, env, cwd, run: run ?? claudeRunner({ env, cwd }), print }));
265
+ }
266
+ }
267
+ if (show("cursor")) {
268
+ note("cursor", installFile({ path: join(homeOf(env), ".cursor", "mcp.json"), server: SERVER, label: "Cursor", print }));
269
+ }
131
270
 
132
- print(`\n ${green("Done.")} Restart the agent so it picks up the new server, then ask it:`);
133
- print(` ${dim('"what can my Buoy wallet do?"')}\n`);
134
- return { wrote: true, targets: done, server: SERVER };
271
+ if (failed.length) {
272
+ print(`\n ${red("Not finished.")} ${failed.join(" and ")} could not be set up: see above. Nothing else was changed.\n`);
273
+ } else {
274
+ print(`\n ${green("Done.")} Restart the agent so it picks up the new server, then ask it:`);
275
+ print(` ${dim('"what can my Buoy wallet do?"')}\n`);
276
+ }
277
+ return { wrote: done.length > 0, targets: done, failed, server: SERVER };
135
278
  }
136
279
 
137
280
  // pathToFileURL, not a hand-built file:// string -- see the note in ts/mcp/server.mjs.
138
281
  if (import.meta.url === pathToFileURL(process.argv[1]).href) {
139
282
  const argv = process.argv.slice(2);
140
- await install({
283
+ const after = (flag, d) => (argv.includes(flag) ? argv[argv.indexOf(flag) + 1] : d);
284
+ const res = await install({
141
285
  yes: argv.includes("-y") || argv.includes("--yes"),
142
- target: argv.includes("--target") ? argv[argv.indexOf("--target") + 1] : "all",
286
+ target: after("--target", "all"),
287
+ scope: after("--scope", "user"),
143
288
  });
289
+ if (res.failed?.length) process.exitCode = 1;
144
290
  }