shinjuku-shield 0.3.133 → 0.3.134

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.134. 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.134
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.134 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.134 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.134", "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": "4a323f156e4f709e57aa52c578de19b1cbb5845f87133e47f3595eabfd736dc0",
5
+ "bytes": 8895185,
6
+ "sourceCommit": "d481787ba3734806ef6b3f2893720d14e2c69310",
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:25:55.132Z"
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.134",
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": "4a323f15",
7
+ "shinjukuSha256": "4a323f156e4f709e57aa52c578de19b1cbb5845f87133e47f3595eabfd736dc0",
8
8
  "license": "SEE LICENSE IN LICENSE.txt",
9
9
  "author": "Shinjuku Shielded",
10
10
  "homepage": "https://github.com/ShinjukuStaition/shinjuku-shield#readme",
@@ -65808,6 +65808,7 @@ var init_errorCodes = __esm({
65808
65808
  "inference_max_tokens_required",
65809
65809
  "inference_max_tokens_too_low",
65810
65810
  "inference_messages_invalid",
65811
+ "inference_tools_invalid",
65811
65812
  "inference_model_unknown",
65812
65813
  "inference_no_provider",
65813
65814
  "inference_origin_refused",
@@ -72584,6 +72585,7 @@ function hostShellWord(word, platform = process.platform) {
72584
72585
  }
72585
72586
  function hostConfigFile(target, { platform = process.platform, env = process.env, home = homedir() } = {}) {
72586
72587
  if (target === "cursor") return join11(home, ".cursor", "mcp.json");
72588
+ if (target === "codex") return join11(env.CODEX_HOME || join11(home, ".codex"), "config.toml");
72587
72589
  if (target === "claude-desktop") {
72588
72590
  if (platform === "win32") return join11(env.APPDATA || join11(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json");
72589
72591
  if (platform === "darwin") return join11(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -72596,9 +72598,264 @@ function hostConfigText({ home, env = process.env, platform = process.platform,
72596
72598
  const files = [["claude-desktop", "Claude Desktop (claude_desktop_config.json)"], ["cursor", "Cursor (~/.cursor/mcp.json)"]].filter(([target]) => !skip.has(target)).map(([, label]) => label);
72597
72599
  return [
72598
72600
  ...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}`)] : []
72601
+ ...files.length ? [`${files.join(" or ")}, inside "mcpServers":`, ...json4.split("\n").map((line) => ` ${line}`)] : [],
72602
+ ...skip.has("codex") ? [] : [
72603
+ "Codex (the Codex app and Codex CLI), at the end of ~/.codex/config.toml:",
72604
+ ...codexTomlBlock(mcpServerEntry({ home, env, npmVersion })).trimEnd().split("\n").map((line) => ` ${line}`)
72605
+ ]
72600
72606
  ].join("\n");
72601
72607
  }
72608
+ function codexTomlBlock(entry) {
72609
+ const lines = [
72610
+ `[mcp_servers.${tomlKey(MCP_SERVER_NAME)}]`,
72611
+ `command = ${tomlString(entry.command)}`,
72612
+ `args = [${entry.args.map(tomlString).join(", ")}]`,
72613
+ `startup_timeout_sec = ${CODEX_STARTUP_TIMEOUT_SEC}`,
72614
+ `tool_timeout_sec = ${CODEX_TOOL_TIMEOUT_SEC}`
72615
+ ];
72616
+ const env = isPlainObject(entry.env) ? Object.entries(entry.env) : [];
72617
+ if (env.length) lines.push("", `[mcp_servers.${tomlKey(MCP_SERVER_NAME)}.env]`, ...env.map(([key, value2]) => `${tomlKey(key)} = ${tomlString(value2)}`));
72618
+ return `${lines.join("\n")}
72619
+ `;
72620
+ }
72621
+ function tomlKeyPath(text3) {
72622
+ const parts = [];
72623
+ let rest = text3.trim();
72624
+ while (rest.length) {
72625
+ let match = /^([A-Za-z0-9_-]+)\s*/.exec(rest) ?? /^"((?:[^"\\]|\\.)*)"\s*/.exec(rest) ?? /^'([^']*)'\s*/.exec(rest);
72626
+ if (!match) return void 0;
72627
+ parts.push(match[0].startsWith('"') ? JSON.parse(`"${match[1]}"`) : match[1]);
72628
+ rest = rest.slice(match[0].length);
72629
+ if (!rest.length) break;
72630
+ if (!rest.startsWith(".")) return void 0;
72631
+ rest = rest.slice(1).trimStart();
72632
+ }
72633
+ return parts.length ? parts : void 0;
72634
+ }
72635
+ function tomlValue(text3) {
72636
+ const src = text3.trim();
72637
+ let at = 0;
72638
+ const space = () => {
72639
+ for (; ; ) {
72640
+ while (/\s/.test(src[at] ?? "")) at += 1;
72641
+ if (src[at] === "#") {
72642
+ while (at < src.length && src[at] !== "\n") at += 1;
72643
+ } else return;
72644
+ }
72645
+ };
72646
+ const string = () => {
72647
+ if (src[at] === "'") {
72648
+ const end = src.indexOf("'", at + 1);
72649
+ if (end < 0) throw new Error("toml");
72650
+ const out3 = src.slice(at + 1, end);
72651
+ at = end + 1;
72652
+ return out3;
72653
+ }
72654
+ if (src[at] !== '"') throw new Error("toml");
72655
+ let out2 = "";
72656
+ at += 1;
72657
+ while (at < src.length && src[at] !== '"') {
72658
+ if (src[at] === "\\") {
72659
+ const c = src[at + 1];
72660
+ const simple = { b: "\b", t: " ", n: "\n", f: "\f", r: "\r", '"': '"', "\\": "\\" }[c];
72661
+ if (simple !== void 0) {
72662
+ out2 += simple;
72663
+ at += 2;
72664
+ } else if (c === "u" || c === "U") {
72665
+ const size = c === "u" ? 4 : 8;
72666
+ out2 += String.fromCodePoint(parseInt(src.slice(at + 2, at + 2 + size), 16));
72667
+ at += 2 + size;
72668
+ } else throw new Error("toml");
72669
+ } else {
72670
+ out2 += src[at];
72671
+ at += 1;
72672
+ }
72673
+ }
72674
+ if (src[at] !== '"') throw new Error("toml");
72675
+ at += 1;
72676
+ return out2;
72677
+ };
72678
+ const value2 = () => {
72679
+ space();
72680
+ if (src[at] === '"' || src[at] === "'") return string();
72681
+ if (src[at] === "[") {
72682
+ at += 1;
72683
+ const out2 = [];
72684
+ for (; ; ) {
72685
+ space();
72686
+ if (src[at] === "]") {
72687
+ at += 1;
72688
+ return out2;
72689
+ }
72690
+ out2.push(value2());
72691
+ space();
72692
+ if (src[at] === ",") at += 1;
72693
+ else if (src[at] !== "]") throw new Error("toml");
72694
+ }
72695
+ }
72696
+ if (src[at] === "{") {
72697
+ at += 1;
72698
+ const out2 = {};
72699
+ for (; ; ) {
72700
+ space();
72701
+ if (src[at] === "}") {
72702
+ at += 1;
72703
+ return out2;
72704
+ }
72705
+ const eq = src.indexOf("=", at);
72706
+ if (eq < 0) throw new Error("toml");
72707
+ const key = tomlKeyPath(src.slice(at, eq));
72708
+ if (!key || key.length !== 1) throw new Error("toml");
72709
+ at = eq + 1;
72710
+ out2[key[0]] = value2();
72711
+ space();
72712
+ if (src[at] === ",") at += 1;
72713
+ else if (src[at] !== "}") throw new Error("toml");
72714
+ }
72715
+ }
72716
+ const number2 = /^[+-]?[0-9_]+(?:\.[0-9_]+)?/.exec(src.slice(at));
72717
+ if (number2) {
72718
+ at += number2[0].length;
72719
+ return Number(number2[0].replace(/_/g, ""));
72720
+ }
72721
+ const bool3 = /^(true|false)\b/.exec(src.slice(at));
72722
+ if (bool3) {
72723
+ at += bool3[0].length;
72724
+ return bool3[0] === "true";
72725
+ }
72726
+ throw new Error("toml");
72727
+ };
72728
+ const out = value2();
72729
+ space();
72730
+ if (at !== src.length) throw new Error("toml");
72731
+ return out;
72732
+ }
72733
+ function tomlValueLines(lines, start, first) {
72734
+ let text3 = first;
72735
+ for (let end = start; end < lines.length; end += 1) {
72736
+ if (end > start) text3 += `
72737
+ ${lines[end]}`;
72738
+ try {
72739
+ tomlValue(text3);
72740
+ return { end, text: text3 };
72741
+ } catch {
72742
+ }
72743
+ }
72744
+ return void 0;
72745
+ }
72746
+ function codexServersIn(text3, names) {
72747
+ const lines = text3.split(/\r?\n/);
72748
+ const servers = {};
72749
+ let unreadable = false;
72750
+ let table;
72751
+ let owner;
72752
+ for (let index = 0; index < lines.length; index += 1) {
72753
+ const line = lines[index];
72754
+ const trimmed = line.trim();
72755
+ if (!trimmed || trimmed.startsWith("#")) continue;
72756
+ if (trimmed.startsWith("[[")) {
72757
+ const path = tomlKeyPath(trimmed.replace(/^\[\[|\]\](\s*#.*)?$/g, ""));
72758
+ table = path;
72759
+ owner = void 0;
72760
+ if (!path || path[0] === "mcp_servers" && names.includes(path[1])) unreadable = true;
72761
+ continue;
72762
+ }
72763
+ if (trimmed.startsWith("[")) {
72764
+ const header = /^\[([^\]]*)\]\s*(?:#.*)?$/.exec(trimmed);
72765
+ const path = header ? tomlKeyPath(header[1]) : void 0;
72766
+ if (!path) {
72767
+ unreadable = true;
72768
+ table = void 0;
72769
+ owner = void 0;
72770
+ continue;
72771
+ }
72772
+ table = path;
72773
+ owner = path[0] === "mcp_servers" && names.includes(path[1]) ? path[1] : void 0;
72774
+ if (owner !== void 0) {
72775
+ const server = servers[owner] ??= { env: {}, ranges: [] };
72776
+ server.ranges.push([index, index + 1]);
72777
+ }
72778
+ continue;
72779
+ }
72780
+ const eq = line.indexOf("=");
72781
+ const key = eq < 0 ? void 0 : tomlKeyPath(line.slice(0, eq));
72782
+ const full = key && table ? [...table, ...key] : key;
72783
+ const multi = eq < 0 ? void 0 : /^\s*("""|''')/.exec(line.slice(eq + 1))?.[1];
72784
+ if (multi) {
72785
+ const after = line.slice(eq + 1).trimStart().slice(3);
72786
+ let end = index;
72787
+ if (!after.includes(multi)) {
72788
+ end += 1;
72789
+ while (end < lines.length && !lines[end].includes(multi)) end += 1;
72790
+ }
72791
+ if (end >= lines.length) {
72792
+ unreadable = true;
72793
+ break;
72794
+ }
72795
+ if (owner !== void 0 || full && full[0] === "mcp_servers" && names.includes(full[1])) unreadable = true;
72796
+ index = end;
72797
+ continue;
72798
+ }
72799
+ const found = full ? tomlValueLines(lines, index, line.slice(eq + 1)) : void 0;
72800
+ if (owner !== void 0) {
72801
+ const server = servers[owner];
72802
+ server.ranges.at(-1)[1] = (found?.end ?? index) + 1;
72803
+ if (!found) {
72804
+ unreadable = true;
72805
+ continue;
72806
+ }
72807
+ const rel = full.slice(2);
72808
+ const value2 = tomlValue(found.text);
72809
+ if (rel.length === 1 && rel[0] === "command") server.command = value2;
72810
+ else if (rel.length === 1 && rel[0] === "args") server.args = value2;
72811
+ else if (rel.length === 1 && rel[0] === "env" && isPlainObject(value2)) server.env = { ...server.env, ...value2 };
72812
+ else if (rel.length === 2 && rel[0] === "env") server.env[rel[1]] = value2;
72813
+ index = found.end;
72814
+ continue;
72815
+ }
72816
+ if (full && full[0] === "mcp_servers" && names.includes(full[1])) unreadable = true;
72817
+ if (found) index = found.end;
72818
+ }
72819
+ for (const server of Object.values(servers)) {
72820
+ for (const range of server.ranges) {
72821
+ while (range[1] < lines.length && !lines[range[1]].trim()) range[1] += 1;
72822
+ }
72823
+ }
72824
+ return { servers, unreadable };
72825
+ }
72826
+ function addToCodexHost(file, entry, { now = /* @__PURE__ */ new Date(), force = false, platform = process.platform, restrict = restrictToOwnerWindows } = {}) {
72827
+ let replaced = [];
72828
+ const block = codexTomlBlock(entry);
72829
+ const result = changeJsonFile(file, (text3) => {
72830
+ const names = [MCP_SERVER_NAME, ...OLD_MCP_SERVER_NAMES];
72831
+ let found;
72832
+ try {
72833
+ found = codexServersIn(text3, names);
72834
+ } catch {
72835
+ found = { unreadable: true };
72836
+ }
72837
+ if (found.unreadable) {
72838
+ 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");
72839
+ }
72840
+ replaced = OLD_MCP_SERVER_NAMES.filter((name) => found.servers[name] !== void 0);
72841
+ const existing = found.servers[MCP_SERVER_NAME];
72842
+ const lines = text3.split(/\r?\n/);
72843
+ const newline = text3.includes("\r\n") ? "\r\n" : "\n";
72844
+ if (existing !== void 0) {
72845
+ const own = lines.slice(existing.ranges[0][0], existing.ranges.at(-1)[1]).join("\n").trim();
72846
+ if (existing.ranges.length <= 2 && own === block.trim() && replaced.length === 0) return void 0;
72847
+ const was = codexEntryOf(existing);
72848
+ if (!force && !sameJson2(was, entry) && !isOlderSetupEntry(was, entry)) {
72849
+ 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`);
72850
+ }
72851
+ }
72852
+ const drop = /* @__PURE__ */ new Set();
72853
+ 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);
72854
+ const kept2 = lines.filter((_, index) => !drop.has(index)).join(newline).replace(/\s+$/, "");
72855
+ return `${kept2 ? `${kept2}${newline}${newline}` : ""}${block.replace(/\n/g, newline)}`;
72856
+ }, { now, platform, restrict, codec: TEXT_CODEC });
72857
+ return { file, ...result, replaced };
72858
+ }
72602
72859
  function isOlderSetupEntry(existing, entry) {
72603
72860
  if (!isPlainObject(existing) || !Array.isArray(existing.args) || entry.command !== "npx" || !Array.isArray(entry.args)) return false;
72604
72861
  const pinned = (args) => args.some((arg) => PINNED_PACKAGE.test(arg));
@@ -72668,20 +72925,12 @@ function allowInClaudeCode(file, { now = /* @__PURE__ */ new Date(), platform =
72668
72925
  }, { now, platform, restrict });
72669
72926
  return { file, ...result, added };
72670
72927
  }
72671
- function changeJsonFile(file, change, { now, platform, restrict }) {
72672
- let current = {};
72928
+ function changeJsonFile(file, change, { now, platform, restrict, codec = JSON_CODEC }) {
72929
+ let current = codec.empty();
72673
72930
  let bytes2;
72674
72931
  if (existsSync(file)) {
72675
72932
  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
- }
72933
+ current = codec.read(bytes2.toString("utf8"));
72685
72934
  }
72686
72935
  const next = change(current);
72687
72936
  if (next === void 0) return { changed: false };
@@ -72716,11 +72965,9 @@ function changeJsonFile(file, change, { now, platform, restrict }) {
72716
72965
  if (platform === "win32") {
72717
72966
  writeFileSync(temp, "", { flag: "wx" });
72718
72967
  restrict(temp);
72719
- writeFileSync(temp, `${JSON.stringify(next, null, 2)}
72720
- `);
72968
+ writeFileSync(temp, codec.write(next));
72721
72969
  } else {
72722
- writeFileSync(temp, `${JSON.stringify(next, null, 2)}
72723
- `, { mode: mode ?? 384, flag: "wx" });
72970
+ writeFileSync(temp, codec.write(next), { mode: mode ?? 384, flag: "wx" });
72724
72971
  }
72725
72972
  if (mode !== void 0 && platform !== "win32") chmodSync(temp, mode);
72726
72973
  renameSync(temp, file);
@@ -72730,7 +72977,7 @@ function changeJsonFile(file, change, { now, platform, restrict }) {
72730
72977
  }
72731
72978
  return { changed: true, ...backup ? { backup } : {} };
72732
72979
  }
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;
72980
+ 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
72981
  var init_config = __esm({
72735
72982
  "wallet/src/setup/config.mjs"() {
72736
72983
  "use strict";
@@ -72786,13 +73033,23 @@ var init_config = __esm({
72786
73033
  };
72787
73034
  MAX_OWN_ADDRESSES = 8;
72788
73035
  isOwnAddressText = (value2) => isPubkey(value2);
72789
- HOST_TARGETS = Object.freeze(["claude-code", "claude-desktop", "cursor"]);
73036
+ HOST_TARGETS = Object.freeze(["claude-code", "claude-desktop", "cursor", "codex"]);
73037
+ HOST_NAMES = Object.freeze({ "claude-code": "Claude Code", "claude-desktop": "Claude Desktop", cursor: "Cursor", codex: "Codex" });
73038
+ CODEX_STARTUP_TIMEOUT_SEC = 120;
73039
+ CODEX_TOOL_TIMEOUT_SEC = 300;
72790
73040
  PINNED_PACKAGE = /^shinjuku(?:-shield(?:ed)?)?@(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
72791
73041
  LAUNCHER_PACKAGE = /^shinjuku@[^\s@]+$/;
72792
73042
  NPM_VERSION = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
72793
73043
  knownNpmVersion = (npmVersion) => typeof npmVersion === "string" && npmVersion !== "0.0.0" && NPM_VERSION.test(npmVersion) ? npmVersion : void 0;
72794
73044
  RELEASES_URL = "https://github.com/ShinjukuStaition/shinjuku-shield#releases";
72795
73045
  WINDOWS_SHELL_CODE = /[%$`"\r\n]/;
73046
+ tomlString = (value2) => `"${String(value2).replace(/[\\"]/g, (c) => `\\${c}`).replace(/[\u0000-\u001f\u007f]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`)}"`;
73047
+ tomlKey = (key) => /^[A-Za-z0-9_-]+$/.test(key) ? key : tomlString(key);
73048
+ codexEntryOf = (server) => ({
73049
+ command: server.command,
73050
+ args: server.args,
73051
+ ...isPlainObject(server.env) && Object.keys(server.env).length ? { env: server.env } : {}
73052
+ });
72796
73053
  isPlainObject = (value2) => Boolean(value2) && typeof value2 === "object" && !Array.isArray(value2);
72797
73054
  sameJson2 = (a, b) => {
72798
73055
  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 +73065,24 @@ var init_config = __esm({
72808
73065
  ]);
72809
73066
  claudeCodeAllowRules = () => READ_ONLY_TOOL_NAMES.map((name) => `mcp__${MCP_SERVER_NAME}__${name}`);
72810
73067
  claudeCodeSettingsFile = ({ env = process.env, home = homedir() } = {}) => join11(env.CLAUDE_CONFIG_DIR || join11(home, ".claude"), "settings.json");
73068
+ JSON_CODEC = Object.freeze({
73069
+ empty: () => ({}),
73070
+ read: (text3) => {
73071
+ let current;
73072
+ try {
73073
+ current = text3.trim() ? JSON.parse(text3) : {};
73074
+ } catch {
73075
+ current = void 0;
73076
+ }
73077
+ if (!isPlainObject(current)) {
73078
+ 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");
73079
+ }
73080
+ return current;
73081
+ },
73082
+ write: (next) => `${JSON.stringify(next, null, 2)}
73083
+ `
73084
+ });
73085
+ TEXT_CODEC = Object.freeze({ empty: () => "", read: (text3) => text3, write: (next) => next });
72811
73086
  }
72812
73087
  });
72813
73088
 
@@ -111562,6 +111837,23 @@ function findModel(model) {
111562
111837
  }
111563
111838
  return found;
111564
111839
  }
111840
+ function contentText(content) {
111841
+ if (typeof content === "string") return content;
111842
+ if (!Array.isArray(content)) return void 0;
111843
+ 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);
111844
+ return parts.every((part) => part !== void 0) ? parts.join("") : void 0;
111845
+ }
111846
+ function checkToolCalls(calls, index) {
111847
+ if (!Array.isArray(calls) || calls.length === 0 || calls.length > MAX_TOOLS) {
111848
+ fail30("inference_messages_invalid", `message ${index} has tool_calls that are not a list of 1 to ${MAX_TOOLS} calls; nothing was paid`);
111849
+ }
111850
+ return calls.map((call) => {
111851
+ 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") {
111852
+ fail30("inference_messages_invalid", `message ${index} has a tool call that needs an id, type "function", and function { name, arguments (text) }; nothing was paid`);
111853
+ }
111854
+ return { id: call.id, type: "function", function: { name: call.function.name, arguments: call.function.arguments } };
111855
+ });
111856
+ }
111565
111857
  function checkMessages(messages) {
111566
111858
  const example = 'pass messages like [{"role":"user","content":"Say hello"}]';
111567
111859
  if (!Array.isArray(messages) || messages.length === 0) {
@@ -111571,12 +111863,49 @@ function checkMessages(messages) {
111571
111863
  if (!message || typeof message !== "object" || !ROLES.includes(message.role)) {
111572
111864
  fail30("inference_messages_invalid", `message ${index} needs a role of ${ROLES.join(", ")}; nothing was paid`, { next: example });
111573
111865
  }
111574
- if (typeof message.content !== "string" || message.content.length === 0) {
111866
+ const text3 = contentText(message.content);
111867
+ if (message.role === "tool") {
111868
+ if (typeof message.tool_call_id !== "string" || !message.tool_call_id || message.tool_call_id.length > 128 || text3 === void 0) {
111869
+ fail30("inference_messages_invalid", `message ${index} (role tool) needs tool_call_id and content as text; nothing was paid`, { next: example });
111870
+ }
111871
+ return { role: "tool", tool_call_id: message.tool_call_id, content: text3 };
111872
+ }
111873
+ if (message.role === "assistant" && message.tool_calls !== void 0 && message.tool_calls !== null) {
111874
+ if (text3 === void 0 && message.content !== null && message.content !== void 0) {
111875
+ fail30("inference_messages_invalid", `message ${index} needs content as text (or null beside tool_calls); nothing was paid`, { next: example });
111876
+ }
111877
+ return { role: "assistant", content: text3 ?? "", tool_calls: checkToolCalls(message.tool_calls, index) };
111878
+ }
111879
+ if (text3 === void 0 || text3.length === 0) {
111575
111880
  fail30("inference_messages_invalid", `message ${index} needs content as non-empty text; nothing was paid`, { next: example });
111576
111881
  }
111577
- return { role: message.role, content: message.content };
111882
+ return { role: message.role, content: text3 };
111883
+ });
111884
+ }
111885
+ function checkTools(tools) {
111886
+ if (tools === void 0 || tools === null || Array.isArray(tools) && tools.length === 0) return void 0;
111887
+ 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`);
111888
+ return tools.map((tool, index) => {
111889
+ const fn = tool?.function;
111890
+ 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))) {
111891
+ fail30("inference_tools_invalid", `tool ${index} needs type "function" and function { name (letters, digits, _ . -), description?, parameters? (an object) }; nothing was paid`);
111892
+ }
111893
+ return { type: "function", function: {
111894
+ name: fn.name,
111895
+ ...fn.description === void 0 ? {} : { description: fn.description },
111896
+ ...fn.parameters === void 0 ? {} : { parameters: fn.parameters }
111897
+ } };
111578
111898
  });
111579
111899
  }
111900
+ function checkToolChoice(choice, tools) {
111901
+ if (choice === void 0 || choice === null) return void 0;
111902
+ if (["auto", "none", "required"].includes(choice)) return choice;
111903
+ const name = choice?.function?.name;
111904
+ if (choice?.type === "function" && TOOL_NAME.test(String(name ?? "")) && tools?.some((tool) => tool.function.name === name)) {
111905
+ return { type: "function", function: { name } };
111906
+ }
111907
+ fail30("inference_tools_invalid", 'tool_choice must be "auto", "none", "required", or { type: "function", function: { name } } of a tool in tools; nothing was paid');
111908
+ }
111580
111909
  function checkMaxTokens(maxTokens, model) {
111581
111910
  if (maxTokens === void 0 || maxTokens === null) return BigInt(defaultMaxTokens(model));
111582
111911
  if (!Number.isSafeInteger(maxTokens) || maxTokens < 1) {
@@ -111588,22 +111917,23 @@ function checkMaxTokens(maxTokens, model) {
111588
111917
  }
111589
111918
  return BigInt(maxTokens);
111590
111919
  }
111591
- function inputTokensBound(messages) {
111920
+ function inputTokensBound(messages, tools) {
111592
111921
  let tokens = 0n;
111593
111922
  for (const message of messages) {
111594
- tokens += BigInt(Buffer.byteLength(message.role) + Buffer.byteLength(message.content)) + MESSAGE_OVERHEAD_TOKENS;
111923
+ 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
111924
  }
111925
+ if (tools) tokens += BigInt(Buffer.byteLength(JSON.stringify(tools))) + MESSAGE_OVERHEAD_TOKENS;
111596
111926
  return tokens;
111597
111927
  }
111598
- function ceilingOf(entry, messages, maxTokens) {
111599
- const estimate = ceilDiv(entry.priceInPerMAtomic * inputTokensBound(messages) + entry.priceOutPerMAtomic * maxTokens, PER_M);
111928
+ function ceilingOf(entry, messages, maxTokens, tools) {
111929
+ const estimate = ceilDiv(entry.priceInPerMAtomic * inputTokensBound(messages, tools) + entry.priceOutPerMAtomic * maxTokens, PER_M);
111600
111930
  return estimate > USEPOD_MIN_PAYMENT_ATOMIC ? estimate : USEPOD_MIN_PAYMENT_ATOMIC;
111601
111931
  }
111602
- function ceilingAtomic({ model, messages, maxTokens }) {
111932
+ function ceilingAtomic({ model, messages, maxTokens, tools }) {
111603
111933
  const entry = findModel(model);
111604
- return ceilingOf(entry, checkMessages(messages), checkMaxTokens(maxTokens, entry.id));
111934
+ return ceilingOf(entry, checkMessages(messages), checkMaxTokens(maxTokens, entry.id), checkTools(tools));
111605
111935
  }
111606
- function buildChatRequest({ model, messages, maxTokens, temperature, stream }) {
111936
+ function buildChatRequest({ model, messages, maxTokens, temperature, stream, tools, toolChoice, parallelToolCalls }) {
111607
111937
  if (stream === true) {
111608
111938
  fail30(
111609
111939
  "inference_stream_unsupported",
@@ -111617,11 +111947,19 @@ function buildChatRequest({ model, messages, maxTokens, temperature, stream }) {
111617
111947
  if (temperature !== void 0 && (typeof temperature !== "number" || !Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
111618
111948
  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
111949
  }
111950
+ const cleanTools = checkTools(tools);
111951
+ const choice = checkToolChoice(toolChoice, cleanTools);
111952
+ if (parallelToolCalls !== void 0 && typeof parallelToolCalls !== "boolean") fail30("inference_tools_invalid", "parallel_tool_calls must be true or false; nothing was paid");
111620
111953
  const body = JSON.stringify({
111621
111954
  model: entry.id,
111622
111955
  messages: clean5,
111623
111956
  max_tokens: Number(tokens),
111624
111957
  ...temperature === void 0 ? {} : { temperature },
111958
+ ...cleanTools ? {
111959
+ tools: cleanTools,
111960
+ ...choice === void 0 ? {} : { tool_choice: choice },
111961
+ ...parallelToolCalls === void 0 ? {} : { parallel_tool_calls: parallelToolCalls }
111962
+ } : {},
111625
111963
  stream: false
111626
111964
  });
111627
111965
  return { url: USEPOD_X402_CHAT_URL, init: { method: "POST", headers: {
@@ -111634,11 +111972,19 @@ function buildChatRequest({ model, messages, maxTokens, temperature, stream }) {
111634
111972
  }, body } };
111635
111973
  }
111636
111974
  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
- }));
111975
+ const choices = json4.choices.map((choice, index) => {
111976
+ 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) => ({
111977
+ id: call.id.slice(0, 128),
111978
+ type: "function",
111979
+ function: { name: call.function.name, arguments: typeof call.function.arguments === "string" ? call.function.arguments : JSON.stringify(call.function.arguments ?? {}) }
111980
+ })) : [];
111981
+ const content = typeof choice?.message?.content === "string" ? choice.message.content : "";
111982
+ return {
111983
+ index: Number.isSafeInteger(choice?.index) ? choice.index : index,
111984
+ message: calls.length ? { role: "assistant", content: content || null, tool_calls: calls } : { role: "assistant", content },
111985
+ finish_reason: typeof choice?.finish_reason === "string" ? choice.finish_reason : null
111986
+ };
111987
+ });
111642
111988
  const count2 = (value2) => Number.isSafeInteger(value2) && value2 >= 0 ? value2 : 0;
111643
111989
  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
111990
  return {
@@ -111670,7 +112016,14 @@ async function readChatResponse(response) {
111670
112016
  fail30("inference_response_invalid", "the AI provider's answer carried no choices", { next: "try again later, or pass a different model" });
111671
112017
  }
111672
112018
  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 };
112019
+ return {
112020
+ content: body.choices[0].message.content ?? "",
112021
+ toolCalls: body.choices[0].message.tool_calls,
112022
+ finishReason: body.choices[0].finish_reason,
112023
+ usage: body.usage,
112024
+ model: body.model,
112025
+ body
112026
+ };
111674
112027
  }
111675
112028
  function receiptOf(response) {
111676
112029
  const raw = response.headers.get(PAYMENT_HEADER);
@@ -111707,17 +112060,30 @@ function overCapNext(entry, messages, cap, ceiling) {
111707
112060
  if (cap < USEPOD_MIN_PAYMENT_ATOMIC) {
111708
112061
  return "allow more than 0.01 USDC (the AI provider's minimum per call) plus the Shinjuku fee for this call";
111709
112062
  }
111710
- const room = cap * PER_M - entry.priceInPerMAtomic * inputTokensBound(messages);
112063
+ const room = cap * PER_M - entry.priceInPerMAtomic * inputTokensBound(messages, void 0);
111711
112064
  const fits = room > 0n ? room / entry.priceOutPerMAtomic : 0n;
111712
112065
  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
112066
  }
111714
- async function inferenceChat({ payFetch, model, messages, maxTokens, temperature, maxPaymentAtomic, requestId, heldPayment: heldPayment2 = false, preparedAtomic }) {
112067
+ async function inferenceChat({
112068
+ payFetch,
112069
+ model,
112070
+ messages,
112071
+ maxTokens,
112072
+ temperature,
112073
+ maxPaymentAtomic,
112074
+ requestId,
112075
+ heldPayment: heldPayment2 = false,
112076
+ preparedAtomic,
112077
+ tools,
112078
+ toolChoice,
112079
+ parallelToolCalls
112080
+ }) {
111715
112081
  if (typeof payFetch !== "function") throw new TypeError("inferenceChat needs a payFetch function");
111716
- const { url, init } = buildChatRequest({ model, messages, maxTokens, temperature });
112082
+ const { url, init } = buildChatRequest({ model, messages, maxTokens, temperature, tools, toolChoice, parallelToolCalls });
111717
112083
  const entry = findModel(model);
111718
112084
  const clean5 = checkMessages(messages);
111719
112085
  const tokens = checkMaxTokens(maxTokens, entry.id);
111720
- const ceiling = ceilingOf(entry, clean5, tokens);
112086
+ const ceiling = ceilingOf(entry, clean5, tokens, checkTools(tools));
111721
112087
  const cap = parseCap(maxPaymentAtomic);
111722
112088
  const sendsPrepared = /^[1-9][0-9]{0,30}$/.test(String(preparedAtomic ?? ""));
111723
112089
  if (ceiling > cap && heldPayment2 !== true && !sendsPrepared) {
@@ -111767,7 +112133,7 @@ async function inferenceChat({ payFetch, model, messages, maxTokens, temperature
111767
112133
  maxTokensDefault: maxTokens === void 0 || maxTokens === null
111768
112134
  };
111769
112135
  }
111770
- var USEPOD_X402_CHAT_URL, USEPOD_MIN_PAYMENT_ATOMIC, INFERENCE_NOTICE, ROLES, MESSAGE_OVERHEAD_TOKENS, PER_M, InferenceError, fail30, modelIds, ceilDiv, spelling;
112136
+ 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
112137
  var init_inference = __esm({
111772
112138
  "wallet/src/inference/index.mjs"() {
111773
112139
  "use strict";
@@ -111777,7 +112143,9 @@ var init_inference = __esm({
111777
112143
  USEPOD_X402_CHAT_URL = "https://api.usepod.ai/proxy/x402/v1/chat/completions";
111778
112144
  USEPOD_MIN_PAYMENT_ATOMIC = 10000n;
111779
112145
  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"]);
112146
+ ROLES = Object.freeze(["system", "user", "assistant", "tool"]);
112147
+ MAX_TOOLS = 128;
112148
+ TOOL_NAME = /^[A-Za-z0-9_.-]{1,64}$/;
111781
112149
  MESSAGE_OVERHEAD_TOKENS = 8n;
111782
112150
  PER_M = 1000000n;
111783
112151
  InferenceError = class extends Error {
@@ -140492,7 +140860,7 @@ __export(serve_exports, {
140492
140860
  paidOf: () => paidOf
140493
140861
  });
140494
140862
  import { createServer as createServer2 } from "node:http";
140495
- import { randomBytes as randomBytes26, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
140863
+ import { createHmac as createHmac9, randomBytes as randomBytes26, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
140496
140864
  function codeOf7(error) {
140497
140865
  if (typeof error?.code === "string" && /^[a-z0-9_]+$/.test(error.code)) return error.code;
140498
140866
  if (typeof error?.error === "string" && /^[a-z0-9_]+$/.test(error.error)) return error.error;
@@ -140735,12 +141103,135 @@ function streamOf(answer, includeUsage) {
140735
141103
  const chunk = (delta, finish = null) => ({ ...head, choices: [{ index: 0, delta, logprobs: null, finish_reason: finish }], ...usageNull });
140736
141104
  const [choice] = answer.choices;
140737
141105
  const events = [chunk({ role: "assistant", content: "" })];
140738
- const chars = Array.from(choice.message.content);
141106
+ const chars = Array.from(choice.message.content ?? "");
140739
141107
  for (let at = 0; at < chars.length; at += STREAM_CHUNK_CHARS) events.push(chunk({ content: chars.slice(at, at + STREAM_CHUNK_CHARS).join("") }));
141108
+ if (Array.isArray(choice.message.tool_calls) && choice.message.tool_calls.length) {
141109
+ events.push(chunk({ tool_calls: choice.message.tool_calls.map((call, index) => ({ index, ...call })) }));
141110
+ }
140740
141111
  events.push({ ...chunk({}, choice.finish_reason), shinjuku: answer.shinjuku });
140741
141112
  if (includeUsage) events.push({ ...head, choices: [], usage: answer.usage ?? null });
140742
141113
  return events.map(sseEvent).join("") + sseEvent("[DONE]");
140743
141114
  }
141115
+ function chatBodyOfResponses(body) {
141116
+ if (body.previous_response_id !== void 0 && body.previous_response_id !== null) {
141117
+ 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");
141118
+ }
141119
+ const messages = [];
141120
+ if (typeof body.instructions === "string" && body.instructions) messages.push({ role: "system", content: body.instructions });
141121
+ const input = typeof body.input === "string" ? [{ type: "message", role: "user", content: body.input }] : body.input;
141122
+ 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");
141123
+ for (const [index, item] of input.entries()) {
141124
+ const type = item?.type ?? (typeof item?.role === "string" ? "message" : void 0);
141125
+ if (type === "reasoning") continue;
141126
+ if (type === "message") {
141127
+ const role = item.role === "developer" ? "system" : item.role;
141128
+ 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");
141129
+ if (Array.isArray(item.content) && item.content.some((part) => !TEXT_PARTS.has(part?.type))) {
141130
+ 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");
141131
+ }
141132
+ const text3 = typeof item.content === "string" ? item.content : Array.isArray(item.content) ? textOfParts(item.content) : void 0;
141133
+ if (text3 === void 0) throw refusal2("inference_messages_invalid", `input item ${index} needs content as text; nothing was paid`, "input");
141134
+ if (text3) messages.push({ role, content: text3 });
141135
+ continue;
141136
+ }
141137
+ if (type === "function_call") {
141138
+ const call = { id: item.call_id, type: "function", function: { name: item.name, arguments: item.arguments } };
141139
+ const last = messages[messages.length - 1];
141140
+ if (last?.role === "assistant") last.tool_calls = [...last.tool_calls ?? [], call];
141141
+ else messages.push({ role: "assistant", content: null, tool_calls: [call] });
141142
+ continue;
141143
+ }
141144
+ if (type === "function_call_output") {
141145
+ const output2 = typeof item.output === "string" ? item.output : Array.isArray(item.output) ? textOfParts(item.output) : JSON.stringify(item.output ?? "");
141146
+ messages.push({ role: "tool", tool_call_id: item.call_id, content: output2 });
141147
+ continue;
141148
+ }
141149
+ 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");
141150
+ }
141151
+ 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");
141152
+ const tools = Array.isArray(body.tools) ? body.tools.filter((tool) => tool?.type === "function").map((tool) => ({ type: "function", function: {
141153
+ name: tool.name,
141154
+ ...typeof tool.description === "string" ? { description: tool.description } : {},
141155
+ ...tool.parameters && typeof tool.parameters === "object" ? { parameters: tool.parameters } : {}
141156
+ } })) : [];
141157
+ 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;
141158
+ const choice = ["auto", "none", "required"].includes(body.tool_choice) ? body.tool_choice : named;
141159
+ return {
141160
+ model: body.model,
141161
+ messages,
141162
+ ...Number.isSafeInteger(body.max_output_tokens) ? { max_tokens: body.max_output_tokens } : {},
141163
+ ...typeof body.temperature === "number" ? { temperature: body.temperature } : {},
141164
+ ...tools.length ? {
141165
+ tools,
141166
+ ...choice === void 0 ? {} : { tool_choice: choice },
141167
+ ...typeof body.parallel_tool_calls === "boolean" ? { parallel_tool_calls: body.parallel_tool_calls } : {}
141168
+ } : {}
141169
+ };
141170
+ }
141171
+ function responseOf(answer) {
141172
+ const id = `resp_${String(answer.shinjuku?.request_id ?? randomBytes26(8).toString("hex")).replace(/[^A-Za-z0-9_-]/g, "_")}`;
141173
+ const message = answer.choices[0].message;
141174
+ const output2 = [];
141175
+ const calls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
141176
+ if (typeof message.content === "string" && message.content || !calls.length) {
141177
+ output2.push({
141178
+ type: "message",
141179
+ id: `msg_${id.slice(5)}`,
141180
+ status: "completed",
141181
+ role: "assistant",
141182
+ content: [{ type: "output_text", text: message.content ?? "", annotations: [] }]
141183
+ });
141184
+ }
141185
+ for (const call of calls) {
141186
+ output2.push({ type: "function_call", id: `fc_${call.id}`, call_id: call.id, name: call.function.name, arguments: call.function.arguments, status: "completed" });
141187
+ }
141188
+ const usage2 = answer.usage;
141189
+ return {
141190
+ id,
141191
+ object: "response",
141192
+ created_at: answer.created,
141193
+ status: "completed",
141194
+ model: answer.model,
141195
+ output: output2,
141196
+ usage: usage2 ? {
141197
+ input_tokens: usage2.prompt_tokens,
141198
+ input_tokens_details: { cached_tokens: 0 },
141199
+ output_tokens: usage2.completion_tokens,
141200
+ output_tokens_details: { reasoning_tokens: 0 },
141201
+ total_tokens: usage2.total_tokens
141202
+ } : null,
141203
+ shinjuku: answer.shinjuku
141204
+ };
141205
+ }
141206
+ function responseStreamOf(response) {
141207
+ let sequence = 0;
141208
+ const event = (type, fields) => `event: ${type}
141209
+ data: ${JSON.stringify({ type, sequence_number: sequence++, ...fields })}
141210
+
141211
+ `;
141212
+ const shell = { ...response, status: "in_progress", output: [], usage: null };
141213
+ let text3 = event("response.created", { response: shell }) + event("response.in_progress", { response: shell });
141214
+ response.output.forEach((item, outputIndex) => {
141215
+ if (item.type === "message") {
141216
+ const whole = item.content[0]?.text ?? "";
141217
+ const part = { type: "output_text", text: "", annotations: [] };
141218
+ text3 += event("response.output_item.added", { output_index: outputIndex, item: { ...item, status: "in_progress", content: [] } });
141219
+ text3 += event("response.content_part.added", { item_id: item.id, output_index: outputIndex, content_index: 0, part });
141220
+ const chars = Array.from(whole);
141221
+ for (let at = 0; at < chars.length; at += STREAM_CHUNK_CHARS) {
141222
+ 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("") });
141223
+ }
141224
+ text3 += event("response.output_text.done", { item_id: item.id, output_index: outputIndex, content_index: 0, text: whole });
141225
+ text3 += event("response.content_part.done", { item_id: item.id, output_index: outputIndex, content_index: 0, part: { ...part, text: whole } });
141226
+ } else {
141227
+ text3 += event("response.output_item.added", { output_index: outputIndex, item: { ...item, status: "in_progress", arguments: "" } });
141228
+ text3 += event("response.function_call_arguments.delta", { item_id: item.id, output_index: outputIndex, delta: item.arguments });
141229
+ text3 += event("response.function_call_arguments.done", { item_id: item.id, output_index: outputIndex, arguments: item.arguments });
141230
+ }
141231
+ text3 += event("response.output_item.done", { output_index: outputIndex, item });
141232
+ });
141233
+ return text3 + event("response.completed", { response });
141234
+ }
140744
141235
  function sendStream(res, text3) {
140745
141236
  res.writeHead(200, { "content-type": "text/event-stream; charset=utf-8", "content-length": Buffer.byteLength(text3), "cache-control": "no-store" });
140746
141237
  res.end(text3);
@@ -140785,6 +141276,7 @@ function createInferenceServer({
140785
141276
  const counted = /* @__PURE__ */ new Map();
140786
141277
  let queue = Promise.resolve();
140787
141278
  let count2 = 0;
141279
+ const retrySecret = randomBytes26(32);
140788
141280
  let boundPort = port;
140789
141281
  const hostAllowed = (host) => host === `${INFERENCE_SERVE_HOST}:${boundPort}` || host === `localhost:${boundPort}`;
140790
141282
  function authorized(header) {
@@ -140846,7 +141338,8 @@ function createInferenceServer({
140846
141338
  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
141339
  }
140848
141340
  const messages = body.messages;
140849
- const ceiling = typeof inference.ceilingAtomic === "function" ? BigInt(inference.ceilingAtomic({ model: body.model, messages, maxTokens })) : void 0;
141341
+ const tools = body.tools === void 0 || body.tools === null ? {} : { tools: body.tools, toolChoice: body.tool_choice, parallelToolCalls: body.parallel_tool_calls };
141342
+ const ceiling = typeof inference.ceilingAtomic === "function" ? BigInt(inference.ceilingAtomic({ model: body.model, messages, maxTokens, tools: tools.tools })) : void 0;
140850
141343
  if (!held && preparedAtomic === void 0 && ceiling !== void 0 && ceiling > perRequestCap) {
140851
141344
  const floor = BigInt(inference.USEPOD_MIN_PAYMENT_ATOMIC ?? 0n);
140852
141345
  const belowFloor = perRequestCap < floor;
@@ -140880,6 +141373,7 @@ function createInferenceServer({
140880
141373
  messages,
140881
141374
  maxTokens,
140882
141375
  ...body.temperature === void 0 ? {} : { temperature: body.temperature },
141376
+ ...tools,
140883
141377
  maxPaymentAtomic: perRequestCap,
140884
141378
  requestId,
140885
141379
  ...held ? { heldPayment: true } : preparedAtomic !== void 0 ? { preparedAtomic: preparedAtomic.toString() } : {}
@@ -140930,7 +141424,7 @@ function createInferenceServer({
140930
141424
  object: "chat.completion",
140931
141425
  created: Math.floor(now() / 1e3),
140932
141426
  model: result.model ?? body.model,
140933
- choices: [{ index: 0, message: { role: "assistant", content: result.content ?? "" }, finish_reason: result.finishReason ?? "stop" }],
141427
+ 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
141428
  ...usageOf(result.usage) ? { usage: usageOf(result.usage) } : {},
140935
141429
  shinjuku: {
140936
141430
  request_id: result.requestId ?? requestId,
@@ -140992,8 +141486,9 @@ ${choice.message.content ?? ""}`;
140992
141486
  }
140993
141487
  const path = new URL(req.url ?? "/", `http://${INFERENCE_SERVE_HOST}`).pathname.replace(/\/+$/, "");
140994
141488
  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"];
141489
+ const route = req.method !== "POST" ? void 0 : path === "/v1/chat/completions" ? "chat" : path === "/v1/responses" ? "responses" : void 0;
141490
+ if (route) {
141491
+ let key = req.headers["idempotency-key"];
140997
141492
  if (key !== void 0 && (typeof key !== "string" || !IDEMPOTENCY_KEY.test(key))) {
140998
141493
  return send2(res, 400, { error: {
140999
141494
  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 +141511,23 @@ ${choice.message.content ?? ""}`;
141016
141511
  return send2(res, status, out, NO_RETRY);
141017
141512
  };
141018
141513
  let body;
141514
+ let chatBody;
141019
141515
  try {
141020
141516
  body = await readJson3(req);
141517
+ chatBody = route === "responses" ? chatBodyOfResponses(body) : body;
141021
141518
  } catch (error) {
141022
141519
  return refused(error);
141023
141520
  }
141024
- const run4 = queue.then(() => chat(body, key));
141521
+ if (route === "responses" && key === void 0) key = `r${createHmac9("sha256", retrySecret).update(JSON.stringify(body)).digest("hex").slice(0, 40)}`;
141522
+ const run4 = queue.then(() => chat(chatBody, key));
141025
141523
  queue = run4.catch(() => {
141026
141524
  });
141027
141525
  try {
141028
- const answer = withNotices(await run4, body);
141526
+ const answer = withNotices(await run4, chatBody);
141527
+ if (route === "responses") {
141528
+ const response = responseOf(answer);
141529
+ return body.stream === true ? sendStream(res, responseStreamOf(response)) : send2(res, 200, response);
141530
+ }
141029
141531
  if (body.stream === true) return sendStream(res, streamOf(answer, body.stream_options?.include_usage === true));
141030
141532
  return send2(res, 200, answer);
141031
141533
  } catch (error) {
@@ -141033,7 +141535,7 @@ ${choice.message.content ?? ""}`;
141033
141535
  }
141034
141536
  }
141035
141537
  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 }
141538
+ 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
141539
  });
141038
141540
  }
141039
141541
  const server = createServer2((req, res) => {
@@ -141068,7 +141570,7 @@ ${choice.message.content ?? ""}`;
141068
141570
  token
141069
141571
  };
141070
141572
  }
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;
141573
+ 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
141574
  var init_serve = __esm({
141073
141575
  "wallet/src/inference/serve.mjs"() {
141074
141576
  "use strict";
@@ -141092,6 +141594,7 @@ var init_serve = __esm({
141092
141594
  "inference_stream_unsupported",
141093
141595
  "inference_model_unknown",
141094
141596
  "inference_messages_invalid",
141597
+ "inference_tools_invalid",
141095
141598
  "inference_temperature_invalid",
141096
141599
  "inference_ceiling_over_cap"
141097
141600
  ]);
@@ -141139,6 +141642,8 @@ var init_serve = __esm({
141139
141642
  sseEvent = (value2) => `data: ${typeof value2 === "string" ? value2 : JSON.stringify(value2)}
141140
141643
 
141141
141644
  `;
141645
+ TEXT_PARTS = /* @__PURE__ */ new Set(["input_text", "output_text", "text"]);
141646
+ textOfParts = (parts) => parts.filter((part) => TEXT_PARTS.has(part?.type) && typeof part.text === "string").map((part) => part.text).join("\n");
141142
141647
  }
141143
141648
  });
141144
141649
 
@@ -142684,17 +143189,21 @@ When it says ready, type /retry: it asks the same question again.` : receivedOnl
142684
143189
  return;
142685
143190
  }
142686
143191
  let prepared;
143192
+ let neverLeft = false;
142687
143193
  if (!surelyNothing) {
142688
143194
  try {
142689
143195
  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))}` : "";
143196
+ if (kept2 === void 0 || kept2.committed !== true || kept2.cancelled === true) neverLeft = true;
143197
+ else if (kept2.prepared === true) prepared = /^[1-9][0-9]{0,30}$/.test(String(kept2.amountAtomic ?? "")) ? ` of ${usdcWords(BigInt(kept2.amountAtomic))}` : "";
142691
143198
  } catch {
142692
143199
  prepared = void 0;
143200
+ neverLeft = false;
142693
143201
  }
142694
143202
  }
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.";
143203
+ const nothing = surelyNothing || neverLeft;
143204
+ 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)";
143205
+ if (!nothing) state.pending = turn;
143206
+ 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
143207
  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
143208
  if (code2 === "inference_tor_required" || code2 === "ECONNREFUSED" || proxyRefusedConnection(error)) {
142700
143209
  say3(`Your private connection (Tor) stopped answering, so the question could not go out. ${paidWords} Start Tor again, then ${again}.${closeOtherwise}`);
@@ -142710,6 +143219,12 @@ When it says ready, type /retry: it asks the same question again.` : receivedOnl
142710
143219
  say3(`The AI provider did not send a chat answer. ${paidWords} Wait a moment and ${again}, or try another model (/model).${closeOtherwise}`);
142711
143220
  } else if (WAIT_CODES.test(code2 ?? "")) {
142712
143221
  say3(`The payment did not finish yet (the wallet or the network is busy). ${paidWords} Wait a moment, then ${again}.${closeOtherwise}`);
143222
+ } else if (HISTORY_CODES.test(code2 ?? "") || HISTORY_CODES.test(String(error?.message ?? ""))) {
143223
+ try {
143224
+ (typeof session.timing === "function" ? session.timing() : void 0)?.("chat-answer-failed", code2 ?? "history_rpc_failed");
143225
+ } catch {
143226
+ }
143227
+ 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
143228
  } else {
142714
143229
  try {
142715
143230
  const logged = ownCodeWords(error).split(":")[0];
@@ -142717,7 +143232,7 @@ When it says ready, type /retry: it asks the same question again.` : receivedOnl
142717
143232
  } catch {
142718
143233
  }
142719
143234
  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}`);
143235
+ 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
143236
  }
142722
143237
  };
142723
143238
  const command = async (text3) => {
@@ -142784,7 +143299,7 @@ When it says ready, type /retry: it asks the same question again.` : receivedOnl
142784
143299
  await session.close();
142785
143300
  }
142786
143301
  }
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;
143302
+ 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
143303
  var init_chat = __esm({
142789
143304
  "wallet/src/inference/chat.mjs"() {
142790
143305
  "use strict";
@@ -142828,6 +143343,7 @@ var init_chat = __esm({
142828
143343
  CAP_CODES = /^(spend_payment_cap_exceeded|mcp_session_cap_exceeded|mcp_cap_argument_above_launch_cap|p03_float_over_maximum)$/;
142829
143344
  WAIT_CODES = /_retry_same_request$|_retry_same_payment$|_retry_later$|^wallet_locked$|another_request_unresolved$/;
142830
143345
  NO_ANSWER_CODES = /^inference_(upstream_failed|response_invalid)$/;
143346
+ HISTORY_CODES = /\b(?:history_rpc_failed|history_source_silent|compact_history_source_unavailable)\b/;
142831
143347
  chatFloatTerms = () => ({
142832
143348
  again: "Type /retry",
142833
143349
  rerun: "Ask again",
@@ -149427,10 +149943,27 @@ function agentHostsOf(env, home) {
149427
149943
  const config = readJsonFile(hostConfigFile(target, { env, home: homedir2() }));
149428
149944
  return config === void 0 ? false : config === null ? null : runsThisWallet(config.mcpServers, home);
149429
149945
  };
149946
+ const codexHost = () => {
149947
+ const file = hostConfigFile("codex", { env, home: homedir2() });
149948
+ let size;
149949
+ try {
149950
+ size = statSync(file).size;
149951
+ } catch (error) {
149952
+ return error?.code === "ENOENT" ? false : null;
149953
+ }
149954
+ if (size > HOST_CONFIG_MAX_BYTES) return null;
149955
+ try {
149956
+ const found = codexServersIn(readFileSync(file, "utf8"), [MCP_SERVER_NAME, ...OLD_MCP_SERVER_NAMES]);
149957
+ return found.unreadable ? null : runsThisWallet(found.servers, home);
149958
+ } catch {
149959
+ return null;
149960
+ }
149961
+ };
149430
149962
  return [
149431
149963
  { app: "Claude Code", ...claudeCodeState(env, home) },
149432
149964
  { app: "Claude Desktop", linked: jsonHost("claude-desktop") },
149433
- { app: "Cursor", linked: jsonHost("cursor") }
149965
+ { app: "Cursor", linked: jsonHost("cursor") },
149966
+ { app: "Codex", linked: codexHost() }
149434
149967
  ];
149435
149968
  }
149436
149969
  function readHomeData({ env = process.env, walletVersion: walletVersion2, torRun } = {}) {
@@ -150612,7 +151145,19 @@ var localAiPasteLines = (answer) => [
150612
151145
  ];
150613
151146
  var localAiRestartLine = () => `It stops when the computer restarts: then run ${cli2()} infer start again; the api key stays the same.`;
150614
151147
  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.";
151148
+ var localAiAppsLines = (answer) => [
151149
+ "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.",
151150
+ "A whole Codex session on it: put these lines in the file shinjuku.config.toml in your Codex folder (~/.codex):",
151151
+ ` model = "${LOCAL_AI_APP_MODEL}"`,
151152
+ ' model_provider = "shinjuku"',
151153
+ " [model_providers.shinjuku]",
151154
+ ' name = "Shinjuku private AI"',
151155
+ ` base_url = "${answer.baseUrl}"`,
151156
+ ' env_key = "SHINJUKU_AI_KEY"',
151157
+ ' wire_api = "responses"',
151158
+ "Set SHINJUKU_AI_KEY to the api key above, then start it with: codex --profile shinjuku. Each Codex turn is one paid answer (about 0.005 USDC with the fee on qwen3-8-flash); your other Codex sessions stay as they are."
151159
+ ];
151160
+ var localAiCodexHint = () => `For a Codex session on this address, run: ${cli2()} infer status --verbose`;
150616
151161
  var LOCAL_AI_CAP_SOURCE = { setup: "from your limits", default: "default", flag: "given at start" };
150617
151162
  var localAiCapSource = (caps, name) => LOCAL_AI_CAP_SOURCE[caps?.source?.[name]] ? ` (${LOCAL_AI_CAP_SOURCE[caps.source[name]]})` : "";
150618
151163
  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 +151281,7 @@ async function runInferStart(values, deps) {
150736
151281
  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
151282
  "Put these lines into your agent app (as an OpenAI-compatible provider):",
150738
151283
  ...localAiPasteLines(answer),
150739
- ...verbose ? [LOCAL_AI_APPS_LINE] : [],
151284
+ ...verbose ? localAiAppsLines(answer) : [localAiCodexHint()],
150740
151285
  `Caps: ${localAiCapsText(answer.caps, answer.limits)}. It pays from your private balance.`,
150741
151286
  ...localAiFloorLines(answer.caps, USEPOD_MIN_PAYMENT_ATOMIC2, { limits: answer.limits }),
150742
151287
  ...localAiLowBalanceLines(values, deps, walletFile),
@@ -150770,7 +151315,7 @@ async function runInferStatus(values, deps) {
150770
151315
  `The local AI server runs${verbose ? ` (pid ${status.pid}${status.startedAt ? `, since ${status.startedAt}` : ""})` : ""}, on this computer only, behind Tor.`,
150771
151316
  "Your agent app uses these lines:",
150772
151317
  ...localAiPasteLines(status),
150773
- ...verbose ? [LOCAL_AI_APPS_LINE] : [],
151318
+ ...verbose ? localAiAppsLines(status) : [localAiCodexHint()],
150774
151319
  `Caps: ${localAiCapsText(status.caps, status.limits)}. Paid so far: ${usdcOr(status.spentAtomic ?? "0")} for ${requestsWords(status.requests)}.`,
150775
151320
  ...localAiFloorLines(status.caps, USEPOD_MIN_PAYMENT_ATOMIC2, { limits: status.limits }),
150776
151321
  ...verbose ? [...localAiDefaultCapsLine(status.caps, { limits: status.limits }), await localAiRequestLine(status.caps, deps)] : [],
@@ -151481,7 +152026,8 @@ function privateInferencePath(config) {
151481
152026
  }
151482
152027
  function agentAppLines({ skip = /* @__PURE__ */ new Set() }) {
151483
152028
  const lines = [];
151484
- for (const [target, app] of [["claude-code", "Claude Code"], ["claude-desktop", "Claude Desktop"], ["cursor", "Cursor"]]) {
152029
+ for (const target of HOST_TARGETS) {
152030
+ const app = target === "codex" ? "Codex (the Codex app or Codex CLI)" : HOST_NAMES[target];
151485
152031
  if (!skip.has(target)) lines.push(`${app}, run this once (setup adds the wallet there):`, ` ${cli2()} setup --add-to ${target}`);
151486
152032
  }
151487
152033
  return lines.join("\n");
@@ -151940,13 +152486,13 @@ async function addToHosts(targets, home, deps, { force = false, npmVersion, ask
151940
152486
  continue;
151941
152487
  }
151942
152488
  const file = hostConfigFile(target, { ...options, home: deps.homedir() });
151943
- const app = target === "cursor" ? "Cursor" : "Claude Desktop";
152489
+ const app = HOST_NAMES[target];
151944
152490
  try {
151945
- const added = addToJsonHost(file, mcpServerEntry(options), { force });
152491
+ const added = (target === "codex" ? addToCodexHost : addToJsonHost)(file, mcpServerEntry(options), { force });
151946
152492
  for (const old of added.replaced ?? []) io.out(`Replaced the old ${old} entry in ${app}.
151947
152493
  `);
151948
152494
  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)}
152495
+ ` : `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
152496
  `);
151951
152497
  done.add(target);
151952
152498
  } catch (error) {
@@ -153231,7 +153777,7 @@ var COMMANDS = [
153231
153777
  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
153778
  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
153779
  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 }),
