shinjuku-shield 0.3.231 → 0.3.232

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
@@ -8,7 +8,7 @@ web services and AI answers from your private balance, so the payment does
8
8
  not show who paid. It works inside your AI app (Claude, Cursor, Codex) and in
9
9
  a terminal. Only you hold the keys: they never leave your computer.
10
10
 
11
- This is version 0.3.231. The command is `shinjuku`.
11
+ This is version 0.3.232. The command is `shinjuku`.
12
12
 
13
13
  ## Set up
14
14
 
@@ -55,7 +55,7 @@ choose Reconnect.
55
55
 
56
56
  ## Add money
57
57
 
58
- Ask your AI app: "Add 0.50 USDC to my private balance." It gives you a
58
+ Ask your AI app: "Give me an address to add 0.50 USDC to my wallet." It gives you a
59
59
  one-time address. Send USDC on Solana to it from any wallet or exchange. Any
60
60
  amount from 0.01 USDC works, and you need no SOL. The USDC becomes private by
61
61
  itself.
@@ -112,7 +112,7 @@ Add it yourself. The name of the wallet in your app is `shinjuku`.
112
112
  Claude Code:
113
113
 
114
114
  ```sh
115
- claude mcp add --scope user shinjuku -- npx -y --prefer-offline --no-audit --no-fund shinjuku-shield@0.3.231 mcp
115
+ claude mcp add --scope user shinjuku -- npx -y --prefer-offline --no-audit --no-fund shinjuku-shield@0.3.232 mcp
116
116
  ```
117
117
 
118
118
  `--prefer-offline` runs the copy of the wallet that npm saved. If npm has not saved it yet, that start asks
@@ -131,7 +131,7 @@ with the Releases table in
131
131
  Versions are published from GitHub Actions with npm provenance.
132
132
 
133
133
  `shinjuku-shield` is the package that holds the wallet. `shinjuku-shielded`
134
- 0.3.231, its older name, runs this package at the same version, so wallets
134
+ 0.3.232, its older name, runs this package at the same version, so wallets
135
135
  installed under that name keep updating. New installs use `shinjuku`.
136
136
 
137
137
  The full guide is
package/manifest.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "schema": "carbon-shielded-wallet/bundle-manifest/v1",
3
3
  "file": "shinjuku-wallet.mjs",
4
- "sha256": "85d42668d914c75fb1ebb54ae6a2f3915963bd346b4221aef2bbb4bbc6ac7837",
5
- "bytes": 10387804,
6
- "sourceCommit": "7592a8701ac1673497c3a7237b586a14e323ff2a",
4
+ "sha256": "2f7cb80719d593daf7009d1fd201163bf0e178bf71da9f2982f540cb88bef93c",
5
+ "bytes": 10397692,
6
+ "sourceCommit": "3e583881833a8dca4001cfedfbf18a779a0c16b5",
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",
10
10
  "lockfiles": [
11
11
  {
12
12
  "path": "package-lock.json",
13
- "sha256": "fb09574c17591c046d1af40aff530699dd7b268182fb12978da32f564dea1ad6"
13
+ "sha256": "3f46c881ebcd4a6da512e689ea562005ae43b8376251aa68d3ef7b937fec66ea"
14
14
  }
15
15
  ],
16
16
  "esbuildVersion": "0.28.1",
@@ -82,8 +82,8 @@
82
82
  },
83
83
  {
84
84
  "path": "wallet/src/mcp/views/price-card.html",
85
- "sha256": "15f2b89b5734a50ad8f7c6df47cf126adf620c1d0b8bb67ac7a527b97b26d054",
86
- "bytes": 6417
85
+ "sha256": "790a908cf656ad8240721d0263a783615297f5d4af98d3d0bf1d40555b74ecc3",
86
+ "bytes": 7464
87
87
  },
88
88
  {
89
89
  "path": "wallet/src/mcp/views/receipts.html",
@@ -92,8 +92,8 @@
92
92
  },
93
93
  {
94
94
  "path": "wallet/src/mcp/views/shared.js",
95
- "sha256": "490941e561a44e115b60d6c38e0d5ecbcae909b59b66106022643908c9e4cda5",
96
- "bytes": 3427
95
+ "sha256": "b4db09678412f922ef07c22bb85d402ddfe90aab7c3a93b9a0ef3395c195b403",
96
+ "bytes": 3546
97
97
  },
98
98
  {
99
99
  "path": "wallet/src/mcp/views/wallet-card.html",
@@ -1968,5 +1968,5 @@
1968
1968
  }
1969
1969
  ]
1970
1970
  },
1971
- "publishedAt": "2026-11-13T13:35:40.888Z"
1971
+ "publishedAt": "2026-11-16T19:43:49.036Z"
1972
1972
  }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "shinjuku-shield",
3
- "version": "0.3.231",
3
+ "version": "0.3.232",
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": "85d42668",
7
- "shinjukuSha256": "85d42668d914c75fb1ebb54ae6a2f3915963bd346b4221aef2bbb4bbc6ac7837",
6
+ "shinjukuRelease": "2f7cb807",
7
+ "shinjukuSha256": "2f7cb80719d593daf7009d1fd201163bf0e178bf71da9f2982f540cb88bef93c",
8
8
  "license": "SEE LICENSE IN LICENSE.txt",
9
9
  "author": "Shinjuku Shield",
10
10
  "homepage": "https://github.com/ShinjukuStaition/shinjuku-shield#readme",
