shinjuku-shield 0.3.201 → 0.3.203

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.201. The command is `shinjuku`.
8
+ This is version 0.3.203. The command is `shinjuku`.
9
9
 
10
10
  ## Set up
11
11
 
12
12
  ```sh
13
- npx -y shinjuku@0.3.201 setup
13
+ npx -y shinjuku@0.3.203 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.201 mcp
110
+ claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.203 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.201", "mcp"] } } }
117
+ { "mcpServers": { "shinjuku": { "command": "npx", "args": ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.203", "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.201", "mcp"]
129
+ args = ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.203", "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.201, its older name, runs this package at the same version, so wallets
147
+ 0.3.203, 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": "571f1b887cf0dbf6b36b6c44932d84de22f13951d26d6c5484dddb44cbfed643",
5
- "bytes": 9479351,
6
- "sourceCommit": "fce3de21b6d6f99c10483960e536f000327bb3b2",
4
+ "sha256": "b5d26888908f60a311b42d9d0ba42bb5be37f1464a4bdcfe1ef3ea4534363443",
5
+ "bytes": 9493844,
6
+ "sourceCommit": "83c229cc05ec51cbedb6720e31c9f21fb5e8a540",
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",
@@ -1932,5 +1932,5 @@
1932
1932
  }
1933
1933
  ]
1934
1934
  },
1935
- "publishedAt": "2026-11-09T05:18:22.436Z"
1935
+ "publishedAt": "2026-11-09T07:57:59.571Z"
1936
1936
  }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "shinjuku-shield",
3
- "version": "0.3.201",
3
+ "version": "0.3.203",
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": "571f1b88",
7
- "shinjukuSha256": "571f1b887cf0dbf6b36b6c44932d84de22f13951d26d6c5484dddb44cbfed643",
6
+ "shinjukuRelease": "b5d26888",
7
+ "shinjukuSha256": "b5d26888908f60a311b42d9d0ba42bb5be37f1464a4bdcfe1ef3ea4534363443",
8
8
  "license": "SEE LICENSE IN LICENSE.txt",
9
9
  "author": "Shinjuku Shield",
10
10
  "homepage": "https://github.com/ShinjukuStaition/shinjuku-shield#readme",
@@ -43905,6 +43905,8 @@ function afterOnionRace(url, signal) {
43905
43905
  function markFirstOnionRaces(timingLog) {
43906
43906
  if (firstRacesMarked) return;
43907
43907
  firstRacesMarked = true;
43908
+ moveTimingLog = timingLog;
43909
+ for (const move of moveRecords.splice(0)) writeMove(move);
43908
43910
  for (const record of firstRaceRecords) {
43909
43911
  record.then((race) => {
43910
43912
  const mark = timingLog.start({ startedAt: race.startedAt });
@@ -44227,12 +44229,7 @@ async function routeFacilitatorsOverOnion(argv2, {
44227
44229
  firstRaceRecords.push(new Promise((resolve43) => {
44228
44230
  ended2 = resolve43;
44229
44231
  }));
44230
- const pinned = group.onions.length - (group.spares?.length ?? 0);
44231
- const role = (onion) => {
44232
- const index = group.onions.indexOf(onion);
44233
- if (kind === "history") return index < pinned ? `history${index + 1}` : `history-spare${index - pinned + 1}`;
44234
- return index < pinned ? `pinned${index + 1}` : `spare${index - pinned + 1}`;
44235
- };
44232
+ const role = (onion) => roleOf(group, onion);
44236
44233
  const note = (entry) => {
44237
44234
  if (record.endedAt === void 0) record.probes.push({ ...entry, at: Date.now() });
44238
44235
  };
@@ -44300,7 +44297,7 @@ async function routeFacilitatorsOverOnion(argv2, {
44300
44297
  } } : {}
44301
44298
  }).startSpares;
44302
44299
  }
44303
- const moveOn = (group, onion, why) => {
44300
+ const moveOn = (group, onion, why, { request, ageMs }) => {
44304
44301
  if (stopped || group.winner !== onion || group.pending) return;
44305
44302
  group.moves = (group.moves ?? 0) + 1;
44306
44303
  const max = group.onions.length;
@@ -44314,7 +44311,11 @@ async function routeFacilitatorsOverOnion(argv2, {
44314
44311
  const others = fresh.length > 0 ? fresh : group.onions.filter((other) => other !== onion);
44315
44312
  group.live = group.onions.length;
44316
44313
  group.winner = void 0;
44317
- err(`tor: the onion ${hostOf(onion)} of ${group.label} gave no answer (${why}); its requests move to the first of ${others.map(hostOf).join(", ")} to answer (move ${group.moves} of ${max})
44314
+ const role = roleOf(group, onion);
44315
+ const move = { at: Date.now(), role, request, cause: why === "the stream failed" ? "stream_failed" : "timeout", ageMs };
44316
+ if (moveTimingLog) writeMove(move);
44317
+ else moveRecords.push(move);
44318
+ err(`tor: the onion ${hostOf(onion)} of ${group.label} gave no answer (${why}); its requests move to the first of ${others.map(hostOf).join(", ")} to answer (move ${group.moves} of ${max}; the request was ${request} to ${role}, sent ${(ageMs / 1e3).toFixed(1)} s before)
44318
44319
  `);
44319
44320
  race(group, others, { onNone: () => err(`tor: no other onion of ${group.label} answered; its requests go to ${hostOf(others[0])} and wait for it
44320
44321
  `) });
@@ -44348,6 +44349,7 @@ async function routeFacilitatorsOverOnion(argv2, {
44348
44349
  }
44349
44350
  }
44350
44351
  const target = `${onion}${url.pathname}${url.search}`;
44352
+ const sentAt = Date.now();
44351
44353
  const sent = original(input instanceof Request ? new Request(target, input) : target, onionInit(init));
44352
44354
  if (group.onions.length < 2) return sent;
44353
44355
  return sent.then((response) => {
@@ -44358,7 +44360,7 @@ async function routeFacilitatorsOverOnion(argv2, {
44358
44360
  return response;
44359
44361
  }, (error) => {
44360
44362
  const why = noAnswer(error, signal);
44361
- if (why && !init?.ownLane) moveOn(group, onion, why);
44363
+ if (why && !init?.ownLane) moveOn(group, onion, why, { request: requestLabel(group, method, url), ageMs: Date.now() - sentAt });
44362
44364
  throw error;
44363
44365
  });
44364
44366
  };
@@ -44380,7 +44382,7 @@ async function routeFacilitatorsOverOnion(argv2, {
44380
44382
  }
44381
44383
  };
44382
44384
  }