153780
+ 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
153781
  // 0.3.97 key rename: the host key is MCP_SERVER_NAME; the old keys go by themselves.
153236
153782
  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
153783
  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 +153796,7 @@ var COMMANDS = [
153250
153796
  `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
153797
  "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
153798
  `--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.`,
153799
+ `--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
153800
  "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
153801
  "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
153802
  `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 +154435,7 @@ function shortHelpText() {
153888
154435
  "Everyday commands:",
153889
154436
  ...rows2.map(([word, about]) => ` ${word.padEnd(width)}${about}`),
153890
154437
  "",
153891
- "Add the wallet to your agent app (claude-code, claude-desktop, or cursor):",
154438
+ "Add the wallet to your agent app (claude-code, claude-desktop, cursor, or codex):",
153892
154439
  ` ${cli2()} setup --add-to claude-code`,
153893
154440
  "",
153894
154441
  `One command, with an example: ${cli2()} help <command>`,
@@ -156859,7 +157406,7 @@ async function runShinjukuWallet(argv2, overrides = {}) {
156859
157406
  }
156860
157407
  return job(["curl", "--url", link2]);
156861
157408
  }
156862
- const hostNames = { "claude-code": "Claude Code", "claude-desktop": "Claude Desktop", cursor: "Cursor" };
157409
+ const hostNames = HOST_NAMES;
156863
157410
  io.err(`Which agent app gets the wallet?
156864
157411
  ${HOST_TARGETS.map((host, index) => ` ${index + 1} ${hostNames[host] ?? host}`).join("\n")}
156865
157412
  `);