shinjuku-shield 0.3.205 → 0.3.207

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.205. The command is `shinjuku`.
8
+ This is version 0.3.207. The command is `shinjuku`.
9
9
 
10
10
  ## Set up
11
11
 
12
12
  ```sh
13
- npx -y shinjuku@0.3.205 setup
13
+ npx -y shinjuku@0.3.207 setup
14
14
  ```
15
15
 
16
16
  Setup does every step for you:
@@ -100,7 +100,7 @@ Add it yourself. The name of the wallet in your app is `shinjuku`.
100
100
  Claude Code:
101
101
 
102
102
  ```sh
103
- claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.205 mcp
103
+ claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.207 mcp
104
104
  ```
105
105
 
106
106
  ## For builders: check what you install
@@ -116,7 +116,7 @@ with the Releases table in
116
116
  Versions are published from GitHub Actions with npm provenance.
117
117
 
118
118
  `shinjuku-shield` is the package that holds the wallet. `shinjuku-shielded`
119
- 0.3.205, its older name, runs this package at the same version, so wallets
119
+ 0.3.207, its older name, runs this package at the same version, so wallets
120
120
  installed under that name keep updating. New installs use `shinjuku`.
121
121
 
122
122
  The full guide is
package/manifest.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schema": "carbon-shielded-wallet/bundle-manifest/v1",
3
3
  "file": "shinjuku-wallet.mjs",
4
- "sha256": "a74629364f4ac22ce7b0ac74294824d926277cc1d2c5fb160f69087cb04a0303",
5
- "bytes": 9497703,
6
- "sourceCommit": "e9c59a9bbfb935841c6182998ac30701f93aedfb",
4
+ "sha256": "cb3d8f7da30834d0d6bb95942a06afe07b394be9ad6f48bc19fff3718d4a05cc",
5
+ "bytes": 9504181,
6
+ "sourceCommit": "33356a03d0762d4617688d52566d63099ca90f39",
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-09T09:27:36.428Z"
1935
+ "publishedAt": "2026-11-10T08:03:21.693Z"
1936
1936
  }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "shinjuku-shield",
3
- "version": "0.3.205",
3
+ "version": "0.3.207",
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": "a7462936",
7
- "shinjukuSha256": "a74629364f4ac22ce7b0ac74294824d926277cc1d2c5fb160f69087cb04a0303",
6
+ "shinjukuRelease": "cb3d8f7d",
7
+ "shinjukuSha256": "cb3d8f7da30834d0d6bb95942a06afe07b394be9ad6f48bc19fff3718d4a05cc",
8
8
  "license": "SEE LICENSE IN LICENSE.txt",
9
9
  "author": "Shinjuku Shield",
10
10
  "homepage": "https://github.com/ShinjukuStaition/shinjuku-shield#readme",
@@ -48437,6 +48437,20 @@ function relayLimitWords(state2 = relayLimitNow(), { now = Date.now(), ownRpc }
48437
48437
  }[state2.reason];
48438
48438
  return `Shinjuku's free Solana chain reader ${what}. It did not pass this step's request to the Solana network.` + (ownRpc ? ` To go on now, ${ownRpc}.` : "");
48439
48439
  }
