shinjuku-shield 0.3.196 → 0.3.197

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.196. The command is `shinjuku`.
8
+ This is version 0.3.197. The command is `shinjuku`.
9
9
 
10
10
  ## Set up
11
11
 
12
12
  ```sh
13
- npx -y shinjuku@0.3.196 setup
13
+ npx -y shinjuku@0.3.197 setup
14
14
  ```
15
15
 
16
16
  Setup does every step for you:
@@ -107,14 +107,14 @@ Add it yourself. The name of the wallet in your app is `shinjuku`.
107
107
  Claude Code:
108
108
 
109
109
  ```sh
110
- claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.196 mcp
110
+ claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.197 mcp
111
111
  ```
112
112
 
113
113
  In this test version only (not offered yet), the same entry for Claude Desktop
114
114
  (`claude_desktop_config.json`) or Cursor (`~/.cursor/mcp.json`):
115
115
 
116
116
  ```json
117
- { "mcpServers": { "shinjuku": { "command": "npx", "args": ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.196", "mcp"] } } }
117
+ { "mcpServers": { "shinjuku": { "command": "npx", "args": ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.197", "mcp"] } } }
118
118
  ```
119
119
 
120
120
  On Windows, if the app cannot find `npx`, use `"command": "cmd"` and put
@@ -126,7 +126,7 @@ CLI read `~/.codex/config.toml`):
126
126
  ```toml
127
127
  [mcp_servers.shinjuku]
128
128
  command = "npx"
129
- args = ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.196", "mcp"]
129
+ args = ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.197", "mcp"]
130
130
  startup_timeout_sec = 120
131
131
  tool_timeout_sec = 300
132
132
  ```
@@ -144,7 +144,7 @@ with the Releases table in
144
144
  Versions are published from GitHub Actions with npm provenance.
145
145
 
146
146
  `shinjuku-shield` is the package that holds the wallet. `shinjuku-shielded`
147
- 0.3.196, its older name, runs this package at the same version, so wallets
147
+ 0.3.197, its older name, runs this package at the same version, so wallets
148
148
  installed under that name keep updating. New installs use `shinjuku`.
149
149
 
150
150
  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": "9f713df26eed69219dcf8555afe39ba224a2606edd8ba970e79786a4de4a79b9",
5
- "bytes": 9433979,
6
- "sourceCommit": "c925abe323dd202a57545aae720d104f9a986160",
4
+ "sha256": "a7aadb545214ada4d5c61433b62539a78559d35e2ae00106e9a0516eff2ad256",
5
+ "bytes": 9445994,
6
+ "sourceCommit": "f7edfb63be8f7d1d43e794308372c9d98bf815b2",
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",
@@ -1040,8 +1040,8 @@
1040
1040
  ],
1041
1041
  "seller": {
1042
1042
  "file": "shinjuku-seller.mjs",
1043
- "sha256": "142cb647b014da52a0866704bfa20365894fb75f72c82d9ab4edb572d2727083",
1044
- "bytes": 3721590,
1043
+ "sha256": "d80fdd16e93996091b8a8b649179a941f7aefb829dd8934a9ecb7b7be1160810",
1044
+ "bytes": 3723544,
1045
1045
  "entry": "wallet/src/seller/exact/index.mjs",
1046
1046
  "external": [
1047
1047
  "@x402/core/http",
@@ -1932,5 +1932,5 @@
1932
1932
  }
1933
1933
  ]
1934
1934
  },
1935
- "publishedAt": "2026-11-08T18:19:02.407Z"
1935
+ "publishedAt": "2026-11-08T22:50:33.779Z"
1936
1936
  }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "shinjuku-shield",
3
- "version": "0.3.196",
3
+ "version": "0.3.197",
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": "9f713df2",
7
- "shinjukuSha256": "9f713df26eed69219dcf8555afe39ba224a2606edd8ba970e79786a4de4a79b9",
6
+ "shinjukuRelease": "a7aadb54",
7
+ "shinjukuSha256": "a7aadb545214ada4d5c61433b62539a78559d35e2ae00106e9a0516eff2ad256",
8
8
  "license": "SEE LICENSE IN LICENSE.txt",
9
9
  "author": "Shinjuku Shield",
10
10
  "homepage": "https://github.com/ShinjukuStaition/shinjuku-shield#readme",