@@ -86,6 +86,8 @@ var init_fs = __esm({
86
86
  <title>Shinjuku Shield price</title>
87
87
  <style>
88
88
  :root { color-scheme: light dark; }
89
+ /* The hidden attribute wins over the display rules below (.actions is flex): without it Pay and Cancel showed on a card with no price. */
90
+ [hidden] { display: none !important; }
89
91
  body { margin: 0; padding: 14px 16px; font-family: var(--font-sans, system-ui, sans-serif); font-size: var(--font-text-sm-size, 14px);
90
92
  color: var(--color-text-primary, CanvasText); background: var(--color-background-primary, Canvas); }
91
93
  .card { border: var(--border-width-regular, 1px) solid var(--color-border-primary, GrayText); border-radius: var(--border-radius-lg, 10px); padding: 14px 16px; }
@@ -114,7 +116,7 @@ var init_fs = __esm({
114
116
  <button id="pay" class="primary" type="button" disabled>Pay</button>
115
117
  <button id="cancel" type="button">Cancel</button>
116
118
  </div>
117
- <div class="actions"><button id="more" type="button" hidden>Get the result (pays nothing more)</button></div>
119
+ <div class="actions" id="more-row" hidden><button id="more" type="button">Get the result (pays nothing more)</button></div>
118
120
  <div id="message" class="message"></div>
119
121
  </div>
120
122
  <!--EXT_APPS-->
@@ -142,12 +144,13 @@ var init_fs = __esm({
142
144
  // (the wallet got the balance ready and the next call pays); "pending" waits for a click (asking for the result pays nothing more).
143
145
  var MAX_ROUNDS = 20;
144
146
  var more = document.getElementById("more");
147
+ var moreRow = document.getElementById("more-row");
145
148
  var moreToken = null;
146
149
  more.addEventListener("click", function () {
147
150
  if (!moreToken) return;
148
151
  var sent = moreToken;
149
152
  moreToken = null;
150
- more.hidden = true;
153
+ moreRow.hidden = true;
151
154
  S.message("Asking for the result...");
152
155
  send(sent, 0);
153
156
  });
@@ -164,7 +167,7 @@ var init_fs = __esm({
164
167
  send(next, round + 1);
165
168
  return;
166
169
  }
167
- if (state === "pending" && next) { moreToken = next; more.hidden = false; }
170
+ if (state === "pending" && next) { moreToken = next; moreRow.hidden = false; }
168
171
  S.message(state === "in_progress" ? "The payment is not finished yet. Ask me whether it paid; your receipts show it. Do not pay again."
169
172
  : say || (state === "paid" ? "Paid." : state === "pending" ? "Sent; the result is not in yet. Do not pay again."
170
173
  : state === "not_paid" ? "Nothing was paid." : "Ask me whether it paid; your receipts show it."),
@@ -179,8 +182,20 @@ var init_fs = __esm({
179
182
  cancel.disabled = true;
180
183
  S.message("Nothing was paid.");
181
184
  });
185
+ // A card with no price to pay: no price rows, no Pay, no Cancel, only the wallet's words (nothing can be paid from it).
186
+ function noPrice(host, text) {
187
+ document.getElementById("host").textContent = host || "";
188
+ document.getElementById("rows").replaceChildren();
189
+ token = null;
190
+ actions.hidden = true;
191
+ pay.disabled = true;
192
+ cancel.disabled = true;
193
+ S.message(text || "Nothing was paid. Ask me for the price again.", "bad");
194
+ }
182
195
  S.start(function (view, data) {
183
196
  if (view.kind === "card-pay") return; // the answer of a Pay click (drawn by the click handler)
197
+ var priced = Boolean(view.priceUsdc || view.totalUsdc);
198
+ if (!priced) { noPrice(view.host, view.reason || (typeof data.say === "string" ? data.say : "")); return; }
184
199
  document.getElementById("host").textContent = view.host || "";
185
200
  var rows = document.getElementById("rows");
186
201
  rows.replaceChildren();
@@ -193,6 +208,9 @@ var init_fs = __esm({
193
208
  pay.disabled = !token;
194
209
  cancel.disabled = !token;
195
210
  S.message(token ? "" : (view.reason || (typeof data.say === "string" ? data.say : "")), token ? "" : "bad");
211
+ }, function (result) {
212
+ // An answer with no card data (an argument refusal, a crash): the same no-price card with its words.
213
+ noPrice("", S.textOf(result));
196
214
  });
197
215
  })();
198
216
  </script>
@@ -261,12 +279,13 @@ var init_fs = __esm({
261
279
  refresh: refresh,
262
280
  contentOf: contentOf,
263
281
  textOf: textOf,
264
- /** start(draw): draw(view, data) on every tool result that carries a view. */
265
- start: function (draw) {
282
+ /** start(draw, bare): draw(view, data) on every tool result that carries a view; bare(result), when given, on one that does not. */
283
+ start: function (draw, bare) {
266
284
  drawn = draw;
267
285
  app.ontoolresult = function (result) {
268
286
  var data = contentOf(result);
269
287
  if (data) draw(data.view, data);
288
+ else if (typeof bare === "function") bare(result);
270
289
  };
271
290
  app.onhostcontextchanged = function (context) { theme(context); };
272
291
  app.connect().then(function () { theme(app.getHostContext()); }, function () { message("This app could not open the wallet view.", "bad"); });
@@ -124396,7 +124415,7 @@ function build(a, tool, npmVersion) {
124396
124415
  if (count3 < 1 && a.sendState === "sending") {
124397
124416
  const where = a.stage === "exit" ? "it may already be there" : "it is on its way";
124398
124417
  return firstFit(
124399
- `Sending ${what} to ${a.to} now; ${where}. Ask again for its transaction; it never sends twice.`,
124418
+ `Sending ${what} to ${a.to} now; ${where}. Ask me later for its transaction.`,
124400
124419
  `Sending ${what} to ${a.to} now; ${where}.`
124401
124420
  );
124402
124421
  }
@@ -124698,8 +124717,8 @@ var init_say = __esm({
124698
124717
  discoverCutRows = (a) => (Array.isArray(a?.sourcesRead) ? a.sourcesRead : []).filter((source) => source && typeof source === "object" && source.ok === true && source.truncated === true && !(source.loading === true && source.partial === true));
124699
124718
  CONFIRMED_SEND_TOOLS = /* @__PURE__ */ new Set(["wallet_unshield"]);
124700
124719
  KEEP_ID_NOTE = "Keep request_id values for your own calls; never show one to the user.";
124701
- BALANCE_READ_DOES = "starts no payment or send, and makes USDC the user added private, which is what the user wants";
124702
- SAFE_BALANCE_READ = `call wallet_balance yourself (do not make the user ask; a balance read is always safe: it reads the chain, ${BALANCE_READ_DOES})`;
124720
+ BALANCE_READ_DOES = "starts no payment or new send; it finishes what is under way: added USDC moves into the user's own private balance, and a stopped earlier send goes on to its address";
124721
+ SAFE_BALANCE_READ = `call wallet_balance yourself (do not make the user ask; a balance read reads the chain, ${BALANCE_READ_DOES})`;
124703
124722
  }
124704
124723
  });
124705
124724
 
@@ -125007,7 +125026,12 @@ async function payTurn({ session, target, method, headers, body, maxPrice, polic
125007
125026
  }), {
125008
125027
  timeoutMs: Number.isSafeInteger(opts?.unpaidTimeoutMs) && opts.unpaidTimeoutMs > 0 ? opts.unpaidTimeoutMs : void 0,
125009
125028
  openTimeoutMs: opts?.unpaidOpenTimeoutMs,
125010
- onCut: opts?.onUnpaidCut
125029
+ onCut: opts?.onUnpaidCut,
125030
+ // A request that must not go twice is resent only on a sure "not sent"; each resend over Tor on a new circuit when
125031
+ // the wallet can move it; the body has its own bound after the headers (unpaidRequest options).
125032
+ resendUnknownTls: false,
125033
+ newCircuitOnResend: true,
125034
+ bodyAllowance: true
125011
125035
  }));
125012
125036
  if (response.status !== 402) return response;
125013
125037
  let encoded = response.headers.get("PAYMENT-REQUIRED");
@@ -125142,7 +125166,18 @@ function unreachedCause(error, { timedOut = error?.name === "TimeoutError", prox
125142
125166
  if (codes.includes("EAI_AGAIN")) return "lookup_failed";
125143
125167
  return "failed";
125144
125168
  }
125145
- async function unpaidRequest(target, init, { fetchImpl = fetch, timeoutMs = UNPAID_TIMEOUT_MS, openTimeoutMs, tor = inTorRun, proxy = runProxy, onCut } = {}) {
125169
+ async function unpaidRequest(target, init, {
125170
+ fetchImpl = fetch,
125171
+ timeoutMs = UNPAID_TIMEOUT_MS,
125172
+ openTimeoutMs,
125173
+ tor = inTorRun,
125174
+ proxy = runProxy,
125175
+ onCut,
125176
+ resendUnknownTls = true,
125177
+ newCircuitOnResend = false,
125178
+ onResend,
125179
+ bodyAllowance = false
125180
+ } = {}) {
125146
125181
  const startedAt = Date.now();
125147
125182
  for (let attempt = 0; ; attempt += 1) {
125148
125183
  const circuit = torCircuit();
@@ -125152,21 +125187,38 @@ async function unpaidRequest(target, init, { fetchImpl = fetch, timeoutMs = UNPA
125152
125187
  const opened = afterTunnelOpen(openTimeoutMs);
125153
125188
  const bound = opened ? AbortSignal.any([timeout, opened.signal]) : timeout;
125154
125189
  const tls = watchTlsDone(target, () => opened?.socket);
125190
+ const own = bodyAllowance ? new AbortController() : void 0;
125191
+ const follow = () => own.abort(bound.reason);
125192
+ if (own) {
125193
+ if (bound.aborted) follow();
125194
+ else bound.addEventListener("abort", follow, { once: true });
125195
+ }
125196
+ const tryBound = own ? own.signal : bound;
125155
125197
  try {
125156
125198
  const response = await withTunnelOpen(opened?.start, () => fetchImpl(target, {
125157
125199
  ...request,
125158
- signal: request.signal ? AbortSignal.any([request.signal, bound]) : bound
125200
+ signal: request.signal ? AbortSignal.any([request.signal, tryBound]) : tryBound
125159
125201
  }));
125160
125202
  opened?.stop();
125161
- return response;
125203
+ if (!own) return response;
125204
+ bound.removeEventListener("abort", follow);
125205
+ return withBodyBound(response, own, timeoutMs);
125162
125206
  } catch (error) {
125163
125207
  opened?.stop();
125208
+ if (own) bound.removeEventListener("abort", follow);
125164
125209
  const code2 = typeof error?.cause?.code === "string" && /^[A-Z][A-Z0-9_]{2,40}$/.test(error.cause.code) ? error.cause.code : void 0;
125165
125210
  const callerAbort = Boolean(request.signal?.aborted);
125166
125211
  const noTls = bound.aborted && !timeout.aborted && !callerAbort && Boolean(opened?.fired) && !tls.done;
125167
125212
  const stalled = bound.aborted && !noTls && !callerAbort && !carriesPayment(request.headers) && resendable(target, request.method) && tor();
125168
- if (attempt === 0 && (UNPAID_NOT_SENT.has(code2) || noTls || stalled)) {
125169
- if (stalled) await moveTorCircuitAfterStall(circuit, target, sentAt);
125213
+ const mayGoTwice = !carriesPayment(request.headers) && resendable(target, request.method);
125214
+ const noTlsResend = noTls && (resendUnknownTls || mayGoTwice);
125215
+ const noTlsKept = noTls && !resendUnknownTls && !mayGoTwice;
125216
+ if (attempt === 0 && (UNPAID_NOT_SENT.has(code2) || noTlsResend || stalled)) {
125217
+ const moved = stalled || newCircuitOnResend && tor() ? await moveTorCircuitAfterStall(circuit, target, sentAt) === true : false;
125218
+ try {
125219
+ onResend?.({ moved });
125220
+ } catch {
125221
+ }
125170
125222
  continue;
125171
125223
  }
125172
125224
  const run2 = proxy();
@@ -125178,7 +125230,7 @@ async function unpaidRequest(target, init, { fetchImpl = fetch, timeoutMs = UNPA
125178
125230
  { unreached: { cause: "proxy_down", tor: true } }
125179
125231
  );
125180
125232
  }
125181
- const cut2 = bound.aborted && !callerAbort && !noTls;
125233
+ const cut2 = bound.aborted && !callerAbort && (!noTls || noTlsKept);
125182
125234
  if (cut2) {
125183
125235
  try {
125184
125236
  onCut?.({ tries: attempt + 1, ms: Date.now() - startedAt });
@@ -125187,7 +125239,7 @@ async function unpaidRequest(target, init, { fetchImpl = fetch, timeoutMs = UNPA
125187
125239
  }
125188
125240
  const openCut = cut2 && !timeout.aborted && Boolean(opened?.fired);
125189
125241
  const seconds2 = Math.round((openCut || noTls ? openTimeoutMs : timeoutMs) / 1e3);
125190
- const cause = noTls ? `no TLS answer in ${seconds2} s after its connection opened` : cut2 ? `no answer in ${seconds2} s${openCut ? " after its connection opened" : ""}` : code2 ?? "network error";
125242
+ const cause = noTls && !noTlsKept ? `no TLS answer in ${seconds2} s after its connection opened` : cut2 ? `no answer in ${seconds2} s${openCut ? " after its connection opened" : ""}` : code2 ?? "network error";
125191
125243
  fail31(
125192
125244
  "fetch_seller_unreachable",
125193
125245
  `the seller did not answer the first, unpaid request${tor() ? " over Tor" : ""} (${cause}); nothing was paid`,
@@ -125198,6 +125250,15 @@ async function unpaidRequest(target, init, { fetchImpl = fetch, timeoutMs = UNPA
125198
125250
  }
125199
125251
  }
125200
125252
  }
125253
+ function withBodyBound(response, own, ms) {
125254
+ if (!response.body) return response;
125255
+ const timer = setTimeout(() => own.abort(new DOMException(`the body did not end within ${ms} ms of its headers`, "TimeoutError")), ms);
125256
+ timer.unref?.();
125257
+ const done = () => clearTimeout(timer);
125258
+ own.signal.addEventListener("abort", done, { once: true });
125259
+ const body = response.body.pipeThrough(new TransformStream({ flush: done, cancel: done }));
125260
+ return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
125261
+ }
125201
125262
  function afterTunnelOpen(ms) {
125202
125263
  if (!Number.isSafeInteger(ms) || ms <= 0) return void 0;
125203
125264
  const controller = new AbortController();
@@ -127333,8 +127394,15 @@ function proofWalkHolds(store) {
127333
127394
  const recovered = last?.pool === store.state.pool && last.recovery?.narrowedByDigests !== true && Array.isArray(last.recovery?.recovered) ? last.recovery.recovered : void 0;
127334
127395
  if (!recovered) return void 0;
127335
127396
  const unspent = recovered.filter((entry) => entry?.spendStatus === "unspent");
127397
+ const holdsValue = (entry) => {
127398
+ try {
127399
+ return BigInt((entry.kind === "account" ? entry.account : entry.note).b) > 0n;
127400
+ } catch {
127401
+ return true;
127402
+ }
127403
+ };
127336
127404
  return {
127337
- none: !recovered.some((entry) => entry?.spendStatus === "unspent" || entry?.spendStatus === "succession-movable"),
127405
+ none: !recovered.some((entry) => (entry?.spendStatus === "unspent" || entry?.spendStatus === "succession-movable") && holdsValue(entry)),
127338
127406
  receivedOnly: !unspent.some((entry) => entry.kind === "account") && unspent.some((entry) => entry.kind === "note")
127339
127407
  };
127340
127408
  }
@@ -139241,7 +139309,7 @@ function createAddFundsTool({
139241
139309
  return {
139242
139310
  name: "wallet_add_funds",
139243
139311
  title: "Add money or get paid: a one-time address for USDC",
139244
- description: "Use this to add money to the wallet, and also when someone wants to pay the user (an invoice, a refund, a friend, another agent): the user sends USDC to the address, or gives it to the person who pays them. Answers a NEW one-time Solana address of this wallet (with a solana: pay link, its QR code and one line to paste). Send USDC to it from any wallet or exchange; after it arrives, " + SAFE_BALANCE_READ + `; one read is enough (no other step). USDC at the address goes in up to the private pool's own limit for one deposit (or the shield limit set at start) at a time; ${NEXT_DEPOSIT_WHEN}. An address takes from ${usdc(PAY_ME_MIN_ATOMIC)} USDC: ${ADD_FUNDS_LEAST}; tell the user this before they send less. amount (USDC text, like "0.37") is optional: a hint shown in the link. An amount below ${usdc(PAY_ME_MIN_ATOMIC)} USDC is refused and makes no address, also with the request_id of an open address. Without request_id each call gives a new address (at most 5 unused ones; then the newest unused one again). With a request_id: the first call makes its address, a later call answers that address and its state. Use each address for ONE payer: a second payer on the same address is linked to the first on chain. Moves no money by itself. Refusals: mcp_argument_invalid, payme_amount_invalid, payme_note_invalid, mcp_request_id_reused, mcp_request_id_reserved, payme_key_probe_exhausted, mcp_tool_disabled, wallet_locked, mcp_add_funds_blocked (an earlier open add-funds address blocks new deposits; its next says what to do), mcp_add_funds_failed.`,
139312
+ description: "Use this to add money to the wallet, and also when someone wants to pay the user (an invoice, a refund, a friend, another agent): the user sends USDC to the address, or gives it to the person who pays them. Answers a NEW one-time Solana address of this wallet (with a solana: pay link, its QR code and one line to paste). Send USDC to it from any wallet or exchange; after it arrives, " + SAFE_BALANCE_READ + `; one read is enough (no other step). USDC at the address goes in up to the private pool's own limit for one deposit (or the shield limit set at start) at a time; ${NEXT_DEPOSIT_WHEN}. An address takes from ${usdc(PAY_ME_MIN_ATOMIC)} USDC: ${ADD_FUNDS_LEAST}; tell the user this before they send less. amount (USDC text, like "0.37") is optional: a hint shown in the link. An amount below ${usdc(PAY_ME_MIN_ATOMIC)} USDC is refused and makes no address, also with the request_id of an open address. Without request_id each call gives a new address (at most 5 unused ones; then the newest unused one again). With a request_id: the first call makes its address, a later call answers that address and its state. Use each address for ONE payer: a second payer on the same address is linked to the first on chain. A new address moves no money: nothing moves until the user sends USDC there from their own wallet or an exchange; then that USDC moves into the user's own private balance in this wallet (a balance read, or this call with its request_id, starts it). This tool pays no one and sends nothing out. Refusals: mcp_argument_invalid, payme_amount_invalid, payme_note_invalid, mcp_request_id_reused, mcp_request_id_reserved, payme_key_probe_exhausted, mcp_tool_disabled, wallet_locked, mcp_add_funds_blocked (an earlier open add-funds address blocks new deposits; its next says what to do), mcp_add_funds_failed.`,
139245
139313
  inputSchema: {
139246
139314
  type: "object",
139247
139315
  properties: {
@@ -142227,7 +142295,14 @@ function floatRefusal(error, overLimit, tool = "pay_for_service") {
142227
142295
  } } : {}
142228
142296
  });
142229
142297
  }
142230
- async function fetchChallenge(url, request) {
142298
+ function errorCodeOf2(error) {
142299
+ for (let link3 = error, depth = 0; link3 && typeof link3 === "object" && depth < 8; link3 = link3.cause, depth += 1) {
142300
+ if (typeof link3.code === "string" && /^[A-Z][A-Z0-9_]{2,40}$/.test(link3.code)) return link3.code;
142301
+ }
142302
+ return typeof error?.name === "string" && /^[A-Za-z]{2,40}$/.test(error.name) ? error.name : "unknown";
142303
+ }
142304
+ async function fetchChallenge(url, request, { log = () => {
142305
+ } } = {}) {
142231
142306
  if (/\.onion$/i.test(new URL(url).hostname) && !inTorRun()) {
142232
142307
  return { refusal: [
142233
142308
  "mcp_preview_unreachable",
@@ -142247,18 +142322,62 @@ async function fetchChallenge(url, request) {
142247
142322
  ] };
142248
142323
  }
142249
142324
  let response;
142325
+ const startedAt = Date.now();
142326
+ let tries = 0;
142327
+ const tor = inTorRun();
142328
+ let closeBody = () => {
142329
+ };
142330
+ let moved;
142331
+ const tryFetch = async (target, init) => {
142332
+ tries += 1;
142333
+ const tryStart = Date.now();
142334
+ const own = new AbortController();
142335
+ const follow = () => own.abort(init.signal.reason);
142336
+ if (init.signal?.aborted) follow();
142337
+ else init.signal?.addEventListener("abort", follow, { once: true });
142338
+ try {
142339
+ const answer = await fetch(target, { ...init, signal: own.signal });
142340
+ init.signal?.removeEventListener("abort", follow);
142341
+ const bodyTimer = setTimeout(() => own.abort(new DOMException("the 402 body was not read in time", "TimeoutError")), PREVIEW_BODY_OPEN_MS);
142342
+ bodyTimer.unref?.();
142343
+ closeBody = () => {
142344
+ clearTimeout(bodyTimer);
142345
+ try {
142346
+ own.abort(new DOMException("the price check is done", "AbortError"));
142347
+ } catch {
142348
+ }
142349
+ };
142350
+ return answer;
142351
+ } catch (error) {
142352
+ init.signal?.removeEventListener("abort", follow);
142353
+ log(`MCP_PREVIEW_FETCH_FAILED code=${errorCodeOf2(error)} try=${tries} ms=${Date.now() - tryStart}${tor ? " tor" : ""}`);
142354
+ throw error;
142355
+ }
142356
+ };
142250
142357
  try {
142251
- response = await fetch(url, {
142358
+ response = await unpaidRequest(url, () => ({
142252
142359
  method: request.method,
142253
142360
  headers: request.headers,
142254
142361
  ...request.body ? { body: request.body } : {},
142255
- redirect: "manual",
142256
- signal: AbortSignal.timeout(PREVIEW_TIMEOUT_MS)
142362
+ redirect: "manual"
142363
+ }), {
142364
+ fetchImpl: tryFetch,
142365
+ timeoutMs: tor ? UNPAID_TOR_TRY_MS : UNPAID_CLEAR_MS,
142366
+ ...tor ? { openTimeoutMs: UNPAID_TOR_OPEN_MS } : {},
142367
+ resendUnknownTls: false,
142368
+ newCircuitOnResend: true,
142369
+ onResend: ({ moved: now }) => {
142370
+ moved = now;
142371
+ },
142372
+ onCut: ({ tries: cutTries, ms }) => log(`MCP_PREVIEW_FETCH_CUT ms=${ms} tries=${cutTries}${tor ? " tor" : ""}`)
142257
142373
  });
142374
+ if (tries > 1) log(`MCP_PREVIEW_FETCH_RESENT tries=${tries} moved=${moved === true} ms=${Date.now() - startedAt}${tor ? " tor" : ""}`);
142258
142375
  } catch (error) {
142259
- const tor = inTorRun();
142260
142376
  const proxy = runProxy();
142261
- const cause = unreachedCause(error, { proxy });
142377
+ const unreached = error?.unreached && typeof error.unreached.cause === "string" ? error.unreached : void 0;
142378
+ const cause = unreached?.cause ?? unreachedCause(error, { proxy });
142379
+ const ownCode = String(error?.message ?? "").split(":", 1)[0];
142380
+ log(`MCP_PREVIEW_FETCH_FAILED final code=${unreached && /^[a-z_]{3,40}$/.test(ownCode) ? ownCode : errorCodeOf2(error)} cause=${cause} tries=${tries}${tries > 1 ? ` moved=${moved === true}` : ""} ms=${Date.now() - startedAt}${tor ? " tor" : ""}`);
142262
142381
  if (cause === "proxy_down") {
142263
142382
  const { why: why2, say: say3 } = unreachedWords({ cause, tor });
142264
142383
  return { refusal: [
@@ -142269,7 +142388,8 @@ async function fetchChallenge(url, request) {
142269
142388
  ] };
142270
142389
  }
142271
142390
  const onion = /\.onion$/i.test(new URL(url).hostname);
142272
- const { why, say: say2 } = unreachedWords({ cause, tor, seconds: Math.round(PREVIEW_TIMEOUT_MS / 1e3), onion });
142391
+ const seconds2 = Number.isSafeInteger(unreached?.seconds) ? unreached.seconds : Math.round((tor ? UNPAID_TOR_TRY_MS : UNPAID_CLEAR_MS) / 1e3);
142392
+ const { why, say: say2 } = unreachedWords({ cause, tor, seconds: seconds2, onion });
142273
142393
  return { refusal: [
142274
142394
  "mcp_preview_unreachable",
142275
142395
  `${why}; nothing was paid`,
@@ -142277,6 +142397,13 @@ async function fetchChallenge(url, request) {
142277
142397
  { say: say2 }
142278
142398
  ] };
142279
142399
  }
142400
+ try {
142401
+ return await challengeOf(response);
142402
+ } finally {
142403
+ closeBody();
142404
+ }
142405
+ }
142406
+ async function challengeOf(response) {
142280
142407
  if (response.status !== 402) {
142281
142408
  await response.body?.cancel();
142282
142409
  return { status: response.status, contentType: response.headers.get("content-type") };
@@ -144905,7 +145032,7 @@ ${key}`).digest("hex").slice(0, 40)}.json`);
144905
145032
  }
144906
145033
  const request = checkRequest(args);
144907
145034
  if (request.refusal) return refuse11(...request.refusal);
144908
- const challenge = await fetchChallenge(target.url, request);
145035
+ const challenge = await fetchChallenge(target.url, request, { log });
144909
145036
  if (challenge.refusal) return refuse11(...challenge.refusal);
144910
145037
  if (!challenge.paymentRequired) {
144911
145038
  return json4({
@@ -145198,6 +145325,16 @@ ${canonical5}`;
145198
145325
  return block;
145199
145326
  };
145200
145327
  const withoutPlan = (short) => planBlockFor(short) ? { ...short, deposits: short.deposits.filter((deposit) => !(deposit.addFunds && deposit.state === "awaiting_funds")) } : short;
145328
+ const nothingToSpend = (error) => {
145329
+ const line = describeError(error, { fallback: "", safeText: SAFE_TEXT });
145330
+ if (line.split(/[\s:;(]/, 1)[0] === "p03_merchant_respend_no_spendable_account") return true;
145331
+ if (insufficientCause(line) !== "short") return false;
145332
+ try {
145333
+ return proofWalkHolds(session.openStore())?.none === true;
145334
+ } catch {
145335
+ return false;
145336
+ }
145337
+ };
145201
145338
  async function primePlanHeld() {
145202
145339
  let store;
145203
145340
  try {
@@ -145776,7 +145913,7 @@ ${canonical5}`;
145776
145913
  }
145777
145914
  ));
145778
145915
  }
145779
- if (code2 === "p03_merchant_respend_no_spendable_account") await primePlanHeld();
145916
+ if (nothingToSpend(error)) await primePlanHeld();
145780
145917
  const failed = payFailure(error, requestId, "pay_for_service", join59, askUnshown);
145781
145918
  const ready = readyInSecondsOf(error, code2);
145782
145919
  return withRefundNotices(ready !== void 0 ? json4({ ...JSON.parse(failed.text), readyInSeconds: ready }) : failed);
@@ -146373,7 +146510,7 @@ ${canonical5}`;
146373
146510
  );
146374
146511
  } else if (insufficientCause(line) === "split") {
146375
146512
  return joinRefusal();
146376
- } else if (code2 === "p03_merchant_respend_no_spendable_account") {
146513
+ } else if (nothingToSpend(error)) {
146377
146514
  const { empty, receivedOnly } = knownZeroBalance();
146378
146515
  if (empty) return zeroBalanceStop({ tool, requestId, same: same2 });
146379
146516
  const known = knownShort({ payment: true });
@@ -146980,7 +147117,7 @@ ${canonical5}`;
146980
147117
  const balance = {
146981
147118
  name: "wallet_balance",
146982
147119
  title: "Balance",
146983
- description: `Use this for "what is my balance" or "how much USDC do I have": it answers ONE balance (balanceAtomic, what a payment can spend) and the public (unshielded) USDC. Always safe: it ${BALANCE_READ_DOES}. On "show my wallet", print \`card\` as it is (at most 9 lines). largestPaymentAtomic: the most ONE payment can spend now; a payment above it is not refused: pay_for_service gets the balance ready first (a tell-first answer, then doneInMinutesLow to doneInMinutesHigh minutes) (changeSettling: 0 only while the last payment's change settles, about changeReadyInSeconds; then one payment can use it all, or up to changeUpToAtomic). balanceParts (above 1): never mention parts, accounts or a merge; say only that a large payment or send first gets the balance ready. balanceAtomic is one number; breakdown names the rest (shieldedAtomic is the same value; privateSendPendingAtomic is what a running private send has not sent yet, already taken off; refundsInFlightAtomic is a refund Shinjuku proved, on its way, not in balanceAtomic; refundsNotCertainAtomic a refund the seller may have kept, in no number; openPaymentsAtomic: paid, waiting on its seller (same request_id finishes it, else refunded); setAsideAtomic (when not 0): value an older version set aside; totalAtomic adds these; during a pool move, pools lists each pool's share, movingAtomic is value on its way to the new pool, and move and poolSwitches show the move). unshieldedAtomic is the public USDC on the wallet's own Solana key (ownAddress), which wallet_shield makes private; unshieldedSolLamports is that key's SOL (Shinjuku pays every fee and rent). A stale balance (a new deposit, a received payment) reads the chain first; past about 20 s it answers the last balance with refreshing: true and finishes in the background (call again in 30 s); with a refreshReason that balance is exact and counts what the reason names (payment_settling: a payment that settles; account_join: all of it, while the wallet gets it ready to send; pool_move: value that arrives from the old pool; refund_check: a refund counted from an old read, which the wallet checks now (never say it is still on its way); first_check: a new wallet's own landed deposits (its first history check); own_send: the user's own send of ownSendAtomic is on its way, balanceAtomic null until it finishes). status reading (balanceAtomic null): the first read of a wallet that may hold money is not done; call again in 30 s. If the public read fails, unshieldedAtomic is null with unshieldedReason. ownKeyTokens: the other tokens on ownAddress (not its USDC; [] when none; null when not read now: say nothing of other tokens), each { mint, amountAtomic, decimals, amount }, at most 10 (ownKeyTokensMore counts the rest); a token is its mint, never a name or symbol; no wallet tool sells, swaps or sends them: they stay on ownAddress. earlierDeposits (when any): USDC at an earlier pool's one-time deposit address, each with a notice line to tell the user; the wallet moves it itself. addFunds (when any): each open wallet_add_funds address, its state and the USDC known to wait there (heldAtomic; null with heldNote when not read in time). startsAtNextRequest true (old name): it starts by itself once USDC is seen there (startsInMinutes; 0: at once). landingAtomic (when not 0): added USDC that landed on chain, not in balanceAtomic yet; this call finishes it (up to about 20 s), else call again when next says. incomingFromSalesAtomic (when not 0; incomingFromSalesPayments counts them): what buyers paid this wallet's sales, moving into the private balance by itself, not in balanceAtomic yet. session:the spending limits (null or "none": no limit), what is left, and how to change them (session.summary, only when a limit is set). With no limit set, say nothing about limits or counters. To add money, use wallet_add_funds. version: this wallet's version. Amounts are atomic (1000000 = 1 USDC); say and usdc give USDC.`,
147120
+ description: `Use this for "what is my balance" or "how much USDC do I have": it answers ONE balance (balanceAtomic, what a payment can spend) and the public (unshielded) USDC. It ${BALANCE_READ_DOES}. On "show my wallet", print \`card\` as it is (at most 9 lines). largestPaymentAtomic: the most ONE payment can spend now; a payment above it is not refused: pay_for_service gets the balance ready first (a tell-first answer, then doneInMinutesLow to doneInMinutesHigh minutes) (changeSettling: 0 only while the last payment's change settles, about changeReadyInSeconds; then one payment can use it all, or up to changeUpToAtomic). balanceParts (above 1): never mention parts, accounts or a merge; say only that a large payment or send first gets the balance ready. balanceAtomic is one number; breakdown names the rest (shieldedAtomic is the same value; privateSendPendingAtomic is what a running private send has not sent yet, already taken off; refundsInFlightAtomic is a refund Shinjuku proved, on its way, not in balanceAtomic; refundsNotCertainAtomic a refund the seller may have kept, in no number; openPaymentsAtomic: paid, waiting on its seller (same request_id finishes it, else refunded); setAsideAtomic (when not 0): value an older version set aside; totalAtomic adds these; during a pool move, pools lists each pool's share, movingAtomic is value on its way to the new pool, and move and poolSwitches show the move). unshieldedAtomic is the public USDC on the wallet's own Solana key (ownAddress), which wallet_shield makes private; unshieldedSolLamports is that key's SOL (Shinjuku pays every fee and rent). A stale balance (a new deposit, a received payment) reads the chain first; past about 20 s it answers the last balance with refreshing: true and finishes in the background (call again in 30 s); with a refreshReason that balance is exact and counts what the reason names (payment_settling: a payment that settles; account_join: all of it, while the wallet gets it ready to send; pool_move: value that arrives from the old pool; refund_check: a refund counted from an old read, which the wallet checks now (never say it is still on its way); first_check: a new wallet's own landed deposits (its first history check); own_send: the user's own send of ownSendAtomic is on its way, balanceAtomic null until it finishes). status reading (balanceAtomic null): the first read of a wallet that may hold money is not done; call again in 30 s. If the public read fails, unshieldedAtomic is null with unshieldedReason. ownKeyTokens: the other tokens on ownAddress (not its USDC; [] when none; null when not read now: say nothing of other tokens), each { mint, amountAtomic, decimals, amount }, at most 10 (ownKeyTokensMore counts the rest); a token is its mint, never a name or symbol; no wallet tool sells, swaps or sends them: they stay on ownAddress. earlierDeposits (when any): USDC at an earlier pool's one-time deposit address, each with a notice line to tell the user; the wallet moves it itself. addFunds (when any): each open wallet_add_funds address, its state and the USDC known to wait there (heldAtomic; null with heldNote when not read in time). startsAtNextRequest true (old name): it starts by itself once USDC is seen there (startsInMinutes; 0: at once). landingAtomic (when not 0): added USDC that landed on chain, not in balanceAtomic yet; this call finishes it (up to about 20 s), else call again when next says. incomingFromSalesAtomic (when not 0; incomingFromSalesPayments counts them): what buyers paid this wallet's sales, moving into the private balance by itself, not in balanceAtomic yet. session:the spending limits (null or "none": no limit), what is left, and how to change them (session.summary, only when a limit is set). With no limit set, say nothing about limits or counters. To add money, use wallet_add_funds. Amounts are atomic (1000000 = 1 USDC); say and usdc give USDC.`,
146984
147121
  inputSchema: { type: "object", properties: {
146985
147122
  verbose: { type: "boolean", description: "Optional. true adds `internal`: the engineering numbers (funded balance records, notes, payments without waiting, a 0 set-aside value). Default false." }
146986
147123
  }, additionalProperties: false },
@@ -147407,8 +147544,8 @@ ${canonical5}`;
147407
147544
  let next;
147408
147545
  if (firstRead) next = `the first balance read of this wallet is not done (it has run ${refresh.refreshingSeconds ?? 0} s); call wallet_balance again in ${POLL_SECONDS2} s: that call waits up to ${waitSeconds} s for the read`;
147409
147546
  else if (refresh.refreshing && refresh.refreshReason === "own_send") {
147410
- const repeat = runningSends.map((send3) => `wallet_unshield with request_id "${send3.requestId}", amount_atomic "${send3.amountAtomic}", to "${send3.to}"`);
147411
- next = `the user's own ${runningSends.length > 1 ? `${runningSends.length} sends are` : "send is"} on the way and hold${runningSends.length > 1 ? "" : "s"} the private balance until ${runningSends.length > 1 ? "they finish" : "it finishes"}, so there is no spendable number now; tell the user the send is on its way` + (repeat.length ? `. For a send's transaction only, call ${repeat.join("; or ")} (exactly these arguments; it never sends twice)` : "") + `; call wallet_balance again in ${POLL_SECONDS2} s for the balance after it`;
147547
+ const ids = runningSends.map((send3) => `"${send3.requestId}"`);
147548
+ next = `the user's own ${runningSends.length > 1 ? `${runningSends.length} sends are` : "send is"} on the way and hold${runningSends.length > 1 ? "" : "s"} the private balance until ${runningSends.length > 1 ? "they finish" : "it finishes"}, so there is no spendable number now; tell the user the send is on its way` + (ids.length ? `. For a send's transaction only, call wallet_receipts with kind "moves" (it starts no new send and can finish an earlier one; its unshield row with requestId ${ids.join(" or ")} shows it once the send ends)` : "") + `; call wallet_balance again in ${POLL_SECONDS2} s for the balance after it`;
147412
147549
  } else if (refresh.refreshing) next = `the wallet is reading the chain in the background; call wallet_balance again in ${POLL_SECONDS2} s for the current private balance`;
147413
147550
  else if (refresh.refreshError === "wallet_locked") {
147414
147551
  next = `the balance read waited for the wallet lock, which ${refresh.lockedBy ? `this wallet's own work holds now (lockedBy: ${refresh.lockedBy}); tell the user the wallet is busy with it, not another program` : "another wallet command or this wallet's own work holds"}; call wallet_balance again in a minute`;
@@ -147712,7 +147849,7 @@ ${canonical5}`;
147712
147849
  ...report.detail ? { detail: detailPublic } : {},
147713
147850
  breakdown,
147714
147851
  ...refresh,
147715
- // Every send this process runs (own_send): amount and full address; next gives each one's call for its transaction.
147852
+ // Every send this process runs (own_send): amount and full address; next names each one's receipts row for its transaction.
147716
147853
  ...runningSends.length ? { ownSends: runningSends.map((send3) => ({ amountAtomic: send3.amountAtomic, to: send3.to })) } : {},
147717
147854
  ...unshielded,
147718
147855
  ...shieldingAtomic > 0n ? { shieldingAtomic: shieldingAtomic.toString() } : {},
@@ -148235,7 +148372,7 @@ ${canonical5}`;
148235
148372
  } : {},
148236
148373
  ...idle !== "not_sent" && endedReason && live !== "sending" ? { reason: endedReason } : {},
148237
148374
  ...idle === "not_known" ? { next: "not known yet: another wallet process is working now, and nothing of this send is signed; call wallet_receipts again in a minute" } : {},
148238
- ...live === "sending" && record.state !== "exited" ? { next: `being sent now; it cannot be cancelled. Call wallet_unshield with request_id "${shown}", amount_atomic "${record.amountAtomic}", and to "${record.mcpTo}" to see when it is done (it never sends twice)` } : {},
148375
+ ...live === "sending" && record.state !== "exited" ? { next: 'being sent now; it cannot be cancelled. Tell the user it is on its way; this row shows state "sent" and the transaction once it ends; the wallet finishes it by itself: if it still shows sending, tell the user to ask again in a few minutes (not in a loop)' } : {},
148239
148376
  ...retry ? { ...retry, next: `${retryWords(retry)}. Call wallet_unshield with request_id "${joining.requestId}", amount_atomic "${joining.amountAtomic}", and to "${joining.to}" to try now (it never sends twice)` } : {},
148240
148377
  ...joining && !retry ? {
148241
148378
  ...joinStepsField(store),
@@ -148467,7 +148604,7 @@ ${canonical5}`;
148467
148604
  const receipts = {
148468
148605
  name: "wallet_receipts",
148469
148606
  title: "List recent receipts and wallet moves",
148470
- description: `List this wallet's most recent receipts, newest first. Payments (kind x402 or inference): seller (the URL paid), sellerHost, item (what was bought), priceAtomic, feeAtomic, amountAtomic (the total), sellerTransaction, privateTransaction (this wallet's private payment), facilitator, answeredAt, paidFrom (agent app or terminal, when known), and transaction / host (the seller's when known). It lists payments from every app and chat that uses this wallet. pay.shinjukustaition.com is Shinjuku, the private payment service, never the seller. A payment the seller did not take shows state refund_pending (the refund is on its way; floatId, refundState: Shinjuku's refund step in words), refund_sent once Shinjuku sent it (refundTransaction; the balance counts it at a later read), then refunded once the balance holds it (refundTransactionNote when its transaction was not read yet). A payment the seller has not served yet shows waiting_for_seller (or seller_paid_not_served once the transfer to the seller landed): call pay_for_service again with its requestId to get it. seller_refused (the seller refused it, sellerStatus) or outcome_not_certain (an earlier send got no clear answer): not certain yet whether the seller kept the payment; do not pay again until the row changes. never_landed: the payment never went through; nothing was paid and nothing comes back. sellerFailed: true (with httpStatus, sellerCode): paid, but the seller's service failed after it took the payment, so no data came back and no refund comes; never call pay_for_service again with its requestId (same error, nothing paid); a new payment is the user's choice, later. The wallet's own moves (kind shield, add-funds, unshield, private-send, token-transfer, or an older deposit kind): requestId, amountAtomic, state, transaction, at; a private-send row with smaller payments still to go shows partsAt (the time and state of each) and next (it is not stuck); a token-transfer row (an older wallet version's token sale and send) shows tokenMint, tokenAmountAtomic, usdcAtomic (what the sell gave) and sentAtomic; an add-funds row also shows heldAtomic, the USDC waiting at its address (it becomes private by itself: never close an address that holds USDC; belowMinimum: less than minimumAtomic waits there for a top-up). An add-funds row with via "cli" was made by the shinjuku add-funds command in a terminal: amountAtomic, state (done or not_finished), transaction; it has no requestId, and wallet_add_funds never continues it. An unshield row with via "cli" is this wallet's own send, made by the shinjuku unshield command in a terminal: amountAtomic, state (sent, not_finished, not_sent), transaction, and next (with unshieldId, the terminal's own id) when it is not finished; it has no requestId, and wallet_unshield never continues it. A received payment (kind received, a move): amountAtomic and state done; at is null and it sorts last (no sender, no time). A sale (kind sale, a move: a buyer paid this wallet): amountAtomic, at (when paid), note, state done (in the private balance), moving_in (it moves in by itself), checking, not_completed (no money comes from it) or stopped (it does not move in; reason and next: tell the user both). requestId is shown for payments made by this wallet process; older ones show requestKey (its SHA-256). kind "payments" or "moves" lists one group only.`,
148607
+ description: `List this wallet's most recent receipts, newest first. It starts no payment or new send; it can finish an earlier send that is under way (it waits up to about 15 s for it), so a send's result is read here. Payments (kind x402 or inference): seller (the URL paid), sellerHost, item (what was bought), priceAtomic, feeAtomic, amountAtomic (the total), sellerTransaction, privateTransaction (this wallet's private payment), facilitator, answeredAt, paidFrom (agent app or terminal, when known), and transaction / host (the seller's when known). It lists payments from every app and chat that uses this wallet. pay.shinjukustaition.com is Shinjuku, the private payment service, never the seller. A payment the seller did not take shows state refund_pending (the refund is on its way; floatId, refundState: Shinjuku's refund step in words), refund_sent once Shinjuku sent it (refundTransaction; the balance counts it at a later read), then refunded once the balance holds it (refundTransactionNote when its transaction was not read yet). A payment the seller has not served yet shows waiting_for_seller (or seller_paid_not_served once the transfer to the seller landed): call pay_for_service again with its requestId to get it. seller_refused (the seller refused it, sellerStatus) or outcome_not_certain (an earlier send got no clear answer): not certain yet whether the seller kept the payment; do not pay again until the row changes. never_landed: the payment never went through; nothing was paid and nothing comes back. sellerFailed: true (with httpStatus, sellerCode): paid, but the seller's service failed after it took the payment, so no data came back and no refund comes; never call pay_for_service again with its requestId (same error, nothing paid); a new payment is the user's choice, later. The wallet's own moves (kind shield, add-funds, unshield, private-send, token-transfer, or an older deposit kind): requestId, amountAtomic, state, transaction, at; a private-send row with smaller payments still to go shows partsAt (the time and state of each) and next (it is not stuck); a token-transfer row (an older wallet version's token sale and send) shows tokenMint, tokenAmountAtomic, usdcAtomic (what the sell gave) and sentAtomic; an add-funds row also shows heldAtomic, the USDC waiting at its address (it becomes private by itself: never close an address that holds USDC; belowMinimum: less than minimumAtomic waits there for a top-up). An add-funds row with via "cli" was made by the shinjuku add-funds command in a terminal: amountAtomic, state (done or not_finished), transaction; it has no requestId, and wallet_add_funds never continues it. An unshield row with via "cli" is this wallet's own send, made by the shinjuku unshield command in a terminal: amountAtomic, state (sent, not_finished, not_sent), transaction, and next (with unshieldId, the terminal's own id) when it is not finished; it has no requestId, and wallet_unshield never continues it. A received payment (kind received, a move): amountAtomic and state done; at is null and it sorts last (no sender, no time). A sale (kind sale, a move: a buyer paid this wallet): amountAtomic, at (when paid), note, state done (in the private balance), moving_in (it moves in by itself), checking, not_completed (no money comes from it) or stopped (it does not move in; reason and next: tell the user both). requestId is shown for payments made by this wallet process; older ones show requestKey (its SHA-256). kind "payments" or "moves" lists one group only.`,
148471
148608
  inputSchema: {
148472
148609
  type: "object",
148473
148610
  properties: {
@@ -148488,6 +148625,7 @@ ${canonical5}`;
148488
148625
  if (!["all", "payments", "moves"].includes(kind)) {
148489
148626
  return refuse11("mcp_argument_invalid", "kind must be all, payments, or moves", "leave kind out for both payments and moves");
148490
148627
  }
148628
+ if (kind !== "payments") await waitForSendsUnderWay(RECEIPTS_SEND_WAIT_MS);
148491
148629
  let store;
148492
148630
  try {
148493
148631
  store = session.openStore();
@@ -149408,8 +149546,8 @@ ${canonical5}`;
149408
149546
  stage: job.stage,
149409
149547
  sendState: "sending",
149410
149548
  ...exitTransaction ? { exitTransaction } : {},
149411
- detail: `the send has started (now: ${stageWords(job.stage)}): the ${usdcText3(job.amountAtomic)} USDC is leaving the private balance for ${job.to}${where}; it cannot be stopped. It goes on in this wallet process. ${KEPT_ON_DISK}`,
149412
- next: `Do not tell the user that no money moved or that nothing was sent: the send has started${job.stage === "exit" ? " and the USDC may already be at the address" : ""}. Tell the user the send is on its way, then ${again(kind, job)} now: it answers within about ${MONEY_FIRST_ANSWER_MS / 1e3} s, at once when the send ends (with its transaction); the same request_id never sends twice`
149549
+ detail: `the send has started (now: ${stageWords(job.stage)}): the ${usdcText3(job.amountAtomic)} USDC is leaving the private balance for ${job.to}${where}; it cannot be stopped. It goes on in this wallet process. ${SEND_KEPT_ON_DISK}`,
149550
+ next: `Do not tell the user that no money moved or that nothing was sent: the send has started${job.stage === "exit" ? " and the USDC may already be at the address" : ""}. Tell the user the send is on its way. ${SEND_RESULT_READ(job.requestId)}`
149413
149551
  });
149414
149552
  }
149415
149553
  }
@@ -150382,7 +150520,7 @@ ${canonical5}`;
150382
150520
  const AUTO_FINISH_FOR_GOOD = /NEW request_id|Do not retry this request/;
150383
150521
  const AUTO_FINISH_FOR_GOOD_CODES = /* @__PURE__ */ new Set(["payment_never_finalized_use_new_unshield_id"]);
150384
150522
  const autoFinishReason = (code2) => code2 === "payment_never_finalized_use_new_unshield_id" ? "its payment inside the wallet never became final on the chain" : plainReason(code2);
150385
- const autoFinishRunning = /* @__PURE__ */ new Set();
150523
+ const autoFinishRunning = /* @__PURE__ */ new Map();
150386
150524
  let autoFinishTimer;
150387
150525
  const cancelsRunning = /* @__PURE__ */ new Set();
150388
150526
  const answerCode = (answer) => {
@@ -150459,9 +150597,24 @@ ${canonical5}`;
150459
150597
  }
150460
150598
  for (const open6 of openAgentUnshields(store)) {
150461
150599
  if (cancelsRunning.has(open6.rid) || autoFinishRunning.has(open6.name)) continue;
150462
- autoFinishRunning.add(open6.name);
150463
- finishOne(open6).catch((error) => log(`MCP_UNSHIELD_AUTO_FINISH_FAILED requestId=${open6.requestId} ${errorCode4(error, "mcp_unshield_failed")}`)).finally(() => autoFinishRunning.delete(open6.name));
150600
+ autoFinishRunning.set(open6.name, finishOne(open6).catch((error) => log(`MCP_UNSHIELD_AUTO_FINISH_FAILED requestId=${open6.requestId} ${errorCode4(error, "mcp_unshield_failed")}`)).finally(() => autoFinishRunning.delete(open6.name)));
150601
+ }
150602
+ }
150603
+ async function waitForSendsUnderWay(ms) {
150604
+ if (resumeSends) {
150605
+ try {
150606
+ finishStoppedSends();
150607
+ } catch {
150608
+ }
150464
150609
  }
150610
+ const under = [...autoFinishRunning.values(), ...[...jobs.values()].filter((job) => job?.kind === "unshield" && job.state === "running" && job.stage !== "confirming" && !isSplitSend(job) && job.promise).map((job) => job.promise)];
150611
+ if (under.length === 0) return;
150612
+ let timer;
150613
+ await Promise.race([Promise.allSettled(under), new Promise((resolve44) => {
150614
+ timer = setTimeout(resolve44, ms);
150615
+ timer.unref?.();
150616
+ })]);
150617
+ clearTimeout(timer);
150465
150618
  }
150466
150619
  async function finishOne(open6) {
150467
150620
  let claim;
@@ -150695,7 +150848,7 @@ ${canonical5}`;
150695
150848
  const openState = (one) => sendStates.get(one.requestId) === "sending" ? "sending" : "joining";
150696
150849
  intent = intents2.find((one) => one.requestId === request.requestId);
150697
150850
  const openSend = (one) => `a send of ${usdcText3(one.amountAtomic)} USDC to ${one.to.slice(0, 4)}...${one.to.slice(-4)} (request_id "${one.requestId}")`;
150698
- const askNext = (one) => `Ask about that send: call wallet_unshield with request_id "${one.requestId}", amount_atomic "${one.amountAtomic}", and to "${one.to}" (it continues the same send and never sends twice)`;
150851
+ const askNext = (one) => openState(one) === "sending" ? `Ask about that send: call wallet_receipts with kind "moves" (it starts no new send); its unshield row with requestId "${one.requestId}" shows its state and transaction` : `Ask about that send: call wallet_unshield with request_id "${one.requestId}", amount_atomic "${one.amountAtomic}", and to "${one.to}" (it continues the same send and never sends twice)`;
150699
150852
  if (intent && (intent.to !== request.to || intent.amountAtomic !== request.amountAtomic || isSplitSend(request))) {
150700
150853
  return refuse11(
150701
150854
  "mcp_request_id_reused",
@@ -152437,7 +152590,7 @@ ${canonical5}`;
152437
152590
  name: "wallet_unshield",
152438
152591
  // UX130-13: a host that defers tools may show only the title: it says where a send goes by default.
152439
152592
  title: "Send USDC privately",
152440
- description: `Use this for "send 2 USDC to <address>" or "withdraw to my wallet" (for "my wallet" leave \`to\` out: it uses the address saved at setup, or says how to set one; do not ask the user for an address first): it sends amount (USDC, like "2"; or amount_atomic) from the PRIVATE balance as plain USDC to \`to\`, a public Solana address. BEFORE you call it to send all of the balance when wallet_balance showed balanceParts above 1, write to the user that the wallet first gets the balance ready to send (never say how the wallet stores the balance; some apps show nothing until this call ends). Privately: the chain shows the pool paying the address, not which wallet paid. This wallet's own public address (ownAddress in wallet_balance: it holds the public USDC, wallet_shield deposits from it) is refused as \`to\`: an exit there would show on chain that the private balance is this wallet's, even if that address never deposited (wallet_add_funds deposits come from one-time addresses, not from it; never tell the user they came from it). Shinjuku pays every network fee; no SOL is needed. The user's saved own addresses (setup or this app's wallet entry) send at once. Any other address needs the user's yes in a dialog of this app; a client that cannot ask is refused (mcp_unshield_to_not_allowed) and a decline sends nothing (mcp_unshield_declined). \`to\` must already be able to receive USDC: an address that cannot is refused before any dialog (mcp_unshield_to_invalid). It runs in steps and may wait for the pool's next anchor. Each call answers within about 20 s (at once when the send ends; a dialog may take longer) with ok: true and stage: confirming, queued, refreshing, self-pay = preparing, exit = sending, done; joining = the wallet first gets the balance ready, then sends; each call goes on with it (joinSteps: its steps, in order; doneInMinutesLow to doneInMinutesHigh: the time to say). For the status, call wallet_unshield again with the SAME request_id, amount and to. When the balance must first be made ready, the FIRST call answers at once with stage joining and joinTellFirst: true; write its say to the user, then call again with the same request_id at once. One exception: when this app sends a progress token with that next call, the call gets the balance ready and then sends, with a progress line every ${JOIN_STEP_MS / 1e3} s ("getting your balance ready to send"; some apps show none, so the line is said before the call, as above). It answers when the send is done, or after about ${joinAnswerSeconds(JOIN_CALL_MAX_MS)} s with how far it got (joinsDone; sendState sending: the USDC is leaving, never say nothing moved); then call again with the same request_id. Without a progress token it answers within about 20 s with stage joining: call again until it sends. The same request_id never sends twice, also after a restart. request_id is optional: without it the answer names the id it made, and the same call again within 10 minutes after it ends reads that same send. An optional unshield limit the user sets may bound each call and what this wallet sends in any 24 hours, from every app (mcp_unshield_cap_exceeded: tell the user). Other refusals: mcp_argument_invalid, mcp_request_id_reused, wallet_locked, mcp_tool_disabled, mcp_unshield_failed, and the unshield's own p03_* codes. A call the app stopped, rejected or interrupted, or one that failed, may still send: call wallet_cancel (no request_id) before you tell the user anything about that send; never say nothing was sent without it. A send is one payment to \`to\`. ${HOST_BLOCKED_LINE}`,
152593
+ description: `Use this for "send 2 USDC to <address>" or "withdraw to my wallet" (for "my wallet" leave \`to\` out: it uses the address saved at setup, or says how to set one; do not ask the user for an address first): it sends amount (USDC, like "2"; or amount_atomic) from the PRIVATE balance as plain USDC to \`to\`, a public Solana address. BEFORE you call it to send all of the balance when wallet_balance showed balanceParts above 1, write to the user that the wallet first gets the balance ready to send (never say how the wallet stores the balance; some apps show nothing until this call ends). Privately: the chain shows the pool paying the address, not which wallet paid. This wallet's own public address (ownAddress in wallet_balance: it holds the public USDC, wallet_shield deposits from it) is refused as \`to\`: an exit there would show on chain that the private balance is this wallet's, even if that address never deposited (wallet_add_funds deposits come from one-time addresses, not from it; never tell the user they came from it). Shinjuku pays every network fee; no SOL is needed. The user's saved own addresses (setup or this app's wallet entry) send at once. Any other address needs the user's yes in a dialog of this app; a client that cannot ask is refused (mcp_unshield_to_not_allowed) and a decline sends nothing (mcp_unshield_declined). \`to\` must already be able to receive USDC: an address that cannot is refused before any dialog (mcp_unshield_to_invalid). It runs in steps and may wait for the pool's next anchor. Each call answers within about 20 s (at once when the send ends; a dialog may take longer) with ok: true and stage: confirming, queued, refreshing, self-pay = preparing, exit = sending, done; joining = the wallet first gets the balance ready, then sends; each call goes on with it (joinSteps: its steps, in order; doneInMinutesLow to doneInMinutesHigh: the time to say). Once it sends (self-pay, exit), read its result with wallet_receipts kind moves (no new send; it can finish the send); before that, call wallet_unshield again with the SAME request_id, amount and to. When the balance must first be made ready, the FIRST call answers at once with stage joining and joinTellFirst: true; write its say to the user, then call again with the same request_id at once. One exception: when this app sends a progress token with that next call, the call gets the balance ready and then sends, with a progress line every ${JOIN_STEP_MS / 1e3} s ("getting your balance ready to send"; some apps show none, so the line is said before the call, as above). It answers when the send is done, or after about ${joinAnswerSeconds(JOIN_CALL_MAX_MS)} s with how far it got (joinsDone; sendState sending: the USDC is leaving, never say nothing moved, read it with wallet_receipts); else call again with the same request_id. Without a progress token it answers within about 20 s with stage joining: call again until it sends. The same request_id never sends twice, also after a restart. request_id is optional: without it the answer names the id it made, and the same call again within 10 minutes after it ends reads that same send. An optional unshield limit the user sets may bound each call and what this wallet sends in any 24 hours, from every app (mcp_unshield_cap_exceeded: tell the user). Other refusals: mcp_argument_invalid, mcp_request_id_reused, wallet_locked, mcp_tool_disabled, mcp_unshield_failed, and the unshield's own p03_* codes. A call the app stopped, rejected or interrupted, or one that failed, may still send: call wallet_cancel (no request_id) before you tell the user anything about that send; never say nothing was sent without it. A send is one payment to \`to\`. ${HOST_BLOCKED_LINE}`,
152441
152594
  inputSchema: {
152442
152595
  type: "object",
152443
152596
  properties: {
@@ -152906,7 +153059,7 @@ ${canonical5}`;
152906
153059
  const payMe = {
152907
153060
  name: "wallet_pay_me",
152908
153061
  title: "A one-time address and link to get paid",
152909
- description: "wallet_add_funds does the same (after USDC arrives, one balance ask lets the wallet see it and make it private by itself); this older name stays for agents that use it. Use this when someone wants to pay the user (an invoice, a refund, a friend, another agent). Answers a FRESH one-time Solana address of this wallet, a solana: pay link with the USDC mint (and the amount, if given), one human line to paste, and how to check. The payer sends USDC to it with any wallet; then wallet_pay_me_status reads the address and shields what arrived into the shielded balance, so the user ends with one number (wallet_balance). The address never expires and takes ONE payment: never share a used link. amount_atomic is optional (a hint in the link, from 0.01 USDC; whatever arrives is shielded, one round of at most that limit at a time; the rest goes in as the next round). The same request_id never makes a second address: it answers the same link again (with the same amount_atomic). Needs no key from the payer and moves no money by itself. Privacy: the chain shows the payer paying this new address and the address depositing into the pool; it does not show the wallet's balance, its other addresses, or its later payments. Refusals: payme_id_invalid, payme_amount_invalid, payme_note_invalid, payme_key_probe_exhausted, mcp_request_id_reused, mcp_tool_disabled, wallet_locked, mcp_pay_me_failed.",
153062
+ description: "wallet_add_funds does the same (after USDC arrives, one balance ask lets the wallet see it and make it private by itself); this older name stays for agents that use it. Use this when someone wants to pay the user (an invoice, a refund, a friend, another agent). Answers a FRESH one-time Solana address of this wallet, a solana: pay link with the USDC mint (and the amount, if given), one human line to paste, and how to check. The payer sends USDC to it with any wallet; then wallet_pay_me_status reads the address and shields what arrived into the shielded balance, so the user ends with one number (wallet_balance). The address never expires and takes ONE payment: never share a used link. amount_atomic is optional (a hint in the link, from 0.01 USDC; whatever arrives is shielded, one round of at most that limit at a time; the rest goes in as the next round). The same request_id never makes a second address: it answers the same link again (with the same amount_atomic). Needs no key from the payer; it pays no one and sends nothing out. Privacy: the chain shows the payer paying this new address and the address depositing into the pool; it does not show the wallet's balance, its other addresses, or its later payments. Refusals: payme_id_invalid, payme_amount_invalid, payme_note_invalid, payme_key_probe_exhausted, mcp_request_id_reused, mcp_tool_disabled, wallet_locked, mcp_pay_me_failed.",
152910
153063
  inputSchema: {
152911
153064
  type: "object",
152912
153065
  properties: {
@@ -153999,7 +154152,7 @@ ${canonical5}`;
153999
154152
  { requestId, paid: false, ...over ? { totalAtomic: total, capAtomic: launch } : {}, ...facts }
154000
154153
  );
154001
154154
  }
154002
- if (errorCode4(error, "") === "p03_merchant_respend_no_spendable_account") await primePlanHeld();
154155
+ if (nothingToSpend(error)) await primePlanHeld();
154003
154156
  return withRefundNotices(inferenceRefusal(error, { requestId, ...facts }) ?? payFailure(error, requestId, "inference_chat"));
154004
154157
  }
154005
154158
  }
@@ -154304,6 +154457,15 @@ ${canonical5}`;
154304
154457
  next: `call ${tool.name} again in about 10 s for the read that goes on; if the seller still has not answered, try another seller (find_paid_services). ` + outsideWalletRule("this URL")
154305
154458
  });
154306
154459
  }
154460
+ if (tool.name === "wallet_receipts") {
154461
+ return json4({
154462
+ say: "Still reading. Ask again in a few seconds; nothing new was paid or sent.",
154463
+ ok: true,
154464
+ stillReading: true,
154465
+ detail: `wallet_receipts did not finish its read in ${Math.round(readBudgetMs / 1e3)} s (a slow chain read, another wallet command, or an earlier send the wallet finishes now); no new payment or send started; the result of an earlier send is not known yet`,
154466
+ next
154467
+ });
154468
+ }
154307
154469
  if (tool.name !== "wallet_balance") {
154308
154470
  return json4({
154309
154471
  say: "Still reading. Ask again in a few seconds; nothing was paid or moved.",
@@ -154415,13 +154577,20 @@ ${JSON.stringify(args ?? {})}`;
154415
154577
  };
154416
154578
  } },
154417
154579
  check_price: { uri: "ui://shinjuku/price-card", build: (answer, args) => {
154418
- if (answer.paymentRequired !== true) return void 0;
154419
154580
  let host = "";
154420
154581
  try {
154421
154582
  host = new URL(String(args.url)).host;
154422
154583
  } catch {
154423
154584
  host = "";
154424
154585
  }
154586
+ if (answer.paymentRequired !== true) {
154587
+ return {
154588
+ kind: "price-card",
154589
+ host,
154590
+ payable: false,
154591
+ reason: typeof answer.say === "string" && answer.say ? answer.say : answer.ok === false ? "Nothing was paid: the price check did not work. Ask me again." : "This URL asks for no payment."
154592
+ };
154593
+ }
154425
154594
  const totalAtomic = answer.totalAtomic ?? answer.priceAtomic;
154426
154595
  const limitShown = answer.caps?.maxPaymentAtomic;
154427
154596
  const token = answer.payable === true && answer.balanceShort !== true && ATOMIC_TEXT.test(String(totalAtomic ?? "")) ? issueCardToken({
@@ -155376,7 +155545,7 @@ function createSetupTools({
155376
155545
  doneTool: sayOnRefusal(doneTool)
155377
155546
  };
155378
155547
  }
155379
- var import_web3133, X402_V1_NEXT, shownCaps, SHINJUKU_WORD7, RELEASE_RETRY_MS, STAGE_WORDS2, 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, UPDATE_CHECK_WAIT_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, SPEND_TOOLS, USER_ACTION_TOOLS, JOIN_STEP_MS, sleep2, PROGRESS_EVERY_MS2, READ_BUDGET_MS, UNPAID_TOR_TRY_MS, UNPAID_TOR_OPEN_MS, UNPAID_CLEAR_MS, READ_BUDGET_TOOLS, FLOAT_BUSY_CODES, RETRY_MARGIN_MS, ASK_PAY_CODES, runningNpmVersion2, terminalCommand2, capPlaceWords, noLimitSetLine, CAP_NAMES, capName, entryPlaces, capRaiseText, runningLimits, payCapFlag, noPriceFits, cheaperText, limitNext, overLimitStep, logCause, SAFE_TEXT, causesLog, ADD_FUNDS_DONE_SHOWN_MS, addFundsShownName, 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, TERMINAL_PLAN_PREFIX, APP_LINK_PREFIX, cliPlanSplit, blockedByOf, AGENT_ID_SCHEMA, agentIdName, minutesText2, ageWords2, agoWords, 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, OWN_READS_REUSE_MS, FLOAT_CORRECT_WAIT_MS, SWITCH_WAIT_MS, UNSHIELD_TO_NO_USDC_DETAIL, UNSHIELD_TO_INVALID_NEXT, ELICIT_TIMEOUT_MS, ALLOW_BOX_HOSTS, ALLOW_BOX_PROGRESS_MS, ELICIT_UNSHOWN_MS, elicitUnshown, ANSWER_ARRIVED_AT, monotonicNow, answerTimeOf, elicitTooFast, 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;
155548
+ var import_web3133, X402_V1_NEXT, shownCaps, SHINJUKU_WORD7, SEND_RESULT_READ, SEND_KEPT_ON_DISK, RELEASE_RETRY_MS, STAGE_WORDS2, 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_SELLER_READ_MS, PREVIEW_BODY_OPEN_MS, CALL_BUDGET_MS, budgetLeft, PAY_ANSWER_MARGIN_MS, MONEY_FIRST_ANSWER_MS, UPDATE_CHECK_WAIT_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, SPEND_TOOLS, USER_ACTION_TOOLS, JOIN_STEP_MS, sleep2, PROGRESS_EVERY_MS2, READ_BUDGET_MS, UNPAID_TOR_TRY_MS, UNPAID_TOR_OPEN_MS, UNPAID_CLEAR_MS, READ_BUDGET_TOOLS, FLOAT_BUSY_CODES, RETRY_MARGIN_MS, ASK_PAY_CODES, runningNpmVersion2, terminalCommand2, capPlaceWords, noLimitSetLine, CAP_NAMES, capName, entryPlaces, capRaiseText, runningLimits, payCapFlag, noPriceFits, cheaperText, limitNext, overLimitStep, logCause, SAFE_TEXT, causesLog, ADD_FUNDS_DONE_SHOWN_MS, addFundsShownName, 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, TERMINAL_PLAN_PREFIX, APP_LINK_PREFIX, cliPlanSplit, blockedByOf, AGENT_ID_SCHEMA, agentIdName, minutesText2, ageWords2, agoWords, 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, RECEIPTS_SEND_WAIT_MS, PRIVATE_ID_NOT_READ, LINK_READ_ANSWER_MS, OWN_READS_AHEAD_MS, OWN_PUBLIC_KNOWN_MS, OWN_READS_REUSE_MS, FLOAT_CORRECT_WAIT_MS, SWITCH_WAIT_MS, UNSHIELD_TO_NO_USDC_DETAIL, UNSHIELD_TO_INVALID_NEXT, ELICIT_TIMEOUT_MS, ALLOW_BOX_HOSTS, ALLOW_BOX_PROGRESS_MS, ELICIT_UNSHOWN_MS, elicitUnshown, ANSWER_ARRIVED_AT, monotonicNow, answerTimeOf, elicitTooFast, 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;
155380
155549
  var init_tools = __esm({
155381
155550
  "wallet/src/mcp/tools.mjs"() {
155382
155551
  "use strict";
@@ -155474,6 +155643,8 @@ var init_tools = __esm({
155474
155643
  X402_V1_NEXT = "nothing was paid. Tell the user: this seller uses the older x402 version 1 format with no Solana USDC payment the wallet makes; nothing was paid; pick another seller. Do not retry this URL; find_paid_services marks the sellers it cannot pay (canPay false)";
155475
155644
  shownCaps = (caps) => Object.fromEntries(Object.entries(caps).map(([name, value2]) => [name, String(value2) === NO_LIMIT_ATOMIC ? "none" : value2]));
155476
155645
  SHINJUKU_WORD7 = typedCommandName("shinjuku");
155646
+ SEND_RESULT_READ = (requestId) => `For its result, call wallet_receipts with kind "moves": it starts no payment or new send, and it can finish this send, which the wallet finishes by itself. Its unshield row with requestId "${requestId}" shows state "sent" and the transaction once the send ends; if it still shows "sending", tell the user the send is still on its way and to ask again in a few minutes (not in a loop). Do not call wallet_unshield again to read it: it never sends twice, but the app may ask the user to approve a send again`;
155647
+ SEND_KEPT_ON_DISK = "It is kept on disk: if this process ends first, the wallet finishes it by itself when it runs again (a wallet_receipts or wallet_balance call can start it; it may take a few minutes) and never moves the money twice";
155477
155648
  RELEASE_RETRY_MS = 3e3;
155478
155649
  STAGE_WORDS2 = Object.freeze({
155479
155650
  queued: "waiting to start",
@@ -155519,8 +155690,8 @@ var init_tools = __esm({
155519
155690
  PRIVATE_HOST3 = /^(localhost|127\.0\.0\.1|\[::1\]|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+)$/;
155520
155691
  FORBIDDEN_HEADERS3 = ["host", "content-length", "connection", "transfer-encoding", "upgrade", "trailer", "te", "expect", "x-payment"];
155521
155692
  MAX_BODY_BYTES2 = 16 * 1024 * 1024;
155522
- PREVIEW_TIMEOUT_MS = 3e4;
155523
155693
  PREVIEW_SELLER_READ_MS = 8e3;
155694
+ PREVIEW_BODY_OPEN_MS = 5e3;
155524
155695
  CALL_BUDGET_MS = 45e3;
155525
155696
  budgetLeft = (startedAt) => Math.max(0, startedAt + CALL_BUDGET_MS - Date.now());
155526
155697
  PAY_ANSWER_MARGIN_MS = 5e3;
@@ -155978,6 +156149,7 @@ var init_tools = __esm({
155978
156149
  FINALITY_SETTLE_WINDOW_SLOTS = 150;
155979
156150
  PUBLIC_READ_ANSWER_MS = 3e3;
155980
156151
  RECEIPTS_ID_LOOKUP_MS = 12e3;
156152
+ RECEIPTS_SEND_WAIT_MS = 15e3;
155981
156153
  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";
155982
156154
  LINK_READ_ANSWER_MS = 15e3;
155983
156155
  OWN_READS_AHEAD_MS = 3e4;
@@ -157988,7 +158160,7 @@ var init_stdioServer = __esm({
157988
158160
  SUPPORTED_PROTOCOL_VERSIONS = Object.freeze(["2025-06-18", "2025-03-26", "2024-11-05"]);
157989
158161
  MAX_LINE_BYTES = 4 * 1024 * 1024;
157990
158162
  POSITIVE_ATOMIC7 = /^[1-9][0-9]{0,30}$/;
157991
- INSTRUCTIONS_BASE = `A self-custody Shinjuku Shield wallet on this machine; no tool takes or returns its keys or passphrase. Each answer's say is one plain sentence for the user; other fields are data. Never tell the user a tool, field, code or protocol name (x402, MCP) unless told to. Map a plain request to one tool: "what is my balance" -> wallet_balance (safe any time); "add money" / "deposit" / "move USDC in from Phantom or an exchange" -> wallet_add_funds (a one-time address; the next wallet_balance after the USDC arrives makes it private); "shield the USDC on this wallet's own address" -> wallet_shield; "stop" / "cancel" -> wallet_cancel (the request_id of what to stop); "pay this URL" -> pay_for_service (no preview needed); "what does this URL cost" -> check_price (only when asked); "find a paid API for X" -> find_paid_services, then pay its url; "send 2 USDC to <address>" -> wallet_unshield; "show my payments" -> wallet_receipts; "sell, swap, or send a token other than USDC" -> no tool: this wallet does not do that, so say so and offer no sale; "which AI models" -> inference_models; "ask an AI model" -> inference_chat; "give my other AI app a private AI" -> inference_server. wallet_balance answers ONE balance (balanceAtomic); pay_for_service pays any paid URL from it. Fields ending in Atomic count 1000000 per USDC; tell the user USDC. The wallet does its own upkeep. A shield, add-funds or unshield call can run for minutes: call again with the SAME request_id as next says. Pass your own request_id to pay_for_service: the same one never pays or moves money twice (a code ending in _retry_same_request: call again with it). pay_for_service never pays above the spending limits (one payment; 24 hours); with none, only the balance bounds it. Never claim a payment happened unless the answer has a transaction. After a pay or send call that stopped, failed, or this app calls rejected or interrupted, call wallet_receipts (a payment) or wallet_cancel (a send; no request_id) before you say whether it happened; never say nothing moved without that. Privacy: the chain does not show which wallet paid, but this app and its model provider see every URL, body, price and answer you handle; reach a seller or its domain only through these tools, never yourself (no curl, browser, DNS or DNS-over-HTTPS lookup), also when the user asks for no Tor: that shows their IP address to the site or a DNS company. When a poolSwitch.items[] item has tellUser true, tell the user its message once, in plain words; the wallet moves the balance itself.`;
158163
+ INSTRUCTIONS_BASE = `A self-custody Shinjuku Shield wallet on this machine; no tool takes or returns its keys or passphrase. Each answer's say is one plain sentence for the user; other fields are data. Never tell the user a tool, field, code or protocol name (x402, MCP) unless told to. Map a plain request to one tool: "what is my balance" -> wallet_balance (starts no payment or new send; it finishes what is under way: added USDC into the user's private balance, a stopped earlier send to its address); "add money" / "deposit" / "move USDC in from Phantom or an exchange" -> wallet_add_funds (only gives a one-time address: nothing moves until the user sends USDC there; the next wallet_balance then moves it into their private balance); "shield the USDC on this wallet's own address" -> wallet_shield; "stop" / "cancel" -> wallet_cancel (the request_id of what to stop); "pay this URL" -> pay_for_service (no preview needed); "what does this URL cost" -> check_price (only when asked); "find a paid API for X" -> find_paid_services, then pay its url; "send 2 USDC to <address>" -> wallet_unshield; "show my payments" -> wallet_receipts; "sell, swap, or send a token other than USDC" -> no tool: this wallet does not do that, so say so and offer no sale; "which AI models" -> inference_models; "ask an AI model" -> inference_chat; "give my other AI app a private AI" -> inference_server. wallet_balance answers ONE balance (balanceAtomic); pay_for_service pays any paid URL from it. Fields ending in Atomic count 1000000 per USDC; tell the user USDC. The wallet does its own upkeep. A shield, add-funds or unshield call can run for minutes: call again with the SAME request_id as next says. Pass your own request_id to pay_for_service: the same one never pays or moves money twice (a code ending in _retry_same_request: call again with it). pay_for_service never pays above the spending limits (one payment; 24 hours); with none, only the balance bounds it. Never claim a payment happened unless the answer has a transaction. After a pay or send call that stopped, failed, or this app calls rejected or interrupted, call wallet_receipts (a payment) or wallet_cancel (a send; no request_id) before you say whether it happened; never say nothing moved without that. Privacy: the chain does not show which wallet paid, but this app and its model provider see every URL, body, price and answer you handle; reach a seller or its domain only through these tools, never yourself (no curl, browser, DNS or DNS-over-HTTPS lookup), also when the user asks for no Tor: that shows their IP address to the site or a DNS company. When a poolSwitch.items[] item has tellUser true, tell the user its message once, in plain words; the wallet moves the balance itself.`;
157992
158164
  OWN_ADDRESS_LINE = '"Send to my (main) wallet": wallet_unshield with no to uses the address saved at setup; never ask for it.';
157993
158165
  INSTRUCTIONS = `${INSTRUCTIONS_BASE} ${OWN_ADDRESS_LINE} ${HOST_BLOCKED_LINE}`;
157994
158166
  MCP_LOG_LEVELS = Object.freeze(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
@@ -161419,13 +161591,13 @@ function holdProgressLines(stream = process.stderr) {
161419
161591
  if (held2.length) original.call(stream, held2.join(""));
161420
161592
  };
161421
161593
  }
161422
- function errorCodeOf2(error) {
161594
+ function errorCodeOf3(error) {
161423
161595
  if (error?.name === "InferenceError" && typeof error.code === "string") return error.code;
161424
161596
  if (error?.name === "SpendRefusalError" && typeof error.error === "string") return error.error;
161425
161597
  return localErrorCodes(error)[0];
161426
161598
  }
161427
161599
  function ownCodeWords(error) {
161428
- const own = errorCodeOf2(error);
161600
+ const own = errorCodeOf3(error);
161429
161601
  const code2 = own && !/^E[A-Z0-9_]+$/.test(own) ? own : "wallet_command_failed";
161430
161602
  return error?.name === "InferenceError" && SELF_TEACHING_CODES.test(code2) && error.detail ? `${code2}: ${error.detail}` : code2;
161431
161603
  }
@@ -162387,7 +162559,7 @@ The next question uses it${state2.mode === "talk" ? ", with the conversation so
162387
162559
  }
162388
162560
  };
162389
162561
  const failed = async (error, turn) => {
162390
- const code2 = errorCodeOf2(error);
162562
+ const code2 = errorCodeOf3(error);
162391
162563
  const surelyNothing = nothingPaid(error);
162392
162564
  const paidLeft = [error, error?.cause].map((one) => one?.paidLeft).find((one) => one && typeof one === "object" && typeof one.left === "boolean");
162393
162565
  const leftAtomic = paidLeft?.left === true && /^[1-9][0-9]{0,30}$/.test(String(paidLeft.atomic ?? "")) ? BigInt(paidLeft.atomic) : void 0;
@@ -172770,12 +172942,18 @@ function localAiServerHooks(session, deps, values) {
172770
172942
  failure3.joinState = join59.state;
172771
172943
  if (join59.readyInSeconds !== void 0) failure3.joinReadyInSeconds = join59.readyInSeconds;
172772
172944
  }
172773
- if (localErrorCodes(error).includes("p03_merchant_respend_no_spendable_account")) {
172945
+ const codes = localErrorCodes(error);
172946
+ const noAccount = codes.includes("p03_merchant_respend_no_spendable_account");
172947
+ if (noAccount || codes.includes("p03_merchant_respend_insufficient_recovered_value") && !codes.includes(SPLIT_CODE2)) {
172948
+ let zero = false;
172774
172949
  try {
172775
172950
  const store = session.openStore();
172776
- if (proofWalkHolds(store)?.none === true && zeroOf(knownShortBalance(store))) failure3.knownZero = true;
172951
+ zero = proofWalkHolds(store)?.none === true && zeroOf(knownShortBalance(store));
172777
172952
  } catch {
172953
+ zero = false;
172778
172954
  }
172955
+ if (zero && !noAccount) throw Object.assign(new Error("p03_merchant_respend_no_spendable_account"), { knownZero: true });
172956
+ if (zero) failure3.knownZero = true;
172779
172957
  }
172780
172958
  const kind = REQUEST_ID_TAKEN2.exec(localErrorCodes(error).join(" "))?.[1];
172781
172959
  if (kind !== void 0 && typeof options?.requestId === "string") {
@@ -174248,7 +174426,7 @@ function fundingStepText() {
174248
174426
  return [
174249
174427
  "Add money: the wallet starts empty. Run this (any amount from 0.01 USDC):",
174250
174428
  ` ${FUND_COMMAND}`,
174251
- ' It gives a one-time address for USDC on Solana: send that amount from an exchange or a phone wallet. Or ask your agent: "Add 0.50 USDC to my private balance".',
174429
+ ' It gives a one-time address for USDC on Solana: send that amount from an exchange or a phone wallet. Or ask your agent: "Give me an address to add 0.50 USDC to my wallet".',
174252
174430
  ""
174253
174431
  ].join("\n");
174254
174432
  }
@@ -174366,7 +174544,7 @@ async function recordOwnAddress(home, address4, deps) {
174366
174544
  }
174367
174545
  var addsAppOnly = (values, targets) => targets.length > 0 && values.get(SETUP_RERUN) === "settings";
174368
174546
  var ADD_ONLY_FLAGS = /* @__PURE__ */ new Set(["--add-to", "--force", "--no-tor", "--yes", "--verbose"]);
174369
- var addAppOnlyText = (targets, added) => targets.every((target) => added.has(target)) ? '\nYour wallet was set up before, so setup only added the app. To add money, ask the app (for example "add 0.50 USDC to my private balance"); it asks about a backup first when none is saved.\n' : "\nYour wallet was set up before, so setup changed nothing else.\n";
174547
+ var addAppOnlyText = (targets, added) => targets.every((target) => added.has(target)) ? '\nYour wallet was set up before, so setup only added the app. To add money, ask the app (for example "give me an address to add 0.50 USDC to my wallet"); it asks about a backup first when none is saved.\n' : "\nYour wallet was set up before, so setup changed nothing else.\n";
174370
174548
  async function offerFundNow(deps, { tor, created }) {
174371
174549
  const io = deps.io;
174372
174550
  try {