@rse/claudex 1.0.17 → 1.1.1

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
@@ -90,6 +90,18 @@ $ CLAUDE_MODEL="ollama:/gemma4:31b-coding-mtp-bf16?context=262K" claudex -T -R -
90
90
  $ CLAUDE_MODEL="openrouter:google/gemini-3.5-flash?context=1000000" claudex -T -R -A
91
91
  ```
92
92
 
93
+ ```sh
94
+ # example: run Claude Code with a Codex model via a local proxy
95
+ $ CLAUDE_MODEL="codex:gpt-6.1-sol[1m]" claudex -T -R -A
96
+ ```
97
+
98
+ Codex mode requires `claude-code-proxy` in `$PATH` with its Codex
99
+ authentication configured. claudeX reuses a healthy proxy at
100
+ `http://127.0.0.1:18765`, or automatically starts
101
+ `claude-code-proxy serve --port 18765 --no-monitor` and waits for readiness.
102
+ The proxy stays running after Claude Code exits so other sessions can reuse it.
103
+ With `-C`, the proxy and its authentication must be available inside the container.
104
+
93
105
  See Also
94
106
  --------
95
107
 
package/claudex.js CHANGED
@@ -7,6 +7,7 @@
7
7
  import * as fs from "node:fs";
8
8
  import * as path from "node:path";
9
9
  import * as os from "node:os";
10
+ import { spawn } from "node:child_process";
10
11
  import { execa, execaSync } from "execa";
11
12
  import which from "which";
12
13
  import chalk from "chalk";
@@ -160,10 +161,10 @@ const execInherit = (file, args, opts = {}) => {
160
161
  reject: false,
161
162
  windowsHide: false
162
163
  });
163
- process.exit(r.exitCode ?? 0);
164
+ process.exit(r.exitCode ?? 1);
164
165
  };
165
166
  /* helper to execute a platform-specific command */
166
- const executeCommand = (config, platformOverride) => {
167
+ const executeCommand = (config, platformOverride, fatalOnFailure = false) => {
167
168
  const platform = platformOverride ?? detectPlatform();
168
169
  const osName = platform.split(":")[0];
169
170
  const command = config[platform] ?? config[`${osName}:*`] ?? config["*"];
@@ -177,7 +178,10 @@ const executeCommand = (config, platformOverride) => {
177
178
  reject: false,
178
179
  windowsHide: false
179
180
  });
180
- return result.exitCode;
181
+ const exitCode = result.exitCode ?? 1;
182
+ if (fatalOnFailure && exitCode !== 0)
183
+ fatal(`failed to execute "${cmd[0]}" (exit ${exitCode})`);
184
+ return exitCode;
181
185
  };
182
186
  /* helper to update an externally managed tool with exactly the package
183
187
  manager which actually provides it, instead of just the preferred one */
@@ -187,7 +191,7 @@ const updateTool = (tool, config) => {
187
191
  info(`skip update of "${tool}" (not provided by MacPorts or Homebrew)`);
188
192
  return 0;
189
193
  }
190
- return executeCommand(config, platform);
194
+ return executeCommand(config, platform, true);
191
195
  };
192
196
  /* helper to determine whether a global NPM installation requires sudo(8),
193
197
  i.e., whether the target directories of the NPM global prefix are not
@@ -253,7 +257,7 @@ const self = async (...args) => {
253
257
  stdio: "inherit",
254
258
  reject: false
255
259
  });
256
- if ((r.exitCode ?? 0) !== 0)
260
+ if ((r.exitCode ?? 1) !== 0)
257
261
  process.exit(r.exitCode ?? 1);
258
262
  return r.exitCode ?? 0;
259
263
  };
@@ -300,7 +304,10 @@ const pruneClaudeVersions = (active) => {
300
304
  const versionsDir = path.join(HOME, ".local/share/claude/versions");
301
305
  if (!fs.existsSync(versionsDir))
302
306
  return;
303
- for (const f of fs.readdirSync(versionsDir)) {
307
+ const versions = fs.readdirSync(versionsDir);
308
+ if (!versions.includes(active))
309
+ return;
310
+ for (const f of versions) {
304
311
  if (f === active)
305
312
  continue;
306
313
  try {
@@ -315,6 +322,8 @@ const pruneClaudeVersions = (active) => {
315
322
  const detectActiveClaudeVersion = (binName) => {
316
323
  try {
317
324
  const r = execaSync(path.join(HOME, ".local/bin", binName), ["--version"], { reject: false });
325
+ if (r.exitCode !== 0)
326
+ return null;
318
327
  const m = /^(\S+)/.exec(r.stdout ?? "");
319
328
  if (m)
320
329
  return m[1];
@@ -345,11 +354,11 @@ const actionInstall = async (capsula) => {
345
354
  info("install Tmux / LazyGit / Git");
346
355
  await self("internal", "capsula", "-s", "sudo", "-E", "apt", "install", "-qq", "-y", "tmux", "lazygit", "git");
347
356
  info("install Node.js");
348
- await self("internal", "capsula", "-s", "sudo", "-E", "bash", "-c", "curl -fsSL https://deb.nodesource.com/setup_24.x | bash -");
357
+ await self("internal", "capsula", "-s", "sudo", "-E", "bash", "-o", "pipefail", "-c", "curl -fsSL https://deb.nodesource.com/setup_24.x | bash -");
349
358
  await self("internal", "capsula", "-s", "sudo", "-E", "apt", "install", "-qq", "-y", "nodejs");
350
359
  await self("internal", "capsula", "-s", "sudo", "-E", "apt", "install", "-qq", "-y", "binutils", "gcc", "g++", "make");
351
360
  info("install Claude Code");
352
- await self("internal", "capsula", "bash", "-c", `PATH="${HOME}/.local/bin:$PATH"; curl -fsSL https://claude.ai/install.sh | bash`);
361
+ await self("internal", "capsula", "bash", "-o", "pipefail", "-c", `PATH=${shQ.quote([path.join(HOME, ".local/bin")])}:"$PATH"; curl -fsSL https://claude.ai/install.sh | bash`);
353
362
  info("install ANSI-Recolor");
354
363
  await self("internal", "capsula", "-s", "sudo", "-E", "npm", "install", "-y", "-g", "--allow-scripts=node-pty,tty-attr", "ansi-recolor");
355
364
  info("install TypeScript LS");
@@ -365,6 +374,7 @@ const actionInstall = async (capsula) => {
365
374
  "[ -d \"$VERSIONS\" ] || exit 0; " +
366
375
  "ACTIVE=$(\"$HOME/.local/bin/claude\" --version 2>/dev/null | awk '{print $1; exit}'); " +
367
376
  "[ -n \"$ACTIVE\" ] || exit 0; " +
377
+ "[ -f \"$VERSIONS/$ACTIVE\" ] || exit 0; " +
368
378
  "find \"$VERSIONS\" -mindepth 1 -maxdepth 1 ! -name \"$ACTIVE\" -exec rm -rf {} +");
369
379
  }
370
380
  else {
@@ -429,7 +439,7 @@ const actionInstall = async (capsula) => {
429
439
  "windows:choco": "choco install -y --accept-license --no-progress nodejs",
430
440
  "macos:ports": "sudo port -N install nodejs26 npm11",
431
441
  "macos:brew": "brew install node",
432
- "linux:apt": "curl -fsSL https://deb.nodesource.com/setup_26.x | sudo -E bash - && sudo apt install -y nodejs",
442
+ "linux:apt": ["bash", "-o", "pipefail", "-c", "curl -fsSL https://deb.nodesource.com/setup_26.x | sudo -E bash - && sudo apt install -y nodejs"],
433
443
  "linux:dnf": "sudo dnf install -y nodejs npm",
434
444
  "linux:yum": "sudo yum install -y nodejs npm",
435
445
  "linux:zypper": "sudo zypper --non-interactive install nodejs npm",
@@ -470,8 +480,8 @@ const actionInstall = async (capsula) => {
470
480
  /* run installation script */
