shinjuku-shield 0.3.133 → 0.3.135

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,19 +6,19 @@ 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.133. The npm packages `shinjuku-shield` and
9
+ This is version 0.3.135. 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
- npm install -g shinjuku@0.3.133
15
+ npm install -g shinjuku@0.3.135
16
16
  shinjuku setup
17
17
  ```
18
18
 
19
19
  Type the two lines as they are. `npx install shinjuku` does not work: npx
20
20
  reads `install` as the name of another npm package. To set up without
21
- installing, type `npx shinjuku@0.3.133 setup`.
21
+ installing, type `npx shinjuku@0.3.135 setup`.
22
22
 
23
23
  Setup makes the wallet on this machine, a private passphrase file, and the
24
24
  checked proof tools (about 191 MB), and writes `config.json`. It also writes
@@ -36,13 +36,13 @@ Every wallet command works after `shinjuku`, for example `shinjuku balance`,
36
36
  Claude Code:
37
37
 
38
38
  ```sh
39
- claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.133 mcp
39
+ claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.135 mcp
40
40
  ```
41
41
 
42
42
  Claude Desktop (`claude_desktop_config.json`) or Cursor (`~/.cursor/mcp.json`):
43
43
 
44
44
  ```json
45
- { "mcpServers": { "shinjuku": { "command": "npx", "args": ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.133", "mcp"] } } }
45
+ { "mcpServers": { "shinjuku": { "command": "npx", "args": ["-y", "--no-audit", "--no-fund", "shinjuku-shield@0.3.135", "mcp"] } } }
46
46
  ```
47
47
 
48
48
  On native Windows, if the host cannot find `npx`, use `"command": "cmd"` and
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": "60d67f9e68f5464e9c70a24a9743bb01a5c6e208627f1f7d6c966f8b2731b75b",
5
- "bytes": 8867259,
6
- "sourceCommit": "419e3dbe9d626493ef68662d11b9a2470284661d",
4
+ "sha256": "45b6c2ae1564c104f82be3d93124b0dffe53f6d5663167b874e720fb8231bc6f",
5
+ "bytes": 8896515,
6
+ "sourceCommit": "282e02a7d33f0f072f2c0ffa95f74166a0ef5b68",
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",
@@ -1037,5 +1037,5 @@
1037
1037
  "version": "1.8.0"
1038
1038
  }
1039
1039
  ],
1040
- "publishedAt": "2026-10-31T15:16:07.835Z"
1040
+ "publishedAt": "2026-10-31T16:57:08.434Z"
1041
1041
  }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "shinjuku-shield",
3
- "version": "0.3.133",
3
+ "version": "0.3.135",
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": "60d67f9e",
7
- "shinjukuSha256": "60d67f9e68f5464e9c70a24a9743bb01a5c6e208627f1f7d6c966f8b2731b75b",
6
+ "shinjukuRelease": "45b6c2ae",
7
+ "shinjukuSha256": "45b6c2ae1564c104f82be3d93124b0dffe53f6d5663167b874e720fb8231bc6f",
8
8
  "license": "SEE LICENSE IN LICENSE.txt",
9
9
  "author": "Shinjuku Shielded",
10
10
  "homepage": "https://github.com/ShinjukuStaition/shinjuku-shield#readme",
@@ -60100,10 +60100,19 @@ function prewarmWalletP03History(args) {
60100
60100
  const runKey = lastRunReportKey(args.store, args.programId, args.pool, args.deploymentIdentity, args.cache);
60101
60101
  if (runKey === void 0) return false;
60102
60102
  const prior = prewarmedWalks.get(runKey);
60103
- if (prior !== void 0 && Date.now() - prior.startedAt <= HISTORY_PREWARM_JOIN_MS) {
60103
+ const recheck = prior !== void 0 && prior.settled === true && Number.isFinite(args.paymentStartedAt) && prior.startedAt < args.paymentStartedAt;
60104
+ if (prior !== void 0 && !recheck && Date.now() - prior.startedAt <= HISTORY_PREWARM_JOIN_MS) {
60104
60105
  latestPrewarm = prior.promise;
60105
60106
  return true;
60106
60107
  }
60108
+ if (recheck && Date.now() - prior.startedAt <= HISTORY_PREWARM_JOIN_MS) {
60109
+ const kept2 = prior.report;
60110
+ const recent = recentLoads.get(runKey);
60111
+ if (kept2 !== null && typeof kept2 === "object" && prior.startedAt >= proofBuiltAt && !PAYMENT_TAKEN_REPORTS.has(kept2) && (recent === void 0 || recentAgeStart(recent) < prior.startedAt)) {
60112
+ recentLoads.set(runKey, { startedAt: prior.startedAt, report: kept2, ageFrom: prior.startedAt });
60113
+ }
60114
+ markPhase("prewarm-recheck");
60115
+ }
60107
60116
  const shared2 = sharedWalks.get(runKey);
60108
60117
  if (shared2 !== void 0 && Date.now() - shared2.startedAt <= HISTORY_PREWARM_JOIN_MS) {
60109
60118
  shared2.joined = true;
@@ -60136,12 +60145,14 @@ function prewarmWalletP03History(args) {
60136
60145
  }
60137
60146
  const marks = walletHistoryHomeMarks(args.store);
60138
60147
  const entry = { startedAt: Date.now(), settled: false, marks };
60139
- entry.promise = loadWalletP03HistoryNow({ ...args, forceRead: false, onListed: () => {
60148
+ const { paymentStartedAt: _paymentStartedAt, ...walkArgs } = args;
60149
+ entry.promise = loadWalletP03HistoryNow({ ...walkArgs, forceRead: false, onListed: () => {
60140
60150
  entry.listedAt ??= Date.now();
60141
60151
  } });
60142
60152
  entry.promise.then(prepareReport).catch(() => {
60143
60153
  });
60144
- entry.promise.then(() => {
60154
+ entry.promise.then((report) => {
60155
+ entry.report = report;
60145
60156
  entry.settled = true;
60146
60157
  }, () => {
60147
60158
  entry.settled = true;
@@ -60682,7 +60693,7 @@ var init_walletHistory = __esm({
60682
60693
  recentScope = new AsyncLocalStorage3();
60683
60694
  withRecentWalletHistory = (fn, { accept } = {}) => recentScope.run({ accept }, fn);
60684
60695
  recentLoads = /* @__PURE__ */ new Map();
60685
- recentAgeStart = (recent) => poolReadAtOf(recent.report) ?? recent.startedAt;
60696
+ recentAgeStart = (recent) => recent.ageFrom ?? poolReadAtOf(recent.report) ?? recent.startedAt;
60686
60697
  forgetRecentWalletHistory = () => {
60687
60698
  recentLoads.clear();
60688
60699
  proofBuiltAt = Date.now();
@@ -65808,6 +65819,7 @@ var init_errorCodes = __esm({
65808
65819
  "inference_max_tokens_required",
65809
65820
  "inference_max_tokens_too_low",
65810
65821
  "inference_messages_invalid",
65822
+ "inference_tools_invalid",
65811
65823
  "inference_model_unknown",
65812
65824
  "inference_no_provider",
65813
65825
  "inference_origin_refused",
@@ -72584,6 +72596,7 @@ function hostShellWord(word, platform = process.platform) {
72584
72596
  }
72585
72597
  function hostConfigFile(target, { platform = process.platform, env = process.env, home = homedir() } = {}) {
72586
72598
  if (target === "cursor") return join11(home, ".cursor", "mcp.json");
72599
+ if (target === "codex") return join11(env.CODEX_HOME || join11(home, ".codex"), "config.toml");
72587
72600
  if (target === "claude-desktop") {
72588
72601
  if (platform === "win32") return join11(env.APPDATA || join11(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json");
72589
72602
  if (platform === "darwin") return join11(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -72596,9 +72609,264 @@ function hostConfigText({ home, env = process.env, platform = process.platform,
72596
72609
  const files = [["claude-desktop", "Claude Desktop (claude_desktop_config.json)"], ["cursor", "Cursor (~/.cursor/mcp.json)"]].filter(([target]) => !skip.has(target)).map(([, label]) => label);
72597
72610
  return [
72598
72611
  ...skip.has("claude-code") ? [] : claudeCodeShellWhy({ home, env, platform }) ? ["Claude Code:", ` ${claudeCodeShellWhy({ home, env, platform })}`] : claudeCodeLines({ home, env, platform, npmVersion }),
72599
- ...files.length ? [`${files.join(" or ")}, inside "mcpServers":`, ...json4.split("\n").map((line) => ` ${line}`)] : []
72612
+ ...files.length ? [`${files.join(" or ")}, inside "mcpServers":`, ...json4.split("\n").map((line) => ` ${line}`)] : [],
72613
+ ...skip.has("codex") ? [] : [
72614
+ "Codex (the Codex app and Codex CLI), at the end of ~/.codex/config.toml:",
72615
+ ...codexTomlBlock(mcpServerEntry({ home, env, npmVersion })).trimEnd().split("\n").map((line) => ` ${line}`)
72616
+ ]
72600
72617
  ].join("\n");
72601
72618
  }
72619
+ function codexTomlBlock(entry) {
72620
+ const lines = [
72621
+ `[mcp_servers.${tomlKey(MCP_SERVER_NAME)}]`,
72622
+ `command = ${tomlString(entry.command)}`,
72623
+ `args = [${entry.args.map(tomlString).join(", ")}]`,
72624
+ `startup_timeout_sec = ${CODEX_STARTUP_TIMEOUT_SEC}`,
72625
+ `tool_timeout_sec = ${CODEX_TOOL_TIMEOUT_SEC}`
72626
+ ];
72627
+ const env = isPlainObject(entry.env) ? Object.entries(entry.env) : [];
72628
+ if (env.length) lines.push("", `[mcp_servers.${tomlKey(MCP_SERVER_NAME)}.env]`, ...env.map(([key, value2]) => `${tomlKey(key)} = ${tomlString(value2)}`));
72629
+ return `${lines.join("\n")}
72630
+ `;
72631
+ }
72632
+ function tomlKeyPath(text3) {
72633
+ const parts = [];
72634
+ let rest = text3.trim();
72635
+ while (rest.length) {
72636
+ let match = /^([A-Za-z0-9_-]+)\s*/.exec(rest) ?? /^"((?:[^"\\]|\\.)*)"\s*/.exec(rest) ?? /^'([^']*)'\s*/.exec(rest);
72637
+ if (!match) return void 0;
72638
+ parts.push(match[0].startsWith('"') ? JSON.parse(`"${match[1]}"`) : match[1]);
72639
+ rest = rest.slice(match[0].length);
72640
+ if (!rest.length) break;
72641
+ if (!rest.startsWith(".")) return void 0;
72642
+ rest = rest.slice(1).trimStart();
72643
+ }
72644
+ return parts.length ? parts : void 0;
72645
+ }
72646
+ function tomlValue(text3) {
72647
+ const src = text3.trim();
72648
+ let at = 0;
72649
+ const space = () => {
72650
+ for (; ; ) {
72651
+ while (/\s/.test(src[at] ?? "")) at += 1;
72652
+ if (src[at] === "#") {
72653
+ while (at < src.length && src[at] !== "\n") at += 1;
72654
+ } else return;
72655
+ }
72656
+ };
72657
+ const string = () => {
72658
+ if (src[at] === "'") {
72659
+ const end = src.indexOf("'", at + 1);
72660
+ if (end < 0) throw new Error("toml");
72661
+ const out3 = src.slice(at + 1, end);
72662
+ at = end + 1;
72663
+ return out3;
72664
+ }
72665
+ if (src[at] !== '"') throw new Error("toml");
72666
+ let out2 = "";
72667
+ at += 1;
72668
+ while (at < src.length && src[at] !== '"') {
72669
+ if (src[at] === "\\") {
72670
+ const c = src[at + 1];
72671
+ const simple = { b: "\b", t: " ", n: "\n", f: "\f", r: "\r", '"': '"', "\\": "\\" }[c];
72672
+ if (simple !== void 0) {
72673
+ out2 += simple;
72674
+ at += 2;
72675
+ } else if (c === "u" || c === "U") {
72676
+ const size = c === "u" ? 4 : 8;
72677
+ out2 += String.fromCodePoint(parseInt(src.slice(at + 2, at + 2 + size), 16));
72678
+ at += 2 + size;
72679
+ } else throw new Error("toml");
72680
+ } else {
72681
+ out2 += src[at];
72682
+ at += 1;
72683
+ }
72684
+ }
72685
+ if (src[at] !== '"') throw new Error("toml");
72686
+ at += 1;
72687
+ return out2;
72688
+ };
72689
+ const value2 = () => {
72690
+ space();
72691
+ if (src[at] === '"' || src[at] === "'") return string();
72692
+ if (src[at] === "[") {
72693
+ at += 1;
72694
+ const out2 = [];
72695
+ for (; ; ) {
72696
+ space();
72697
+ if (src[at] === "]") {
72698
+ at += 1;
72699
+ return out2;
72700
+ }
72701
+ out2.push(value2());
72702
+ space();
72703
+ if (src[at] === ",") at += 1;
72704
+ else if (src[at] !== "]") throw new Error("toml");
72705
+ }
72706
+ }
72707
+ if (src[at] === "{") {
72708
+ at += 1;
72709
+ const out2 = {};
72710
+ for (; ; ) {
72711
+ space();
72712
+ if (src[at] === "}") {
72713
+ at += 1;
72714
+ return out2;
72715
+ }
72716
+ const eq = src.indexOf("=", at);
72717
+ if (eq < 0) throw new Error("toml");
72718
+ const key = tomlKeyPath(src.slice(at, eq));
72719
+ if (!key || key.length !== 1) throw new Error("toml");
72720
+ at = eq + 1;
72721
+ out2[key[0]] = value2();
72722
+ space();
72723
+ if (src[at] === ",") at += 1;
72724
+ else if (src[at] !== "}") throw new Error("toml");
72725
+ }
72726
+ }
72727
+ const number2 = /^[+-]?[0-9_]+(?:\.[0-9_]+)?/.exec(src.slice(at));
72728
+ if (number2) {
72729
+ at += number2[0].length;
72730
+ return Number(number2[0].replace(/_/g, ""));
72731
+ }
72732
+ const bool3 = /^(true|false)\b/.exec(src.slice(at));
72733
+ if (bool3) {
72734
+ at += bool3[0].length;
72735
+ return bool3[0] === "true";
72736
+ }
72737
+ throw new Error("toml");
72738
+ };
72739
+ const out = value2();
72740
+ space();
72741
+ if (at !== src.length) throw new Error("toml");
72742
+ return out;
72743
+ }
72744
+ function tomlValueLines(lines, start, first) {
72745
+ let text3 = first;
72746
+ for (let end = start; end < lines.length; end += 1) {
72747
+ if (end > start) text3 += `
72748
+ ${lines[end]}`;
72749
+ try {
72750
+ tomlValue(text3);
72751
+ return { end, text: text3 };
72752
+ } catch {
72753
+ }
72754
+ }
72755
+ return void 0;
72756
+ }
72757
+ function codexServersIn(text3, names) {
72758
+ const lines = text3.split(/\r?\n/);
72759
+ const servers = {};
72760
+ let unreadable = false;
72761
+ let table;
72762
+ let owner;
72763
+ for (let index = 0; index < lines.length; index += 1) {
72764
+ const line = lines[index];
72765
+ const trimmed = line.trim();
72766
+ if (!trimmed || trimmed.startsWith("#")) continue;
72767
+ if (trimmed.startsWith("[[")) {
72768
+ const path = tomlKeyPath(trimmed.replace(/^\[\[|\]\](\s*#.*)?$/g, ""));
72769
+ table = path;
72770
+ owner = void 0;
72771
+ if (!path || path[0] === "mcp_servers" && names.includes(path[1])) unreadable = true;
72772
+ continue;
72773
+ }
72774
+ if (trimmed.startsWith("[")) {
72775
+ const header = /^\[([^\]]*)\]\s*(?:#.*)?$/.exec(trimmed);
72776
+ const path = header ? tomlKeyPath(header[1]) : void 0;
72777
+ if (!path) {
72778
+ unreadable = true;
72779
+ table = void 0;
72780
+ owner = void 0;
72781
+ continue;
72782
+ }
72783
+ table = path;
72784
+ owner = path[0] === "mcp_servers" && names.includes(path[1]) ? path[1] : void 0;
72785
+ if (owner !== void 0) {
72786
+ const server = servers[owner] ??= { env: {}, ranges: [] };
72787
+ server.ranges.push([index, index + 1]);
72788
+ }
72789
+ continue;
72790
+ }
72791
+ const eq = line.indexOf("=");
72792
+ const key = eq < 0 ? void 0 : tomlKeyPath(line.slice(0, eq));
72793
+ const full = key && table ? [...table, ...key] : key;
72794
+ const multi = eq < 0 ? void 0 : /^\s*("""|''')/.exec(line.slice(eq + 1))?.[1];
72795
+ if (multi) {
72796
+ const after = line.slice(eq + 1).trimStart().slice(3);
72797
+ let end = index;
72798
+ if (!after.includes(multi)) {
72799
+ end += 1;
72800
+ while (end < lines.length && !lines[end].includes(multi)) end += 1;
72801
+ }
72802
+ if (end >= lines.length) {
72803
+ unreadable = true;
72804
+ break;
72805
+ }
72806
+ if (owner !== void 0 || full && full[0] === "mcp_servers" && names.includes(full[1])) unreadable = true;
72807
+ index = end;
72808
+ continue;
72809
+ }
72810
+ const found = full ? tomlValueLines(lines, index, line.slice(eq + 1)) : void 0;
72811
+ if (owner !== void 0) {
72812
+ const server = servers[owner];
72813
+ server.ranges.at(-1)[1] = (found?.end ?? index) + 1;
72814
+ if (!found) {
72815
+ unreadable = true;
72816
+ continue;
72817
+ }
72818
+ const rel = full.slice(2);
72819
+ const value2 = tomlValue(found.text);
72820
+ if (rel.length === 1 && rel[0] === "command") server.command = value2;
72821
+ else if (rel.length === 1 && rel[0] === "args") server.args = value2;
72822
+ else if (rel.length === 1 && rel[0] === "env" && isPlainObject(value2)) server.env = { ...server.env, ...value2 };
72823
+ else if (rel.length === 2 && rel[0] === "env") server.env[rel[1]] = value2;
72824
+ index = found.end;
72825
+ continue;
72826
+ }
72827
+ if (full && full[0] === "mcp_servers" && names.includes(full[1])) unreadable = true;
72828
+ if (found) index = found.end;
72829
+ }
72830
+ for (const server of Object.values(servers)) {
72831
+ for (const range of server.ranges) {
72832
+ while (range[1] < lines.length && !lines[range[1]].trim()) range[1] += 1;
72833
+ }
72834
+ }
72835
+ return { servers, unreadable };
72836
+ }
72837
+ function addToCodexHost(file, entry, { now = /* @__PURE__ */ new Date(), force = false, platform = process.platform, restrict = restrictToOwnerWindows } = {}) {
72838
+ let replaced = [];
72839
+ const block = codexTomlBlock(entry);
72840
+ const result = changeJsonFile(file, (text3) => {
72841
+ const names = [MCP_SERVER_NAME, ...OLD_MCP_SERVER_NAMES];
72842
+ let found;
72843
+ try {
72844
+ found = codexServersIn(text3, names);
72845
+ } catch {
72846
+ found = { unreadable: true };
72847
+ }
72848
+ if (found.unreadable) {
72849
+ throw new Error("setup_host_config_unreadable: Codex's config.toml names the wallet's server in a way setup does not change, so setup left it alone; add the printed entry by hand");
72850
+ }
72851
+ replaced = OLD_MCP_SERVER_NAMES.filter((name) => found.servers[name] !== void 0);
72852
+ const existing = found.servers[MCP_SERVER_NAME];
72853
+ const lines = text3.split(/\r?\n/);
72854
+ const newline = text3.includes("\r\n") ? "\r\n" : "\n";
72855
+ if (existing !== void 0) {
72856
+ const own = lines.slice(existing.ranges[0][0], existing.ranges.at(-1)[1]).join("\n").trim();
72857
+ if (existing.ranges.length <= 2 && own === block.trim() && replaced.length === 0) return void 0;
72858
+ const was = codexEntryOf(existing);
72859
+ if (!force && !sameJson2(was, entry) && !isOlderSetupEntry(was, entry)) {
72860
+ throw new Error(`setup_host_config_conflict: Codex's config.toml already has a different "${MCP_SERVER_NAME}" server, so setup left it alone; rerun setup with --force to replace it (the old file is backed up first), or edit it by hand`);
72861
+ }
72862
+ }
72863
+ const drop = /* @__PURE__ */ new Set();
72864
+ for (const name of [MCP_SERVER_NAME, ...replaced]) for (const [from, to] of found.servers[name]?.ranges ?? []) for (let i = from; i < to; i += 1) drop.add(i);
72865
+ const kept2 = lines.filter((_, index) => !drop.has(index)).join(newline).replace(/\s+$/, "");
72866
+ return `${kept2 ? `${kept2}${newline}${newline}` : ""}${block.replace(/\n/g, newline)}`;
72867
+ }, { now, platform, restrict, codec: TEXT_CODEC });
72868
+ return { file, ...result, replaced };
72869
+ }
72602
72870
  function isOlderSetupEntry(existing, entry) {
72603
72871
  if (!isPlainObject(existing) || !Array.isArray(existing.args) || entry.command !== "npx" || !Array.isArray(entry.args)) return false;
72604
72872
  const pinned = (args) => args.some((arg) => PINNED_PACKAGE.test(arg));
@@ -72668,20 +72936,12 @@ function allowInClaudeCode(file, { now = /* @__PURE__ */ new Date(), platform =
72668
72936
  }, { now, platform, restrict });
72669
72937
  return { file, ...result, added };
72670
72938
  }