48440
+ function relayLimitStateOf(error, now = Date.now()) {
48441
+ for (let link3 = error, depth = 0; link3 && depth < 8; depth += 1) {
48442
+ if (REASONS.has(link3.relayReason) && Number.isSafeInteger(link3.opensAtMs) && link3.opensAtMs > now) return { reason: link3.relayReason, opensAtMs: link3.opensAtMs };
48443
+ link3 = link3 instanceof Error ? link3.cause : void 0;
48444
+ }
48445
+ return relayLimitNow(now);
48446
+ }
48447
+ function relayLimitShortWords(state2 = relayLimitNow(), { now = Date.now() } = {}) {
48448
+ if (!state2) return void 0;
48449
+ const left = waitWords(state2.opensAtMs - now);
48450
+ if (state2.reason === "relay_budget_unavailable") return `Shinjuku's free Solana chain reader could not count its use for a moment. Ask again in about ${left}.`;
48451
+ const when = state2.reason === "relay_daily_limit" ? "today" : "this hour";
48452
+ return `Shinjuku's free Solana chain reader is full for ${when}. It opens again at ${clockWords(state2.opensAtMs)} (in about ${left}). Ask again then.`;
48453
+ }
48440
48454
  function relayLimitError(state2, now) {
48441
48455
  const seconds2 = Math.max(1, Math.ceil((state2.opensAtMs - now) / 1e3));
48442
48456
  return Object.assign(
@@ -48451,7 +48465,7 @@ function isRelayLimitError(error) {
48451
48465
  }
48452
48466
  return false;
48453
48467
  }
48454
- var REASONS, RELAY_BUDGET_RETRY_MAX_SECONDS, fallbackSeconds, BUDGET_PAUSE_MAX_SECONDS, closed, waitWords, clockWords;
48468
+ var REASONS, RELAY_BUDGET_RETRY_MAX_SECONDS, fallbackSeconds, BUDGET_PAUSE_MAX_SECONDS, closed, waitWords, clockWords, relayLimitSeconds;
48455
48469
  var init_relayLimit = __esm({
48456
48470
  "wallet/src/net/relayLimit.mjs"() {
48457
48471
  "use strict";
@@ -48470,6 +48484,7 @@ var init_relayLimit = __esm({
48470
48484
  return minutes >= 60 ? `${Math.floor(minutes / 60)} h ${minutes % 60} min` : `${minutes} min`;
48471
48485
  };
48472
48486
  clockWords = (ms) => `${new Date(Math.ceil(ms / 6e4) * 6e4).toISOString().slice(11, 16)} UTC`;
48487
+ relayLimitSeconds = (state2, now = Date.now()) => state2 ? Math.max(1, Math.ceil((state2.opensAtMs - now) / 1e3)) : void 0;
48473
48488
  }
48474
48489
  });
48475
48490
 
@@ -110156,7 +110171,7 @@ function paymentTimeText(paidAtMs, nowMs = Date.now()) {
110156
110171
  function validPaymentTimeMs(ms) {
110157
110172
  return Number.isSafeInteger(ms) && ms >= PAYMENT_TIME_MIN_MS && ms <= PAYMENT_TIME_MAX_MS && Number.isFinite(new Date(ms).getTime());
110158
110173
  }
110159
- function readFloatRefundOutcomes(store, now = Date.now()) {
110174
+ function readFloatRefundOutcomes(store, now = Date.now(), arrived2 = []) {
110160
110175
  const outcomes = [];
110161
110176
  let names;
110162
110177
  try {
@@ -110164,29 +110179,71 @@ function readFloatRefundOutcomes(store, now = Date.now()) {
110164
110179
  } catch {
110165
110180
  return outcomes;
110166
110181
  }
110182
+ const keys3 = new Set((Array.isArray(arrived2) ? arrived2 : []).flatMap((one) => [
110183
+ typeof one?.requestId === "string" ? `r:${one.requestId}` : void 0,
110184
+ typeof one?.floatId === "string" ? `f:${one.floatId}` : void 0
110185
+ ]).filter(Boolean));
110167
110186
  for (const name of names) {
110168
110187
  if (!name.startsWith(FLOAT_PAYMENT_WAL_PREFIX2)) continue;
110169
110188
  try {
110170
110189
  const record = store.readWal(name);
110171
110190
  if (record?.schema !== FLOAT_PAYMENT_SCHEMA2 || !["refund_pending", "submitted"].includes(floatRecordState(record))) continue;
110172
- if (record.refundOutcome === void 0 || record.refundOutcomeShown !== false) continue;
110173
- const inner = String(record.innerRequestId ?? "");
110174
- outcomes.push({
110175
- floatId: record.floatId,
110176
- paidAtomic: record.paidAtomic,
110177
- host: floatSellerHost(record),
110178
- outcome: record.refundOutcome,
110179
- atMs: record.refundOutcomeAtMs,
110180
- // The first VALID time (Codex round 1 on 7faf9c93: `??` took an invalid non-null time before a valid later one).
110181
- // and never one after now (Codex round 1 on 41e095b2: a time in the future is no time).
110182
- paidAtMs: [record.floatPaidAtMs, record.submittedAtMs, record.createdAtMs].find((ms) => validPaymentTimeMs(ms) && ms <= now),
110183
- ...inner.endsWith(":float") ? { requestId: inner.slice(0, -":float".length) } : {}
110184
- });
110191
+ if (record.refundOutcome === void 0) {
110192
+ const key = refundKeyOf(record);
110193
+ const told = keys3.has(key) ? heldRefundOutcome(record, now) : void 0;
110194
+ if (told) outcomes.push({ ...told, held: true });
110195
+ continue;
110196
+ }
110197
+ if (record.refundOutcomeShown !== false) continue;
110198
+ outcomes.push(refundOutcomeView(record, record.refundOutcome, record.refundOutcomeAtMs, now));
110185
110199
  } catch {
110186
110200
  }
110187
110201
  }
110188
110202
  return outcomes;
110189
110203
  }
110204
+ function refundKeyOf(record) {
110205
+ const inner = String(record?.innerRequestId ?? "");
110206
+ return inner.endsWith(":float") ? `r:${inner.slice(0, -":float".length)}` : `f:${record?.floatId}`;
110207
+ }
110208
+ function writeHeldRefundOutcomes(store, floatIds, now = Date.now()) {
110209
+ const wanted = new Set(floatIds);
110210
+ if (!wanted.size) return;
110211
+ let names;
110212
+ try {
110213
+ names = store.listWal();
110214
+ } catch {
110215
+ return;
110216
+ }
110217
+ for (const name of names) {
110218
+ if (!name.startsWith(FLOAT_PAYMENT_WAL_PREFIX2)) continue;
110219
+ try {
110220
+ const record = store.readWal(name);
110221
+ if (record?.schema !== FLOAT_PAYMENT_SCHEMA2 || !wanted.has(record.floatId) || record.refundOutcome !== void 0) continue;
110222
+ if (!["refund_pending", "submitted"].includes(floatRecordState(record)) || typeof record.innerRequestId !== "string") continue;
110223
+ releaseRefundedReservation({ store, requestId: record.innerRequestId });
110224
+ store.writeWal(name, { ...record, refundOutcome: "refund_arrived", refundOutcomeAtMs: now, refundOutcomeShown: false });
110225
+ } catch {
110226
+ }
110227
+ }
110228
+ }
110229
+ function refundOutcomeView(record, outcome, atMs, now) {
110230
+ const inner = String(record.innerRequestId ?? "");
110231
+ return {
110232
+ floatId: record.floatId,
110233
+ paidAtomic: record.paidAtomic,
110234
+ host: floatSellerHost(record),
110235
+ outcome,
110236
+ atMs,
110237
+ paidAtMs: [record.floatPaidAtMs, record.submittedAtMs, record.createdAtMs].find((ms) => validPaymentTimeMs(ms) && ms <= now),
110238
+ ...inner.endsWith(":float") ? { requestId: inner.slice(0, -":float".length) } : {}
110239
+ };
110240
+ }
110241
+ function heldRefundOutcome(record, now = Date.now()) {
110242
+ const state2 = floatRecordState(record);
110243
+ if (record?.refundOutcome !== void 0 || state2 !== "submitted" && state2 !== "refund_pending") return void 0;
110244
+ const old = state2 === "submitted" ? submittedNewsOld([record.submittedAtMs, record.floatPaidAtMs, record.createdAtMs], now) : !(now - record.refundPendingAtMs < REFUND_OUTCOME_NEWS_MS);
110245
+ return old ? void 0 : refundOutcomeView(record, "refund_arrived", now, now);
110246
+ }
110190
110247
  function markFloatRefundOutcomesShown(store, shown) {
110191
110248
  const wanted = new Map(shown.map(({ floatId, outcome }) => [floatId, outcome]));
110192
110249
  if (!wanted.size) return;
@@ -113268,10 +113325,10 @@ async function everyAccountHeld({ store, connection, programId, serviceUrl: serv
113268
113325
  function assertAccountsNotSplit({ accounts, account, notes, allNotes = notes, amountAtomic }) {
113269
113326
  const atomicOf = (entries, key) => entries.reduce((sum2, entry) => sum2 + BigInt(entry[key].b), 0n);
113270
113327
  if (accounts.length > 1 && BigInt(account.account.b) + atomicOf(notes, "note") < BigInt(amountAtomic) && atomicOf(accounts, "account") + atomicOf(allNotes, "note") >= BigInt(amountAtomic)) {
113271
- throw new Error(
113328
+ throw Object.assign(new Error(
113272
113329
  "p03_merchant_respend_insufficient_recovered_value",
113273
113330
  { cause: new Error("p03_merchant_respend_accounts_split_merge_first") }
113274
- );
113331
+ ), { splitAmountAtomic: BigInt(amountAtomic).toString() });
113275
113332
  }
113276
113333
  }
113277
113334
  async function prepareRecoveredPayment({
@@ -116274,13 +116331,6 @@ function sellerInputLine(missing, line, room = SAY_MAX_WORDS) {
116274
116331
  const lines = tries.map((text3) => line(text3, list.length));
116275
116332
  return lines.find((text3) => words(text3) <= room) ?? lines[lines.length - 1];
116276
116333
  }
116277
- function refundInFlightAtomic(breakdown) {
116278
- const total = String(breakdown?.refundsInFlightAtomic ?? "");
116279
- if (!ATOMIC7.test(total)) return void 0;
116280
- const arrived2 = (Array.isArray(breakdown.refundsInFlight) ? breakdown.refundsInFlight : []).filter((entry) => entry?.refundArrived === true && ATOMIC7.test(String(entry.refundAtomic ?? ""))).reduce((sum2, entry) => sum2 + BigInt(entry.refundAtomic), 0n);
116281
- const left = BigInt(total) - arrived2;
116282
- return (left > 0n ? left : 0n).toString();
116283
- }
116284
116334
  function spendSentence(a, tails = ["."], room = SAY_MAX_WORDS) {
116285
116335
  if (!ATOMIC7.test(String(a?.balanceAtomic ?? ""))) return void 0;
116286
116336
  const heads = spendHeads(a.balanceAtomic, a.largestPaymentAtomic, a);
@@ -116330,8 +116380,8 @@ function refusalSay(a, tool, again, npmVersion) {
116330
116380
  const Seller = `${seller[0].toUpperCase()}${seller.slice(1)}`;
116331
116381
  const data = tool === "inference_chat" ? "answer" : "data";
116332
116382
  if (/^rpc_relay_limit\b/.test(code2)) {
116333
- const opens = relayLimitWords(relayLimitNow());
116334
- return opens ? `${opens.split(/(?<=\.)\s/)[0]} Ask again then.` : "Shinjuku's free Solana chain reader reached its limit for now. Ask again later.";
116383
+ const state2 = Number.isSafeInteger(a.relayOpensAtMs) && typeof a.relayReason === "string" ? { reason: a.relayReason, opensAtMs: a.relayOpensAtMs } : relayLimitNow();
116384
+ return relayLimitShortWords(state2) ?? "Shinjuku's free Solana chain reader reached its limit for now. Ask again later.";
116335
116385
  }
116336
116386
  if (code2 === "mcp_max_payment_not_usdc") {
116337
116387
  const cap = usdcText2(a.capAtomic);
@@ -117748,7 +117798,7 @@ var init_say = __esm({
117748
117798
  doneInText = (a) => Number.isSafeInteger(a.doneInMinutesLow) && Number.isSafeInteger(a.doneInMinutesHigh) ? `about ${a.doneInMinutesLow} to ${a.doneInMinutesHigh} minutes` : "";
117749
117799
  positive = (text3) => text3 !== void 0 && text3 !== "0";
117750
117800
  str = (value2) => typeof value2 === "string" ? value2 : "";
117751
- refundInFlight = (a) => usdcText2(refundInFlightAtomic(a.breakdown));
117801
+ refundInFlight = (a) => usdcText2(a.breakdown?.refundsInFlightAtomic);
117752
117802
  sellerAnswered = (status, data) => status >= 500 ? "had a server error" : status >= 400 ? "refused the request" : `sent no ${data}`;
117753
117803
  urlAnswered = (status) => status === 404 || status === 410 ? "was not found" : status === 401 || status === 403 ? "refused access" : status >= 500 ? "had a server error" : "refused the request";
117754
117804
  OWN_WORK_WORDS = Object.freeze({
@@ -121590,6 +121640,7 @@ function floatRefunds(store, snapshot) {
121590
121640
  const notCertainFor = [];
121591
121641
  let open5 = 0n;
121592
121642
  const openFor = [];
121643
+ const arrivedFor = [];
121593
121644
  for (const name of store.listWal()) {
121594
121645
  if (!name.startsWith(FLOAT_PAYMENT_WAL_PREFIX2)) continue;
121595
121646
  let record;
@@ -121609,7 +121660,9 @@ function floatRefunds(store, snapshot) {
121609
121660
  openFor.push({ ...payment, paidAtomic: refundAtomic });
121610
121661
  continue;
121611
121662
  }
121612
- if (state2 !== "refund_pending" && !refusedOpen || floatRefundHeld(snapshot, record)) continue;
121663
+ const held2 = floatRefundHeld(snapshot, record);
121664
+ if (held2 && heldRefundOutcome(record) !== void 0) arrivedFor.push(refundOf(record));
121665
+ if (state2 !== "refund_pending" && !refusedOpen || held2) continue;
121613
121666
  if (refusedOpen || !knowsRecipients) {
121614
121667
  notCertain += BigInt(record.paidAtomic);
121615
121668
  notCertainFor.push(refundOf(record));
@@ -121618,7 +121671,7 @@ function floatRefunds(store, snapshot) {
121618
121671
  provenFor.push(refundOf(record));
121619
121672
  }
121620
121673
  }
121621
- return { proven, notCertain, provenFor, notCertainFor, open: open5, openFor };
121674
+ return { proven, notCertain, provenFor, notCertainFor, open: open5, openFor, arrivedFor };
121622
121675
  }
121623
121676
  function balanceView(store) {
121624
121677
  const neverReceived = /* @__PURE__ */ new Set();
@@ -121684,6 +121737,7 @@ function partsOf(report, store, snapshot) {
121684
121737
  refundsNotCertain: refunds.notCertainFor,
121685
121738
  openPaymentsAtomic: refunds.open.toString(),
121686
121739
  openPayments: refunds.openFor,
121740
+ refundsArrived: refunds.arrivedFor,
121687
121741
  setAsideAtomic: setAside.toString(),
121688
121742
  totalAtomic: (spendable + setAside + refunds.proven).toString(),
121689
121743
  privateSendPendingAtomic: report.split.privateSendPendingAtomic,
@@ -125234,6 +125288,28 @@ function joinPlanSize(outputs, exitReserved = /* @__PURE__ */ new Set(), held2)
125234
125288
  })];
125235
125289
  }
125236
125290
  }
125291
+ function oneSpendCovers(store, amountAtomic) {
125292
+ try {
125293
+ const snapshotRead = readBalanceSnapshot(store);
125294
+ const snapshot = snapshotRead.snapshot;
125295
+ if (!snapshot || snapshot.pool !== store.state.pool || !Array.isArray(snapshot.outputs)) return false;
125296
+ const sendHeld = savedSendHold({ store, snapshotRead });
125297
+ if (sendHeld === null) return false;
125298
+ const key = (commitment) => BigInt(commitment).toString();
125299
+ const joinHeld = /* @__PURE__ */ new Set();
125300
+ for (const { record } of mergeRecords(store)) {
125301
+ if (!openJoin(record)) continue;
125302
+ joinHeld.add(key(record.mergeAccountCommitment));
125303
+ for (const note of record.mergeNoteCommitments ?? []) joinHeld.add(key(note));
125304
+ }
125305
+ const exitReserved = exitReservedNoteCommitments(store);
125306
+ const free = snapshot.outputs.filter((output2) => output2.spendStatus === "unspent" && !joinHeld.has(key(output2.commitment)) && !(output2.kind === "account" ? sendHeld.accounts : sendHeld.notes).has(String(output2.commitment)) && !(output2.kind === "note" && exitReserved.has(key(output2.commitment))));
125307
+ const most = largestOneSpend(free);
125308
+ return most !== void 0 && most >= BigInt(amountAtomic);
125309
+ } catch {
125310
+ return false;
125311
+ }
125312
+ }
125237
125313
  function joinParts(store, snapshotRead) {
125238
125314
  try {
125239
125315
  const read = snapshotRead ?? readBalanceSnapshot(store);
@@ -135790,20 +135866,41 @@ function refundOutcomeText(outcome, nowMs = Date.now()) {
135790
135866
  if (outcome?.outcome === "refund_arrived") return `The ${amount}refund for ${payment} arrived.`;
135791
135867
  return `The ${amount}refund for ${payment} could not be matched in your balance (this balance read cannot tell refunds apart); if it came back, balanceAtomic counts it already.`;
135792
135868
  }
135793
- function refundOutcomesToShow(outcomes, shown, exceptFloatId) {
135794
- return outcomes.filter(({ floatId, outcome }) => !shown.has(`${floatId}:${outcome}`) && !(typeof exceptFloatId === "string" && floatId === exceptFloatId));
135869
+ function answerCountsBalance(breakdown) {
135870
+ return Boolean(breakdown) && typeof breakdown === "object" && /^[0-9]+$/.test(String(breakdown.shieldedAtomic ?? ""));
135871
+ }
135872
+ function answerRefundOutcomes(store, breakdown, now = Date.now()) {
135873
+ if (!answerCountsBalance(breakdown)) return [];
135874
+ try {
135875
+ return readFloatRefundOutcomes(store, now, breakdown.refundsArrived);
135876
+ } catch {
135877
+ return [];
135878
+ }
135879
+ }
135880
+ function writeToldRefunds(leased, fresh) {
135881
+ writeHeldRefundOutcomes(leased, fresh.filter(({ held: held2 }) => held2 === true).map(({ floatId }) => floatId));
135882
+ markFloatRefundOutcomesShown(leased, fresh);
135883
+ }
135884
+ function refundNotCounted(breakdown, outcome) {
135885
+ if (outcome?.outcome !== "refund_arrived" || !breakdown || typeof breakdown !== "object") return false;
135886
+ const names = (entry) => typeof entry?.requestId === "string" && entry.requestId === outcome.requestId || typeof entry?.floatId === "string" && entry.floatId === outcome.floatId;
135887
+ return [breakdown.refundsInFlight, breakdown.refundsNotCertain, breakdown.openPayments].some((list) => Array.isArray(list) && list.some(names));
135888
+ }
135889
+ function refundOutcomesToShow(outcomes, shown, exceptFloatId, breakdown) {
135890
+ return outcomes.filter((outcome) => !shown.has(`${outcome.floatId}:${outcome.outcome}`) && !(typeof exceptFloatId === "string" && outcome.floatId === exceptFloatId) && !refundNotCounted(breakdown, outcome));
135795
135891
  }
135796
135892
  function noticesOnce({
135797
135893
  outcomes,
135798
135894
  readUnkept,
135799
135895
  shown,
135800
135896
  exceptFloatId,
135897
+ breakdown,
135801
135898
  markRefunds,
135802
135899
  markUnkept,
135803
135900
  textOf: textOf2 = (outcome) => refundOutcomeText(outcome),
135804
135901
  unkeptText = answerNotKeptNoticeWords
135805
135902
  }) {
135806
- const fresh = refundOutcomesToShow(outcomes, shown, exceptFloatId);
135903
+ const fresh = refundOutcomesToShow(outcomes, shown, exceptFloatId, breakdown);
135807
135904
  let unkept;
135808
135905
  let refundNotices;
135809
135906
  let paidNotices;
@@ -135812,21 +135909,13 @@ function noticesOnce({
135812
135909
  refundNotices = fresh.map((outcome) => textOf2(outcome));
135813
135910
  paidNotices = unkept.map((notice) => unkeptText(notice));
135814
135911
  } catch {
135815
- return { notices: {}, arrived: [] };
135912
+ return {};
135816
135913
  }
135817
135914
  for (const { floatId, outcome } of fresh) shown.add(`${floatId}:${outcome}`);
135818
135915
  for (const { requestId } of unkept) shown.add(`unkept:${requestId}`);
135819
135916
  if (fresh.length) markRefunds(fresh);
135820
135917
  if (unkept.length) markUnkept(unkept);
135821
- return {
135822
- notices: { ...refundNotices.length ? { refundNotices } : {}, ...paidNotices.length ? { paidNotices } : {} },
135823
- arrived: fresh.filter(({ outcome }) => outcome === "refund_arrived")
135824
- };
135825
- }
135826
- function markArrivedRefunds(breakdown, arrived2) {
135827
- if (!breakdown || !Array.isArray(breakdown.refundsInFlight) || !arrived2?.length) return breakdown;
135828
- const named = (entry) => arrived2.some((one) => typeof entry?.requestId === "string" && entry.requestId === one.requestId || typeof entry?.floatId === "string" && entry.floatId === one.floatId);
135829
- return { ...breakdown, refundsInFlight: breakdown.refundsInFlight.map((entry) => named(entry) ? { ...entry, refundArrived: true } : entry) };
135918
+ return { ...refundNotices.length ? { refundNotices } : {}, ...paidNotices.length ? { paidNotices } : {} };
135830
135919
  }
135831
135920
  function floatRefusal(error, overLimit, tool = "pay_for_service") {
135832
135921
  const code2 = String(error?.message ?? "").split(/[\s:;(]/, 1)[0];
@@ -136993,6 +137082,9 @@ function balanceFields(parts) {
136993
137082
  // UX136-1: a payment whose seller answered an error while Shinjuku's transfer is open (balanceNow.mjs openPaymentsAtomic).
136994
137083
  openPaymentsAtomic: parts.openPaymentsAtomic,
136995
137084
  ...parts.openPayments?.length ? { openPayments: parts.openPayments } : {},
137085
+ // Lotus to-do 85 follow-up: refunds already in shieldedAtomic with no notice told yet; this answer's notice step tells
137086
+ // them (takeRefundNotices reads only its own answer's breakdown).
137087
+ ...parts.refundsArrived?.length ? { refundsArrived: parts.refundsArrived } : {},
136996
137088
  setAsideAtomic: parts.setAsideAtomic,
136997
137089
  totalAtomic: parts.totalAtomic,
136998
137090
  // Parts of a running wallet_unshield private send not sent yet: already taken off shieldedAtomic (R4, no overspend in flight).
@@ -137510,25 +137602,21 @@ ${key}`).digest("hex").slice(0, 40)}.json`);
137510
137602
  ...share ? { share } : {}
137511
137603
  });
137512
137604
  const shownRefunds = /* @__PURE__ */ new Set();
137513
- const takeRefundNotices = (store, exceptFloatId) => {
137605
+ const takeRefundNotices = (store, exceptFloatId, breakdown) => {
137514
137606
  let open5;
137515
137607
  try {
137516
137608
  open5 = store ?? session.openStore();
137517
137609
  } catch {
137518
- return { notices: {}, arrived: [] };
137519
- }
137520
- let outcomes;
137521
- try {
137522
- outcomes = readFloatRefundOutcomes(open5);
137523
- } catch {
137524
- outcomes = [];
137610
+ return {};
137525
137611
  }
137612
+ const outcomes = answerRefundOutcomes(open5, breakdown);
137526
137613
  return noticesOnce({
137527
137614
  outcomes,
137528
137615
  readUnkept: () => readAnswerNotKeptNotices(open5),
137529
137616
  shown: shownRefunds,
137530
137617
  exceptFloatId,
137531
- markRefunds: (fresh) => underLease((leased) => markFloatRefundOutcomesShown(leased, fresh)).catch(() => {
137618
+ breakdown,
137619
+ markRefunds: (fresh) => underLease((leased) => writeToldRefunds(leased, fresh)).catch(() => {
137532
137620
  }),
137533
137621
  markUnkept: (unkept) => underLease((leased) => markAnswerNotKeptShown(leased, unkept)).catch(() => {
137534
137622
  })
@@ -137543,11 +137631,10 @@ ${key}`).digest("hex").slice(0, 40)}.json`);
137543
137631
  return answer;
137544
137632
  }
137545
137633
  if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) return answer;
137546
- const { notices, arrived: arrived2 } = takeRefundNotices(store, value2.floatId);
137634
+ const notices = takeRefundNotices(store, value2.floatId, value2.breakdown);
137547
137635
  if (!notices.refundNotices && !notices.paidNotices) return answer;
137548
137636
  return json4({
137549
137637
  ...value2,
137550
- ...value2.breakdown ? { breakdown: markArrivedRefunds(value2.breakdown, arrived2) } : {},
137551
137638
  ...notices,
137552
137639
  ...typeof value2.next === "string" ? { next: `${value2.next.replace(/[.\s]+$/, "")}${noticesStep(notices)}` } : {}
137553
137640
  });
@@ -138901,12 +138988,18 @@ ${canonical5}`;
138901
138988
  return void 0;
138902
138989
  }
138903
138990
  const readyInSecondsOf = (error, code2) => FLOAT_BUSY_CODES.has(code2) ? Number.isFinite(error?.retryAfterSeconds) && error.retryAfterSeconds > 0 ? Math.ceil(error.retryAfterSeconds) : code2 === "p03_float_busy_retry_later" ? 30 : 60 : code2 === "p03_float_config_unreadable" ? 60 : void 0;
138991
+ function splitAmountOf(error) {
138992
+ for (let at = error, depth = 0; at && depth < 6; at = at.cause, depth += 1) {
138993
+ if (ATOMIC_TEXT.test(String(at.splitAmountAtomic ?? ""))) return String(at.splitAmountAtomic);
138994
+ }
138995
+ return void 0;
138996
+ }
138904
138997
  function joinHolds(error, code2) {
138905
138998
  if (insufficientCause(describeError(error, { fallback: "mcp_payment_failed", safeText: SAFE_TEXT })) === "split") return true;
138906
138999
  const blocking = error?.blockingRequestId ?? error?.cause?.blockingRequestId;
138907
139000
  return /another_request_unresolved$/.test(code2) && typeof blocking === "string" && /^unshield-merge-/.test(blocking);
138908
139001
  }
138909
- async function payJoin2({ requestId, calledAt, progress: progress2, canProgress, signal }) {
139002
+ async function payJoin2({ requestId, calledAt, progress: progress2, canProgress, signal, amountAtomic }) {
138910
139003
  const asked = joiner.request({ key: sha256Hex2(Buffer.from(`x402_pay:${requestId}`, "utf8")) });
138911
139004
  if (!asked.joining) return { join: { joining: false } };
138912
139005
  if (asked.first && canProgress) return { join: { joining: true, first: true } };
@@ -138918,6 +139011,15 @@ ${canonical5}`;
138918
139011
  let end2;
138919
139012
  try {
138920
139013
  end2 = await joinLoop({ until, signal, onReady: () => true, each: () => {
139014
+ if (amountAtomic !== void 0) {
139015
+ let store;
139016
+ try {
139017
+ store = session.openStore();
139018
+ } catch {
139019
+ store = void 0;
139020
+ }
139021
+ if (store && oneSpendCovers(store, amountAtomic)) return { stop: "covered" };
139022
+ }
138921
139023
  try {
138922
139024
  progress2("getting your balance ready to pay, then the payment; nothing was paid yet");
138923
139025
  } catch {
@@ -138932,8 +139034,9 @@ ${canonical5}`;
138932
139034
  seen.moved ||= joinCounts.final > before.final || joinCounts.sent > before.sent;
138933
139035
  payJoinSeen.set(requestId, seen);
138934
139036
  const late2 = end2.end === "stop" && canProgress && Date.now() + PAY_AFTER_JOIN_MS > calledAt + joinCallMaxMs;
138935
- line(end2.end === "stop" ? late2 ? "ready-late" : "ready" : end2.end);
138936
- if (end2.end === "stop" && !late2) return { ready: true };
139037
+ const covered = end2.end === "stop" && end2.value === "covered";
139038
+ line(end2.end === "stop" ? `${late2 ? "ready-late" : "ready"}${covered ? " covered=1" : ""}` : end2.end);
139039
+ if (end2.end === "stop" && !late2) return { ready: true, covered };
138937
139040
  return { join: {
138938
139041
  joining: true,
138939
139042
  joinsDone: seen.joinsDone,
@@ -139044,6 +139147,7 @@ ${canonical5}`;
139044
139147
  let askUnshown = false;
139045
139148
  let retriedInCall = false;
139046
139149
  let joinedInCall = false;
139150
+ let coveredJoin = false;
139047
139151
  for (let attempt = 0; response === void 0; attempt += 1) {
139048
139152
  try {
139049
139153
  response = await (attempt === 0 && first ? first : payOnce());
@@ -139105,7 +139209,9 @@ ${canonical5}`;
139105
139209
  if (replaced) return replaced;
139106
139210
  let join51;
139107
139211
  if (joinHolds(error, code2)) {
139108
- const joined = joinedInCall ? { join: { joining: true } } : await payJoin2({ requestId, calledAt, progress: progress2, canProgress, signal });
139212
+ const again2 = joinedInCall && coveredJoin;
139213
+ const joined = joinedInCall && !again2 ? { join: { joining: true } } : await payJoin2({ requestId, calledAt, progress: progress2, canProgress, signal, amountAtomic: again2 ? void 0 : splitAmountOf(error) });
139214
+ coveredJoin = !again2 && joined.covered === true;
139109
139215
  joinedInCall = true;
139110
139216
  if (joined.ready) {
139111
139217
  payJoinSeen.delete(requestId);
@@ -139227,8 +139333,8 @@ ${canonical5}`;
139227
139333
  }
139228
139334
  mark("mcp-result");
139229
139335
  const shinjukuTransaction = floatPaid ? leg1Transaction(paidStore, float, requestId) : null;
139230
- const { notices, arrived: arrivedRefunds } = takeRefundNotices(paidStore, float?.floatId);
139231
139336
  const shownBalance = balanceAnswer(one);
139337
+ const notices = takeRefundNotices(paidStore, float?.floatId, shownBalance.breakdown);
139232
139338
  return answerResult(paidAnswerContent({
139233
139339
  status: response.status,
139234
139340
  headers: response.headers,
@@ -139249,7 +139355,6 @@ ${canonical5}`;
139249
139355
  // Leg 1 (this wallet's private payment to Shinjuku, a pool transaction): the seller may return no settle signature.
139250
139356
  ...floatPaid ? { via: "shinjuku", shinjukuTransaction } : {},
139251
139357
  ...shownBalance,
139252
- ...shownBalance.breakdown ? { breakdown: markArrivedRefunds(shownBalance.breakdown, arrivedRefunds) } : {},
139253
139358
  ...notices,
139254
139359
  next: (unpaid ? "nothing was paid: this request id's payment never landed (the pool's public history proves it), and the answer it got came back again; nothing new was paid. Tell the user nothing was paid for it" : receipt.replayed === true ? "this request id was already paid: the stored receipt came back and nothing new was paid" + (floatPaid && receipt.receiptFinality === "pending" ? `. ${floatPaidNext({ transaction, shinjukuTransaction, pending: true })}` : "") : floatPaid ? floatPaidNext({ transaction: unpaid ? null : transaction, shinjukuTransaction, pending: receipt.receiptFinality === "pending" }) + (receipt.stallResent === true || float?.sellerStallResent === true ? `. Tell the user too: ${stallResentLine()}` : "") : "paid; tell the user what was paid (amountAtomic, transaction). wallet_receipts lists this payment, wallet_balance shows the new balance") + noticesStep(notices)
139255
139360
  }, "pay_for_service")
@@ -139813,6 +139918,22 @@ ${canonical5}`;
139813
139918
  next = "nothing was paid. Tell the user this seller's price terms are in an older or broken form this wallet cannot read. Do not retry this URL unchanged; find_paid_services finds sellers this wallet can pay";
139814
139919
  } else if (code2.startsWith("wallet_quote_refused_") || code2.startsWith("fetch_")) {
139815
139920
  next = inference ? "nothing was paid; do not call inference_chat again unchanged" : code2.startsWith("wallet_quote_refused_") ? "nothing was paid; do not pay this URL. Pay a different seller (find_paid_services finds one)" : "nothing was paid; do not retry this URL unchanged";
139921
+ } else if (code2 === "rpc_relay_limit" || isRelayLimitError(error)) {
139922
+ const state2 = relayLimitStateOf(error);
139923
+ const seconds2 = relayLimitSeconds(state2);
139924
+ const short = relayLimitShortWords(state2) ?? "Shinjuku's free Solana chain reader reached its limit for now. Ask again later.";
139925
+ const again2 = inference ? resume : `call ${tool} again with request_id "${requestId}" (it never pays twice)`;
139926
+ return refuse11(
139927
+ "rpc_relay_limit",
139928
+ `the payment did not finish: ${relayLimitWords(state2) ?? reasonOf("rpc_relay_limit")}`,
139929
+ `The free chain reader stopped this step before it reached the Solana network. Tell the user: ${short} Do not call ${tool} again before then${seconds2 ? ` (wait at least ${seconds2} s)` : ""}: a call before then meets the same limit. Then ${again2}, or close an unsent payment with wallet_cancel request_id "${requestId}"; wallet_receipts lists it if it was paid`,
139930
+ {
139931
+ requestId,
139932
+ ...fields,
139933
+ ...seconds2 ? { readyInSeconds: seconds2 } : {},
139934
+ ...state2 ? { relayReason: state2.reason, relayOpensAtMs: state2.opensAtMs } : {}
139935
+ }
139936
+ );
139816
139937
  } else {
139817
139938
  next = inference ? `the outcome is not known to be final: ${resume}. Or close an unsent payment with wallet_cancel request_id "${requestId}"; wallet_receipts lists it if it was paid` : `the outcome is not known to be final: call pay_for_service again with request_id "${requestId}" (it never pays twice), or close an unsent payment with wallet_cancel request_id "${requestId}"; wallet_receipts lists it if it was paid`;
139818
139939
  }
@@ -140157,12 +140278,11 @@ ${canonical5}`;
140157
140278
  }
140158
140279
  }
140159
140280
  const landedFrom = (total, sales) => sales <= 0n ? "USDC you added" : sales >= total ? "USDC from your sales" : "USDC you added and from your sales";
140160
- function walletCard({ one, unshielded, landingAtomic, landingSalesAtomic = 0n, recordFaultAtomic = 0n, sales, store, lastRead, refundBreakdown = one.breakdown, refresh = {} }) {
140281
+ function walletCard({ one, unshielded, landingAtomic, landingSalesAtomic = 0n, recordFaultAtomic = 0n, sales, store, lastRead, refresh = {} }) {
140161
140282
  const known = ATOMIC_TEXT.test(String(one.balanceAtomic ?? ""));
140162
140283
  const landing = `${landingAtomic > 0n ? `; ${usdcText3(landingAtomic)} ${landedFrom(landingAtomic, landingSalesAtomic)} is being counted` : ""}${sales ? `; ${sales.line}` : ""}`;
140163
140284
  const reading2 = lastRead ? `the wallet is still reading it; the last full read, ${ageWords2(lastRead.ageMinutes)} ago, showed ${usdcText3(lastRead.privateAtomic)} USDC` : "the wallet is still reading it";
140164
- const inFlightAtomic = refundInFlightAtomic(refundBreakdown);
140165
- const inFlight = /^0*[1-9][0-9]*$/.test(String(inFlightAtomic ?? "")) ? usdcText3(inFlightAtomic) : void 0;
140285
+ const inFlight = /^[1-9][0-9]*$/.test(String(one.breakdown?.refundsInFlightAtomic ?? "")) ? usdcText3(one.breakdown.refundsInFlightAtomic) : void 0;
140166
140286
  const checking = refresh.refreshing === true && (refresh.refreshReason === void 0 || refresh.refreshReason === "refund_check");
140167
140287
  const lines = [!known ? `Private balance: not known yet (${reading2})${landing}` : checking ? `Private balance: last known ${usdcText3(one.balanceAtomic)} USDC${inFlight ? `, plus a ${inFlight} USDC refund` : ""}; the wallet is checking it now${landing}` : `Private balance: ${spendHeads(one.balanceAtomic, one.largestPaymentAtomic, one)[0].replace(/^You /, "you ")}${inFlight ? `, plus ${inFlight} USDC refund on its way` : ""}${landing}`];
140168
140288
  if (recordFaultAtomic > 0n) lines.push(`${usdcText3(recordFaultAtomic)} USDC you added landed, but Shinjuku's record of it does not match; nothing is lost; do not send it again`);
@@ -140707,7 +140827,7 @@ ${canonical5}`;
140707
140827
  if (sales) {
140708
140828
  next = `${next}. Tell the user: buyers paid ${sales.usdc} USDC for ${sales.payments === 1 ? "a sale" : `${sales.payments} sales`}, and the wallet is moving it into the private balance by itself (it is not in the balance yet; nothing to do). Call wallet_balance in a few minutes to see it in the balance`;
140709
140829
  }
140710
- const { notices, arrived: arrivedRefunds } = takeRefundNotices();
140830
+ const notices = takeRefundNotices(void 0, void 0, one?.breakdown);
140711
140831
  next = `${next}${noticesStep(notices)}`;
140712
140832
  if (ownTokens?.tokens.length) {
140713
140833
  const count3 = ownTokens.tokens.length + ownTokens.more;
@@ -140748,7 +140868,7 @@ ${canonical5}`;
140748
140868
  }
140749
140869
  internal.unshieldedTotalAtomic = exitedTotalAtomic ?? null;
140750
140870
  const { setAsideAtomic, ...breakdownRest } = one.breakdown;
140751
- const breakdown = markArrivedRefunds(setAsideAtomic === "0" ? breakdownRest : one.breakdown, arrivedRefunds);
140871
+ const breakdown = setAsideAtomic === "0" ? breakdownRest : one.breakdown;
140752
140872
  if (setAsideAtomic === "0") internal.setAsideAtomic = "0";
140753
140873
  const noLimit = (atomic5) => atomic5 === void 0 || atomic5 === null || String(atomic5) === NO_LIMIT_ATOMIC;
140754
140874
  const capWords2 = (atomic5) => noLimit(atomic5) ? "no limit" : `${usdcText3(atomic5)} USDC`;
@@ -140771,7 +140891,7 @@ ${canonical5}`;
140771
140891
  ...reportPublic,
140772
140892
  ...firstRead ? { status: "reading" } : {},
140773
140893
  ...balanceTextFields(one),
140774
- card: walletCard({ one, unshielded, landingAtomic, landingSalesAtomic: landingParts.salesAtomic, recordFaultAtomic: landingParts.recordFaultAtomic, sales, store, lastRead, refundBreakdown: breakdown, refresh }),
140894
+ card: walletCard({ one, unshielded, landingAtomic, landingSalesAtomic: landingParts.salesAtomic, recordFaultAtomic: landingParts.recordFaultAtomic, sales, store, lastRead, refresh }),
140775
140895
  ...lastRead ? { lastRead } : {},
140776
140896
  // joinSteps: the joins, one after another (autoJoin.mjs joinParts joins), when the wallet gets the balance ready by
140777
140897
  // itself; doneInMinutes*: the time to send all of it (UX128-9).