471
481
  ensureTool("bash", { hint: "https://www.gnu.org/software/bash/" });
472
482
  ensureTool("curl", { hint: "https://curl.se/" });
473
- await execa("bash", ["-c", `PATH="${HOME}/.local/bin:$PATH"; curl -fsSL https://claude.ai/install.sh | bash`], {
474
- stdio: "inherit", reject: false
483
+ await execa("bash", ["-o", "pipefail", "-c", `PATH=${shQ.quote([path.join(HOME, ".local/bin")])}:"$PATH"; curl -fsSL https://claude.ai/install.sh | bash`], {
484
+ stdio: "inherit"
475
485
  });
476
486
  /* prune obsolete versions only after successful install */
477
487
  pruneClaudeVersions(detectActiveClaudeVersion("claude"));
@@ -482,7 +492,7 @@ const actionInstall = async (capsula) => {
482
492
  /* run installation script */
483
493
  ensureTool("powershell");
484
494
  await execa("powershell", ["-NoProfile", "-Command", "irm https://claude.ai/install.ps1 | iex"], {
485
- stdio: "inherit", reject: false
495
+ stdio: "inherit"
486
496
  });
487
497
  /* prune obsolete versions only after successful install */
488
498
  pruneClaudeVersions(detectActiveClaudeVersion("claude.exe"));
@@ -508,7 +518,7 @@ const actionUpdate = async (capsula) => {
508
518
  await self("internal", "capsula", "-s", "sudo", "apt", "update", "-qq");
509
519
  await self("internal", "capsula", "-s", "sudo", "apt", "upgrade", "-qq", "-y");
510
520
  info("update Claude Code");
511
- await self("internal", "capsula", "bash", "-c", `PATH="${HOME}/.local/bin:$PATH"; ${HOME}/.local/bin/claude update`);
521
+ await self("internal", "capsula", "bash", "-c", `PATH=${shQ.quote([path.join(HOME, ".local/bin")])}:"$PATH"; ${shQ.quote([path.join(HOME, ".local/bin/claude")])} update`);
512
522
  info("update ANSI-Recolor");
513
523
  await self("internal", "capsula", "-s", "sudo", "-E", "npm", "install", "-y", "-g", "--allow-scripts=node-pty,tty-attr", "ansi-recolor");
514
524
  info("update TypeScript LS");
@@ -576,24 +586,24 @@ const actionUpdate = async (capsula) => {
576
586
  info("update ANSI-Recolor");
577
587
  executeCommand({
578
588
  "*": npmInstallGlobal("--allow-scripts=node-pty,tty-attr", "ansi-recolor")
579
- });
589
+ }, undefined, true);
580
590
  info("update TypeScript-Language-Server");
581
591
  executeCommand({
582
592
  "*": npmInstallGlobal("typescript-language-server")
583
- });
593
+ }, undefined, true);
584
594
  info("update CodeBurn");
585
595
  executeCommand({
586
596
  "*": npmInstallGlobal("codeburn")
587
- });
597
+ }, undefined, true);
588
598
  info("update ASE");
589
599
  executeCommand({
590
600
  "*": npmInstallGlobal("@rse/ase")
591
- });
601
+ }, undefined, true);
592
602
  info("update Claude Code");
