shinjuku-shield 0.3.220 → 0.3.222

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
@@ -5,12 +5,12 @@ web services and AI answers from your private balance, so the payment does
5
5
  not show who paid. It works inside your AI app (Claude, Cursor, Codex) and in
6
6
  a terminal. Only you hold the keys: they never leave your computer.
7
7
 
8
- This is version 0.3.220. The command is `shinjuku`.
8
+ This is version 0.3.222. The command is `shinjuku`.
9
9
 
10
10
  ## Set up
11
11
 
12
12
  ```sh
13
- npx -y shinjuku@0.3.220 setup
13
+ npx -y shinjuku@0.3.222 setup
14
14
  ```
15
15
 
16
16
  Setup does every step for you:
@@ -100,7 +100,7 @@ Add it yourself. The name of the wallet in your app is `shinjuku`.
100
100
  Claude Code:
101
101
 
102
102
  ```sh
103
- claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.220 mcp
103
+ claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.222 mcp
104
104
  ```
105
105
 
106
106
  ## For builders: check what you install
@@ -116,7 +116,7 @@ with the Releases table in
116
116
  Versions are published from GitHub Actions with npm provenance.
117
117
 
118
118
  `shinjuku-shield` is the package that holds the wallet. `shinjuku-shielded`
119
- 0.3.220, its older name, runs this package at the same version, so wallets
119
+ 0.3.222, its older name, runs this package at the same version, so wallets
120
120
  installed under that name keep updating. New installs use `shinjuku`.
121
121
 
122
122
  The full guide is
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": "a910db1e1c876a207fdc040c809315913121206f32723a9d87192c8a75a7823c",
5
- "bytes": 10294711,
6
- "sourceCommit": "a4a5fa17d6f6c9ef6009c96dfdb3255bcd674e72",
4
+ "sha256": "a2402ed74f220f3e905e948b89b40c954b82b7dfe205a190256513a3b530976a",
5
+ "bytes": 10301256,
6
+ "sourceCommit": "af208b57f4e1150cd0770d9cbfdc232c90bf7372",
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",
@@ -1075,8 +1075,8 @@
1075
1075
  ],
1076
1076
  "seller": {
1077
1077
  "file": "shinjuku-seller.mjs",
1078
- "sha256": "7e40398886e63df2a3981ac6603e19ff0772b5c86162e65e64ac1f5c0a7dce32",
1079
- "bytes": 4182275,
1078
+ "sha256": "0278f5d89c7b8a73482c5e156f7c28a96ece6b4746aca02626447e79cd55d815",
1079
+ "bytes": 4184815,
1080
1080
  "entry": "wallet/src/seller/exact/index.mjs",
1081
1081
  "external": [
1082
1082
  "@x402/core/http",
@@ -1968,5 +1968,5 @@
1968
1968
  }
1969
1969
  ]
1970
1970
  },
1971
- "publishedAt": "2026-11-12T15:31:01.378Z"
1971
+ "publishedAt": "2026-11-12T16:40:00.515Z"
1972
1972
  }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "shinjuku-shield",
3
- "version": "0.3.220",
3
+ "version": "0.3.222",
4
4
  "mcpName": "io.github.ShinjukuStaition/shinjuku-shield",
5
5
  "description": "Shinjuku Shield, private x402 payments 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": "a910db1e",
7
- "shinjukuSha256": "a910db1e1c876a207fdc040c809315913121206f32723a9d87192c8a75a7823c",
6
+ "shinjukuRelease": "a2402ed7",
7
+ "shinjukuSha256": "a2402ed74f220f3e905e948b89b40c954b82b7dfe205a190256513a3b530976a",
8
8
  "license": "SEE LICENSE IN LICENSE.txt",
9
9
  "author": "Shinjuku Shield",
10
10
  "homepage": "https://github.com/ShinjukuStaition/shinjuku-shield#readme",
