shinjuku-shielded 0.3.130 → 0.3.131

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
@@ -6,19 +6,19 @@ answers privately, in a terminal chat or for your agent app. Its `mcp`
6
6
  command runs a local MCP server (stdio) for your agent. Your keys never
7
7
  leave your machine.
8
8
 
9
- This is version 0.3.130. The npm packages `shinjuku-shield` and
9
+ This is version 0.3.131. The npm packages `shinjuku-shield` and
10
10
  `shinjuku-shielded` hold the same files. The command is `shinjuku`.
11
11
 
12
12
  ## Set up
13
13
 
14
14
  ```sh
15
- npm install -g shinjuku@0.3.130
15
+ npm install -g shinjuku@0.3.131
16
16
  shinjuku setup
17
17
  ```
18
18
 
19
19
  Type the two lines as they are. `npx install shinjuku` does not work: npx
20
20
  reads `install` as the name of another npm package. To set up without
21
- installing, type `npx shinjuku@0.3.130 setup`.
21
+ installing, type `npx shinjuku@0.3.131 setup`.
22
22
 
23
23
  Setup makes the wallet on this machine, a private passphrase file, and the
24
24
  checked proof tools (about 191 MB), and writes `config.json`. It also writes
@@ -36,13 +36,13 @@ Every wallet command works after `shinjuku`, for example `shinjuku balance`,
36
36
  Claude Code:
37
37
 
38
38
  ```sh
39
- claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.130 mcp
39
+ claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.131 mcp
40
40
  ```
41
41
 
42
42
  Claude Desktop (`claude_desktop_config.json`) or Cursor (`~/.cursor/mcp.json`):
43
43
 
44
44
  ```json
45
- { "mcpServers": { "shinjuku": { "command": "npx", "args": ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.130", "mcp"] } } }
45
+ { "mcpServers": { "shinjuku": { "command": "npx", "args": ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.131", "mcp"] } } }
46
46
  ```
47
47
 
48
48
  On native Windows, if the host cannot find `npx`, use `"command": "cmd"` and
package/manifest.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schema": "carbon-shielded-wallet/bundle-manifest/v1",
3
3
  "file": "shinjuku-wallet.mjs",
4
- "sha256": "8f281d4a0dfc79a40a10dbf8c31de01823d8dffb15c151b6e774d781e96f1736",
5
- "bytes": 8847121,
6
- "sourceCommit": "34b666b11401c493bf128482267e696279c5be79",
4
+ "sha256": "3c8b302d8f0616edc98cc277f1b41b5cc47d121efb77a7b1cba3214ab60fb8b8",
5
+ "bytes": 8854666,
6
+ "sourceCommit": "f8edc34bbba2bacdd4a92606edf067a54db57d94",
7
7
  "sourceDirty": false,
8
8
  "installRecordMatchesLockfile": true,
9
9
  "releaseRule": "valid only when two fresh npm ci --ignore-scripts builds on different OSes give the same sha256; installRecordMatchesLockfile true means every entry npm installed equals its package-lock.json entry and every entry not marked optional, devOptional included, is installed: an optional entry (a package for another platform) may be absent",
@@ -1037,5 +1037,5 @@
1037
1037
  "version": "1.8.0"
1038
1038
  }
1039
1039
  ],
1040
- "publishedAt": "2026-10-30T09:28:04.209Z"
1040
+ "publishedAt": "2026-10-30T10:43:17.514Z"
1041
1041
  }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "shinjuku-shielded",
3
- "version": "0.3.130",
3
+ "version": "0.3.131",
4
4
  "mcpName": "io.github.ShinjukuStaition/shinjuku-mcp",
5
5
  "description": "Shinjuku Shielded, the private x402 facilitator on Solana: the self-custody wallet CLI and its MCP server. Shield, pay, and unshield USDC from any MCP agent, under caps you set.",
6
- "shinjukuRelease": "8f281d4a",
7
- "shinjukuSha256": "8f281d4a0dfc79a40a10dbf8c31de01823d8dffb15c151b6e774d781e96f1736",
6
+ "shinjukuRelease": "3c8b302d",
7
+ "shinjukuSha256": "3c8b302d8f0616edc98cc277f1b41b5cc47d121efb77a7b1cba3214ab60fb8b8",
8
8
  "license": "SEE LICENSE IN LICENSE.txt",
9
9
  "author": "Shinjuku Shielded",
10
10
  "homepage": "https://github.com/ShinjukuStaition/shinjuku-shield#readme",