44383
- var SITE_ONIONS, SITE_SPARE_ONIONS, PINNED_FACILITATOR_ONIONS, PINNED_SPARE_ONIONS, HISTORY_ONIONS, HISTORY_SPARE_ONIONS, PINNED_HISTORY_ONIONS, PINNED_HISTORY_SPARE_ONIONS, HISTORY_PROBE_PATH, SITE_PROBE_PATH, SITE_PROBE_ANSWERS, KEPT_ANSWER_MS, KEPT_ANSWER_BYTES, KEPT_BODY_MS, FACILITATOR_FLAGS, V3_ONION, DISCOVERY_TIMEOUT_MS, WARM_TIMEOUT_MS, RACE_TIMEOUT_MS, ROUTE_WAIT_MS, SPARE_AFTER_MS, SPARE_CAUSE, routedGroups, liveOnions, hostOf, noAnswer, routedOnions, routedOrigins, onionsOfOrigin, routesOverOnion, routedGroupOf, firstRaces, firstRaceRecords, firstRacesMarked, firstOnionRace, GLOBAL_DISPATCHER3, onionDispatchers, ownTag, ownTagDispatchers, onOwnTagNow, ownTagInit;
44385
+ var SITE_ONIONS, SITE_SPARE_ONIONS, PINNED_FACILITATOR_ONIONS, PINNED_SPARE_ONIONS, HISTORY_ONIONS, HISTORY_SPARE_ONIONS, PINNED_HISTORY_ONIONS, PINNED_HISTORY_SPARE_ONIONS, HISTORY_PROBE_PATH, SITE_PROBE_PATH, SITE_PROBE_ANSWERS, KEPT_ANSWER_MS, KEPT_ANSWER_BYTES, KEPT_BODY_MS, FACILITATOR_FLAGS, V3_ONION, DISCOVERY_TIMEOUT_MS, WARM_TIMEOUT_MS, RACE_TIMEOUT_MS, ROUTE_WAIT_MS, SPARE_AFTER_MS, SPARE_CAUSE, routedGroups, liveOnions, hostOf, noAnswer, routedOnions, routedOrigins, onionsOfOrigin, routesOverOnion, routedGroupOf, firstRaces, firstRaceRecords, firstRacesMarked, roleOf, ROUTE_LABELS, requestLabel, moveRecords, moveTimingLog, writeMove, firstOnionRace, GLOBAL_DISPATCHER3, onionDispatchers, ownTag, ownTagDispatchers, onOwnTagNow, ownTagInit;
44384
44386
  var init_facilitatorOnion = __esm({
44385
44387
  "wallet/src/net/facilitatorOnion.mjs"() {
44386
44388
  "use strict";
@@ -44439,6 +44441,48 @@ var init_facilitatorOnion = __esm({
44439
44441
  firstRaces = /* @__PURE__ */ new Map();
44440
44442
  firstRaceRecords = [];
44441
44443
  firstRacesMarked = false;
44444
+ roleOf = (group, onion) => {
44445
+ const index = group.onions.indexOf(onion);
44446
+ const pinned = group.onions.length - (group.spares?.length ?? 0);
44447
+ if (group.kind === "history") return index < pinned ? `history${index + 1}` : `history-spare${index - pinned + 1}`;
44448
+ return index < pinned ? `pinned${index + 1}` : `spare${index - pinned + 1}`;
44449
+ };
44450
+ ROUTE_LABELS = [
44451
+ [/^\/api\/solana-rpc\/?$/, "solana_rpc"],
44452
+ [/^\/api\/wallet\/release\/?$/, "wallet_release"],
44453
+ [/^\/api\/health\/?$/, "health"],
44454
+ [/^\/api\/x402\/(anchor|supported|verify|settle|claim|exit|seller-profile)\/?$/, (m) => `x402_${m[1].replaceAll("-", "_")}`],
44455
+ [/^\/api\/x402\/deposit\/?$/, "deposit"],
44456
+ [/^\/api\/x402\/deposit\/reclaim\/?$/, "deposit_reclaim"],
44457
+ [/^\/api\/x402\/float\/config\/?$/, "float_config"],
44458
+ [/^\/api\/x402\/float\/(pay|memo|status)(\/[^/]+)?\/?$/, (m) => `float_${m[1]}`],
44459
+ [/^\/api\/x402\/move\/(pay|status)(\/[^/]+)?\/?$/, (m) => `move_${m[1]}`],
44460
+ [/^\/api\/x402\/succession\/move\/?$/, "succession_move"],
44461
+ [/^\/api\/x402\/inbound\/(config|lanes|open|accounts|sale-address|sales)(\/.*)?$/, (m) => `inbound_${m[1].replaceAll("-", "_")}`],
44462
+ [/^\/api\/shielded-x402\/memos\/?$/, "memos"],
44463
+ [/^\/api\/shielded-x402\/memos\/batch\/?$/, "memos_batch"],
44464
+ [/^\/api\/shielded-x402\/memos\/[^/]+\/?$/, "memos_one"],
44465
+ [/^\/api\/shielded-commerce\/config\/?$/, "commerce_config"],
44466
+ [/^\/api\/agent\/claim-item\/?$/, "claim_item"],
44467
+ [/^\/wallet\/[^/]+\/manifest\.json$/, "wallet_manifest"]
44468
+ ];
44469
+ requestLabel = (group, method, url) => {
44470
+ const verb = /^[A-Z]{1,10}$/.test(method) ? method.toLowerCase() : "other";
44471
+ if (group.kind === "history") return `${verb}_history_read`;
44472
+ for (const [pattern, label] of ROUTE_LABELS) {
44473
+ const match = pattern.exec(url.pathname);
44474
+ if (match) return `${verb}_${typeof label === "function" ? label(match) : label}`;
44475
+ }
44476
+ return `${verb}_other`;
44477
+ };
44478
+ moveRecords = [];
44479
+ writeMove = (move) => {
44480
+ try {
44481
+ const outcome = `${move.role.replaceAll("-", "_")}_${move.request}_${move.cause}_age_${move.ageMs}`;
44482
+ moveTimingLog?.start({ startedAt: move.at - move.ageMs })("onion:move", outcome, move.at);
44483
+ } catch {
44484
+ }
44485
+ };
44442
44486
  firstOnionRace = (origin) => {
44443
44487
  const race = firstRaces.get(origin);
44444
44488
  return race === void 0 ? void 0 : { ...race };
@@ -106104,11 +106148,23 @@ async function pocketPaymentBlocker({ store, name, record, connection, waitMs, c
106104
106148
  }
106105
106149
  let before;
106106
106150
  for (let page = 0; page < HISTORY_PAGES; page += 1) {
106107
- const list = await connection.getSignaturesForAddress(
106108
- new import_web3116.PublicKey(record.pocketAta),
106109
- { limit: HISTORY_PAGE, minContextSlot: finalizedSlot, ...before ? { before } : {} },
106110
- "finalized"
106111
- );
106151
+ let list;
106152
+ for (; ; ) {
106153
+ try {
106154
+ list = await connection.getSignaturesForAddress(
106155
+ new import_web3116.PublicKey(record.pocketAta),
106156
+ { limit: HISTORY_PAGE, minContextSlot: finalizedSlot, ...before ? { before } : {} },
106157
+ "finalized"
106158
+ );
106159
+ break;
106160
+ } catch (error) {
106161
+ if (error?.code !== MIN_CONTEXT_SLOT_NOT_REACHED) throw error;
106162
+ if (clock2.now() + DEAD_POLL_MS > deadline) {
106163
+ return { why: `its blockhash is proven expired at finalized slot ${finalizedSlot}, but this RPC's history has not reached that slot yet; rerun in a few seconds (nothing is lost)` };
106164
+ }
106165
+ await clock2.sleep(DEAD_POLL_MS);
106166
+ }
106167
+ }
106112
106168
  for (const entry of list) {
106113
106169
  if (lifetime && entry.slot <= Number(lifetime.readAtSlot) || entry.signature === exits.first) return { finalizedSlot };
106114
106170
  if (entry.err !== null || exits.all.has(entry.signature)) continue;
@@ -108992,7 +109048,7 @@ function computeBalance({ store, snapshotRead, source = "local", now = Date.now(
108992
109048
  });
108993
109049
  mark("bal-wal-read", "n" + records.length);
108994
109050
  const byName = new Map(records.map((entry) => [entry.name, entry]));
108995
- const reasons = [];
109051
+ const reasons2 = [];
108996
109052
  const byAddFunds = (depositId) => byName.has(`add-funds-${String(depositId).replace(/-part\d+$/, "")}`);
108997
109053
  const continueAddFunds = `To continue it, run:
108998
109054
  ${commandLine("add-funds")}`;
@@ -109076,7 +109132,7 @@ function computeBalance({ store, snapshotRead, source = "local", now = Date.now(
109076
109132
  ...status === "current" && Number.isSafeInteger(detail.fundedAccounts) ? {
109077
109133
  paymentsWithoutWaiting: `payments without waiting: up to ${detail.fundedAccounts} (one per funded deposit; a deposit newer than the newest pool anchor, such as a payment's change, pays after the next pool anchor)`
109078
109134
  } : {},
109079
- ...reasons.length ? { reasons } : {},
109135
+ ...reasons2.length ? { reasons: reasons2 } : {},
109080
109136
  ...next2 ? { next: next2 } : {},
109081
109137
  detail
109082
109138
  };
@@ -109120,13 +109176,13 @@ It asks the amount, then gives a one-time address and its QR code: send USDC to
109120
109176
  0n
109121
109177
  );
109122
109178
  }
109123
- reasons.push("this wallet has a deposit, add-funds, sale or payment record but no balance walk yet: its balance is not known until the first read");
109179
+ reasons2.push("this wallet has a deposit, add-funds, sale or payment record but no balance walk yet: its balance is not known until the first read");
109124
109180
  return report("unknown", null, proved ? byAddFunds(proved.depositId) ? `deposit ${proved.depositId} of add-funds is proved but not sent yet. ${continueAddFunds}` : `deposit ${proved.depositId} is proved but not sent: back up (${commandLine("help backup-export")}), then rerun the same deposit command with --submit --service <server URL>` : awaiting ? byAddFunds(awaiting.depositId) ? `deposit ${awaiting.depositId} of add-funds waits for USDC at its one-time address; add-funds shows the address again. ${continueAddFunds}` : `deposit ${awaiting.depositId} waits for USDC at its one-time address: fund it, then rerun the same deposit --relay command (it prints the address)` : refreshCommand(state2));
109125
109181
  }
109126
109182
  const valueRecords = records.filter((entry) => !NO_VALUE_TYPES.has(entry.type) && !(entry.type === "deposit" && (entry.phase === "pre-chain" || entry.phase === "void")));
109127
109183
  const landedDeposits = valueRecords.filter((entry) => entry.type === "deposit" && entry.phase === "done" && typeof entry.record?.receipt?.signature === "string" && entry.record.receipt.signature.length > 0 && canonicalAtomic(entry.record.amountAtomic));
109128
109184
  if (firstDepositEstimate && !snapshotRead?.unreadable && !state2.restoredFromRecoveryText && landedDeposits.length > 0 && landedDeposits.length === valueRecords.length) {
109129
- reasons.push("the wallet has not finished its first full check of your balance; this number is your own deposit");
109185
+ reasons2.push("the wallet has not finished its first full check of your balance; this number is your own deposit");
109130
109186
  return report(
109131
109187
  "stale",
109132
109188
  sum2(landedDeposits.map((entry) => entry.record.amountAtomic)),
@@ -109135,11 +109191,11 @@ It asks the amount, then gives a one-time address and its QR code: send USDC to
109135
109191
  landedDeposits.reduce((most, entry) => BigInt(entry.record.amountAtomic) > most ? BigInt(entry.record.amountAtomic) : most, 0n)
109136
109192
  );
109137
109193
  }
109138
- reasons.push(snapshotRead?.unreadable ? `the saved balance walk is unreadable (${snapshotRead.unreadable}); it is only a cache` : state2.restoredFromRecoveryText && !couldHoldValue ? "this wallet was rebuilt from the recovery text (restore) and has no balance walk yet: its value is on chain, not in this file" : "this wallet has deposit or payment records but no balance walk yet");
109194
+ reasons2.push(snapshotRead?.unreadable ? `the saved balance walk is unreadable (${snapshotRead.unreadable}); it is only a cache` : state2.restoredFromRecoveryText && !couldHoldValue ? "this wallet was rebuilt from the recovery text (restore) and has no balance walk yet: its value is on chain, not in this file" : "this wallet has deposit or payment records but no balance walk yet");
109139
109195
  return report("unknown", null, refreshCommand(state2));
109140
109196
  }
109141
109197
  if (snapshot.pool !== state2.pool) {
109142
- reasons.push("the saved balance walk belongs to another pool");
109198
+ reasons2.push("the saved balance walk belongs to another pool");
109143
109199
  return report("unknown", null, refreshCommand(state2));
109144
109200
  }
109145
109201
  const unspent = new Map(snapshot.outputs.filter((output2) => output2.spendStatus === "unspent").map((output2) => [output2.commitment, output2]));
@@ -109230,9 +109286,9 @@ It asks the amount, then gives a one-time address and its QR code: send USDC to
109230
109286
  continue;
109231
109287
  }
109232
109288
  if (heldByWalk(entry)) continue;
109233
- reasons.push(`${entry.type} record ${entry.name} reached ${entry.state} after the last refresh`);
109289
+ reasons2.push(`${entry.type} record ${entry.name} reached ${entry.state} after the last refresh`);
109234
109290
  } else if (entry.phase === "other" && before !== entry.state) {
109235
- reasons.push(`record ${entry.name} changed after the last refresh and this command cannot read it`);
109291
+ reasons2.push(`record ${entry.name} changed after the last refresh and this command cannot read it`);
109236
109292
  } else if (entry.phase === "done" && ["deposit", "payment"].includes(entry.type)) {
109237
109293
  const digest2 = digestKey(entry.record.memoDigest);
109238
109294
  if (digest2 && !snapshotDigests.has(digest2)) {
@@ -109248,11 +109304,11 @@ It asks the amount, then gives a one-time address and its QR code: send USDC to
109248
109304
  settlingReasons.push(`payment record ${entry.name} was answered and its settlement is on its way to finality: the balance counts it as paid; refresh again in a minute`);
109249
109305
  continue;
109250
109306
  }
109251
- reasons.push(answered2 ? `payment record ${entry.name} was answered, but its settlement may not have been final at the last refresh; refresh again in a minute` : `${entry.type} record ${entry.name} finished before the last refresh, but the walk has no output from its memo (unpublished memo, or --fresh before publication)`);
109307
+ reasons2.push(answered2 ? `payment record ${entry.name} was answered, but its settlement may not have been final at the last refresh; refresh again in a minute` : `${entry.type} record ${entry.name} finished before the last refresh, but the walk has no output from its memo (unpublished memo, or --fresh before publication)`);
109252
109308
  }
109253
109309
  }
109254
109310
  }
109255
- if (reasons.length) return report("stale", null, refreshCommand(state2, snapshot.programId));
109311
+ if (reasons2.length) return report("stale", null, refreshCommand(state2, snapshot.programId));
109256
109312
  const spentInWalk = new Set(snapshot.outputs.filter((output2) => output2.spendStatus !== "unspent").map((output2) => output2.commitment));
109257
109313
  const reserved = /* @__PURE__ */ new Set();
109258
109314
  const joining = /* @__PURE__ */ new Set();
@@ -109261,12 +109317,12 @@ It asks the amount, then gives a one-time address and its QR code: send USDC to
109261
109317
  const reserve = (commitments, label, digest2, into = reserved) => {
109262
109318
  if (commitments.every((commitment) => spentInWalk.has(commitment))) {
109263
109319
  if (digest2 !== void 0 && !snapshotDigests.has(digestKey(digest2))) {
109264
- reasons.push(`${label} landed before the last refresh, but the walk has no output from its memo`);
109320
+ reasons2.push(`${label} landed before the last refresh, but the walk has no output from its memo`);
109265
109321
  }
109266
109322
  return "landed";
109267
109323
  }
109268
109324
  if (!commitments.every((commitment) => unspent.has(commitment))) {
109269
- reasons.push(`${label} spends outputs the last refresh did not see`);
109325
+ reasons2.push(`${label} spends outputs the last refresh did not see`);
109270
109326
  }
109271
109327
  commitments.forEach((commitment) => into.add(commitment));
109272
109328
  return into === joining ? "joining" : "reserved";
@@ -109355,7 +109411,7 @@ It asks the amount, then gives a one-time address and its QR code: send USDC to
109355
109411
  detail.depositsRecordFaultAtomic = sum2(depositsRecordFault.map((deposit) => deposit.amountAtomic)).toString();
109356
109412
  detail.depositsRecordFault = depositsRecordFault;
109357
109413
  }
109358
- if (reasons.length) return report("stale", null, refreshCommand(state2, snapshot.programId));
109414
+ if (reasons2.length) return report("stale", null, refreshCommand(state2, snapshot.programId));
109359
109415
  const reservedAtomic = unknownInputs ? unspentAtomic : sum2([...reserved].filter((commitment) => unspent.has(commitment)).map((commitment) => unspent.get(commitment).valueAtomic));
109360
109416
  detail.reservedAtomic = reservedAtomic.toString();
109361
109417
  const settlingJoined = new Set(settling.filter((payment) => payment.join).flatMap((payment) => payment.inputs));
@@ -109388,12 +109444,12 @@ It asks the amount, then gives a one-time address and its QR code: send USDC to
109388
109444
  if (afterJoin !== void 0) detail.paymentReadyAtomic = afterJoin.toString();
109389
109445
  }
109390
109446
  if (settling.some((payment) => payment.inputs.some((commitment) => reserved.has(commitment) || joining.has(commitment))) || unknownInputs && settling.length) {
109391
- reasons.push(...settlingReasons);
109447
+ reasons2.push(...settlingReasons);
109392
109448
  return report("stale", null, refreshCommand(state2, snapshot.programId));
109393
109449
  }
109394
109450
  const spendable = unspentAtomic - reservedAtomic - sum2(settling.map((payment) => payment.amountAtomic));
109395
109451
  if (spendable < 0n) {
109396
- reasons.push(...settlingReasons);
109452
+ reasons2.push(...settlingReasons);
109397
109453
  return report("stale", null, refreshCommand(state2, snapshot.programId));
109398
109454
  }
109399
109455
  const anchorIndex = canonicalAtomic(snapshot.anchorIndex) ? BigInt(snapshot.anchorIndex) : void 0;
@@ -109410,7 +109466,7 @@ If a payment to this wallet settled, read the chain again with:
109410
109466
  settlingReasons.push(`${formatAtomic(movedInAtomic, decimals)} moved into this pool from the old pool after the last refresh: the balance counts it; refresh again in a minute`);
109411
109467
  }
109412
109468
  if (settling.length || movedInAtomic > 0n) {
109413
- reasons.push(...settlingReasons);
109469
+ reasons2.push(...settlingReasons);
109414
109470
  const sendHeldAtomic = sendHold === null || sendHold.notes.size > 0 ? null : sum2(free.filter(isHeld).map((output2) => output2.valueAtomic));
109415
109471
  const inputsOf = (payment) => sum2(payment.inputs.map((commitment) => unspent.get(commitment).valueAtomic));
109416
109472
  const distinctInputs = new Set(settling.flatMap((payment) => payment.inputs)).size === settling.reduce((count3, payment) => count3 + payment.inputs.length, 0);
@@ -109435,7 +109491,7 @@ If a payment to this wallet settled, read the chain again with:
109435
109491
  }
109436
109492
  const newestSale = store.path ? newestSalePaidAt(store.path) : void 0;
109437
109493
  if (newestSale !== void 0 && newestSale * 1e3 > Date.parse(snapshot.refreshedAt)) {
109438
- reasons.push("Shinjuku paid a sale after the last balance read");
109494
+ reasons2.push("Shinjuku paid a sale after the last balance read");
109439
109495
  return report("stale", spendable + successionMovableAtomic, next ?? refreshCommand(state2, snapshot.programId), void 0, largest);
109440
109496
  }
109441
109497
  return report("current", spendable + successionMovableAtomic, next, void 0, largest);
@@ -109558,6 +109614,16 @@ function refundEtaLeft(dueAtMs, now = Date.now(), floorSeconds = 60) {
109558
109614
  if (!Number.isSafeInteger(dueAtMs) || now > dueAtMs + 6e4) return void 0;
109559
109615
  return Math.max(floorSeconds, Math.ceil((dueAtMs - now) / 1e3));
109560
109616
  }
109617
+ async function rerunStatusRead(record, fetchImpl, answerByMs, now = Date.now()) {
109618
+ const left = Number.isSafeInteger(answerByMs) ? answerByMs - now : RERUN_STATUS_READ_MAX_MS;
109619
+ const timeoutMs = Math.min(RERUN_STATUS_READ_MAX_MS, left);
109620
+ if (!(timeoutMs > 0)) return void 0;
109621
+ try {
109622
+ return await readFloatTransferState(record, fetchImpl, timeoutMs);
109623
+ } catch {
109624
+ return void 0;
109625
+ }
109626
+ }
109561
109627
  function freshRefundRead(record, read, now = Date.now()) {
109562
109628
  if (read?.state !== "dead" || typeof read.floatState !== "string") return { record, etaSeconds: void 0 };
109563
109629
  if (read.floatState === "refunded") {
@@ -110978,12 +111044,7 @@ async function payViaFloat({
110978
111044
  if (record.memoryOnly === true && !memoryRequestHeld(record)) keepMemoryRequest(record.fingerprint, { url, programId, request: requestData });
110979
111045
  let statusRead;
110980
111046
  if (floatReceiptPending(record)) {
110981
- let read;
110982
- try {
110983
- read = await readFloatTransferState(record, fetchImpl);
110984
- } catch {
110985
- read = void 0;
110986
- }
111047
+ const read = await rerunStatusRead(record, fetchImpl, deps.answerByMs);
110987
111048
  statusRead = { read };
110988
111049
  const proof = pendingReceiptProof(walName2, record, read);
110989
111050
  const next = proof ? settledPendingReceipt(record, proof) : void 0;
@@ -110994,14 +111055,7 @@ async function payViaFloat({
110994
111055
  }
110995
111056
  let refundFresh;
110996
111057
  if (record.state === "refund_pending" && record.refundOutcome !== "refund_arrived" && !isSolanaSignature(record.refundTransaction)) {
110997
- let read = statusRead?.read;
110998
- if (statusRead === void 0) {
110999
- try {
111000
- read = await readFloatTransferState(record, fetchImpl);
111001
- } catch {
111002
- read = void 0;
111003
- }
111004
- }
111058
+ const read = statusRead === void 0 ? await rerunStatusRead(record, fetchImpl, deps.answerByMs) : statusRead.read;
111005
111059
  refundFresh = freshRefundRead(record, read);
111006
111060
  if (refundFresh.record !== record) {
111007
111061
  record = refundFresh.record;
@@ -112051,7 +112105,7 @@ function paidResult(record, replayed) {
112051
112105
  float: { floatId: record.floatId }
112052
112106
  };
112053
112107
  }
112054
- 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, REFUND_SENT_FLOOR_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, RESIGN_ASK_WINDOW_MS, RESIGN_ASK_TIMEOUT_MS, RESIGN_FINISHING_WAIT_MS, RESIGN_MIN_SELLER_LEFT_MS, RESIGN_ANSWER_MAX_BYTES, 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;
112108
+ 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, RERUN_STATUS_READ_MAX_MS, REFUND_SENT_FLOOR_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, RESIGN_ASK_WINDOW_MS, RESIGN_ASK_TIMEOUT_MS, RESIGN_FINISHING_WAIT_MS, RESIGN_MIN_SELLER_LEFT_MS, RESIGN_ANSWER_MAX_BYTES, 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;
112055
112109
  var init_floatPay = __esm({
112056
112110
  "wallet/src/pay/floatPay.mjs"() {
112057
112111
  "use strict";
@@ -112094,6 +112148,7 @@ var init_floatPay = __esm({
112094
112148
  FLOAT_REFUND_ETA_SECONDS = 420;
112095
112149
  REFUND_READ_EARLY_MS = 1e4;
112096
112150
  REFUND_ETA_MAX_SECONDS = 3600;
112151
+ RERUN_STATUS_READ_MAX_MS = 12e3;
112097
112152
  REFUND_SENT_FLOOR_SECONDS = 10;
112098
112153
  refundDueOf = (read) => Number.isSafeInteger(read?.refundDueAtMs) ? { refundDueAtMs: read.refundDueAtMs } : {};
112099
112154
  REFUND_SETTLED_AFTER_MS = 48e4;
@@ -116823,7 +116878,7 @@ function linkSay(a) {
116823
116878
  return withBalance(`${positive(done) ? `${done} USDC` : "The USDC"} is now private.`, a);
116824
116879
  }
116825
116880
  case "closed":
116826
- return "Closed. Nothing was paid or moved. USDC sent here later stays safe, and your agent can still take it in.";
116881
+ return "Closed: this link asks for no more payments, and nothing was paid or moved. USDC sent to it later still goes into your private balance.";
116827
116882
  case "reclaimed": {
116828
116883
  const late2 = usdcText2(a.heldAtomic);
116829
116884
  return positive(late2) ? `${late2} USDC came to this finished address later. It is safe and yours; only a terminal step takes it back. Do not send again.` : "This address is finished: its deposit was taken back or closed, so nothing goes in. Do not send to it again; ask me for a new address.";
@@ -117124,6 +117179,13 @@ function balanceLine(a, room = SAY_MAX_WORDS) {
117124
117179
  }
117125
117180
  if (balance === "0" && !refunds) return emptyBalanceWords({ surface: "mcp", publicAtomic: a.unshieldedAtomic, canShield });
117126
117181
  if (a.receivedOnly === true && positive(balance)) return have(`. Ask me to send one.${pubPart}`, ". Ask me to send one.");
117182
+ const done = Array.isArray(a.addFundsDone) ? a.addFundsDone.filter((row) => ATOMIC7.test(String(row?.shieldedAtomic ?? ""))) : [];
117183
+ const doneAtomic = done.reduce((sum2, row) => sum2 + BigInt(row.shieldedAtomic), 0n);
117184
+ if (doneAtomic > 0n && ATOMIC7.test(String(a.balanceAtomic ?? "")) && BigInt(a.balanceAtomic) >= doneAtomic) {
117185
+ const lead = `The ${usdcText2(doneAtomic)} USDC paid to your ${done.length === 1 ? "link" : "links"} is private now. `;
117186
+ const rest = spendSentence(a, [`.${pubPart}`, "."], SAY_MAX_WORDS - words(lead));
117187
+ if (rest && words(`${lead}${rest}`) <= SAY_MAX_WORDS) return `${lead}${rest}`;
117188
+ }
117127
117189
  return have(`.${pubPart}`, ".");
117128
117190
  }
117129
117191
  function quoteRefusedWhy(a) {
@@ -117351,12 +117413,12 @@ function build(a, tool, npmVersion) {
117351
117413
  const status = Number(a.status);
117352
117414
  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.`;
117353
117415
  }
117354
- if (a.cancelled === true || a.stage === "cancelled") {
117416
+ if (a.kind !== "add_funds" && (a.cancelled === true || a.stage === "cancelled")) {
117355
117417
  if (a.privateSend && typeof a.privateSend === "object") return stoppedSay(a);
117356
117418
  const sent = usdcText2(a.sentAtomic);
117357
117419
  return positive(sent) ? `Stopped. ${sent} USDC was already sent; the rest stays in your private balance.` : "Closed. Nothing was paid or moved.";
117358
117420
  }
117359
- if (a.cancelled === false && tool === "wallet_cancel") return "Nothing to close. Nothing was paid or moved.";
117421
+ if (a.cancelled === false && tool === "wallet_cancel" && a.kind !== "add_funds") return "Nothing to close. Nothing was paid or moved.";
117360
117422
  if (a.stage === "joining") {
117361
117423
  const steps = Number.isSafeInteger(a.joinSteps) && a.joinSteps > 1 ? `, in ${a.joinSteps} steps` : "";
117362
117424
  const time = doneInText(a);
@@ -117447,16 +117509,36 @@ function build(a, tool, npmVersion) {
117447
117509
  return balanceSay(a);
117448
117510
  }
117449
117511
  if (tool === "wallet_receipts" && Number.isSafeInteger(a.count)) {
117512
+ const notRead = Number.isSafeInteger(a.privateIdsNotRead) && a.privateIdsNotRead > 0 ? a.privateIdsNotRead === 1 ? "1 private payment ID is not read yet; it shows after a history read." : `${a.privateIdsNotRead} private payment IDs are not read yet; they show after a history read.` : "";
117513
+ const notReadShort = !notRead ? "" : a.privateIdsNotRead === 1 ? "1 payment ID not read yet." : `${a.privateIdsNotRead} payment IDs not read yet.`;
117514
+ const pick = (lines) => [
117515
+ ...notRead ? lines.map((line) => `${line} ${notRead}`) : [],
117516
+ ...notReadShort ? lines.map((line) => `${line} ${notReadShort}`) : [],
117517
+ ...lines
117518
+ ].find((line) => words(line) <= SAY_MAX_WORDS) ?? lines.at(-1);
117519
+ const entries = `${a.count} ${a.count === 1 ? "entry" : "entries"}.`;
117450
117520
  const arrived2 = Array.isArray(a.receipts) ? a.receipts.find((row) => row?.kind === "add-funds" && row.belowMinimum !== true && /^[1-9][0-9]*$/.test(String(row.heldAtomic ?? ""))) : void 0;
117451
- if (arrived2) return `${a.count} ${a.count === 1 ? "entry" : "entries"}. ${usdcText2(arrived2.heldAtomic)} USDC reached an add-funds address and becomes private by itself.`;
117521
+ if (arrived2) {
117522
+ return pick([
117523
+ `${entries} ${usdcText2(arrived2.heldAtomic)} USDC reached an add-funds address and becomes private by itself.`,
117524
+ `${entries} ${usdcText2(arrived2.heldAtomic)} USDC you added becomes private by itself.`
117525
+ ]);
117526
+ }
117452
117527
  const dust = Array.isArray(a.receipts) ? a.receipts.find((row) => row?.kind === "add-funds" && row.belowMinimum === true && ATOMIC7.test(String(row.heldAtomic ?? "")) && ATOMIC7.test(String(row.minimumAtomic ?? ""))) : void 0;
117453
- if (dust) return `${a.count} ${a.count === 1 ? "entry" : "entries"}. ${usdcText2(dust.heldAtomic)} USDC at an add-funds address is below the ${usdcText2(dust.minimumAtomic)} USDC minimum and waits for more.`;
117528
+ if (dust) {
117529
+ return pick([
117530
+ `${entries} ${usdcText2(dust.heldAtomic)} USDC at an add-funds address is below the ${usdcText2(dust.minimumAtomic)} USDC minimum and waits for more.`,
117531
+ `${entries} ${usdcText2(dust.heldAtomic)} USDC waits below the ${usdcText2(dust.minimumAtomic)} USDC minimum.`
117532
+ ]);
117533
+ }
117454
117534
  if (a.count === 0) return "No receipts or wallet moves yet.";
117455
117535
  const head = `${a.count} ${a.count === 1 ? "entry" : "entries, newest first"}.`;
117456
117536
  const received = Array.isArray(a.receipts) ? a.receipts.filter((row) => row?.kind === "received" && ATOMIC7.test(String(row.amountAtomic ?? ""))) : [];
117457
117537
  const sales = Array.isArray(a.receipts) ? a.receipts.filter((row) => row?.kind === "sale") : [];
117458
117538
  if (received.length === 0 && sales.length === a.count) return `${head} These are sales: buyers paid you, and each one moves into your private balance by itself.`;
117459
- if (received.length === 0) return `${head} Each payment names its seller; pay.shinjukustaition.com is Shinjuku, the private payment service.`;
117539
+ if (received.length === 0) {
117540
+ return pick([`${head} Each payment names its seller; pay.shinjukustaition.com is Shinjuku, the private payment service.`, `${head} Each payment names its seller.`]);
117541
+ }
117460
117542
  const total = usdcText2(received.reduce((sum2, row) => sum2 + BigInt(row.amountAtomic), 0n));
117461
117543
  const newest = received.map((row) => typeof row.at === "number" ? row.at : Date.parse(String(row.at ?? ""))).filter((ms) => Number.isFinite(ms) && Math.abs(ms) <= 864e13).sort((x, y) => y - x)[0];
117462
117544
  const stamp = newest === void 0 ? "" : new Date(newest).toISOString();
@@ -117467,7 +117549,7 @@ function build(a, tool, npmVersion) {
117467
117549
  "Each payment you made names its seller; pay.shinjukustaition.com is Shinjuku, the private payment service.",
117468
117550
  "pay.shinjukustaition.com is Shinjuku, the private payment service, not a seller."
117469
117551
  ];
117470
- return [...sellers.map((tail) => `${head} ${got}${when}. ${tail}`), `${head} ${got}${when}.`].find((line) => words(line) <= SAY_MAX_WORDS) ?? `${head} ${got}.`;
117552
+ return pick([...sellers.map((tail) => `${head} ${got}${when}. ${tail}`), `${head} ${got}${when}.`, `${head} ${got}.`]);
117471
117553
  }
117472
117554
  if (Array.isArray(a.models) && (a.models.length > 0 || a.checked === true) && a.paid !== true) return modelsSay(a);
117473
117555
  if (a.done === false) return "Still running. Ask again in about 30 seconds; it never moves money twice.";
@@ -120167,7 +120249,7 @@ function familyRootResolver(records, unproven = []) {
120167
120249
  return firstLink.get(family)?.predecessor ?? pool2;
120168
120250
  };
120169
120251
  }
120170
- async function loadFamilyRootResolver({ successions = [], programId, connection }) {
120252
+ async function loadFamilyRootResolver({ successions = [], programId, connection, onPair }) {
120171
120253
  if (!Array.isArray(successions)) fail33("family_successions_invalid");
120172
120254
  if (successions.length > 0 && typeof connection?.getAccountInfo !== "function") fail33("family_connection_invalid");
120173
120255
  const records = [];
@@ -120189,6 +120271,16 @@ async function loadFamilyRootResolver({ successions = [], programId, connection
120189
120271
  const account = await connection.getAccountInfo(new import_web3122.PublicKey(address4), "finalized");
120190
120272
  const parsed2 = account && account.owner?.toBase58?.() === program ? parseSuccessionRecord(account.data) : void 0;
120191
120273
  if (parsed2 && parsed2.bump === bump && parsed2.predecessor === from && parsed2.successor === to && from !== to) record = parsed2;
120274
+ } catch {
120275
+ try {
120276
+ onPair?.(from, to, "unread");
120277
+ } catch {
120278
+ }
120279
+ unproven.push(from, to);
120280
+ continue;
120281
+ }
120282
+ try {
120283
+ onPair?.(from, to, record ? "proven" : "mismatch");
120192
120284
  } catch {
120193
120285
  }
120194
120286
  if (record) records.push(record);
@@ -120196,17 +120288,81 @@ async function loadFamilyRootResolver({ successions = [], programId, connection
120196
120288
  }
120197
120289
  return familyRootResolver(records, unproven);
120198
120290
  }
120291
+ function setFamilyRootsUnread() {
120292
+ setFamilyRootResolver(() => void 0);
120293
+ reasons = { all: "unread", byPool: /* @__PURE__ */ new Map() };
120294
+ }
120295
+ function reasonsByPool(outcomes) {
120296
+ const parent = /* @__PURE__ */ new Map();
120297
+ const find = (pool2) => {
120298
+ let node3 = pool2;
120299
+ while (parent.has(node3) && parent.get(node3) !== node3) node3 = parent.get(node3);
120300
+ return node3;
120301
+ };
120302
+ for (const { from, to } of outcomes) {
120303
+ for (const pool2 of [from, to]) if (!parent.has(pool2)) parent.set(pool2, pool2);
120304
+ const a = find(from);
120305
+ const b = find(to);
120306
+ if (a !== b) parent.set(a, b);
120307
+ }
120308
+ const family = /* @__PURE__ */ new Map();
120309
+ for (const { from, outcome } of outcomes) {
120310
+ const root = find(from);
120311
+ if (outcome === "mismatch") family.set(root, "mismatch");
120312
+ else if (outcome === "unread" && family.get(root) !== "mismatch") family.set(root, "unread");
120313
+ }
120314
+ const byPool = /* @__PURE__ */ new Map();
120315
+ for (const pool2 of parent.keys()) {
120316
+ const reason = family.get(find(pool2));
120317
+ if (reason) byPool.set(pool2, reason);
120318
+ }
120319
+ return byPool;
120320
+ }
120321
+ function reasonFor(pool2) {
120322
+ let key;
120323
+ try {
120324
+ key = pool2 === void 0 ? void 0 : new import_web3122.PublicKey(pool2).toBase58();
120325
+ } catch {
120326
+ key = void 0;
120327
+ }
120328
+ if (key !== void 0 && reasons.byPool.has(key)) return reasons.byPool.get(key);
120329
+ if (reasons.all) return reasons.all;
120330
+ return [...reasons.byPool.values()].includes("mismatch") ? "mismatch" : "unread";
120331
+ }
120332
+ function familyUnprovenWords(pool2) {
120333
+ if (reasonFor(pool2) === "mismatch") {
120334
+ const hours = Math.round(FAMILY_REFRESH_MS / 36e5);
120335
+ return {
120336
+ reason: "mismatch",
120337
+ detail: `the wallet could not confirm its private pool's records: the records it read on chain do not match the ones it keeps, so it makes no new address from them; nothing was moved. It checks them again when the wallet restarts and every ${hours} hours`
120338
+ };
120339
+ }
120340
+ const minutes = Math.max(1, Math.round(FAMILY_RETRY_MS / 6e4));
120341
+ return {
120342
+ reason: "unread",
120343
+ detail: "the wallet is still starting: it could not yet confirm its private pool's records on chain (over Tor this read can take a while); nothing was moved",
120344
+ when: `in about ${minutes} minute${minutes === 1 ? "" : "s"}`
120345
+ };
120346
+ }
120199
120347
  async function installFamilyRoots({ home, connect: connect3, publicKeyHex, apply = applyStoredSuccessions }) {
120348
+ const ticket = ++installTicket;
120349
+ const applyNewest = (resolver2, next) => {
120350
+ if (ticket < appliedTicket) return false;
120351
+ appliedTicket = ticket;
120352
+ setFamilyRootResolver(resolver2);
120353
+ reasons = next;
120354
+ return true;
120355
+ };
120200
120356
  let body;
120201
120357
  try {
120202
120358
  body = apply({ home, ...publicKeyHex === void 0 ? {} : { publicKeyHex } });
120203
120359
  } catch (error) {
120204
- setFamilyRootResolver(allUnproven);
120360
+ if (!applyNewest(allUnproven, { all: "mismatch", byPool: /* @__PURE__ */ new Map() })) return { state: "superseded" };
120205
120361
  return { state: "invalid", code: /^[a-z0-9_]+/.exec(String(error?.message ?? ""))?.[0] ?? "wallet_successions_invalid" };
120206
120362
  }
120207
120363
  const successions = body?.successions ?? [];
120208
120364
  if (successions.length === 0) {
120209
- setFamilyRootResolver(null);
120365
+ if (!applyNewest(null, { all: void 0, byPool: /* @__PURE__ */ new Map() })) return { state: "superseded" };
120210
120366
  return { state: "none", ...body ? { seq: body.seq } : {} };
120211
120367
  }
120212
120368
  let connection;
@@ -120217,15 +120373,28 @@ async function installFamilyRoots({ home, connect: connect3, publicKeyHex, apply
120217
120373
  }
120218
120374
  const listedUnproven = () => familyRootResolver([], successions.flatMap((entry) => [entry.from, entry.to]));
120219
120375
  let resolver;
120376
+ const outcomes = [];
120377
+ const unreadAll = () => successions.map((entry) => ({ from: entry.from, to: entry.to, outcome: "unread" }));
120220
120378
  try {
120221
- resolver = typeof connection?.getAccountInfo === "function" ? await loadFamilyRootResolver({ successions, connection }) : listedUnproven();
120222
- } catch {
120379
+ if (typeof connection?.getAccountInfo === "function") {
120380
+ resolver = await loadFamilyRootResolver({ successions, connection, onPair: (from, to, outcome) => outcomes.push({ from, to, outcome }) });
120381
+ } else {
120382
+ outcomes.push(...unreadAll());
120383
+ resolver = listedUnproven();
120384
+ }
120385
+ } catch (error) {
120386
+ const malformed = String(error?.message ?? "").startsWith("p03_pocket_family_successions_invalid");
120387
+ outcomes.splice(0, outcomes.length, ...unreadAll().map((pair) => malformed ? { ...pair, outcome: "mismatch" } : pair));
120223
120388
  resolver = listedUnproven();
120224
120389
  }
120225
- setFamilyRootResolver(resolver);
120226
- return { state: "installed", seq: body.seq, count: successions.length };
120390
+ const read = !outcomes.some((pair) => pair.outcome === "unread");
120391
+ if (!applyNewest(resolver, { all: void 0, byPool: reasonsByPool(outcomes) })) return { state: "superseded", seq: body.seq };
120392
+ return { state: read ? "installed" : "unproven", seq: body.seq, count: successions.length };
120393
+ }
120394
+ function familyRootsWaitRead() {
120395
+ return reasons.all === "unread" || [...reasons.byPool.values()].includes("unread");
120227
120396
  }
120228
- var import_web3122, fail33, base58, allUnproven;
120397
+ var import_web3122, fail33, base58, allUnproven, FAMILY_RETRY_MS, FAMILY_REFRESH_MS, reasons, installTicket, appliedTicket;
120229
120398
  var init_family = __esm({
120230
120399
  "wallet/src/pocket/family.mjs"() {
120231
120400
  "use strict";
@@ -120238,6 +120407,11 @@ var init_family = __esm({
120238
120407
  };
120239
120408
  base58 = (value2) => new import_web3122.PublicKey(value2).toBase58();
120240
120409
  allUnproven = () => void 0;
120410
+ FAMILY_RETRY_MS = 6e4;
120411
+ FAMILY_REFRESH_MS = 6 * 60 * 60 * 1e3;
120412
+ reasons = { all: void 0, byPool: /* @__PURE__ */ new Map() };
120413
+ installTicket = 0;
120414
+ appliedTicket = 0;
120241
120415
  }
120242
120416
  });
120243
120417
 
@@ -132567,7 +132741,9 @@ function createAddFundsTool({
132567
132741
  },
132568
132742
  randomId = () => randomBytes29(6).toString("hex"),
132569
132743
  wake,
132570
- timing
132744
+ timing,
132745
+ // Lotus to-do 75: the pool a new address derives from (the wallet's own pool), so a refusal names that family's reason.
132746
+ familyPool
132571
132747
  } = {}) {
132572
132748
  const note = (line) => {
132573
132749
  try {
@@ -132747,6 +132923,15 @@ function createAddFundsTool({
132747
132923
  );
132748
132924
  }
132749
132925
  const code2 = codeOf5(error);
132926
+ if (code2 === "p03_pocket_family_unproven") {
132927
+ const words2 = familyUnprovenWords(familyPool?.());
132928
+ return refuse9(
132929
+ code2,
132930
+ words2.detail,
132931
+ words2.when ? `call wallet_add_funds again${agentId ? ` with request_id "${agentId}"` : ""} ${words2.when}. Tell the user: the wallet is still starting and nothing was moved; ask again ${words2.when}` : "Do not call wallet_add_funds again now: it gives the same answer. Tell the user: the wallet cannot make a deposit address right now because its private pool's records do not match the chain; nothing was moved; restarting the wallet checks them again",
132932
+ { ...extra, familyReason: words2.reason }
132933
+ );
132934
+ }
132750
132935
  const locked2 = /wallet_locked|wallet_process_locked/.test(code2);
132751
132936
  return refuse9(
132752
132937
  locked2 ? "wallet_locked" : "mcp_add_funds_failed",
@@ -132937,6 +133122,7 @@ var init_addFunds = __esm({
132937
133122
  "use strict";
132938
133123
  init_phaseTiming();
132939
133124
  init_payMe();
133125
+ init_family();
132940
133126
  init_qr();
132941
133127
  init_relayLimit();
132942
133128
  init_say();
@@ -139773,6 +139959,37 @@ ${canonical5}`;
139773
139959
  };
139774
139960
  });
139775
139961
  }
139962
+ function addFundsDoneRows(store, snapshotSlot) {
139963
+ if (!/^[0-9]+$/.test(String(snapshotSlot ?? ""))) return [];
139964
+ let snapshot;
139965
+ try {
139966
+ snapshot = readBalanceSnapshot(store)?.snapshot;
139967
+ } catch {
139968
+ snapshot = void 0;
139969
+ }
139970
+ if (!snapshot || String(snapshot.slot) !== String(snapshotSlot) || !Array.isArray(snapshot.outputs)) return [];
139971
+ const unspent = new Set(snapshot.outputs.filter((output2) => output2?.spendStatus === "unspent").map((output2) => String(output2.digest ?? "")));
139972
+ const digestOf = (value2) => String(value2 ?? "").replace(/^0x/i, "").toLowerCase();
139973
+ const rows2 = [];
139974
+ for (const record of listPayMe(store)) {
139975
+ if (record.state !== "done" || !/^[1-9][0-9]*$/.test(String(record.shieldedAtomic ?? ""))) continue;
139976
+ const doneMs = Date.parse(String(record.doneAt ?? ""));
139977
+ if (!Number.isFinite(doneMs) || Date.now() - doneMs > ADD_FUNDS_DONE_SHOWN_MS) continue;
139978
+ const rounds = Number.isSafeInteger(record.round) && record.round > 0 ? record.round : 1;
139979
+ let counted2 = true;
139980
+ for (let round = 1; round <= rounds && counted2; round += 1) {
139981
+ let digest2 = "";
139982
+ try {
139983
+ digest2 = digestOf(store.readWal(`deposit-${payMeRoundDepositId(record.id, round)}`)?.memoDigest);
139984
+ } catch {
139985
+ digest2 = "";
139986
+ }
139987
+ counted2 = /^[0-9a-f]{64}$/.test(digest2) && unspent.has(digest2);
139988
+ }
139989
+ if (counted2) rows2.push({ requestId: shownId(record.requestId, record.id), shieldedAtomic: String(record.shieldedAtomic), doneAt: String(record.doneAt) });
139990
+ }
139991
+ return rows2;
139992
+ }
139776
139993
  async function finishSentDeposits(store) {
139777
139994
  if (!elsewhereEnabled || paysInFlight > 0 || moneyCallsInFlight > 0) return [];
139778
139995
  const ids = [];
@@ -140014,11 +140231,20 @@ ${canonical5}`;
140014
140231
  return refuse11("mcp_wallet_unreadable", "the wallet records cannot be read", "check that no restore or migration is running on this wallet, then call wallet_balance again");
140015
140232
  }
140016
140233
  let report = now.report;
140234
+ const poolOf = (one2) => {
140235
+ try {
140236
+ return String(one2.state.pool);
140237
+ } catch {
140238
+ return void 0;
140239
+ }
140240
+ };
140241
+ let reportPool = poolOf(store);
140017
140242
  const reread = (source) => {
140018
140243
  const read2 = balanceNow(store, { programId: session.programId, source });
140019
140244
  if (read2 !== null) {
140020
140245
  now = read2;
140021
140246
  report = read2.report;
140247
+ reportPool = poolOf(store);
140022
140248
  }
140023
140249
  };
140024
140250
  const positive2 = (atomic5) => /^[1-9][0-9]*$/.test(String(atomic5 ?? ""));
@@ -140287,6 +140513,12 @@ ${canonical5}`;
140287
140513
  } catch {
140288
140514
  addFundsOpen = [];
140289
140515
  }
140516
+ let addFundsDone = [];
140517
+ try {
140518
+ addFundsDone = report.status === "current" && refresh.refreshing !== true && refreshRun === void 0 && reportPool !== void 0 && poolOf(store) === reportPool ? addFundsDoneRows(store, report.detail?.lastRefresh?.slot) : [];
140519
+ } catch {
140520
+ addFundsDone = [];
140521
+ }
140290
140522
  let sendWaiting;
140291
140523
  try {
140292
140524
  const intent = openJoinIntents(store)[0];
@@ -140482,6 +140714,7 @@ ${canonical5}`;
140482
140714
  ...move ? { move } : {},
140483
140715
  ...openSwitches.length ? { poolSwitches: openSwitches } : {},
140484
140716
  ...addFundsOpen.length ? { addFunds: addFundsOpen } : {},
140717
+ ...addFundsDone.length ? { addFundsDone } : {},
140485
140718
  ...landingAtomic > 0n ? { landingAtomic: landingAtomic.toString() } : {},
140486
140719
  ...landingParts.recordFaultAtomic > 0n ? { landedRecordFaultAtomic: landingParts.recordFaultAtomic.toString() } : {},
140487
140720
  ...sales ? { incomingFromSalesAtomic: sales.atomic, incomingFromSalesPayments: sales.payments } : {},
@@ -141206,7 +141439,8 @@ ${canonical5}`;
141206
141439
  additionalProperties: false
141207
141440
  },
141208
141441
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
141209
- async run(args) {
141442
+ async run(args, { progress: progress2 } = {}) {
141443
+ const callStartedAt = Date.now();
141210
141444
  const limit = args.limit ?? 20;
141211
141445
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200) {
141212
141446
  return refuse11("mcp_argument_invalid", "limit must be a whole number from 1 to 200", "leave limit out for the last 20");
@@ -141247,20 +141481,29 @@ ${canonical5}`;
141247
141481
  }
141248
141482
  let payments = kind === "moves" ? [] : paymentRows(store, names, refunds.states);
141249
141483
  const missing = (row) => row.state !== "never_landed" && row.state !== "cancelled" && row.privateTransaction === null && (row.scheme === "shielded-exact" || Boolean(row.facilitator));
141250
- if (payments.some(missing) && [...payments].sort((left, right) => right.at - left.at).slice(0, limit).some(missing)) {
141484
+ const moves = kind === "payments" ? [] : moveRows(store, names, linkHeld, { otherWorker });
141485
+ const shownPayments = () => [...payments, ...moves].sort((left, right) => right.at - left.at).slice(0, limit).filter((row) => payments.includes(row));
141486
+ if (shownPayments().some(missing)) {
141251
141487
  try {
141252
141488
  if (latestPrewarmedWalletHistory() === void 0 && paysInFlight === 0 && !historyPrewarmRunning()) warmPaymentHistory(session);
141253
141489
  const walk = latestPrewarmedWalletHistory();
141490
+ const lookupEnd = callStartedAt + RECEIPTS_ID_LOOKUP_MS;
141254
141491
  const bound = (promise, ms) => Promise.race([promise, new Promise((resolve43) => {
141255
141492
  const timer = setTimeout(resolve43, Math.max(0, ms));
141256
141493
  timer.unref?.();
141257
141494
  })]);
141258
- const history = walk ? await bound(walk.catch(() => void 0), readsEnd - Date.now()) : void 0;
141495
+ if (walk) {
141496
+ try {
141497
+ progress2?.("reading this wallet's history for a private payment's id");
141498
+ } catch {
141499
+ }
141500
+ }
141501
+ const history = walk ? await bound(walk.catch(() => void 0), lookupEnd - Date.now()) : void 0;
141259
141502
  if (history) {
141260
- const settled = underLease((leased) => Date.now() >= readsEnd ? 0 : finalizePendingFromHistory({ store: leased, history: assertAuthenticatedFinalizedP03History(history), programId: session.programId }));
141503
+ const settled = underLease((leased) => Date.now() >= lookupEnd ? 0 : finalizePendingFromHistory({ store: leased, history: assertAuthenticatedFinalizedP03History(history), programId: session.programId }));
141261
141504
  settled.catch(() => {
141262
141505
  });
141263
- const written = await bound(settled.catch(() => 0), Math.max(1e3, readsEnd - Date.now()));
141506
+ const written = await bound(settled.catch(() => 0), Math.max(1e3, lookupEnd - Date.now()));
141264
141507
  if (written > 0) {
141265
141508
  store = session.openStore();
141266
141509
  payments = paymentRows(store, store.listWal(), refunds.states);
@@ -141269,13 +141512,15 @@ ${canonical5}`;
141269
141512
  } catch {
141270
141513
  }
141271
141514
  }
141272
- const rows2 = [
141273
- ...payments,
141274
- ...kind === "payments" ? [] : moveRows(store, names, linkHeld, { otherWorker })
141275
- ];
141515
+ const rows2 = [...payments, ...moves];
141276
141516
  rows2.sort((left, right) => right.at - left.at);
141277
141517
  const verbose = args.verbose === true;
141518
+ let idsNotRead = 0;
141278
141519
  const shown = rows2.slice(0, limit).map((row) => {
141520
+ if (payments.includes(row) && missing(row)) {
141521
+ idsNotRead += 1;
141522
+ row = { ...row, privateTransactionNote: PRIVATE_ID_NOT_READ };
141523
+ }
141279
141524
  const { at, ...all } = row;
141280
141525
  const { scheme, receiptFinality, ...plain } = all;
141281
141526
  const rest = verbose ? all : { ...plain, ...receiptFinality !== void 0 && receiptFinality !== "finalized" ? { receiptFinality } : {} };
@@ -141287,6 +141532,7 @@ ${canonical5}`;
141287
141532
  total: rows2.length,
141288
141533
  scope: RECEIPTS_SCOPE,
141289
141534
  facilitatorNote: RECEIPTS_FACILITATOR_NOTE,
141535
+ ...idsNotRead > 0 ? { privateIdsNotRead: idsNotRead } : {},
141290
141536
  receipts: shown,
141291
141537
  ...rows2.some((row) => row.at < 0) ? { note: "a time is null for received payments and for records of older wallet versions (they carry no time); they sort last" } : {}
141292
141538
  });
@@ -141730,7 +141976,7 @@ ${canonical5}`;
141730
141976
  const cancel = {
141731
141977
  name: "wallet_cancel",
141732
141978
  title: "Close or stop one unfinished request",
141733
- description: `Use this when the user says "stop that send", also after this app stopped a call before its answer (then never say nothing was sent: leave request_id out and this reads the newest send of this session, or says to check wallet_receipts), or wants to stop something unfinished, by its request_id: a payment (pay_for_service or inference_chat) that can no longer settle, so its reserved balance comes back; a private send in smaller payments (an older wallet version started it): its smaller payments not sent yet stop and stay in the balance; a wallet_add_funds address nothing reached: it closes. A single send (one exit, a send of the whole balance too) cannot be stopped: the answer says its state and, once it is out, its transaction (exitTransaction; without request_id it waits up to 15 s for it): give the user that transaction. A private send's stop is written under the wallet lock: when another step of this wallet holds it (one of the smaller payments being sent, a payment), this call waits for that step, up to about ${CALL_BUDGET_MS / 1e3} s. Only an answer with cancelled: true means the stop is saved; an answer with stage cancelling means nothing is stopped yet: call wallet_cancel again. It finds the request by itself; when one request_id names two of these, pass kind. A payment whose bytes never left the wallet closes at once. A sent payment closes only once the chain proves it can never land (usually about two minutes after its quote expired); until then it is refused, because closing earlier could let a retry pay twice. Pays nothing and moves nothing.`,
141979
+ description: `Use this when the user says "stop that send", also after this app stopped a call before its answer (then never say nothing was sent: leave request_id out and this reads the newest send of this session, or says to check wallet_receipts), or wants to stop something unfinished, by its request_id: a payment (pay_for_service or inference_chat) that can no longer settle, so its reserved balance comes back; a private send in smaller payments (an older wallet version started it): its smaller payments not sent yet stop and stay in the balance; a wallet_add_funds address nothing reached: it closes (the link asks for no payment any more; USDC sent to it later still goes into the private balance). A single send (one exit, a send of the whole balance too) cannot be stopped: the answer says its state and, once it is out, its transaction (exitTransaction; without request_id it waits up to 15 s for it): give the user that transaction. A private send's stop is written under the wallet lock: when another step of this wallet holds it (one of the smaller payments being sent, a payment), this call waits for that step, up to about ${CALL_BUDGET_MS / 1e3} s. Only an answer with cancelled: true means the stop is saved; an answer with stage cancelling means nothing is stopped yet: call wallet_cancel again. It finds the request by itself; when one request_id names two of these, pass kind. A payment whose bytes never left the wallet closes at once. A sent payment closes only once the chain proves it can never land (usually about two minutes after its quote expired); until then it is refused, because closing earlier could let a retry pay twice. Pays nothing and moves nothing.`,
141734
141980
  inputSchema: {
141735
141981
  type: "object",
141736
141982
  properties: {
@@ -141825,7 +142071,7 @@ ${canonical5}`;
141825
142071
  );
141826
142072
  }
141827
142073
  try {
141828
- return cancelWords(await closeLink(requestId));
142074
+ return cancelWords(await closeLink(requestId, { fromCancel: true }));
141829
142075
  } catch (error) {
141830
142076
  return cancelWords(payMeRefusal(error, `call wallet_add_funds with request_id "${requestId}" to read it`));
141831
142077
  }
@@ -145007,6 +145253,15 @@ ${canonical5}`;
145007
145253
  return refuse11(error.code, `${detail}; nothing was moved`, next);
145008
145254
  }
145009
145255
  const code2 = describeError(error, { fallback: "mcp_pay_me_failed", safeText: SAFE_TEXT }).split(/[\s:;(]/, 1)[0];
145256
+ if (code2 === "p03_pocket_family_unproven") {
145257
+ const words2 = familyUnprovenWords(session.pool);
145258
+ return refuse11(
145259
+ code2,
145260
+ words2.detail,
145261
+ words2.when ? `call the same tool again with the same request_id ${words2.when}. Tell the user: the wallet is still starting and nothing was moved; ask again ${words2.when}` : "Do not call it again now: it gives the same answer. Tell the user: the wallet cannot make a payment link right now because its private pool's records do not match the chain; nothing was moved; restarting the wallet checks them again",
145262
+ { familyReason: words2.reason }
145263
+ );
145264
+ }
145010
145265
  const locked2 = /wallet_locked|wallet_process_locked/.test(code2);
145011
145266
  return refuse11(
145012
145267
  locked2 ? "wallet_locked" : "mcp_pay_me_failed",
@@ -145276,11 +145531,16 @@ ${canonical5}`;
145276
145531
  }
145277
145532
  }
145278
145533
  };
145279
- async function closeLink(given) {
145534
+ async function closeLink(given, { fromCancel = false } = {}) {
145280
145535
  const id = toRecordId(given);
145281
145536
  const record = await session.serial(() => closePayMe({ store: session.openStore(), connection: session.connection, id }));
145282
145537
  log(`MCP_PAY_ME_CLOSED requestId=${id}`);
145283
- return payMeAnswer({ record, heldAtomic: "0", stage: record.state === "reclaimed" ? "reclaimed" : "closed" }, { requestId: given, id: given });
145538
+ const stage = record.state === "closed" ? "closed" : record.state === "reclaimed" ? "reclaimed" : record.state === "done" ? "done" : record.state === "shielding" ? "shielding" : "waiting_for_payment";
145539
+ const held2 = stage === "shielding" && /^[1-9][0-9]*$/.test(String(record.shieldAtomic ?? "")) ? String(record.shieldAtomic) : "0";
145540
+ return payMeAnswer(
145541
+ { record, heldAtomic: held2, stage },
145542
+ { requestId: given, id: given, ...fromCancel ? { kind: "add_funds", cancelled: record.state === "closed" } : {} }
145543
+ );
145284
145544
  }
145285
145545
  const payMeStatus = {
145286
145546
  name: "wallet_pay_me_status",
@@ -146366,6 +146626,7 @@ ${canonical5}`;
146366
146626
  }
146367
146627
  };
146368
146628
  const addFunds2 = createAddFundsTool({
146629
+ familyPool: () => session.pool,
146369
146630
  payMeCreate: ({ id, requestId, amountAtomic, note }) => createPayMeLeased({ store: session.openStore(), connection: session.connection, id, requestId, amountAtomic, note }),
146370
146631
  payMeRead: (id) => readPayMe(session.openStore(), id),
146371
146632
  payMeList: () => listPayMe(session.openStore()),
@@ -147327,7 +147588,7 @@ function createSetupTools({
147327
147588
  doneTool: sayOnRefusal(doneTool)
147328
147589
  };
147329
147590
  }
147330
- var import_web3133, X402_V1_NEXT, shownCaps, RELEASE_RETRY_MS, STAGE_WORDS, slowReadWords, stageWords, INTERNAL_BALANCE_DETAIL, shownBreakdown, sessionLeftShown, RESOURCE_PAYMENT_WAL_PREFIX2, POOL_LAYOUT_CODE, POOL_LAYOUT_UPDATE, USEPOD_VIA_INFERENCE_CHAT, SEND_RUNS_ON, DEPOSIT_RUNS_ON, CLI_FUNDS_PLAN_PREFIX, CLI_FUNDS_SCHEMA, SELF_PAY_ORIGIN3, REQUEST_ID4, POSITIVE_ATOMIC6, PRIVATE_HOST3, FORBIDDEN_HEADERS3, MAX_BODY_BYTES2, PREVIEW_TIMEOUT_MS, PREVIEW_SELLER_READ_MS, CALL_BUDGET_MS, budgetLeft, PAY_ANSWER_MARGIN_MS, MONEY_FIRST_ANSWER_MS, BALANCE_AFTER_LANDING_MS, JOIN_CALL_MAX_MS, JOIN_CALL_ANSWER_MARGIN_S, PAY_AFTER_JOIN_MS, joinAnswerSeconds, JOIN_TIME_MS, JOIN_NUDGE_QUIET_MS, JOIN_STEP_MS, sleep2, PROGRESS_EVERY_MS2, READ_BUDGET_MS, UNPAID_TOR_TRY_MS, UNPAID_CLEAR_MS, READ_BUDGET_TOOLS, FLOAT_BUSY_CODES, RETRY_MARGIN_MS, ASK_PAY_CODES, runningNpmVersion, terminalCommand2, capPlaceWords, noLimitSetLine, CAP_NAMES, capName, entryPlaces, capRaiseText, runningLimits, payCapFlag, noPriceFits, cheaperText, limitNext, overLimitStep, logCause, SAFE_TEXT, causesLog, MCP_TOOL_ALIASES, POOL_SWITCH_WHY, POOL_SWITCH_NEXT, SWITCH_STATES, quietSwitch, switchKey, ATOMIC_TEXT, MAX_PAYMENT_ATOMIC_LEAST, movedTo, FLOAT_ID2, ANSWERED_EXIT_RETRY_MS, ANSWERED_EXIT_UNCONFIRMED_MS, ANSWERED_EXIT_RETRY_WINDOW_MS, ANSWERED_EXIT_CLOSED, switchAmount, switchEta, switchRows, OWNER_CAP_CODES, JOIN_END_MCP, JOIN_END_TERMINAL_LIBRARY, JOIN_RETRY_BACKOFF_MS, WALLET_CAP_FIX, ENTRY_CAP_CODES, MCP_CAP_FIX, capFix, ownerOnlyNext, mcpNext, CONFIDENTIAL_RETIRED, json4, answerResult, discoverTool, LAUNCH_CAP_CODES, dayCapKind, refuse11, newRequestIdFor, payCapName, limitQuestion, stableJson, requestPrint, JSON_SNIFF_MAX_CHARS, publicOffer, FLOAT_PAID_CODES, FLOAT_NOT_CERTAIN_CODES, FLOAT_PRIVATE_LEG, SELLER_ONLY_HERE, outsideWalletRule, TOR_START_STEP, MONEY_ID2, toRecordId, linkKindOf, moneyId, REFUSED_CODES, SEND_STOPPED, SEND_STOP_NOT_SAVED, sendStoppedError, refusedCodeOf, PLAIN_REASONS, insufficientCause, INSUFFICIENT_REASONS, historyRefusalCode, reasonOf, plainReason, KEPT_SEND_TRIES, shownId, isSplitSend, PROMISED_NEXT, partFailReason, sendAnswerOf, PUBLIC_READ_TIMEOUT_MS, RECIPIENT_CHECK_TIMEOUT_MS, withTimeout, ownKey, readFailure, OWN_KEY_TOKENS_MAX, tokenAmountText, elsewhereId, AGENT_ID_SCHEMA, agentIdName, minutesText2, ageWords2, DEPOSIT_SENT_STATES, depositLanded, usdcText3, walkWalletHistory, REFRESH_LEASE_WALK_MS, HOME_MARKS_SETTLED_MS2, AUTO_BACKUPS_KEPT, AUTO_BACKUP_NAME, AUTO_BACKUP_VERIFIED, FRONTED_SETTLE_MARGIN_SLOTS, RECIPIENT_READ_TOTAL_MS, RECIPIENT_READ_SLOW_MS, slowReadSaid, UNSHIELD_WINDOW_YIELD_MS, NOT_FINAL_YET, FINISH_FINALITY_WAIT_MS, FINISH_FINALITY_WAITS, FINISH_FINALITY_RECENT_MS, walkStillCurrent, DIRECT_EXIT_GONE, BALANCE_REFRESH_WAIT_MS, BALANCE_REFRESH_GRACE_MS, BALANCE_REFRESH_LONG_MS, INBOUND_REFRESH_AGE_MS, REFUND_CHECK_MIN_MS, SALE_VIEW_AGE_SECONDS, saleViewRead, balanceTextFields, changeFields, balanceAnswer, REFRESH_RETRY_MS, FINALITY_POLL_MS, FINALITY_WAIT_MS, FINALITY_REFRESH_LIMIT_MS, FINALITY_CLOSE_WAIT_MS, POOL_WATCH_MS, POOL_WATCH_POLL_MS, EARLY_BALANCE_DELAY_MS, FINALITY_SETTLE_WINDOW_SLOTS, PUBLIC_READ_ANSWER_MS, LINK_READ_ANSWER_MS, OWN_READS_AHEAD_MS, OWN_PUBLIC_KNOWN_MS, FLOAT_CORRECT_WAIT_MS, SWITCH_WAIT_MS, UNSHIELD_TO_NO_USDC_DETAIL, UNSHIELD_TO_INVALID_NEXT, INFERENCE_MIN_MAX_TOKENS, ELICIT_TIMEOUT_MS, ALLOW_BOX_HOSTS, ALLOW_BOX_PROGRESS_MS, ELICIT_UNSHOWN_MS, elicitUnshown, POLL_SECONDS2, TEMP_CLEAN_DELAY_MS, KEPT_ON_DISK, receiveGenerator, MCP_TOOL_NAMES, MCP_HIDDEN_TOOL_NAMES, setupTerminalNext, SETUP_RUNNING_SAY, SETUP_WAITING_SAY, ACCEPTED_NEXT, SETUP_RUNNING_NEXT, SETUP_ANSWER_WAIT_MS, SETUP_CONFIRMING_SAY, SETUP_CONFIRMING_NEXT, OWN_ADDRESS_QUESTION, OWN_ADDRESS_WHERE, OWN_ADDRESS_INVALID, HOST_CHAT_NOT_PRIVATE, PRIVATE_INFERENCE_WHY, RESTART_STEPS, HOST_BLOCKED_LINE, TOR_BROWSER_PORT, SETUP_TOR_TITLE, SETUP_TOR_WHY;
147591
+ var import_web3133, X402_V1_NEXT, shownCaps, RELEASE_RETRY_MS, STAGE_WORDS, slowReadWords, stageWords, INTERNAL_BALANCE_DETAIL, shownBreakdown, sessionLeftShown, RESOURCE_PAYMENT_WAL_PREFIX2, POOL_LAYOUT_CODE, POOL_LAYOUT_UPDATE, USEPOD_VIA_INFERENCE_CHAT, SEND_RUNS_ON, DEPOSIT_RUNS_ON, CLI_FUNDS_PLAN_PREFIX, CLI_FUNDS_SCHEMA, SELF_PAY_ORIGIN3, REQUEST_ID4, POSITIVE_ATOMIC6, PRIVATE_HOST3, FORBIDDEN_HEADERS3, MAX_BODY_BYTES2, PREVIEW_TIMEOUT_MS, PREVIEW_SELLER_READ_MS, CALL_BUDGET_MS, budgetLeft, PAY_ANSWER_MARGIN_MS, MONEY_FIRST_ANSWER_MS, BALANCE_AFTER_LANDING_MS, JOIN_CALL_MAX_MS, JOIN_CALL_ANSWER_MARGIN_S, PAY_AFTER_JOIN_MS, joinAnswerSeconds, JOIN_TIME_MS, JOIN_NUDGE_QUIET_MS, JOIN_STEP_MS, sleep2, PROGRESS_EVERY_MS2, READ_BUDGET_MS, UNPAID_TOR_TRY_MS, UNPAID_CLEAR_MS, READ_BUDGET_TOOLS, FLOAT_BUSY_CODES, RETRY_MARGIN_MS, ASK_PAY_CODES, runningNpmVersion, terminalCommand2, capPlaceWords, noLimitSetLine, CAP_NAMES, capName, entryPlaces, capRaiseText, runningLimits, payCapFlag, noPriceFits, cheaperText, limitNext, overLimitStep, logCause, SAFE_TEXT, causesLog, ADD_FUNDS_DONE_SHOWN_MS, MCP_TOOL_ALIASES, POOL_SWITCH_WHY, POOL_SWITCH_NEXT, SWITCH_STATES, quietSwitch, switchKey, ATOMIC_TEXT, MAX_PAYMENT_ATOMIC_LEAST, movedTo, FLOAT_ID2, ANSWERED_EXIT_RETRY_MS, ANSWERED_EXIT_UNCONFIRMED_MS, ANSWERED_EXIT_RETRY_WINDOW_MS, ANSWERED_EXIT_CLOSED, switchAmount, switchEta, switchRows, OWNER_CAP_CODES, JOIN_END_MCP, JOIN_END_TERMINAL_LIBRARY, JOIN_RETRY_BACKOFF_MS, WALLET_CAP_FIX, ENTRY_CAP_CODES, MCP_CAP_FIX, capFix, ownerOnlyNext, mcpNext, CONFIDENTIAL_RETIRED, json4, answerResult, discoverTool, LAUNCH_CAP_CODES, dayCapKind, refuse11, newRequestIdFor, payCapName, limitQuestion, stableJson, requestPrint, JSON_SNIFF_MAX_CHARS, publicOffer, FLOAT_PAID_CODES, FLOAT_NOT_CERTAIN_CODES, FLOAT_PRIVATE_LEG, SELLER_ONLY_HERE, outsideWalletRule, TOR_START_STEP, MONEY_ID2, toRecordId, linkKindOf, moneyId, REFUSED_CODES, SEND_STOPPED, SEND_STOP_NOT_SAVED, sendStoppedError, refusedCodeOf, PLAIN_REASONS, insufficientCause, INSUFFICIENT_REASONS, historyRefusalCode, reasonOf, plainReason, KEPT_SEND_TRIES, shownId, isSplitSend, PROMISED_NEXT, partFailReason, sendAnswerOf, PUBLIC_READ_TIMEOUT_MS, RECIPIENT_CHECK_TIMEOUT_MS, withTimeout, ownKey, readFailure, OWN_KEY_TOKENS_MAX, tokenAmountText, elsewhereId, AGENT_ID_SCHEMA, agentIdName, minutesText2, ageWords2, DEPOSIT_SENT_STATES, depositLanded, usdcText3, walkWalletHistory, REFRESH_LEASE_WALK_MS, HOME_MARKS_SETTLED_MS2, AUTO_BACKUPS_KEPT, AUTO_BACKUP_NAME, AUTO_BACKUP_VERIFIED, FRONTED_SETTLE_MARGIN_SLOTS, RECIPIENT_READ_TOTAL_MS, RECIPIENT_READ_SLOW_MS, slowReadSaid, UNSHIELD_WINDOW_YIELD_MS, NOT_FINAL_YET, FINISH_FINALITY_WAIT_MS, FINISH_FINALITY_WAITS, FINISH_FINALITY_RECENT_MS, walkStillCurrent, DIRECT_EXIT_GONE, BALANCE_REFRESH_WAIT_MS, BALANCE_REFRESH_GRACE_MS, BALANCE_REFRESH_LONG_MS, INBOUND_REFRESH_AGE_MS, REFUND_CHECK_MIN_MS, SALE_VIEW_AGE_SECONDS, saleViewRead, balanceTextFields, changeFields, balanceAnswer, REFRESH_RETRY_MS, FINALITY_POLL_MS, FINALITY_WAIT_MS, FINALITY_REFRESH_LIMIT_MS, FINALITY_CLOSE_WAIT_MS, POOL_WATCH_MS, POOL_WATCH_POLL_MS, EARLY_BALANCE_DELAY_MS, FINALITY_SETTLE_WINDOW_SLOTS, PUBLIC_READ_ANSWER_MS, RECEIPTS_ID_LOOKUP_MS, PRIVATE_ID_NOT_READ, LINK_READ_ANSWER_MS, OWN_READS_AHEAD_MS, OWN_PUBLIC_KNOWN_MS, FLOAT_CORRECT_WAIT_MS, SWITCH_WAIT_MS, UNSHIELD_TO_NO_USDC_DETAIL, UNSHIELD_TO_INVALID_NEXT, INFERENCE_MIN_MAX_TOKENS, ELICIT_TIMEOUT_MS, ALLOW_BOX_HOSTS, ALLOW_BOX_PROGRESS_MS, ELICIT_UNSHOWN_MS, elicitUnshown, POLL_SECONDS2, TEMP_CLEAN_DELAY_MS, KEPT_ON_DISK, receiveGenerator, MCP_TOOL_NAMES, MCP_HIDDEN_TOOL_NAMES, setupTerminalNext, SETUP_RUNNING_SAY, SETUP_WAITING_SAY, ACCEPTED_NEXT, SETUP_RUNNING_NEXT, SETUP_ANSWER_WAIT_MS, SETUP_CONFIRMING_SAY, SETUP_CONFIRMING_NEXT, OWN_ADDRESS_QUESTION, OWN_ADDRESS_WHERE, OWN_ADDRESS_INVALID, HOST_CHAT_NOT_PRIVATE, PRIVATE_INFERENCE_WHY, RESTART_STEPS, HOST_BLOCKED_LINE, TOR_BROWSER_PORT, SETUP_TOR_TITLE, SETUP_TOR_WHY;
147331
147592
  var init_tools = __esm({
147332
147593
  "wallet/src/mcp/tools.mjs"() {
147333
147594
  "use strict";
@@ -147376,6 +147637,7 @@ var init_tools = __esm({
147376
147637
  init_rpcRefusal();
147377
147638
  init_relayLimit();
147378
147639
  init_book();
147640
+ init_family();
147379
147641
  init_pay();
147380
147642
  init_errorLine();
147381
147643
  init_spendPolicy();
@@ -147530,6 +147792,7 @@ var init_tools = __esm({
147530
147792
  };
147531
147793
  SAFE_TEXT = /^(fetch_|spend_|mcp_|wallet_locked|history_rpc_failed|p03_deposit_(?:rpc_refused|token_balance_unreadable)|p03_pocket_payment_(?:rpc_refused|pocket_balance_unreadable))/;
147532
147794
  causesLog = (causes) => causes.length ? ` causes=${causes.join(",")}` : "";
147795
+ ADD_FUNDS_DONE_SHOWN_MS = 30 * 6e4;
147533
147796
  MCP_TOOL_ALIASES = Object.freeze({
147534
147797
  fetch_paid: "pay_for_service",
147535
147798
  wallet_pool_switch_status: "wallet_move_status",
@@ -147906,6 +148169,8 @@ var init_tools = __esm({
147906
148169
  EARLY_BALANCE_DELAY_MS = 50;
147907
148170
  FINALITY_SETTLE_WINDOW_SLOTS = 150;
147908
148171
  PUBLIC_READ_ANSWER_MS = 3e3;
148172
+ RECEIPTS_ID_LOOKUP_MS = 12e3;
148173
+ PRIVATE_ID_NOT_READ = "not read yet: no history read of this wallet has found this private payment yet; it shows here once one does (a balance refresh reads it). The payment itself is done; only its id is not read";
147909
148174
  LINK_READ_ANSWER_MS = 15e3;
147910
148175
  OWN_READS_AHEAD_MS = 3e4;
147911
148176
  OWN_PUBLIC_KNOWN_MS = 6e4;
@@ -149136,6 +149401,7 @@ async function openWalletServer({
149136
149401
  }
149137
149402
  const home = proofToolsRefresh.home;
149138
149403
  let installed = cliRoots !== void 0 && (cliRoots.state !== "none" || cliRoots.seq !== void 0) ? cliRoots : await installFamilyRoots({ home, connect: () => session.connection });
149404
+ if (installed.state === "unproven") installed = await installFamilyRoots({ home, connect: () => session.connection });
149139
149405
  if (installed.state !== "none" || installed.seq !== void 0) return installed;
149140
149406
  try {
149141
149407
  const facilitator = readSetupConfig(home)?.memoService;
@@ -149144,18 +149410,18 @@ async function openWalletServer({
149144
149410
  }
149145
149411
  installed = await installFamilyRoots({ home, connect: () => session.connection });
149146
149412
  if (installed.state !== "none" || installed.seq !== void 0) return installed;
149147
- setFamilyRootResolver(() => void 0);
149413
+ setFamilyRootsUnread();
149148
149414
  return { state: "unproven" };
149149
149415
  };
149150
149416
  const installing = install();
149151
149417
  const land = Promise.race([installing, late2]).finally(() => clearTimeout(timer)).then((installed) => {
149152
- if (installed.state === "timeout") setFamilyRootResolver(() => void 0);
149418
+ if (installed.state === "timeout") setFamilyRootsUnread();
149153
149419
  if (installed.state !== "none") log(`FAMILY_ROOTS ${installed.state}${installed.seq === void 0 ? "" : ` seq=${installed.seq}`}${installed.count === void 0 ? "" : ` count=${installed.count}`}${installed.code ? ` code=${installed.code}` : ""}`);
149154
149420
  });
149155
149421
  if (!rootsInBackground) await land;
149156
149422
  else {
149157
149423
  rootsLanded = land.catch((error) => {
149158
- setFamilyRootResolver(() => void 0);
149424
+ setFamilyRootsUnread();
149159
149425
  log(`FAMILY_ROOTS failed code=${String(error?.message ?? error).split(/[\s:;(]/, 1)[0]}`);
149160
149426
  });
149161
149427
  toolRootsLanded = rootsForTools(installing, rootsLanded);
@@ -149169,7 +149435,7 @@ async function openWalletServer({
149169
149435
  rootsLanded = Promise.race([cliRootsLate.then(() => "landed", () => "landed"), late2]).then((state2) => {
149170
149436
  clearTimeout(timer);
149171
149437
  if (state2 !== "timeout") return;
149172
- setFamilyRootResolver(() => void 0);
149438
+ setFamilyRootsUnread();
149173
149439
  log("FAMILY_ROOTS timeout");
149174
149440
  });
149175
149441
  toolRootsLanded = rootsForTools(cliRootsLate, rootsLanded);
@@ -149353,11 +149619,11 @@ function startProofToolsRefresh({
149353
149619
  session,
149354
149620
  live,
149355
149621
  log,
149356
- intervalMs = 6 * 60 * 60 * 1e3,
149622
+ intervalMs = FAMILY_REFRESH_MS,
149357
149623
  refresh = refreshTrustedProofTools,
149358
149624
  fetchSuccessions = loadSuccessions,
149359
149625
  installRoots = installFamilyRoots,
149360
- familyRetryMs = 6e4
149626
+ familyRetryMs = FAMILY_RETRY_MS
149361
149627
  }) {
149362
149628
  let running = false;
149363
149629
  let retry;
@@ -149370,8 +149636,8 @@ function startProofToolsRefresh({
149370
149636
  }
149371
149637
  const installed = await installRoots({ home, connect: () => session.connection });
149372
149638
  if (installed.state !== "none") log(`FAMILY_ROOTS ${installed.state}${installed.seq === void 0 ? "" : ` seq=${installed.seq}`}${installed.count === void 0 ? "" : ` count=${installed.count}`}${installed.code ? ` code=${installed.code}` : ""}`);
149373
- if (installed.state === "none" && installed.seq === void 0) {
149374
- setFamilyRootResolver(() => void 0);
149639
+ if (installed.state === "none" && installed.seq === void 0) setFamilyRootsUnread();
149640
+ if (installed.state === "unproven" || familyRootsWaitRead()) {
149375
149641
  if (!session.closed && retry === void 0) {
149376
149642
  retry = setTimeout(() => {
149377
149643
  retry = void 0;
@@ -149672,7 +149938,6 @@ var init_stdioServer = __esm({
149672
149938
  init_channel();
149673
149939
  init_successions();
149674
149940
  init_family();
149675
- init_keys();
149676
149941
  init_tools();
149677
149942
  init_prompts();
149678
149943
  init_sendRunner();