72671
- function changeJsonFile(file, change, { now, platform, restrict }) {
72672
- let current = {};
72939
+ function changeJsonFile(file, change, { now, platform, restrict, codec = JSON_CODEC }) {
72940
+ let current = codec.empty();
72673
72941
  let bytes2;
72674
72942
  if (existsSync(file)) {
72675
72943
  bytes2 = readFileSync(file);
72676
- const text3 = bytes2.toString("utf8");
72677
- try {
72678
- current = text3.trim() ? JSON.parse(text3) : {};
72679
- } catch {
72680
- current = void 0;
72681
- }
72682
- if (!isPlainObject(current)) {
72683
- throw new Error("setup_host_config_unreadable: the host's config file is not a JSON object, so setup left it alone; add the printed entry by hand");
72684
- }
72944
+ current = codec.read(bytes2.toString("utf8"));
72685
72945
  }
72686
72946
  const next = change(current);
72687
72947
  if (next === void 0) return { changed: false };
@@ -72716,11 +72976,9 @@ function changeJsonFile(file, change, { now, platform, restrict }) {
72716
72976
  if (platform === "win32") {
72717
72977
  writeFileSync(temp, "", { flag: "wx" });
72718
72978
  restrict(temp);
72719
- writeFileSync(temp, `${JSON.stringify(next, null, 2)}
72720
- `);
72979
+ writeFileSync(temp, codec.write(next));
72721
72980
  } else {
72722
- writeFileSync(temp, `${JSON.stringify(next, null, 2)}
72723
- `, { mode: mode ?? 384, flag: "wx" });
72981
+ writeFileSync(temp, codec.write(next), { mode: mode ?? 384, flag: "wx" });
72724
72982
  }
72725
72983
  if (mode !== void 0 && platform !== "win32") chmodSync(temp, mode);
72726
72984
  renameSync(temp, file);
@@ -72730,7 +72988,7 @@ function changeJsonFile(file, change, { now, platform, restrict }) {
72730
72988
  }
72731
72989
  return { changed: true, ...backup ? { backup } : {} };
72732
72990
  }
72733
- var import_web3104, CONFIG_SCHEMA, CONFIG_FILE, NPM_PACKAGE_NAMES, COMMAND_PACKAGE, NPX_PACKAGE, NPX_INSTALL_FLAGS, MCP_SERVER_NAME, OLD_MCP_SERVER_NAMES, P03_BINDING2, PRODUCTION, RETIRED_POOLS, NO_LIMIT_ATOMIC, DEFAULT_CAPS, OLD_DEFAULT_SETUP_CAPS, OLD_DEFAULT_WALLET_BUDGETS, capText, POSITIVE_ATOMIC, HOME_FOLDER, OLDER_HOME_FOLDER, defaultHomeWords, configPath, homeWalletPath, invalid, isPubkey, MAX_OWN_ADDRESSES, isOwnAddressText, HOST_TARGETS, PINNED_PACKAGE, LAUNCHER_PACKAGE, NPM_VERSION, knownNpmVersion, RELEASES_URL, WINDOWS_SHELL_CODE, isPlainObject, sameJson2, READ_ONLY_TOOL_NAMES, claudeCodeAllowRules, claudeCodeSettingsFile;
72991
+ var import_web3104, CONFIG_SCHEMA, CONFIG_FILE, NPM_PACKAGE_NAMES, COMMAND_PACKAGE, NPX_PACKAGE, NPX_INSTALL_FLAGS, MCP_SERVER_NAME, OLD_MCP_SERVER_NAMES, P03_BINDING2, PRODUCTION, RETIRED_POOLS, NO_LIMIT_ATOMIC, DEFAULT_CAPS, OLD_DEFAULT_SETUP_CAPS, OLD_DEFAULT_WALLET_BUDGETS, capText, POSITIVE_ATOMIC, HOME_FOLDER, OLDER_HOME_FOLDER, defaultHomeWords, configPath, homeWalletPath, invalid, isPubkey, MAX_OWN_ADDRESSES, isOwnAddressText, HOST_TARGETS, HOST_NAMES, CODEX_STARTUP_TIMEOUT_SEC, CODEX_TOOL_TIMEOUT_SEC, PINNED_PACKAGE, LAUNCHER_PACKAGE, NPM_VERSION, knownNpmVersion, RELEASES_URL, WINDOWS_SHELL_CODE, tomlString, tomlKey, codexEntryOf, isPlainObject, sameJson2, READ_ONLY_TOOL_NAMES, claudeCodeAllowRules, claudeCodeSettingsFile, JSON_CODEC, TEXT_CODEC;
72734
72992
  var init_config = __esm({
72735
72993
  "wallet/src/setup/config.mjs"() {
72736
72994
  "use strict";
@@ -72786,13 +73044,23 @@ var init_config = __esm({
72786
73044
  };
72787
73045
  MAX_OWN_ADDRESSES = 8;
72788
73046
  isOwnAddressText = (value2) => isPubkey(value2);
72789
- HOST_TARGETS = Object.freeze(["claude-code", "claude-desktop", "cursor"]);
73047
+ HOST_TARGETS = Object.freeze(["claude-code", "claude-desktop", "cursor", "codex"]);
73048
+ HOST_NAMES = Object.freeze({ "claude-code": "Claude Code", "claude-desktop": "Claude Desktop", cursor: "Cursor", codex: "Codex" });
73049
+ CODEX_STARTUP_TIMEOUT_SEC = 120;
73050
+ CODEX_TOOL_TIMEOUT_SEC = 300;
72790
73051
  PINNED_PACKAGE = /^shinjuku(?:-shield(?:ed)?)?@(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
72791
73052
  LAUNCHER_PACKAGE = /^shinjuku@[^\s@]+$/;
72792
73053
  NPM_VERSION = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
72793
73054
  knownNpmVersion = (npmVersion) => typeof npmVersion === "string" && npmVersion !== "0.0.0" && NPM_VERSION.test(npmVersion) ? npmVersion : void 0;
72794
73055
  RELEASES_URL = "https://github.com/ShinjukuStaition/shinjuku-shield#releases";
72795
73056
  WINDOWS_SHELL_CODE = /[%$`"\r\n]/;
73057
+ tomlString = (value2) => `"${String(value2).replace(/[\\"]/g, (c) => `\\${c}`).replace(/[\u0000-\u001f\u007f]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`)}"`;
73058
+ tomlKey = (key) => /^[A-Za-z0-9_-]+$/.test(key) ? key : tomlString(key);
73059
+ codexEntryOf = (server) => ({
73060
+ command: server.command,
73061
+ args: server.args,
73062
+ ...isPlainObject(server.env) && Object.keys(server.env).length ? { env: server.env } : {}
73063
+ });
72796
73064
  isPlainObject = (value2) => Boolean(value2) && typeof value2 === "object" && !Array.isArray(value2);
72797
73065
  sameJson2 = (a, b) => {
72798
73066
  const canonical5 = (value2) => Array.isArray(value2) ? value2.map(canonical5) : isPlainObject(value2) ? Object.fromEntries(Object.keys(value2).sort().map((key) => [key, canonical5(value2[key])])) : value2;
@@ -72808,6 +73076,24 @@ var init_config = __esm({
72808
73076
  ]);
72809
73077
  claudeCodeAllowRules = () => READ_ONLY_TOOL_NAMES.map((name) => `mcp__${MCP_SERVER_NAME}__${name}`);
72810
73078
  claudeCodeSettingsFile = ({ env = process.env, home = homedir() } = {}) => join11(env.CLAUDE_CONFIG_DIR || join11(home, ".claude"), "settings.json");
73079
+ JSON_CODEC = Object.freeze({
73080
+ empty: () => ({}),
73081
+ read: (text3) => {
73082
+ let current;
73083
+ try {
73084
+ current = text3.trim() ? JSON.parse(text3) : {};
73085
+ } catch {
73086
+ current = void 0;
73087
+ }
73088
+ if (!isPlainObject(current)) {
73089
+ throw new Error("setup_host_config_unreadable: the host's config file is not a JSON object, so setup left it alone; add the printed entry by hand");
73090
+ }
73091
+ return current;
73092
+ },
73093
+ write: (next) => `${JSON.stringify(next, null, 2)}
73094
+ `
73095
+ });
73096
+ TEXT_CODEC = Object.freeze({ empty: () => "", read: (text3) => text3, write: (next) => next });
72811
73097
  }
72812
73098
  });
72813
73099
 
@@ -109766,6 +110052,7 @@ function onOwnTorCircuit(pay) {
109766
110052
  }
109767
110053
  async function payTurn({ session, target, method, headers, body, maxPrice, policy, cap, requestId, memoryOnly, opts }) {
109768
110054
  if (session.closed) fail25("fetch_session_closed", "this payer session is closed; open a new one");
110055
+ const paymentStartedAt = Date.now();
109769
110056
  const timing = typeof opts?.timing === "function" ? opts.timing : session.timing();
109770
110057
  const mark = (phase) => {
109771
110058
  try {
@@ -109782,7 +110069,7 @@ async function payTurn({ session, target, method, headers, body, maxPrice, polic
109782
110069
  let askLeg1;
109783
110070
  if (!rerun) {
109784
110071
  if (store !== void 0) {
109785
- startHistoryPrewarm(session, store, mark);
110072
+ startHistoryPrewarm(session, store, mark, paymentStartedAt);
109786
110073
  warmFloatPay({ store, connection: session.connection });
109787
110074
  warmFloatConfig({ origin: new URL(session.memoServiceUrl).origin, timing: mark });
109788
110075
  startRecoveredPaymentTools(lazyProofTools(session));
@@ -109867,6 +110154,7 @@ async function payTurn({ session, target, method, headers, body, maxPrice, polic
109867
110154
  timing,
109868
110155
  mark,
109869
110156
  memoryOnly,
110157
+ paymentStartedAt,
109870
110158
  answerByMs: opts?.answerByMs,
109871
110159
  paidFrom: opts?.paidFrom
109872
110160
  }).finally(rotateTorCircuit));
@@ -109964,10 +110252,11 @@ function warmPaymentHistory(session) {
109964
110252
  } catch {
109965
110253
  }
109966
110254
  }
109967
- function startHistoryPrewarm(session, store, mark) {
110255
+ function startHistoryPrewarm(session, store, mark, paymentStartedAt) {
109968
110256
  try {
109969
110257
  withPhaseScope(mark, "prewarm", () => prewarmWalletP03History({
109970
110258
  store,
110259
+ paymentStartedAt,
109971
110260
  connection: connectSplit(session.connection, session.historyUrl),
109972
110261
  programId: session.programId,
109973
110262
  pool: store.state.pool,
@@ -110081,7 +110370,7 @@ function startedIds(policy) {
110081
110370
  if (ids === void 0) startedUnder.set(policy, ids = /* @__PURE__ */ new Set());
110082
110371
  return ids;
110083
110372
  }
110084
- async function paidCall({ session, target, method, headers, body, cap, maxPrice, requestId, price, challenge, timing, mark, memoryOnly = false, answerByMs, paidFrom }) {
110373
+ async function paidCall({ session, target, method, headers, body, cap, maxPrice, requestId, price, challenge, timing, mark, memoryOnly = false, paymentStartedAt, answerByMs, paidFrom }) {
110085
110374
  if (session.closed) fail25("fetch_session_closed", "this payer session is closed; open a new one");
110086
110375
  const floatConfig = price?.floatConfig;
110087
110376
  const release = await paymentLease(session);
@@ -110108,7 +110397,7 @@ async function paidCall({ session, target, method, headers, body, cap, maxPrice,
110108
110397
  throw error;
110109
110398
  }
110110
110399
  }
110111
- if (own?.kind !== "pocket" && !replayOnly) startHistoryPrewarm(session, store, mark);
110400
+ if (own?.kind !== "pocket" && !replayOnly) startHistoryPrewarm(session, store, mark, paymentStartedAt);
110112
110401
  const policy = session.spendPolicy;
110113
110402
  const prepared = preparedOnly(own, store);
110114
110403
  const askPrepared = prepared && sendsKeptBytes(own, {
@@ -111562,6 +111851,23 @@ function findModel(model) {
111562
111851
  }
111563
111852
  return found;
111564
111853
  }
111854
+ function contentText(content) {
111855
+ if (typeof content === "string") return content;
111856
+ if (!Array.isArray(content)) return void 0;
111857
+ const parts = content.map((part) => part && typeof part === "object" && ["text", "input_text", "output_text"].includes(part.type) && typeof part.text === "string" ? part.text : void 0);
111858
+ return parts.every((part) => part !== void 0) ? parts.join("") : void 0;
111859
+ }
111860
+ function checkToolCalls(calls, index) {
111861
+ if (!Array.isArray(calls) || calls.length === 0 || calls.length > MAX_TOOLS) {
111862
+ fail30("inference_messages_invalid", `message ${index} has tool_calls that are not a list of 1 to ${MAX_TOOLS} calls; nothing was paid`);
111863
+ }
111864
+ return calls.map((call) => {
111865
+ if (!call || typeof call.id !== "string" || !call.id || call.id.length > 128 || (call.type ?? "function") !== "function" || !TOOL_NAME.test(String(call.function?.name ?? "")) || typeof call.function?.arguments !== "string") {
111866
+ fail30("inference_messages_invalid", `message ${index} has a tool call that needs an id, type "function", and function { name, arguments (text) }; nothing was paid`);
111867
+ }
111868
+ return { id: call.id, type: "function", function: { name: call.function.name, arguments: call.function.arguments } };
111869
+ });
111870
+ }
111565
111871
  function checkMessages(messages) {
111566
111872
  const example = 'pass messages like [{"role":"user","content":"Say hello"}]';
111567
111873
  if (!Array.isArray(messages) || messages.length === 0) {
@@ -111571,12 +111877,49 @@ function checkMessages(messages) {
111571
111877
  if (!message || typeof message !== "object" || !ROLES.includes(message.role)) {
111572
111878
  fail30("inference_messages_invalid", `message ${index} needs a role of ${ROLES.join(", ")}; nothing was paid`, { next: example });
111573
111879
  }
111574
- if (typeof message.content !== "string" || message.content.length === 0) {
111880
+ const text3 = contentText(message.content);
111881
+ if (message.role === "tool") {
111882
+ if (typeof message.tool_call_id !== "string" || !message.tool_call_id || message.tool_call_id.length > 128 || text3 === void 0) {
111883
+ fail30("inference_messages_invalid", `message ${index} (role tool) needs tool_call_id and content as text; nothing was paid`, { next: example });
111884
+ }
111885
+ return { role: "tool", tool_call_id: message.tool_call_id, content: text3 };
111886
+ }
111887
+ if (message.role === "assistant" && message.tool_calls !== void 0 && message.tool_calls !== null) {
111888
+ if (text3 === void 0 && message.content !== null && message.content !== void 0) {
111889
+ fail30("inference_messages_invalid", `message ${index} needs content as text (or null beside tool_calls); nothing was paid`, { next: example });
111890
+ }
111891
+ return { role: "assistant", content: text3 ?? "", tool_calls: checkToolCalls(message.tool_calls, index) };
111892
+ }
111893
+ if (text3 === void 0 || text3.length === 0) {
111575
111894
  fail30("inference_messages_invalid", `message ${index} needs content as non-empty text; nothing was paid`, { next: example });
111576
111895
  }
111577
- return { role: message.role, content: message.content };
111896
+ return { role: message.role, content: text3 };
111578
111897
  });
111579
111898
  }
111899
+ function checkTools(tools) {
111900
+ if (tools === void 0 || tools === null || Array.isArray(tools) && tools.length === 0) return void 0;
111901
+ if (!Array.isArray(tools) || tools.length > MAX_TOOLS) fail30("inference_tools_invalid", `tools must be a list of at most ${MAX_TOOLS} function tools; nothing was paid`);
111902
+ return tools.map((tool, index) => {
111903
+ const fn = tool?.function;
111904
+ if (tool?.type !== "function" || !fn || !TOOL_NAME.test(String(fn.name ?? "")) || fn.description !== void 0 && typeof fn.description !== "string" || fn.parameters !== void 0 && (typeof fn.parameters !== "object" || fn.parameters === null || Array.isArray(fn.parameters))) {
111905
+ fail30("inference_tools_invalid", `tool ${index} needs type "function" and function { name (letters, digits, _ . -), description?, parameters? (an object) }; nothing was paid`);
111906
+ }
111907
+ return { type: "function", function: {
111908
+ name: fn.name,
111909
+ ...fn.description === void 0 ? {} : { description: fn.description },
111910
+ ...fn.parameters === void 0 ? {} : { parameters: fn.parameters }
111911
+ } };
111912
+ });
111913
+ }
111914
+ function checkToolChoice(choice, tools) {
111915
+ if (choice === void 0 || choice === null) return void 0;
111916
+ if (["auto", "none", "required"].includes(choice)) return choice;
111917
+ const name = choice?.function?.name;
111918
+ if (choice?.type === "function" && TOOL_NAME.test(String(name ?? "")) && tools?.some((tool) => tool.function.name === name)) {
111919
+ return { type: "function", function: { name } };
111920
+ }
111921
+ fail30("inference_tools_invalid", 'tool_choice must be "auto", "none", "required", or { type: "function", function: { name } } of a tool in tools; nothing was paid');
111922
+ }
111580
111923
  function checkMaxTokens(maxTokens, model) {
111581
111924
  if (maxTokens === void 0 || maxTokens === null) return BigInt(defaultMaxTokens(model));
111582
111925
  if (!Number.isSafeInteger(maxTokens) || maxTokens < 1) {
@@ -111588,22 +111931,23 @@ function checkMaxTokens(maxTokens, model) {
111588
111931
  }
111589
111932
  return BigInt(maxTokens);
111590
111933
  }
111591
- function inputTokensBound(messages) {
111934
+ function inputTokensBound(messages, tools) {
111592
111935
  let tokens = 0n;
111593
111936
  for (const message of messages) {
111594
- tokens += BigInt(Buffer.byteLength(message.role) + Buffer.byteLength(message.content)) + MESSAGE_OVERHEAD_TOKENS;
111937
+ tokens += BigInt(Buffer.byteLength(message.role) + Buffer.byteLength(message.content) + (message.tool_calls ? Buffer.byteLength(JSON.stringify(message.tool_calls)) : 0) + (message.tool_call_id ? Buffer.byteLength(message.tool_call_id) : 0)) + MESSAGE_OVERHEAD_TOKENS;
111595
111938
  }
111939
+ if (tools) tokens += BigInt(Buffer.byteLength(JSON.stringify(tools))) + MESSAGE_OVERHEAD_TOKENS;
111596
111940
  return tokens;
111597
111941
  }
111598
- function ceilingOf(entry, messages, maxTokens) {
111599
- const estimate = ceilDiv(entry.priceInPerMAtomic * inputTokensBound(messages) + entry.priceOutPerMAtomic * maxTokens, PER_M);
111942
+ function ceilingOf(entry, messages, maxTokens, tools) {
111943
+ const estimate = ceilDiv(entry.priceInPerMAtomic * inputTokensBound(messages, tools) + entry.priceOutPerMAtomic * maxTokens, PER_M);
111600
111944
  return estimate > USEPOD_MIN_PAYMENT_ATOMIC ? estimate : USEPOD_MIN_PAYMENT_ATOMIC;
111601
111945
  }
111602
- function ceilingAtomic({ model, messages, maxTokens }) {
111946
+ function ceilingAtomic({ model, messages, maxTokens, tools }) {
111603
111947
  const entry = findModel(model);
111604
- return ceilingOf(entry, checkMessages(messages), checkMaxTokens(maxTokens, entry.id));
111948
+ return ceilingOf(entry, checkMessages(messages), checkMaxTokens(maxTokens, entry.id), checkTools(tools));
111605
111949
  }
111606
- function buildChatRequest({ model, messages, maxTokens, temperature, stream }) {
111950
+ function buildChatRequest({ model, messages, maxTokens, temperature, stream, tools, toolChoice, parallelToolCalls }) {
111607
111951
  if (stream === true) {
111608
111952
  fail30(
111609
111953
  "inference_stream_unsupported",
@@ -111617,11 +111961,19 @@ function buildChatRequest({ model, messages, maxTokens, temperature, stream }) {
111617
111961
  if (temperature !== void 0 && (typeof temperature !== "number" || !Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
111618
111962
  fail30("inference_temperature_invalid", "temperature must be a number from 0 to 2; nothing was paid", { next: "pass temperature 0.7, or leave it out" });
111619
111963
  }
111964
+ const cleanTools = checkTools(tools);
111965
+ const choice = checkToolChoice(toolChoice, cleanTools);
111966
+ if (parallelToolCalls !== void 0 && typeof parallelToolCalls !== "boolean") fail30("inference_tools_invalid", "parallel_tool_calls must be true or false; nothing was paid");
111620
111967
  const body = JSON.stringify({
111621
111968
  model: entry.id,
111622
111969
  messages: clean5,
111623
111970
  max_tokens: Number(tokens),
111624
111971
  ...temperature === void 0 ? {} : { temperature },
111972
+ ...cleanTools ? {
111973
+ tools: cleanTools,
111974
+ ...choice === void 0 ? {} : { tool_choice: choice },
111975
+ ...parallelToolCalls === void 0 ? {} : { parallel_tool_calls: parallelToolCalls }
111976
+ } : {},
111625
111977
  stream: false
111626
111978
  });
111627
111979
  return { url: USEPOD_X402_CHAT_URL, init: { method: "POST", headers: {
@@ -111634,11 +111986,19 @@ function buildChatRequest({ model, messages, maxTokens, temperature, stream }) {
111634
111986
  }, body } };
111635
111987
  }
111636
111988
  function sanitize(json4) {
111637
- const choices = json4.choices.map((choice, index) => ({
111638
- index: Number.isSafeInteger(choice?.index) ? choice.index : index,
111639
- message: { role: "assistant", content: typeof choice?.message?.content === "string" ? choice.message.content : "" },
111640
- finish_reason: typeof choice?.finish_reason === "string" ? choice.finish_reason : null
111641
- }));
111989
+ const choices = json4.choices.map((choice, index) => {
111990
+ const calls = Array.isArray(choice?.message?.tool_calls) ? choice.message.tool_calls.filter((call) => typeof call?.id === "string" && TOOL_NAME.test(String(call?.function?.name ?? ""))).map((call) => ({
111991
+ id: call.id.slice(0, 128),
111992
+ type: "function",
111993
+ function: { name: call.function.name, arguments: typeof call.function.arguments === "string" ? call.function.arguments : JSON.stringify(call.function.arguments ?? {}) }
111994
+ })) : [];
111995
+ const content = typeof choice?.message?.content === "string" ? choice.message.content : "";
111996
+ return {
111997
+ index: Number.isSafeInteger(choice?.index) ? choice.index : index,
111998
+ message: calls.length ? { role: "assistant", content: content || null, tool_calls: calls } : { role: "assistant", content },
111999
+ finish_reason: typeof choice?.finish_reason === "string" ? choice.finish_reason : null
112000
+ };
112001
+ });
111642
112002
  const count2 = (value2) => Number.isSafeInteger(value2) && value2 >= 0 ? value2 : 0;
111643
112003
  const usage2 = json4.usage && typeof json4.usage === "object" ? { prompt_tokens: count2(json4.usage.prompt_tokens), completion_tokens: count2(json4.usage.completion_tokens), total_tokens: count2(json4.usage.total_tokens) } : null;
111644
112004
  return {
@@ -111670,7 +112030,14 @@ async function readChatResponse(response) {
111670
112030
  fail30("inference_response_invalid", "the AI provider's answer carried no choices", { next: "try again later, or pass a different model" });
111671
112031
  }
111672
112032
  const body = sanitize(json4);
111673
- return { content: body.choices[0].message.content, finishReason: body.choices[0].finish_reason, usage: body.usage, model: body.model, body };
112033
+ return {
112034
+ content: body.choices[0].message.content ?? "",
112035
+ toolCalls: body.choices[0].message.tool_calls,
112036
+ finishReason: body.choices[0].finish_reason,
112037
+ usage: body.usage,
112038
+ model: body.model,
112039
+ body
112040
+ };
111674
112041
  }
111675
112042
  function receiptOf(response) {
111676
112043
  const raw = response.headers.get(PAYMENT_HEADER);
@@ -111707,17 +112074,30 @@ function overCapNext(entry, messages, cap, ceiling) {
111707
112074
  if (cap < USEPOD_MIN_PAYMENT_ATOMIC) {
111708
112075
  return "allow more than 0.01 USDC (the AI provider's minimum per call) plus the Shinjuku fee for this call";
111709
112076
  }
111710
- const room = cap * PER_M - entry.priceInPerMAtomic * inputTokensBound(messages);
112077
+ const room = cap * PER_M - entry.priceInPerMAtomic * inputTokensBound(messages, void 0);
111711
112078
  const fits = room > 0n ? room / entry.priceOutPerMAtomic : 0n;
111712
112079
  return fits >= 1n ? `lower max_tokens to ${fits}, or allow up to ${usdcWords(ceiling)} for this call` : `shorten the messages, or allow up to ${usdcWords(ceiling)} for this call`;
111713
112080
  }
111714
- async function inferenceChat({ payFetch, model, messages, maxTokens, temperature, maxPaymentAtomic, requestId, heldPayment: heldPayment2 = false, preparedAtomic }) {
112081
+ async function inferenceChat({
112082
+ payFetch,
112083
+ model,
112084
+ messages,
112085
+ maxTokens,
112086
+ temperature,
112087
+ maxPaymentAtomic,
112088
+ requestId,
112089
+ heldPayment: heldPayment2 = false,
112090
+ preparedAtomic,
112091
+ tools,
112092
+ toolChoice,
112093
+ parallelToolCalls
112094
+ }) {
111715
112095
  if (typeof payFetch !== "function") throw new TypeError("inferenceChat needs a payFetch function");
111716
- const { url, init } = buildChatRequest({ model, messages, maxTokens, temperature });
112096
+ const { url, init } = buildChatRequest({ model, messages, maxTokens, temperature, tools, toolChoice, parallelToolCalls });
111717
112097
  const entry = findModel(model);
111718
112098
  const clean5 = checkMessages(messages);
111719
112099
  const tokens = checkMaxTokens(maxTokens, entry.id);
111720
- const ceiling = ceilingOf(entry, clean5, tokens);
112100
+ const ceiling = ceilingOf(entry, clean5, tokens, checkTools(tools));
111721
112101
  const cap = parseCap(maxPaymentAtomic);
111722
112102
  const sendsPrepared = /^[1-9][0-9]{0,30}$/.test(String(preparedAtomic ?? ""));
111723
112103
  if (ceiling > cap && heldPayment2 !== true && !sendsPrepared) {
@@ -111767,7 +112147,7 @@ async function inferenceChat({ payFetch, model, messages, maxTokens, temperature
111767
112147
  maxTokensDefault: maxTokens === void 0 || maxTokens === null
111768
112148
  };
111769
112149
  }
111770
- var USEPOD_X402_CHAT_URL, USEPOD_MIN_PAYMENT_ATOMIC, INFERENCE_NOTICE, ROLES, MESSAGE_OVERHEAD_TOKENS, PER_M, InferenceError, fail30, modelIds, ceilDiv, spelling;
112150
+ var USEPOD_X402_CHAT_URL, USEPOD_MIN_PAYMENT_ATOMIC, INFERENCE_NOTICE, ROLES, MAX_TOOLS, TOOL_NAME, MESSAGE_OVERHEAD_TOKENS, PER_M, InferenceError, fail30, modelIds, ceilDiv, spelling;
111771
112151
  var init_inference = __esm({
111772
112152
  "wallet/src/inference/index.mjs"() {
111773
112153
  "use strict";
@@ -111777,7 +112157,9 @@ var init_inference = __esm({
111777
112157
  USEPOD_X402_CHAT_URL = "https://api.usepod.ai/proxy/x402/v1/chat/completions";
111778
112158
  USEPOD_MIN_PAYMENT_ATOMIC = 10000n;
111779
112159
  INFERENCE_NOTICE = "Each call pays the AI provider its quoted cap for max_tokens on chain (often far below 0.01 USDC; 0.01 USDC when the AI provider offers only its standard payment) plus the Shinjuku fee, and what the call does not use of that cap is not refunded to you. The AI provider and the company that runs the model see your prompt and the answer; they do not see which wallet paid.";
111780
- ROLES = Object.freeze(["system", "user", "assistant"]);
112160
+ ROLES = Object.freeze(["system", "user", "assistant", "tool"]);
112161
+ MAX_TOOLS = 128;
112162
+ TOOL_NAME = /^[A-Za-z0-9_.-]{1,64}$/;
111781
112163
  MESSAGE_OVERHEAD_TOKENS = 8n;
111782
112164
  PER_M = 1000000n;
111783
112165
  InferenceError = class extends Error {
@@ -140492,7 +140874,7 @@ __export(serve_exports, {
140492
140874
  paidOf: () => paidOf
140493
140875
  });
140494
140876
  import { createServer as createServer2 } from "node:http";
140495
- import { randomBytes as randomBytes26, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
140877
+ import { createHmac as createHmac9, randomBytes as randomBytes26, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
140496
140878
  function codeOf7(error) {
140497
140879
  if (typeof error?.code === "string" && /^[a-z0-9_]+$/.test(error.code)) return error.code;
140498
140880
  if (typeof error?.error === "string" && /^[a-z0-9_]+$/.test(error.error)) return error.error;
@@ -140735,12 +141117,135 @@ function streamOf(answer, includeUsage) {
140735
141117
  const chunk = (delta, finish = null) => ({ ...head, choices: [{ index: 0, delta, logprobs: null, finish_reason: finish }], ...usageNull });
140736
141118
  const [choice] = answer.choices;
140737
141119
  const events = [chunk({ role: "assistant", content: "" })];
140738
- const chars = Array.from(choice.message.content);
141120
+ const chars = Array.from(choice.message.content ?? "");
140739
141121
  for (let at = 0; at < chars.length; at += STREAM_CHUNK_CHARS) events.push(chunk({ content: chars.slice(at, at + STREAM_CHUNK_CHARS).join("") }));
141122
+ if (Array.isArray(choice.message.tool_calls) && choice.message.tool_calls.length) {
141123
+ events.push(chunk({ tool_calls: choice.message.tool_calls.map((call, index) => ({ index, ...call })) }));
141124
+ }
140740
141125
  events.push({ ...chunk({}, choice.finish_reason), shinjuku: answer.shinjuku });
140741
141126
  if (includeUsage) events.push({ ...head, choices: [], usage: answer.usage ?? null });
140742
141127
  return events.map(sseEvent).join("") + sseEvent("[DONE]");
140743
141128
  }
141129
+ function chatBodyOfResponses(body) {
141130
+ if (body.previous_response_id !== void 0 && body.previous_response_id !== null) {
141131
+ throw refusal2("inference_messages_invalid", "previous_response_id is not supported: this server stores no answers (the wallet keeps no copy of a private conversation), so send the whole conversation in input with store: false, as Codex does; nothing was paid", "previous_response_id");
141132
+ }
141133
+ const messages = [];
141134
+ if (typeof body.instructions === "string" && body.instructions) messages.push({ role: "system", content: body.instructions });
141135
+ const input = typeof body.input === "string" ? [{ type: "message", role: "user", content: body.input }] : body.input;
141136
+ if (!Array.isArray(input) || input.length === 0) throw refusal2("inference_messages_invalid", "input must be text or a non-empty list of items; nothing was paid", "input");
141137
+ for (const [index, item] of input.entries()) {
141138
+ const type = item?.type ?? (typeof item?.role === "string" ? "message" : void 0);
141139
+ if (type === "reasoning") continue;
141140
+ if (type === "message") {
141141
+ const role = item.role === "developer" ? "system" : item.role;
141142
+ if (!["system", "user", "assistant"].includes(role)) throw refusal2("inference_messages_invalid", `input item ${index} has role ${String(item.role).slice(0, 20)}; nothing was paid`, "input");
141143
+ if (Array.isArray(item.content) && item.content.some((part) => !TEXT_PARTS.has(part?.type))) {
141144
+ throw refusal2("inference_messages_invalid", `input item ${index} holds a part that is not text (${String(item.content.find((part) => !TEXT_PARTS.has(part?.type))?.type).slice(0, 30)}); only text reaches the AI provider here; nothing was paid`, "input");
141145
+ }
141146
+ const text3 = typeof item.content === "string" ? item.content : Array.isArray(item.content) ? textOfParts(item.content) : void 0;
141147
+ if (text3 === void 0) throw refusal2("inference_messages_invalid", `input item ${index} needs content as text; nothing was paid`, "input");
141148
+ if (text3) messages.push({ role, content: text3 });
141149
+ continue;
141150
+ }
141151
+ if (type === "function_call") {
141152
+ const call = { id: item.call_id, type: "function", function: { name: item.name, arguments: item.arguments } };
141153
+ const last = messages[messages.length - 1];
141154
+ if (last?.role === "assistant") last.tool_calls = [...last.tool_calls ?? [], call];
141155
+ else messages.push({ role: "assistant", content: null, tool_calls: [call] });
141156
+ continue;
141157
+ }
141158
+ if (type === "function_call_output") {
141159
+ const output2 = typeof item.output === "string" ? item.output : Array.isArray(item.output) ? textOfParts(item.output) : JSON.stringify(item.output ?? "");
141160
+ messages.push({ role: "tool", tool_call_id: item.call_id, content: output2 });
141161
+ continue;
141162
+ }
141163
+ throw refusal2("inference_messages_invalid", `input item ${index} has type ${String(type).slice(0, 40)}, which this server cannot send to the AI provider; nothing was paid`, "input");
141164
+ }
141165
+ if (!messages.some((message) => message.role !== "system")) throw refusal2("inference_messages_invalid", "input holds no message for the model to answer; nothing was paid", "input");
141166
+ const tools = Array.isArray(body.tools) ? body.tools.filter((tool) => tool?.type === "function").map((tool) => ({ type: "function", function: {
141167
+ name: tool.name,
141168
+ ...typeof tool.description === "string" ? { description: tool.description } : {},
141169
+ ...tool.parameters && typeof tool.parameters === "object" ? { parameters: tool.parameters } : {}
141170
+ } })) : [];
141171
+ const named = body.tool_choice?.type === "function" && tools.some((tool) => tool.function.name === body.tool_choice.name) ? { type: "function", function: { name: body.tool_choice.name } } : void 0;
141172
+ const choice = ["auto", "none", "required"].includes(body.tool_choice) ? body.tool_choice : named;
141173
+ return {
141174
+ model: body.model,
141175
+ messages,
141176
+ ...Number.isSafeInteger(body.max_output_tokens) ? { max_tokens: body.max_output_tokens } : {},
141177
+ ...typeof body.temperature === "number" ? { temperature: body.temperature } : {},
141178
+ ...tools.length ? {
141179
+ tools,
141180
+ ...choice === void 0 ? {} : { tool_choice: choice },
141181
+ ...typeof body.parallel_tool_calls === "boolean" ? { parallel_tool_calls: body.parallel_tool_calls } : {}
141182
+ } : {}
141183
+ };
141184
+ }
141185
+ function responseOf(answer) {
141186
+ const id = `resp_${String(answer.shinjuku?.request_id ?? randomBytes26(8).toString("hex")).replace(/[^A-Za-z0-9_-]/g, "_")}`;
141187
+ const message = answer.choices[0].message;
141188
+ const output2 = [];
141189
+ const calls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
141190
+ if (typeof message.content === "string" && message.content || !calls.length) {
141191
+ output2.push({
141192
+ type: "message",
141193
+ id: `msg_${id.slice(5)}`,
141194
+ status: "completed",
141195
+ role: "assistant",
141196
+ content: [{ type: "output_text", text: message.content ?? "", annotations: [] }]
141197
+ });
141198
+ }
141199
+ for (const call of calls) {
141200
+ output2.push({ type: "function_call", id: `fc_${call.id}`, call_id: call.id, name: call.function.name, arguments: call.function.arguments, status: "completed" });
141201
+ }
141202
+ const usage2 = answer.usage;
141203
+ return {
141204
+ id,
141205
+ object: "response",
141206
+ created_at: answer.created,
141207
+ status: "completed",
141208
+ model: answer.model,
141209
+ output: output2,
141210
+ usage: usage2 ? {
141211
+ input_tokens: usage2.prompt_tokens,
141212
+ input_tokens_details: { cached_tokens: 0 },
141213
+ output_tokens: usage2.completion_tokens,
141214
+ output_tokens_details: { reasoning_tokens: 0 },
141215
+ total_tokens: usage2.total_tokens
141216
+ } : null,
141217
+ shinjuku: answer.shinjuku
141218
+ };
141219
+ }
141220
+ function responseStreamOf(response) {
141221
+ let sequence = 0;
141222
+ const event = (type, fields) => `event: ${type}
141223
+ data: ${JSON.stringify({ type, sequence_number: sequence++, ...fields })}
141224
+
141225
+ `;
141226
+ const shell = { ...response, status: "in_progress", output: [], usage: null };
141227
+ let text3 = event("response.created", { response: shell }) + event("response.in_progress", { response: shell });
141228
+ response.output.forEach((item, outputIndex) => {
141229
+ if (item.type === "message") {
141230
+ const whole = item.content[0]?.text ?? "";
141231
+ const part = { type: "output_text", text: "", annotations: [] };
141232
+ text3 += event("response.output_item.added", { output_index: outputIndex, item: { ...item, status: "in_progress", content: [] } });
141233
+ text3 += event("response.content_part.added", { item_id: item.id, output_index: outputIndex, content_index: 0, part });
141234
+ const chars = Array.from(whole);
141235
+ for (let at = 0; at < chars.length; at += STREAM_CHUNK_CHARS) {
141236
+ text3 += event("response.output_text.delta", { item_id: item.id, output_index: outputIndex, content_index: 0, delta: chars.slice(at, at + STREAM_CHUNK_CHARS).join("") });
141237
+ }
141238
+ text3 += event("response.output_text.done", { item_id: item.id, output_index: outputIndex, content_index: 0, text: whole });
141239
+ text3 += event("response.content_part.done", { item_id: item.id, output_index: outputIndex, content_index: 0, part: { ...part, text: whole } });
141240
+ } else {
141241
+ text3 += event("response.output_item.added", { output_index: outputIndex, item: { ...item, status: "in_progress", arguments: "" } });
141242
+ text3 += event("response.function_call_arguments.delta", { item_id: item.id, output_index: outputIndex, delta: item.arguments });
141243
+ text3 += event("response.function_call_arguments.done", { item_id: item.id, output_index: outputIndex, arguments: item.arguments });
141244
+ }
141245
+ text3 += event("response.output_item.done", { output_index: outputIndex, item });
141246
+ });
141247
+ return text3 + event("response.completed", { response });
141248
+ }
140744
141249
  function sendStream(res, text3) {
140745
141250
  res.writeHead(200, { "content-type": "text/event-stream; charset=utf-8", "content-length": Buffer.byteLength(text3), "cache-control": "no-store" });
140746
141251
  res.end(text3);
@@ -140785,6 +141290,7 @@ function createInferenceServer({
140785
141290
  const counted = /* @__PURE__ */ new Map();
140786
141291
  let queue = Promise.resolve();
140787
141292
  let count2 = 0;
141293
+ const retrySecret = randomBytes26(32);
140788
141294
  let boundPort = port;
140789
141295
  const hostAllowed = (host) => host === `${INFERENCE_SERVE_HOST}:${boundPort}` || host === `localhost:${boundPort}`;
140790
141296
  function authorized(header) {
@@ -140846,7 +141352,8 @@ function createInferenceServer({
140846
141352
  throw refusal2("inference_ceiling_over_cap", `a payment of ${usdcWords(preparedAtomic)} is prepared for this Idempotency-Key and not sent, above this server's limit per request (${usdcWords(perRequestCap)}); nothing was paid. To send it, ${restartStep(preparedAtomic)}. If you no longer want it, close it: run ${commandLine(`cancel --cancel-request ${requestId}`)} in a terminal (nothing was sent, so nothing is lost)`, null);
140847
141353
  }
140848
141354
  const messages = body.messages;
140849
- const ceiling = typeof inference.ceilingAtomic === "function" ? BigInt(inference.ceilingAtomic({ model: body.model, messages, maxTokens })) : void 0;
141355
+ const tools = body.tools === void 0 || body.tools === null ? {} : { tools: body.tools, toolChoice: body.tool_choice, parallelToolCalls: body.parallel_tool_calls };
141356
+ const ceiling = typeof inference.ceilingAtomic === "function" ? BigInt(inference.ceilingAtomic({ model: body.model, messages, maxTokens, tools: tools.tools })) : void 0;
140850
141357
  if (!held && preparedAtomic === void 0 && ceiling !== void 0 && ceiling > perRequestCap) {
140851
141358
  const floor = BigInt(inference.USEPOD_MIN_PAYMENT_ATOMIC ?? 0n);
140852
141359
  const belowFloor = perRequestCap < floor;
@@ -140880,6 +141387,7 @@ function createInferenceServer({
140880
141387
  messages,
140881
141388
  maxTokens,
140882
141389
  ...body.temperature === void 0 ? {} : { temperature: body.temperature },
141390
+ ...tools,
140883
141391
  maxPaymentAtomic: perRequestCap,
140884
141392
  requestId,
140885
141393
  ...held ? { heldPayment: true } : preparedAtomic !== void 0 ? { preparedAtomic: preparedAtomic.toString() } : {}
@@ -140930,7 +141438,7 @@ function createInferenceServer({
140930
141438
  object: "chat.completion",
140931
141439
  created: Math.floor(now() / 1e3),
140932
141440
  model: result.model ?? body.model,
140933
- choices: [{ index: 0, message: { role: "assistant", content: result.content ?? "" }, finish_reason: result.finishReason ?? "stop" }],
141441
+ choices: [{ index: 0, message: Array.isArray(result.toolCalls) && result.toolCalls.length ? { role: "assistant", content: result.content || null, tool_calls: result.toolCalls } : { role: "assistant", content: result.content ?? "" }, finish_reason: result.finishReason ?? "stop" }],
140934
141442
  ...usageOf(result.usage) ? { usage: usageOf(result.usage) } : {},
140935
141443
  shinjuku: {
140936
141444
  request_id: result.requestId ?? requestId,
@@ -140992,8 +141500,9 @@ ${choice.message.content ?? ""}`;
140992
141500
  }
140993
141501
  const path = new URL(req.url ?? "/", `http://${INFERENCE_SERVE_HOST}`).pathname.replace(/\/+$/, "");
140994
141502
  if (path === "/v1/models" && req.method === "GET") return send2(res, 200, models());
140995
- if (path === "/v1/chat/completions" && req.method === "POST") {
140996
- const key = req.headers["idempotency-key"];
141503
+ const route = req.method !== "POST" ? void 0 : path === "/v1/chat/completions" ? "chat" : path === "/v1/responses" ? "responses" : void 0;
141504
+ if (route) {
141505
+ let key = req.headers["idempotency-key"];
140997
141506
  if (key !== void 0 && (typeof key !== "string" || !IDEMPOTENCY_KEY.test(key))) {
140998
141507
  return send2(res, 400, { error: {
140999
141508
  message: "the Idempotency-Key header must be 1-64 characters of A-Z a-z 0-9 _ -; nothing was paid. Example: Idempotency-Key: chat-2026-001",
@@ -141016,16 +141525,23 @@ ${choice.message.content ?? ""}`;
141016
141525
  return send2(res, status, out, NO_RETRY);
141017
141526
  };
141018
141527
  let body;
141528
+ let chatBody;
141019
141529
  try {
141020
141530
  body = await readJson3(req);
141531
+ chatBody = route === "responses" ? chatBodyOfResponses(body) : body;
141021
141532
  } catch (error) {
141022
141533
  return refused(error);
141023
141534
  }
141024
- const run4 = queue.then(() => chat(body, key));
141535
+ if (route === "responses" && key === void 0) key = `r${createHmac9("sha256", retrySecret).update(JSON.stringify(body)).digest("hex").slice(0, 40)}`;
141536
+ const run4 = queue.then(() => chat(chatBody, key));
141025
141537
  queue = run4.catch(() => {
141026
141538
  });
141027
141539
  try {
141028
- const answer = withNotices(await run4, body);
141540
+ const answer = withNotices(await run4, chatBody);
141541
+ if (route === "responses") {
141542
+ const response = responseOf(answer);
141543
+ return body.stream === true ? sendStream(res, responseStreamOf(response)) : send2(res, 200, response);
141544
+ }
141029
141545
  if (body.stream === true) return sendStream(res, streamOf(answer, body.stream_options?.include_usage === true));
141030
141546
  return send2(res, 200, answer);
141031
141547
  } catch (error) {
@@ -141033,7 +141549,7 @@ ${choice.message.content ?? ""}`;
141033
141549
  }
141034
141550
  }
141035
141551
  return send2(res, 404, {
141036
- error: { message: `no route ${req.method} ${path || "/"}; this server answers GET /v1/models and POST /v1/chat/completions`, type: OPENAI_TYPE.request, param: null, code: null }
141552
+ error: { message: `no route ${req.method} ${path || "/"}; this server answers GET /v1/models, POST /v1/chat/completions and POST /v1/responses`, type: OPENAI_TYPE.request, param: null, code: null }
141037
141553
  });
141038
141554
  }
141039
141555
  const server = createServer2((req, res) => {
@@ -141068,7 +141584,7 @@ ${choice.message.content ?? ""}`;
141068
141584
  token
141069
141585
  };
141070
141586
  }
141071
- var INFERENCE_SERVE_HOST, INFERENCE_SERVE_PORT, SERVE_API_KEY_MIN_LENGTH, BODY_LIMIT_BYTES, STREAM_CHUNK_CHARS, IDEMPOTENCY_KEY, NO_RETRY, REQUEST_CODES, SESSION_CAP_CODE, FLOAT_REFUSED_FIRST, FLOAT_LATER, REQUEST_ID_TAKEN, SERVE_CONFLICT_TERMS, SERVE_FLOAT_TERMS, OPENAI_TYPE, OPENAI_CODE, bodyCodeOf, ServeRefusal, refusal2, sseEvent;
141587
+ var INFERENCE_SERVE_HOST, INFERENCE_SERVE_PORT, SERVE_API_KEY_MIN_LENGTH, BODY_LIMIT_BYTES, STREAM_CHUNK_CHARS, IDEMPOTENCY_KEY, NO_RETRY, REQUEST_CODES, SESSION_CAP_CODE, FLOAT_REFUSED_FIRST, FLOAT_LATER, REQUEST_ID_TAKEN, SERVE_CONFLICT_TERMS, SERVE_FLOAT_TERMS, OPENAI_TYPE, OPENAI_CODE, bodyCodeOf, ServeRefusal, refusal2, sseEvent, TEXT_PARTS, textOfParts;
141072
141588
  var init_serve = __esm({
141073
141589
  "wallet/src/inference/serve.mjs"() {
141074
141590
  "use strict";
@@ -141092,6 +141608,7 @@ var init_serve = __esm({
141092
141608
  "inference_stream_unsupported",
141093
141609
  "inference_model_unknown",
141094
141610
  "inference_messages_invalid",
141611
+ "inference_tools_invalid",
141095
141612
  "inference_temperature_invalid",
141096
141613
  "inference_ceiling_over_cap"
141097
141614
  ]);
@@ -141139,6 +141656,8 @@ var init_serve = __esm({
141139
141656
  sseEvent = (value2) => `data: ${typeof value2 === "string" ? value2 : JSON.stringify(value2)}
141140
141657
 
141141
141658
  `;
141659
+ TEXT_PARTS = /* @__PURE__ */ new Set(["input_text", "output_text", "text"]);
141660
+ textOfParts = (parts) => parts.filter((part) => TEXT_PARTS.has(part?.type) && typeof part.text === "string").map((part) => part.text).join("\n");
141142
141661
  }
141143
141662
  });
141144
141663
 
@@ -142684,17 +143203,21 @@ When it says ready, type /retry: it asks the same question again.` : receivedOnl
142684
143203
  return;
142685
143204
  }
142686
143205
  let prepared;
143206
+ let neverLeft = false;
142687
143207
  if (!surelyNothing) {
142688
143208
  try {
142689
143209
  const kept2 = keptPayment(session.openStore(), turn.requestId);
142690
- if (kept2?.prepared === true) prepared = /^[1-9][0-9]{0,30}$/.test(String(kept2.amountAtomic ?? "")) ? ` of ${usdcWords(BigInt(kept2.amountAtomic))}` : "";
143210
+ if (kept2 === void 0 || kept2.committed !== true || kept2.cancelled === true) neverLeft = true;
143211
+ else if (kept2.prepared === true) prepared = /^[1-9][0-9]{0,30}$/.test(String(kept2.amountAtomic ?? "")) ? ` of ${usdcWords(BigInt(kept2.amountAtomic))}` : "";
142691
143212
  } catch {
142692
143213
  prepared = void 0;
143214
+ neverLeft = false;
142693
143215
  }
142694
143216
  }
142695
- const again = surelyNothing ? "ask again" : prepared !== void 0 ? "type /retry (it sends that same payment, never a second one)" : "type /retry (it finishes the same payment and never pays twice)";
142696
- if (!surelyNothing) state.pending = turn;
142697
- const paidWords = surelyNothing ? "Nothing was paid." : prepared !== void 0 ? `Nothing was paid: a payment${prepared} is prepared for this question and not sent yet.` : "It may be paid already.";
143217
+ const nothing = surelyNothing || neverLeft;
143218
+ const again = nothing ? "ask again" : prepared !== void 0 ? "type /retry (it sends that same payment, never a second one)" : "type /retry (it finishes the same payment and never pays twice)";
143219
+ if (!nothing) state.pending = turn;
143220
+ const paidWords = nothing ? "Nothing was paid." : prepared !== void 0 ? `Nothing was paid: a payment${prepared} is prepared for this question and not sent yet.` : "It may be paid already.";
142698
143221
  const closeOtherwise = prepared === void 0 ? "" : ` If you no longer want it, close it: in another terminal, run ${commandLine(`cancel --cancel-request ${turn.requestId}`)} (nothing was sent, so nothing is lost).`;
142699
143222
  if (code2 === "inference_tor_required" || code2 === "ECONNREFUSED" || proxyRefusedConnection(error)) {
142700
143223
  say3(`Your private connection (Tor) stopped answering, so the question could not go out. ${paidWords} Start Tor again, then ${again}.${closeOtherwise}`);
@@ -142710,6 +143233,12 @@ When it says ready, type /retry: it asks the same question again.` : receivedOnl
142710
143233
  say3(`The AI provider did not send a chat answer. ${paidWords} Wait a moment and ${again}, or try another model (/model).${closeOtherwise}`);
142711
143234
  } else if (WAIT_CODES.test(code2 ?? "")) {
142712
143235
  say3(`The payment did not finish yet (the wallet or the network is busy). ${paidWords} Wait a moment, then ${again}.${closeOtherwise}`);
143236
+ } else if (HISTORY_CODES.test(code2 ?? "") || HISTORY_CODES.test(String(error?.message ?? ""))) {
143237
+ try {
143238
+ (typeof session.timing === "function" ? session.timing() : void 0)?.("chat-answer-failed", code2 ?? "history_rpc_failed");
143239
+ } catch {
143240
+ }
143241
+ say3(`The pool's public history did not answer in time over Tor (a slow Tor route)${nothing ? ", so the payment could not start" : ""}. ${paidWords} Wait a moment, then ${again}.${closeOtherwise}`);
142713
143242
  } else {
142714
143243
  try {
142715
143244
  const logged = ownCodeWords(error).split(":")[0];
@@ -142717,7 +143246,7 @@ When it says ready, type /retry: it asks the same question again.` : receivedOnl
142717
143246
  } catch {
142718
143247
  }
142719
143248
  const own = error?.name === "InferenceError" && SELF_TEACHING_CODES.test(code2 ?? "") && typeof error.detail === "string" && error.detail ? error.detail.replace(/[;.]?\s*nothing was (?:sent or )?paid\.?$/i, "") : void 0;
142720
- say3(`The answer failed${own ? `: ${own}` : " for a reason this chat has no plain words for yet"}. ${paidWords} ${surelyNothing ? "Ask again, or try another model (/model)." : prepared !== void 0 ? "Type /retry to send it: it sends that same payment, never a second one." : "Type /retry to ask the same again: it never pays twice."}${closeOtherwise}`);
143249
+ say3(`The answer failed${own ? `: ${own}` : " for a reason this chat has no plain words for yet"}. ${paidWords} ${nothing ? "Ask again, or try another model (/model)." : prepared !== void 0 ? "Type /retry to send it: it sends that same payment, never a second one." : "Type /retry to ask the same again: it never pays twice."}${closeOtherwise}`);
142721
143250
  }
142722
143251
  };
142723
143252
  const command = async (text3) => {
@@ -142784,7 +143313,7 @@ When it says ready, type /retry: it asks the same question again.` : receivedOnl
142784
143313
  await session.close();
142785
143314
  }
142786
143315
  }
142787
- var DEFAULT_MODEL2, CHAT_DEFAULT_MODEL, CHAT_MAX_TOKENS, CHAT_SHORT_TOKENS, DEFAULT_ANSWER_CAP_ATOMIC, DEFAULT_CHAT_CAP_ATOMIC, CHEAPEST_MODEL, STILL_WAITING_MS, higherCap, shortInChat, POSITIVE_ATOMIC9, SHORT_QUESTION_TOKENS, PASTE_JOIN_MS, CAP_CODES, WAIT_CODES, NO_ANSWER_CODES, chatFloatTerms, floatRetry, floatSpent, asSentence, upFirst, lowFirst, NOTHING_PAID, CAP_FROM, PROGRESS_LINE, SHOWN_PROGRESS, isProgressLine, fail46, nothingPaid;
143316
+ var DEFAULT_MODEL2, CHAT_DEFAULT_MODEL, CHAT_MAX_TOKENS, CHAT_SHORT_TOKENS, DEFAULT_ANSWER_CAP_ATOMIC, DEFAULT_CHAT_CAP_ATOMIC, CHEAPEST_MODEL, STILL_WAITING_MS, higherCap, shortInChat, POSITIVE_ATOMIC9, SHORT_QUESTION_TOKENS, PASTE_JOIN_MS, CAP_CODES, WAIT_CODES, NO_ANSWER_CODES, HISTORY_CODES, chatFloatTerms, floatRetry, floatSpent, asSentence, upFirst, lowFirst, NOTHING_PAID, CAP_FROM, PROGRESS_LINE, SHOWN_PROGRESS, isProgressLine, fail46, nothingPaid;
142788
143317
  var init_chat = __esm({
142789
143318
  "wallet/src/inference/chat.mjs"() {
142790
143319
  "use strict";
@@ -142828,6 +143357,7 @@ var init_chat = __esm({
142828
143357
  CAP_CODES = /^(spend_payment_cap_exceeded|mcp_session_cap_exceeded|mcp_cap_argument_above_launch_cap|p03_float_over_maximum)$/;
142829
143358
  WAIT_CODES = /_retry_same_request$|_retry_same_payment$|_retry_later$|^wallet_locked$|another_request_unresolved$/;
142830
143359
  NO_ANSWER_CODES = /^inference_(upstream_failed|response_invalid)$/;
143360
+ HISTORY_CODES = /\b(?:history_rpc_failed|history_source_silent|compact_history_source_unavailable)\b/;
142831
143361
  chatFloatTerms = () => ({
142832
143362
  again: "Type /retry",
142833
143363
  rerun: "Ask again",
@@ -149427,10 +149957,27 @@ function agentHostsOf(env, home) {
149427
149957
  const config = readJsonFile(hostConfigFile(target, { env, home: homedir2() }));
149428
149958
  return config === void 0 ? false : config === null ? null : runsThisWallet(config.mcpServers, home);
149429
149959
  };
149960
+ const codexHost = () => {
149961
+ const file = hostConfigFile("codex", { env, home: homedir2() });
149962
+ let size;
149963
+ try {
149964
+ size = statSync(file).size;
149965
+ } catch (error) {
149966
+ return error?.code === "ENOENT" ? false : null;
149967
+ }
149968
+ if (size > HOST_CONFIG_MAX_BYTES) return null;
149969
+ try {
149970
+ const found = codexServersIn(readFileSync(file, "utf8"), [MCP_SERVER_NAME, ...OLD_MCP_SERVER_NAMES]);
149971
+ return found.unreadable ? null : runsThisWallet(found.servers, home);
149972
+ } catch {
149973
+ return null;
149974
+ }
149975
+ };
149430
149976
  return [
149431
149977
  { app: "Claude Code", ...claudeCodeState(env, home) },
149432
149978
  { app: "Claude Desktop", linked: jsonHost("claude-desktop") },
149433
- { app: "Cursor", linked: jsonHost("cursor") }
149979
+ { app: "Cursor", linked: jsonHost("cursor") },
149980
+ { app: "Codex", linked: codexHost() }
149434
149981
  ];
149435
149982
  }
149436
149983
  function readHomeData({ env = process.env, walletVersion: walletVersion2, torRun } = {}) {
@@ -150612,7 +151159,21 @@ var localAiPasteLines = (answer) => [
150612
151159
  ];
150613
151160
  var localAiRestartLine = () => `It stops when the computer restarts: then run ${cli2()} infer start again; the api key stays the same.`;
150614
151161
  var requestsWords = (count2) => `${count2 ?? 0} request${count2 === 1 ? "" : "s"}`;
150615
- var LOCAL_AI_APPS_LINE = "It serves the OpenAI Chat Completions API (/v1/chat/completions, streaming too) and /v1/models. Apps that use the OpenAI Responses API (/v1/responses) do not work with it yet.";
151162
+ var localAiAppsLines = (answer) => [
151163
+ "It serves the OpenAI Chat Completions API (/v1/chat/completions, streaming and function tools too), the OpenAI Responses API (/v1/responses, which Codex uses) and /v1/models.",
151164
+ "A whole Codex session on it: put these lines in the file shinjuku.config.toml in your Codex folder (~/.codex):",
151165
+ ` model = "${LOCAL_AI_APP_MODEL}"`,
151166
+ ' model_provider = "shinjuku"',
151167
+ " [model_providers.shinjuku]",
151168
+ ' name = "Shinjuku private AI"',
151169
+ ` base_url = "${answer.baseUrl}"`,
151170
+ ' env_key = "SHINJUKU_AI_KEY"',
151171
+ ' wire_api = "responses"',
151172
+ // CX3 (live, npm 0.3.134, 2026-10-31): Codex pays once per model call, and one turn makes several (PrivAI: a turn with 2 tool
151173
+ // calls made 4 paid calls, 0.0208 USDC, 2 min 28 s over Tor; mcp66: a one-sentence turn with no tool made 2, 0.009792 USDC).
151174
+ "Set SHINJUKU_AI_KEY to the api key above, then start it with: codex --profile shinjuku. Codex pays once per model call, and one turn can make several: about 0.005 USDC each with the fee on qwen3-8-flash (a short turn paid about 0.01 USDC; a turn with 2 tool calls paid about 0.021 USDC). Your other Codex sessions stay as they are."
151175
+ ];
151176
+ var localAiCodexHint = () => `For a Codex session on this address, run: ${cli2()} infer status --verbose`;
150616
151177
  var LOCAL_AI_CAP_SOURCE = { setup: "from your limits", default: "default", flag: "given at start" };
150617
151178
  var localAiCapSource = (caps, name) => LOCAL_AI_CAP_SOURCE[caps?.source?.[name]] ? ` (${LOCAL_AI_CAP_SOURCE[caps.source[name]]})` : "";
150618
151179
  var localAiDayLimitWords = (limits) => limits?.maxSessionAtomic === void 0 ? "" : `, and your limit of ${usdcOr(limits.maxSessionAtomic)} in any 24 hours counts every payment from this wallet`;
@@ -150736,7 +151297,7 @@ async function runInferStart(values, deps) {
150736
151297
  answer.state === "alive" ? `The local AI server of this wallet runs already${verbose ? ` (pid ${answer.pid}${since})` : ""}, so nothing new was started.` : `The local AI server runs in the background now${verbose ? ` (pid ${answer.pid})` : ""}, on this computer only, behind Tor. It keeps running after this terminal closes.`,
150737
151298
  "Put these lines into your agent app (as an OpenAI-compatible provider):",
150738
151299
  ...localAiPasteLines(answer),
150739
- ...verbose ? [LOCAL_AI_APPS_LINE] : [],
151300
+ ...verbose ? localAiAppsLines(answer) : [localAiCodexHint()],
150740
151301
  `Caps: ${localAiCapsText(answer.caps, answer.limits)}. It pays from your private balance.`,
150741
151302
  ...localAiFloorLines(answer.caps, USEPOD_MIN_PAYMENT_ATOMIC2, { limits: answer.limits }),
150742
151303
  ...localAiLowBalanceLines(values, deps, walletFile),
@@ -150770,7 +151331,7 @@ async function runInferStatus(values, deps) {
150770
151331
  `The local AI server runs${verbose ? ` (pid ${status.pid}${status.startedAt ? `, since ${status.startedAt}` : ""})` : ""}, on this computer only, behind Tor.`,
150771
151332
  "Your agent app uses these lines:",
150772
151333
  ...localAiPasteLines(status),
150773
- ...verbose ? [LOCAL_AI_APPS_LINE] : [],
151334
+ ...verbose ? localAiAppsLines(status) : [localAiCodexHint()],
150774
151335
  `Caps: ${localAiCapsText(status.caps, status.limits)}. Paid so far: ${usdcOr(status.spentAtomic ?? "0")} for ${requestsWords(status.requests)}.`,
150775
151336
  ...localAiFloorLines(status.caps, USEPOD_MIN_PAYMENT_ATOMIC2, { limits: status.limits }),
150776
151337
  ...verbose ? [...localAiDefaultCapsLine(status.caps, { limits: status.limits }), await localAiRequestLine(status.caps, deps)] : [],
@@ -151481,7 +152042,8 @@ function privateInferencePath(config) {
151481
152042
  }
151482
152043
  function agentAppLines({ skip = /* @__PURE__ */ new Set() }) {
151483
152044
  const lines = [];
151484
- for (const [target, app] of [["claude-code", "Claude Code"], ["claude-desktop", "Claude Desktop"], ["cursor", "Cursor"]]) {
152045
+ for (const target of HOST_TARGETS) {
152046
+ const app = target === "codex" ? "Codex (the Codex app or Codex CLI)" : HOST_NAMES[target];
151485
152047
  if (!skip.has(target)) lines.push(`${app}, run this once (setup adds the wallet there):`, ` ${cli2()} setup --add-to ${target}`);
151486
152048
  }
151487
152049
  return lines.join("\n");
@@ -151940,13 +152502,13 @@ async function addToHosts(targets, home, deps, { force = false, npmVersion, ask
151940
152502
  continue;
151941
152503
  }
151942
152504
  const file = hostConfigFile(target, { ...options, home: deps.homedir() });
151943
- const app = target === "cursor" ? "Cursor" : "Claude Desktop";
152505
+ const app = HOST_NAMES[target];
151944
152506
  try {
151945
- const added = addToJsonHost(file, mcpServerEntry(options), { force });
152507
+ const added = (target === "codex" ? addToCodexHost : addToJsonHost)(file, mcpServerEntry(options), { force });
151946
152508
  for (const old of added.replaced ?? []) io.out(`Replaced the old ${old} entry in ${app}.
151947
152509
  `);
151948
152510
  io.out(!added.changed ? `${app} already has the wallet: ${file} (nothing changed).
151949
- ` : `Added the wallet to ${app}: ${file}${added.backup ? ` (the old file was copied to ${added.backup}, readable by you alone)` : ""}. ${RESTART_APP(app)}
152511
+ ` : `Added the wallet to ${app}: ${file}${added.backup ? ` (the old file was copied to ${added.backup}, readable by you alone)` : ""}. ${RESTART_APP(target === "codex" ? "the Codex app or Codex CLI" : app)}${target === "codex" ? ` In Codex, type /mcp to see the wallet's tools, then ask in plain words, for example "what is my Shinjuku balance".` : ""}
151950
152512
  `);
151951
152513
  done.add(target);
151952
152514
  } catch (error) {
@@ -153231,7 +153793,7 @@ var COMMANDS = [
153231
153793
  flag2("--own-address", "<address>", `optional, in your own terminal only (the same as the answer to setup's address question): your own wallet address (Phantom, Solflare, an exchange's deposit address), for sending money back to yourself: the MCP sends to it without asking each time (as mcp --unshield-to), also in an agent app that cannot show a question. Not this wallet's own key (the address this wallet itself receives on). Refused in a script, a pipe, or an agent's tool (no terminal), also with --yes: an agent must never approve an address. A rerun adds it to the ones config.json records (at most ${MAX_OWN_ADDRESSES})`),
153232
153794
  flag2("--passphrase-file", "<file>", "your own passphrase file (8 or more characters); default: setup writes a new random passphrase to <home>/passphrase.txt, readable by you alone. Needed for a wallet that exists already"),
153233
153795
  flag2("--facilitator", "<https origin>", `the server whose release, pool, and setup files setup uses; default ${GUIDE.facilitator}`, { check: "origin" }),
153234
- flag2("--add-to", "<claude-code|claude-desktop|cursor>", `also add the server (npx -y --no-audit --no-fund ${NPX_AT_VERSION} mcp: the host starts this npm version; a wallet not installed from npm writes shinjuku-shield without a version) to this agent host's config; repeat it for more. Without it, setup prints the configs`, { repeat: true }),
153796
+ flag2("--add-to", "<claude-code|claude-desktop|cursor|codex>", `also add the server (npx -y --no-audit --no-fund ${NPX_AT_VERSION} mcp: the host starts this npm version; a wallet not installed from npm writes shinjuku-shield without a version) to this agent host's config; repeat it for more. Without it, setup prints the configs`, { repeat: true }),
153235
153797
  // 0.3.97 key rename: the host key is MCP_SERVER_NAME; the old keys go by themselves.
153236
153798
  bool2("--force", `with --add-to: replace a different ${MCP_SERVER_NAME} entry already in a JSON host config (the old file is backed up first, mode 0600), or in Claude Code (claude mcp remove of that one server, then add). An old ${OLD_MCP_SERVER_NAMES.join(" or ")} entry is replaced by itself, without --force`),
153237
153799
  flag2("--trust-proof-tools", "<sha256>", `ADVANCED: install the set of setup files whose SHA256SUMS has this SHA-256 instead of the set this wallet build pins (needed for a server the build does not pin). Check the set out of band first; the normal fix for a new set is to update the wallet: ${UPDATE_SETUP}`)
@@ -153250,6 +153812,7 @@ var COMMANDS = [
153250
153812
  `The setup files are the set this wallet build PINS (its SHA256SUMS hash is in the wallet; --trust-proof-tools replaces it). A server whose /api/wallet/release names another set is refused (setup_proof_tools_pin_mismatch; to update the wallet, ${UPDATE_SETUP}). SHA256SUMS must have the pinned SHA-256, and every file must have the SHA-256 its line names, as /skill.md section 7b; bin/ and house/bin/ get the execute bit. A file that does not match is not kept. Each download has a hard size limit.`,
153251
153813
  "Your own --passphrase-file must be private: on Linux and macOS setup refuses a file that group or other may read or write, or that another user owns (setup_passphrase_file_insecure: chmod 600 <file>). On Windows setup cannot read the access list; it accepts the file with a warning.",
153252
153814
  `--add-to for Claude Desktop or Cursor: a host config whose mcpServers is not a JSON object, or that has a different ${MCP_SERVER_NAME} entry (without --force), is left alone. Otherwise the old file is copied to <file>.bak-<time> (mode 0600 on Linux and macOS; on Windows the folder's access list) and the new file replaces it in one rename. An entry an older setup wrote (no version, another version, or an old package name, shinjuku or shinjuku-shielded; the same home) is replaced without --force, in a JSON host and in Claude Code. An entry under an old key (${OLD_MCP_SERVER_NAMES.join(" or ")}) is replaced by itself, in every host, so the host never starts two wallet servers. For Claude Code, a different ${MCP_SERVER_NAME} server (not an older entry of this wallet) needs --force.`,
153815
+ `--add-to codex: the Codex app and Codex CLI read one file, config.toml in CODEX_HOME (else ~/.codex). Setup writes the [mcp_servers.${MCP_SERVER_NAME}] tables at its end with startup_timeout_sec = 120 (a first start downloads the wallet) and tool_timeout_sec = 300, and keeps every other line; the same rules as a JSON host (a different entry stays without --force; the old file is backed up first). Then type /mcp in Codex to see the tools.`,
153253
153816
  "The provers are Linux programs. Linux: ready. Windows: the wallet runs them through WSL; setup checks that wsl.exe runs (wsl --install -d Ubuntu otherwise). macOS: not supported; setup says so and creates nothing.",
153254
153817
  "Run it again at any time: it never changes an existing wallet, keeps the recorded caps unless you pass new ones, checks every setup file again, downloads what is missing or newer, and rewrites config.json.",
153255
153818
  `A wallet that ${CLI_WORD} restore made and did not read back yet (the restore stopped): setup reads its money back from the chain in place of the add-money question, so setup finishes that restore.`,
@@ -153888,7 +154451,7 @@ function shortHelpText() {
153888
154451
  "Everyday commands:",
153889
154452
  ...rows2.map(([word, about]) => ` ${word.padEnd(width)}${about}`),
153890
154453
  "",
153891
- "Add the wallet to your agent app (claude-code, claude-desktop, or cursor):",
154454
+ "Add the wallet to your agent app (claude-code, claude-desktop, cursor, or codex):",
153892
154455
  ` ${cli2()} setup --add-to claude-code`,
153893
154456
  "",
153894
154457
  `One command, with an example: ${cli2()} help <command>`,
@@ -156859,7 +157422,7 @@ async function runShinjukuWallet(argv2, overrides = {}) {
156859
157422
  }
156860
157423
  return job(["curl", "--url", link2]);
156861
157424
  }
156862
- const hostNames = { "claude-code": "Claude Code", "claude-desktop": "Claude Desktop", cursor: "Cursor" };
157425
+ const hostNames = HOST_NAMES;
156863
157426
  io.err(`Which agent app gets the wallet?
156864
157427
  ${HOST_TARGETS.map((host, index) => ` ${index + 1} ${hostNames[host] ?? host}`).join("\n")}
156865
157428
  `);