shinjuku-shield 0.3.184 → 0.3.186

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
@@ -6,13 +6,13 @@ answers privately, in a terminal chat or for your agent app. Its `mcp`
6
6
  command runs a local MCP server (stdio) for your agent. Your keys never
7
7
  leave your machine.
8
8
 
9
- This is version 0.3.184. The npm packages `shinjuku-shield` and
9
+ This is version 0.3.186. The npm packages `shinjuku-shield` and
10
10
  `shinjuku-shielded` hold the same files. The command is `shinjuku`.
11
11
 
12
12
  ## Set up
13
13
 
14
14
  ```sh
15
- npx -y shinjuku@0.3.184 setup
15
+ npx -y shinjuku@0.3.186 setup
16
16
  ```
17
17
 
18
18
  Setup offers to install the `shinjuku` command and, on Windows, adds npm's
@@ -35,13 +35,13 @@ Every wallet command works after `shinjuku`, for example `shinjuku balance`,
35
35
  Claude Code:
36
36
 
37
37
  ```sh
38
- claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.184 mcp
38
+ claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.186 mcp
39
39
  ```
40
40
 
41
41
  Claude Desktop (`claude_desktop_config.json`) or Cursor (`~/.cursor/mcp.json`):
42
42
 
43
43
  ```json
44
- { "mcpServers": { "shinjuku": { "command": "npx", "args": ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.184", "mcp"] } } }
44
+ { "mcpServers": { "shinjuku": { "command": "npx", "args": ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.186", "mcp"] } } }
45
45
  ```
46
46
 
47
47
  On native Windows, if the host cannot find `npx`, use `"command": "cmd"` and
@@ -54,7 +54,7 @@ Codex (the Codex app and Codex CLI read the same file, `~/.codex/config.toml`):
54
54
  ```toml
55
55
  [mcp_servers.shinjuku]
56
56
  command = "npx"
57
- args = ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.184", "mcp"]
57
+ args = ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.186", "mcp"]
58
58
  startup_timeout_sec = 120
59
59
  tool_timeout_sec = 300
60
60
  ```
package/manifest.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schema": "carbon-shielded-wallet/bundle-manifest/v1",
3
3
  "file": "shinjuku-wallet.mjs",
4
- "sha256": "fed76293d7f682c50f249284a7f4bbf14d2d6c7d8926c052c6ef1f683419b8dd",
5
- "bytes": 9349716,
6
- "sourceCommit": "37820c4cf40bdbd57dece9d1b739e1c541f534ed",
4
+ "sha256": "80d2ed100a8e4a1f0c3926c4572c20f71ed5c333ff510dd0e291065480fe2d98",
5
+ "bytes": 9360488,
6
+ "sourceCommit": "cb04124afb5e7deb6c6e7132dcb0175a1bc0eb2c",
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",
@@ -1038,5 +1038,5 @@
1038
1038
  "version": "1.8.0"
1039
1039
  }
1040
1040
  ],
1041
- "publishedAt": "2026-11-06T16:14:51.926Z"
1041
+ "publishedAt": "2026-11-06T17:55:56.110Z"
1042
1042
  }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "shinjuku-shield",
3
- "version": "0.3.184",
3
+ "version": "0.3.186",
4
4
  "mcpName": "io.github.ShinjukuStaition/shinjuku-mcp",
5
5
  "description": "Shinjuku Shielded, the private x402 facilitator 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": "fed76293",
7
- "shinjukuSha256": "fed76293d7f682c50f249284a7f4bbf14d2d6c7d8926c052c6ef1f683419b8dd",
6
+ "shinjukuRelease": "80d2ed10",
7
+ "shinjukuSha256": "80d2ed100a8e4a1f0c3926c4572c20f71ed5c333ff510dd0e291065480fe2d98",
8
8
  "license": "SEE LICENSE IN LICENSE.txt",
9
9
  "author": "Shinjuku Shielded",
10
10
  "homepage": "https://github.com/ShinjukuStaition/shinjuku-shield#readme",
@@ -588,6 +588,16 @@ function processLockAddress(name, platform = process.platform) {
588
588
  if (platform === "linux") return `\0shinjuku-lock-${hash12}`;
589
589
  return join2(tmpdir2(), `shinjuku-lock-${hash12.slice(0, 32)}.sock`);
590
590
  }