@@ -40168,6 +40168,7 @@ var init_errorCodes = __esm({
40168
40168
  "p03_float_busy_retry_later",
40169
40169
  "p03_float_fee_account_low",
40170
40170
  "p03_float_not_ready_retry_later",
40171
+ "p03_float_rate_limited_retry_later",
40171
40172
  "p03_float_payment_in_flight_retry_later",
40172
40173
  "p03_float_already_paid",
40173
40174
  "p03_float_request_refused",
@@ -48646,7 +48647,7 @@ function connect2(rpcUrl, commitment = "finalized", { timeoutMs, wrapFetch = (fe
48646
48647
  headers.delete("content-length");
48647
48648
  return new Response(body, { status: response.status, statusText: response.statusText, headers });
48648
48649
  } catch (error) {
48649
- if (stalled.signal.aborted && !init?.signal?.aborted && !init?.ownLane) await moveTorCircuitAfterStall(circuit);
48650
+ if (stalled.signal.aborted && !init?.signal?.aborted && !init?.ownLane && !init?.noStallMove) await moveTorCircuitAfterStall(circuit);
48650
48651
  throw error;
48651
48652
  } finally {
48652
48653
  clearTimeout(timer);
@@ -48655,7 +48656,7 @@ function connect2(rpcUrl, commitment = "finalized", { timeoutMs, wrapFetch = (fe
48655
48656
  });
48656
48657
  const connection = countRpcCalls(new import_web396.Connection(rpcUrl, { commitment, fetch: fetch2, disableRetryOnRateLimit: true }));
48657
48658
  Object.defineProperty(connection, "abortableRpcRequest", {
48658
- value: async (method, params, signal, onResponse, { id, lane, rejectHttpError = false, bodyStallMs, totalCapMs } = {}) => {
48659
+ value: async (method, params, signal, onResponse, { id, lane, rejectHttpError = false, bodyStallMs, totalCapMs, noStallMove = false } = {}) => {
48659
48660
  let reported = false;
48660
48661
  const onResponseHead = (response2) => {
48661
48662
  if (reported) return;
@@ -48671,6 +48672,7 @@ function connect2(rpcUrl, commitment = "finalized", { timeoutMs, wrapFetch = (fe
48671
48672
  onResponseHead,
48672
48673
  bodyStallMs,
48673
48674
  totalCapMs,
48675
+ ...noStallMove ? { noStallMove: true } : {},
48674
48676
  headers: { "content-type": "application/json" },
48675
48677
  body: JSON.stringify({ jsonrpc: "2.0", id: id ?? randomUUID2(), method, params })
48676
48678
  };
@@ -53596,7 +53598,7 @@ function requestListNow(history, pool2, from, size, attempts, signal, lane) {
53596
53598
  if (runEnded()) return { error: runEndedError() };
53597
53599
  const circuit = torCircuit();
53598
53600
  try {
53599
- return { response: await listRequest(history, params, { signal, lane, label: attempts === 1 ? `tail${from}` : `page${from}_try${index + 1}` }) };
53601
+ return { response: await listRequest(history, params, { signal, lane: lane ?? historyStallLane(), label: attempts === 1 ? `tail${from}` : `page${from}_try${index + 1}` }) };
53600
53602
  } catch (error) {
53601
53603
  if (lane !== void 0 && !runEnded() && !signal.aborted && !proxyRefusedConnection(error)) {
53602
53604
  dropTorLane(lane);
@@ -53613,6 +53615,32 @@ function requestListNow(history, pool2, from, size, attempts, signal, lane) {
53613
53615
  };
53614
53616
  return attempt(0);
53615
53617
  }
53618
+ function historyStallLane() {
53619
+ return inTorRun() && stallLaneCircuit !== void 0 && stallLaneCircuit === torCircuit() ? HISTORY_STALL_LANE : void 0;
53620
+ }
53621
+ function noteHistoryStall(circuit, lane, gen3) {
53622
+ if (!inTorRun() || circuit !== torCircuit()) return;
53623
+ if (lane === void 0 ? stallLaneCircuit === circuit : gen3 !== stallLaneGen) return;
53624
+ if (stallLaneCircuit !== circuit) {
53625
+ stallLaneCircuit = circuit;
53626
+ stallLaneMoves = 0;
53627
+ stallLaneSpent = false;
53628
+ }
53629
+ if (stallLaneMoves >= HISTORY_LANE_MAX_MOVES) {
53630
+ if (!stallLaneSpent) markPhase("compact-history-lane", "spent");
53631
+ stallLaneSpent = true;
53632
+ return;
53633
+ }
53634
+ if (lane === HISTORY_STALL_LANE) dropTorLane(HISTORY_STALL_LANE);
53635
+ stallLaneGen += 1;
53636
+ stallLaneMoves += 1;
53637
+ markPhase("compact-history-lane", `move${stallLaneMoves}`);
53638
+ try {
53639
+ process.stderr.write(`tor: a history read stalled on its circuit, so the history reads moved to a new Tor circuit of their own (${stallLaneMoves} of ${HISTORY_LANE_MAX_MOVES} in a row); payments keep theirs
53640
+ `);
53641
+ } catch {
53642
+ }
53643
+ }
53616
53644
  function tailLane(history) {
53617
53645
  if (!inTorRun()) return void 0;
53618
53646
  const winner = historyOnionWinner(history?.rpcEndpoint);
@@ -53652,6 +53680,7 @@ async function listRequest(history, params, { signal, label, lane }) {
53652
53680
  await parked;
53653
53681
  }
53654
53682
  const circuit = torCircuit();
53683
+ const gen3 = stallLaneGen;
53655
53684
  const headless = new AbortController();
53656
53685
  let timer;
53657
53686
  markPhase("compact-list-request", label);
@@ -53663,7 +53692,13 @@ async function listRequest(history, params, { signal, label, lane }) {
53663
53692
  clearTimeout(timer);
53664
53693
  markPhase("compact-list-head", label);
53665
53694
  },
53666
- { rejectHttpError: true, bodyStallMs: LIST_BODY_STALL_MS, totalCapMs: LIST_TOTAL_CAP_MS, ...lane === void 0 ? {} : { lane } }
53695
+ {
53696
+ rejectHttpError: true,
53697
+ bodyStallMs: LIST_BODY_STALL_MS,
53698
+ totalCapMs: LIST_TOTAL_CAP_MS,
53699
+ noStallMove: lane !== HISTORY_TAIL_LANE,
53700
+ ...lane === void 0 ? {} : { lane }
53701
+ }
53667
53702
  );
53668
53703
  read.catch(() => {
53669
53704
  });
@@ -53672,17 +53707,22 @@ async function listRequest(history, params, { signal, label, lane }) {
53672
53707
  timer = setTimeout(() => {
53673
53708
  headless.abort();
53674
53709
  reject(new Error(LIST_HEAD_STALLED));
53675
- }, lane === void 0 ? LIST_HEAD_TIMEOUT_MS : LANE_HEAD_TIMEOUT_MS);
53710
+ }, lane === HISTORY_TAIL_LANE ? LANE_HEAD_TIMEOUT_MS : LIST_HEAD_TIMEOUT_MS);
53676
53711
  })]) : read);
53677
53712
  markPhase("compact-list-answer", label);
53713
+ if (lane === HISTORY_STALL_LANE && circuit === stallLaneCircuit && gen3 === stallLaneGen) {
53714
+ stallLaneMoves = 0;
53715
+ stallLaneSpent = false;
53716
+ }
53678
53717
  return response;
53679
53718
  } catch (error) {
53680
53719
  if (error?.message === LIST_HEAD_STALLED) {
53681
53720
  markPhase("compact-list-head-timeout", label);
53682
- if (lane === void 0) await moveTorCircuitAfterStall(circuit);
53721
+ if (lane !== HISTORY_TAIL_LANE) noteHistoryStall(circuit, lane, gen3);
53683
53722
  } else {
53684
53723
  const cause = signal?.aborted ? "stopped" : { [HISTORY_BODY_STALLED]: "body_stall", [HISTORY_BODY_CAPPED]: "capped" }[error?.message] ?? failureCause(error);
53685
53724
  markPhase("compact-list-failed", `${label}_${cause}`);
53725
+ if (lane !== HISTORY_TAIL_LANE && !signal?.aborted && ["body_stall", "capped", "timeout"].includes(cause)) noteHistoryStall(circuit, lane, gen3);
53686
53726
  }
53687
53727
  throw error;
53688
53728
  } finally {
@@ -53691,7 +53731,7 @@ async function listRequest(history, params, { signal, label, lane }) {
53691
53731
  }
53692
53732
  function sourceUnreachable(error, circuit) {
53693
53733
  if (["ECONNREFUSED", "UND_ERR_CONNECT_TIMEOUT"].includes(error?.cause?.code ?? error?.code)) return true;
53694
- return inTorRun() && failureCause(error) === "timeout" && torCircuit() === circuit;
53734
+ return inTorRun() && failureCause(error) === "timeout" && torCircuit() === circuit && (stallLaneCircuit !== circuit || stallLaneSpent);
53695
53735
  }
53696
53736
  function failureCause(error) {
53697
53737
  const text2 = String(error?.message ?? error ?? "");
@@ -54908,7 +54948,7 @@ async function tryCompactP03HistoryReport(options) {
54908
54948
  return { ok: false, reason, ...detail ? { detail } : {}, error };
54909
54949
  }
54910
54950
  }
54911
- var import_web398, P03_COMPACT_HISTORY_SOURCE_MODEL, P03_COMPACT_PAGE, P03_COMPACT_SPOT_CHECKS, FIELD_MODULUS5, SUBTREE_LEAVES3, LOCAL_DEPTH2, OUTER_DEPTH2, PRIMARY_PROOF_BYTES2, FIELD_BYTES3, ED25519_SPKI_PREFIX3, VERSION_1_PREFIX2, HEX64, BASE58, REPLAY_STORE_INDEXED2, PROFILES2, MOVE_HEAD_BYTES2, MOVE_INSERTED_VALUES2, refuse2, hash4, bitAt, zeroRootsMemo, lastFolds, PRE_FOLD_SLICE_MS, preFolds, FOLD_CHECKPOINT_EVERY, foldNode, foldFrontier, foldHex, servedWithoutRecords, isSignature, isIndex, IMPORT_KEYS, IMPORT_MAX_VALUES, LIST_ATTEMPTS, listInFlight, HISTORY_TAIL_LANE, LIST_HEAD_TIMEOUT_MS, LIST_HEAD_STALLED, LANE_HEAD_TIMEOUT_MS, LIST_BODY_STALL_MS, LIST_TOTAL_CAP_MS, OWN_READ_TIMEOUT_MS, BOUNDED_OWN_METHODS, P03_COMPACT_TAIL_GRID, TAIL_RETRY_REFUSALS, tailFrom, sameJson, SPOT_HEDGE_AFTER_MS, SPOT_HEDGE_LANE, POOL_HEDGE_AFTER_MS, POOL_HEDGE_LANE, compactReportsRunning;
54951
+ var import_web398, P03_COMPACT_HISTORY_SOURCE_MODEL, P03_COMPACT_PAGE, P03_COMPACT_SPOT_CHECKS, FIELD_MODULUS5, SUBTREE_LEAVES3, LOCAL_DEPTH2, OUTER_DEPTH2, PRIMARY_PROOF_BYTES2, FIELD_BYTES3, ED25519_SPKI_PREFIX3, VERSION_1_PREFIX2, HEX64, BASE58, REPLAY_STORE_INDEXED2, PROFILES2, MOVE_HEAD_BYTES2, MOVE_INSERTED_VALUES2, refuse2, hash4, bitAt, zeroRootsMemo, lastFolds, PRE_FOLD_SLICE_MS, preFolds, FOLD_CHECKPOINT_EVERY, foldNode, foldFrontier, foldHex, servedWithoutRecords, isSignature, isIndex, IMPORT_KEYS, IMPORT_MAX_VALUES, LIST_ATTEMPTS, listInFlight, HISTORY_TAIL_LANE, HISTORY_STALL_LANE, HISTORY_LANE_MAX_MOVES, stallLaneCircuit, stallLaneMoves, stallLaneGen, stallLaneSpent, LIST_HEAD_TIMEOUT_MS, LIST_HEAD_STALLED, LANE_HEAD_TIMEOUT_MS, LIST_BODY_STALL_MS, LIST_TOTAL_CAP_MS, OWN_READ_TIMEOUT_MS, BOUNDED_OWN_METHODS, P03_COMPACT_TAIL_GRID, TAIL_RETRY_REFUSALS, tailFrom, sameJson, SPOT_HEDGE_AFTER_MS, SPOT_HEDGE_LANE, POOL_HEDGE_AFTER_MS, POOL_HEDGE_LANE, compactReportsRunning;
54912
54952
  var init_compact = __esm({
54913
54953
  "wallet/src/history/compact.mjs"() {
54914
54954
  "use strict";
@@ -55054,6 +55094,11 @@ var init_compact = __esm({
55054
55094
  LIST_ATTEMPTS = 6;
55055
55095
  listInFlight = /* @__PURE__ */ new Map();
55056
55096
  HISTORY_TAIL_LANE = "history-tail";
55097
+ HISTORY_STALL_LANE = "history-stall";
55098
+ HISTORY_LANE_MAX_MOVES = 2;
55099
+ stallLaneMoves = 0;
55100
+ stallLaneGen = 0;
55101
+ stallLaneSpent = false;
55057
55102
  LIST_HEAD_TIMEOUT_MS = 1e4;
55058
55103
  LIST_HEAD_STALLED = "ETIMEDOUT: history list answer head stalled";
55059
55104
  LANE_HEAD_TIMEOUT_MS = 1500;
@@ -53307,7 +53307,7 @@ function connect2(rpcUrl, commitment = "finalized", { timeoutMs, wrapFetch = (fe
53307
53307
  headers.delete("content-length");
53308
53308
  return new Response(body, { status: response.status, statusText: response.statusText, headers });
53309
53309
  } catch (error) {
53310
- if (stalled.signal.aborted && !init?.signal?.aborted && !init?.ownLane) await moveTorCircuitAfterStall(circuit);
53310
+ if (stalled.signal.aborted && !init?.signal?.aborted && !init?.ownLane && !init?.noStallMove) await moveTorCircuitAfterStall(circuit);
53311
53311
  throw error;
53312
53312
  } finally {
53313
53313
  clearTimeout(timer);
@@ -53316,7 +53316,7 @@ function connect2(rpcUrl, commitment = "finalized", { timeoutMs, wrapFetch = (fe
53316
53316
  });
53317
53317
  const connection = countRpcCalls(new import_web395.Connection(rpcUrl, { commitment, fetch: fetch2, disableRetryOnRateLimit: true }));
53318
53318
  Object.defineProperty(connection, "abortableRpcRequest", {
53319
- value: async (method, params, signal, onResponse, { id, lane, rejectHttpError = false, bodyStallMs, totalCapMs } = {}) => {
53319
+ value: async (method, params, signal, onResponse, { id, lane, rejectHttpError = false, bodyStallMs, totalCapMs, noStallMove = false } = {}) => {
53320
53320
  let reported = false;
53321
53321
  const onResponseHead = (response2) => {
53322
53322
  if (reported) return;
@@ -53332,6 +53332,7 @@ function connect2(rpcUrl, commitment = "finalized", { timeoutMs, wrapFetch = (fe
53332
53332
  onResponseHead,
53333
53333
  bodyStallMs,
53334
53334
  totalCapMs,
53335
+ ...noStallMove ? { noStallMove: true } : {},
53335
53336
  headers: { "content-type": "application/json" },
53336
53337
  body: JSON.stringify({ jsonrpc: "2.0", id: id ?? randomUUID(), method, params })
53337
53338
  };
@@ -62291,7 +62292,7 @@ function requestListNow(history, pool2, from, size, attempts, signal, lane) {
62291
62292
  if (runEnded()) return { error: runEndedError() };
62292
62293
  const circuit = torCircuit();
62293
62294
  try {
62294
- return { response: await listRequest(history, params, { signal, lane, label: attempts === 1 ? `tail${from}` : `page${from}_try${index + 1}` }) };
62295
+ return { response: await listRequest(history, params, { signal, lane: lane ?? historyStallLane(), label: attempts === 1 ? `tail${from}` : `page${from}_try${index + 1}` }) };
62295
62296
  } catch (error) {
62296
62297
  if (lane !== void 0 && !runEnded() && !signal.aborted && !proxyRefusedConnection(error)) {
62297
62298
  dropTorLane(lane);
@@ -62308,6 +62309,32 @@ function requestListNow(history, pool2, from, size, attempts, signal, lane) {
62308
62309
  };
62309
62310
  return attempt(0);
62310
62311
  }
62312
+ function historyStallLane() {
62313
+ return inTorRun() && stallLaneCircuit !== void 0 && stallLaneCircuit === torCircuit() ? HISTORY_STALL_LANE : void 0;
62314
+ }
62315
+ function noteHistoryStall(circuit, lane, gen3) {
62316
+ if (!inTorRun() || circuit !== torCircuit()) return;
62317
+ if (lane === void 0 ? stallLaneCircuit === circuit : gen3 !== stallLaneGen) return;
62318
+ if (stallLaneCircuit !== circuit) {
62319
+ stallLaneCircuit = circuit;
62320
+ stallLaneMoves = 0;
62321
+ stallLaneSpent = false;
62322
+ }
62323
+ if (stallLaneMoves >= HISTORY_LANE_MAX_MOVES) {
62324
+ if (!stallLaneSpent) markPhase("compact-history-lane", "spent");
62325
+ stallLaneSpent = true;
62326
+ return;
62327
+ }
62328
+ if (lane === HISTORY_STALL_LANE) dropTorLane(HISTORY_STALL_LANE);
62329
+ stallLaneGen += 1;
62330
+ stallLaneMoves += 1;
62331
+ markPhase("compact-history-lane", `move${stallLaneMoves}`);
62332
+ try {
62333
+ process.stderr.write(`tor: a history read stalled on its circuit, so the history reads moved to a new Tor circuit of their own (${stallLaneMoves} of ${HISTORY_LANE_MAX_MOVES} in a row); payments keep theirs
62334
+ `);
62335
+ } catch {
62336
+ }
62337
+ }
62311
62338
  function tailLane(history) {
62312
62339
  if (!inTorRun()) return void 0;
62313
62340
  const winner = historyOnionWinner(history?.rpcEndpoint);
@@ -62347,6 +62374,7 @@ async function listRequest(history, params, { signal, label, lane }) {
62347
62374
  await parked;
62348
62375
  }
62349
62376
  const circuit = torCircuit();
62377
+ const gen3 = stallLaneGen;
62350
62378
  const headless = new AbortController();
62351
62379
  let timer;
62352
62380
  markPhase("compact-list-request", label);
@@ -62358,7 +62386,13 @@ async function listRequest(history, params, { signal, label, lane }) {
62358
62386
  clearTimeout(timer);
62359
62387
  markPhase("compact-list-head", label);
62360
62388
  },
62361
- { rejectHttpError: true, bodyStallMs: LIST_BODY_STALL_MS, totalCapMs: LIST_TOTAL_CAP_MS, ...lane === void 0 ? {} : { lane } }
62389
+ {
62390
+ rejectHttpError: true,
62391
+ bodyStallMs: LIST_BODY_STALL_MS,
62392
+ totalCapMs: LIST_TOTAL_CAP_MS,
62393
+ noStallMove: lane !== HISTORY_TAIL_LANE,
62394
+ ...lane === void 0 ? {} : { lane }
62395
+ }
62362
62396
  );
62363
62397
  read.catch(() => {
62364
62398
  });
@@ -62367,17 +62401,22 @@ async function listRequest(history, params, { signal, label, lane }) {
62367
62401
  timer = setTimeout(() => {
62368
62402
  headless.abort();
62369
62403
  reject(new Error(LIST_HEAD_STALLED));
62370
- }, lane === void 0 ? LIST_HEAD_TIMEOUT_MS : LANE_HEAD_TIMEOUT_MS);
62404
+ }, lane === HISTORY_TAIL_LANE ? LANE_HEAD_TIMEOUT_MS : LIST_HEAD_TIMEOUT_MS);
62371
62405
  })]) : read);
62372
62406
  markPhase("compact-list-answer", label);
62407
+ if (lane === HISTORY_STALL_LANE && circuit === stallLaneCircuit && gen3 === stallLaneGen) {
62408
+ stallLaneMoves = 0;
62409
+ stallLaneSpent = false;
62410
+ }
62373
62411
  return response;
62374
62412
  } catch (error) {
62375
62413
  if (error?.message === LIST_HEAD_STALLED) {
62376
62414
  markPhase("compact-list-head-timeout", label);
62377
- if (lane === void 0) await moveTorCircuitAfterStall(circuit);
62415
+ if (lane !== HISTORY_TAIL_LANE) noteHistoryStall(circuit, lane, gen3);
62378
62416
  } else {
62379
62417
  const cause = signal?.aborted ? "stopped" : { [HISTORY_BODY_STALLED]: "body_stall", [HISTORY_BODY_CAPPED]: "capped" }[error?.message] ?? failureCause(error);
62380
62418
  markPhase("compact-list-failed", `${label}_${cause}`);
62419
+ if (lane !== HISTORY_TAIL_LANE && !signal?.aborted && ["body_stall", "capped", "timeout"].includes(cause)) noteHistoryStall(circuit, lane, gen3);
62381
62420
  }
62382
62421
  throw error;
62383
62422
  } finally {
@@ -62386,7 +62425,7 @@ async function listRequest(history, params, { signal, label, lane }) {
62386
62425
  }
62387
62426
  function sourceUnreachable(error, circuit) {
62388
62427
  if (["ECONNREFUSED", "UND_ERR_CONNECT_TIMEOUT"].includes(error?.cause?.code ?? error?.code)) return true;
62389
- return inTorRun() && failureCause(error) === "timeout" && torCircuit() === circuit;
62428
+ return inTorRun() && failureCause(error) === "timeout" && torCircuit() === circuit && (stallLaneCircuit !== circuit || stallLaneSpent);
62390
62429
  }
62391
62430
  function failureCause(error) {
62392
62431
  const text3 = String(error?.message ?? error ?? "");
@@ -63603,7 +63642,7 @@ async function tryCompactP03HistoryReport(options) {
63603
63642
  return { ok: false, reason, ...detail ? { detail } : {}, error };
63604
63643
  }
63605
63644
  }
63606
- var import_web398, P03_COMPACT_HISTORY_SOURCE_MODEL, P03_COMPACT_PAGE, P03_COMPACT_SPOT_CHECKS, FIELD_MODULUS5, SUBTREE_LEAVES3, LOCAL_DEPTH2, OUTER_DEPTH2, PRIMARY_PROOF_BYTES2, FIELD_BYTES3, ED25519_SPKI_PREFIX3, VERSION_1_PREFIX2, HEX642, BASE58, REPLAY_STORE_INDEXED2, PROFILES2, MOVE_HEAD_BYTES2, MOVE_INSERTED_VALUES2, refuse3, hash4, bitAt, zeroRootsMemo, lastFolds, PRE_FOLD_SLICE_MS, preFolds, FOLD_CHECKPOINT_EVERY, foldNode, foldFrontier, foldHex, servedWithoutRecords, isSignature, isIndex, IMPORT_KEYS, IMPORT_MAX_VALUES, LIST_ATTEMPTS, listInFlight, HISTORY_TAIL_LANE, LIST_HEAD_TIMEOUT_MS, LIST_HEAD_STALLED, LANE_HEAD_TIMEOUT_MS, LIST_BODY_STALL_MS, LIST_TOTAL_CAP_MS, OWN_READ_TIMEOUT_MS, BOUNDED_OWN_METHODS, P03_COMPACT_TAIL_GRID, TAIL_RETRY_REFUSALS, tailFrom, sameJson2, SPOT_HEDGE_AFTER_MS, SPOT_HEDGE_LANE, POOL_HEDGE_AFTER_MS, POOL_HEDGE_LANE, compactReportsRunning, compactHistoryReadsRunning;
63645
+ var import_web398, P03_COMPACT_HISTORY_SOURCE_MODEL, P03_COMPACT_PAGE, P03_COMPACT_SPOT_CHECKS, FIELD_MODULUS5, SUBTREE_LEAVES3, LOCAL_DEPTH2, OUTER_DEPTH2, PRIMARY_PROOF_BYTES2, FIELD_BYTES3, ED25519_SPKI_PREFIX3, VERSION_1_PREFIX2, HEX642, BASE58, REPLAY_STORE_INDEXED2, PROFILES2, MOVE_HEAD_BYTES2, MOVE_INSERTED_VALUES2, refuse3, hash4, bitAt, zeroRootsMemo, lastFolds, PRE_FOLD_SLICE_MS, preFolds, FOLD_CHECKPOINT_EVERY, foldNode, foldFrontier, foldHex, servedWithoutRecords, isSignature, isIndex, IMPORT_KEYS, IMPORT_MAX_VALUES, LIST_ATTEMPTS, listInFlight, HISTORY_TAIL_LANE, HISTORY_STALL_LANE, HISTORY_LANE_MAX_MOVES, stallLaneCircuit, stallLaneMoves, stallLaneGen, stallLaneSpent, LIST_HEAD_TIMEOUT_MS, LIST_HEAD_STALLED, LANE_HEAD_TIMEOUT_MS, LIST_BODY_STALL_MS, LIST_TOTAL_CAP_MS, OWN_READ_TIMEOUT_MS, BOUNDED_OWN_METHODS, P03_COMPACT_TAIL_GRID, TAIL_RETRY_REFUSALS, tailFrom, sameJson2, SPOT_HEDGE_AFTER_MS, SPOT_HEDGE_LANE, POOL_HEDGE_AFTER_MS, POOL_HEDGE_LANE, compactReportsRunning, compactHistoryReadsRunning;
63607
63646
  var init_compact = __esm({
63608
63647
  "wallet/src/history/compact.mjs"() {
63609
63648
  "use strict";
@@ -63749,6 +63788,11 @@ var init_compact = __esm({
63749
63788
  LIST_ATTEMPTS = 6;
63750
63789
  listInFlight = /* @__PURE__ */ new Map();
63751
63790
  HISTORY_TAIL_LANE = "history-tail";
63791
+ HISTORY_STALL_LANE = "history-stall";
63792
+ HISTORY_LANE_MAX_MOVES = 2;
63793
+ stallLaneMoves = 0;
63794
+ stallLaneGen = 0;
63795
+ stallLaneSpent = false;
63752
63796
  LIST_HEAD_TIMEOUT_MS = 1e4;
63753
63797
  LIST_HEAD_STALLED = "ETIMEDOUT: history list answer head stalled";
63754
63798
  LANE_HEAD_TIMEOUT_MS = 1500;
@@ -72782,6 +72826,7 @@ var init_errorCodes = __esm({
72782
72826
  "p03_float_busy_retry_later",
72783
72827
  "p03_float_fee_account_low",
72784
72828
  "p03_float_not_ready_retry_later",
72829
+ "p03_float_rate_limited_retry_later",
72785
72830
  "p03_float_payment_in_flight_retry_later",
72786
72831
  "p03_float_already_paid",
72787
72832
  "p03_float_request_refused",
@@ -87272,6 +87317,9 @@ async function createSellerAdapter({
87272
87317
  if (refusedBeforeSettlement(receipt)) {
87273
87318
  await put(nonce, { ...offer, phase: "prepared", settleAttempted: false });
87274
87319
  mark("settle-refused-before-record");
87320
+ if (FRONTIER_WAIT_EXPIRED.test(String(receipt.errorMessage ?? ""))) {
87321
+ return { status: 202, code: "payment_pending_retry_same_payment" };
87322
+ }
87275
87323
  return {
87276
87324
  status: 202,
87277
87325
  code: PAYMENT_REFUSED,
@@ -87439,7 +87487,7 @@ async function createSellerAdapter({
87439
87487
  };
87440
87488
  return { server, handle, close, signerPublicKey, settledTransactions, offerSummaries, discardUnsentOffer };
87441
87489
  }
87442
- var import_web3115, LOOPBACK_ORIGIN, BINDING, SCHEMA2, OFFERS_LAYOUT, SNAPSHOT_EVERY_MS, LOADER2, canonical4, storeProfileIdentity, jsonSafe, bigint, encodeHeader, PROGRAM_DATA_HEADER_BYTES, hashedProgramDataHeaders, ringModeReads, PAYMENT_REFUSED, FACILITATOR_UNDERFUNDED, DEFINITE_VERIFY_REFUSALS, definiteVerifyRefusal, refusedBeforeSettlement, ANCHOR_REQUEST_TIMEOUT_MS2, ANCHOR_POLL_ATTEMPTS, ANCHOR_POLL_MS, ANCHOR_BUSY_DEFAULT_SECONDS, ANCHOR_BUSY_MAX_SECONDS, MEMO_PRECOMPUTES_MAX, MEMO_PRECOMPUTE_WAIT_MS, WALLET_MERCHANT_SLOT, PRE_SETTLE_REUSE_MARGIN_S, PRE_SETTLE_REUSE_MAX_AGE_MS, FINALIZED_MEMO_MAX_AGE_MS, INTAKE_REUSE_MAX_AGE_MS, pause, FOLLOW_UP_DELAYS_MS, FOLLOW_UP_RESETTLE_FROM, UPSTREAM_FAILED, UPSTREAM_BODY_MAX, upstreamFailure, forwardedContentType, CONFIRMED_TRANSACTION_READ;
87490
+ var import_web3115, LOOPBACK_ORIGIN, BINDING, SCHEMA2, OFFERS_LAYOUT, SNAPSHOT_EVERY_MS, LOADER2, canonical4, storeProfileIdentity, jsonSafe, bigint, encodeHeader, PROGRAM_DATA_HEADER_BYTES, hashedProgramDataHeaders, ringModeReads, PAYMENT_REFUSED, FACILITATOR_UNDERFUNDED, FRONTIER_WAIT_EXPIRED, DEFINITE_VERIFY_REFUSALS, definiteVerifyRefusal, refusedBeforeSettlement, ANCHOR_REQUEST_TIMEOUT_MS2, ANCHOR_POLL_ATTEMPTS, ANCHOR_POLL_MS, ANCHOR_BUSY_DEFAULT_SECONDS, ANCHOR_BUSY_MAX_SECONDS, MEMO_PRECOMPUTES_MAX, MEMO_PRECOMPUTE_WAIT_MS, WALLET_MERCHANT_SLOT, PRE_SETTLE_REUSE_MARGIN_S, PRE_SETTLE_REUSE_MAX_AGE_MS, FINALIZED_MEMO_MAX_AGE_MS, INTAKE_REUSE_MAX_AGE_MS, pause, FOLLOW_UP_DELAYS_MS, FOLLOW_UP_RESETTLE_FROM, UPSTREAM_FAILED, UPSTREAM_BODY_MAX, upstreamFailure, forwardedContentType, CONFIRMED_TRANSACTION_READ;
87443
87491
  var init_service = __esm({
87444
87492
  "wallet/src/seller/service.mjs"() {
87445
87493
  "use strict";
@@ -87479,6 +87527,7 @@ var init_service = __esm({
87479
87527
  ringModeReads = /* @__PURE__ */ new WeakSet();
87480
87528
  PAYMENT_REFUSED = "payment_refused_pay_again";
87481
87529
  FACILITATOR_UNDERFUNDED = "facilitator_underfunded";
87530
+ FRONTIER_WAIT_EXPIRED = /: p03_frontier_sync_wait_expired$/;
87482
87531
  DEFINITE_VERIFY_REFUSALS = /* @__PURE__ */ new Set([
87483
87532
  "p03_quote_expired",
87484
87533
  "p03_quote_commitment_invalid",
@@ -107498,7 +107547,7 @@ function floatOutcomeWords(code2, error, t) {
107498
107547
  return [
107499
107548
  code2,
107500
107549
  unsure[1],
107501
- `${t.userReads === true ? `${told}.` : `Tell the user plainly: "${told}."`} It usually comes back about 2 minutes after the payment (up to about 7). ${t.userReads === true ? `Later: ${t.result}` : `The next wallet_balance, pay_for_service or inference_chat answer says when the refund arrives (refundNotices: tell the user that line); ${t.result}`}. Do not pay again with ${t.newId} until then`
107550
+ `${t.userReads === true ? `${told}.` : `Tell the user plainly: "${told}."`} It usually comes back 2 to 5 minutes after the payment (up to about 7). ${t.userReads === true ? `Later: ${t.result}` : `The next wallet_balance, pay_for_service or inference_chat answer says when the refund arrives (refundNotices: tell the user that line); ${t.result}`}. Do not pay again with ${t.newId} until then`
107502
107551
  ];
107503
107552
  }
107504
107553
  return [
@@ -107524,7 +107573,7 @@ function floatOutcomeWords(code2, error, t) {
107524
107573
  return [
107525
107574
  code2,
107526
107575
  `PAID ${totalText(error)} to Shinjuku (${t.privateLeg}); ${what}, and Shinjuku's transfer to ${p.the} is now too close to its end for ${p.the} to take it (a Solana transfer lasts about 30 s after it is signed), so the wallet did not send it again. The wallet does not know yet whether ${p.the} took it before that`,
107527
- `Nothing to do now: if ${p.the} did not take it, ${amountText(error?.paidAtomic, "the amount paid")} comes back to ${t.balance} by itself, usually about 2 minutes after the payment (up to about 7); if it did, no refund comes. ${t.result}. Do not pay again with ${t.newId} until then. After that, if ${stillWants(t)} ${data}, ${t.askNew}`
107576
+ `Nothing to do now: if ${p.the} did not take it, ${amountText(error?.paidAtomic, "the amount paid")} comes back to ${t.balance} by itself, usually 2 to 5 minutes after the payment (up to about 7); if it did, no refund comes. ${t.result}. Do not pay again with ${t.newId} until then. After that, if ${stillWants(t)} ${data}, ${t.askNew}`
107528
107577
  ];
107529
107578
  }
107530
107579
  case "p03_float_request_expired_nothing_paid":
@@ -107568,6 +107617,10 @@ function floatOutcomeWords(code2, error, t) {
107568
107617
  }
107569
107618
  case "p03_float_busy_retry_later":
107570
107619
  return [code2, "Shinjuku's shared float is busy right now; nothing was paid", t.againIn(error?.retryAfterSeconds ?? 30)];
107620
+ // Shinjuku's unpaid price check refused for now (its rate limit: one bucket for every Tor user, or this address's own;
107621
+ // PLAN AB272): the wallet asked once and stopped, so nothing was sent. The wait is the server's Retry-After.
107622
+ case "p03_float_rate_limited_retry_later":
107623
+ return [code2, "Shinjuku cannot check this payment's price right now; nothing was paid", t.againIn(error?.retryAfterSeconds ?? 60)];
107571
107624
  case "p03_float_not_ready_retry_later":
107572
107625
  return [code2, "Shinjuku's shared float is not ready yet (it is being filled); nothing was paid", t.againIn(error?.retryAfterSeconds ?? 60)];
107573
107626
  // The fee payer of Shinjuku's shared pockets is low on SOL (floatPay.mjs floatRefusalError, 0.3.113): only its operator
@@ -110047,6 +110100,10 @@ function speculateFloatQuoteFromFresh({
110047
110100
  if (speculatedQuotes.has(requestId) || store.readWal(floatPaymentWalName(hash7(requestId)))) return;
110048
110101
  const origin = floatOriginOf(floatOrigin, serviceUrl2);
110049
110102
  if (!config || !paymentRequired) return false;
110103
+ if (quoteLimitRefusal(config.payUrlPrefix)) {
110104
+ mark("leg1-ahead-limited");
110105
+ return false;
110106
+ }
110050
110107
  const cached = configCache.get(origin);
110051
110108
  const kept3 = { config, readAtMs: cached?.config === config ? cached.readAtMs : now };
110052
110109
  const stale = now - kept3.readAtMs >= CONFIG_CACHE_MS;
@@ -110073,6 +110130,7 @@ function speculateFloatQuoteFromFresh({
110073
110130
  const aheadUrl = `${slot3.payUrlPrefix}${body.floatId}`;
110074
110131
  void expectRequestSent(aheadUrl).then((sent) => mark(sent ? "leg1-ahead-wire" : "leg1-ahead-wire-unseen"));
110075
110132
  const socket = watchRequestPath(new URL(aheadUrl).pathname);
110133
+ const sentAt = performance.now();
110076
110134
  const ownTag2 = onOwnTagNow();
110077
110135
  let response;
110078
110136
  try {
@@ -110089,6 +110147,11 @@ function speculateFloatQuoteFromFresh({
110089
110147
  mark("leg1-ahead-402");
110090
110148
  const encoded = response.headers.get("PAYMENT-REQUIRED");
110091
110149
  void drainBody(response);
110150
+ if (response.status === 429) {
110151
+ rateLimitRefusal(aheadUrl, response.headers.get("retry-after"));
110152
+ return { refundTo, body, challenge: void 0 };
110153
+ }
110154
+ if (response.status === 402) quoteAdmitted(aheadUrl, sentAt);
110092
110155
  return { refundTo, body, challenge: response.status === 402 && encoded && encoded.length <= 128 * 1024 ? encoded : void 0 };
110093
110156
  })();
110094
110157
  slot3.ready.catch(() => void 0);
@@ -110330,9 +110393,16 @@ function floatBodyRequirement(offer) {
110330
110393
  }
110331
110394
  function floatFetch(base, seen) {
110332
110395
  const wrapper2 = async (target, init = {}) => {
110396
+ const sentAt = performance.now();
110333
110397
  const response = await base(target, floatInit(init));
110334
110398
  const paid = Object.keys(init.headers ?? {}).some((name) => name.toLowerCase() === "payment-signature");
110399
+ if (!paid && response.status === 402 && onFloatPayRoute(target)) quoteAdmitted(target, sentAt);
110335
110400
  if (paid || response.status === 402 || response.status < 400) return response;
110401
+ if (response.status === 429 && onFloatPayRoute(target)) {
110402
+ await response.body?.cancel?.();
110403
+ seen.refusal = rateLimitRefusal(target, response.headers.get("retry-after"));
110404
+ return new Response(null, { status: 400 });
110405
+ }
110336
110406
  let answer;
110337
110407
  try {
110338
110408
  answer = await readJson2(response.clone(), 8 * 1024);
@@ -110354,6 +110424,29 @@ function floatFetch(base, seen) {
110354
110424
  };
110355
110425
  return Object.defineProperty(wrapper2, "baseFetch", { value: base });
110356
110426
  }
110427
+ function onFloatPayRoute(target) {
110428
+ try {
110429
+ return new URL(typeof target === "string" ? target : target?.url ?? String(target)).pathname.startsWith(FLOAT_PAY_PATH);
110430
+ } catch {
110431
+ return false;
110432
+ }
110433
+ }
110434
+ function rateLimitRefusal(url, retryAfterHeader) {
110435
+ const value2 = Number(retryAfterHeader);
110436
+ const seconds2 = Number.isFinite(value2) && value2 > 0 ? Math.min(Math.ceil(value2), 3600) : 60;
110437
+ const at = performance.now();
110438
+ const origin = originOf(url);
110439
+ quoteLimits.set(origin, { setAt: at, until: Math.max(quoteLimits.get(origin)?.until ?? 0, at + seconds2 * 1e3) });
110440
+ return { code: "float_quote_rate_limited", retryAfterSeconds: seconds2 };
110441
+ }
110442
+ function quoteAdmitted(url, sentAt) {
110443
+ const origin = originOf(url);
110444
+ if (sentAt >= (quoteLimits.get(origin)?.setAt ?? Infinity)) quoteLimits.delete(origin);
110445
+ }
110446
+ function quoteLimitRefusal(url) {
110447
+ const left = (quoteLimits.get(originOf(url))?.until ?? 0) - performance.now();
110448
+ return left > 0 ? { code: "float_quote_rate_limited", retryAfterSeconds: Math.ceil(left / 1e3) } : void 0;
110449
+ }
110357
110450
  function floatRefusalError(refusal3, record) {
110358
110451
  const extra = {
110359
110452
  ...refusal3.retryAfterSeconds ? { retryAfterSeconds: refusal3.retryAfterSeconds } : {},
@@ -110373,6 +110466,9 @@ function floatRefusalError(refusal3, record) {
110373
110466
  return Object.assign(new Error("p03_float_payment_in_flight_retry_later"), { retryAfterSeconds: 60, ...extra });
110374
110467
  case "float_already_paid":
110375
110468
  return Object.assign(new Error("p03_float_already_paid"), extra);
110469
+ // Shinjuku's unpaid-quote limit is full for now (PLAN AB272): nothing was sent; the same request works after the window.
110470
+ case "float_quote_rate_limited":
110471
+ return Object.assign(new Error("p03_float_rate_limited_retry_later"), { retryAfterSeconds: 60, ...extra });
110376
110472
  // The message names Shinjuku's code too (refusal.code is ^float_[a-z_]{1,60}$), so the CLI's reason shows it.
110377
110473
  default:
110378
110474
  return Object.assign(new Error(`p03_float_request_refused: ${refusal3.code}`), {
@@ -110513,8 +110609,15 @@ async function payViaFloat({
110513
110609
  if (BigInt(offer.paidAtomic) > BigInt(maximumAtomic)) {
110514
110610
  fail25("p03_float_over_maximum", { priceAtomic: offer.priceAtomic, feeAtomic: offer.feeAtomic, paidAtomic: offer.paidAtomic, maximumAtomic });
110515
110611
  }
110612
+ const ownAsk = speculatedQuotes.get(requestId)?.ready;
110516
110613
  const ahead = takeSpeculatedQuote(requestId, { url, origin, offer, config });
110517
110614
  const asked = ahead ? await ahead.ready.catch(() => void 0) : void 0;
110615
+ if (!ahead && ownAsk) await ownAsk.catch(() => void 0);
110616
+ const limited = asked?.challenge ? void 0 : quoteLimitRefusal(config.payUrlPrefix);
110617
+ if (limited) {
110618
+ mark("leg1-quote-rate-limited");
110619
+ throw floatRefusalError(limited, offer);
110620
+ }
110518
110621
  const refundTo = asked ? asked.refundTo : await refundRead;
110519
110622
  const body = asked ? asked.body : canonicalBody({ requestId, seedHex: store.state.seedHex, requirement: offer.requirement, refundTo });
110520
110623
  aheadChallenge = asked?.challenge;
@@ -110567,6 +110670,14 @@ async function payViaFloat({
110567
110670
  });
110568
110671
  quoteTooShort(record);
110569
110672
  }
110673
+ if (record.xPayment === void 0 && innerUnsent() && !aheadChallenge) {
110674
+ const limited = quoteLimitRefusal(record.payUrlPrefix);
110675
+ if (limited) {
110676
+ mark("leg1-quote-rate-limited");
110677
+ dropUnsent();
110678
+ throw floatRefusalError(limited, record);
110679
+ }
110680
+ }
110570
110681
  let answeredThisRun = false;
110571
110682
  if (record.xPayment === void 0) {
110572
110683
  let regenerated = false;
@@ -111401,7 +111512,7 @@ function paidResult(record, replayed) {
111401
111512
  float: { floatId: record.floatId }
111402
111513
  };
111403
111514
  }
111404
- var import_web3117, FLOAT_PAYMENT_SCHEMA2, REGENERATE_CODES, FLOAT_PAYMENT_WAL_PREFIX2, FLOAT_CONFIG_SCHEMA, FLOAT_PAY_PATH, FLOAT_MEMO_PATH, FLOAT_STATUS_PATH, MAX_BODY_BYTES, FLOAT_REFUND_ETA_SECONDS, REFUND_READ_EARLY_MS, REFUND_ETA_MAX_SECONDS, refundDueOf, REFUND_SETTLED_AFTER_MS, REFUND_OUTCOME_NEWS_MS, FINISHING_POLL_MS, FINISHING_LIMIT_MS, SELLER_TIMEOUT_MS, SELLER_TIMEOUT_ABSURD_SECONDS, SELLER_STALL_CHECK_AFTER_MS, SELLER_STALL_CHECK_EVERY_MS, SELLER_STALL_CHECK_TIMEOUT_MS, SELLER_STALL_MISSES, RESULT_LIMIT_BYTES, FLOAT_STATUS_START_MS, FLOAT_STATUS_POLL_MS, FLOAT_STATUS_TIMEOUT_MS, CONFIRM_READ_MS, FLOAT_TRANSFER_DEAD, FLOAT_PAYMENT_REVERTED, VERDICT_POLL_MS, SELLER_ANSWER_VERDICT_MS, TRANSFER_MIN_BLOCKS_LEFT, TRANSFER_FRESH_MS, BLOCK_HEIGHT_TIMEOUT_MS, CONFIG_TIMEOUT_MS, MEMO_UPLOAD_TIMEOUT_MS, CONFIG_CACHE_MS, FLOAT_POOL_WARM_MS, DECIMAL3, POSITIVE, PENDING_CODES, FLOAT_FRONT_HEADER, hash7, fail25, GENERIC_REASON, SELLER_REASON_MAX, SELLER_REASON_READ_BYTES, FEE_PAYER_RESENDS, FEE_PAYER_RESEND_MS, GLOBAL_DISPATCHER5, sortedJson, MODEL_ID, floatPaymentWalName, floatRecordName, FLOAT_KEEP_BYTES_MS, memoryOnlyNeedsScrub, FLOAT_KEEP_OPEN_REQUEST_MS, configCache, configGeneration, configReadSequence, configReads, configRefreshes, SPECULATED_MAX_AGE_MS, speculatedQuotes, poolDomains, FLOAT_FACTS_SCHEMA, floatFacts, floatFactsKey, floatFactsMac, poolDomainReads, poolDomainWarmFailedAt, WARM_RETRY_MS, payerGenerator, etaEntry, loadPayerGenerator, plainText, BROADCAST_REFUSED, BROADCAST_REFUSED_STANDARD, BROADCAST_DEAD, TRANSFER_LANDING_WINDOW_MS, PROOF_DELIVERY_MS, SELF_BROADCAST_LEG1_LEFT_MS, BROADCAST_UNSIGNED, BROADCAST_NO_LOOKUP, BROADCAST_LANDED, BROADCAST_LIMIT_MS, BROADCAST_QUOTE_MARGIN_MS, SELF_BROADCAST_RESEND_MS, SELF_BROADCAST_UNANSWERED_RESEND_MS, SELLER_HEADERS_MAX_COUNT, SELLER_HEADERS_MAX_BYTES, FINAL_AFTER_202_MS, SELLER_HEADERS_KEPT;
111515
+ var import_web3117, FLOAT_PAYMENT_SCHEMA2, REGENERATE_CODES, FLOAT_PAYMENT_WAL_PREFIX2, FLOAT_CONFIG_SCHEMA, FLOAT_PAY_PATH, FLOAT_MEMO_PATH, FLOAT_STATUS_PATH, MAX_BODY_BYTES, FLOAT_REFUND_ETA_SECONDS, REFUND_READ_EARLY_MS, REFUND_ETA_MAX_SECONDS, refundDueOf, REFUND_SETTLED_AFTER_MS, REFUND_OUTCOME_NEWS_MS, FINISHING_POLL_MS, FINISHING_LIMIT_MS, SELLER_TIMEOUT_MS, SELLER_TIMEOUT_ABSURD_SECONDS, SELLER_STALL_CHECK_AFTER_MS, SELLER_STALL_CHECK_EVERY_MS, SELLER_STALL_CHECK_TIMEOUT_MS, SELLER_STALL_MISSES, RESULT_LIMIT_BYTES, FLOAT_STATUS_START_MS, FLOAT_STATUS_POLL_MS, FLOAT_STATUS_TIMEOUT_MS, CONFIRM_READ_MS, FLOAT_TRANSFER_DEAD, FLOAT_PAYMENT_REVERTED, VERDICT_POLL_MS, SELLER_ANSWER_VERDICT_MS, TRANSFER_MIN_BLOCKS_LEFT, TRANSFER_FRESH_MS, BLOCK_HEIGHT_TIMEOUT_MS, CONFIG_TIMEOUT_MS, MEMO_UPLOAD_TIMEOUT_MS, CONFIG_CACHE_MS, FLOAT_POOL_WARM_MS, DECIMAL3, POSITIVE, PENDING_CODES, FLOAT_FRONT_HEADER, hash7, fail25, GENERIC_REASON, SELLER_REASON_MAX, SELLER_REASON_READ_BYTES, FEE_PAYER_RESENDS, FEE_PAYER_RESEND_MS, GLOBAL_DISPATCHER5, sortedJson, MODEL_ID, floatPaymentWalName, floatRecordName, FLOAT_KEEP_BYTES_MS, memoryOnlyNeedsScrub, FLOAT_KEEP_OPEN_REQUEST_MS, configCache, configGeneration, configReadSequence, configReads, configRefreshes, SPECULATED_MAX_AGE_MS, speculatedQuotes, poolDomains, FLOAT_FACTS_SCHEMA, floatFacts, floatFactsKey, floatFactsMac, poolDomainReads, poolDomainWarmFailedAt, WARM_RETRY_MS, payerGenerator, etaEntry, loadPayerGenerator, plainText, quoteLimits, originOf, BROADCAST_REFUSED, BROADCAST_REFUSED_STANDARD, BROADCAST_DEAD, TRANSFER_LANDING_WINDOW_MS, PROOF_DELIVERY_MS, SELF_BROADCAST_LEG1_LEFT_MS, BROADCAST_UNSIGNED, BROADCAST_NO_LOOKUP, BROADCAST_LANDED, BROADCAST_LIMIT_MS, BROADCAST_QUOTE_MARGIN_MS, SELF_BROADCAST_RESEND_MS, SELF_BROADCAST_UNANSWERED_RESEND_MS, SELLER_HEADERS_MAX_COUNT, SELLER_HEADERS_MAX_BYTES, FINAL_AFTER_202_MS, SELLER_HEADERS_KEPT;
111405
111516
  var init_floatPay = __esm({
111406
111517
  "wallet/src/pay/floatPay.mjs"() {
111407
111518
  "use strict";
@@ -111511,6 +111622,14 @@ var init_floatPay = __esm({
111511
111622
  new URL("__bundled_source__/wallet/src/pay/floatPay.mjs", import.meta.url).href
111512
111623
  )), "utf8")).payerKeys.generator;
111513
111624
  plainText = (value2) => value2.replace(/[^ -~]+/g, " ").trim().slice(0, 300);
111625
+ quoteLimits = /* @__PURE__ */ new Map();
111626
+ originOf = (url) => {
111627
+ try {
111628
+ return new URL(typeof url === "string" ? url : url?.url ?? String(url)).origin;
111629
+ } catch {
111630
+ return "";
111631
+ }
111632
+ };
111514
111633
  BROADCAST_REFUSED = /* @__PURE__ */ new Set([
111515
111634
  "unsupported_scheme",
111516
111635
  "pocket_payment_network_unsupported",
@@ -111640,6 +111759,7 @@ async function selfPayOnce({
111640
111759
  }
111641
111760
  if (record && (record.schema !== SELF_PAY_WAL_SCHEMA || record.amountAtomic !== String(amountAtomic))) fail26("id_reused_with_different_amount");
111642
111761
  if (record?.state === "started" && record.refusedCode === "mcp_unshield_stopped") fail26("request_stopped_use_new_unshield_id");
111762
+ if (/^pocket-\d+-f\d+$/.test(unshieldId) && record?.state === "abandoned") fail26("request_closed_use_new_unshield_id");
111643
111763
  if (record?.mode === "direct-exit") fail26("record_is_direct_exit");
111644
111764
  const paymentStarted = () => Boolean(store.readWal(`resource-payment-${sha256Hex2(Buffer.from(selfPayRequestId(unshieldId), "utf8"))}`));
111645
111765
  const recorded = record?.pocketFill === true ? "pocketFill" : record?.ownerUnshield === true ? "owner" : record?.ownerUnshield === false ? "payment" : void 0;
@@ -115719,7 +115839,7 @@ function refusalSay(a, tool, again, npmVersion) {
115719
115839
  const what = total ? `your ${total} USDC` : "your payment";
115720
115840
  if (code2 === "p03_float_seller_refused_after_payment" || code2 === "p03_float_outcome_not_certain") {
115721
115841
  const unsure = code2 === "p03_float_outcome_not_certain";
115722
- const head = unsure ? "An earlier send got no clear answer." : Number.isInteger(a.httpStatus) ? `${Seller} refused it (HTTP ${a.httpStatus}) after payment.` : `${Seller} refused it after payment.`;
115842
+ const head = unsure ? "An earlier send got no clear answer." : `${Seller} refused it after payment.`;
115723
115843
  const kept3 = `Not known yet if ${unsure ? seller : "it"} kept ${what}`;
115724
115844
  const slow = tool === "inference_chat" ? "; the AI provider tried to charge it too late" : ", and this seller is too slow to charge it";
115725
115845
  const late2 = !unsure && floatChargeTooLate(a) ? [
@@ -115727,7 +115847,7 @@ function refusalSay(a, tool, again, npmVersion) {
115727
115847
  `${Seller} took ${a.sellerAnswerSeconds} s; Solana payments expire in about 30 s. ${kept3}. Nothing to do now.`
115728
115848
  ] : [];
115729
115849
  const data2 = tool === "inference_chat" ? "no answer" : "no data";
115730
- const refusedHead = a.httpStatus === 402 ? `${Seller} refused the payment and sent ${data2}.` : Number.isInteger(a.httpStatus) ? `${Seller} refused the request (HTTP ${a.httpStatus}) and sent ${data2}.` : `${Seller} refused the request and sent ${data2}.`;
115850
+ const refusedHead = a.httpStatus === 402 ? `${Seller} refused the payment and sent ${data2}.` : Number.isInteger(a.httpStatus) && a.httpStatus >= 500 ? `${Seller} had a server error and sent ${data2}.` : `${Seller} refused the request and sent ${data2}.`;
115731
115851
  const comesBack = [
115732
115852
  `Your ${total ? `${total} USDC` : "payment"} comes back by itself unless ${seller} still takes it.`,
115733
115853
  `${what[0].toUpperCase()}${what.slice(1)} comes back unless ${seller} still takes it.`
@@ -115744,25 +115864,23 @@ function refusalSay(a, tool, again, npmVersion) {
115744
115864
  }
115745
115865
  if (code2 === "p03_resource_paid_seller_failed") {
115746
115866
  const tx = typeof a.transaction === "string" && /^[1-9A-HJ-NP-Za-km-z]{43,90}$/.test(a.transaction) ? a.transaction : void 0;
115747
- const head = (status) => `${total ? `Paid ${total} USDC` : "Paid"}; ${seller} got paid, but ${a.sellerUnanswered === true ? "sent nothing in time" : `its service failed${status}`}.`;
115748
- const statuses = [...Number.isInteger(a.httpStatus) ? [` (HTTP ${a.httpStatus})`] : [], ""];
115867
+ const head = `${total ? `Paid ${total} USDC` : "Paid"}; ${seller} got paid, but ${a.sellerUnanswered === true ? "sent nothing in time" : "its service failed"}.`;
115749
115868
  return firstFit(
115750
- ...tx ? statuses.map((s3) => `${head(s3)} Shinjuku refunds nothing. Do not pay again; ask its support, giving transaction ${tx}.`) : [],
115751
- ...statuses.map((s3) => `${head(s3)} No refund comes from Shinjuku. Do not pay again; ask its support.`),
115752
- `${head("")} Shinjuku refunds nothing. Do not pay again.`
115869
+ ...tx ? [`${head} Shinjuku refunds nothing. Do not pay again; ask its support, giving transaction ${tx}.`] : [],
115870
+ `${head} No refund comes from Shinjuku. Do not pay again; ask its support.`,
115871
+ `${head} Shinjuku refunds nothing. Do not pay again.`
115753
115872
  );
115754
115873
  }
115755
115874
  if (code2 === "p03_float_transfer_expired") {
115756
- const status = Number.isInteger(a.httpStatus);
115757
- const head = status ? `${Seller} ${sellerAnswered(a.httpStatus, data)}.` : `No ${data} came back in time.`;
115758
- return [
115759
- `${head} Do not pay again yet: unless the payment was taken, ${total ? `${total} USDC` : "it"} returns in about 2 minutes.`,
115760
- `${head} Not known yet if ${status ? "it" : seller} kept ${what}. Do not pay again yet.`
115761
- ].find((line) => words(line) <= SAY_MAX_WORDS) ?? `Not known yet if ${seller} kept ${what}. Do not pay again yet.`;
115875
+ const amount = total ? `${total} USDC` : "the payment";
115876
+ return firstFit(
115877
+ `Not sent again: the transfer expired. Unless ${seller} took it, ${amount} comes back by itself in about 2 to 5 minutes.`,
115878
+ `Not sent again. Unless ${seller} took it, ${amount} comes back by itself in about 2 to 5 minutes.`
115879
+ );
115762
115880
  }
115763
115881
  if (code2 === "p03_float_seller_unanswered_retry_same_request" && a.paid === true) {
115764
115882
  const answer = Number.isInteger(a.httpStatus) ? `${seller} ${sellerAnswered(a.httpStatus, data)}` : `${seller} has not answered yet`;
115765
- const head = a.transferLanded === true ? `${Seller} has your payment, but ${answer}.` : `Sent to Shinjuku; ${answer}. Not known yet whether ${seller} takes it.`;
115883
+ const head = a.transferLanded === true ? `${Seller} has your payment, but ${Number.isInteger(a.httpStatus) ? `it ${sellerAnswered(a.httpStatus, data)}` : "has not answered yet"}.` : `Sent to Shinjuku; ${answer}. Not known yet whether ${seller} takes it.`;
115766
115884
  return [`${head} ${again}`, `${head} ${ask}.`].find((line) => words(line) <= SAY_MAX_WORDS) ?? head;
115767
115885
  }
115768
115886
  if (code2 === "p03_resource_payment_clock_unreadable_retry_same_request" && a.paid === false) {
@@ -115772,6 +115890,10 @@ function refusalSay(a, tool, again, npmVersion) {
115772
115890
  return a.paid === true ? `Paid, but ${seller} has not answered yet. ${again}` : `The result is not known yet. ${again}`;
115773
115891
  }
115774
115892
  if (code2 === "p03_float_fee_account_low") return "Nothing was paid. The payment service's network fee account is low; its operator was alerted. Try again later.";
115893
+ if (code2 === "p03_float_rate_limited_retry_later") {
115894
+ const said = /in about ([0-9]{1,4}) s\b/.exec(next);
115895
+ return `Nothing was paid. Shinjuku cannot check this payment's price right now. Try again in about ${said ? said[1] : 60} seconds.`;
115896
+ }
115775
115897
  if (BUSY.test(code2)) {
115776
115898
  const said = /in about ([0-9]{1,4}) s\b/.exec(next);
115777
115899
  const seconds2 = Number.isFinite(a.readyInSeconds) && a.readyInSeconds > 0 ? Math.ceil(a.readyInSeconds) : said ? Number(said[1]) : 30;
@@ -116643,7 +116765,7 @@ function build(a, tool, npmVersion) {
116643
116765
  }
116644
116766
  if (a.paid === false && !Object.hasOwn(a, "stage") && (tool === void 0 || tool === "pay_for_service")) {
116645
116767
  const status = Number(a.status);
116646
- return a.status === void 0 || status >= 200 && status < 300 ? "The page was free. Nothing was paid." : typeof a.movedTo === "string" ? `The URL moved to ${a.movedTo} and gave no data. Nothing was paid.` : `The URL answered HTTP ${a.status} and did not ask for a payment, so it gave no data. Nothing was paid.`;
116768
+ return a.status === void 0 || status >= 200 && status < 300 ? "The page was free. Nothing was paid." : typeof a.movedTo === "string" ? `The URL moved to ${a.movedTo} and gave no data. Nothing was paid.` : `The URL ${urlAnswered(status)} and did not ask for a payment, so it gave no data. Nothing was paid.`;
116647
116769
  }
116648
116770
  if (a.cancelled === true || a.stage === "cancelled") {
116649
116771
  if (a.privateSend && typeof a.privateSend === "object") return stoppedSay(a);
@@ -116869,7 +116991,7 @@ function plainFields(parsed2, toolName) {
116869
116991
  function withSay(tool, options = {}) {
116870
116992
  return { ...tool, run: async (args, ctx) => withKeepIdNote(addSay(await tool.run(args, ctx), tool.name, options)) };
116871
116993
  }
116872
- var SAY_MAX_WORDS, CHECK_FIRST, MONEY_TOOLS, nextStepOf, DECIMALS, ATOMIC7, SAY_FIRST, SAY_BANNED, CODE_TOKEN, LONG_NUMBER, AI_FLOAT_REFUSED, MOVE_LINE, minutesText, ageWords, MOVING_ROLES, CLOSE_LATER, PAY_CAP_CODES, raiseLine, MOVE_CAP_CODES, LIMIT_MOVE_TOOLS, OWNER_LIMIT_CODES, BUSY, SHIELD_TOOLS, PAY_BALANCE_EMPTY_CODE, PAY_NOTHING_SPENDABLE_CODE, words, firstFit, doneInText, positive, str, refundInFlight, sellerAnswered, OWN_WORK_WORDS, dayLimitWords, DISCOVER_LIST_NAMES, listNames, discoverCutRows, CONFIRMED_SEND_TOOLS, KEEP_ID_NOTE, BALANCE_READ_DOES, SAFE_BALANCE_READ;
116994
+ var SAY_MAX_WORDS, CHECK_FIRST, MONEY_TOOLS, nextStepOf, DECIMALS, ATOMIC7, SAY_FIRST, SAY_BANNED, CODE_TOKEN, LONG_NUMBER, AI_FLOAT_REFUSED, MOVE_LINE, minutesText, ageWords, MOVING_ROLES, CLOSE_LATER, PAY_CAP_CODES, raiseLine, MOVE_CAP_CODES, LIMIT_MOVE_TOOLS, OWNER_LIMIT_CODES, BUSY, SHIELD_TOOLS, PAY_BALANCE_EMPTY_CODE, PAY_NOTHING_SPENDABLE_CODE, words, firstFit, doneInText, positive, str, refundInFlight, sellerAnswered, urlAnswered, OWN_WORK_WORDS, dayLimitWords, DISCOVER_LIST_NAMES, listNames, discoverCutRows, CONFIRMED_SEND_TOOLS, KEEP_ID_NOTE, BALANCE_READ_DOES, SAFE_BALANCE_READ;
116873
116995
  var init_say = __esm({
116874
116996
  "wallet/src/mcp/say.mjs"() {
116875
116997
  "use strict";
@@ -116933,7 +117055,8 @@ var init_say = __esm({
116933
117055
  positive = (text3) => text3 !== void 0 && text3 !== "0";
116934
117056
  str = (value2) => typeof value2 === "string" ? value2 : "";
116935
117057
  refundInFlight = (a) => Array.isArray(a.refundNotices) && a.refundNotices.length ? void 0 : usdcText2(a.breakdown?.refundsInFlightAtomic);
116936
- sellerAnswered = (status, data) => status >= 400 ? `answered an error (HTTP ${status})` : `sent no ${data} (HTTP ${status})`;
117058
+ sellerAnswered = (status, data) => status >= 500 ? "had a server error" : status >= 400 ? "refused the request" : `sent no ${data}`;
117059
+ urlAnswered = (status) => status === 404 || status === 410 ? "was not found" : status === 401 || status === 403 ? "refused access" : status >= 500 ? "had a server error" : "refused the request";
116937
117060
  OWN_WORK_WORDS = Object.freeze({
116938
117061
  token_transfer: "your older token transfer",
116939
117062
  shield: "your shield",
@@ -121961,6 +122084,27 @@ async function fillPockets({
121961
122084
  reconcileFills(store);
121962
122085
  fill = void 0;
121963
122086
  }
122087
+ if (!newFills && fill?.state === "started" && selfPayNeverMade(store, fill)) {
122088
+ const name = `self-pay-${fill.unshieldId}`;
122089
+ const record = store.readWal(name);
122090
+ if (!record) {
122091
+ store.writeWal(name, {
122092
+ schema: SELF_PAY_WAL_SCHEMA,
122093
+ state: "abandoned",
122094
+ amountAtomic: String(fill.amountAtomic),
122095
+ ownerUnshield: false,
122096
+ pocketFill: true,
122097
+ closedReason: "never_made"
122098
+ });
122099
+ } else if (record.state === "started") {
122100
+ store.writeWal(name, { ...record, state: "abandoned", closedReason: "never_made" });
122101
+ }
122102
+ say2("Money an older version started to set aside never left the wallet; it stays in your private balance.");
122103
+ fill.state = "abandoned";
122104
+ store.save();
122105
+ reconcileFills(store);
122106
+ fill = void 0;
122107
+ }
121964
122108
  if (fill && heldFill(fill)) {
121965
122109
  if (await releaseIfDead({ store, steps, clock: clock2, entry, fill, onReleased })) return RELEASED;
121966
122110
  throw heldRefusal(fill.relayRefusal);
@@ -122134,7 +122278,7 @@ function releaseRefusedFill(store, entry, fill) {
122134
122278
  reconcileFills(store);
122135
122279
  return { index: entry.index, unshieldId: fill.unshieldId, amountAtomic: fill.amountAtomic, released: true };
122136
122280
  }
122137
- var import_web3125, PERMANENT_RELAY_REFUSAL, RELEASABLE_RELAY_REFUSAL, NOTE_EXIT_VALID_BEFORE_INPUT2, EXIT_WINDOW_AFTER_SELF_PAY_S, MAX_RELEASE_WAIT_MS, RELEASE_WAIT_STEP_MS, RELEASED_WORDS, MAX_FILLS_PER_RUN, ANCHOR_WAIT_MS, EPOCH_MARGIN_MS2, NOT_FINALIZED_RETRY_MS, firstCode, DEAD_MARGIN_MS, fillNoteCommitment, noteExitName, selfPayKey, selfPayRecord, QUOTE_RAN_OUT, SELF_PAY_NEVER_LANDED, fail37, pendingFill2, RELEASED, stderrSay, heldFill, unreconciledRelease;
122281
+ var import_web3125, PERMANENT_RELAY_REFUSAL, RELEASABLE_RELAY_REFUSAL, NOTE_EXIT_VALID_BEFORE_INPUT2, EXIT_WINDOW_AFTER_SELF_PAY_S, MAX_RELEASE_WAIT_MS, RELEASE_WAIT_STEP_MS, RELEASED_WORDS, MAX_FILLS_PER_RUN, ANCHOR_WAIT_MS, EPOCH_MARGIN_MS2, NOT_FINALIZED_RETRY_MS, firstCode, DEAD_MARGIN_MS, fillNoteCommitment, noteExitName, selfPayKey, selfPayRecord, selfPayNeverMade, QUOTE_RAN_OUT, SELF_PAY_NEVER_LANDED, fail37, pendingFill2, RELEASED, stderrSay, heldFill, unreconciledRelease;
122138
122282
  var init_fill = __esm({
122139
122283
  "wallet/src/pocket/fill.mjs"() {
122140
122284
  "use strict";
@@ -122169,6 +122313,7 @@ var init_fill = __esm({
122169
122313
  noteExitName = (note, recipient) => `note-exit-${sha256Hex2(Buffer.from(`${note}:${recipient}`)).slice(0, 32)}`;
122170
122314
  selfPayKey = (fill) => sha256Hex2(Buffer.from(selfPayRequestId(fill.unshieldId), "utf8"));
122171
122315
  selfPayRecord = (store, fill) => store.readWal(`resource-payment-${selfPayKey(fill)}`);
122316
+ selfPayNeverMade = (store, fill) => !selfPayRecord(store, fill) && store.readWal(`resource-proof-${selfPayKey(fill)}`)?.proved === void 0;
122172
122317
  QUOTE_RAN_OUT = /^p03_resource_payment_quote_expired(_before_submission)?$/;
122173
122318
  SELF_PAY_NEVER_LANDED = "p03_self_pay_payment_never_finalized_use_new_unshield_id";
122174
122319
  fail37 = (reason) => {
@@ -154862,7 +155007,7 @@ function priceOf(text3) {
154862
155007
  if (BigInt(parsed2.atomic) > MAX_PRICE_ATOMIC) return { refusal: "That price is above the most one payment may cost here (1000 USDC): give a lower price, for example 0.01." };
154863
155008
  return { value: parsed2.atomic };
154864
155009
  }
154865
- function originOf(text3) {
155010
+ function originOf2(text3) {
154866
155011
  let url;
154867
155012
  try {
154868
155013
  url = configuredUrl(text3, { httpsOnly: true });
@@ -155117,7 +155262,7 @@ async function setUpWith({ values, deps, terminal, say: say2, home, wallet, make
155117
155262
  flag: "--public-origin",
155118
155263
  question: `The public https address buyers reach, for example ${EXAMPLE_ORIGIN} (a tunnel such as Cloudflare Tunnel, or your reverse proxy such as Caddy or nginx, sends it to this computer):`,
155119
155264
  fallback: typeof old?.publicOrigin === "string" ? old.publicOrigin : void 0,
155120
- check: async (text3) => originOf(text3)
155265
+ check: async (text3) => originOf2(text3)
155121
155266
  },
155122
155267
  {
155123
155268
  flag: "--port",
@@ -157960,6 +158105,10 @@ var reclaimedAny = (store, plan) => splitDepositIds(plan.fundsId, splitOf(plan))
157960
158105
  function unfinishedFundsPlan(store) {
157961
158106
  return fundsPlans(store).filter((plan) => isUnfinished(store, plan)).at(-1);
157962
158107
  }
158108
+ function olderMoneyPlan(store) {
158109
+ if (!olderFillsOpen(store).length) return void 0;
158110
+ return fundsPlans(store).filter((plan) => !reclaimedAny(store, plan) && !oldRouteStopped(store, plan) && !["address", "funding"].includes(currentStage(store, plan))).at(-1);
158111
+ }
157963
158112
  var isUnfinished = (store, plan) => !plan.done?.ready && !reclaimedAny(store, plan) && !oldRouteStopped(store, plan);
157964
158113
  function nextFundsId(store) {
157965
158114
  const taken = new Set(store.listWal());
@@ -158042,7 +158191,16 @@ function fundsView(store, plan, { now = Date.now(), running } = {}) {
158042
158191
  ...split4 === 1 && deposit?.receipt?.signature ? { depositSignature: deposit.receipt.signature } : {},
158043
158192
  lastUpdate: plan.status?.at ?? plan.createdAt
158044
158193
  };
158045
- if (!stage) {
158194
+ const older = stage ? [] : olderFillsOpen(store);
158195
+ if (older.length) {
158196
+ view2.ready = false;
158197
+ view2.stage = "older-money";
158198
+ const amount = `${usdc3(older.reduce((sum2, fill) => sum2 + BigInt(fill.amountAtomic), 0n), decimals)} USDC`;
158199
+ const words2 = `your deposit arrived, but ${amount} that an older version of the wallet started to set aside for payments is not finished yet. That money is safe: nothing was lost and nothing moves twice`;
158200
+ view2.olderMoney = { fills: older.length, amount, words: words2 };
158201
+ view2.status = `older-money: ${words2}`;
158202
+ view2.next = `run ${commandLine("add-funds")} again: it finishes that money first, then says what you can spend`;
158203
+ } else if (!stage) {
158046
158204
  const parts2 = balanceNow(store, { now });
158047
158205
  const words2 = balanceWords(parts2);
158048
158206
  const fundedAccounts2 = parts2?.report?.detail?.fundedAccounts;
@@ -158617,12 +158775,9 @@ function pocketFillArgs(ctx) {
158617
158775
  values.passphraseFile,
158618
158776
  // No --rpc-file: the step reads the URL from UNDERMARKET_SOLANA_RPC_URL (childEnv), the one this run resolved.
158619
158777
  ...values.rpcFile === void 0 ? [] : ["--rpc-file", values.rpcFile],
158620
- "--payer-proof-tools",
158621
- values.proofTools,
158622
- "--exit-proof-tools",
158623
- values.exitProofTools,
158624
- "--profile",
158625
- values.profile,
158778
+ // A file this run has no value for is left out, never passed as "undefined" (to-do 33: ENOENT on every resume): add-funds
158779
+ // gets them from this home's config.json (shinjukuWallet.mjs configDefaults); without one the step refuses by its name.
158780
+ ...[["--payer-proof-tools", values.proofTools], ["--exit-proof-tools", values.exitProofTools], ["--profile", values.profile]].flatMap(([name, value2]) => value2 === void 0 ? [] : [name, value2]),
158626
158781
  "--program",
158627
158782
  values.program,
158628
158783
  "--facilitator",
@@ -158662,10 +158817,13 @@ async function recoverOlderPockets(ctx, openStore) {
158662
158817
  states = [];
158663
158818
  }
158664
158819
  const exited = states.includes("exited");
158665
- const closed2 = states.some((state2) => state2 === "abandoned" || state2 === "released");
158820
+ const abandoned = states.includes("abandoned");
158821
+ const releasedNow = states.includes("released");
158822
+ const closed2 = abandoned || releasedNow;
158666
158823
  const open5 = !states.length || states.some((state2) => state2 === "started" || state2 === "paid" || state2 === void 0);
158667
158824
  if (exited) ctx.say("pocket", "done: that money is set aside for payments now, and this wallet pays from it first");
158668
- if (closed2) ctx.say("pocket", "that earlier step had moved nothing, so it was closed and its money stays in your private balance");
158825
+ if (abandoned) ctx.say("pocket", "that earlier step sent nothing, so it was closed and its money stays in your private balance");
158826
+ if (releasedNow) ctx.say("pocket", "Shinjuku did not take that earlier step, so its money came back to your private balance");
158669
158827
  if (open5 && !finished.aborted) {
158670
158828
  ctx.say("pocket", `that step did not finish${finished.exit !== 0 ? ` (${finished.code ?? "no error code"})` : ""}; that money stays set aside, the next add-funds run tries again, and nothing moves twice`);
158671
158829
  }
@@ -158674,6 +158832,13 @@ async function recoverOlderPockets(ctx, openStore) {
158674
158832
  function unfinishedFillIds(store) {
158675
158833
  return pocketBook(store).entries.flatMap((entry) => entry.fills).filter((fill) => (fill.state === "started" || fill.state === "paid") && !(fill.state === "paid" && RELEASABLE_RELAY_REFUSAL.test(fill.relayRefusal ?? ""))).map((fill) => fill.unshieldId);
158676
158834
  }
158835
+ function olderFillsOpen(store) {
158836
+ try {
158837
+ return pocketBook(store).entries.flatMap((entry) => entry.fills).filter((fill) => (fill.state === "started" || fill.state === "paid" && !fill.relayRefusal) && /^[1-9][0-9]*$/.test(String(fill.amountAtomic ?? "")));
158838
+ } catch {
158839
+ return [];
158840
+ }
158841
+ }
158677
158842
  function heldFillIds(store) {
158678
158843
  try {
158679
158844
  return pocketBook(store).entries.flatMap((entry) => entry.fills.filter((fill) => fill.state === "paid" && fill.relayRefusal).map((fill) => fill.unshieldId));
@@ -158924,9 +159089,11 @@ async function addFunds(values, deps) {
158924
159089
  });
158925
159090
  if (resolved.shown) {
158926
159091
  await recoverOlderPockets(ctx, openStore);
159092
+ const view3 = fundsView(openStore(), plan, { now: deps.now() });
159093
+ if (!view3.ready) throw failure("stopped", `${view3.olderMoney.words}. ${sentence(view3.next.replace(/^r/, "R"))}`);
158927
159094
  io.err(`add-funds ${plan.fundsId} is ready already, so nothing new was started.
158928
159095
  `);
158929
- printEnd(deps, fundsView(openStore(), plan, { now: deps.now() }), ctx.terminal);
159096
+ printEnd(deps, view3, ctx.terminal);
158930
159097
  return;
158931
159098
  }
158932
159099
  if (oldRouteStopped(store, plan)) {
@@ -158976,10 +159143,15 @@ async function addFunds(values, deps) {
158976
159143
  while (!abort.signal.aborted) {
158977
159144
  const stage = markDone();
158978
159145
  if (!stage) {
159146
+ const view3 = fundsView(openStore(), plan, { now: deps.now() });
159147
+ if (!view3.ready) {
159148
+ plan.status = { stage: "balance", at: iso(deps.now()), stopped: "older_money_not_finished", waitsFor: view3.olderMoney.words };
159149
+ save2();
159150
+ throw failure("stopped", `${view3.olderMoney.words}. ${sentence(view3.next.replace(/^r/, "R"))}`);
159151
+ }
158979
159152
  plan.done = { ...plan.done, ready: iso(deps.now()) };
158980
159153
  plan.status = { stage: "ready", at: iso(deps.now()) };
158981
159154
  save2();
158982
- const view3 = fundsView(openStore(), plan, { now: deps.now() });
158983
159155
  if (!ctx.terminal) ctx.say("ready", view3.status);
158984
159156
  printEnd(deps, view3, ctx.terminal);
158985
159157
  return;
@@ -163783,6 +163955,35 @@ async function requireBackupBeforeAddress(deps, io, walletFile, again) {
163783
163955
  }
163784
163956
  throw new PublicFailure(`backup_needed: this wallet has no backup yet, so no deposit address was made; nothing was moved. A folder made by the backup-export command alone is not a backup: it cannot open the wallet without the recovery file and the passphrase file. To make one, ${confirmSteps}`);
163785
163957
  }
163958
+ function addFundsMakesAddress(values, deps) {
163959
+ try {
163960
+ const store = deps.openWalletStore(deps.walletPath(values.get("--pool")), payerPassphrase(values, deps));
163961
+ const wanted = values.get("--funds-id");
163962
+ const plan = wanted !== void 0 ? fundsPlans(store).find((entry) => entry.fundsId === wanted) : (!values.has("--amount") ? olderMoneyPlan(store) : void 0) ?? unfinishedFundsPlan(store);
163963
+ if (!plan) return true;
163964
+ if (plan.done?.ready) return false;
163965
+ const asked = values.get("--split");
163966
+ if (asked !== void 0 && String(asked) !== String(plan.split ?? 1)) return true;
163967
+ return fundsView(store, plan).stage === "address";
163968
+ } catch {
163969
+ return true;
163970
+ }
163971
+ }
163972
+ async function backupReminder(deps, io, walletFile) {
163973
+ const home = walletFile !== void 0 ? dirname41(dirname41(resolve41(walletFile))) : setupHome(deps.env);
163974
+ let config;
163975
+ try {
163976
+ config = readSetupConfig(home);
163977
+ } catch {
163978
+ config = null;
163979
+ }
163980
+ if (!config?.pool || walletFile !== void 0 && !sameFile(walletFile, homeWalletPath(home, config.pool))) return;
163981
+ if (!backupNeeded(home)) return;
163982
+ if (deps.stdinIsTTY() && deps.stdoutIsTTY?.() === true) await offerBackup({ ...deps, io }, home);
163983
+ if (!backupNeeded(home)) return;
163984
+ io.err(`This wallet has no backup yet. This run goes on, because it only finishes money you already sent, and it makes no new address. Make a backup now: run ${CLI_WORD} add-funds in a terminal and answer its backup question, or ask your agent app to "save my backup". Without a backup, this money is lost if this computer is lost.
163985
+ `);
163986
+ }
163786
163987
  async function backupAfterExport(values, deps, io) {
163787
163988
  const home = setupHome(deps.env);
163788
163989
  let config;
@@ -164973,18 +165174,32 @@ async function fillAddFunds(values, deps) {
164973
165174
  const command = COMMAND_BY_NAME.get("add-funds");
164974
165175
  const terminal = deps.stdinIsTTY() && deps.stdoutIsTTY?.() === true;
164975
165176
  let plan;
165177
+ let arrived2 = false;
165178
+ let shownOnly = false;
164976
165179
  if (!values.has("--route") || !values.has("--amount")) {
164977
165180
  try {
164978
165181
  const store = deps.openWalletStore(deps.walletPath(values.get("--pool")), payerPassphrase(values, deps));
164979
165182
  const wanted = values.get("--funds-id");
164980
- plan = wanted !== void 0 ? fundsPlans(store).find((entry) => entry.fundsId === wanted && !entry.done?.ready) : unfinishedFundsPlan(store);
165183
+ const older = wanted === void 0 && !values.has("--amount") ? olderMoneyPlan(store) : void 0;
165184
+ if (older) values.set("--funds-id", older.fundsId);
165185
+ plan = older ?? (wanted !== void 0 ? fundsPlans(store).find((entry) => entry.fundsId === wanted) : unfinishedFundsPlan(store));
165186
+ try {
165187
+ const stage = plan ? fundsView(store, plan).stage : void 0;
165188
+ arrived2 = Boolean(plan) && !["address", "funding"].includes(stage);
165189
+ shownOnly = stage === "ready";
165190
+ } catch {
165191
+ arrived2 = false;
165192
+ }
164981
165193
  } catch {
164982
165194
  plan = void 0;
164983
165195
  }
164984
165196
  }
164985
165197
  const kept3 = /^[1-9][0-9]{0,19}$/.test(String(plan?.amountAtomic ?? "")) ? plan.amountAtomic : void 0;
164986
165198
  if (!plan && !values.has("--route")) values.set("--route", "exchange");
164987
- if (!values.has("--amount")) {
165199
+ if (kept3 && arrived2 && !values.has("--amount")) {
165200
+ if (!shownOnly) deps.io.err(`This finishes the add-funds run of ${usdcText4(kept3)} USDC: that USDC arrived already, so nothing more is needed from you.
165201
+ `);
165202
+ } else if (!values.has("--amount")) {
164988
165203
  if (terminal) await offerCloseAddMoney(values, deps);
164989
165204
  if (kept3) {
164990
165205
  const least = usdcText4(PAY_ME_MIN_ATOMIC.toString());
@@ -165222,7 +165437,8 @@ var COMMANDS = [
165222
165437
  } catch {
165223
165438
  walletFile = void 0;
165224
165439
  }
165225
- await requireBackupBeforeAddress(deps, io, walletFile, `${CLI_WORD} add-funds`);
165440
+ if (addFundsMakesAddress(values, deps)) await requireBackupBeforeAddress(deps, io, walletFile, `${CLI_WORD} add-funds`);
165441
+ else await backupReminder(deps, io, walletFile);
165226
165442
  await fillAddFunds(values, { ...deps, io });
165227
165443
  return deps.fundsMain("add-funds", values, { ...deps, io });
165228
165444
  }
@@ -165316,7 +165532,13 @@ var COMMANDS = [
165316
165532
  } catch {
165317
165533
  walletFile = void 0;
165318
165534
  }
165319
- await requireBackupBeforeAddress(deps, io, walletFile, `${CLI_WORD} add-funds`);
165535
+ let recorded = false;
165536
+ try {
165537
+ recorded = walletFile !== void 0 && Boolean(deps.openWalletStore(walletFile, payerPassphrase(values, deps)).readWal(`deposit-${values.get("--deposit-id")}`));
165538
+ } catch {
165539
+ recorded = false;
165540
+ }
165541
+ if (!recorded) await requireBackupBeforeAddress(deps, io, walletFile, `${CLI_WORD} add-funds`);
165320
165542
  }
165321
165543
  return runDeposit(args, values, deps);
165322
165544
  }
@@ -166731,7 +166953,8 @@ function configDefaults(command, args, deps) {
166731
166953
  const wantWallet = !has2("--pool") && has2("--wallet") && !given.has("--wallet");
166732
166954
  const wantFile = Boolean(passphraseFileSpec) && !given.has("--passphrase-file") && (passphraseFileSpec.required || !envPassphrase);
166733
166955
  const wantEnv = !passphraseFileSpec && command.env.includes(PASSPHRASE_ENV3) && !envPassphrase;
166734
- if (!wantPool && !wantWallet && !wantFile && !wantEnv) return unchanged;
166956
+ const wantOptional = command.name === "add-funds" && (!given.has("--exit-proof-tools") || !given.has("--profile"));
166957
+ if (!wantPool && !wantWallet && !wantFile && !wantEnv && !wantOptional) return unchanged;
166735
166958
  const home = setupHome(deps.env);
166736
166959
  const config = setupConfigOf(home);
166737
166960
  if (!config) return unchanged;
@@ -166744,9 +166967,11 @@ function configDefaults(command, args, deps) {
166744
166967
  ["--memo-service", config.memoService],
166745
166968
  // T9 (live run 2026-10-23 18:44 UTC, npm 0.3.83): unshield refused "missing 7 flags" although config.json holds its
166746
166969
  // files; merge (the step an unshield of the whole balance names) takes the same ones.
166747
- ...["unshield", "prepare"].includes(command.name) ? [["--payer-proof-tools", config.proofTools], ["--exit-proof-tools", config.exitProofTools], ["--profile", config.profile]] : []
166970
+ // add-funds (to-do 33, live run npm 0.3.196 2026-11-08 19:10 UTC): its hidden --exit-proof-tools/--profile were never in
166971
+ // a set-up home's run, so its resume of an older pocket fill passed "undefined" and failed ENOENT on every run.
166972
+ ...["unshield", "prepare", "add-funds"].includes(command.name) ? [["--payer-proof-tools", config.proofTools], ["--exit-proof-tools", config.exitProofTools], ["--profile", config.profile]] : []
166748
166973
  ];
166749
- const fromConfigAlways = new Set(command.name === "curl" ? ["--proof-tools"] : []);
166974
+ const fromConfigAlways = new Set(command.name === "curl" ? ["--proof-tools"] : command.name === "add-funds" ? ["--exit-proof-tools", "--profile"] : []);
166750
166975
  const needed = (spec) => spec.required || fromConfigAlways.has(spec.name) || spec.refreshOnly && given.has("--refresh") || spec.requiredUnless && !given.has(spec.requiredUnless);
166751
166976
  if (wantPool || wantWallet || given.has("--wallet") || given.get("--pool") === config.pool) {
166752
166977
  for (const [name, value2] of fromConfig) {