593
603
  if (process.platform !== "win32") {
594
604
  ensureTool("bash");
595
- await execa("bash", ["-c", `PATH="${HOME}/.local/bin:$PATH"; ${HOME}/.local/bin/claude update`], {
596
- stdio: "inherit", reject: false
605
+ await execa("bash", ["-c", `PATH=${shQ.quote([path.join(HOME, ".local/bin")])}:"$PATH"; ${shQ.quote([path.join(HOME, ".local/bin/claude")])} update`], {
606
+ stdio: "inherit"
597
607
  });
598
608
  /* prune obsolete versions only after successful update */
599
609
  pruneClaudeVersions(detectActiveClaudeVersion("claude"));
@@ -603,7 +613,7 @@ const actionUpdate = async (capsula) => {
603
613
  fatal("on Windows the \"update\" command has to be run from within a PowerShell session");
604
614
  ensureTool("powershell");
605
615
  await execa("powershell", ["-NoProfile", "-Command", "claude update"], {
606
- stdio: "inherit", reject: false
616
+ stdio: "inherit"
607
617
  });
608
618
  /* prune obsolete versions only after successful update */
609
619
  pruneClaudeVersions(detectActiveClaudeVersion("claude.exe"));
@@ -655,7 +665,7 @@ const actionInternalTmux = (opts, args) => {
655
665
  }
656
666
  conf = conf.replace(/@USER@/g, USER);
657
667
  const confFile = path.join(os.tmpdir(), `claudex-tmux-${process.pid}.conf`);
658
- fs.writeFileSync(confFile, conf, { mode: 0o600 });
668
+ fs.writeFileSync(confFile, conf, { mode: 0o600, flag: "wx" });
659
669
  /* ensure the temp config is removed on normal exit AND on signal-driven
660
670
  termination (SIGINT/SIGTERM); SIGKILL and process panics remain
661
671
  uncoverable. tmux.conf is read once at startup and not re-read via
@@ -669,6 +679,10 @@ const actionInternalTmux = (opts, args) => {
669
679
  process.on("exit", cleanup);
670
680
  process.on("SIGINT", () => { cleanup(); process.exit(130); });
671
681
  process.on("SIGTERM", () => { cleanup(); process.exit(143); });
682
+ /* pass each new Unix session its own invocation environment */
683
+ if (!isPsmux() && args[0] === "new-session")
684
+ for (const name of ["CLAUDEX_FLAGS", "CLAUDEX_INTERNAL_EXEC", "CLAUDE_MODEL", "OPENROUTER_API_KEY"])
685
+ args.splice(1, 0, "-e", `${name}=${process.env[name] ?? ""}`);
672
686
  const r = execaSync("tmux", [
673
687
  "-f", confFile,
674
688
  ...args
@@ -678,7 +692,7 @@ const actionInternalTmux = (opts, args) => {
678
692
  windowsHide: false
679
693
  });
680
694
  cleanup();
681
- return process.exit(r.exitCode ?? 0);
695
+ return process.exit(r.exitCode ?? 1);
682
696
  };
683
697
  /* action: internal "shell" -- spawn an interactive login shell */
684
698
  const actionInternalShell = (_opts, args) => {
@@ -744,6 +758,8 @@ const actionInternalCapsula = (_opts, args) => {
744
758
  const envOpts = ["-e", "!"];
745
759
  for (const e of envs)
746
760
  envOpts.push("-e", e);
761
+ if (process.env.OPENROUTER_API_KEY !== undefined)
762
+ envOpts.push("-e", "OPENROUTER_API_KEY");
747
763
  /* find list of dot-files (relative to $HOME) */
748
764
  const dotfiles = [
749
765
  ".inputrc",
@@ -849,7 +865,7 @@ const actionInternal = async (opts, args) => {
849
865
  }
850
866
  };
851
867
  /* action: top-level command -- run "claude" */
852
- const actionDefault = (opts, args) => {
868
+ const actionDefault = async (opts, args) => {
853
869
  /* build the inner self-invocation flag list. Pass-through "-R"/"-A" only,
854
870
  as "-C" and "-T" are consumed at the outer layer to avoid recursion. */
855
871
  const innerFlags = [];
@@ -883,14 +899,20 @@ const actionDefault = (opts, args) => {
883
899
  execaSync("docker", ["start", container], { reject: false, stdio: "ignore" });
884
900
  /* enter already running container and run tmux */
885
901
  return execInherit("docker", [
886
- "exec", "-i", "-t", container,
902
+ "exec", "-i", ...(process.stdin.isTTY ? ["-t"] : []),
903
+ "-w", process.cwd(),
904
+ "-e", `CLAUDE_MODEL=${process.env.CLAUDE_MODEL ?? ""}`,
905
+ ...(process.env.OPENROUTER_API_KEY !== undefined ? ["-e", "OPENROUTER_API_KEY"] : []),
906
+ container,
887
907
  "bash", "-c",
888
908
  `TERM=${shQ.quote([TERM])} ` +
889
909
  `HOME=${shQ.quote([HOME])} ` +
890
910
  `CLAUDEX_FLAGS=${shQ.quote([claudexFlags])} ` +
911
+ `CLAUDEX_INTERNAL_EXEC=${shQ.quote([inPane])} ` +
891
912
  `sudo -E -u ${shQ.quote([USER])} ` +
892
913
  `${shQ.quote(["node" /* process.execPath is not valid inside container! */, selfPathJS])} ` +
893
- `${opts.ase ? "-A " : ""}internal tmux new-session -A -s ${shQ.quote([session])}`
914
+ `${opts.ase ? "-A " : ""}internal tmux new-session -A -s ${shQ.quote([session])} ` +
915
+ `-n claude ${shQ.quote(["claudex internal exec"])}`
894
916
  ]);
895
917
  }
896
918
  else {
@@ -936,7 +958,11 @@ const actionDefault = (opts, args) => {
936
958
  execaSync("docker", ["start", container], { reject: false, stdio: "ignore" });
937
959
  /* enter already running container and run claude (single-quote shell-escape) */
938
960
  return execInherit("docker", [
939
- "exec", "-i", "-t", container,
961
+ "exec", "-i", ...(process.stdin.isTTY ? ["-t"] : []),
962
+ "-w", process.cwd(),
963
+ "-e", `CLAUDE_MODEL=${process.env.CLAUDE_MODEL ?? ""}`,
964
+ ...(process.env.OPENROUTER_API_KEY !== undefined ? ["-e", "OPENROUTER_API_KEY"] : []),
965
+ container,
940
966
  "bash", "-c",
941
967
  `TERM=${shQ.quote([TERM])} ` +
942
968
  `HOME=${shQ.quote([HOME])} ` +
@@ -960,7 +986,7 @@ const actionDefault = (opts, args) => {
960
986
  const recolor = opts.recolor === true;
961
987
  if (recolor)
962
988
  ensureTool("ansi-recolor");
963
- process.env.PATH = `${HOME}/.local/bin:${process.env.PATH ?? ""}`;
989
+ process.env.PATH = `${path.join(HOME, ".local/bin")}${path.delimiter}${process.env.PATH ?? ""}`;
964
990
  ensureTool("claude");
965
991
  const env = { ...process.env };
966
992
  const claudeModel = process.env.CLAUDE_MODEL ?? "";
@@ -1006,9 +1032,10 @@ const actionDefault = (opts, args) => {
1006
1032
  env.ANTHROPIC_AUTH_TOKEN = "ollama";
1007
1033
  env.ANTHROPIC_BASE_URL = `http://${ohost}`;
1008
1034
  env.ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES = capabilities;
1009
- env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model;
1035
+ env.ANTHROPIC_DEFAULT_FABLE_MODEL = model;
1010
1036
  env.ANTHROPIC_DEFAULT_OPUS_MODEL = model;
1011
1037
  env.ANTHROPIC_DEFAULT_SONNET_MODEL = model;
1038
+ env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model;
1012
1039
  env.CLAUDE_CODE_SUBAGENT_MODEL = model;
1013
1040
  env.CLAUDE_CODE_ATTRIBUTION_HEADER = "0";
1014
1041
  env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = context;
@@ -1045,9 +1072,10 @@ const actionDefault = (opts, args) => {
1045
1072
  env.ANTHROPIC_AUTH_TOKEN = process.env.OPENROUTER_API_KEY;
1046
1073
  env.ANTHROPIC_BASE_URL = "https://openrouter.ai/api";
1047
1074
  env.ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES = capabilities;
1048
- env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model;
1075
+ env.ANTHROPIC_DEFAULT_FABLE_MODEL = model;
1049
1076
  env.ANTHROPIC_DEFAULT_OPUS_MODEL = model;
1050
1077
  env.ANTHROPIC_DEFAULT_SONNET_MODEL = model;
1078
+ env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model;
1051
1079
  env.CLAUDE_CODE_SUBAGENT_MODEL = model;
1052
1080
  env.CLAUDE_CODE_ATTRIBUTION_HEADER = "0";
1053
1081
  env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = context;
@@ -1055,10 +1083,67 @@ const actionDefault = (opts, args) => {
1055
1083
  env.DISABLE_LOGOUT_COMMAND = "1";
1056
1084
  env.ENABLE_TOOL_SEARCH = "auto";
1057
1085
  }
1086
+ else if (/^codex:/.test(claudeModel)) {
1087
+ const model = claudeModel.slice("codex:".length);
1088
+ if (model.trim() === "")
1089
+ fatal("invalid CLAUDE_MODEL: missing model name in " +
1090
+ `"${claudeModel}" (expected: codex:<model>)`);
1091
+ /* reuse a healthy proxy or start a persistent detached server */
1092
+ const baseURL = "http://127.0.0.1:18765";
1093
+ const deadline = Date.now() + 10000;
1094
+ let proxy;
1095
+ let proxyError = "";
1096
+ while (true) {
1097
+ try {
1098
+ const response = await fetch(`${baseURL}/healthz`, { signal: AbortSignal.timeout(500) });
1099
+ await response.body?.cancel();
1100
+ if (response.ok)
1101
+ break;
1102
+ }
1103
+ catch (_e) {
1104
+ /* not ready yet */
1105
+ }
1106
+ if (proxy === undefined) {
1107
+ ensureTool("claude-code-proxy", { hint: "install claude-code-proxy and configure its Codex authentication first" });
1108
+ proxy = spawn("claude-code-proxy", ["serve", "--port", "18765", "--no-monitor"], {
1109
+ detached: true,
1110
+ stdio: "ignore",
1111
+ windowsHide: true
1112
+ });
1113
+ proxy.on("error", (err) => { proxyError = err.message; });
1114
+ proxy.unref();
1115
+ }
1116
+ else if (proxyError !== "" || proxy.exitCode !== null || proxy.signalCode !== null)
1117
+ fatal("failed to start claude-code-proxy" +
1118
+ (proxyError !== "" ? `: ${proxyError}` : ` (exit ${proxy.exitCode ?? proxy.signalCode})`) +
1119
+ " -- run \"claude-code-proxy serve --port 18765 --no-monitor\" for details");
1120
+ if (Date.now() >= deadline) {
1121
+ proxy.kill();
1122
+ fatal(`claude-code-proxy did not become ready at ${baseURL} within 10 seconds`);
1123
+ }
1124
+ await new Promise((resolve) => setTimeout(resolve, 100));
1125
+ }
1126
+ /* override Claude Code configuration as in the claude-codex wrapper */
1127
+ env.ANTHROPIC_BASE_URL = baseURL;
1128
+ env.ANTHROPIC_API_KEY = "";
1129
+ env.ANTHROPIC_AUTH_TOKEN = "unused";
1130
+ env.ANTHROPIC_DEFAULT_MODEL = model;
1131
+ env.ANTHROPIC_DEFAULT_FABLE_MODEL = "gpt-6-astra[1m]";
1132
+ env.ANTHROPIC_DEFAULT_OPUS_MODEL = "gpt-6.1-sol[1m]";
1133
+ env.ANTHROPIC_DEFAULT_SONNET_MODEL = "gpt-6-luna[1m]";
1134
+ env.ANTHROPIC_DEFAULT_HAIKU_MODEL = "gpt-6-luna[1m]";
1135
+ env.CLAUDE_CODE_SUBAGENT_MODEL = "inherit";
1136
+ env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = "272000";
1137
+ env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1";
1138
+ env.CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK = "1";
1139
+ env.DISABLE_LOGIN_COMMAND = "1";
1140
+ env.DISABLE_LOGOUT_COMMAND = "1";
1141
+ env.ENABLE_TOOL_SEARCH = "auto";
1142
+ }
1058
1143
  else if (claudeModel !== "")
1059
1144
  fatal(`invalid CLAUDE_MODEL "${claudeModel}" ` +
1060
- "(supports only: \"ollama[://<host>[:<port>]]/<model>[?[context=<size>],[capabilities=<list>]]\" " +
1061
- "and \"openrouter:<model>[?[context=<size>],[capabilities=<list>]]\")");
1145
+ "(supports only: \"ollama[://<host>[:<port>]]/<model>[?[context=<size>],[capabilities=<list>]]\", " +
1146
+ "\"openrouter:<model>[?[context=<size>],[capabilities=<list>]]\" and \"codex:<model>\")");
1062
1147
  /* override ASE configuration (for its diagram rendering) */
1063
1148
  if (opts.ase) {
1064
1149
  if (env.ASE_TERM_WIDTH === undefined) {
@@ -1100,7 +1185,7 @@ const actionDefault = (opts, args) => {
1100
1185
  ]
1101
1186
  }
1102
1187
  };
1103
- if (opts.tmux) {
1188
+ if (process.env.TMUX) {
1104
1189
  claudeSettings = deepmerge(claudeSettings, {
1105
1190
  "env": {
1106
1191
  "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
@@ -1134,7 +1219,7 @@ const actionDefault = (opts, args) => {
1134
1219
  /* action: top-level "-h/--help" */
1135
1220
  const actionHelp = () => {
1136
1221
  /* run "claude --help" */
1137
- process.env.PATH = `${HOME}/.local/bin:${process.env.PATH ?? ""}`;
1222
+ process.env.PATH = `${path.join(HOME, ".local/bin")}${path.delimiter}${process.env.PATH ?? ""}`;
1138
1223
  ensureTool("claude");
1139
1224
  const claudeBin = path.join(HOME, ".local/bin/claude");
1140
1225
  execaSync(claudeBin, ["--help"], { reject: false, stdio: ["ignore", "inherit", "inherit"] });
@@ -1156,7 +1241,7 @@ const actionHelp = () => {
1156
1241
  /* action: top-level "-v/-V/--version" */
1157
1242
  const actionVersion = () => {
1158
1243
  /* run "claude --version" */
1159
- process.env.PATH = `${HOME}/.local/bin:${process.env.PATH ?? ""}`;
1244
+ process.env.PATH = `${path.join(HOME, ".local/bin")}${path.delimiter}${process.env.PATH ?? ""}`;
1160
1245
  ensureTool("claude");
1161
1246
  const claudeBin = path.join(HOME, ".local/bin/claude");
1162
1247
  execaSync(claudeBin, ["--version"], { reject: false, stdio: ["ignore", "inherit", "inherit"] });
@@ -1171,12 +1256,12 @@ const main = async () => {
1171
1256
  the top-level "-R"/"-C"/"-T"/"-A" flags by default. Merge env-derived
1172
1257
  flags with the command-line flags (env first, command-line second, so
1173
1258
  the user can extend or override on the command line). Skip for the
1174
- "internal" sub-dispatch (which uses CLAUDEX_FLAGS_PASSTHROUGH for
1175
- tmux.conf bind-key flag propagation), and skip flags that are already
1176
- present on argv to avoid duplicating boolean options. */
1259
+ "internal" sub-dispatch; tmux.conf bind-keys invoke plain "claudex",
1260
+ whose defaults come from CLAUDEX_FLAGS. Skip flags already present
1261
+ on argv to avoid duplicating boolean options. */
1177
1262
  {
1178
1263
  const topArgs = process.argv.slice(2);
1179
- const subcmd = topArgs.find((a) => !a.startsWith("-")) ?? "";
1264
+ const subcmd = topArgs.find((a, i) => !a.startsWith("-") && (i === 0 || (topArgs[i - 1] !== "-T" && topArgs[i - 1] !== "--tmux"))) ?? "";
1180
1265
  const envFlags = (process.env.CLAUDEX_FLAGS ?? "").trim();
1181
1266
  const claudeNativeSubcmds = [
1182
1267
  "agents", "auth", "auto-mode", "doctor", "mcp",
@@ -1217,7 +1302,19 @@ const main = async () => {
1217
1302
  filtered.push(t);
1218
1303
  }
1219
1304
  /* insert in front of the other arguments */
1220
- const toInsert = filtered.filter((t) => !present(t));
1305
+ const toInsert = [];
1306
+ for (let i = 0; i < filtered.length; i++) {
1307
+ const t = filtered[i];
1308
+ const hasSession = (t === "-T" || t === "--tmux")
1309
+ && i + 1 < filtered.length && !filtered[i + 1].startsWith("-");
1310
+ if (!present(t)) {
1311
+ toInsert.push(t);
1312
+ if (hasSession)
1313
+ toInsert.push(filtered[i + 1]);
1314
+ }
1315
+ if (hasSession)
1316
+ i++;
1317
+ }
1221
1318
  if (toInsert.length > 0)
1222
1319
  process.argv.splice(2, 0, ...toInsert);
1223
1320
  }
@@ -1225,7 +1322,7 @@ const main = async () => {
1225
1322
  /* intercept top-level "-h/--help" and "-v/-V/--version" before commander
1226
1323
  grabs them, so we can pass-through to "claude" and append our extension info */
1227
1324
  const topArgs = process.argv.slice(2);
1228
- const firstNonFlag = topArgs.findIndex((a) => !a.startsWith("-"));
1325
+ const firstNonFlag = topArgs.findIndex((a, i) => !a.startsWith("-") && (i === 0 || (topArgs[i - 1] !== "-T" && topArgs[i - 1] !== "--tmux")));
1229
1326
  const headFlags = firstNonFlag < 0 ? topArgs : topArgs.slice(0, firstNonFlag);
1230
1327
  const subcmd = firstNonFlag < 0 ? "" : topArgs[firstNonFlag];
1231
1328
  if ((headFlags.includes("-h") || headFlags.includes("--help"))
@@ -1248,8 +1345,8 @@ const main = async () => {
1248
1345
  .option("-R, --recolor", "wrap Claude Code with ANSI recoloring for improved theming")
1249
1346
  .option("-A, --ase", "enable ASE-specific ASE_* environment variables and Tmux settings")
1250
1347
  .argument("[args...]", "arguments passed unparsed to Claude Code")
1251
- .action((args, opts) => {
1252
- actionDefault(opts, args);
1348
+ .action(async (args, opts) => {
1349
+ await actionDefault(opts, args);
1253
1350
  });
1254
1351
  /* dispatch "install" sub-command */
1255
1352
  program
@@ -1284,6 +1381,7 @@ const main = async () => {
1284
1381
  .command("internal")
1285
1382
  .description("internal command dispatcher (tmux, shell, lazygit, ase-task-edit, capsula)")
1286
1383
  .helpOption("-h, --help", "display help for command")
1384
+ .passThroughOptions()
1287
1385
  .allowUnknownOption()
1288
1386
  .argument("[args...]", "internal command name and its arguments")
1289
1387
  .action(async (args, _opts, cmd) => {
package/claudex.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  import * as fs from "node:fs"
9
9
  import * as path from "node:path"
10
10
  import * as os from "node:os"
11
+ import { spawn } from "node:child_process"
11
12
  import { execa, execaSync } from "execa"
12
13
  import which from "which"
13
14
  import chalk from "chalk"
@@ -179,11 +180,11 @@ const execInherit = (file: string, args: string[], opts: { env?: Env } = {}): ne
179
180
  reject: false,
180
181
  windowsHide: false
181
182
  })
182
- process.exit(r.exitCode ?? 0)
183
+ process.exit(r.exitCode ?? 1)
183
184
  }
184
185
 
185
186
  /* helper to execute a platform-specific command */
186
- const executeCommand = (config: { [ platform: string ]: string[] | string }, platformOverride?: string) => {
187
+ const executeCommand = (config: { [ platform: string ]: string[] | string }, platformOverride?: string, fatalOnFailure = false) => {
187
188
  const platform = platformOverride ?? detectPlatform()
188
189
  const osName = platform.split(":")[0]
189
190
  const command = config[platform] ?? config[`${osName}:*`] ?? config["*"]
@@ -197,7 +198,10 @@ const executeCommand = (config: { [ platform: string ]: string[] | string }, pla
197
198
  reject: false,
198
199
  windowsHide: false
199
200
  })
200
- return result.exitCode
201
+ const exitCode = result.exitCode ?? 1
202
+ if (fatalOnFailure && exitCode !== 0)
203
+ fatal(`failed to execute "${cmd[0]}" (exit ${exitCode})`)
204
+ return exitCode
201
205
  }
202
206
 
203
207
  /* helper to update an externally managed tool with exactly the package
@@ -208,7 +212,7 @@ const updateTool = (tool: string, config: { [ platform: string ]: string[] | str
208
212
  info(`skip update of "${tool}" (not provided by MacPorts or Homebrew)`)
209
213
  return 0
210
214
  }
211
- return executeCommand(config, platform)
215
+ return executeCommand(config, platform, true)
212
216
  }
213
217
 
214
218
  /* helper to determine whether a global NPM installation requires sudo(8),
@@ -283,7 +287,7 @@ const self = async (...args: string[]): Promise<number> => {
283
287
  stdio: "inherit",
284
288
  reject: false
285
289
  })
286
- if ((r.exitCode ?? 0) !== 0)
290
+ if ((r.exitCode ?? 1) !== 0)
287
291
  process.exit(r.exitCode ?? 1)
288
292
  return r.exitCode ?? 0
289
293
  }
@@ -333,7 +337,10 @@ const pruneClaudeVersions = (active: string | null): void => {
333
337
  const versionsDir = path.join(HOME, ".local/share/claude/versions")
334
338
  if (!fs.existsSync(versionsDir))
335
339
  return
336
- for (const f of fs.readdirSync(versionsDir)) {
340
+ const versions = fs.readdirSync(versionsDir)
341
+ if (!versions.includes(active))
342
+ return
343
+ for (const f of versions) {
337
344
  if (f === active)
338
345
  continue
339
346
  try {
@@ -349,6 +356,8 @@ const pruneClaudeVersions = (active: string | null): void => {
349
356
  const detectActiveClaudeVersion = (binName: string): string | null => {
350
357
  try {
351
358
  const r = execaSync(path.join(HOME, ".local/bin", binName), [ "--version" ], { reject: false })
359
+ if (r.exitCode !== 0)
360
+ return null
352
361
  const m = /^(\S+)/.exec(r.stdout ?? "")
353
362
  if (m)
354
363
  return m[1]
@@ -392,12 +401,12 @@ const actionInstall = async (capsula: boolean): Promise<void> => {
392
401
  await self("internal", "capsula", "-s", "sudo", "-E", "apt", "install", "-qq", "-y", "tmux", "lazygit", "git")
393
402
 
394
403
  info("install Node.js")
395
- await self("internal", "capsula", "-s", "sudo", "-E", "bash", "-c", "curl -fsSL https://deb.nodesource.com/setup_24.x | bash -")
404
+ await self("internal", "capsula", "-s", "sudo", "-E", "bash", "-o", "pipefail", "-c", "curl -fsSL https://deb.nodesource.com/setup_24.x | bash -")
396
405
  await self("internal", "capsula", "-s", "sudo", "-E", "apt", "install", "-qq", "-y", "nodejs")
397
406
  await self("internal", "capsula", "-s", "sudo", "-E", "apt", "install", "-qq", "-y", "binutils", "gcc", "g++", "make")
398
407
 
399
408
  info("install Claude Code")
400
- await self("internal", "capsula", "bash", "-c", `PATH="${HOME}/.local/bin:$PATH"; curl -fsSL https://claude.ai/install.sh | bash`)
409
+ await self("internal", "capsula", "bash", "-o", "pipefail", "-c", `PATH=${shQ.quote([ path.join(HOME, ".local/bin") ])}:"$PATH"; curl -fsSL https://claude.ai/install.sh | bash`)
401
410
 
402
411
  info("install ANSI-Recolor")
403
412
  await self("internal", "capsula", "-s", "sudo", "-E", "npm", "install", "-y", "-g", "--allow-scripts=node-pty,tty-attr", "ansi-recolor")
@@ -420,6 +429,7 @@ const actionInstall = async (capsula: boolean): Promise<void> => {
420
429
  "[ -d \"$VERSIONS\" ] || exit 0; " +
421
430
  "ACTIVE=$(\"$HOME/.local/bin/claude\" --version 2>/dev/null | awk '{print $1; exit}'); " +
422
431
  "[ -n \"$ACTIVE\" ] || exit 0; " +
432
+ "[ -f \"$VERSIONS/$ACTIVE\" ] || exit 0; " +
423
433
  "find \"$VERSIONS\" -mindepth 1 -maxdepth 1 ! -name \"$ACTIVE\" -exec rm -rf {} +"
424
434
  )
425
435
  }
@@ -489,7 +499,7 @@ const actionInstall = async (capsula: boolean): Promise<void> => {
489
499
  "windows:choco": "choco install -y --accept-license --no-progress nodejs",
490
500
  "macos:ports": "sudo port -N install nodejs26 npm11",
491
501
  "macos:brew": "brew install node",
492
- "linux:apt": "curl -fsSL https://deb.nodesource.com/setup_26.x | sudo -E bash - && sudo apt install -y nodejs",
502
+ "linux:apt": [ "bash", "-o", "pipefail", "-c", "curl -fsSL https://deb.nodesource.com/setup_26.x | sudo -E bash - && sudo apt install -y nodejs" ],
493
503
  "linux:dnf": "sudo dnf install -y nodejs npm",
494
504
  "linux:yum": "sudo yum install -y nodejs npm",
495
505
  "linux:zypper": "sudo zypper --non-interactive install nodejs npm",
@@ -535,8 +545,8 @@ const actionInstall = async (capsula: boolean): Promise<void> => {
535
545
  /* run installation script */
536
546
  ensureTool("bash", { hint: "https://www.gnu.org/software/bash/" })
537
547
  ensureTool("curl", { hint: "https://curl.se/" })
538
- await execa("bash", [ "-c", `PATH="${HOME}/.local/bin:$PATH"; curl -fsSL https://claude.ai/install.sh | bash` ], {
539
- stdio: "inherit", reject: false
548
+ await execa("bash", [ "-o", "pipefail", "-c", `PATH=${shQ.quote([ path.join(HOME, ".local/bin") ])}:"$PATH"; curl -fsSL https://claude.ai/install.sh | bash` ], {
549
+ stdio: "inherit"
540
550
  })
541
551
 
542
552
  /* prune obsolete versions only after successful install */
@@ -549,7 +559,7 @@ const actionInstall = async (capsula: boolean): Promise<void> => {
549
559
  /* run installation script */
550
560
  ensureTool("powershell")
551
561
  await execa("powershell", [ "-NoProfile", "-Command", "irm https://claude.ai/install.ps1 | iex" ], {
552
- stdio: "inherit", reject: false
562
+ stdio: "inherit"
553
563
  })
554
564
 
555
565
  /* prune obsolete versions only after successful install */
@@ -580,7 +590,7 @@ const actionUpdate = async (capsula: boolean): Promise<void> => {
580
590
  await self("internal", "capsula", "-s", "sudo", "apt", "upgrade", "-qq", "-y")
581
591
 
582
592
  info("update Claude Code")
583
- await self("internal", "capsula", "bash", "-c", `PATH="${HOME}/.local/bin:$PATH"; ${HOME}/.local/bin/claude update`)
593
+ await self("internal", "capsula", "bash", "-c", `PATH=${shQ.quote([ path.join(HOME, ".local/bin") ])}:"$PATH"; ${shQ.quote([ path.join(HOME, ".local/bin/claude") ])} update`)
584
594
 
585
595
  info("update ANSI-Recolor")
586
596
  await self("internal", "capsula", "-s", "sudo", "-E", "npm", "install", "-y", "-g", "--allow-scripts=node-pty,tty-attr", "ansi-recolor")
@@ -657,28 +667,28 @@ const actionUpdate = async (capsula: boolean): Promise<void> => {
657
667
  info("update ANSI-Recolor")
658
668
  executeCommand({
659
669
  "*": npmInstallGlobal("--allow-scripts=node-pty,tty-attr", "ansi-recolor")
660
- })
670
+ }, undefined, true)
661
671
 
662
672
  info("update TypeScript-Language-Server")
663
673
  executeCommand({
664
674
  "*": npmInstallGlobal("typescript-language-server")
665
- })
675
+ }, undefined, true)
666
676
 
667
677
  info("update CodeBurn")
668
678
  executeCommand({
669
679
  "*": npmInstallGlobal("codeburn")
670
- })
680
+ }, undefined, true)
671
681
 
672
682
  info("update ASE")
673
683
  executeCommand({
674
684
  "*": npmInstallGlobal("@rse/ase")
675
- })
685
+ }, undefined, true)
676
686
 
677
687
  info("update Claude Code")
678
688
  if (process.platform !== "win32") {
679
689
  ensureTool("bash")
680
- await execa("bash", [ "-c", `PATH="${HOME}/.local/bin:$PATH"; ${HOME}/.local/bin/claude update` ], {
681
- stdio: "inherit", reject: false
690
+ await execa("bash", [ "-c", `PATH=${shQ.quote([ path.join(HOME, ".local/bin") ])}:"$PATH"; ${shQ.quote([ path.join(HOME, ".local/bin/claude") ])} update` ], {
691
+ stdio: "inherit"
682
692
  })
683
693
 
684
694
  /* prune obsolete versions only after successful update */
@@ -689,7 +699,7 @@ const actionUpdate = async (capsula: boolean): Promise<void> => {
689
699
  fatal("on Windows the \"update\" command has to be run from within a PowerShell session")
690
700
  ensureTool("powershell")
691
701
  await execa("powershell", [ "-NoProfile", "-Command", "claude update" ], {
692
- stdio: "inherit", reject: false
702
+ stdio: "inherit"
693
703
  })
694
704
 
695
705
  /* prune obsolete versions only after successful update */
@@ -743,7 +753,7 @@ const actionInternalTmux = (opts: TopOpts, args: string[]): never => {
743
753
  }
744
754
  conf = conf.replace(/@USER@/g, USER)
745
755
  const confFile = path.join(os.tmpdir(), `claudex-tmux-${process.pid}.conf`)
746
- fs.writeFileSync(confFile, conf, { mode: 0o600 })
756
+ fs.writeFileSync(confFile, conf, { mode: 0o600, flag: "wx" })
747
757
  /* ensure the temp config is removed on normal exit AND on signal-driven
748
758
  termination (SIGINT/SIGTERM); SIGKILL and process panics remain
749
759
  uncoverable. tmux.conf is read once at startup and not re-read via
@@ -755,6 +765,12 @@ const actionInternalTmux = (opts: TopOpts, args: string[]): never => {
755
765
  process.on("exit", cleanup)
756
766
  process.on("SIGINT", () => { cleanup(); process.exit(130) })
757
767
  process.on("SIGTERM", () => { cleanup(); process.exit(143) })
768
+
769
+ /* pass each new Unix session its own invocation environment */
770
+ if (!isPsmux() && args[0] === "new-session")
771
+ for (const name of [ "CLAUDEX_FLAGS", "CLAUDEX_INTERNAL_EXEC", "CLAUDE_MODEL", "OPENROUTER_API_KEY" ])
772
+ args.splice(1, 0, "-e", `${name}=${process.env[name] ?? ""}`)
773
+
758
774
  const r = execaSync("tmux", [
759
775
  "-f", confFile,
760
776
  ...args
@@ -764,7 +780,7 @@ const actionInternalTmux = (opts: TopOpts, args: string[]): never => {
764
780
  windowsHide: false
765
781
  })
766
782
  cleanup()
767
- return process.exit(r.exitCode ?? 0)
783
+ return process.exit(r.exitCode ?? 1)
768
784
  }
769
785
 
770
786
  /* action: internal "shell" -- spawn an interactive login shell */
@@ -835,6 +851,8 @@ const actionInternalCapsula = (_opts: TopOpts, args: string[]): never => {
835
851
  const envOpts: string[] = [ "-e", "!" ]
836
852
  for (const e of envs)
837
853
  envOpts.push("-e", e)
854
+ if (process.env.OPENROUTER_API_KEY !== undefined)
855
+ envOpts.push("-e", "OPENROUTER_API_KEY")
838
856
 
839
857
  /* find list of dot-files (relative to $HOME) */
840
858
  const dotfiles = [
@@ -947,7 +965,7 @@ const actionInternal = async (opts: TopOpts, args: string[]): Promise<void> => {
947
965
  }
948
966
 
949
967
  /* action: top-level command -- run "claude" */
950
- const actionDefault = (opts: TopOpts, args: string[]): never => {
968
+ const actionDefault = async (opts: TopOpts, args: string[]): Promise<never> => {
951
969
  /* build the inner self-invocation flag list. Pass-through "-R"/"-A" only,
952
970
  as "-C" and "-T" are consumed at the outer layer to avoid recursion. */
953
971
  const innerFlags: string[] = []
@@ -986,14 +1004,20 @@ const actionDefault = (opts: TopOpts, args: string[]): never => {
986
1004
 
987
1005
  /* enter already running container and run tmux */
988
1006
  return execInherit("docker", [
989
- "exec", "-i", "-t", container,
1007
+ "exec", "-i", ...(process.stdin.isTTY ? [ "-t" ] : []),
1008
+ "-w", process.cwd(),
1009
+ "-e", `CLAUDE_MODEL=${process.env.CLAUDE_MODEL ?? ""}`,
1010
+ ...(process.env.OPENROUTER_API_KEY !== undefined ? [ "-e", "OPENROUTER_API_KEY" ] : []),
1011
+ container,
990
1012
  "bash", "-c",
991
1013
  `TERM=${shQ.quote([ TERM ])} ` +
992
1014
  `HOME=${shQ.quote([ HOME ])} ` +
993
1015
  `CLAUDEX_FLAGS=${shQ.quote([ claudexFlags ])} ` +
1016
+ `CLAUDEX_INTERNAL_EXEC=${shQ.quote([ inPane ])} ` +
994
1017
  `sudo -E -u ${shQ.quote([ USER ])} ` +
995
1018
  `${shQ.quote([ "node" /* process.execPath is not valid inside container! */, selfPathJS ])} ` +
996
- `${opts.ase ? "-A " : ""}internal tmux new-session -A -s ${shQ.quote([ session ])}`
1019
+ `${opts.ase ? "-A " : ""}internal tmux new-session -A -s ${shQ.quote([ session ])} ` +
1020
+ `-n claude ${shQ.quote([ "claudex internal exec" ])}`
997
1021
  ])
998
1022
  }
999
1023
  else {
@@ -1041,7 +1065,11 @@ const actionDefault = (opts: TopOpts, args: string[]): never => {
1041
1065
 
1042
1066
  /* enter already running container and run claude (single-quote shell-escape) */
1043
1067
  return execInherit("docker", [
1044
- "exec", "-i", "-t", container,
1068
+ "exec", "-i", ...(process.stdin.isTTY ? [ "-t" ] : []),
1069
+ "-w", process.cwd(),
1070
+ "-e", `CLAUDE_MODEL=${process.env.CLAUDE_MODEL ?? ""}`,
1071
+ ...(process.env.OPENROUTER_API_KEY !== undefined ? [ "-e", "OPENROUTER_API_KEY" ] : []),
1072
+ container,
1045
1073
  "bash", "-c",
1046
1074
  `TERM=${shQ.quote([ TERM ])} ` +
1047
1075
  `HOME=${shQ.quote([ HOME ])} ` +
@@ -1066,7 +1094,7 @@ const actionDefault = (opts: TopOpts, args: string[]): never => {
1066
1094
  const recolor = opts.recolor === true
1067
1095
  if (recolor)
1068
1096
  ensureTool("ansi-recolor")
1069
- process.env.PATH = `${HOME}/.local/bin:${process.env.PATH ?? ""}`
1097
+ process.env.PATH = `${path.join(HOME, ".local/bin")}${path.delimiter}${process.env.PATH ?? ""}`
1070
1098
  ensureTool("claude")
1071
1099
  const env: Env = { ...process.env }
1072
1100
  const claudeModel = process.env.CLAUDE_MODEL ?? ""
@@ -1111,9 +1139,10 @@ const actionDefault = (opts: TopOpts, args: string[]): never => {
1111
1139
  env.ANTHROPIC_AUTH_TOKEN = "ollama"
1112
1140
  env.ANTHROPIC_BASE_URL = `http://${ohost}`
1113
1141
  env.ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES = capabilities
1114
- env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model
1142
+ env.ANTHROPIC_DEFAULT_FABLE_MODEL = model
1115
1143
  env.ANTHROPIC_DEFAULT_OPUS_MODEL = model
1116
1144
  env.ANTHROPIC_DEFAULT_SONNET_MODEL = model
1145
+ env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model
1117
1146
  env.CLAUDE_CODE_SUBAGENT_MODEL = model
1118
1147
  env.CLAUDE_CODE_ATTRIBUTION_HEADER = "0"
1119
1148
  env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = context
@@ -1149,9 +1178,10 @@ const actionDefault = (opts: TopOpts, args: string[]): never => {
1149
1178
  env.ANTHROPIC_AUTH_TOKEN = process.env.OPENROUTER_API_KEY
1150
1179
  env.ANTHROPIC_BASE_URL = "https://openrouter.ai/api"
1151
1180
  env.ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES = capabilities
1152
- env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model
1181
+ env.ANTHROPIC_DEFAULT_FABLE_MODEL = model
1153
1182
  env.ANTHROPIC_DEFAULT_OPUS_MODEL = model
1154
1183
  env.ANTHROPIC_DEFAULT_SONNET_MODEL = model
1184
+ env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model
1155
1185
  env.CLAUDE_CODE_SUBAGENT_MODEL = model
1156
1186
  env.CLAUDE_CODE_ATTRIBUTION_HEADER = "0"
1157
1187
  env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = context
@@ -1159,10 +1189,69 @@ const actionDefault = (opts: TopOpts, args: string[]): never => {
1159
1189
  env.DISABLE_LOGOUT_COMMAND = "1"
1160
1190
  env.ENABLE_TOOL_SEARCH = "auto"
1161
1191
  }
1192
+ else if (/^codex:/.test(claudeModel)) {
1193
+ const model = claudeModel.slice("codex:".length)
1194
+ if (model.trim() === "")
1195
+ fatal("invalid CLAUDE_MODEL: missing model name in " +
1196
+ `"${claudeModel}" (expected: codex:<model>)`)
1197
+
1198
+ /* reuse a healthy proxy or start a persistent detached server */
1199
+ const baseURL = "http://127.0.0.1:18765"
1200
+ const deadline = Date.now() + 10000
1201
+ let proxy: ReturnType<typeof spawn> | undefined
1202
+ let proxyError = ""
1203
+ while (true) {
1204
+ try {
1205
+ const response = await fetch(`${baseURL}/healthz`, { signal: AbortSignal.timeout(500) })
1206
+ await response.body?.cancel()
1207
+ if (response.ok)
1208
+ break
1209
+ }
1210
+ catch (_e) {
1211
+ /* not ready yet */
1212
+ }
1213
+ if (proxy === undefined) {
1214
+ ensureTool("claude-code-proxy", { hint: "install claude-code-proxy and configure its Codex authentication first" })
1215
+ proxy = spawn("claude-code-proxy", [ "serve", "--port", "18765", "--no-monitor" ], {
1216
+ detached: true,
1217
+ stdio: "ignore",
1218
+ windowsHide: true
1219
+ })
1220
+ proxy.on("error", (err: Error) => { proxyError = err.message })
1221
+ proxy.unref()
1222
+ }
1223
+ else if (proxyError !== "" || proxy.exitCode !== null || proxy.signalCode !== null)
1224
+ fatal("failed to start claude-code-proxy" +
1225
+ (proxyError !== "" ? `: ${proxyError}` : ` (exit ${proxy.exitCode ?? proxy.signalCode})`) +
1226
+ " -- run \"claude-code-proxy serve --port 18765 --no-monitor\" for details")
1227
+ if (Date.now() >= deadline) {
1228
+ proxy.kill()
1229
+ fatal(`claude-code-proxy did not become ready at ${baseURL} within 10 seconds`)
1230
+ }
1231
+ await new Promise((resolve) => setTimeout(resolve, 100))
1232
+ }
1233
+
1234
+ /* override Claude Code configuration as in the claude-codex wrapper */
1235
+ env.ANTHROPIC_BASE_URL = baseURL
1236
+ env.ANTHROPIC_API_KEY = ""
1237
+ env.ANTHROPIC_AUTH_TOKEN = "unused"
1238
+ env.ANTHROPIC_DEFAULT_MODEL = model
1239
+ env.ANTHROPIC_DEFAULT_FABLE_MODEL = "gpt-6-astra[1m]"
1240
+ env.ANTHROPIC_DEFAULT_OPUS_MODEL = "gpt-6.1-sol[1m]"
1241
+ env.ANTHROPIC_DEFAULT_SONNET_MODEL = "gpt-6-luna[1m]"
1242
+ env.ANTHROPIC_DEFAULT_HAIKU_MODEL = "gpt-6-luna[1m]"
1243
+ env.CLAUDE_CODE_SUBAGENT_MODEL = "inherit"
1244
+ env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = "272000"
1245
+ env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1"
1246
+ env.CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK = "1"
1247
+ env.DISABLE_LOGIN_COMMAND = "1"
1248
+ env.DISABLE_LOGOUT_COMMAND = "1"
1249
+ env.ENABLE_TOOL_SEARCH = "auto"
1250
+ }
1162
1251
  else if (claudeModel !== "")
1163
1252
  fatal(`invalid CLAUDE_MODEL "${claudeModel}" ` +
1164
- "(supports only: \"ollama[://<host>[:<port>]]/<model>[?[context=<size>],[capabilities=<list>]]\" " +
1165
- "and \"openrouter:<model>[?[context=<size>],[capabilities=<list>]]\")")
1253
+ "(supports only: \"ollama[://<host>[:<port>]]/<model>[?[context=<size>],[capabilities=<list>]]\", " +
1254
+ "\"openrouter:<model>[?[context=<size>],[capabilities=<list>]]\" and \"codex:<model>\")")
1166
1255
 
1167
1256
  /* override ASE configuration (for its diagram rendering) */
1168
1257
  if (opts.ase) {
@@ -1206,7 +1295,7 @@ const actionDefault = (opts: TopOpts, args: string[]): never => {
1206
1295
  ]
1207
1296
  }
1208
1297
  } as Record<string, unknown>
1209
- if (opts.tmux) {
1298
+ if (process.env.TMUX) {
1210
1299
  claudeSettings = deepmerge(claudeSettings, {
1211
1300
  "env": {
1212
1301
  "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
@@ -1242,7 +1331,7 @@ const actionDefault = (opts: TopOpts, args: string[]): never => {
1242
1331
  /* action: top-level "-h/--help" */
1243
1332
  const actionHelp = (): never => {
1244
1333
  /* run "claude --help" */
1245
- process.env.PATH = `${HOME}/.local/bin:${process.env.PATH ?? ""}`
1334
+ process.env.PATH = `${path.join(HOME, ".local/bin")}${path.delimiter}${process.env.PATH ?? ""}`
1246
1335
  ensureTool("claude")
1247
1336
  const claudeBin = path.join(HOME, ".local/bin/claude")
1248
1337
  execaSync(claudeBin, [ "--help" ], { reject: false, stdio: [ "ignore", "inherit", "inherit" ] })
@@ -1268,7 +1357,7 @@ const actionHelp = (): never => {
1268
1357
  /* action: top-level "-v/-V/--version" */
1269
1358
  const actionVersion = (): never => {
1270
1359
  /* run "claude --version" */
1271
- process.env.PATH = `${HOME}/.local/bin:${process.env.PATH ?? ""}`
1360
+ process.env.PATH = `${path.join(HOME, ".local/bin")}${path.delimiter}${process.env.PATH ?? ""}`
1272
1361
  ensureTool("claude")
1273
1362
  const claudeBin = path.join(HOME, ".local/bin/claude")
1274
1363
  execaSync(claudeBin, [ "--version" ], { reject: false, stdio: [ "ignore", "inherit", "inherit" ] })
@@ -1285,12 +1374,13 @@ const main = async (): Promise<void> => {
1285
1374
  the top-level "-R"/"-C"/"-T"/"-A" flags by default. Merge env-derived
1286
1375
  flags with the command-line flags (env first, command-line second, so
1287
1376
  the user can extend or override on the command line). Skip for the
1288
- "internal" sub-dispatch (which uses CLAUDEX_FLAGS_PASSTHROUGH for
1289
- tmux.conf bind-key flag propagation), and skip flags that are already
1290
- present on argv to avoid duplicating boolean options. */
1377
+ "internal" sub-dispatch; tmux.conf bind-keys invoke plain "claudex",
1378
+ whose defaults come from CLAUDEX_FLAGS. Skip flags already present
1379
+ on argv to avoid duplicating boolean options. */
1291
1380
  {
1292
1381
  const topArgs = process.argv.slice(2)
1293
- const subcmd = topArgs.find((a) => !a.startsWith("-")) ?? ""
1382
+ const subcmd = topArgs.find((a, i) =>
1383
+ !a.startsWith("-") && (i === 0 || (topArgs[i - 1] !== "-T" && topArgs[i - 1] !== "--tmux"))) ?? ""
1294
1384
  const envFlags = (process.env.CLAUDEX_FLAGS ?? "").trim()
1295
1385
  const claudeNativeSubcmds = [
1296
1386
  "agents", "auth", "auto-mode", "doctor", "mcp",
@@ -1334,7 +1424,19 @@ const main = async (): Promise<void> => {
1334
1424
  }
1335
1425
 
1336
1426
  /* insert in front of the other arguments */
1337
- const toInsert = filtered.filter((t) => !present(t))
1427
+ const toInsert: string[] = []
1428
+ for (let i = 0; i < filtered.length; i++) {
1429
+ const t = filtered[i]
1430
+ const hasSession = (t === "-T" || t === "--tmux")
1431
+ && i + 1 < filtered.length && !filtered[i + 1].startsWith("-")
1432
+ if (!present(t)) {
1433
+ toInsert.push(t)
1434
+ if (hasSession)
1435
+ toInsert.push(filtered[i + 1])
1436
+ }
1437
+ if (hasSession)
1438
+ i++
1439
+ }
1338
1440
  if (toInsert.length > 0)
1339
1441
  process.argv.splice(2, 0, ...toInsert)
1340
1442
  }
@@ -1343,7 +1445,8 @@ const main = async (): Promise<void> => {
1343
1445
  /* intercept top-level "-h/--help" and "-v/-V/--version" before commander
1344
1446
  grabs them, so we can pass-through to "claude" and append our extension info */
1345
1447
  const topArgs = process.argv.slice(2)
1346
- const firstNonFlag = topArgs.findIndex((a) => !a.startsWith("-"))
1448
+ const firstNonFlag = topArgs.findIndex((a, i) =>
1449
+ !a.startsWith("-") && (i === 0 || (topArgs[i - 1] !== "-T" && topArgs[i - 1] !== "--tmux")))
1347
1450
  const headFlags = firstNonFlag < 0 ? topArgs : topArgs.slice(0, firstNonFlag)
1348
1451
  const subcmd = firstNonFlag < 0 ? "" : topArgs[firstNonFlag]
1349
1452
  if ((headFlags.includes("-h") || headFlags.includes("--help"))
@@ -1367,8 +1470,8 @@ const main = async (): Promise<void> => {
1367
1470
  .option("-R, --recolor", "wrap Claude Code with ANSI recoloring for improved theming")
1368
1471
  .option("-A, --ase", "enable ASE-specific ASE_* environment variables and Tmux settings")
1369
1472
  .argument("[args...]", "arguments passed unparsed to Claude Code")
1370
- .action((args: string[], opts: TopOpts) => {
1371
- actionDefault(opts, args)
1473
+ .action(async (args: string[], opts: TopOpts) => {
1474
+ await actionDefault(opts, args)
1372
1475
  })
1373
1476
 
1374
1477
  /* dispatch "install" sub-command */
@@ -1407,6 +1510,7 @@ const main = async (): Promise<void> => {
1407
1510
  .command("internal")
1408
1511
  .description("internal command dispatcher (tmux, shell, lazygit, ase-task-edit, capsula)")
1409
1512
  .helpOption("-h, --help", "display help for command")
1513
+ .passThroughOptions()
1410
1514
  .allowUnknownOption()
1411
1515
  .argument("[args...]", "internal command name and its arguments")
1412
1516
  .action(async (args: string[], _opts: object, cmd: Command) => {
package/lazygit.yaml CHANGED
@@ -40,10 +40,10 @@ gui:
40
40
  - blue
41
41
  sidePanels:
42
42
  - [ files ]
43
- - [ worktrees ]
44
- - [ branches, submodules ]
45
- - [ commits, reflog, tags ]
46
43
  - [ stash ]
44
+ - [ commits, reflog, tags ]
45
+ - [ branches, submodules ]
46
+ - [ worktrees ]
47
47
  spinner:
48
48
  frames:
49
49
  - ●∙∙∙
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rse/claudex",
3
3
  "publishConfig": { "access": "public" },
4
- "version": "1.0.17",
4
+ "version": "1.1.1",
5
5
  "description": "Claude Code eXtended",
6
6
  "type": "module",
7
7
  "keywords": [ "claude", "code", "extension", "wrapper" ],