591
+ async function processLockFree(name) {
592
+ const address4 = processLockAddress(name);
593
+ try {
594
+ (await listen(address4)).close();
595
+ return true;
596
+ } catch (error) {
597
+ if (!["EADDRINUSE", "EACCES"].includes(error?.code)) throw error;
598
+ }
599
+ return process.platform === "darwin" ? deadSocketFile(address4) : false;
600
+ }
591
601
  async function takeProcessLock(name, {
592
602
  onWait = () => {
593
603
  },
@@ -48776,6 +48786,15 @@ function torOwnCircuitInit(lane, init = {}) {
48776
48786
  const made = torLaneInit(lane, init);
48777
48787
  return made !== init && made?.dispatcher !== void 0 ? made : void 0;
48778
48788
  }
48789
+ function freshTorCircuitProxy() {
48790
+ if (!inTorRun() || runEnded()) return void 0;
48791
+ try {
48792
+ if (globalThis[GLOBAL_DISPATCHER4]?.constructor?.name !== "EnvHttpProxyAgent") return void 0;
48793
+ return withRunTag(`http://${new URL(process.env[MARK].split(" ")[1]).host}`);
48794
+ } catch {
48795
+ return void 0;
48796
+ }
48797
+ }
48779
48798
  function onCurrentCircuit(init) {
48780
48799
  const lane = laneOfDispatcher.get(init?.dispatcher);
48781
48800
  return lane === void 0 || laneDispatchers.get(lane) === init.dispatcher ? init : torLaneInit(lane, init);
@@ -83641,7 +83660,7 @@ var init_p03LoopLag = __esm({
83641
83660
  });
83642
83661
 
83643
83662
  // src/server/payments/shielded/p03IndexedReplay.ts
83644
- var import_web3110, ERROR_KINDS, P03_E1_MOVE_INPUTS, MOVE_VALUE_INDICES, MOVE_HEAD_BYTES3, UPGRADEABLE_LOADER, TOKEN_PROGRAM, E1_CHANGELOG_BYTES2, P03_E1_TREE_READ_BYTES, rpcHttpFetch;
83663
+ var import_web3110, P03_E1_BEHIND_RETRY_MS, P03_E1_BEHIND_RETRIES, P03_E1_BEHIND_POLL_MS, P03_E1_BEHIND_KEEPS, ERROR_KINDS, P03_E1_MOVE_INPUTS, MOVE_VALUE_INDICES, MOVE_HEAD_BYTES3, UPGRADEABLE_LOADER, TOKEN_PROGRAM, E1_CHANGELOG_BYTES2, P03_E1_TREE_READ_BYTES, rpcHttpFetch;
83645
83664
  var init_p03IndexedReplay = __esm({
83646
83665
  "src/server/payments/shielded/p03IndexedReplay.ts"() {
83647
83666
  "use strict";
@@ -83653,6 +83672,10 @@ var init_p03IndexedReplay = __esm({
83653
83672
  init_p03MinContextSlotRetry();
83654
83673
  init_p03LoopLag();
83655
83674
  init_ShieldedSolanaP03Types();
83675
+ P03_E1_BEHIND_RETRY_MS = 1e3;
83676
+ P03_E1_BEHIND_RETRIES = 2;
83677
+ P03_E1_BEHIND_POLL_MS = 200;
83678
+ P03_E1_BEHIND_KEEPS = P03_E1_BEHIND_RETRIES * (1 + Math.floor((P03_E1_BEHIND_RETRY_MS - 1) / P03_E1_BEHIND_POLL_MS));
83656
83679
  ERROR_KINDS = /* @__PURE__ */ new Map([
83657
83680
  [E1_ERROR_CODES2.E1NotInGap, "not-in-gap"],
83658
83681
  [E1_ERROR_CODES2.E1LeafModified, "leaf-modified"],
@@ -104914,7 +104937,7 @@ function floatOutcomeWords(code2, error, t) {
104914
104937
  const why = code2 === "p03_float_paid_finishing_retry_same_request" ? `Shinjuku is still signing the transfer to ${p.the}` : error?.transferLanded === true ? `Shinjuku's transfer to ${p.the} landed (${p.the} has the payment), and ${answer}` : `${answer}. Not known yet whether ${p.the} takes it`;
104915
104938
  return [
104916
104939
  code2,
104917
- `PAID ${totalText(error)} to Shinjuku (${t.privateLeg}); ${why}`,
104940
+ `PAID ${totalText(error)} to Shinjuku (${t.privateLeg}); ${why}${stallResentWords(p, error)}`,
104918
104941
  `${t.again}: it resends the same payment and never pays twice`
104919
104942
  ];
104920
104943
  }
@@ -104984,7 +105007,7 @@ function floatOutcomeWords(code2, error, t) {
104984
105007
  case "p03_float_seller_unanswered_paid_retry_same_request":
104985
105008
  return [
104986
105009
  code2,
104987
- `PAID ${totalText(error)}: the transfer to ${p.the} landed${withTransaction(error)}, but ${p.the} did not answer` + (typeof error?.httpStatus === "number" ? ` (it answered HTTP ${error.httpStatus}${typeof error?.sellerReason === "string" ? `: ${JSON.stringify(error.sellerReason)}` : ""})` : ""),
105010
+ `PAID ${totalText(error)}: the transfer to ${p.the} landed${withTransaction(error)}, but ${p.the} did not answer` + (typeof error?.httpStatus === "number" ? ` (it answered HTTP ${error.httpStatus}${typeof error?.sellerReason === "string" ? `: ${JSON.stringify(error.sellerReason)}` : ""})` : "") + stallResentWords(p, error),
104988
105011
  `${t.again}: it resends the same proof of payment and never pays twice`
104989
105012
  ];
104990
105013
  case "p03_float_seller_kept_payment": {
@@ -105084,6 +105107,12 @@ function floatOutcomeWords(code2, error, t) {
105084
105107
  return void 0;
105085
105108
  }
105086
105109
  }
105110
+ function stallResentWords(p, error) {
105111
+ return error?.stallResent === true ? `; the Tor connection to ${p?.the ?? "the seller"} stalled, so the wallet sent this same payment once more on a new Tor route: it is still one payment, not a second one` : "";
105112
+ }
105113
+ function stallResentLine(payee = "the seller") {
105114
+ return `The Tor connection to ${payee} stalled, so the wallet sent this same payment once more on a new Tor route: it is still one payment, not a second one.`;
105115
+ }
105087
105116
  var ATOMIC4, TRANSFER_DEAD_WORDS, payeeOf, floatSellerCanBeFixed, withoutProviderText, floatSeller4xx, answeredInstead, floatStillSettling, floatChargeTooLate, amountText, withTransaction, PAID_SELLER_FAILED_CODE, stillWants, AI_SERVER_WRONG, QUOTE_REFUSED_WHY;
105088
105117
  var init_floatWords = __esm({
105089
105118
  "wallet/src/pay/floatWords.mjs"() {
@@ -106098,6 +106127,138 @@ function sellerAnswerInit(url, init, ms) {
106098
106127
  if (target() === void 0) return init;
106099
106128
  return { ...init, dispatcher: { dispatch: (options, handler) => target().dispatch({ ...options, headersTimeout: ms, bodyTimeout: ms }, handler) } };
106100
106129
  }
106130
+ async function sendWatchingStall(fetchImpl, url, init, waitMs, { mark = () => {
106131
+ }, onResend = () => {
106132
+ }, resentBefore = false } = {}) {
106133
+ const global2 = globalThis[GLOBAL_DISPATCHER5];
106134
+ const proxy = process.env.HTTPS_PROXY;
106135
+ const watched = !resentBefore && inTorRun() && init.dispatcher === void 0 && routeDispatcherOf(url) === void 0 && global2?.constructor?.name === "EnvHttpProxyAgent" && typeof proxy === "string" && proxy !== "";
106136
+ if (!watched) return { response: await fetchImpl(url, sellerAnswerInit(url, init, waitMs)), stallResent: false };
106137
+ const sameCircuit = () => {
106138
+ try {
106139
+ return proxyDispatcher(global2.constructor, proxy);
106140
+ } catch {
106141
+ return void 0;
106142
+ }
106143
+ };
106144
+ const first = new AbortController();
106145
+ let ended2 = false;
106146
+ let timer;
106147
+ let checkStop;
106148
+ const stalled = new Promise((resolve43) => {
106149
+ let misses = 0;
106150
+ const check = async () => {
106151
+ const startedAtMs = Date.now();
106152
+ mark("seller-stall-check");
106153
+ checkStop = new AbortController();
106154
+ const dispatcher = sameCircuit();
106155
+ let alive2 = false;
106156
+ try {
106157
+ if (dispatcher === void 0) throw new Error("no dispatcher");
106158
+ const answer = await fetchImpl(new URL(url).origin, {
106159
+ method: "HEAD",
106160
+ redirect: "manual",
106161
+ dispatcher,
106162
+ signal: AbortSignal.any([AbortSignal.timeout(SELLER_STALL_CHECK_TIMEOUT_MS), checkStop.signal, ...init.signal ? [init.signal] : []])
106163
+ });
106164
+ alive2 = true;
106165
+ answer.body?.cancel?.().catch?.(() => {
106166
+ });
106167
+ } catch {
106168
+ alive2 = false;
106169
+ }
106170
+ dispatcher?.destroy().catch(() => {
106171
+ });
106172
+ if (ended2) return;
106173
+ misses = alive2 ? 0 : misses + 1;
106174
+ mark("seller-stall-check-done", alive2 ? "answered" : `missed_${misses}`);
106175
+ if (misses >= SELLER_STALL_MISSES) {
106176
+ resolve43(true);
106177
+ return;
106178
+ }
106179
+ timer = setTimeout(check, Math.max(0, startedAtMs + SELLER_STALL_CHECK_EVERY_MS - Date.now()));
106180
+ };
106181
+ timer = setTimeout(check, SELLER_STALL_CHECK_AFTER_MS);
106182
+ });
106183
+ const firstSend = fetchImpl(url, sellerAnswerInit(url, { ...init, signal: AbortSignal.any([...init.signal ? [init.signal] : [], first.signal]) }, waitMs)).then((response) => ({ response }), (error) => ({ error }));
106184
+ let outcome;
106185
+ try {
106186
+ outcome = await Promise.race([firstSend, stalled.then(() => ({ stalled: true }))]);
106187
+ } finally {
106188
+ ended2 = true;
106189
+ clearTimeout(timer);
106190
+ checkStop?.abort();
106191
+ }
106192
+ if (outcome.stalled !== true) {
106193
+ if (outcome.error !== void 0) throw outcome.error;
106194
+ return { response: outcome.response, stallResent: false };
106195
+ }
106196
+ const replacementProxy = freshTorCircuitProxy();
106197
+ let fresh;
106198
+ try {
106199
+ fresh = replacementProxy === void 0 ? void 0 : proxyDispatcher(global2.constructor, replacementProxy);
106200
+ } catch {
106201
+ fresh = void 0;
106202
+ }
106203
+ if (fresh === void 0) {
106204
+ const kept3 = await firstSend;
106205
+ if (kept3.error !== void 0) throw kept3.error;
106206
+ return { response: kept3.response, stallResent: false };
106207
+ }
106208
+ onResend(replacementProxy);
106209
+ mark("seller-stall-resend");
106210
+ const second = new AbortController();
106211
+ const resend = fetchImpl(url, sellerAnswerInit(url, {
106212
+ ...init,
106213
+ dispatcher: fresh,
106214
+ signal: AbortSignal.any([...init.signal ? [init.signal] : [], second.signal])
106215
+ }, waitMs)).then((response) => ({ response, from: "resend" }), (error) => ({ error, from: "resend" }));
106216
+ const whole = (side) => side.then((one) => one.error !== void 0 ? one : wholeAnswer(one.response).then((response) => ({ response, from: one.from }), (error) => ({ error, from: one.from })));
106217
+ const firstWhole = whole(firstSend.then((one) => ({ ...one, from: "first" })));
106218
+ const resendWhole = whole(resend);
106219
+ const ok = (one) => one.response !== void 0 && one.response.status >= 200 && one.response.status <= 299;
106220
+ try {
106221
+ const earlier = await Promise.race([firstWhole, resendWhole]);
106222
+ let winner = earlier;
106223
+ if (!ok(earlier)) {
106224
+ const other = await (earlier.from === "first" ? resendWhole : firstWhole);
106225
+ winner = ok(other) ? other : earlier.response !== void 0 ? earlier : other.response !== void 0 ? other : void 0;
106226
+ if (winner === void 0) {
106227
+ if (init.signal?.aborted) throw init.signal.reason;
106228
+ throw (earlier.from === "resend" ? earlier : other).error;
106229
+ }
106230
+ }
106231
+ (winner.from === "first" ? second : first).abort();
106232
+ mark("seller-stall-answer", winner.from);
106233
+ return { response: winner.response, stallResent: true, replacementProxy };
106234
+ } finally {
106235
+ fresh.close().catch(() => {
106236
+ });
106237
+ }
106238
+ }
106239
+ async function wholeAnswer(response) {
106240
+ const nullBody = [101, 103, 204, 205, 304].includes(response.status);
106241
+ if (!response.body || nullBody) {
106242
+ await response.body?.cancel?.().catch?.(() => {
106243
+ });
106244
+ return new Response(null, { status: response.status, statusText: response.statusText, headers: response.headers });
106245
+ }
106246
+ const reader = response.body.getReader();
106247
+ const chunks = [];
106248
+ let size = 0;
106249
+ while (size <= RESULT_LIMIT_BYTES) {
106250
+ const { done, value: value2 } = await reader.read();
106251
+ if (done) break;
106252
+ size += value2.byteLength;
106253
+ chunks.push(Buffer.from(value2));
106254
+ }
106255
+ if (size > RESULT_LIMIT_BYTES) await reader.cancel().catch(() => {
106256
+ });
106257
+ return new Response(
106258
+ Buffer.concat(chunks).subarray(0, RESULT_LIMIT_BYTES + 1),
106259
+ { status: response.status, statusText: response.statusText, headers: response.headers }
106260
+ );
106261
+ }
106101
106262
  async function sellerRefusalText(response) {
106102
106263
  let text3 = "";
106103
106264
  let reader;
@@ -106153,9 +106314,10 @@ function x402HeaderText(response, name, field4) {
106153
106314
  const value2 = x402Header(response, name)?.[field4];
106154
106315
  return typeof value2 === "string" && value2.trim() !== "" ? value2 : void 0;
106155
106316
  }
106156
- function newConnectionDispatcher() {
106317
+ function newConnectionDispatcher(stallProxy) {
106157
106318
  try {
106158
106319
  const Dispatcher = globalThis[GLOBAL_DISPATCHER5]?.constructor;
106320
+ if (stallProxy !== void 0) return Dispatcher?.name === "EnvHttpProxyAgent" ? proxyDispatcher(Dispatcher, stallProxy) : void 0;
106159
106321
  if (Dispatcher?.name === "Agent") return new Dispatcher();
106160
106322
  const proxy = String(process.env.SHINJUKU_WALLET_PROXIED ?? "").startsWith("tor ") ? process.env.HTTPS_PROXY : void 0;
106161
106323
  return Dispatcher?.name === "EnvHttpProxyAgent" && proxy ? proxyDispatcher(Dispatcher, proxy) : void 0;
@@ -107504,6 +107666,10 @@ async function payViaFloat({
107504
107666
  for (const dispatcher of resendDispatchers) dispatcher.close().catch(() => {
107505
107667
  });
107506
107668
  }
107669
+ function stallResent() {
107670
+ record = { ...record, sellerStallResent: true };
107671
+ store.writeWal(walName2, record);
107672
+ }
107507
107673
  function unanswered2(error) {
107508
107674
  if (wasKept) keptAgain();
107509
107675
  const verdict = watch.verdict();
@@ -107521,6 +107687,7 @@ async function payViaFloat({
107521
107687
  refundPendingAnswer(record);
107522
107688
  }
107523
107689
  if (verdict?.state === "cancelled") byVerdict(verdict, {}, { cause: error });
107690
+ const resentNow = record.sellerStallResent === true ? { stallResent: true } : {};
107524
107691
  if (verdict?.state === "final") {
107525
107692
  fail22("p03_float_seller_unanswered_paid_retry_same_request", {
107526
107693
  cause: error,
@@ -107528,7 +107695,8 @@ async function payViaFloat({
107528
107695
  ...verdict.transaction ? { transaction: verdict.transaction } : {},
107529
107696
  paidAtomic: record.paidAtomic,
107530
107697
  priceAtomic: record.priceAtomic,
107531
- feeAtomic: record.feeAtomic
107698
+ feeAtomic: record.feeAtomic,
107699
+ ...resentNow
107532
107700
  });
107533
107701
  }
107534
107702
  fail22("p03_float_seller_unanswered_retry_same_request", {
@@ -107537,7 +107705,8 @@ async function payViaFloat({
107537
107705
  paidAtomic: record.paidAtomic,
107538
107706
  priceAtomic: record.priceAtomic,
107539
107707
  feeAtomic: record.feeAtomic,
107540
- ...verdict?.state === "landed" ? { transferLanded: true } : {}
107708
+ ...verdict?.state === "landed" ? { transferLanded: true } : {},
107709
+ ...resentNow
107541
107710
  });
107542
107711
  }
107543
107712
  async function finalAfterLanded() {
@@ -107564,6 +107733,7 @@ async function payViaFloat({
107564
107733
  let resendUntilMs;
107565
107734
  let answeredAtMs;
107566
107735
  let dispatcher;
107736
+ let stallProxy;
107567
107737
  const waitMs = sellerWaitMs(record);
107568
107738
  const sellerTimeout = AbortSignal.timeout(waitMs);
107569
107739
  const stopResends = () => Date.now() > resendUntilMs || ["landed", "dead", "final", "cancelled"].includes(watch.verdict()?.state);
@@ -107577,7 +107747,16 @@ async function payViaFloat({
107577
107747
  };
107578
107748
  const socketWatch = resend === 0 ? watchRequestSocket(record.url) : void 0;
107579
107749
  try {
107580
- response = await fetchImpl(record.url, sellerAnswerInit(record.url, dispatcher === void 0 ? keepAliveInit(init) : { ...init, dispatcher }, waitMs));
107750
+ ({ response } = await sendWatchingStall(
107751
+ fetchImpl,
107752
+ record.url,
107753
+ dispatcher === void 0 ? keepAliveInit(init) : { ...init, dispatcher },
107754
+ waitMs,
107755
+ { mark, resentBefore: record.sellerStallResent === true, onResend: (proxy) => {
107756
+ stallProxy ??= proxy;
107757
+ stallResent();
107758
+ } }
107759
+ ));
107581
107760
  } catch (error) {
107582
107761
  unanswered2(error);
107583
107762
  } finally {
@@ -107590,7 +107769,7 @@ async function payViaFloat({
107590
107769
  mark(resend === 0 ? "seller-answered" : `seller-answered-resend-${resend}`);
107591
107770
  resendUntilMs ??= Date.now() + FEE_PAYER_RESEND_MS;
107592
107771
  if (wasKept || resend >= FEE_PAYER_RESENDS || stopResends() || !(feePayerRotated(response, accepted) || feePayerNotManaged(response))) break;
107593
- dispatcher = newConnectionDispatcher();
107772
+ dispatcher = newConnectionDispatcher(stallProxy);
107594
107773
  if (dispatcher === void 0) break;
107595
107774
  resendDispatchers.push(dispatcher);
107596
107775
  await drainBody(response);
@@ -107863,6 +108042,8 @@ async function selfBroadcastLeg({ store, walName: walName2, record, sendRequest,
107863
108042
  fail22("p03_float_seller_kept_payment", landed);
107864
108043
  }
107865
108044
  let unanswered2 = 0;
108045
+ let stallProxy;
108046
+ let stallDeadline;
107866
108047
  const resendUnanswered = async () => {
107867
108048
  const wait2 = SELF_BROADCAST_UNANSWERED_RESEND_MS[unanswered2];
107868
108049
  if (wait2 === void 0 || Date.now() + wait2 >= record.selfBroadcast.expiresAtMs) return false;
@@ -107878,22 +108059,38 @@ async function selfBroadcastLeg({ store, walName: walName2, record, sendRequest,
107878
108059
  }
107879
108060
  mark("seller-sent");
107880
108061
  let response;
108062
+ const onStallTag = stallProxy === void 0 ? void 0 : newConnectionDispatcher(stallProxy);
108063
+ const sendDeadline = stallDeadline ?? AbortSignal.timeout(sellerWaitMs(record));
107881
108064
  try {
107882
- response = await fetchImpl(record.url, sellerAnswerInit(record.url, keepAliveInit({
108065
+ ({ response } = await sendWatchingStall(fetchImpl, record.url, keepAliveInit({
107883
108066
  method: sendRequest.method,
107884
108067
  headers: { ...Object.fromEntries(sendRequest.headers), "PAYMENT-SIGNATURE": header },
107885
108068
  ...sendRequest.method === "POST" ? { body: Buffer.from(sendRequest.bodyBase64, "base64") } : {},
107886
108069
  redirect: "error",
107887
- signal: AbortSignal.timeout(sellerWaitMs(record))
107888
- }), sellerWaitMs(record)));
108070
+ signal: sendDeadline,
108071
+ ...onStallTag !== void 0 ? { dispatcher: onStallTag } : {}
108072
+ }), sellerWaitMs(record), { mark, resentBefore: record.sellerStallResent === true, onResend: (proxy) => {
108073
+ stallProxy ??= proxy;
108074
+ stallDeadline ??= sendDeadline;
108075
+ record = { ...record, sellerStallResent: true };
108076
+ store.writeWal(walName2, record);
108077
+ } }));
107889
108078
  } catch (error) {
108079
+ onStallTag?.close().catch(() => {
108080
+ });
107890
108081
  const timedOut = error?.name === "TimeoutError" || error?.cause?.name === "TimeoutError";
107891
108082
  if (!timedOut && !proxyRefusedConnection(error) && await resendUnanswered()) {
107892
108083
  attempt -= 1;
107893
108084
  continue;
107894
108085
  }
107895
- fail22("p03_float_seller_unanswered_paid_retry_same_request", { cause: error, ...landed });
108086
+ fail22("p03_float_seller_unanswered_paid_retry_same_request", {
108087
+ cause: error,
108088
+ ...landed,
108089
+ ...record.sellerStallResent === true ? { stallResent: true } : {}
108090
+ });
107896
108091
  }
108092
+ onStallTag?.close().catch(() => {
108093
+ });
107897
108094
  mark("seller-answered");
107898
108095
  if (response.ok && response.status !== 202) {
107899
108096
  let settled;
@@ -108005,6 +108202,9 @@ function paidResult(record, replayed) {
108005
108202
  replayed,
108006
108203
  scheme: "exact",
108007
108204
  status: record.status ?? 200,
108205
+ // AB32: the paid request went once more on a new Tor circuit after a stall (sendWatchingStall); every paid line says
108206
+ // it is still one payment (Codex round 1 on aa3927fc item 3).
108207
+ ...!replayed && record.sellerStallResent === true ? { stallResent: true } : {},
108008
108208
  // A record written before headers were kept has none.
108009
108209
  sellerHeaders: Array.isArray(record.sellerHeaders) ? record.sellerHeaders : [],
108010
108210
  receipt: { ...record.receipt, float: { floatId: record.floatId, settleTransaction: record.floatSettleTransaction ?? null } },
@@ -108016,7 +108216,7 @@ function paidResult(record, replayed) {
108016
108216
  float: { floatId: record.floatId }
108017
108217
  };
108018
108218
  }
108019
- var import_web3115, FLOAT_PAYMENT_SCHEMA2, REGENERATE_CODES, FLOAT_PAYMENT_WAL_PREFIX2, FLOAT_CONFIG_SCHEMA, FLOAT_PAY_PATH, FLOAT_MEMO_PATH, FLOAT_STATUS_PATH, MAX_BODY_BYTES, FLOAT_REFUND_ETA_SECONDS, REFUND_READ_EARLY_MS, REFUND_ETA_MAX_SECONDS, refundDueOf, REFUND_SETTLED_AFTER_MS, REFUND_OUTCOME_NEWS_MS, FINISHING_POLL_MS, FINISHING_LIMIT_MS, SELLER_TIMEOUT_MS, SELLER_TIMEOUT_ABSURD_SECONDS, FLOAT_STATUS_START_MS, FLOAT_STATUS_POLL_MS, FLOAT_STATUS_TIMEOUT_MS, FLOAT_TRANSFER_DEAD, FLOAT_PAYMENT_REVERTED, VERDICT_POLL_MS, SELLER_ANSWER_VERDICT_MS, TRANSFER_MIN_BLOCKS_LEFT, TRANSFER_FRESH_MS, BLOCK_HEIGHT_TIMEOUT_MS, CONFIG_TIMEOUT_MS, MEMO_UPLOAD_TIMEOUT_MS, CONFIG_CACHE_MS, FLOAT_POOL_WARM_MS, DECIMAL3, POSITIVE, PENDING_CODES, FLOAT_FRONT_HEADER, hash7, fail22, GENERIC_REASON, SELLER_REASON_MAX, SELLER_REASON_READ_BYTES, FEE_PAYER_RESENDS, FEE_PAYER_RESEND_MS, GLOBAL_DISPATCHER5, sortedJson, MODEL_ID, floatPaymentWalName, floatRecordName, FLOAT_KEEP_BYTES_MS, memoryOnlyNeedsScrub, FLOAT_KEEP_OPEN_REQUEST_MS, configCache, configGeneration, configReadSequence, configReads, configRefreshes, SPECULATED_MAX_AGE_MS, speculatedQuotes, poolDomains, FLOAT_FACTS_SCHEMA, floatFacts, floatFactsKey, floatFactsMac, poolDomainReads, poolDomainWarmFailedAt, WARM_RETRY_MS, payerGenerator, etaEntry, loadPayerGenerator, plainText, BROADCAST_REFUSED, BROADCAST_REFUSED_STANDARD, BROADCAST_DEAD, TRANSFER_LANDING_WINDOW_MS, PROOF_DELIVERY_MS, SELF_BROADCAST_LEG1_LEFT_MS, BROADCAST_UNSIGNED, BROADCAST_NO_LOOKUP, BROADCAST_LANDED, BROADCAST_LIMIT_MS, BROADCAST_QUOTE_MARGIN_MS, SELF_BROADCAST_RESEND_MS, SELF_BROADCAST_UNANSWERED_RESEND_MS, SELLER_HEADERS_MAX_COUNT, SELLER_HEADERS_MAX_BYTES, FINAL_AFTER_202_MS, SELLER_HEADERS_KEPT;
108219
+ var import_web3115, FLOAT_PAYMENT_SCHEMA2, REGENERATE_CODES, FLOAT_PAYMENT_WAL_PREFIX2, FLOAT_CONFIG_SCHEMA, FLOAT_PAY_PATH, FLOAT_MEMO_PATH, FLOAT_STATUS_PATH, MAX_BODY_BYTES, FLOAT_REFUND_ETA_SECONDS, REFUND_READ_EARLY_MS, REFUND_ETA_MAX_SECONDS, refundDueOf, REFUND_SETTLED_AFTER_MS, REFUND_OUTCOME_NEWS_MS, FINISHING_POLL_MS, FINISHING_LIMIT_MS, SELLER_TIMEOUT_MS, SELLER_TIMEOUT_ABSURD_SECONDS, SELLER_STALL_CHECK_AFTER_MS, SELLER_STALL_CHECK_EVERY_MS, SELLER_STALL_CHECK_TIMEOUT_MS, SELLER_STALL_MISSES, RESULT_LIMIT_BYTES, FLOAT_STATUS_START_MS, FLOAT_STATUS_POLL_MS, FLOAT_STATUS_TIMEOUT_MS, FLOAT_TRANSFER_DEAD, FLOAT_PAYMENT_REVERTED, VERDICT_POLL_MS, SELLER_ANSWER_VERDICT_MS, TRANSFER_MIN_BLOCKS_LEFT, TRANSFER_FRESH_MS, BLOCK_HEIGHT_TIMEOUT_MS, CONFIG_TIMEOUT_MS, MEMO_UPLOAD_TIMEOUT_MS, CONFIG_CACHE_MS, FLOAT_POOL_WARM_MS, DECIMAL3, POSITIVE, PENDING_CODES, FLOAT_FRONT_HEADER, hash7, fail22, GENERIC_REASON, SELLER_REASON_MAX, SELLER_REASON_READ_BYTES, FEE_PAYER_RESENDS, FEE_PAYER_RESEND_MS, GLOBAL_DISPATCHER5, sortedJson, MODEL_ID, floatPaymentWalName, floatRecordName, FLOAT_KEEP_BYTES_MS, memoryOnlyNeedsScrub, FLOAT_KEEP_OPEN_REQUEST_MS, configCache, configGeneration, configReadSequence, configReads, configRefreshes, SPECULATED_MAX_AGE_MS, speculatedQuotes, poolDomains, FLOAT_FACTS_SCHEMA, floatFacts, floatFactsKey, floatFactsMac, poolDomainReads, poolDomainWarmFailedAt, WARM_RETRY_MS, payerGenerator, etaEntry, loadPayerGenerator, plainText, BROADCAST_REFUSED, BROADCAST_REFUSED_STANDARD, BROADCAST_DEAD, TRANSFER_LANDING_WINDOW_MS, PROOF_DELIVERY_MS, SELF_BROADCAST_LEG1_LEFT_MS, BROADCAST_UNSIGNED, BROADCAST_NO_LOOKUP, BROADCAST_LANDED, BROADCAST_LIMIT_MS, BROADCAST_QUOTE_MARGIN_MS, SELF_BROADCAST_RESEND_MS, SELF_BROADCAST_UNANSWERED_RESEND_MS, SELLER_HEADERS_MAX_COUNT, SELLER_HEADERS_MAX_BYTES, FINAL_AFTER_202_MS, SELLER_HEADERS_KEPT;
108020
108220
  var init_floatPay = __esm({
108021
108221
  "wallet/src/pay/floatPay.mjs"() {
108022
108222
  "use strict";
@@ -108064,6 +108264,11 @@ var init_floatPay = __esm({
108064
108264
  FINISHING_LIMIT_MS = 6e4;
108065
108265
  SELLER_TIMEOUT_MS = 12e4;
108066
108266
  SELLER_TIMEOUT_ABSURD_SECONDS = 86400;
108267
+ SELLER_STALL_CHECK_AFTER_MS = 3e4;
108268
+ SELLER_STALL_CHECK_EVERY_MS = 3e4;
108269
+ SELLER_STALL_CHECK_TIMEOUT_MS = 15e3;
108270
+ SELLER_STALL_MISSES = 2;
108271
+ RESULT_LIMIT_BYTES = 1024 * 1024;
108067
108272
  FLOAT_STATUS_START_MS = 45e3;
108068
108273
  FLOAT_STATUS_POLL_MS = 5e3;
108069
108274
  FLOAT_STATUS_TIMEOUT_MS = 5e3;
@@ -114440,7 +114645,9 @@ async function paidCall({ session, target, method, headers, body, cap, maxPrice,
114440
114645
  amountAtomic: amountAtomic ?? null,
114441
114646
  requestId,
114442
114647
  replayed: result.replayed === true,
114443
- receiptFinality: result.receiptFinality ?? null
114648
+ receiptFinality: result.receiptFinality ?? null,
114649
+ // AB32 (pay/floatPay.mjs sendWatchingStall): the paid request went once more on a new Tor circuit; still one payment.
114650
+ ...result.stallResent === true ? { stallResent: true } : {}
114444
114651
  };
114445
114652
  const status = Number.isInteger(result.status) && result.status >= 200 && result.status <= 299 ? result.status : 200;
114446
114653
  return new Response(
@@ -134730,7 +134937,7 @@ ${canonical5}`;
134730
134937
  ...floatPaid ? { via: "shinjuku", shinjukuTransaction } : {},
134731
134938
  ...balanceAnswer(one),
134732
134939
  ...notices,
134733
- next: (unpaid ? "nothing was paid: this request id's payment never landed (the pool's public history proves it), and the answer it got came back again; nothing new was paid. Tell the user nothing was paid for it" : receipt.replayed === true ? "this request id was already paid: the stored receipt came back and nothing new was paid" : floatPaid ? floatPaidNext({ transaction: unpaid ? null : transaction, shinjukuTransaction }) : "paid; tell the user what was paid (amountAtomic, transaction). wallet_receipts lists this payment, wallet_balance shows the new balance") + noticesStep(notices)
134940
+ next: (unpaid ? "nothing was paid: this request id's payment never landed (the pool's public history proves it), and the answer it got came back again; nothing new was paid. Tell the user nothing was paid for it" : receipt.replayed === true ? "this request id was already paid: the stored receipt came back and nothing new was paid" : floatPaid ? floatPaidNext({ transaction: unpaid ? null : transaction, shinjukuTransaction }) + (receipt.stallResent === true || float?.sellerStallResent === true ? `. Tell the user too: ${stallResentLine()}` : "") : "paid; tell the user what was paid (amountAtomic, transaction). wallet_receipts lists this payment, wallet_balance shows the new balance") + noticesStep(notices)
134734
134941
  }, "pay_for_service")
134735
134942
  }));
134736
134943
  }
@@ -135042,6 +135249,8 @@ ${canonical5}`;
135042
135249
  ...!ambiguous && floatSellerCanBeFixed(error) ? { sellerFixable: true } : {},
135043
135250
  ...error?.transferLanded === true ? { transferLanded: true } : {},
135044
135251
  ...error?.resent === true ? { resent: true } : {},
135252
+ // AB32: this payment went once more on a new Tor circuit after a stall (floatPay.mjs sendWatchingStall).
135253
+ ...error?.stallResent === true ? { stallResent: true } : {},
135045
135254
  ...error?.pruned === true ? { pruned: true } : {},
135046
135255
  ...typeof error?.floatCode === "string" ? { floatCode: error.floatCode } : {},
135047
135256
  // AB164: the seller's own code beside its error after it took the payment (floatWords.mjs PAID_SELLER_FAILED_CODE).
@@ -149456,6 +149665,7 @@ The next question uses it${state2.mode === "talk" ? ", with the conversation so
149456
149665
  else if (plainPaid && reader?.terminal && unsureAtomic() === 0n && !dayRoom2) {
149457
149666
  if (cut2) say2(cut2.trim());
149458
149667
  } else say2(`${cut2}${paidText}. ${tail}`);
149668
+ if (plainPaid && result.receipt?.stallResent === true) say2(stallResentLine("the AI provider"));
149459
149669
  if (state2.mode === "each" && !state2.eachHinted) {
149460
149670
  state2.eachHinted = true;
149461
149671
  say2(paint([["Each question goes alone: the AI does not see your earlier questions. For follow-ups, /mode 2 picks a conversation.", "mute"]], color));
@@ -156463,15 +156673,18 @@ function freePort() {
156463
156673
  var failure2 = (plain, detail, extra = {}) => Object.assign(new Error(detail ?? plain), { plain, ...extra });
156464
156674
  var sleep4 = (ms) => new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
156465
156675
  var tunnelOf = (port) => `http://127.0.0.1:${port}`;
156466
- function takeLock(home, say2) {
156467
- mkdirSync(managedTorDir(home), { recursive: true, mode: 448 });
156676
+ function lockName(home) {
156468
156677
  let real = home;
156469
156678
  try {
156470
156679
  real = realpathSync.native(home);
156471
156680
  } catch {
156472
156681
  }
156473
156682
  if (process.platform === "win32" || process.platform === "darwin") real = real.toLowerCase();
156474
- return takeProcessLock(`tor-start ${real}`, {
156683
+ return `tor-start ${real}`;
156684
+ }
156685
+ function takeLock(home, say2) {
156686
+ mkdirSync(managedTorDir(home), { recursive: true, mode: 448 });
156687
+ return takeProcessLock(lockName(home), {
156475
156688
  waitEveryMs: Infinity,
156476
156689
  onWait: () => say2("Waiting for Tor, which is starting in the background."),
156477
156690
  lostError: () => failure2("another start took over. Ask again", "the start lock was taken over")
@@ -156532,6 +156745,13 @@ async function installBundle(home, say2) {
156532
156745
  `);
156533
156746
  renameSync(unpacking, target);
156534
156747
  }
156748
+ function bootstrappedSince(home, from) {
156749
+ try {
156750
+ return /Bootstrapped 100%/.test(readFileSync(logFile(home), "utf8").slice(Number.isInteger(from) ? from : 0));
156751
+ } catch {
156752
+ return false;
156753
+ }
156754
+ }
156535
156755
  async function waitBootstrapped(home, alive2, from) {
156536
156756
  const until = Date.now() + BOOTSTRAP_TIMEOUT_MS;
156537
156757
  for (; ; ) {
@@ -156611,9 +156831,27 @@ async function startTor(home, port, say2, assertHeld = () => {
156611
156831
  child.once("exit", () => {
156612
156832
  ended2 = true;
156613
156833
  });
156834
+ let stopped = false;
156835
+ const endStart = () => {
156836
+ if (!ended2) child.kill();
156837
+ try {
156838
+ rmSync(stateFile(home), { force: true });
156839
+ } catch {
156840
+ }
156841
+ };
156842
+ const onStop = (signal) => {
156843
+ stopped = true;
156844
+ if (!bootstrappedSince(home, from)) endStart();
156845
+ if (process.listenerCount(signal) === 1) process.exit(signal === "SIGINT" ? 130 : 143);
156846
+ };
156847
+ const stopSignals = ["SIGINT", "SIGTERM"];
156848
+ for (const signal of stopSignals) process.on(signal, onStop);
156614
156849
  await new Promise((resolvePromise, reject) => {
156615
156850
  child.once("error", (error) => reject(blocked(error)));
156616
156851
  child.once("spawn", resolvePromise);
156852
+ }).catch((error) => {
156853
+ for (const signal of stopSignals) process.off(signal, onStop);
156854
+ throw error;
156617
156855
  });
156618
156856
  child.unref();
156619
156857
  try {
@@ -156628,14 +156866,13 @@ async function startTor(home, port, say2, assertHeld = () => {
156628
156866
  );
156629
156867
  }
156630
156868
  say2("Starting Tor in the background (a few seconds; up to a minute the first time).");
156631
- await waitBootstrapped(home, () => !ended2, from);
156869
+ await waitBootstrapped(home, () => !ended2 && !stopped, from);
156632
156870
  } catch (error) {
156633
- if (!ended2) child.kill();
156634
- try {
156635
- rmSync(stateFile(home), { force: true });
156636
- } catch {
156637
- }
156871
+ if (!stopped || !bootstrappedSince(home, from)) endStart();
156872
+ if (stopped) throw failure2("you stopped the start with Ctrl+C, so Tor was stopped too. Ask again to start it", "the Tor start was stopped (Ctrl+C)");
156638
156873
  throw error;
156874
+ } finally {
156875
+ for (const signal of stopSignals) process.off(signal, onStop);
156639
156876
  }
156640
156877
  }
156641
156878
  async function recordTunnel(home, tunnel) {
@@ -156644,7 +156881,7 @@ async function recordTunnel(home, tunnel) {
156644
156881
  } catch {
156645
156882
  }
156646
156883
  }
156647
- async function ownTorReady(home, state2) {
156884
+ async function ownTorReady(home, state2, { wait: wait2 = true } = {}) {
156648
156885
  if (!state2 || !pidAlive4(state2.pid)) return void 0;
156649
156886
  let now;
156650
156887
  try {
@@ -156656,6 +156893,7 @@ async function ownTorReady(home, state2) {
156656
156893
  let own = await controlCheck(home, state2);
156657
156894
  if (own?.tunnelPort !== state2.port) return void 0;
156658
156895
  if (own.progress < 100) {
156896
+ if (!wait2) return void 0;
156659
156897
  await waitBootstrapped(home, () => pidAlive4(state2.pid), Number.isInteger(state2.logFrom) ? state2.logFrom : 0);
156660
156898
  own = await controlCheck(home, state2);
156661
156899
  if (own?.tunnelPort !== state2.port || own.progress < 100) return void 0;
@@ -156719,8 +156957,9 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
156719
156957
  const ownPort = ownPortOf(home);
156720
156958
  if (explicit && Number(url.port) !== ownPort) return proxy;
156721
156959
  try {
156722
- const ready = await ownTorReady(home, managedTorState(home));
156723
- if (ready) {
156960
+ const known = managedTorState(home);
156961
+ const ready = await ownTorReady(home, known, { wait: false });
156962
+ if (ready && await processLockFree(lockName(home)) && pidAlive4(known.pid)) {
156724
156963
  await recordTunnel(home, ready);
156725
156964
  return ready;
156726
156965
  }
@@ -159182,7 +159421,8 @@ async function curlOutput(response, values, deps, requestId) {
159182
159421
  const person = values.get(PERSON_LINK);
159183
159422
  const said = (text4) => person ? personWords(text4, { homeJob: person.homeJob }) : text4;
159184
159423
  io.err(said(unpaid ? `the same answer as before; nothing was paid: the earlier payment for request-id ${requestId} never went through
159185
- ` : paid ? `paid ${usdcOr(paid.amountAtomic)} from your private balance${route} (the chain does not show who paid); request-id ${requestId}${paid.replayed ? " (replayed: this request was paid before; nothing new was paid)" : ""}
159424
+ ` : paid ? `paid ${usdcOr(paid.amountAtomic)} from your private balance${route} (the chain does not show who paid); request-id ${requestId}${paid.replayed ? " (replayed: this request was paid before; nothing new was paid)" : ""}${paid.stallResent === true && !paid.replayed ? `
159425
+ ${stallResentLine()}` : ""}
159186
159426
  ` : `free (no 402): HTTP ${response.status}; nothing was paid
159187
159427
  `));
159188
159428
  if (values.has("--out")) {
@@ -159629,6 +159869,8 @@ function inferOutput(result, { values, io, model: model2, quiet, requestId, held
159629
159869
  `);
159630
159870
  if (plainPaid) {
159631
159871
  io.err(`${paidLine(BigInt(result.paidAtomic), { color: brandColor(process.stderr, process.env) })}${quiet ? "" : ` request-id ${result.requestId ?? requestId}`}${stopped}
159872
+ `);
159873
+ if (result.receipt?.stallResent === true) io.err(`${stallResentLine("the AI provider")}
159632
159874
  `);
159633
159875
  }
159634
159876
  }