@@ -45162,6 +45162,8 @@ var init_errorCodes = __esm({
45162
45162
  // A damaged config.json (row 78): the setup-mode server repairs it and keeps the wallet (cli runMcpFirstRun).
45163
45163
  "mcp_config_damaged",
45164
45164
  "setup_tor_unavailable",
45165
+ // The agent-app setup's own Tor did not start before setup ran (cli mcpSetupBehindTor; nothing ran).
45166
+ "setup_tor_not_started",
45165
45167
  // The wallet server behind Tor that the setup server starts after a Tor setup (stdioServer.mjs startTorRelay).
45166
45168
  "setup_tor_wallet_ended",
45167
45169
  "setup_tor_wallet_slow",
@@ -79435,7 +79437,7 @@ init_timing();
79435
79437
  import { spawn as spawn3, spawnSync as spawnSync3 } from "node:child_process";
79436
79438
  import { createHash as createHash27, createHmac as createHmac12, randomBytes as randomBytes17, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
79437
79439
  import net3 from "node:net";
79438
- import { basename as basename6, dirname as dirname20, join as join24 } from "node:path";
79440
+ import { basename as basename6, dirname as dirname20, join as join24, sep as sep3 } from "node:path";
79439
79441
  import { Readable } from "node:stream";
79440
79442
  import { pipeline } from "node:stream/promises";
79441
79443
  var ownTorPlatform = (platform = process.platform, arch = process.arch) => platform === "win32" || platform === "darwin" || platform === "linux" && arch === "x64";
@@ -79977,7 +79979,7 @@ async function installBundle(home, say) {
79977
79979
  say(`Getting Tor for the wallet (once, about ${pinned.mb} MB from the Tor Project, checked).`);
79978
79980
  let response;
79979
79981
  try {
79980
- response = await fetch(pinned.url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
79982
+ response = await fetch(pinned.url, { redirect: "error", signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
79981
79983
  } catch (error) {
79982
79984
  throw failure("the Tor download did not finish. Check the internet connection, then ask again", `the Tor download did not answer (${error?.name === "TimeoutError" ? "no answer in 5 minutes" : error?.cause?.code ?? error?.message ?? error})`);
79983
79985
  }
@@ -80353,15 +80355,76 @@ async function ownTorReady(home, state2, { wait = true, deadline } = {}) {
80353
80355
  }
80354
80356
  return tunnelOf(state2.port);
80355
80357
  }
80356
- function ownPortOf(home) {
80357
- const state2 = managedTorState(home);
80358
- if (state2) return state2.port;
80359
- if (!bundleComplete(home) && !existsSync(join24(managedTorDir(home), "torrc"))) return void 0;
80358
+ var NOTICE_READ_MAX = 2 * 1024 * 1024;
80359
+ var TUNNEL_LISTENER_LINE = /^[A-Z][a-z]{2} [ 0-9]?[0-9] [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3} \[notice\] Opened HTTP tunnel listener (?:connection \(ready\) )?on 127\.0\.0\.1:([0-9]{1,5})\r?$/gm;
80360
+ function readHomeFileTail(home, path, max) {
80361
+ try {
80362
+ const kind = lstatSync(path);
80363
+ if (!kind.isFile()) return void 0;
80364
+ if (!realpathSync(path).startsWith(`${realpathSync(home)}${sep3}`)) return void 0;
80365
+ const length = Math.min(kind.size, max);
80366
+ const bytes2 = Buffer.alloc(length);
80367
+ const fd = openSync(path, "r");
80368
+ try {
80369
+ readSync(fd, bytes2, 0, length, kind.size - length);
80370
+ } finally {
80371
+ closeSync(fd);
80372
+ }
80373
+ return bytes2.toString("utf8");
80374
+ } catch {
80375
+ return void 0;
80376
+ }
80377
+ }
80378
+ function loggedTunnelPorts(home) {
80379
+ const ports = /* @__PURE__ */ new Set();
80380
+ const text2 = readHomeFileTail(home, logFile(home), NOTICE_READ_MAX);
80381
+ if (text2 === void 0) return ports;
80382
+ for (const match of text2.matchAll(TUNNEL_LISTENER_LINE)) {
80383
+ const port = Number(match[1]);
80384
+ if (port > 0 && port < 65536) ports.add(port);
80385
+ }
80386
+ return ports;
80387
+ }
80388
+ var ownPortsFile = (home) => join24(managedTorDir(home), "own-ports.json");
80389
+ var OWN_PORTS_MAX = 256;
80390
+ var OWN_PORTS_READ_MAX = 16 * 1024;
80391
+ function recordedOwnPorts(home) {
80392
+ const text2 = readHomeFileTail(home, ownPortsFile(home), OWN_PORTS_READ_MAX + 1);
80393
+ if (text2 === void 0 || text2.length > OWN_PORTS_READ_MAX) return void 0;
80394
+ let parsed;
80360
80395
  try {
80361
- return Number(new URL(readSetupConfig(home)?.torTunnel ?? "").port) || void 0;
80396
+ parsed = JSON.parse(text2);
80362
80397
  } catch {
80363
80398
  return void 0;
80364
80399
  }
80400
+ if (!Array.isArray(parsed?.ports) || !parsed.ports.every((port) => Number.isInteger(port) && port > 0 && port < 65536)) return void 0;
80401
+ return parsed.ports;
80402
+ }
80403
+ function recordOwnPort(home, port) {
80404
+ try {
80405
+ const path = ownPortsFile(home);
80406
+ const known = recordedOwnPorts(home);
80407
+ if (known === void 0 && existsSync(path) && !lstatSync(path).isFile()) return;
80408
+ if (known?.includes(port)) return;
80409
+ writeAtomic(path, `${JSON.stringify({ ports: [...known ?? [], port].slice(-OWN_PORTS_MAX) })}
80410
+ `);
80411
+ } catch {
80412
+ }
80413
+ }
80414
+ function ownTunnelPort(home, tunnel) {
80415
+ let url;
80416
+ try {
80417
+ url = new URL(tunnel);
80418
+ } catch {
80419
+ return void 0;
80420
+ }
80421
+ if (url.protocol !== "http:" || url.hostname !== "127.0.0.1") return void 0;
80422
+ const port = Number(url.port);
80423
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) return void 0;
80424
+ const state2 = managedTorState(home);
80425
+ if (state2) return state2.port === port ? port : void 0;
80426
+ if (recordedOwnPorts(home)?.includes(port)) return port;
80427
+ return loggedTunnelPorts(home).has(port) ? port : void 0;
80365
80428
  }
80366
80429
  async function ensureWalletTor(proxy, { env = process.env, platform = process.platform, explicit = false, say = () => {
80367
80430
  } } = {}) {
@@ -80373,14 +80436,15 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
80373
80436
  return proxy;
80374
80437
  }
80375
80438
  const home = setupHome(env);
80376
- const ownPort = ownPortOf(home);
80377
- if (explicit && Number(url.port) !== ownPort) return proxy;
80439
+ const ownPort = explicit ? ownTunnelPort(home, proxy) : void 0;
80440
+ if (explicit && ownPort === void 0) return proxy;
80378
80441
  let deadline = Date.now() + BOOTSTRAP_MAX_MS;
80379
80442
  const timeLeft = () => deadline - Date.now();
80380
80443
  try {
80381
80444
  const known = managedTorState(home);
80382
80445
  const ready = await ownTorReady(home, known, { wait: false });
80383
80446
  if (ready && await processLockFree(lockName(home)) && pidAlive3(known.pid)) {
80447
+ recordOwnPort(home, known.port);
80384
80448
  await recordTunnel(home, ready, deadline);
80385
80449
  return ready;
80386
80450
  }
@@ -80395,6 +80459,7 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
80395
80459
  if (!(error?.stalled === true && timeLeft() >= RESTART_MIN_MS)) throw error;
80396
80460
  }
80397
80461
  if (again) {
80462
+ recordOwnPort(home, state2.port);
80398
80463
  await recordTunnel(home, again, deadline);
80399
80464
  return again;
80400
80465
  }
@@ -80425,6 +80490,7 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
80425
80490
  if (timeLeft() < RESTART_MIN_MS) throw noTimeLeft();
80426
80491
  try {
80427
80492
  await startTor(home, port, say, assertHeld, deadline);
80493
+ recordOwnPort(home, port);
80428
80494
  await recordTunnel(home, tunnelOf(port), deadline);
80429
80495
  return tunnelOf(port);
80430
80496
  } catch (error) {
@@ -80450,10 +80516,8 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
80450
80516
  setTunnelCircuitProbe(async ({ proxyHost, proxyPort } = {}) => {
80451
80517
  if (String(proxyHost) !== "127.0.0.1") return void 0;
80452
80518
  const home = setupHome(process.env);
80453
- const port = ownPortOf(home);
80454
- if (!Number.isInteger(port) || Number(proxyPort) !== port) return void 0;
80455
80519
  const state2 = managedTorState(home);
80456
- if (!state2 || state2.port !== port) return void 0;
80520
+ if (!state2 || Number(proxyPort) !== state2.port) return void 0;
80457
80521
  const answer = await controlCheck(home, state2, { circuits: true, unref: true });
80458
80522
  return answer && answer.tunnelPort === Number(proxyPort) ? answer.circuits : void 0;
80459
80523
  });
@@ -80646,11 +80710,12 @@ function proxyDispatcherClass() {
80646
80710
  async function sellerTor(recorded, home) {
80647
80711
  let tunnel = recorded;
80648
80712
  if (home) {
80649
- const current = readSetupConfig(home)?.torTunnel ?? recorded;
80713
+ const walletRecorded = readSetupConfig(home)?.torTunnel;
80714
+ const current = walletRecorded ?? recorded;
80650
80715
  try {
80651
80716
  tunnel = await ensureWalletTor(current, {
80652
80717
  env: { ...process.env, SHIELDED_WALLET_HOME: home },
80653
- explicit: true,
80718
+ explicit: walletRecorded !== void 0,
80654
80719
  say: (line) => process.stderr.write(`${line}
80655
80720
  `)
80656
80721
  });
@@ -80865,6 +80865,8 @@ var init_errorCodes = __esm({
80865
80865
  // A damaged config.json (row 78): the setup-mode server repairs it and keeps the wallet (cli runMcpFirstRun).
80866
80866
  "mcp_config_damaged",
80867
80867
  "setup_tor_unavailable",
80868
+ // The agent-app setup's own Tor did not start before setup ran (cli mcpSetupBehindTor; nothing ran).
80869
+ "setup_tor_not_started",
80868
80870
  // The wallet server behind Tor that the setup server starts after a Tor setup (stdioServer.mjs startTorRelay).
80869
80871
  "setup_tor_wallet_ended",
80870
80872
  "setup_tor_wallet_slow",
@@ -123884,8 +123886,13 @@ function build(a, tool, npmVersion) {
123884
123886
  if (tool === "find_paid_services" || tool === void 0 && Array.isArray(a.results) && typeof a.query === "string") return discoverSay(a);
123885
123887
  if (a.paid === false && a.replayed === true) return "Here is the same answer as before. Nothing was paid: the earlier payment for it never went through.";
123886
123888
  if (a.paid === true) {
123887
- const unconfirmed = a.receiptFinality === "pending" ? " The chain does not show the payment to the seller yet." : "";
123888
- if (a.replayed === true) return `This request was already paid. Here is the same answer; nothing new was paid.${unconfirmed}`;
123889
+ const unconfirmed = a.receiptFinality === "pending" ? " This wallet has not seen the payment to the seller on the chain yet." : "";
123890
+ if (a.replayed === true) {
123891
+ return firstFit(
123892
+ `This request was already paid. Here is the same answer; nothing new was paid.${unconfirmed}`,
123893
+ `Already paid: here is the same answer, nothing new was paid.${unconfirmed}`
123894
+ );
123895
+ }
123889
123896
  if (tool === "inference_chat" || typeof a.model === "string" && Object.hasOwn(a, "content")) {
123890
123897
  const paid = usdcText2(a.paidAtomic);
123891
123898
  const price3 = usdcText2(a.priceAtomic);
@@ -123899,7 +123906,7 @@ function build(a, tool, npmVersion) {
123899
123906
  if (!total) return withBalance(`Paid. Here is the answer.${unconfirmed}`, a);
123900
123907
  if (price2 && positive(fee)) {
123901
123908
  const paid = `Paid ${total} USDC (${price2} price + ${fee} Shinjuku fee).`;
123902
- return withBalance([`${paid} Here is the answer.${unconfirmed}`, `${paid}${unconfirmed}`], a);
123909
+ return withBalance([`${paid} Here is the answer.${unconfirmed}`, `${paid}${unconfirmed}`].filter((line, index, all) => words(line) <= SAY_MAX_WORDS || index === all.length - 1), a);
123903
123910
  }
123904
123911
  return withBalance(`Paid ${total} USDC. Here is the answer.${unconfirmed}`, a);
123905
123912
  }
@@ -139023,7 +139030,7 @@ function cloudPlace(place, { platform = process.platform, env = process.env, hom
139023
139030
  const text3 = String(place ?? "").trim();
139024
139031
  if (!text3) return void 0;
139025
139032
  const fold = platform === "win32" || platform === "darwin";
139026
- const sep6 = platform === "win32" ? "\\" : "/";
139033
+ const sep7 = platform === "win32" ? "\\" : "/";
139027
139034
  const norm = (path) => {
139028
139035
  const full = (platform === "win32" ? resolve26(localForm(path, platform)) : posix.resolve(path)).replace(/[\\/]+$/, "");
139029
139036
  return fold ? full.toLowerCase() : full;
@@ -139031,7 +139038,7 @@ function cloudPlace(place, { platform = process.platform, env = process.env, hom
139031
139038
  const at = norm(text3);
139032
139039
  for (const root of (roots ?? (() => cloudRoots({ platform, env, home })))()) {
139033
139040
  const base = norm(root.path);
139034
- if (base && (at === base || at.startsWith(`${base}${sep6}`))) return root.service;
139041
+ if (base && (at === base || at.startsWith(`${base}${sep7}`))) return root.service;
139035
139042
  }
139036
139043
  for (const part of text3.split(/[\\/]+/).map((name) => name.trim().toLowerCase())) {
139037
139044
  if (part === "onedrive" || part.startsWith("onedrive - ") || part.startsWith("onedrive-")) return "OneDrive";
@@ -142109,7 +142116,7 @@ function leg1Transaction(store, float, requestId) {
142109
142116
  }
142110
142117
  function floatPaidNext({ transaction, shinjukuTransaction, pending = false }) {
142111
142118
  if (pending) {
142112
- return "the seller answered with its data, and this wallet's private payment to Shinjuku is done; Shinjuku's payment to the seller is not seen on the public chain yet. Tell the user: the data came; the payment is not confirmed on the chain yet; wallet_receipts shows its state. Tell the user the price (priceAtomic), the Shinjuku fee (feeAtomic; never a network fee) and the total (amountAtomic). Do not pay this again: it is one payment. wallet_balance shows the new balance";
142119
+ return "the seller answered with its data, and this wallet's private payment to Shinjuku is done; this wallet has not yet seen Shinjuku's payment to the seller on the public chain (a quick check; the chain can already hold it). Tell the user: the data came; this wallet has not seen the payment to the seller on the chain yet; wallet_receipts shows its state. Tell the user the price (priceAtomic), the Shinjuku fee (feeAtomic; never a network fee) and the total (amountAtomic). Do not pay this again: it is one payment. wallet_balance shows the new balance";
142113
142120
  }
142114
142121
  const ids = [
142115
142122
  transaction ? "the transaction (the seller's settle transaction)" : void 0,
@@ -145174,7 +145181,7 @@ ${canonical5}`;
145174
145181
  requestId,
145175
145182
  scheme: receipt.scheme ?? null,
145176
145183
  // AB249 live run 2 (echomarkets, 2026-11-07): a pending receipt named the seller's claimed signature as its
145177
- // transaction. Until the chain shows it, it is only sellerClaimedTransaction.
145184
+ // transaction. Until this wallet sees it confirmed, it is only sellerClaimedTransaction.
145178
145185
  ...floatPaid && receipt.receiptFinality === "pending" ? { transaction: null, ...transaction ? { sellerClaimedTransaction: transaction } : {} } : { transaction: unpaid ? null : transaction },
145179
145186
  ...amounts,
145180
145187
  replayed: receipt.replayed === true,
@@ -147346,7 +147353,7 @@ ${canonical5}`;
147346
147353
  scheme: "exact",
147347
147354
  state: "payment_not_confirmed",
147348
147355
  ...claimed ? { sellerClaimedTransaction: claimed } : {},
147349
- note: "the seller answered with its data, but the public chain does not show Shinjuku's payment to the seller yet. Each wallet_receipts call reads it again: when it lands, this row shows the seller's transaction; if it can never land, this row shows a refund. Do not pay for this again with a new request_id until then"
147356
+ note: "the seller answered with its data, but this wallet has not seen Shinjuku's payment to the seller on the public chain yet. Each wallet_receipts call reads it again: when it lands, this row shows the seller's transaction; if it can never land, this row shows a refund. Do not pay for this again with a new request_id until then"
147350
147357
  });
147351
147358
  continue;
147352
147359
  }
@@ -148141,7 +148148,7 @@ ${canonical5}`;
148141
148148
  const record = float ? void 0 : [paymentRecordName(target), `${POCKET_PAYMENT_WAL_PREFIX}${key}`].map((name) => store.readWal(name)).find((one) => one?.state === "receipt" && one.receiptFinality !== "never-finalized");
148142
148149
  if (float && floatReceiptPending(float)) {
148143
148150
  return json4({
148144
- say: "The seller already answered this payment, so there is nothing to cancel. The public chain does not show the payment to the seller yet; wallet_receipts shows it when it does.",
148151
+ say: "The seller already answered this payment, so there is nothing to cancel. This wallet has not seen the payment to the seller on the chain yet.",
148145
148152
  ok: true,
148146
148153
  requestId,
148147
148154
  kind: "payment",
@@ -148149,7 +148156,7 @@ ${canonical5}`;
148149
148156
  finished: true,
148150
148157
  transaction: null,
148151
148158
  receiptFinality: "pending",
148152
- detail: "the seller answered this payment, so there is nothing to cancel; the public chain does not show Shinjuku's payment to the seller yet",
148159
+ detail: "the seller answered this payment, so there is nothing to cancel; this wallet has not seen Shinjuku's payment to the seller on the public chain yet (wallet_receipts reads it again)",
148153
148160
  next: "Tell the user the seller already answered, so there is nothing to cancel; nothing was changed. Do not pay for it again. wallet_receipts shows whether the payment to the seller landed or a refund comes"
148154
148161
  });
148155
148162
  }
@@ -148166,7 +148173,7 @@ ${canonical5}`;
148166
148173
  finished: true,
148167
148174
  transaction,
148168
148175
  ...typeof record?.receiptFinality === "string" ? { receiptFinality: record.receiptFinality } : {},
148169
- detail: `this payment is finished and paid${transaction ? ` (transaction ${transaction})` : ""}${final ? "" : "; the seller answered and the chain has not made it final yet"}; there is nothing to cancel, and a payment a seller took cannot be taken back`,
148176
+ detail: `this payment is finished and paid${transaction ? ` (transaction ${transaction})` : ""}${final ? "" : "; the seller answered and this wallet has not seen it final on the chain yet"}; there is nothing to cancel, and a payment a seller took cannot be taken back`,
148170
148177
  next: "Tell the user the payment is finished and paid; nothing was changed. wallet_receipts lists it"
148171
148178
  });
148172
148179
  }
@@ -153852,6 +153859,25 @@ function createSetupTools({
153852
153859
  return out;
153853
153860
  }
153854
153861
  function statusOf(current, end2) {
153862
+ if (current.state === "failed" && current.ownTor === true && current.failure?.error === "setup_tor_not_started") {
153863
+ const recoveryFile = current.recoveryFile;
153864
+ end2();
153865
+ const reason = String(current.failure.detail ?? "").split("nothing was sent: ")[1]?.trim().replace(/\.$/, "") ?? "";
153866
+ const download3 = /^the Tor download/.test(reason);
153867
+ const what = download3 ? "the Tor download for the wallet did not finish" : "Tor did not start on this computer";
153868
+ return refuse11(
153869
+ "setup_tor_not_started",
153870
+ `the user chose Tor in the setup question, and the wallet's own Tor ${download3 ? "could not be downloaded" : "did not start"}${reason ? ` (${reason})` : ""}; ${recoveryFile ? "the wallet an earlier setup made stays as it is; nothing was paid" : "nothing was created or paid"}`,
153871
+ `Tell the user: ${reason ? `${reason[0].toUpperCase()}${reason.slice(1)}` : download3 ? "The wallet could not download Tor" : "Tor did not start on this computer"}. ` + (recoveryFile ? `Nothing was paid. The wallet was already made: tell the user to copy its recovery file (${recoveryFile}) to two offline places now. ` : "Nothing was created or paid. ") + `When the user asks again, call shinjuku_setup again: it tries Tor again (a Tor download that finished and passed its check is kept; an unfinished one starts again). Or, to set up without Tor, the user asks again and unticks "${SETUP_TOR_TITLE}" in the question`,
153872
+ recoveryFile ? { recoveryFile, say: fitSay([
153873
+ `Not set up: ${what}. Your wallet was made earlier: copy its recovery file ${recoveryFile} to two offline places now. Then ask me again, or set up without Tor.`,
153874
+ `Not set up: ${what}. Your wallet was made earlier: copy its recovery file (named below) to two offline places now. Then ask me again, or set up without Tor.`
153875
+ ]) } : { say: fitSay([
153876
+ `Not set up: ${what}. Nothing was created. Ask me again, or set up without Tor.`,
153877
+ `Not set up: ${download3 ? "the Tor download failed" : "Tor did not start"}. Ask me again, or set up without Tor.`
153878
+ ]) }
153879
+ );
153880
+ }
153855
153881
  if (current.state === "failed") {
153856
153882
  const { error, detail } = current.failure;
153857
153883
  const recoveryFile = current.recoveryFile;
@@ -154076,8 +154102,11 @@ function createSetupTools({
154076
154102
  answered2();
154077
154103
  return;
154078
154104
  }
154079
- if (answer.tor && !inTorRun()) {
154080
- const tunnel = await localTorCheck(TOR_HTTP_TUNNEL);
154105
+ const ownTor = setup.ownTor?.() === true;
154106
+ job.ownTor = ownTor && answer.tor && !inTorRun();
154107
+ if (answer.tor && !inTorRun() && !ownTor) {
154108
+ const probed = setup.torTunnel?.() ?? TOR_HTTP_TUNNEL;
154109
+ const tunnel = await localTorCheck(probed);
154081
154110
  if (tunnel.answer === "refused" || tunnel.answer === "too_old") {
154082
154111
  if (tunnel.answer === "refused") job.torBrowser = await localTorProof(TOR_BROWSER_PORT) !== "refused";
154083
154112
  else job.torTooOld = tunnel.version;
@@ -161711,7 +161740,7 @@ ${words2}`;
161711
161740
  import { spawn as spawn11, spawnSync as spawnSync9 } from "node:child_process";
161712
161741
  import { createHash as createHash43, createHmac as createHmac15, randomBytes as randomBytes44, timingSafeEqual as timingSafeEqual6 } from "node:crypto";
161713
161742
  import net3 from "node:net";
161714
- import { basename as basename12, dirname as dirname42, join as join51 } from "node:path";
161743
+ import { basename as basename12, dirname as dirname42, join as join51, sep as sep6 } from "node:path";
161715
161744
  import { Readable } from "node:stream";
161716
161745
  import { pipeline } from "node:stream/promises";
161717
161746
  function bootstrapProgress(text3) {
@@ -162136,7 +162165,7 @@ async function installBundle(home, say2) {
162136
162165
  say2(`Getting Tor for the wallet (once, about ${pinned.mb} MB from the Tor Project, checked).`);
162137
162166
  let response;
162138
162167
  try {
162139
- response = await fetch(pinned.url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
162168
+ response = await fetch(pinned.url, { redirect: "error", signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
162140
162169
  } catch (error) {
162141
162170
  throw failure2("the Tor download did not finish. Check the internet connection, then ask again", `the Tor download did not answer (${error?.name === "TimeoutError" ? "no answer in 5 minutes" : error?.cause?.code ?? error?.message ?? error})`);
162142
162171
  }
@@ -162511,16 +162540,75 @@ async function ownTorReady(home, state2, { wait: wait2 = true, deadline } = {})
162511
162540
  }
162512
162541
  return tunnelOf(state2.port);
162513
162542
  }
162514
- function ownPortOf(home) {
162515
- const state2 = managedTorState(home);
162516
- if (state2) return state2.port;
162517
- if (!bundleComplete(home) && !existsSync(join51(managedTorDir(home), "torrc"))) return void 0;
162543
+ function readHomeFileTail(home, path, max) {
162518
162544
  try {
162519
- return Number(new URL(readSetupConfig(home)?.torTunnel ?? "").port) || void 0;
162545
+ const kind = lstatSync(path);
162546
+ if (!kind.isFile()) return void 0;
162547
+ if (!realpathSync(path).startsWith(`${realpathSync(home)}${sep6}`)) return void 0;
162548
+ const length = Math.min(kind.size, max);
162549
+ const bytes2 = Buffer.alloc(length);
162550
+ const fd = openSync(path, "r");
162551
+ try {
162552
+ readSync(fd, bytes2, 0, length, kind.size - length);
162553
+ } finally {
162554
+ closeSync(fd);
162555
+ }
162556
+ return bytes2.toString("utf8");
162520
162557
  } catch {
162521
162558
  return void 0;
162522
162559
  }
162523
162560
  }
162561
+ function loggedTunnelPorts(home) {
162562
+ const ports = /* @__PURE__ */ new Set();
162563
+ const text3 = readHomeFileTail(home, logFile(home), NOTICE_READ_MAX);
162564
+ if (text3 === void 0) return ports;
162565
+ for (const match of text3.matchAll(TUNNEL_LISTENER_LINE)) {
162566
+ const port = Number(match[1]);
162567
+ if (port > 0 && port < 65536) ports.add(port);
162568
+ }
162569
+ return ports;
162570
+ }
162571
+ function recordedOwnPorts(home) {
162572
+ const text3 = readHomeFileTail(home, ownPortsFile(home), OWN_PORTS_READ_MAX + 1);
162573
+ if (text3 === void 0 || text3.length > OWN_PORTS_READ_MAX) return void 0;
162574
+ let parsed2;
162575
+ try {
162576
+ parsed2 = JSON.parse(text3);
162577
+ } catch {
162578
+ return void 0;
162579
+ }
162580
+ if (!Array.isArray(parsed2?.ports) || !parsed2.ports.every((port) => Number.isInteger(port) && port > 0 && port < 65536)) return void 0;
162581
+ return parsed2.ports;
162582
+ }
162583
+ function recordOwnPort(home, port) {
162584
+ try {
162585
+ const path = ownPortsFile(home);
162586
+ const known = recordedOwnPorts(home);
162587
+ if (known === void 0 && existsSync(path) && !lstatSync(path).isFile()) return;
162588
+ if (known?.includes(port)) return;
162589
+ writeAtomic5(path, `${JSON.stringify({ ports: [...known ?? [], port].slice(-OWN_PORTS_MAX) })}
162590
+ `);
162591
+ } catch {
162592
+ }
162593
+ }
162594
+ function ownTunnelPort(home, tunnel) {
162595
+ let url;
162596
+ try {
162597
+ url = new URL(tunnel);
162598
+ } catch {
162599
+ return void 0;
162600
+ }
162601
+ if (url.protocol !== "http:" || url.hostname !== "127.0.0.1") return void 0;
162602
+ const port = Number(url.port);
162603
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) return void 0;
162604
+ const state2 = managedTorState(home);
162605
+ if (state2) return state2.port === port ? port : void 0;
162606
+ if (recordedOwnPorts(home)?.includes(port)) return port;
162607
+ return loggedTunnelPorts(home).has(port) ? port : void 0;
162608
+ }
162609
+ function isWalletOwnTunnel(home, tunnel) {
162610
+ return ownTunnelPort(home, tunnel) !== void 0;
162611
+ }
162524
162612
  async function setWalletTor(home, on, { say: say2 = () => {
162525
162613
  }, platform = process.platform } = {}) {
162526
162614
  let config;
@@ -162535,13 +162623,7 @@ async function setWalletTor(home, on, { say: say2 = () => {
162535
162623
  return { tor: false, agentAppRestart: true };
162536
162624
  }
162537
162625
  const recorded = config.torTunnel;
162538
- let recordedPort;
162539
- try {
162540
- recordedPort = recorded ? Number(new URL(recorded).port) : void 0;
162541
- } catch {
162542
- recordedPort = void 0;
162543
- }
162544
- const explicit = recorded !== void 0 && recordedPort !== ownPortOf(home);
162626
+ const explicit = recorded !== void 0 && ownTunnelPort(home, recorded) === void 0;
162545
162627
  const tunnel = await ensureWalletTor(recorded ?? TOR_HTTP_TUNNEL, { env: { ...process.env, SHIELDED_WALLET_HOME: home }, platform, explicit, say: say2 });
162546
162628
  if (!ownTorPlatform(platform) || explicit) {
162547
162629
  let now;
@@ -162565,14 +162647,15 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
162565
162647
  return proxy;
162566
162648
  }
162567
162649
  const home = setupHome(env);
162568
- const ownPort = ownPortOf(home);
162569
- if (explicit && Number(url.port) !== ownPort) return proxy;
162650
+ const ownPort = explicit ? ownTunnelPort(home, proxy) : void 0;
162651
+ if (explicit && ownPort === void 0) return proxy;
162570
162652
  let deadline = Date.now() + BOOTSTRAP_MAX_MS;
162571
162653
  const timeLeft = () => deadline - Date.now();
162572
162654
  try {
162573
162655
  const known = managedTorState(home);
162574
162656
  const ready = await ownTorReady(home, known, { wait: false });
162575
162657
  if (ready && await processLockFree(lockName(home)) && pidAlive5(known.pid)) {
162658
+ recordOwnPort(home, known.port);
162576
162659
  await recordTunnel(home, ready, deadline);
162577
162660
  return ready;
162578
162661
  }
@@ -162587,6 +162670,7 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
162587
162670
  if (!(error?.stalled === true && timeLeft() >= RESTART_MIN_MS)) throw error;
162588
162671
  }
162589
162672
  if (again) {
162673
+ recordOwnPort(home, state2.port);
162590
162674
  await recordTunnel(home, again, deadline);
162591
162675
  return again;
162592
162676
  }
@@ -162617,6 +162701,7 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
162617
162701
  if (timeLeft() < RESTART_MIN_MS) throw noTimeLeft();
162618
162702
  try {
162619
162703
  await startTor(home, port, say2, assertHeld, deadline);
162704
+ recordOwnPort(home, port);
162620
162705
  await recordTunnel(home, tunnelOf(port), deadline);
162621
162706
  return tunnelOf(port);
162622
162707
  } catch (error) {
@@ -162706,7 +162791,7 @@ function startTorTimingMarks() {
162706
162791
  }
162707
162792
  });
162708
162793
  }
162709
- var ownTorPlatform, MAC, LINUX, SYSTEM2, bundle, managedTorDir, stateFile, bundleDir, torExe, MAC_SIGNED, COMPLETE, LINUX_TOR, BUNDLE_FILES, logFile, BOOTSTRAP_STALL_MS, BOOTSTRAP_MAX_MS, STALL_RESTART_PERCENT, RESTART_MIN_MS, REACHED_RELAY_PERCENT, phaseWords, DOWNLOAD_TIMEOUT_MS, BIND_TRIES, POLL_MS2, pidAlive5, WIN_OWN_TOR, STOP_WAIT_MS, cookieFile, CONTROL_TIMEOUT_MS, SERVER_KEY, CLIENT_KEY, failure2, sleep4, tunnelOf, bundleComplete, LINUX_HASHES, fileSha256, startErrorsFile, EVENT_LINE_MAX, TOR_TIMING_MAX, HS_DESC_ACTIONS, HS_DESC_REASONS, CIRC_STATUSES, CIRC_PURPOSES, CIRC_HS_STATES, CIRC_REASONS;
162794
+ var ownTorPlatform, MAC, LINUX, SYSTEM2, bundle, managedTorDir, stateFile, bundleDir, torExe, MAC_SIGNED, COMPLETE, LINUX_TOR, BUNDLE_FILES, logFile, BOOTSTRAP_STALL_MS, BOOTSTRAP_MAX_MS, STALL_RESTART_PERCENT, RESTART_MIN_MS, REACHED_RELAY_PERCENT, phaseWords, DOWNLOAD_TIMEOUT_MS, BIND_TRIES, POLL_MS2, pidAlive5, WIN_OWN_TOR, STOP_WAIT_MS, cookieFile, CONTROL_TIMEOUT_MS, SERVER_KEY, CLIENT_KEY, failure2, sleep4, tunnelOf, bundleComplete, LINUX_HASHES, fileSha256, startErrorsFile, NOTICE_READ_MAX, TUNNEL_LISTENER_LINE, ownPortsFile, OWN_PORTS_MAX, OWN_PORTS_READ_MAX, EVENT_LINE_MAX, TOR_TIMING_MAX, HS_DESC_ACTIONS, HS_DESC_REASONS, CIRC_STATUSES, CIRC_PURPOSES, CIRC_HS_STATES, CIRC_REASONS;
162710
162795
  var init_managedTor = __esm({
162711
162796
  "wallet/src/net/managedTor.mjs"() {
162712
162797
  "use strict";
@@ -162837,13 +162922,16 @@ public static class ShinjukuOwnTor {
162837
162922
  LINUX_HASHES = ".hashes.json";
162838
162923
  fileSha256 = (path) => createHash43("sha256").update(readFileSync(path)).digest("hex");
162839
162924
  startErrorsFile = (home) => join51(managedTorDir(home), "start-errors.log");
162925
+ NOTICE_READ_MAX = 2 * 1024 * 1024;
162926
+ TUNNEL_LISTENER_LINE = /^[A-Z][a-z]{2} [ 0-9]?[0-9] [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3} \[notice\] Opened HTTP tunnel listener (?:connection \(ready\) )?on 127\.0\.0\.1:([0-9]{1,5})\r?$/gm;
162927
+ ownPortsFile = (home) => join51(managedTorDir(home), "own-ports.json");
162928
+ OWN_PORTS_MAX = 256;
162929
+ OWN_PORTS_READ_MAX = 16 * 1024;
162840
162930
  setTunnelCircuitProbe(async ({ proxyHost, proxyPort } = {}) => {
162841
162931
  if (String(proxyHost) !== "127.0.0.1") return void 0;
162842
162932
  const home = setupHome(process.env);
162843
- const port = ownPortOf(home);
162844
- if (!Number.isInteger(port) || Number(proxyPort) !== port) return void 0;
162845
162933
  const state2 = managedTorState(home);
162846
- if (!state2 || state2.port !== port) return void 0;
162934
+ if (!state2 || Number(proxyPort) !== state2.port) return void 0;
162847
162935
  const answer = await controlCheck(home, state2, { circuits: true, unref: true });
162848
162936
  return answer && answer.tunnelPort === Number(proxyPort) ? answer.circuits : void 0;
162849
162937
  });
@@ -163089,11 +163177,12 @@ function proxyDispatcherClass() {
163089
163177
  async function sellerTor(recorded, home) {
163090
163178
  let tunnel = recorded;
163091
163179
  if (home) {
163092
- const current = readSetupConfig(home)?.torTunnel ?? recorded;
163180
+ const walletRecorded = readSetupConfig(home)?.torTunnel;
163181
+ const current = walletRecorded ?? recorded;
163093
163182
  try {
163094
163183
  tunnel = await ensureWalletTor(current, {
163095
163184
  env: { ...process.env, SHIELDED_WALLET_HOME: home },
163096
- explicit: true,
163185
+ explicit: walletRecorded !== void 0,
163097
163186
  say: (line) => process.stderr.write(`${line}
163098
163187
  `)
163099
163188
  });
@@ -172476,6 +172565,18 @@ function mcpSetupAdapter(values, home, deps) {
172476
172565
  return { ...platform, maxPaymentAtomic: caps.maxPayment, maxSessionAtomic: caps.maxSession };
172477
172566
  },
172478
172567
  missing: () => missingPieces(home, configOrNull(home)),
172568
+ // A "Use Tor?" yes: run() starts the wallet's own Tor first (mcpSetupBehindTor -> torTunnelReady -> ensureWalletTor)
172569
+ // when it applies, so the setup box probes no tunnel then (a live check on npm 0.3.219, a fresh computer, 2026-11-12 15:23:32 UTC: a
172570
+ // fresh home with nothing at 127.0.0.1:9080 stopped at tor_not_running with a terminal step before that start). The
172571
+ // rule: an own-Tor platform, and no recorded torTunnel, or the recorded one is this home's own Tor tunnel by the rule
172572
+ // every Tor run uses (isWalletOwnTunnel: managed.json, else tor\own-ports.json, else tor\notice.log; never config.json).
172573
+ // Any other recorded tunnel is the user's, and the box probes it.
172574
+ // torTunnel: the tunnel the probe checks otherwise (a Tor the user set, recorded in config.json; else the default).
172575
+ ownTor: () => {
172576
+ const recorded = configOrNull(home)?.torTunnel;
172577
+ return ownTorPlatform() && (recorded === void 0 || isWalletOwnTunnel(home, recorded));
172578
+ },
172579
+ torTunnel: () => configOrNull(home)?.torTunnel ?? TOR_HTTP_TUNNEL,
172479
172580
  // privateInference: the human ticked "Add a private AI tool to this app" (a yes, as setup --private-inference);
172480
172581
  // no tick keeps what config.json records. tor: the answer to "Use Tor?" (private inference turns it on). A server
172481
172582
  // already behind Tor (or an old caller with no answer) sets up in place.
@@ -172502,7 +172603,9 @@ async function mcpSetupBehindTor(values, home, deps, { privateInference, onStage
172502
172603
  const recorded = configOrNull(home)?.torTunnel;
172503
172604
  tunnel = await torTunnelReady(recorded ?? TOR_HTTP_TUNNEL, { explicit: recorded !== void 0 });
172504
172605
  } catch (error) {
172505
- throw new Error(`setup_tor_unavailable: ${String(error.message).replace(/^[a-z][a-z0-9_]*: /, "")}`);
172606
+ const made = configOrNull(home)?.recoveryFile;
172607
+ if (made && existsSync(made)) onStage("wallet-created", { recoveryFile: made });
172608
+ throw new Error(`${error?.managedTor ? "setup_tor_not_started" : "setup_tor_unavailable"}: ${String(error.message).replace(/^[a-z][a-z0-9_]*: /, "")}`);
172506
172609
  }
172507
172610
  const resultDir = mkdtempSync(join58(tmpdir8(), "shinjuku-setup-"));
172508
172611
  const prior = process.env[RESULT_FILE_ENV];
@@ -173352,7 +173455,7 @@ async function hostCheckProxy(home, deps, noTor) {
173352
173455
  if (proxy.tor) {
173353
173456
  if (!inProxiedRun(deps.env)) {
173354
173457
  try {
173355
- proxy = { ...proxy, url: await torTunnelReady(proxy.url, { explicit: proxy.url !== TOR_HTTP_TUNNEL }) };
173458
+ proxy = { ...proxy, url: await torTunnelReady(proxy.url, { explicit: proxy.explicit === true }) };
173356
173459
  } catch {
173357
173460
  return { down: true };
173358
173461
  }
@@ -173545,8 +173648,8 @@ Setup stopped. Run the same setup line again to finish it; files already downloa
173545
173648
  }
173546
173649
  function installProxy(deps, behindTor, tunnel) {
173547
173650
  const run2 = childRunProxy(deps.env).args;
173548
- if (run2[0] === "--tor") return { url: run2[2] ?? TOR_HTTP_TUNNEL, tor: true };
173549
- return behindTor ? { url: tunnel ?? TOR_HTTP_TUNNEL, tor: true } : void 0;
173651
+ if (run2[0] === "--tor") return { url: run2[2] ?? TOR_HTTP_TUNNEL, tor: true, explicit: run2[2] !== void 0 };
173652
+ return behindTor ? { url: tunnel ?? TOR_HTTP_TUNNEL, tor: true, explicit: tunnel !== void 0 } : void 0;
173550
173653
  }
173551
173654
  var COMMAND_NOT_INSTALLED = "The shinjuku command could not be installed on this computer; the longer command below works the same.";
173552
173655
  async function installCommand(deps, {
@@ -173570,7 +173673,7 @@ async function installCommand(deps, {
173570
173673
  tunnelOf2(proxy.url);
173571
173674
  if (!inProxiedRun(deps.env)) {
173572
173675
  try {
173573
- proxy = { ...proxy, url: await torTunnelReady(proxy.url, { explicit: proxy.url !== TOR_HTTP_TUNNEL }) };
173676
+ proxy = { ...proxy, url: await torTunnelReady(proxy.url, { explicit: proxy.explicit === true }) };
173574
173677
  } catch {
173575
173678
  return "tor-down";
173576
173679
  }