@@ -126,7 +126,7 @@ var require_utils = __commonJS({
126
126
  exports.createHasher = createHasher3;
127
127
  exports.createOptHasher = createOptHasher;
128
128
  exports.createXOFer = createXOFer2;
129
- exports.randomBytes = randomBytes30;
129
+ exports.randomBytes = randomBytes31;
130
130
  var crypto_1 = require_cryptoNode();
131
131
  function isBytes4(a) {
132
132
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
@@ -324,7 +324,7 @@ var require_utils = __commonJS({
324
324
  exports.wrapConstructor = createHasher3;
325
325
  exports.wrapConstructorWithOpts = createOptHasher;
326
326
  exports.wrapXOFConstructorWithOpts = createXOFer2;
327
- function randomBytes30(bytesLength = 32) {
327
+ function randomBytes31(bytesLength = 32) {
328
328
  if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") {
329
329
  return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
330
330
  }
@@ -2496,7 +2496,7 @@ var require_edwards = __commonJS({
2496
2496
  });
2497
2497
  const { prehash } = eddsaOpts;
2498
2498
  const { BASE: BASE2, Fp: Fp2, Fn: Fn2 } = Point;
2499
- const randomBytes30 = eddsaOpts.randomBytes || utils_ts_1.randomBytes;
2499
+ const randomBytes31 = eddsaOpts.randomBytes || utils_ts_1.randomBytes;
2500
2500
  const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes2) => bytes2);
2501
2501
  const domain3 = eddsaOpts.domain || ((data, ctx, phflag) => {
2502
2502
  (0, utils_ts_1._abool2)(phflag, "phflag");
@@ -2578,7 +2578,7 @@ var require_edwards = __commonJS({
2578
2578
  signature: 2 * _size,
2579
2579
  seed: _size
2580
2580
  };
2581
- function randomSecretKey(seed = randomBytes30(lengths.seed)) {
2581
+ function randomSecretKey(seed = randomBytes31(lengths.seed)) {
2582
2582
  return (0, utils_ts_1._abytes2)(seed, lengths.seed, "seed");
2583
2583
  }
2584
2584
  function keygen(seed) {
@@ -6502,7 +6502,7 @@ var require_utils3 = __commonJS({
6502
6502
  exports.createHasher = createHasher3;
6503
6503
  exports.createOptHasher = createOptHasher;
6504
6504
  exports.createXOFer = createXOFer2;
6505
- exports.randomBytes = randomBytes30;
6505
+ exports.randomBytes = randomBytes31;
6506
6506
  var crypto_1 = require_cryptoNode2();
6507
6507
  function isBytes4(a) {
6508
6508
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
@@ -6700,7 +6700,7 @@ var require_utils3 = __commonJS({
6700
6700
  exports.wrapConstructor = createHasher3;
6701
6701
  exports.wrapConstructorWithOpts = createOptHasher;
6702
6702
  exports.wrapXOFConstructorWithOpts = createXOFer2;
6703
- function randomBytes30(bytesLength = 32) {
6703
+ function randomBytes31(bytesLength = 32) {
6704
6704
  if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") {
6705
6705
  return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
6706
6706
  }
@@ -18266,7 +18266,7 @@ var require_websocket = __commonJS({
18266
18266
  var http2 = __require("http");
18267
18267
  var net2 = __require("net");
18268
18268
  var tls = __require("tls");
18269
- var { randomBytes: randomBytes30, createHash: createHash32 } = __require("crypto");
18269
+ var { randomBytes: randomBytes31, createHash: createHash32 } = __require("crypto");
18270
18270
  var { Duplex, Readable } = __require("stream");
18271
18271
  var { URL: URL4 } = __require("url");
18272
18272
  var PerMessageDeflate = require_permessage_deflate();
@@ -18804,7 +18804,7 @@ var require_websocket = __commonJS({
18804
18804
  }
18805
18805
  }
18806
18806
  const defaultPort = isSecure ? 443 : 80;
18807
- const key = randomBytes30(16).toString("base64");
18807
+ const key = randomBytes31(16).toString("base64");
18808
18808
  const request = isSecure ? https.request : http2.request;
18809
18809
  const protocolSet = /* @__PURE__ */ new Set();
18810
18810
  let perMessageDeflate;
@@ -22414,7 +22414,7 @@ var require_weierstrass = __commonJS({
22414
22414
  bits2int: "function",
22415
22415
  bits2int_modN: "function"
22416
22416
  });
22417
- const randomBytes30 = ecdsaOpts.randomBytes || utils_ts_1.randomBytes;
22417
+ const randomBytes31 = ecdsaOpts.randomBytes || utils_ts_1.randomBytes;
22418
22418
  const hmac4 = ecdsaOpts.hmac || ((key, ...msgs) => (0, hmac_js_1.hmac)(hash12, key, (0, utils_ts_1.concatBytes)(...msgs)));
22419
22419
  const { Fp: Fp2, Fn: Fn2 } = Point;
22420
22420
  const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn2;
@@ -22569,7 +22569,7 @@ var require_weierstrass = __commonJS({
22569
22569
  const d = _normFnElement2(Fn2, privateKey);
22570
22570
  const seedArgs = [int2octets(d), int2octets(h1int)];
22571
22571
  if (extraEntropy != null && extraEntropy !== false) {
22572
- const e14 = extraEntropy === true ? randomBytes30(lengths.secretKey) : extraEntropy;
22572
+ const e14 = extraEntropy === true ? randomBytes31(lengths.secretKey) : extraEntropy;
22573
22573
  seedArgs.push((0, utils_ts_1.ensureBytes)("extraEntropy", e14));
22574
22574
  }
22575
22575
  const seed = (0, utils_ts_1.concatBytes)(...seedArgs);
@@ -45679,7 +45679,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
45679
45679
  });
45680
45680
  const { prehash } = eddsaOpts;
45681
45681
  const { BASE: BASE2, Fp: Fp2, Fn: Fn2 } = Point;
45682
- const randomBytes30 = eddsaOpts.randomBytes || randomBytes3;
45682
+ const randomBytes31 = eddsaOpts.randomBytes || randomBytes3;
45683
45683
  const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes2) => bytes2);
45684
45684
  const domain3 = eddsaOpts.domain || ((data, ctx, phflag) => {
45685
45685
  _abool2(phflag, "phflag");
@@ -45761,7 +45761,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
45761
45761
  signature: 2 * _size,
45762
45762
  seed: _size
45763
45763
  };
45764
- function randomSecretKey(seed = randomBytes30(lengths.seed)) {
45764
+ function randomSecretKey(seed = randomBytes31(lengths.seed)) {
45765
45765
  return _abytes2(seed, lengths.seed, "seed");
45766
45766
  }
45767
45767
  function keygen(seed) {
@@ -71122,10 +71122,10 @@ async function createKeyPairFromBytes(bytes2, extractable = false) {
71122
71122
  ),
71123
71123
  createPrivateKeyFromBytes(bytes2.slice(0, 32), extractable)
71124
71124
  ]);
71125
- const randomBytes30 = new Uint8Array(32);
71126
- crypto.getRandomValues(randomBytes30);
71127
- const signedData = await signBytes(privateKey, randomBytes30);
71128
- const isValid2 = await verifySignature3(publicKey3, signedData, randomBytes30);
71125
+ const randomBytes31 = new Uint8Array(32);
71126
+ crypto.getRandomValues(randomBytes31);
71127
+ const signedData = await signBytes(privateKey, randomBytes31);
71128
+ const isValid2 = await verifySignature3(publicKey3, signedData, randomBytes31);
71129
71129
  if (!isValid2) {
71130
71130
  throw new SolanaError(SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY);
71131
71131
  }
@@ -77044,10 +77044,25 @@ function createSpendPolicy({
77044
77044
  walletDay = false,
77045
77045
  maxDayAtomic,
77046
77046
  maxDayNext,
77047
- now = Date.now
77047
+ now = Date.now,
77048
+ limitsNow
77048
77049
  } = {}) {
77049
- const maxPayment = atomicOption(maxPaymentAtomic, "maxPaymentAtomic", { required: true });
77050
- const maxSession = atomicOption(maxSessionAtomic, "maxSessionAtomic", { required: false });
77050
+ const launchPayment = atomicOption(maxPaymentAtomic, "maxPaymentAtomic", { required: true });
77051
+ const launchSession = atomicOption(maxSessionAtomic, "maxSessionAtomic", { required: false });
77052
+ if (limitsNow !== void 0 && typeof limitsNow !== "function") invalid2("limitsNow must be a function");
77053
+ const nowOr = (name, launch) => {
77054
+ if (limitsNow === void 0 || launch === void 0) return launch;
77055
+ let value2;
77056
+ try {
77057
+ value2 = limitsNow()?.[name];
77058
+ } catch {
77059
+ return launch;
77060
+ }
77061
+ const text3 = typeof value2 === "bigint" ? value2.toString() : String(value2 ?? "");
77062
+ return POSITIVE_ATOMIC2.test(text3) ? BigInt(text3) : launch;
77063
+ };
77064
+ const paymentCap = () => nowOr("maxPaymentAtomic", launchPayment);
77065
+ const sessionCap = () => nowOr("maxSessionAtomic", launchSession);
77051
77066
  const maxDay = atomicOption(maxDayAtomic, "maxDayAtomic", { required: false });
77052
77067
  if (maxDayNext !== void 0 && (typeof maxDayNext !== "string" || !maxDayNext)) invalid2("maxDayNext must be a non-empty text");
77053
77068
  const dayNext = maxDayNext ?? "wait until older payments leave the 24-hour window, or raise your limit for any 24 hours and start again";
@@ -77067,13 +77082,15 @@ function createSpendPolicy({
77067
77082
  let sessionSpent = 0n;
77068
77083
  let windowSpent;
77069
77084
  let grant;
77070
- const limits = Object.freeze({
77071
- maxPaymentAtomic: maxPayment.toString(),
77072
- ...maxSession !== void 0 ? { maxSessionAtomic: maxSession.toString() } : {},
77073
- ...maxDay !== void 0 ? { maxDayAtomic: maxDay.toString() } : {},
77074
- ...maxHostDay !== void 0 ? { maxPerHostDayAtomic: maxHostDay.toString() } : {},
77075
- ...allowed ? { allowHosts: Object.freeze([...allowed]) } : {}
77076
- });
77085
+ const limits = Object.freeze(Object.defineProperties({}, {
77086
+ maxPaymentAtomic: { get: () => paymentCap().toString(), enumerable: true },
77087
+ ...launchSession !== void 0 ? { maxSessionAtomic: { get: () => sessionCap().toString(), enumerable: true } } : {},
77088
+ ...Object.getOwnPropertyDescriptors({
77089
+ ...maxDay !== void 0 ? { maxDayAtomic: maxDay.toString() } : {},
77090
+ ...maxHostDay !== void 0 ? { maxPerHostDayAtomic: maxHostDay.toString() } : {},
77091
+ ...allowed ? { allowHosts: Object.freeze([...allowed]) } : {}
77092
+ })
77093
+ }));
77077
77094
  function liveGrant() {
77078
77095
  if (grant !== void 0 && now() >= grant.untilMs) grant = void 0;
77079
77096
  return grant;
@@ -77099,6 +77116,7 @@ function createSpendPolicy({
77099
77116
  return POSITIVE_ATOMIC2.test(amountText2) && BigInt(amountText2) <= live.amount;
77100
77117
  }
77101
77118
  function resolvePaymentCap(argument2, { requestId } = {}) {
77119
+ const maxPayment = paymentCap();
77102
77120
  if (argument2 === void 0 || argument2 === null) return { ok: true, maxPaymentAtomic: maxPayment.toString() };
77103
77121
  const text3 = typeof argument2 === "bigint" ? argument2.toString() : String(argument2);
77104
77122
  if (!POSITIVE_ATOMIC2.test(text3)) {
@@ -77135,6 +77153,7 @@ function createSpendPolicy({
77135
77153
  return spendHost(url)?.host === live.host ? live.amount.toString() : void 0;
77136
77154
  }
77137
77155
  function checkWith({ store, url, amountAtomic, requestId } = {}, covered) {
77156
+ const maxPayment = paymentCap();
77138
77157
  const hosts = spendHost(url);
77139
77158
  if (!hosts) return refusal("spend_policy_invalid", "the URL has no host", "pass an absolute http(s) URL");
77140
77159
  const amountText2 = typeof amountAtomic === "bigint" ? amountAtomic.toString() : String(amountAtomic ?? "");
@@ -77183,6 +77202,7 @@ function createSpendPolicy({
77183
77202
  return { ok: true };
77184
77203
  }
77185
77204
  function checkWindow({ store, amountAtomic, requestId } = {}) {
77205
+ const maxSession = sessionCap();
77186
77206
  if (maxSession === void 0 && maxDay === void 0) return { ok: true };
77187
77207
  const amount = BigInt(typeof amountAtomic === "bigint" ? amountAtomic : String(amountAtomic));
77188
77208
  if (maxDay !== void 0 && store !== void 0 && store !== null) {
@@ -77209,10 +77229,18 @@ function createSpendPolicy({
77209
77229
  `restart with a higher --max-session to pay more (JS: a new createSpendPolicy with a higher maxSessionAtomic)`
77210
77230
  );
77211
77231
  }
77232
+ let follows = false;
77233
+ if (limitsNow !== void 0) {
77234
+ try {
77235
+ follows = limitsNow()?.maxSessionAtomic !== void 0;
77236
+ } catch {
77237
+ follows = false;
77238
+ }
77239
+ }
77212
77240
  return refusal(
77213
77241
  "mcp_session_cap_exceeded",
77214
77242
  `this wallet paid ${usdcWords(spent)} in the last 24 hours (payments not finished included${counted.fromUpgrade ? "; payments with no recorded time, made before this wallet version, count for 24 hours from the upgrade" : ""}) and its limit is ${usdcWords(maxSession)} in any 24 hours; a ${usdcWords(amount)} payment would pass it; nothing was paid`,
77215
- `wait until older payments leave the 24-hour window, or raise the limit for any 24 hours: run ${agentCommandLine("limits")} in a terminal (a limit typed in this app's wallet entry is changed in that entry instead), then restart the app`,
77243
+ `wait until older payments leave the 24-hour window, or raise the limit for any 24 hours: run ${agentCommandLine("limits")} in a terminal ` + (follows ? "(it counts at once)" : "(a limit typed in this app's wallet entry is changed in that entry instead), then restart the app"),
77216
77244
  { totalAtomic: (spent + amount).toString(), capAtomic: maxSession.toString() }
77217
77245
  );
77218
77246
  }
@@ -77254,6 +77282,7 @@ function createSpendPolicy({
77254
77282
  return (windowSpent ?? sessionSpent).toString();
77255
77283
  },
77256
77284
  get sessionLeftAtomic() {
77285
+ const maxSession = sessionCap();
77257
77286
  if (maxSession === void 0) return void 0;
77258
77287
  const left = maxSession - (windowSpent ?? sessionSpent);
77259
77288
  return (left > 0n ? left : 0n).toString();
@@ -78515,7 +78544,7 @@ function ecdsa(Point, hash12, ecdsaOpts = {}) {
78515
78544
  bits2int: "function",
78516
78545
  bits2int_modN: "function"
78517
78546
  });
78518
- const randomBytes30 = ecdsaOpts.randomBytes || randomBytes3;
78547
+ const randomBytes31 = ecdsaOpts.randomBytes || randomBytes3;
78519
78548
  const hmac4 = ecdsaOpts.hmac || ((key, ...msgs) => hmac3(hash12, key, concatBytes3(...msgs)));
78520
78549
  const { Fp: Fp2, Fn: Fn2 } = Point;
78521
78550
  const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn2;
@@ -78670,7 +78699,7 @@ function ecdsa(Point, hash12, ecdsaOpts = {}) {
78670
78699
  const d = _normFnElement(Fn2, privateKey);
78671
78700
  const seedArgs = [int2octets(d), int2octets(h1int)];
78672
78701
  if (extraEntropy != null && extraEntropy !== false) {
78673
- const e14 = extraEntropy === true ? randomBytes30(lengths.secretKey) : extraEntropy;
78702
+ const e14 = extraEntropy === true ? randomBytes31(lengths.secretKey) : extraEntropy;
78674
78703
  seedArgs.push(ensureBytes("extraEntropy", e14));
78675
78704
  }
78676
78705
  const seed = concatBytes3(...seedArgs);
@@ -104392,6 +104421,32 @@ function partMayHaveSigned(store, part) {
104392
104421
  if (!payment) return false;
104393
104422
  return !(payment.state === "cancelled" || payment.state === "receipt" && payment.receiptFinality === "never-finalized");
104394
104423
  }
104424
+ function plannedPartIds(store) {
104425
+ const ids = /* @__PURE__ */ new Set();
104426
+ for (const name of store.listWal()) {
104427
+ if (!name.startsWith(PRIVATE_SEND_WAL_PREFIX)) continue;
104428
+ try {
104429
+ const plan = store.readWal(name);
104430
+ if (Array.isArray(plan?.parts)) for (const part of plan.parts) ids.add(String(part?.unshieldId));
104431
+ } catch {
104432
+ }
104433
+ }
104434
+ return ids;
104435
+ }
104436
+ function terminalSendResumable(store, unshieldId, record, partIds) {
104437
+ if (unshieldId.startsWith("merge-") || /^pocket-\d+-f\d+$/.test(unshieldId) || partIds.has(unshieldId)) return false;
104438
+ if (record?.schema !== SELF_PAY_WAL_SCHEMA || !/^[1-9][0-9]*$/.test(String(record.amountAtomic ?? "")) || record.mcpTo !== void 0) return false;
104439
+ const direct = record.mode === DIRECT_EXIT_MODE;
104440
+ if (!direct && (record.mode !== void 0 || record.ownerUnshield !== true)) return false;
104441
+ if (directExitGone(record) || record.directExitCancelled === true) return false;
104442
+ if (record.state === "paid") return true;
104443
+ if (record.state !== "started") return false;
104444
+ try {
104445
+ return partMayHaveSigned(store, { unshieldId }) || direct && directExitMayHaveSent(store, record);
104446
+ } catch {
104447
+ return false;
104448
+ }
104449
+ }
104395
104450
  function privateSendPendingAtomic(store) {
104396
104451
  const unsent = unsentParts(store);
104397
104452
  return unsent === null ? null : unsent.reduce((sum2, { part }) => sum2 + BigInt(part.amountAtomic), 0n);
@@ -107660,9 +107715,15 @@ function capFlagFromLaunchLine(flag3, argv2 = process.argv) {
107660
107715
  if (at < 0) return false;
107661
107716
  return argv2.slice(at + 1).some((arg) => arg === flag3 || arg.startsWith(`${flag3}=`));
107662
107717
  }
107718
+ function setLimitsFollowConfig(on) {
107719
+ limitsFollowConfig = on === true;
107720
+ }
107721
+ var limitsFollowConfig, capCountsNow;
107663
107722
  var init_launchCaps = __esm({
107664
107723
  "wallet/src/caps/launchCaps.mjs"() {
107665
107724
  "use strict";
107725
+ limitsFollowConfig = false;
107726
+ capCountsNow = (flag3, argv2 = process.argv) => limitsFollowConfig && (flag3 === "--max-payment" || flag3 === "--max-session") && !capFlagFromLaunchLine(flag3, argv2);
107666
107727
  }
107667
107728
  });
107668
107729
 
@@ -109095,6 +109156,10 @@ var init_say = __esm({
109095
109156
  const lines = capFlagFromLaunchLine(flag3) ? [
109096
109157
  "Only you can raise this limit, in this app's wallet entry; then reconnect the wallet.",
109097
109158
  "Only you can raise it, in this app's wallet entry."
109159
+ ] : capCountsNow(flag3) ? [
109160
+ `Change it: run ${agentCommandLine("limits", { npmVersion })} in a terminal; it counts at once.`,
109161
+ "Change it with the limits command in a terminal; it counts at once.",
109162
+ "Change it with the limits command; it counts at once."
109098
109163
  ] : [
109099
109164
  `Change it: run ${agentCommandLine("limits", { npmVersion })} in a terminal, then restart this app.`,
109100
109165
  "Change it with the limits command in a terminal, then restart this app.",
@@ -111753,6 +111818,7 @@ var init_publicRead = __esm({
111753
111818
  });
111754
111819
 
111755
111820
  // wallet/src/unshield/cli.mjs
111821
+ import { randomBytes as randomBytes19 } from "node:crypto";
111756
111822
  import { resolve as resolve18 } from "node:path";
111757
111823
  import { fileURLToPath as fileURLToPath12 } from "node:url";
111758
111824
  function facilitatorAnchor(origin, fetchImpl = fetch, { sleep: sleep4 = (ms) => new Promise((resolve35) => setTimeout(resolve35, ms)) } = {}) {
@@ -112056,6 +112122,25 @@ async function unshieldOnce({
112056
112122
  mark("unshield-lease-self-pay");
112057
112123
  const stop3 = before(store);
112058
112124
  if (stop3 !== void 0) return { stop: stop3 };
112125
+ if (typeof onAnswered === "function") {
112126
+ const name2 = `self-pay-${unshieldId}`;
112127
+ const record = store.readWal(name2);
112128
+ const sendTo = { sendTo: recipientOwner.toBase58(), sendToAccount: options.to };
112129
+ if (!record) {
112130
+ store.writeWal(name2, {
112131
+ schema: SELF_PAY_WAL_SCHEMA,
112132
+ state: "started",
112133
+ amountAtomic: String(amountAtomic),
112134
+ ownerUnshield: true,
112135
+ signingKey: `0x${randomBytes19(32).toString("hex")}`,
112136
+ encryptionKey: randomBytes19(32).toString("hex"),
112137
+ createdAtMs: Date.now(),
112138
+ ...sendTo
112139
+ });
112140
+ } else if (record.sendTo === void 0 && record.mcpTo === void 0 && record.mode === void 0) {
112141
+ store.writeWal(name2, { ...record, ...sendTo });
112142
+ }
112143
+ }
112059
112144
  mark("unshield-self-pay");
112060
112145
  const paid2 = await selfPay({
112061
112146
  store,
@@ -112081,11 +112166,6 @@ async function unshieldOnce({
112081
112166
  });
112082
112167
  const payment = store.readWal(`resource-payment-${sha256Hex2(Buffer.from(selfPayRequestId(unshieldId), "utf8"))}`);
112083
112168
  if (!payment?.memoDigest || !paid2.noteCommitment) fail31("self_pay_record_incomplete");
112084
- if (typeof onAnswered === "function") {
112085
- const name2 = `self-pay-${unshieldId}`;
112086
- const record = store.readWal(name2);
112087
- if (record && record.sendTo === void 0) store.writeWal(name2, { ...record, sendTo: recipientOwner.toBase58(), sendToAccount: options.to });
112088
- }
112089
112169
  mark("unshield-paid");
112090
112170
  return { paid: paid2, memoDigest: payment.memoDigest, pool: store.state.pool };
112091
112171
  });
@@ -113782,7 +113862,7 @@ var init_autoPockets = __esm({
113782
113862
 
113783
113863
  // wallet/src/move/job.mjs
113784
113864
  import { fileURLToPath as fileURLToPath14 } from "node:url";
113785
- import { randomBytes as randomBytes19 } from "node:crypto";
113865
+ import { randomBytes as randomBytes20 } from "node:crypto";
113786
113866
  function moveLegs(store, fromPool) {
113787
113867
  const prefix = moveWalPrefix(fromPool);
113788
113868
  const legs = [];
@@ -113903,7 +113983,7 @@ function walletEta2(store) {
113903
113983
  return deriveWalletViewingAuthority2({ seedBytes: Uint8Array.from(Buffer.from(store.state.seedHex, "hex")), generator: generator2 }).eta;
113904
113984
  }
113905
113985
  function ownTargetAddress(eta, poolDomain) {
113906
- return deriveShieldedSolanaP03Recipient({ eta, poolDomain: BigInt(poolDomain), resourceNonce: randomBytes19(32) }).payTo;
113986
+ return deriveShieldedSolanaP03Recipient({ eta, poolDomain: BigInt(poolDomain), resourceNonce: randomBytes20(32) }).payTo;
113907
113987
  }
113908
113988
  async function refreshPool({ store, connection, historyUrl, programId, serviceUrl: serviceUrl2, proofTools, deps = {} }) {
113909
113989
  const walStates = captureWalStates(store);
@@ -117464,7 +117544,7 @@ var init_adoptOneTime = __esm({
117464
117544
  });
117465
117545
 
117466
117546
  // wallet/src/mcp/requestIds.mjs
117467
- import { randomBytes as randomBytes20 } from "node:crypto";
117547
+ import { randomBytes as randomBytes21 } from "node:crypto";
117468
117548
  function recordId(id) {
117469
117549
  if (typeof id !== "string" || !REQUEST_ID2.test(id)) {
117470
117550
  throw new Error("mcp_argument_invalid: request_id must be 1-128 characters of A-Z a-z 0-9 . _ : -");
@@ -117476,7 +117556,7 @@ function reservedId(id) {
117476
117556
  return typeof id === "string" && RESERVED_ID.test(id);
117477
117557
  }
117478
117558
  function newAutoId() {
117479
- return `auto-${randomBytes20(6).toString("hex")}`;
117559
+ return `auto-${randomBytes21(6).toString("hex")}`;
117480
117560
  }
117481
117561
  function atomicText(value2, name) {
117482
117562
  const text3 = typeof value2 === "bigint" ? value2.toString() : typeof value2 === "number" && Number.isSafeInteger(value2) ? String(value2) : value2;
@@ -122177,7 +122257,7 @@ var init_qr = __esm({
122177
122257
 
122178
122258
  // wallet/src/mcp/addFunds.mjs
122179
122259
  import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
122180
- import { randomBytes as randomBytes21 } from "node:crypto";
122260
+ import { randomBytes as randomBytes22 } from "node:crypto";
122181
122261
  import diagnosticsChannel2 from "node:diagnostics_channel";
122182
122262
  function onRequestCreate(message) {
122183
122263
  try {
@@ -122225,7 +122305,7 @@ function createAddFundsTool({
122225
122305
  offStep = () => ({ step: "Run setup again in a terminal, then reconnect the wallet", extra: {} }),
122226
122306
  log = () => {
122227
122307
  },
122228
- randomId = () => randomBytes21(6).toString("hex"),
122308
+ randomId = () => randomBytes22(6).toString("hex"),
122229
122309
  wake,
122230
122310
  timing
122231
122311
  } = {}) {
@@ -122628,7 +122708,7 @@ var init_addFunds = __esm({
122628
122708
  });
122629
122709
 
122630
122710
  // wallet/src/mcp/earlyAnswer.mjs
122631
- import { randomBytes as randomBytes22 } from "node:crypto";
122711
+ import { randomBytes as randomBytes23 } from "node:crypto";
122632
122712
  function argsKey(args) {
122633
122713
  const sorted2 = (value2) => Array.isArray(value2) ? value2.map(sorted2) : value2 !== null && typeof value2 === "object" ? Object.fromEntries(Object.keys(value2).sort().map((key) => [key, sorted2(value2[key])])) : value2;
122634
122714
  const { request_id: _id, ...rest } = args;
@@ -122667,7 +122747,7 @@ function withEarlyAnswer(tool, {
122667
122747
  if (given && (typeof args.request_id !== "string" || !REQUEST_ID3.test(args.request_id))) return tool.run(args, ...rest);
122668
122748
  const shareKey = given ? void 0 : autoKey(args);
122669
122749
  const shared2 = shareKey === void 0 ? void 0 : autoRunning.get(shareKey);
122670
- const requestId = given ? args.request_id : shared2 !== void 0 && payments.get(shared2)?.done === false ? shared2 : `mcp-${randomBytes22(8).toString("hex")}`;
122750
+ const requestId = given ? args.request_id : shared2 !== void 0 && payments.get(shared2)?.done === false ? shared2 : `mcp-${randomBytes23(8).toString("hex")}`;
122671
122751
  let entry = payments.get(requestId);
122672
122752
  if (!entry && given) {
122673
122753
  const key = sameRequest(args);
@@ -126816,7 +126896,7 @@ var init_jupiter = __esm({
126816
126896
  });
126817
126897
 
126818
126898
  // wallet/src/mcp/tools.mjs
126819
- import { randomBytes as randomBytes23, randomInt as randomInt6 } from "node:crypto";
126899
+ import { randomBytes as randomBytes24, randomInt as randomInt6 } from "node:crypto";
126820
126900
  import { basename as basename5, dirname as dirname27, join as join30 } from "node:path";
126821
126901
  import { fileURLToPath as fileURLToPath16 } from "node:url";
126822
126902
  async function readReleasePoolsTwice(args) {
@@ -127526,8 +127606,8 @@ function bindUnshieldRecipient(store, unshieldId, amountAtomic, to, requestId) {
127526
127606
  schema: SELF_PAY_WAL_SCHEMA,
127527
127607
  state: "started",
127528
127608
  amountAtomic: String(amountAtomic),
127529
- signingKey: `0x${randomBytes23(32).toString("hex")}`,
127530
- encryptionKey: randomBytes23(32).toString("hex"),
127609
+ signingKey: `0x${randomBytes24(32).toString("hex")}`,
127610
+ encryptionKey: randomBytes24(32).toString("hex"),
127531
127611
  mcpTo: to,
127532
127612
  createdAtMs: Date.now(),
127533
127613
  // the send's start, set once (real-user pass E4: the row time moved with each write)
@@ -128012,8 +128092,8 @@ async function directExitUnshield({
128012
128092
  },
128013
128093
  timing = () => void 0,
128014
128094
  onAnswered,
128015
- // A direct exit's record is not one the next unshield finishes (cli.mjs finishAnsweredUnshields: self-pay records only).
128016
- onCheckPending = () => progress(sentNotRecordedLine(unshieldId, { nextFinishes: false }))
128095
+ // UX130-10: the next plain unshield finishes a single direct exit too (shinjukuWallet.mjs resumeOpenUnshields).
128096
+ onCheckPending = () => progress(sentNotRecordedLine(unshieldId))
128017
128097
  }) {
128018
128098
  const name = `self-pay-${unshieldId}`;
128019
128099
  let selfPays = false;
@@ -128039,9 +128119,21 @@ async function directExitUnshield({
128039
128119
  selfPays = true;
128040
128120
  return null;
128041
128121
  },
128042
- // runUnshield chooses only for a record that exists (wallet_unshield binds one first); this one is bound to no recipient.
128122
+ // runUnshield chooses only for a record that exists (wallet_unshield binds one first); this one is bound to no agent
128123
+ // recipient. UX130-10: a single send (onAnswered; a part of an older send in parts passes none) keeps its wallet address
128124
+ // before anything can be signed, as cli.mjs unshieldOnce does for a self-payment, so the next plain unshield finishes it
128125
+ // (the record's exitRecipient is the token account, which does not name the address).
128126
+ // A direct exit an older version started keeps none: it gets this run's address only when that address's USDC account is
128127
+ // the one the exit is bound to (runDirectExit refuses any other, with nothing signed).
128043
128128
  prepare: (store) => {
128044
- if (!store.readWal(name)) bindUnshieldRecipient(store, unshieldId, amountAtomic, void 0);
128129
+ const sendTo = { sendTo: recipientOwner, sendToAccount: recipientTokenAccount };
128130
+ const record = store.readWal(name);
128131
+ if (!record) {
128132
+ bindUnshieldRecipient(store, unshieldId, amountAtomic, void 0);
128133
+ if (typeof onAnswered === "function") store.writeWal(name, { ...store.readWal(name), ...sendTo });
128134
+ } else if (typeof onAnswered === "function" && record.mode === DIRECT_EXIT_MODE && record.mcpTo === void 0 && record.sendTo === void 0 && record.exitRecipient === getAssociatedTokenAddressSync(new import_web3133.PublicKey(store.state.asset), new import_web3133.PublicKey(recipientOwner), true, TOKEN_PROGRAM_ID).toBase58()) {
128135
+ store.writeWal(name, { ...record, ...sendTo });
128136
+ }
128045
128137
  return store;
128046
128138
  },
128047
128139
  // Never reached (`before` stops every self-pay case): the terminal's own self-payment runs that path.
@@ -129356,7 +129448,7 @@ function createWalletTools({
129356
129448
  const pay = {
129357
129449
  name: "x402_pay",
129358
129450
  title: "Pay a URL from the private balance",
129359
- description: `Use this when the user says "pay this URL", "buy this", or "fetch this paid API": it pays a paid URL (a paid web service) from the PRIVATE balance (privately: the chain does not show which wallet paid) and returns the paid answer. No preview is needed. It fetches the URL; when the URL answers HTTP 402, it pays the SELLER's price and returns the answer. Pass max_payment (USDC, like "0.05") to cap this call (max_payment_atomic is the same in atomic units). The wallet pays at most the per-payment limit set at start (by setup or this app's wallet entry); max_payment can LOWER it. When max_payment or a price is above that limit and this app can ask the user, the wallet asks the user once to allow this one payment; else the answer says the price and the limit. The 24-hour payment limit bounds what this wallet pays in any 24 hours, from every app that runs it. A free URL is fetched and nothing is paid. When the local balance is stale (for example right after wallet_shield), it first reads the chain by itself. A seller that takes only hidden-amount payments is refused with the error code confidential_retired: those payments are retired, and nothing is paid. Never claim a payment happened unless the answer has a transaction. On an error code that ends in _retry_same_request, call x402_pay again with the SAME request_id and the same url/method/headers/body: it never pays twice. A seller that takes only a standard USDC payment (Coinbase CDP, PayAI, ...) is paid through Shinjuku: the wallet pays Shinjuku privately (priceAtomic + feeAtomic = amountAtomic) and Shinjuku pays the seller; max_payment must cover the total. If Shinjuku proved that seller can no longer get the payment, the answer is p03_float_refund_pending with paid: true and refunding: true: the refund (refundAtomic) comes back by itself (refundEtaSeconds: Shinjuku's time, when it gave one); nothing more to do. An answer with ambiguous: true is not certain yet (the seller may have kept it): wallet_receipts shows which. Every answer starts with say (one plain line for the user) and carries balanceAtomic, what a payment can spend now (breakdown names refunds and each refund's request_id; usdc shows amounts in USDC). A seller still working 25 s after the payment started (it already holds the payment) gets stage seller_working with the request_id: call x402_pay again with that SAME request_id for its answer (that call waits up to ${EARLY_ANSWER_MS / 1e3} s for it); it never pays twice. ` + SELLER_ONLY_HERE,
129451
+ description: `Use this when the user says "pay this URL", "buy this", or "fetch this paid API": it pays a paid URL (a paid web service) from the PRIVATE balance (privately: the chain does not show which wallet paid) and returns the paid answer. No preview is needed. It fetches the URL; when the URL answers HTTP 402, it pays the SELLER's price and returns the answer. Pass max_payment (USDC, like "0.05") to cap this call (max_payment_atomic is the same in atomic units). The wallet pays at most the per-payment limit (the user's limits, or this app's wallet entry); max_payment can LOWER it. When max_payment or a price is above that limit and this app can ask the user, the wallet asks the user once to allow this one payment; else the answer says the price and the limit. The 24-hour payment limit bounds what this wallet pays in any 24 hours, from every app that runs it. A free URL is fetched and nothing is paid. When the local balance is stale (for example right after wallet_shield), it first reads the chain by itself. A seller that takes only hidden-amount payments is refused with the error code confidential_retired: those payments are retired, and nothing is paid. Never claim a payment happened unless the answer has a transaction. On an error code that ends in _retry_same_request, call x402_pay again with the SAME request_id and the same url/method/headers/body: it never pays twice. A seller that takes only a standard USDC payment (Coinbase CDP, PayAI, ...) is paid through Shinjuku: the wallet pays Shinjuku privately (priceAtomic + feeAtomic = amountAtomic) and Shinjuku pays the seller; max_payment must cover the total. If Shinjuku proved that seller can no longer get the payment, the answer is p03_float_refund_pending with paid: true and refunding: true: the refund (refundAtomic) comes back by itself (refundEtaSeconds: Shinjuku's time, when it gave one); nothing more to do. An answer with ambiguous: true is not certain yet (the seller may have kept it): wallet_receipts shows which. Every answer starts with say (one plain line for the user) and carries balanceAtomic, what a payment can spend now (breakdown names refunds and each refund's request_id; usdc shows amounts in USDC). A seller still working 25 s after the payment started (it already holds the payment) gets stage seller_working with the request_id: call x402_pay again with that SAME request_id for its answer (that call waits up to ${EARLY_ANSWER_MS / 1e3} s for it); it never pays twice. ` + SELLER_ONLY_HERE,
129360
129452
  inputSchema: {
129361
129453
  type: "object",
129362
129454
  properties: {
@@ -129385,7 +129477,7 @@ function createWalletTools({
129385
129477
  if (notUsdc) return refuse12(...notUsdc);
129386
129478
  const argument2 = capArg.atomic;
129387
129479
  const given = args.request_id !== void 0 && args.request_id !== null && args._autoRequestId !== true;
129388
- const requestId = args.request_id !== void 0 && args.request_id !== null ? args.request_id : `mcp-${randomBytes23(8).toString("hex")}`;
129480
+ const requestId = args.request_id !== void 0 && args.request_id !== null ? args.request_id : `mcp-${randomBytes24(8).toString("hex")}`;
129389
129481
  if (typeof requestId !== "string" || !REQUEST_ID4.test(requestId)) {
129390
129482
  return refuse12("mcp_argument_invalid", "request_id must be 1-128 characters of A-Z a-z 0-9 . _ : -", "leave request_id out for a new payment");
129391
129483
  }
@@ -131313,7 +131405,7 @@ ${canonical5}`;
131313
131405
  const sessionLeft = sessionLeftShown(policy, countStore);
131314
131406
  const setLimits = [["--max-payment", "per-payment limit", policy.limits.maxPaymentAtomic], ["--max-session", "24-hour limit", policy.limits.maxSessionAtomic]].filter(([, , atomic4]) => !noLimit(atomic4));
131315
131407
  const fromYourLimits = setLimits.some(([flag3]) => !capFlagFromLaunchLine(flag3));
131316
- const sessionSummary = setLimits.length === 0 ? void 0 : `Spending limits: ${payCapFlag(policy.limits.maxPaymentAtomic) === "--max-session" ? "one payment can use all of the 24-hour limit, which is " : `${capWords(policy.limits.maxPaymentAtomic)} per payment and `}${capWords(policy.limits.maxSessionAtomic)} in any 24 hours, for this wallet (every app that runs this wallet counts; a pool upgrade starts a new 24-hour count)${sessionLeft === null ? "" : ` (${usdcText3(sessionLeft)} USDC left now)`}; ${usdcText3(policy.sessionSpentAtomic) ?? "0"} USDC paid in the last 24 hours. ` + setLimits.map(([flag3, limitName]) => `The ${limitName} comes from ${capPlaceWords(flag3)}. `).join("") + (setLimits.some(([flag3]) => capFlagFromLaunchLine(flag3)) ? "A limit set in this app's wallet entry: only the user can change it there (in USDC, like 0.05), then reconnect the wallet. " : "") + `To ${fromYourLimits ? "change a limit from your limits, or set another" : "set another limit"}, the user runs ${terminalCommand2("limits")} in a terminal (it asks each limit: one payment, 24 hours, all payments together), then restarts the host`;
131408
+ const sessionSummary = setLimits.length === 0 ? void 0 : `Spending limits: ${payCapFlag(policy.limits.maxPaymentAtomic) === "--max-session" ? "one payment can use all of the 24-hour limit, which is " : `${capWords(policy.limits.maxPaymentAtomic)} per payment and `}${capWords(policy.limits.maxSessionAtomic)} in any 24 hours, for this wallet (every app that runs this wallet counts; a pool upgrade starts a new 24-hour count)${sessionLeft === null ? "" : ` (${usdcText3(sessionLeft)} USDC left now)`}; ${usdcText3(policy.sessionSpentAtomic) ?? "0"} USDC paid in the last 24 hours. ` + setLimits.map(([flag3, limitName]) => `The ${limitName} comes from ${capPlaceWords(flag3)}. `).join("") + (setLimits.some(([flag3]) => capFlagFromLaunchLine(flag3)) ? "A limit set in this app's wallet entry: only the user can change it there (in USDC, like 0.05), then reconnect the wallet. " : "") + `To ${fromYourLimits ? "change a limit from your limits, or set another" : "set another limit"}, the user runs ${terminalCommand2("limits")} in a terminal (it asks each limit: one payment, 24 hours, all payments together)${["--max-payment", "--max-session"].every((flag3) => capCountsNow(flag3)) ? "; it counts at once" : ", then restarts the host"}`;
131317
131409
  if (setLimits.length === 0) next = `${next}. No spending limit is set; when the user asks about one, tell the user: ${noLimitSetLine()}`;
131318
131410
  return json3({
131319
131411
  ok: true,
@@ -131971,15 +132063,8 @@ ${canonical5}`;
131971
132063
  ...done ? {} : { next: "made by the shinjuku add-funds command, not finished; `shinjuku funds-status` in a terminal shows its stage" }
131972
132064
  });
131973
132065
  }
131974
- const planPrefix = privateSendPlanName("");
131975
- const planPartIds = new Set(names.filter((name) => name.startsWith(planPrefix)).flatMap((name) => {
131976
- try {
131977
- const plan = store.readWal(name);
131978
- return Array.isArray(plan?.parts) ? plan.parts.map((part) => String(part?.unshieldId)) : [];
131979
- } catch {
131980
- return [];
131981
- }
131982
- }));
132066
+ const partIds = plannedPartIds(store);
132067
+ const ownSend = "a send this wallet started itself, in a terminal on this computer (the shinjuku unshield command); it did not finish. In a terminal, run ";
131983
132068
  for (const name of names) {
131984
132069
  if (!name.startsWith("self-pay-") || name.startsWith("self-pay-mcp-") || name.startsWith("self-pay-merge-") || /^self-pay-pocket-\d+-f\d+$/.test(name)) continue;
131985
132070
  let record;
@@ -132002,7 +132087,6 @@ ${canonical5}`;
132002
132087
  const state = record.state === "exited" ? "sent" : gone ? "not_sent" : signed ? "not_finished" : record.state === "started" ? otherWorker === false ? "not_sent" : "not_known" : void 0;
132003
132088
  if (state === void 0) continue;
132004
132089
  const at = Number.isSafeInteger(sentAtMs(record)) ? sentAtMs(record) : record.state !== "exited" && Number.isSafeInteger(record.createdAtMs) ? record.createdAtMs : walTimeMs(store, name);
132005
- const resumable = record.state === "paid" && record.mode === void 0 && !planPartIds.has(unshieldId);
132006
132090
  rows2.push({
132007
132091
  kind: "unshield",
132008
132092
  via: "cli",
@@ -132011,8 +132095,8 @@ ${canonical5}`;
132011
132095
  transaction: sigOrNull(record.exitTransaction),
132012
132096
  at,
132013
132097
  ...state === "not_sent" ? { reason: refusedReason(record), next: "nothing was sent; nothing to do" } : {},
132014
- ...state === "not_finished" ? { unshieldId, next: resumable ? "made by the shinjuku unshield command, not finished; in a terminal, run shinjuku unshield all to finish it (it never sends twice)" : `made by the shinjuku unshield command, not finished; in a terminal, run shinjuku unshield --amount all --to <the address it was sent to> --unshield-id ${unshieldId} to finish it (it never sends twice)` } : {},
132015
- ...state === "not_known" ? { next: "not known yet: another wallet process is working now, and nothing of this send is signed; call wallet_receipts again in a minute" } : {}
132098
+ ...state === "not_finished" ? { unshieldId, next: terminalSendResumable(store, unshieldId, record, partIds) ? `${ownSend}shinjuku unshield all to finish it (it never sends twice)` : `${ownSend}shinjuku unshield --amount all --to <the address it was sent to> --unshield-id ${unshieldId} to finish it (it never sends twice)` } : {},
132099
+ ...state === "not_known" ? { next: "not known yet: another process of this same wallet on this computer (a terminal command or an agent app) is working now, and nothing of this send is signed; call wallet_receipts again in a minute" } : {}
132016
132100
  });
132017
132101
  }
132018
132102
  for (const note of receivedNotes(store)) rows2.push({ kind: "received", amountAtomic: String(note.valueAtomic), state: "done", at: -1 });
@@ -132021,7 +132105,7 @@ ${canonical5}`;
132021
132105
  const receipts = {
132022
132106
  name: "wallet_receipts",
132023
132107
  title: "List recent receipts and wallet moves",
132024
- description: `List this wallet's most recent receipts, newest first. Payments (kind x402 or inference): seller (the URL paid), sellerHost, item (what was bought), priceAtomic, feeAtomic, amountAtomic (the total), sellerTransaction, privateTransaction (this wallet's private payment), facilitator, answeredAt, and transaction / host (the seller's when known). pay.shinjukustaition.com is Shinjuku, the private payment service, never the seller. A payment the seller did not take shows state refund_pending (the refund is on its way; floatId, refundState: Shinjuku's refund step in words), refund_sent once Shinjuku sent it (refundTransaction; the balance counts it at a later read), then refunded once the balance holds it. A payment the seller has not served yet shows waiting_for_seller (or seller_paid_not_served once the transfer to the seller landed): call x402_pay again with its requestId to get it. seller_refused (the seller refused it, sellerStatus) or outcome_not_certain (an earlier send got no clear answer): not certain yet whether the seller kept the payment; do not pay again until the row changes. never_landed: the payment never went through; nothing was paid and nothing comes back. The wallet's own moves (kind shield, add-funds, unshield, private-send, token-transfer, or an older deposit kind): requestId, amountAtomic, state, transaction, at; a private-send row with smaller payments still to go shows partsAt (the time and state of each) and next (it is not stuck); a token-transfer row (wallet_transfer_token) shows tokenMint, tokenAmountAtomic, usdcAtomic (what the sell gave) and sentAtomic; an add-funds row also shows heldAtomic, the USDC waiting at its address (it becomes private by itself: never close an address that holds USDC; belowMinimum: less than minimumAtomic waits there for a top-up). An add-funds row with via "cli" was made by the shinjuku add-funds command in a terminal: amountAtomic, state (done or not_finished), transaction; it has no requestId, and wallet_add_funds never continues it. An unshield row with via "cli" was made by the shinjuku unshield command: amountAtomic, state (sent, not_finished, not_sent), transaction, and next (with unshieldId, the terminal's own id) when it is not finished; it has no requestId, and wallet_unshield never continues it. A received payment (kind received, a move): amountAtomic and state done; at is null and it sorts last (no sender, no time). requestId is shown for payments made by this wallet process; older ones show requestKey (its SHA-256). kind "payments" or "moves" lists one group only.`,
132108
+ description: `List this wallet's most recent receipts, newest first. Payments (kind x402 or inference): seller (the URL paid), sellerHost, item (what was bought), priceAtomic, feeAtomic, amountAtomic (the total), sellerTransaction, privateTransaction (this wallet's private payment), facilitator, answeredAt, and transaction / host (the seller's when known). pay.shinjukustaition.com is Shinjuku, the private payment service, never the seller. A payment the seller did not take shows state refund_pending (the refund is on its way; floatId, refundState: Shinjuku's refund step in words), refund_sent once Shinjuku sent it (refundTransaction; the balance counts it at a later read), then refunded once the balance holds it. A payment the seller has not served yet shows waiting_for_seller (or seller_paid_not_served once the transfer to the seller landed): call x402_pay again with its requestId to get it. seller_refused (the seller refused it, sellerStatus) or outcome_not_certain (an earlier send got no clear answer): not certain yet whether the seller kept the payment; do not pay again until the row changes. never_landed: the payment never went through; nothing was paid and nothing comes back. The wallet's own moves (kind shield, add-funds, unshield, private-send, token-transfer, or an older deposit kind): requestId, amountAtomic, state, transaction, at; a private-send row with smaller payments still to go shows partsAt (the time and state of each) and next (it is not stuck); a token-transfer row (wallet_transfer_token) shows tokenMint, tokenAmountAtomic, usdcAtomic (what the sell gave) and sentAtomic; an add-funds row also shows heldAtomic, the USDC waiting at its address (it becomes private by itself: never close an address that holds USDC; belowMinimum: less than minimumAtomic waits there for a top-up). An add-funds row with via "cli" was made by the shinjuku add-funds command in a terminal: amountAtomic, state (done or not_finished), transaction; it has no requestId, and wallet_add_funds never continues it. An unshield row with via "cli" is this wallet's own send, made by the shinjuku unshield command in a terminal: amountAtomic, state (sent, not_finished, not_sent), transaction, and next (with unshieldId, the terminal's own id) when it is not finished; it has no requestId, and wallet_unshield never continues it. A received payment (kind received, a move): amountAtomic and state done; at is null and it sorts last (no sender, no time). requestId is shown for payments made by this wallet process; older ones show requestKey (its SHA-256). kind "payments" or "moves" lists one group only.`,
132025
132109
  inputSchema: {
132026
132110
  type: "object",
132027
132111
  properties: {
@@ -133612,7 +133696,16 @@ ${canonical5}`;
133612
133696
  } catch {
133613
133697
  continue;
133614
133698
  }
133615
- if (record?.schema !== SELF_PAY_WAL_SCHEMA || record.state !== "paid" || record.mode !== void 0 || typeof record.mcpTo !== "string" || typeof record.exitTransaction === "string" || record.exitUnconfirmed === true || !ATOMIC_TEXT.test(String(record.amountAtomic ?? ""))) continue;
133699
+ if (record?.schema !== SELF_PAY_WAL_SCHEMA || ![void 0, DIRECT_EXIT_MODE].includes(record.mode) || typeof record.mcpTo !== "string" || typeof record.exitTransaction === "string" || record.exitUnconfirmed === true || !ATOMIC_TEXT.test(String(record.amountAtomic ?? "")) || directExitGone(record) || record.directExitCancelled === true) continue;
133700
+ let open4 = record.state === "paid";
133701
+ if (record.state === "started") {
133702
+ try {
133703
+ open4 = selfPayMayHaveSigned(store, name.slice("self-pay-".length));
133704
+ } catch {
133705
+ open4 = false;
133706
+ }
133707
+ }
133708
+ if (!open4) continue;
133616
133709
  return { requestId: shownId(record.mcpRequestId, rid), amountAtomic: String(record.amountAtomic), to: record.mcpTo };
133617
133710
  }
133618
133711
  return void 0;
@@ -135030,6 +135123,7 @@ ${canonical5}`;
135030
135123
  };
135031
135124
  const unshield = {
135032
135125
  name: "wallet_unshield",
135126
+ // UX130-13: a host that defers tools may show only the title: it says where a send goes by default.
135033
135127
  title: "Send USDC privately",
135034
135128
  description: `Use this when the user says "send 2 USDC to <address>" or "withdraw to my wallet" (for "my wallet" leave \`to\` out: it uses the address saved at setup, or says how to set one; never ask the user first): it sends amount (USDC, like "2"; or amount_atomic) from the PRIVATE balance as plain USDC to \`to\`, a public Solana address (it receives the USDC at that address). BEFORE you call it to send all of the balance when wallet_balance showed balanceParts above 1, write to the user that the wallet first gets the balance ready to send (do not tell the user how the wallet stores the balance; some apps show nothing until this call ends). Privately: the chain shows the pool paying the address, not which wallet paid. The wallet's own key (ownAddress in wallet_balance) is this wallet's public address: it holds the public USDC, wallet_shield deposits from it, and wallet_transfer_token sells from it. So it is refused as \`to\`: an exit there would show on chain that the private balance belongs to this wallet. This holds whether or not that key ever deposited: wallet_add_funds deposits come from one-time addresses, not from this key, so never tell the user the deposits came from it. Shinjuku pays every network fee; no SOL is needed. The user's saved own addresses (setup or this app's wallet entry) send at once. Any other address is sent only after the user confirms it in this app (a confirmation dialog); a client that cannot ask is refused (mcp_unshield_to_not_allowed) and a decline sends nothing (mcp_unshield_declined). \`to\` must already be able to receive USDC: an address that cannot is refused before any dialog (mcp_unshield_to_invalid). It runs in steps and may wait for the pool's next anchor: the call answers within about 20 s with stage (confirming, queued, refreshing, self-pay = preparing, exit = sending, done; joining = the wallet first gets the balance ready to send, then sends; each call goes on with it (joinSteps: its steps, one after another; doneInMinutesLow to doneInMinutesHigh: the time to say), ok: true); call wallet_unshield again with the SAME request_id, amount, and to for the status (each call answers within about 20 s, at once when the send ends; a confirmation dialog the user answers may take longer). When the wallet must first get the balance ready to send, the FIRST call answers at once with stage joining and joinTellFirst: true; write its say to the user, then call again with the same request_id at once. One exception: for a send whose balance must first be made ready, when this app sends a progress token with the call, that next call gets the balance ready and then sends, with a progress line every ${JOIN_STEP_MS / 1e3} s ("getting your balance ready to send"; some apps show none of them, so the line is said before the call, as above). It answers when the send is done, or after about ${joinAnswerSeconds(JOIN_CALL_MAX_MS)} s with how far it got (joinsDone; sendState sending: the USDC is leaving, never say nothing moved); then call again with the same request_id. Without a progress token it answers within about 20 s with stage joining: call again until it sends. The same request_id never sends twice, also after a restart. request_id is optional: without it the answer names the id it made, and the same call again within 10 minutes after it ends reads that same send. When it lands, the wallet writes an encrypted backup (backupPath). x402_pay calls wait while it runs. An optional limit the user sets (the unshield limit) may bound each call and what this wallet sends in any 24 hours, from every app that runs it (mcp_unshield_cap_exceeded: tell the user). Other refusals: mcp_argument_invalid, mcp_request_id_reused, mcp_unshield_to_invalid, wallet_locked, mcp_tool_disabled, mcp_unshield_failed, and the unshield's own p03_* codes. A send is one payment to \`to\`. ${HOST_BLOCKED_LINE}`,
135035
135129
  inputSchema: {
@@ -136459,8 +136553,11 @@ ${canonical5}`;
136459
136553
  }
136460
136554
  const transferToken = {
136461
136555
  name: "wallet_transfer_token",
136462
- title: "Sell a token and send the USDC privately",
136463
- description: `Use this when the user says "send my BONK to <address> privately" or "move this token to my other wallet with no link". It sells amount_atomic of token_mint from this wallet's own key (ownAddress in wallet_balance) for USDC through Jupiter, shields that USDC, and sends it to \`to\` in one private transfer. \`to\` RECEIVES USDC, NOT THE TOKEN: the swap back at \`to\` is not built yet; tell the user to swap at \`to\` themselves. token_mint is the token's base58 mint address, never a name or symbol (BONK is DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263); amount_atomic is in the token's own base units ("1250000" = 1.25 of a 6-decimal token). Cost: the user needs no SOL. Shinjuku pays the sale's network fee (and, when the own key has no USDC holder yet, that holder's rent; Shinjuku keeps the right to close it once empty and take that rent back), the shield, and the send. Never ask the user for SOL. If Shinjuku cannot pay now (transfer_fee_relay_unavailable), nothing is sold: tell the user to ask again in a few minutes with the same request. Right after the sale, before the send, the wallet closes the sold token's empty holder on the own key when it can (Shinjuku pays that fee for a classic token; the holder's small SOL deposit comes back to the own key); the done answer's \`leftover\` says what stays (this wallet cannot send SOL out privately). Price: a quote whose price impact is over 1 % is refused (transfer_price_impact_high) unless allow_impact is true; the sell fails on chain rather than fill below max_slippage_bps (default 50 = 0.5 %, at most 300). The 5 USDC private balance cap is checked on the quote before the sell; if the real USDC no longer fits after it, the plan waits (stage sold_waiting_room) and shields nothing. Privacy: the chain shows the own key selling the token and depositing the USDC, and the pool paying \`to\` in one public transfer that shows its amount. Hidden: which deposit funded it. Limits: \`to\` receives the sold USDC rounded down to a whole 0.01 USDC, one 0.01 USDC more kept back when the sale is a whole number of them (the rest stays in the private balance; the answer's send names both), so the transfer never equals the sale's exact amount, but a close amount can still be matched while the pool's crowd is small; Shinjuku pays the sale and relays the deposit and the send, so the sale shows Shinjuku's fee key beside the own key on chain at sale time, and Shinjuku learns which token and how much was sold; Jupiter and the RPC see the own key, the token, and the amount. The user confirms once (the dialog shows the token, the amount, the USDC expected, the impact, and \`to\`); the user's saved own addresses need no dialog. It takes a few minutes: the first call answers stage (selling, shielding, sending, done) within about ${MONEY_FIRST_ANSWER_MS / 1e3} s; for progress call wallet_transfer_token_status with the same request_id: each call waits up to about ${MONEY_FIRST_ANSWER_MS / 1e3} s for the next step, so call it again right after each answer while it sells and shields, and follow its next during the send. The plan is saved before anything is signed, continues after a restart, and never sells, shields, or sends twice. Refusals: transfer_* codes, mcp_unshield_to_*, mcp_shield_above_balance_cap, mcp_request_id_reused, mcp_tool_disabled, and the deposit and unshield codes.`,
136556
+ // UX130-11 (mcp66 on 0.3.130, a fresh Claude Code session): "Sell them [JUP] for USDC and send the USDC to my main
136557
+ // wallet" made no tool call; the agent said the wallet cannot sell or swap. Claude Code defers MCP tools, so the agent
136558
+ // judges by the title and the first words: both say sell and swap.
136559
+ title: "Sell or swap a token for USDC",
136560
+ description: `Sell or swap a token this wallet holds for USDC (then send the USDC privately). Use this when the user says "sell my JUP for USDC", "swap this token", "send my BONK to <address> privately" or "move this token to my other wallet with no link". It sells amount_atomic of token_mint from this wallet's own key (ownAddress in wallet_balance) for USDC through Jupiter, shields that USDC, and sends it to \`to\` in one private transfer. \`to\` RECEIVES USDC, NOT THE TOKEN: the swap back at \`to\` is not built yet; tell the user to swap at \`to\` themselves. token_mint is the token's base58 mint address, never a name or symbol (BONK is DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263); amount_atomic is in the token's own base units ("1250000" = 1.25 of a 6-decimal token). Cost: the user needs no SOL. Shinjuku pays the sale's network fee (and, when the own key has no USDC holder yet, that holder's rent; Shinjuku keeps the right to close it once empty and take that rent back), the shield, and the send. Never ask the user for SOL. If Shinjuku cannot pay now (transfer_fee_relay_unavailable), nothing is sold: tell the user to ask again in a few minutes with the same request. Right after the sale, before the send, the wallet closes the sold token's empty holder on the own key when it can (Shinjuku pays that fee for a classic token; the holder's small SOL deposit comes back to the own key); the done answer's \`leftover\` says what stays (this wallet cannot send SOL out privately). Price: a quote whose price impact is over 1 % is refused (transfer_price_impact_high) unless allow_impact is true; the sell fails on chain rather than fill below max_slippage_bps (default 50 = 0.5 %, at most 300). The 5 USDC private balance cap is checked on the quote before the sell; if the real USDC no longer fits after it, the plan waits (stage sold_waiting_room) and shields nothing. Privacy: the chain shows the own key selling the token and depositing the USDC, and the pool paying \`to\` in one public transfer that shows its amount. Hidden: which deposit funded it. Limits: \`to\` receives the sold USDC rounded down to a whole 0.01 USDC, one 0.01 USDC more kept back when the sale is a whole number of them (the rest stays in the private balance; the answer's send names both), so the transfer never equals the sale's exact amount, but a close amount can still be matched while the pool's crowd is small; Shinjuku pays the sale and relays the deposit and the send, so the sale shows Shinjuku's fee key beside the own key on chain at sale time, and Shinjuku learns which token and how much was sold; Jupiter and the RPC see the own key, the token, and the amount. The user confirms once (the dialog shows the token, the amount, the USDC expected, the impact, and \`to\`); the user's saved own addresses need no dialog. It takes a few minutes: the first call answers stage (selling, shielding, sending, done) within about ${MONEY_FIRST_ANSWER_MS / 1e3} s; for progress call wallet_transfer_token_status with the same request_id: each call waits up to about ${MONEY_FIRST_ANSWER_MS / 1e3} s for the next step, so call it again right after each answer while it sells and shields, and follow its next during the send. The plan is saved before anything is signed, continues after a restart, and never sells, shields, or sends twice. Refusals: transfer_* codes, mcp_unshield_to_*, mcp_shield_above_balance_cap, mcp_request_id_reused, mcp_tool_disabled, and the deposit and unshield codes.`,
136464
136561
  inputSchema: {
136465
136562
  type: "object",
136466
136563
  properties: {
@@ -136803,7 +136900,7 @@ ${canonical5}`;
136803
136900
  }
136804
136901
  const target = checkUrl(inference.USEPOD_X402_CHAT_URL);
136805
136902
  if (target.refusal) return refuse12(...target.refusal);
136806
- const requestId = args.request_id ?? `mcp-${randomBytes23(8).toString("hex")}`;
136903
+ const requestId = args.request_id ?? `mcp-${randomBytes24(8).toString("hex")}`;
136807
136904
  if (typeof requestId !== "string" || !REQUEST_ID4.test(requestId)) {
136808
136905
  return refuse12("mcp_argument_invalid", "request_id must be 1-128 characters of A-Z a-z 0-9 . _ : -", "leave request_id out for a new call");
136809
136906
  }
@@ -137697,7 +137794,7 @@ function createSetupTools({
137697
137794
  ...privateInference ? { privateInference: true } : {},
137698
137795
  ...current.userAddress?.saved ? { unshieldTo: current.userAddress.saved } : {},
137699
137796
  ...current.userAddress?.notSaved ? { ownWalletAddressNotSaved: current.userAddress.notSaved } : {},
137700
- next: `${ACCEPTED_NEXT}The wallet tools are live in this server: the tool list changed (the setup tools are gone, wallet_status included; wallet_balance answers it). This is not a disconnect: do not tell the user to restart or reconnect. Call wallet_balance.${recoveryNext(summary)}` + userAddressNext(current.userAddress) + (limitLine && !say3.includes(limitLine) ? ` No spending limit is set: tell the user "${limitLine}" (the restart is only for after that command).` : "") + (summary.tor === true ? " Setup ran over Tor, and the wallet runs over Tor: the servers it talks to do not see this computer's IP address." : "") + ` To add funds, call wallet_add_funds: it gives a one-time address for any amount from 0.01 USDC. After the user sends USDC there, ${SAFE_BALANCE_READ}.` + (privateInference ? " Private inference is on: after funding, call inference_chat (with no prompt it lists the models and prices); if this app's wallet entry turns Tor off, inference_chat refuses until the user removes that setting there and reconnects the wallet, so it runs behind Tor." : "")
137797
+ next: `${ACCEPTED_NEXT}The wallet tools are live in this server: the tool list changed (the setup tools are gone, wallet_status included; wallet_balance answers it). This is not a disconnect: do not tell the user to restart or reconnect. Call wallet_balance.${recoveryNext(summary)}` + userAddressNext(current.userAddress) + (limitLine && !say3.includes(limitLine) ? ` No spending limit is set: tell the user "${limitLine}"${/restart/.test(limitLine) ? " (the restart is only for after that command)" : ""}.` : "") + (summary.tor === true ? " Setup ran over Tor, and the wallet runs over Tor: the servers it talks to do not see this computer's IP address." : "") + ` To add funds, call wallet_add_funds: it gives a one-time address for any amount from 0.01 USDC. After the user sends USDC there, ${SAFE_BALANCE_READ}.` + (privateInference ? " Private inference is on: after funding, call inference_chat (with no prompt it lists the models and prices); if this app's wallet entry turns Tor off, inference_chat refuses until the user removes that setting there and reconnects the wallet, so it runs behind Tor." : "")
137701
137798
  });
137702
137799
  }
137703
137800
  if (current.state === "confirming") return json3({ say: SETUP_CONFIRMING_SAY, ok: true, stage: "confirming", next: SETUP_CONFIRMING_NEXT });
@@ -138137,7 +138234,7 @@ var init_tools = __esm({
138137
138234
  ASK_PAY_CODES = /* @__PURE__ */ new Set(["spend_payment_cap_exceeded", "mcp_cap_argument_above_launch_cap"]);
138138
138235
  terminalCommand2 = (words2, { code: code2 = false } = {}) => agentCommandLine(words2, { npmVersion: runningNpmVersion, code: code2 });
138139
138236
  capPlaceWords = (flag3) => capFlagFromLaunchLine(flag3) ? "this app's wallet entry" : "your limits";
138140
- noLimitSetLine = () => `To set a spending limit, run ${terminalCommand2("limits")} in a terminal, then restart this app.`;
138237
+ noLimitSetLine = () => `To set a spending limit, run ${terminalCommand2("limits")} in a terminal${capCountsNow("--max-payment") ? "; it counts at once" : ", then restart this app"}.`;
138141
138238
  CAP_NAMES = {
138142
138239
  "--max-payment": "per-payment limit",
138143
138240
  "--max-session": "24-hour payment limit",
@@ -138153,7 +138250,7 @@ var init_tools = __esm({
138153
138250
  const both = flag3 === "--max-payment" ? " (raise the 24-hour payment limit there too when it is below the new amount: the wallet does not start with it lower)" : "";
138154
138251
  return `The ${capName(flag3)} is set in this app's wallet entry; only the user can change it there${both}, with amounts in USDC like 0.5, then reconnect the wallet (restart this app). ${entryPlaces("with the new value")} Running setup does not change this limit: the value in the entry wins over the limit setup records.`;
138155
138252
  }
138156
- return `The ${capName(flag3)} comes from ${capPlaceWords(flag3)}. To change it, the user runs ${terminalCommand2("limits")} in a terminal: it asks each limit as a question (amounts in USDC like 0.5, or Enter for no limit). Then the user restarts this app.`;
138253
+ return `The ${capName(flag3)} comes from ${capPlaceWords(flag3)}. To change it, the user runs ${terminalCommand2("limits")} in a terminal: it asks each limit as a question (amounts in USDC like 0.5, or Enter for no limit). ${capCountsNow(flag3) ? "It counts at once (no restart)." : "Then the user restarts this app."}`;
138157
138254
  };
138158
138255
  payCapFlag = (capAtomic) => {
138159
138256
  const day = runningLimits?.maxSessionAtomic;
@@ -138550,7 +138647,7 @@ var init_tools = __esm({
138550
138647
  OWN_ADDRESS_INVALID = "That is not a Solana address (32 to 44 letters and digits, as your wallet app shows it)";
138551
138648
  PRIVATE_INFERENCE_WHY = "Your agent then buys AI answers from an AI provider, paid from your private balance over Tor; the AI provider and the company that runs the model see the prompt, not who paid.";
138552
138649
  RESTART_STEPS = `In Claude Code: type /mcp, pick ${MCP_SERVER_NAME}, and choose Reconnect. In Claude Desktop: quit it and open it again. In another app: restart it`;
138553
- HOST_BLOCKED_LINE = "If this app blocks a wallet tool (Claude Code's auto mode can), say nothing moved; in Claude Code, shift+tab turns auto mode off, then ask again. Never suggest a rule that lets a payment or send run with no question, or another way around the block.";
138650
+ HOST_BLOCKED_LINE = "If this app blocks a wallet tool (Claude Code's auto mode can), say nothing moved; in Claude Code, press shift+tab until it shows manual mode, then ask again. Never suggest a rule that lets a payment or send run with no question, or another way around the block.";
138554
138651
  TOR_BROWSER_PORT = "http://127.0.0.1:9150";
138555
138652
  SETUP_TOR_TITLE = "Use Tor?";
138556
138653
  SETUP_TOR_WHY = "It hides your IP address from the payment service and sellers.";
@@ -139353,6 +139450,7 @@ async function openWalletServer({
139353
139450
  maxSessionAtomic,
139354
139451
  maxPerHostDayAtomic,
139355
139452
  allowHosts,
139453
+ limitsNow,
139356
139454
  allowShield,
139357
139455
  noShield = false,
139358
139456
  maxShieldAtomic,
@@ -139410,9 +139508,12 @@ async function openWalletServer({
139410
139508
  maxSessionAtomic: asText(maxSessionAtomic),
139411
139509
  // --max-session is the most this wallet pays in any 24 hours, from every MCP process (a host may start one per request).
139412
139510
  walletDay: true,
139511
+ // UX130-12: a run whose limits came from config.json (the CLI's mcpServerOptions) reads them there at each check.
139512
+ ...typeof limitsNow === "function" ? { limitsNow } : {},
139413
139513
  ...maxPerHostDayAtomic !== void 0 ? { maxPerHostDayAtomic: asText(maxPerHostDayAtomic) } : {},
139414
139514
  ...allowHosts !== void 0 && (!Array.isArray(allowHosts) || allowHosts.length) ? { allowHosts } : {}
139415
139515
  });
139516
+ setLimitsFollowConfig(typeof limitsNow === "function");
139416
139517
  const session = await openSession({
139417
139518
  walletPath: walletPath2,
139418
139519
  passphrase: passphrase2,
@@ -139950,13 +140051,14 @@ async function runSetupModeServer({
139950
140051
  }
139951
140052
  return { closed: ended };
139952
140053
  }
139953
- var import_web3134, SUPPORTED_PROTOCOL_VERSIONS, MAX_LINE_BYTES, POSITIVE_ATOMIC7, INSTRUCTIONS_BASE, INSTRUCTIONS, MCP_LOG_LEVELS, POOL_SWITCH_LOG_LEVEL, validId, PRODUCT_NAME, listedTitle, BUNDLED_SOURCE_DIR, SHA256_HEX, UPDATE_NOTICE_TOOLS, UPDATE_NOTICE_MAX_TEXT, NPM_VERSION2, GIT_COMMIT, ownWalletVersion, mcpServerVersion, UPDATE_NOTICE_TEXT, updateNoticeLine, commandUpdateField, LAUNCH_NOTICE_TOOLS, withLaunchLine, capRequired, setupInvalid, TOOL_ROOTS_WAIT_MS, ROOTS_FREE_TOOLS, MCP_CLOSE_BOUND_MS, MCP_CLOSE_HISTORY_BOUND_MS, MCP_CLOSE_UNREADABLE_BOUND_MS, MCP_CLOSE_POLL_MS, closeHistoryBusy, SETUP_INSTRUCTIONS, TOR_RELAY_READY_MS, RELAY_INIT_ID, runMcp;
140054
+ var import_web3134, SUPPORTED_PROTOCOL_VERSIONS, MAX_LINE_BYTES, POSITIVE_ATOMIC7, INSTRUCTIONS_BASE, SELL_LINE, OWN_ADDRESS_LINE, INSTRUCTIONS, MCP_LOG_LEVELS, POOL_SWITCH_LOG_LEVEL, validId, PRODUCT_NAME, listedTitle, BUNDLED_SOURCE_DIR, SHA256_HEX, UPDATE_NOTICE_TOOLS, UPDATE_NOTICE_MAX_TEXT, NPM_VERSION2, GIT_COMMIT, ownWalletVersion, mcpServerVersion, UPDATE_NOTICE_TEXT, updateNoticeLine, commandUpdateField, LAUNCH_NOTICE_TOOLS, withLaunchLine, capRequired, setupInvalid, TOOL_ROOTS_WAIT_MS, ROOTS_FREE_TOOLS, MCP_CLOSE_BOUND_MS, MCP_CLOSE_HISTORY_BOUND_MS, MCP_CLOSE_UNREADABLE_BOUND_MS, MCP_CLOSE_POLL_MS, closeHistoryBusy, SETUP_INSTRUCTIONS, TOR_RELAY_READY_MS, RELAY_INIT_ID, runMcp;
139954
140055
  var init_stdioServer = __esm({
139955
140056
  "wallet/src/mcp/stdioServer.mjs"() {
139956
140057
  "use strict";
139957
140058
  init_fs();
139958
140059
  import_web3134 = __toESM(require_index_cjs(), 1);
139959
140060
  init_spendPolicy();
140061
+ init_launchCaps();
139960
140062
  init_usdcWords();
139961
140063
  init_proxy();
139962
140064
  init_facilitatorOnion();
@@ -139983,8 +140085,10 @@ var init_stdioServer = __esm({
139983
140085
  SUPPORTED_PROTOCOL_VERSIONS = Object.freeze(["2025-06-18", "2025-03-26", "2024-11-05"]);
139984
140086
  MAX_LINE_BYTES = 4 * 1024 * 1024;
139985
140087
  POSITIVE_ATOMIC7 = /^[1-9][0-9]{0,30}$/;
139986
- INSTRUCTIONS_BASE = `A self-custody Shinjuku Shield wallet on this machine; no tool takes or returns its keys or passphrase. Each answer's say is one plain sentence for the user; other fields hold the numbers. Never tell the user a tool, field, code or protocol name (x402, MCP) unless told to. Map the user's plain request to one tool: "what is my balance" -> wallet_balance (safe at any time); "add money" / "deposit" / "move USDC in from Phantom or an exchange" -> wallet_add_funds (a one-time address; the next wallet_balance after the USDC arrives makes it private, up to 5 USDC private); "shield the USDC on this wallet's own address" -> wallet_shield; "stop" / "cancel" -> wallet_cancel with the request_id of what to stop; "pay this URL" -> x402_pay (no preview needed); "what does this URL cost" -> x402_preview (only when asked); "find a paid API for X" -> x402_discover, then x402_pay on the url it found; "send 2 USDC to <address>" -> wallet_unshield; "show my payments" -> wallet_receipts; "send another token" -> wallet_transfer_token; "ask an AI model" / "which AI models" -> inference_chat (with no prompt it lists the models and prices); "give my other AI app a private AI" -> inference_server (a local OpenAI-compatible URL and key for that app). wallet_balance answers ONE balance (balanceAtomic), and x402_pay pays any paid URL from it (a seller that cannot take a private payment is paid through Shinjuku: max_payment covers amountAtomic, fee included). Fields ending in Atomic are atomic units (1000000 = 1 USDC); tell the user USDC. The wallet does its own upkeep (no user command). A shield, add-funds or unshield call can run for minutes: call again with the SAME request_id as next says. Pass your own request_id to x402_pay: the same request_id never pays or moves money twice (a code ending in _retry_same_request: call again with it). A wallet_unshield send to an address not approved ahead asks the user to confirm first. x402_pay never pays above the user's spending limits (one payment; any 24 hours); with none, the balance is the only bound. Never claim a payment happened unless the answer has a transaction. Privacy: the chain does not show which wallet paid, but this app and its model provider see every URL, body, price and paid answer you handle; reach a seller or its domain only through these tools, never yourself (no curl, browser or DNS lookup, DNS-over-HTTPS too), also when the user asks for no Tor: it shows the user's IP address to the site or a DNS company. When an item of an answer's poolSwitch.items[] has tellUser true, tell the user its message once, in plain words; the wallet moves the balance by itself.`;
139987
- INSTRUCTIONS = `${INSTRUCTIONS_BASE} ${HOST_BLOCKED_LINE}`;
140088
+ INSTRUCTIONS_BASE = `A self-custody Shinjuku Shield wallet on this machine; no tool takes or returns its keys or passphrase. Each answer's say is one plain sentence for the user; other fields hold numbers. Never tell the user a tool, field, code or protocol name (x402, MCP) unless told to. Map a plain request to one tool: "what is my balance" -> wallet_balance (safe at any time); "add money" / "deposit" / "move USDC in from Phantom or an exchange" -> wallet_add_funds (a one-time address; the next wallet_balance after the USDC arrives makes it private, up to 5 USDC); "shield the USDC on this wallet's own address" -> wallet_shield; "stop" / "cancel" -> wallet_cancel (the request_id of what to stop); "pay this URL" -> x402_pay (no preview needed); "what does this URL cost" -> x402_preview (only when asked); "find a paid API for X" -> x402_discover, then x402_pay on its url; "send 2 USDC to <address>" -> wallet_unshield; "show my payments" -> wallet_receipts; "send another token" -> wallet_transfer_token; "ask an AI model" / "which AI models" -> inference_chat (no prompt: it lists models and prices); "give my other AI app a private AI" -> inference_server (a local OpenAI-compatible URL and key). wallet_balance answers ONE balance (balanceAtomic); x402_pay pays any paid URL from it (a seller that cannot take a private payment is paid through Shinjuku; max_payment covers amountAtomic with fee). Fields ending in Atomic are atomic units (1000000 = 1 USDC); tell the user USDC. The wallet does its own upkeep (no user command). A shield, add-funds or unshield call can run for minutes: call again with the SAME request_id as next says. Pass your own request_id to x402_pay: the same one never pays or moves money twice (a code ending in _retry_same_request: call again with it). A wallet_unshield send to an address not approved ahead asks the user to confirm. x402_pay never pays above the spending limits (one payment; 24 hours); with none, the balance is the only bound. Never claim a payment happened unless the answer has a transaction. Privacy: the chain does not show which wallet paid, but this app and its model provider see every URL, body, price and answer you handle; reach a seller or its domain only through these tools, never yourself (no curl, browser, DNS or DNS-over-HTTPS lookup), also when the user asks for no Tor: that shows their IP address to the site or a DNS company. When an answer's poolSwitch.items[] item has tellUser true, tell the user its message once, in plain words; the wallet moves the balance by itself.`;
140089
+ SELL_LINE = "To sell or swap a token the wallet holds: wallet_transfer_token.";
140090
+ OWN_ADDRESS_LINE = '"Send to my (main) wallet": wallet_unshield with no to uses the address saved at setup; never ask for it.';
140091
+ INSTRUCTIONS = `${INSTRUCTIONS_BASE} ${SELL_LINE} ${OWN_ADDRESS_LINE} ${HOST_BLOCKED_LINE}`;
139988
140092
  MCP_LOG_LEVELS = Object.freeze(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
139989
140093
  POOL_SWITCH_LOG_LEVEL = "info";
139990
140094
  validId = (id) => id === null || typeof id === "string" || typeof id === "number" && Number.isFinite(id);
@@ -140040,7 +140144,7 @@ __export(serve_exports, {
140040
140144
  paidOf: () => paidOf
140041
140145
  });
140042
140146
  import { createServer as createServer2 } from "node:http";
140043
- import { randomBytes as randomBytes24, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
140147
+ import { randomBytes as randomBytes25, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
140044
140148
  function codeOf7(error) {
140045
140149
  if (typeof error?.code === "string" && /^[a-z0-9_]+$/.test(error.code)) return error.code;
140046
140150
  if (typeof error?.error === "string" && /^[a-z0-9_]+$/.test(error.error)) return error.error;
@@ -140297,7 +140401,7 @@ function createInferenceServer({
140297
140401
  preparedPayment,
140298
140402
  answerNeverPaid: answerNeverPaid2,
140299
140403
  apiKey,
140300
- token = randomBytes24(16).toString("hex"),
140404
+ token = randomBytes25(16).toString("hex"),
140301
140405
  port = INFERENCE_SERVE_PORT,
140302
140406
  log = () => {
140303
140407
  },
@@ -140366,7 +140470,7 @@ function createInferenceServer({
140366
140470
  const ids = inference.listModels().map((model) => model.id).join(", ");
140367
140471
  throw refusal2("inference_model_unknown", `model is required; pick one of: ${ids} (GET /v1/models lists them with prices)`, "model");
140368
140472
  }
140369
- const requestId = key ? `infer-${key}` : `infer-${randomBytes24(8).toString("hex")}`;
140473
+ const requestId = key ? `infer-${key}` : `infer-${randomBytes25(8).toString("hex")}`;
140370
140474
  let held = false;
140371
140475
  try {
140372
140476
  held = key !== void 0 && typeof heldPayment2 === "function" && heldPayment2({ requestId }) === true;
@@ -140646,11 +140750,11 @@ var init_serve = __esm({
140646
140750
  });
140647
140751
 
140648
140752
  // wallet/src/inference/serveRunner.mjs
140649
- import { randomBytes as randomBytes25 } from "node:crypto";
140753
+ import { randomBytes as randomBytes26 } from "node:crypto";
140650
140754
  import { spawn as spawn5, spawnSync as spawnSync4 } from "node:child_process";
140651
140755
  import { dirname as dirname29, join as join32, resolve as resolve24 } from "node:path";
140652
140756
  function writeAtomic4(path, text3) {
140653
- const temp = `${path}.${randomBytes25(4).toString("hex")}.tmp`;
140757
+ const temp = `${path}.${randomBytes26(4).toString("hex")}.tmp`;
140654
140758
  writeFileSync(temp, text3, { mode: 384, flag: "wx" });
140655
140759
  try {
140656
140760
  renameSync(temp, path);
@@ -140708,8 +140812,8 @@ function localAiServerApiKey(home, { walletPath: walletPath2 } = {}) {
140708
140812
  rmSync(earlier, { force: true });
140709
140813
  return key2;
140710
140814
  }
140711
- const key = randomBytes25(24).toString("hex");
140712
- const temp = `${path}.${randomBytes25(4).toString("hex")}.tmp`;
140815
+ const key = randomBytes26(24).toString("hex");
140816
+ const temp = `${path}.${randomBytes26(4).toString("hex")}.tmp`;
140713
140817
  writeFileSync(temp, `${key}
140714
140818
  `, { mode: 384, flag: "wx" });
140715
140819
  try {
@@ -141131,7 +141235,7 @@ async function startLocalAiServer({
141131
141235
  rmSync(localAiServerStopPath(walletPath2), { force: true });
141132
141236
  } catch {
141133
141237
  }
141134
- const launchId = randomBytes25(16).toString("hex");
141238
+ const launchId = randomBytes26(16).toString("hex");
141135
141239
  const childEnv = childRunProxy(env).env;
141136
141240
  for (const name of Object.keys(childEnv)) {
141137
141241
  if (NODE_ENV_DROP.includes(name) || name.startsWith("SHINJUKU_WALLET_SEND_RUNNER") || name.startsWith("SHINJUKU_WALLET_LOCAL_AI_SERVER")) delete childEnv[name];
@@ -141552,7 +141656,7 @@ __export(chat_exports, {
141552
141656
  runChat: () => runChat,
141553
141657
  savedBalance: () => savedBalance
141554
141658
  });
141555
- import { randomBytes as randomBytes27 } from "node:crypto";
141659
+ import { randomBytes as randomBytes28 } from "node:crypto";
141556
141660
  import { createInterface } from "node:readline";
141557
141661
  function leastAnswerAtomic(entry, maxTokens = CHAT_MAX_TOKENS) {
141558
141662
  return (entry.priceInPerMAtomic * SHORT_QUESTION_TOKENS + entry.priceOutPerMAtomic * BigInt(maxTokens) + 999999n) / 1000000n + SHINJUKU_FEE_ATOMIC;
@@ -142251,7 +142355,7 @@ When it says ready, type /retry: it asks the same question again.` : receivedOnl
142251
142355
  if (state.pending) say3("(The unfinished answer is dropped; this is a new question.)");
142252
142356
  state.pending = void 0;
142253
142357
  await runTurn({
142254
- requestId: `chat-${randomBytes27(8).toString("hex")}`,
142358
+ requestId: `chat-${randomBytes28(8).toString("hex")}`,
142255
142359
  model: state.model,
142256
142360
  messages: [...state.history, { role: "user", content: text3 }],
142257
142361
  capAtomic: void 0
@@ -142457,7 +142561,7 @@ init_emptyBalance();
142457
142561
  init_knownZero();
142458
142562
  init_publicRead();
142459
142563
  init_timing();
142460
- import { randomBytes as randomBytes29 } from "node:crypto";
142564
+ import { randomBytes as randomBytes30 } from "node:crypto";
142461
142565
  import { dirname as dirname32, join as join38, resolve as resolve33 } from "node:path";
142462
142566
  import { spawn as spawn9 } from "node:child_process";
142463
142567
  import { fileURLToPath as fileURLToPath21 } from "node:url";
@@ -142490,7 +142594,7 @@ init_successions();
142490
142594
  init_chain2();
142491
142595
  init_rpcDefault();
142492
142596
  init_commandName();
142493
- import { randomBytes as randomBytes26 } from "node:crypto";
142597
+ import { randomBytes as randomBytes27 } from "node:crypto";
142494
142598
  import { spawnSync as spawnSync5 } from "node:child_process";
142495
142599
  import { join as join33, resolve as resolve26 } from "node:path";
142496
142600
  var POSITIVE_ATOMIC8 = /^[1-9][0-9]{0,30}$/;
@@ -142732,7 +142836,7 @@ async function runSetup(options, deps = {}) {
142732
142836
  throw fail40("setup_passphrase_needed", "a wallet already exists for this pool in this home, and setup has no passphrase file for it. Rerun setup with --passphrase-file <a private file that holds its passphrase>; setup never changes or replaces an existing wallet");
142733
142837
  } else {
142734
142838
  try {
142735
- writeRecoveryFile(ownFile, randomBytes26(32).toString("base64url"));
142839
+ writeRecoveryFile(ownFile, randomBytes27(32).toString("base64url"));
142736
142840
  } catch (error) {
142737
142841
  throw fail40("setup_passphrase_file_failed", `the new passphrase file could not be written privately (${String(error?.message ?? "").split(":")[0]}); on Linux the wallet home must be a folder only you can write to. Nothing was created`);
142738
142842
  }
@@ -146116,7 +146220,7 @@ init_balance();
146116
146220
  init_balanceNow();
146117
146221
  init_deposit();
146118
146222
  import { spawn as spawn8 } from "node:child_process";
146119
- import { randomBytes as randomBytes28, randomInt as randomInt9 } from "node:crypto";
146223
+ import { randomBytes as randomBytes29, randomInt as randomInt9 } from "node:crypto";
146120
146224
  import { tmpdir as tmpdir4 } from "node:os";
146121
146225
  import { join as join36, resolve as resolve31 } from "node:path";
146122
146226
  init_chat();
@@ -146445,7 +146549,7 @@ var STEP_TOR_LINE = /^(?:tor|proxy): /;
146445
146549
  var DENOMINATION_WARNING = /^warning: this pool has no fixed deposit size\b/;
146446
146550
  async function runStep(ctx, argv2) {
146447
146551
  if (ctx.signal.aborted) return { exit: 1, held: [], codes: [], details: {}, aborted: true };
146448
- const file = join36(ctx.tempDir, `step-${randomBytes28(8).toString("hex")}.json`);
146552
+ const file = join36(ctx.tempDir, `step-${randomBytes29(8).toString("hex")}.json`);
146449
146553
  const held = [];
146450
146554
  let last;
146451
146555
  const proc = spawn8(process.execPath, [...process.execArgv, ctx.entry, ...ctx.proxyArgs, ...argv2], {
@@ -149437,14 +149541,14 @@ async function runCurl(values, deps) {
149437
149541
  throw new UsageError("curl is missing --max-payment <usdc>: the most this request may pay, in USDC (0.02 = 2 cents); in a terminal, curl shows the seller's price and asks instead", COMMAND_BY_NAME.get("curl"));
149438
149542
  }
149439
149543
  const io = deps.io;
149440
- const requestId = values.get("--request-id") ?? `curl-${randomBytes29(8).toString("hex")}`;
149544
+ const requestId = values.get("--request-id") ?? `curl-${randomBytes30(8).toString("hex")}`;
149441
149545
  let kept2;
149442
149546
  if (values.has("--request-id")) {
149443
149547
  const { walletPath: walletPath2, passphrase: passphrase2 } = payerSessionOptions(values, deps);
149444
149548
  kept2 = keptPayment((deps.openWalletStore ?? openWalletStore)(walletPath2, passphrase2), requestId);
149445
149549
  if (kept2?.committed) kept2 = void 0;
149446
149550
  }
149447
- const probeId = kept2 ? `curl-${randomBytes29(8).toString("hex")}` : requestId;
149551
+ const probeId = kept2 ? `curl-${randomBytes30(8).toString("hex")}` : requestId;
149448
149552
  const probe = createSpendPolicy({ maxPaymentAtomic: NO_LIMIT_ATOMIC2, allowHosts: ["price-probe.invalid"] });
149449
149553
  const body = curlBody(values);
149450
149554
  const method = (values.get("--method") ?? (body === void 0 ? "GET" : "POST")).toUpperCase();
@@ -149498,7 +149602,7 @@ async function runCurlPaid(values, deps, { requestId: probeId } = {}) {
149498
149602
  const method = (values.get("--method") ?? (body === void 0 ? "GET" : "POST")).toUpperCase();
149499
149603
  const headers = (values.get("--header") ?? []).map((line) => [line.slice(0, line.indexOf(":")).trim(), line.slice(line.indexOf(":") + 1).trim()]);
149500
149604
  const given = values.get("--request-id");
149501
- const requestId = given ?? probeId ?? `curl-${randomBytes29(8).toString("hex")}`;
149605
+ const requestId = given ?? probeId ?? `curl-${randomBytes30(8).toString("hex")}`;
149502
149606
  const session = await (deps.openPayerSession ?? openPayerSession)({ ...payerSessionOptions(values, deps), spendPolicy: policy });
149503
149607
  let response;
149504
149608
  try {
@@ -149764,7 +149868,7 @@ async function runInfer(values, deps) {
149764
149868
  ...terminalDayLimit(values, deps)
149765
149869
  });
149766
149870
  const given = values.get("--request-id");
149767
- const requestId = given ?? `infer-${randomBytes29(8).toString("hex")}`;
149871
+ const requestId = given ?? `infer-${randomBytes30(8).toString("hex")}`;
149768
149872
  const session = await (deps.openPayerSession ?? openPayerSession)({ ...payerSessionOptions(values, deps), spendPolicy: policy });
149769
149873
  const quiet = inProxiedRun(deps.env) && terminalQuiet(values, deps);
149770
149874
  const stopWatch = quiet && !given ? idLineOnInterrupt(io, inferIdLine(requestId)) : () => {
@@ -150505,6 +150609,7 @@ function mcpServerOptions(values, deps) {
150505
150609
  ...options,
150506
150610
  maxPaymentAtomic: values.get("--max-payment"),
150507
150611
  maxSessionAtomic: values.get("--max-session"),
150612
+ ...capsNowOf(values.get(MCP_FROM_CONFIG)) ? { limitsNow: capsNowOf(values.get(MCP_FROM_CONFIG)) } : {},
150508
150613
  ...values.has("--max-per-host-day") ? { maxPerHostDayAtomic: values.get("--max-per-host-day") } : {},
150509
150614
  ...values.has("--allow-host") ? { allowHosts: values.get("--allow-host") } : {},
150510
150615
  ...values.has("--no-shield") ? { noShield: true } : {},
@@ -150581,6 +150686,17 @@ function homeJobTor(argv2, env) {
150581
150686
  if (job.mode === "tor") return typed ? true : void 0;
150582
150687
  return typed || env[NO_TOR_RUN_ENV] === "1" ? false : void 0;
150583
150688
  }
150689
+ var typedCapsOf = (values) => ({ payment: values.has("--max-payment"), session: values.has("--max-session") });
150690
+ function capsNowOf(fromConfig) {
150691
+ if (!fromConfig || fromConfig.typedCaps?.payment && fromConfig.typedCaps?.session) return void 0;
150692
+ return () => {
150693
+ const caps = readSetupConfig(fromConfig.home)?.caps ?? {};
150694
+ return {
150695
+ ...fromConfig.typedCaps?.payment ? {} : { maxPaymentAtomic: caps.maxPayment },
150696
+ ...fromConfig.typedCaps?.session ? {} : { maxSessionAtomic: caps.maxSession }
150697
+ };
150698
+ };
150699
+ }
150584
150700
  function fillFromConfig(values, home, config) {
150585
150701
  for (const [name, value2] of mcpFlagsFromConfig(home, config)) if (!values.has(name)) values.set(name, value2);
150586
150702
  }
@@ -150595,8 +150711,9 @@ function mcpBeforeValidate(values, deps, args, oldForm = []) {
150595
150711
  return SKIP_VALIDATE;
150596
150712
  }
150597
150713
  const typedTo = values.has("--unshield-to");
150714
+ const typedCaps = typedCapsOf(values);
150598
150715
  fillFromConfig(values, home, config);
150599
- values.set(MCP_FROM_CONFIG, { home, config, typedTo });
150716
+ values.set(MCP_FROM_CONFIG, { home, config, typedTo, typedCaps });
150600
150717
  }
150601
150718
  requireMcpCaps(values);
150602
150719
  return void 0;
@@ -150687,7 +150804,7 @@ function mcpTorAheadHome(values, deps) {
150687
150804
  return firstRun && setupConfigOf(firstRun.home)?.tor === true ? firstRun.home : void 0;
150688
150805
  }
150689
150806
  async function torRunOf(args, deps) {
150690
- const startedFile = join38(tmpdir5(), `shinjuku-wallet-tor-run-${randomBytes29(16).toString("hex")}`);
150807
+ const startedFile = join38(tmpdir5(), `shinjuku-wallet-tor-run-${randomBytes30(16).toString("hex")}`);
150691
150808
  try {
150692
150809
  const code2 = await deps.torReexec(args, { startedFile });
150693
150810
  return { code: code2, started: existsSync(startedFile) };
@@ -150755,8 +150872,9 @@ function mcpValuesAfterSetup(values, home, deps) {
150755
150872
  if (!config) throw new PublicFailure(`mcp_not_set_up: setup wrote no config.json; run setup again:
150756
150873
  ${cli2()} setup`);
150757
150874
  const typedTo = next.has("--unshield-to");
150875
+ const typedCaps = typedCapsOf(next);
150758
150876
  fillFromConfig(next, home, config);
150759
- next.set(MCP_FROM_CONFIG, { home, config, typedTo });
150877
+ next.set(MCP_FROM_CONFIG, { home, config, typedTo, typedCaps });
150760
150878
  next.set(MCP_RAW_ARGS, values.get(MCP_RAW_ARGS) ?? []);
150761
150879
  next.set(MCP_OLD_FORM, values.get(MCP_OLD_FORM) ?? []);
150762
150880
  requireMcpCaps(next);
@@ -151122,7 +151240,7 @@ async function runRestoreCommand(values, deps) {
151122
151240
  if (!restored) {
151123
151241
  mkdirSync(home, { recursive: true, mode: 448 });
151124
151242
  const ownFile = join38(home, PASSPHRASE_FILE);
151125
- if (!existsSync(ownFile)) writeRecoveryFile(ownFile, randomBytes29(32).toString("base64url"));
151243
+ if (!existsSync(ownFile)) writeRecoveryFile(ownFile, randomBytes30(32).toString("base64url"));
151126
151244
  await deps.setupInit({ home, passphrase: readSecretText(ownFile, "the passphrase file"), args: [
151127
151245
  "restore",
151128
151246
  "--pool",
@@ -151317,7 +151435,7 @@ function allowWalletChecks(deps) {
151317
151435
  const file = claudeCodeSettingsFile({ env: deps.env, home: deps.homedir() });
151318
151436
  try {
151319
151437
  const { changed, backup } = allowInClaudeCode(file);
151320
- return { same: !changed, say: `Claude Code runs the wallet's checks that move no money (balance, receipts) without a question${backup ? ` (its old settings file was copied to ${backup}, readable by you alone)` : ""}. In Claude Code's default mode, payments and sends still ask first; its auto mode may pay with no question or block a send (press shift+tab until auto mode is off). To undo the wallet's rules, remove the shinjuku rules in Claude Code's /permissions.` };
151438
+ return { same: !changed, say: `Claude Code runs the wallet's checks that move no money (balance, receipts) without a question${backup ? ` (its old settings file was copied to ${backup}, readable by you alone)` : ""}. Claude Code may start in auto mode: then a payment or a send can run with no question, or be blocked. Press shift+tab until it shows manual mode: there every payment and send asks you first. To undo the wallet's rules, remove the shinjuku rules in Claude Code's /permissions.` };
151321
151439
  } catch (error) {
151322
151440
  const unreadable = String(error.message).startsWith("setup_host_config_unreadable:");
151323
151441
  return { same: false, say: `Claude Code still asks before each wallet check: ${unreadable ? `the wallet cannot read the settings in ${file}, so it did not change that file` : `the wallet could not write ${file}`}.` };
@@ -151453,7 +151571,7 @@ async function installCommand(deps, { npmVersion, proxy, verbose = false }) {
151453
151571
  }
151454
151572
  if (answer === "refused" || answer === "too_old") return "tor-down";
151455
151573
  }
151456
- const args = ["install", "-g", "--no-audit", "--no-fund", ...proxy ? ["--https-proxy", proxy.url, "--proxy", proxy.url] : [], installPackageWord(npmVersion)];
151574
+ const args = ["install", "-g", "--no-audit", "--no-fund", "--prefer-online", ...proxy ? ["--https-proxy", proxy.url, "--proxy", proxy.url] : [], installPackageWord(npmVersion)];
151457
151575
  io.err(`Installing the shinjuku command${proxy?.tor ? " over Tor" : ""} (npm install; this can take a minute)...
151458
151576
  `);
151459
151577
  let result;
@@ -153901,7 +154019,7 @@ async function runUnshieldRequest(args, values, deps, io) {
153901
154019
  };
153902
154020
  const ensureId = () => {
153903
154021
  if (id !== void 0) return;
153904
- id = `unshield-${randomBytes29(6).toString("hex")}`;
154022
+ id = `unshield-${randomBytes30(6).toString("hex")}`;
153905
154023
  setArg("--unshield-id", id);
153906
154024
  values.set(UNSHIELD_MADE_ID, id);
153907
154025
  if (quiet) {
@@ -153947,8 +154065,9 @@ async function runUnshieldRequest(args, values, deps, io) {
153947
154065
  const report = await refreshAfterUnshield(walletAt >= 0 ? gated[walletAt + 1] : values.get("--wallet"), values, deps, io);
153948
154066
  if (!terminal) return;
153949
154067
  let unfinished = [];
154068
+ const queued = values.get(RESUME_QUEUE) ?? /* @__PURE__ */ new Set();
153950
154069
  try {
153951
- unfinished = unfinishedUnshields(openStore());
154070
+ unfinished = unfinishedUnshields(openStore()).filter((one) => !queued.has(one.unshieldId));
153952
154071
  } catch {
153953
154072
  }
153954
154073
  let parts;
@@ -153964,6 +154083,7 @@ async function runUnshieldRequest(args, values, deps, io) {
153964
154083
  }
153965
154084
  }
153966
154085
  var RESUMING_OPEN_UNSHIELD = /* @__PURE__ */ Symbol("finishing an open unshield");
154086
+ var RESUME_QUEUE = /* @__PURE__ */ Symbol("open sends finished next");
153967
154087
  async function resumeOpenUnshields(args, values, deps, io) {
153968
154088
  const store = commandStore(values, deps);
153969
154089
  if (!store) return 0;
@@ -153985,7 +154105,7 @@ async function resumeOpenUnshields(args, values, deps, io) {
153985
154105
  if (valueFlags.has(args[index]) && index + 1 < args.length) kept2.push(args[index += 1]);
153986
154106
  }
153987
154107
  let finished = 0;
153988
- for (const one of open4) {
154108
+ for (const [index, one] of open4.entries()) {
153989
154109
  let to = one.to;
153990
154110
  if (to === void 0) {
153991
154111
  to = await openUnshieldAddress(one, values, deps);
@@ -153997,7 +154117,13 @@ async function resumeOpenUnshields(args, values, deps, io) {
153997
154117
  const resumeValues = new Map([...values].filter(([name]) => !replaced.has(name)));
153998
154118
  for (const [name, value2] of [["--amount", "all"], ["--to", to], ["--unshield-id", one.unshieldId]]) resumeValues.set(name, value2);
153999
154119
  resumeValues.set(RESUMING_OPEN_UNSHIELD, true);
154000
- await runUnshieldCommand([...kept2, "--amount", "all", "--to", to, "--unshield-id", one.unshieldId], resumeValues, deps, io);
154120
+ resumeValues.set(RESUME_QUEUE, new Set(open4.slice(index + 1).map((next) => next.unshieldId)));
154121
+ try {
154122
+ await runUnshieldCommand([...kept2, "--amount", "all", "--to", to, "--unshield-id", one.unshieldId], resumeValues, deps, io);
154123
+ } catch (error) {
154124
+ if (one.to !== void 0 || !String(error?.message ?? "").startsWith("p03_unshield_id_reused_with_different_recipient")) throw error;
154125
+ throw unshieldRefusal("open_send_other_address", `${to} is not the address your earlier send of ${usdcOr(one.amountAtomic)} was started for, so nothing was sent; that send stays open. Run ${cli2()} unshield all again and give the address you first sent it to`);
154126
+ }
154001
154127
  finished += 1;
154002
154128
  }
154003
154129
  return finished;
@@ -154043,12 +154169,11 @@ function unfinishedUnshields(store) {
154043
154169
  }
154044
154170
  };
154045
154171
  const names = store.listWal();
154046
- const planPrefix = privateSendPlanName("");
154047
- const partIds = new Set(names.filter((name) => name.startsWith(planPrefix)).flatMap((name) => {
154048
- const plan = read(name);
154049
- return Array.isArray(plan?.parts) ? plan.parts.map((part) => String(part?.unshieldId)) : [];
154050
- }));
154051
- return names.filter((name) => name.startsWith("self-pay-")).map((name) => name.slice("self-pay-".length)).filter((unshieldId) => !unshieldId.startsWith("merge-") && !/^pocket-\d+-f\d+$/.test(unshieldId)).map((unshieldId) => ({ unshieldId, record: read(`self-pay-${unshieldId}`) })).filter(({ record }) => record?.schema === SELF_PAY_WAL_SCHEMA && record.state === "paid" && /^[1-9][0-9]*$/.test(String(record.amountAtomic ?? "")) && (record.mode === DIRECT_EXIT_MODE ? record.mcpTo === void 0 : record.ownerUnshield === true)).map(({ unshieldId, record }) => {
154172
+ const partIds = plannedPartIds(store);
154173
+ return names.filter((name) => name.startsWith("self-pay-")).map((name) => name.slice("self-pay-".length)).filter((unshieldId) => !unshieldId.startsWith("merge-") && !/^pocket-\d+-f\d+$/.test(unshieldId)).map((unshieldId) => {
154174
+ const record = read(`self-pay-${unshieldId}`);
154175
+ return { unshieldId, record, resumable: terminalSendResumable(store, unshieldId, record, partIds) };
154176
+ }).filter(({ record, resumable }) => resumable || record?.schema === SELF_PAY_WAL_SCHEMA && record.state === "paid" && /^[1-9][0-9]*$/.test(String(record.amountAtomic ?? "")) && (record.mode === DIRECT_EXIT_MODE ? record.mcpTo === void 0 : record.ownerUnshield === true)).map(({ unshieldId, record, resumable }) => {
154052
154177
  const to = typeof record.exitRecipientOwner === "string" ? record.exitRecipientOwner : typeof record.sendTo === "string" ? record.sendTo : void 0;
154053
154178
  return {
154054
154179
  unshieldId,
@@ -154057,9 +154182,9 @@ function unfinishedUnshields(store) {
154057
154182
  answered: Number.isSafeInteger(record.exitAnsweredAtMs) && typeof record.exitTransaction === "string",
154058
154183
  ...typeof record.exitTransaction === "string" ? { exitTransaction: record.exitTransaction } : {},
154059
154184
  ...to !== void 0 ? { to } : {},
154060
- // UX130-1: a plain unshield finishes it first (resumeOpenUnshields): this terminal's own self-payment unshield, not a
154061
- // direct exit, not a part of a planned send, and not a send an agent app started (mcpTo: the MCP finishes its own).
154062
- resumable: record.mode === void 0 && record.mcpTo === void 0 && !partIds.has(unshieldId),
154185
+ // UX130-1, UX130-10: a plain unshield finishes it first (resumeOpenUnshields): this terminal's own send, a
154186
+ // self-payment unshield or a direct exit, paid or stopped after it signed (terminalSendResumable).
154187
+ resumable,
154063
154188
  startedAtMs: Number.isSafeInteger(record.createdAtMs) ? record.createdAtMs : 0
154064
154189
  };
154065
154190
  }).sort((a, b) => a.startedAtMs - b.startedAtMs).map(({ startedAtMs: _at, ...one }) => one);
@@ -154600,7 +154725,9 @@ async function runLimits(values, deps, io) {
154600
154725
  ` all payments ${limitText(config.maxCumulativeAtomic)} (paid so far: ${usdcText4(String(config.spentCumulativeAtomic ?? "0"))} USDC)`,
154601
154726
  ...leftLines,
154602
154727
  ...aiLine,
154603
- "Close and open your agent app so the wallet reads them.",
154728
+ // UX130-12: an agent app that runs from config.json reads them at its next payment (spendPolicy.mjs limitsNow); a limit
154729
+ // typed in its wallet entry stays as typed there.
154730
+ "Your agent app uses them from its next payment (a limit typed in its wallet entry stays as it is there).",
154604
154731
  ""
154605
154732
  ].join("\n"));
154606
154733
  return;