@rse/claudex 0.9.13 → 0.9.14

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/claudex.js CHANGED
@@ -10,6 +10,7 @@ import * as os from "node:os";
10
10
  import { execa, execaSync } from "execa";
11
11
  import which from "which";
12
12
  import chalk from "chalk";
13
+ import { Command } from "commander";
13
14
  /* determine our base directory (handle absolute, relative, PATH, symlinks) */
14
15
  const findBaseDir = () => {
15
16
  const argv1 = process.argv[1] ?? "";
@@ -28,8 +29,6 @@ const basedir = findBaseDir();
28
29
  and embedded shell strings (docker/tmux) need a runnable command */
29
30
  const selfPath = path.join(basedir, "claudex");
30
31
  const selfPathJS = process.argv[1] ?? path.join(basedir, "claudex.js");
31
- /* command line arguments (after node and script path) */
32
- let argv = process.argv.slice(2);
33
32
  /* helper for displaying info messages */
34
33
  const info = (msg) => {
35
34
  process.stderr.write(`${chalk.blue("claudex: ")}${chalk.blue.bold("INFO:")}${chalk.blue(` ${msg}`)}\n`);
@@ -42,6 +41,28 @@ const fatal = (msg) => {
42
41
  /* helper for detecting the platform and package manager combination */
43
42
  const detectPlatform = () => {
44
43
  const has = (tool) => which.sync(tool, { nothrow: true }) !== null;
44
+ /* honor explicit override via CLAUDEX_PKG (e.g. "brew", "ports", "apt", ...)
45
+ to disambiguate hosts where multiple package managers are installed */
46
+ const override = process.env.CLAUDEX_PKG ?? "";
47
+ if (override !== "") {
48
+ const pm = {
49
+ winget: { plat: "win32", tool: "winget", key: "windows:winget" },
50
+ choco: { plat: "win32", tool: "choco", key: "windows:choco" },
51
+ ports: { plat: "darwin", tool: "port", key: "macos:ports" },
52
+ brew: { plat: "darwin", tool: "brew", key: "macos:brew" },
53
+ apt: { plat: "linux", tool: "apt", key: "linux:apt" },
54
+ apk: { plat: "linux", tool: "apk", key: "linux:apk" }
55
+ };
56
+ const entry = pm[override];
57
+ if (entry === undefined)
58
+ return fatal(`unknown CLAUDEX_PKG value "${override}" ` +
59
+ `(allowed: ${Object.keys(pm).join(", ")})`);
60
+ if (process.platform !== entry.plat)
61
+ return fatal(`CLAUDEX_PKG="${override}" is not valid on platform "${process.platform}"`);
62
+ if (!has(entry.tool))
63
+ return fatal(`CLAUDEX_PKG="${override}" requested but tool "${entry.tool}" not found in $PATH`);
64
+ return entry.key;
65
+ }
45
66
  if (process.platform === "win32" && has("winget"))
46
67
  return "windows:winget";
47
68
  else if (process.platform === "win32" && has("choco"))
@@ -59,8 +80,8 @@ const detectPlatform = () => {
59
80
  };
60
81
  /* helper to spawn a child synchronously inheriting stdio, then exit
61
82
  with its code (the closest equivalent of Bash "exec ...") */
62
- const execInherit = async (file, args, opts = {}) => {
63
- const r = await execa(file, args, {
83
+ const execInherit = (file, args, opts = {}) => {
84
+ const r = execaSync(file, args, {
64
85
  stdio: "inherit",
65
86
  env: opts.env,
66
87
  reject: false,
@@ -74,7 +95,7 @@ const executeCommand = (config) => {
74
95
  const osName = platform.split(":")[0];
75
96
  const command = config[platform] ?? config[`${osName}:*`];
76
97
  if (command === undefined)
77
- return -1;
98
+ fatal(`no command configured for platform "${platform}"`);
78
99
  const cmd = command instanceof Array ? command : command.split(/\s+/);
79
100
  info(`execute: $ ${cmd.join(" ")}`);
80
101
  const result = execaSync(cmd[0], cmd.slice(1), {
@@ -89,22 +110,31 @@ const executeCommand = (config) => {
89
110
  const ensureTool = (tool, options = {}) => {
90
111
  const tools = typeof tool === "string" ? [tool] : tool;
91
112
  for (const tool of tools) {
92
- const r = which.sync(tool, { nothrow: true });
93
- if (r === null) {
94
- if (options.install) {
95
- const returnCode = executeCommand(options.install);
96
- if (returnCode === 0)
113
+ let r = which.sync(tool, { nothrow: true });
114
+ if (r === null && options.install) {
115
+ const rc = executeCommand(options.install);
116
+ if (rc !== 0) {
117
+ if (options.optional)
97
118
  continue;
119
+ fatal(`failed to install required tool "${tool}" (exit ${rc})` +
120
+ (options.hint !== undefined ? ` -- hint: ${options.hint}` : ""));
98
121
  }
99
- if (options.optional)
100
- continue;
101
- if (options.hint !== undefined)
102
- fatal(`required tool "${tool}" not found in $PATH -- hint: ${options.hint}`);
103
- else
104
- fatal(`required tool "${tool}" not found in $PATH`);
122
+ r = which.sync(tool, { nothrow: true });
105
123
  }
124
+ if (r !== null)
125
+ continue;
126
+ if (options.optional)
127
+ continue;
128
+ if (options.hint !== undefined)
129
+ fatal(`required tool "${tool}" not found in $PATH -- hint: ${options.hint}`);
130
+ else
131
+ fatal(`required tool "${tool}" not found in $PATH`);
106
132
  }
107
133
  };
134
+ /* helper to POSIX-single-quote-escape a string for safe interpolation
135
+ into a "bash -c" command line (defense against shell injection of
136
+ user-supplied or env-derived values) */
137
+ const shq = (s) => `'${s.replace(/'/g, "'\\''")}'`;
108
138
  /* re-invoke this same script (mirrors "$0 ..." in Bash) */
109
139
  const self = async (...args) => {
110
140
  const r = await execa(process.execPath, [selfPathJS, ...args], {
@@ -115,585 +145,714 @@ const self = async (...args) => {
115
145
  process.exit(r.exitCode ?? 1);
116
146
  return r.exitCode ?? 0;
117
147
  };
118
- /* sanity check usage */
119
- if (argv.length === 0) {
120
- process.stderr.write("claudex: ERROR: missing command\n");
121
- process.stderr.write("claudex: USAGE: claudex install\n");
122
- process.stderr.write("claudex: USAGE: claudex update\n");
123
- process.stderr.write("claudex: USAGE: claudex session\n");
124
- process.stderr.write("claudex: USAGE: claudex shell [...]\n");
125
- process.stderr.write("claudex: USAGE: claudex claude [...]\n");
126
- process.exit(1);
127
- }
128
- /* support special "-s" (sandbox) option */
129
- let sandbox = false;
130
- if (argv.length >= 1 && argv[0] === "-s") {
131
- argv = argv.slice(1);
132
- sandbox = true;
133
- }
134
- /* determine command */
135
- const cmd = argv[0];
136
- argv = argv.slice(1);
148
+ /* detect the session/project name by walking up from the current working
149
+ directory looking for an AGENTS.md / CLAUDE.md marker; fall back to the
150
+ basename of the current working directory */
151
+ const detectSessionName = () => {
152
+ let dir = process.cwd();
153
+ while (true) {
154
+ if (fs.existsSync(path.join(dir, "AGENTS.md")) || fs.existsSync(path.join(dir, "CLAUDE.md")))
155
+ return path.basename(dir);
156
+ const parent = path.dirname(dir);
157
+ if (parent === dir)
158
+ break;
159
+ dir = parent;
160
+ }
161
+ const session = path.basename(process.cwd()) || "default";
162
+ info(`no AGENTS.md/CLAUDE.md marker found; using cwd basename "${session}" as session name`);
163
+ return session;
164
+ };
137
165
  /* determine information */
138
166
  const HOME = process.env.HOME ?? os.homedir();
139
167
  const USER = process.env.USER ?? "";
140
168
  const TERM = process.env.TERM ?? "";
141
169
  const ENVIRONMENT = process.env.ENVIRONMENT ?? "";
142
- /* the main procedure */
143
- const main = async () => {
144
- /* dispatch according to command */
145
- switch (cmd) {
146
- case "version": {
147
- const ver = JSON.parse(fs.readFileSync(path.join(basedir, "package.json"), "utf8")).version;
148
- process.stdout.write(`claudeX ${ver}\n`);
149
- break;
170
+ /* helper: prune all but the given active Claude Code version */
171
+ const pruneClaudeVersions = (active) => {
172
+ if (active === null)
173
+ return;
174
+ const versionsDir = path.join(HOME, ".local/share/claude/versions");
175
+ if (!fs.existsSync(versionsDir))
176
+ return;
177
+ for (const f of fs.readdirSync(versionsDir)) {
178
+ if (f === active)
179
+ continue;
180
+ try {
181
+ fs.rmSync(path.join(versionsDir, f), { recursive: true, force: true });
150
182
  }
151
- case "install": {
152
- /* sanity check environment */
153
- if (ENVIRONMENT === "capsula")
154
- fatal("cannot execute \"install\" command from within Capsula environment");
155
- /* ensure we are not running from the home directory
156
- in order to not read-write mount its ~/.local/! */
157
- try {
158
- process.chdir(basedir);
159
- }
160
- catch (_e) {
161
- fatal("cannot switch to base directory");
162
- }
163
- /* dispatch according to host/container mode */
164
- if (sandbox) {
165
- info("update Debian GNU/Linux operating system");
166
- await self("shell", "-s", "sudo", "-E", "apt", "update", "-qq");
167
- await self("shell", "-s", "sudo", "-E", "apt", "upgrade", "-qq", "-y");
168
- info("install Tmux / LazyGit / Git");
169
- await self("shell", "-s", "sudo", "-E", "apt", "install", "-qq", "-y", "tmux", "lazygit", "git");
170
- info("install Node.js");
171
- await self("shell", "-s", "sudo", "-E", "bash", "-c", "curl -fsSL https://deb.nodesource.com/setup_24.x | bash -");
172
- await self("shell", "-s", "sudo", "-E", "apt", "install", "-qq", "-y", "nodejs");
173
- await self("shell", "-s", "sudo", "-E", "apt", "install", "-qq", "-y", "binutils", "gcc", "g++", "make");
174
- info("install Claude Code");
175
- await self("shell", "bash", "-c", "rm -f $HOME/.local/bin/claude");
176
- await self("shell", "bash", "-c", "rm -f $HOME/.local/share/claude/versions/*");
177
- await self("shell", "bash", "-c", `PATH="${HOME}/.local/bin:$PATH"; curl -kfsSL https://claude.ai/install.sh | bash`);
178
- info("install ANSI-Recolor");
179
- await self("shell", "-s", "sudo", "-E", "npm", "install", "-y", "-g", "ansi-recolor");
180
- info("install TypeScript LS");
181
- await self("shell", "-s", "sudo", "-E", "npm", "install", "-y", "-g", "typescript-language-server");
182
- info("install Claude wrapper");
183
- await self("shell", "-s", "sudo", "install", "-c", "-m", "755", `${basedir}/claude`, "/usr/bin/claude");
184
- }
185
- else {
186
- const platform = detectPlatform();
187
- info("install Tmux");
188
- ensureTool("tmux", {
189
- hint: platform.match(/^windows:/) ?
190
- "https://github.com/psmux/psmux" :
191
- "https://github.com/tmux/tmux/",
192
- install: {
193
- "windows:winget": "winget install --accept-package-agreements --accept-source-agreements --silent -e psmux",
194
- "windows:choco": "choco install -y --accept-license --no-progress psmux",
195
- "macos:ports": "sudo port -N install tmux",
196
- "macos:brew": "sudo brew install tmux",
197
- "linux:apt": "sudo apt install -y tmux",
198
- "linux:apk": "sudo apk add --no-interactive tmux"
199
- }
200
- });
201
- info("install LazyGit");
202
- ensureTool("lazygit", {
203
- optional: true,
204
- hint: "https://github.com/jesseduffield/lazygit/",
205
- install: {
206
- "windows:winget": "winget install --accept-package-agreements --accept-source-agreements --silent -e --id JesseDuffield.lazygit",
207
- "windows:choco": "choco install -y --accept-license --no-progress lazygit",
208
- "macos:ports": "sudo port -N install lazygit",
209
- "macos:brew": "sudo brew install lazygit",
210
- "linux:apt": "sudo apt install -y lazygit",
211
- "linux:apk": "sudo apk add --no-interactive lazygit"
212
- }
213
- });
214
- info("install Git");
215
- ensureTool("git", {
216
- optional: true,
217
- hint: "https://git-scm.com",
218
- install: {
219
- "windows:winget": "winget install --accept-package-agreements --accept-source-agreements --silent -e --id Git.Git --source winget",
220
- "windows:choco": "choco install -y --accept-license --no-progress git",
221
- "macos:ports": "sudo port -N install git",
222
- "macos:brew": "sudo brew install git",
223
- "linux:apt": "sudo apt install -y git",
224
- "linux:apk": "sudo apk add --no-interactive git"
225
- }
226
- });
227
- info("install Node.js");
228
- ensureTool(["node", "npm"], {
229
- hint: "https://nodejs.org",
230
- install: {
231
- "windows:winget": "winget install --accept-package-agreements --accept-source-agreements --silent -e --id OpenJS.NodeJS.LTS",
232
- "windows:choco": "choco install -y --accept-license --no-progress nodejs",
233
- "macos:ports": "sudo port -N install nodejs24 npm11",
234
- "macos:brew": "sudo brew install node",
235
- "linux:apt": "curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash - && sudo apt install -y nodejs",
236
- "linux:apk": "sudo apk add --no-interactive nodejs npm"
237
- }
238
- });
239
- info("install ANSI-Recolor");
240
- ensureTool("ansi-recolor", {
241
- hint: "https://github.com/rse/ansi-recolor",
242
- install: {
243
- "windows:*": "npm install -g ansi-recolor",
244
- "macos:*": "sudo npm install -g ansi-recolor",
245
- "linux:*": "sudo npm install -g ansi-recolor"
246
- }
247
- });
248
- info("install TypeScript-Language-Server");
249
- ensureTool("typescript-language-server", {
250
- hint: "https://github.com/typescript-language-server/typescript-language-server",
251
- install: {
252
- "windows:*": "npm install -g typescript-language-server",
253
- "macos:*": "sudo npm install -g typescript-language-server",
254
- "linux:*": "sudo npm install -g typescript-language-server"
255
- }
256
- });
257
- info("install Claude Code");
258
- /* helper: remove obsolete Claude Code versions */
259
- const removeObsoleteClaudeVersions = (binName) => {
260
- try {
261
- fs.unlinkSync(path.join(HOME, ".local/bin", binName));
262
- }
263
- catch (_e) {
264
- }
265
- const versionsDir = path.join(HOME, ".local/share/claude/versions");
266
- if (fs.existsSync(versionsDir)) {
267
- for (const f of fs.readdirSync(versionsDir)) {
268
- try {
269
- fs.unlinkSync(path.join(versionsDir, f));
270
- }
271
- catch (_e) {
272
- }
273
- }
274
- }
275
- };
276
- if (process.platform !== "win32") {
277
- removeObsoleteClaudeVersions("claude");
278
- /* run installation script */
279
- ensureTool("bash", { hint: "https://www.gnu.org/software/bash/" });
280
- ensureTool("curl", { hint: "https://curl.se/" });
281
- await execa("bash", ["-c", `PATH="${HOME}/.local/bin:$PATH"; curl -kfsSL https://claude.ai/install.sh | bash`], {
282
- stdio: "inherit", reject: false
283
- });
284
- }
285
- else {
286
- if (!process.env.PSModulePath)
287
- fatal("on Windows the \"install\" command has to be run from within a PowerShell session");
288
- removeObsoleteClaudeVersions("claude.exe");
289
- /* run installation script */
290
- ensureTool("powershell");
291
- await execa("powershell", ["-NoProfile", "-Command", "irm https://claude.ai/install.ps1 | iex"], {
292
- stdio: "inherit", reject: false
293
- });
294
- }
295
- }
296
- break;
183
+ catch (_e) {
297
184
  }
298
- case "update": {
299
- /* sanity check environment */
300
- if (ENVIRONMENT === "capsula")
301
- fatal("cannot execute \"update\" command from within Capsula environment");
302
- /* ensure we are not running from the home directory
303
- in order to not read-write mount its ~/.local/! */
304
- try {
305
- process.chdir(basedir);
306
- }
307
- catch (_e) {
308
- fatal("cannot switch to base directory");
309
- }
310
- /* dispatch according to host/container mode */
311
- if (sandbox) {
312
- info("update Debian GNU/Linux operating system");
313
- await self("shell", "-s", "sudo", "apt", "update", "-qq");
314
- await self("shell", "-s", "sudo", "apt", "upgrade", "-qq", "-y");
315
- info("update Claude Code");
316
- await self("shell", "bash", "-c", `PATH="${HOME}/.local/bin:$PATH"; ${HOME}/.local/bin/claude update`);
317
- info("update ANSI-Recolor");
318
- await self("shell", "-s", "sudo", "-E", "npm", "install", "-y", "-g", "ansi-recolor");
319
- info("update TypeScript LS");
320
- await self("shell", "-s", "sudo", "-E", "npm", "install", "-y", "-g", "typescript-language-server");
321
- info("update Claude wrapper");
322
- await self("shell", "-s", "sudo", "install", "-c", "-m", "755", `${basedir}/claude`, "/usr/bin/claude");
185
+ }
186
+ };
187
+ /* helper: detect the active Claude Code version via the installed binary */
188
+ const detectActiveClaudeVersion = (binName) => {
189
+ try {
190
+ const r = execaSync(path.join(HOME, ".local/bin", binName), ["--version"], { reject: false });
191
+ const m = /^(\S+)/.exec(r.stdout ?? "");
192
+ if (m)
193
+ return m[1];
194
+ }
195
+ catch (_e) {
196
+ /* binary missing or not executable */
197
+ }
198
+ return null;
199
+ };
200
+ /* action: install host-side or in-container dependencies */
201
+ const actionInstall = async (capsula) => {
202
+ /* sanity check environment */
203
+ if (ENVIRONMENT === "capsula")
204
+ fatal("cannot execute \"install\" command from within Capsula environment");
205
+ /* ensure we are not running from the home directory
206
+ in order to not read-write mount its ~/.local/! */
207
+ try {
208
+ process.chdir(basedir);
209
+ }
210
+ catch (_e) {
211
+ fatal("cannot switch to base directory");
212
+ }
213
+ /* dispatch according to host/container mode */
214
+ if (capsula) {
215
+ info("update Debian GNU/Linux operating system");
216
+ await self("internal", "capsula", "sudo", "-E", "apt", "update", "-qq");
217
+ await self("internal", "capsula", "sudo", "-E", "apt", "upgrade", "-qq", "-y");
218
+ info("install Tmux / LazyGit / Git");
219
+ await self("internal", "capsula", "sudo", "-E", "apt", "install", "-qq", "-y", "tmux", "lazygit", "git");
220
+ info("install Node.js");
221
+ await self("internal", "capsula", "sudo", "-E", "bash", "-c", "curl -fsSL https://deb.nodesource.com/setup_24.x | bash -");
222
+ await self("internal", "capsula", "sudo", "-E", "apt", "install", "-qq", "-y", "nodejs");
223
+ await self("internal", "capsula", "sudo", "-E", "apt", "install", "-qq", "-y", "binutils", "gcc", "g++", "make");
224
+ info("install Claude Code");
225
+ await self("internal", "capsula", "bash", "-c", `PATH="${HOME}/.local/bin:$PATH"; curl -kfsSL https://claude.ai/install.sh | bash`);
226
+ /* prune obsolete versions only after successful install */
227
+ await self("internal", "capsula", "bash", "-c", "VERSIONS=\"$HOME/.local/share/claude/versions\"; " +
228
+ "[ -d \"$VERSIONS\" ] || exit 0; " +
229
+ "ACTIVE=$(\"$HOME/.local/bin/claude\" --version 2>/dev/null | awk '{print $1; exit}'); " +
230
+ "[ -n \"$ACTIVE\" ] || exit 0; " +
231
+ "find \"$VERSIONS\" -mindepth 1 -maxdepth 1 ! -name \"$ACTIVE\" -exec rm -rf {} +");
232
+ info("install ANSI-Recolor");
233
+ await self("internal", "capsula", "sudo", "-E", "npm", "install", "-y", "-g", "ansi-recolor");
234
+ info("install TypeScript LS");
235
+ await self("internal", "capsula", "sudo", "-E", "npm", "install", "-y", "-g", "typescript-language-server");
236
+ info("install Claude wrapper");
237
+ await self("internal", "capsula", "sudo", "install", "-c", "-m", "755", `${basedir}/claude`, "/usr/bin/claude");
238
+ }
239
+ else {
240
+ const platform = detectPlatform();
241
+ info("install Tmux");
242
+ ensureTool("tmux", {
243
+ hint: platform.match(/^windows:/) ?
244
+ "https://github.com/psmux/psmux" :
245
+ "https://github.com/tmux/tmux/",
246
+ install: {
247
+ "windows:winget": "winget install --accept-package-agreements --accept-source-agreements --silent -e psmux",
248
+ "windows:choco": "choco install -y --accept-license --no-progress psmux",
249
+ "macos:ports": "sudo port -N install tmux",
250
+ "macos:brew": "sudo brew install tmux",
251
+ "linux:apt": "sudo apt install -y tmux",
252
+ "linux:apk": "sudo apk add --no-interactive tmux"
323
253
  }
324
- else {
325
- info("update Tmux");
326
- executeCommand({
327
- "windows:winget": "winget upgrade --accept-package-agreements --accept-source-agreements --silent -e psmux",
328
- "windows:choco": "choco upgrade -y --accept-license --no-progress psmux",
329
- "macos:ports": "sudo port -N upgrade tmux",
330
- "macos:brew": "sudo brew upgrade tmux",
331
- "linux:apt": "sudo apt install --only-upgrade -y tmux",
332
- "linux:apk": "sudo apk upgrade --no-interactive tmux"
333
- });
334
- info("update LazyGit");
335
- executeCommand({
336
- "windows:winget": "winget upgrade --accept-package-agreements --accept-source-agreements --silent -e --id JesseDuffield.lazygit",
337
- "windows:choco": "choco upgrade -y --accept-license --no-progress lazygit",
338
- "macos:ports": "sudo port -N upgrade lazygit",
339
- "macos:brew": "sudo brew upgrade lazygit",
340
- "linux:apt": "sudo apt install --only-upgrade -y lazygit",
341
- "linux:apk": "sudo apk upgrade --no-interactive lazygit"
342
- });
343
- info("update Git");
344
- executeCommand({
345
- "windows:winget": "winget upgrade --accept-package-agreements --accept-source-agreements --silent -e --id Git.Git --source winget",
346
- "windows:choco": "choco upgrade -y --accept-license --no-progress git",
347
- "macos:ports": "sudo port -N upgrade git",
348
- "macos:brew": "sudo brew upgrade git",
349
- "linux:apt": "sudo apt install --only-upgrade -y git",
350
- "linux:apk": "sudo apk upgrade --no-interactive git"
351
- });
352
- info("update Node.js");
353
- executeCommand({
354
- "windows:winget": "winget upgrade --accept-package-agreements --accept-source-agreements --silent -e --id OpenJS.NodeJS.LTS",
355
- "windows:choco": "choco upgrade -y --accept-license --no-progress nodejs",
356
- "macos:ports": "sudo port -N upgrade nodejs24 npm11",
357
- "macos:brew": "sudo brew upgrade node",
358
- "linux:apt": "sudo apt install --only-upgrade -y nodejs",
359
- "linux:apk": "sudo apk upgrade --no-interactive nodejs npm"
360
- });
361
- info("update ANSI-Recolor");
362
- executeCommand({
363
- "windows:*": "npm install -g ansi-recolor",
364
- "macos:*": "sudo npm install -g ansi-recolor",
365
- "linux:*": "sudo npm install -g ansi-recolor"
366
- });
367
- info("update TypeScript-Language-Server");
368
- executeCommand({
369
- "windows:*": "npm install -g typescript-language-server",
370
- "macos:*": "sudo npm install -g typescript-language-server",
371
- "linux:*": "sudo npm install -g typescript-language-server"
372
- });
373
- info("update Claude Code");
374
- if (process.platform !== "win32") {
375
- ensureTool("bash");
376
- await execa("bash", ["-c", `PATH="${HOME}/.local/bin:$PATH"; ${HOME}/.local/bin/claude update`], {
377
- stdio: "inherit", reject: false
378
- });
379
- }
380
- else {
381
- if (!process.env.PSModulePath)
382
- fatal("on Windows the \"update\" command has to be run from within a PowerShell session");
383
- ensureTool("powershell");
384
- await execa("powershell", ["-NoProfile", "-Command", "claude update"], {
385
- stdio: "inherit", reject: false
386
- });
387
- }
254
+ });
255
+ info("install LazyGit");
256
+ ensureTool("lazygit", {
257
+ optional: true,
258
+ hint: "https://github.com/jesseduffield/lazygit/",
259
+ install: {
260
+ "windows:winget": "winget install --accept-package-agreements --accept-source-agreements --silent -e --id JesseDuffield.lazygit",
261
+ "windows:choco": "choco install -y --accept-license --no-progress lazygit",
262
+ "macos:ports": "sudo port -N install lazygit",
263
+ "macos:brew": "sudo brew install lazygit",
264
+ "linux:apt": "sudo apt install -y lazygit",
265
+ "linux:apk": "sudo apk add --no-interactive lazygit"
388
266
  }
389
- break;
390
- }
391
- case "session": {
392
- /* sanity check environment */
393
- if (ENVIRONMENT === "capsula")
394
- fatal("cannot execute \"session\" command from within Capsula environment");
395
- /* determine session name */
396
- let session = "default";
397
- if (argv.length >= 1) {
398
- session = argv[0];
399
- argv = argv.slice(1);
267
+ });
268
+ info("install Git");
269
+ ensureTool("git", {
270
+ optional: true,
271
+ hint: "https://git-scm.com",
272
+ install: {
273
+ "windows:winget": "winget install --accept-package-agreements --accept-source-agreements --silent -e --id Git.Git --source winget",
274
+ "windows:choco": "choco install -y --accept-license --no-progress git",
275
+ "macos:ports": "sudo port -N install git",
276
+ "macos:brew": "sudo brew install git",
277
+ "linux:apt": "sudo apt install -y git",
278
+ "linux:apk": "sudo apk add --no-interactive git"
400
279
  }
401
- else {
402
- let dir = process.cwd();
403
- while (true) {
404
- if (fs.existsSync(path.join(dir, "AGENTS.md")) || fs.existsSync(path.join(dir, "CLAUDE.md"))) {
405
- session = path.basename(dir);
406
- break;
407
- }
408
- const parent = path.dirname(dir);
409
- if (parent === dir)
410
- break;
411
- dir = parent;
412
- }
280
+ });
281
+ info("install Node.js");
282
+ ensureTool(["node", "npm"], {
283
+ hint: "https://nodejs.org",
284
+ install: {
285
+ "windows:winget": "winget install --accept-package-agreements --accept-source-agreements --silent -e --id OpenJS.NodeJS.LTS",
286
+ "windows:choco": "choco install -y --accept-license --no-progress nodejs",
287
+ "macos:ports": "sudo port -N install nodejs24 npm11",
288
+ "macos:brew": "sudo brew install node",
289
+ "linux:apt": "curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash - && sudo apt install -y nodejs",
290
+ "linux:apk": "sudo apk add --no-interactive nodejs npm"
413
291
  }
414
- /* dispatch according to environment */
415
- if (sandbox) {
416
- /* enter/start container */
417
- ensureTool("docker");
418
- const container = `capsula-${USER}-debian-claude-${session}`;
419
- const inspect = execaSync("docker", ["inspect", container], { reject: false, stdio: "ignore" });
420
- if (inspect.exitCode === 0) {
421
- /* enter already running container and run tmux */
422
- await execInherit("docker", [
423
- "exec", "-i", "-t", container,
424
- "bash", "-c",
425
- `TERM=${TERM} HOME=${HOME} sudo -E -u ${USER} ${selfPath} util tmux new-session -A -s "${session}"`
426
- ]);
427
- }
428
- else {
429
- /* start a new container and run tmux */
430
- await self("shell", "-C", container, selfPath, "util", "tmux", "new-session", "-A", "-s", session, "-n", "claude", selfPath + " claude");
431
- process.exit(0);
432
- }
292
+ });
293
+ info("install ANSI-Recolor");
294
+ ensureTool("ansi-recolor", {
295
+ hint: "https://github.com/rse/ansi-recolor",
296
+ install: {
297
+ "windows:*": "npm install -g ansi-recolor",
298
+ "macos:*": "sudo npm install -g ansi-recolor",
299
+ "linux:*": "sudo npm install -g ansi-recolor"
433
300
  }
434
- else {
435
- /* enter/start plain tmux */
436
- await execInherit(selfPath, ["util", "tmux", "new-session", "-A", "-s", session, "-n", "claude", `${selfPath} claude`]);
301
+ });
302
+ info("install TypeScript-Language-Server");
303
+ ensureTool("typescript-language-server", {
304
+ hint: "https://github.com/typescript-language-server/typescript-language-server",
305
+ install: {
306
+ "windows:*": "npm install -g typescript-language-server",
307
+ "macos:*": "sudo npm install -g typescript-language-server",
308
+ "linux:*": "sudo npm install -g typescript-language-server"
437
309
  }
438
- break;
310
+ });
311
+ info("install Claude Code");
312
+ if (process.platform !== "win32") {
313
+ /* run installation script */
314
+ ensureTool("bash", { hint: "https://www.gnu.org/software/bash/" });
315
+ ensureTool("curl", { hint: "https://curl.se/" });
316
+ await execa("bash", ["-c", `PATH="${HOME}/.local/bin:$PATH"; curl -kfsSL https://claude.ai/install.sh | bash`], {
317
+ stdio: "inherit", reject: false
318
+ });
319
+ /* prune obsolete versions only after successful install */
320
+ pruneClaudeVersions(detectActiveClaudeVersion("claude"));
321
+ }
322
+ else {
323
+ if (!process.env.PSModulePath)
324
+ fatal("on Windows the \"install\" command has to be run from within a PowerShell session");
325
+ /* run installation script */
326
+ ensureTool("powershell");
327
+ await execa("powershell", ["-NoProfile", "-Command", "irm https://claude.ai/install.ps1 | iex"], {
328
+ stdio: "inherit", reject: false
329
+ });
330
+ /* prune obsolete versions only after successful install */
331
+ pruneClaudeVersions(detectActiveClaudeVersion("claude.exe"));
439
332
  }
440
- case "naked": {
441
- /* sanity check environment */
442
- if (ENVIRONMENT === "capsula")
443
- fatal("cannot execute \"naked\" command from within Capsula environment");
444
- /* dispatch according to environment */
445
- if (sandbox) {
446
- ensureTool("docker");
447
- const session = "default";
448
- const container = `capsula-${USER}-debian-claude-${session}`;
449
- const inspect = execaSync("docker", ["inspect", container], { reject: false, stdio: "ignore" });
450
- if (inspect.exitCode === 0) {
451
- /* enter already running container and run claude (single-quote shell-escape) */
452
- const passthru = argv.map((a) => `'${a.replace(/'/g, "'\\''")}'`).join(" ");
453
- await execInherit("docker", [
454
- "exec", "-i", "-t", container,
455
- "bash", "-c",
456
- `TERM=${TERM} HOME=${HOME} sudo -E -u ${USER} ${selfPath} claude ${passthru}`
457
- ]);
458
- }
459
- else {
460
- /* start a new container and run claude */
461
- await self("shell", "-C", container, selfPath, "claude", ...argv);
462
- process.exit(0);
463
- }
333
+ }
334
+ };
335
+ /* action: update host-side or in-container components */
336
+ const actionUpdate = async (capsula) => {
337
+ /* sanity check environment */
338
+ if (ENVIRONMENT === "capsula")
339
+ fatal("cannot execute \"update\" command from within Capsula environment");
340
+ /* ensure we are not running from the home directory
341
+ in order to not read-write mount its ~/.local/! */
342
+ try {
343
+ process.chdir(basedir);
344
+ }
345
+ catch (_e) {
346
+ fatal("cannot switch to base directory");
347
+ }
348
+ /* dispatch according to host/container mode */
349
+ if (capsula) {
350
+ info("update Debian GNU/Linux operating system");
351
+ await self("internal", "capsula", "sudo", "apt", "update", "-qq");
352
+ await self("internal", "capsula", "sudo", "apt", "upgrade", "-qq", "-y");
353
+ info("update Claude Code");
354
+ await self("internal", "capsula", "bash", "-c", `PATH="${HOME}/.local/bin:$PATH"; ${HOME}/.local/bin/claude update`);
355
+ info("update ANSI-Recolor");
356
+ await self("internal", "capsula", "sudo", "-E", "npm", "install", "-y", "-g", "ansi-recolor");
357
+ info("update TypeScript LS");
358
+ await self("internal", "capsula", "sudo", "-E", "npm", "install", "-y", "-g", "typescript-language-server");
359
+ info("update Claude wrapper");
360
+ await self("internal", "capsula", "sudo", "install", "-c", "-m", "755", `${basedir}/claude`, "/usr/bin/claude");
361
+ }
362
+ else {
363
+ info("update Tmux");
364
+ executeCommand({
365
+ "windows:winget": "winget upgrade --accept-package-agreements --accept-source-agreements --silent -e psmux",
366
+ "windows:choco": "choco upgrade -y --accept-license --no-progress psmux",
367
+ "macos:ports": "sudo port -N upgrade tmux",
368
+ "macos:brew": "sudo brew upgrade tmux",
369
+ "linux:apt": "sudo apt install --only-upgrade -y tmux",
370
+ "linux:apk": "sudo apk upgrade --no-interactive tmux"
371
+ });
372
+ info("update LazyGit");
373
+ executeCommand({
374
+ "windows:winget": "winget upgrade --accept-package-agreements --accept-source-agreements --silent -e --id JesseDuffield.lazygit",
375
+ "windows:choco": "choco upgrade -y --accept-license --no-progress lazygit",
376
+ "macos:ports": "sudo port -N upgrade lazygit",
377
+ "macos:brew": "sudo brew upgrade lazygit",
378
+ "linux:apt": "sudo apt install --only-upgrade -y lazygit",
379
+ "linux:apk": "sudo apk upgrade --no-interactive lazygit"
380
+ });
381
+ info("update Git");
382
+ executeCommand({
383
+ "windows:winget": "winget upgrade --accept-package-agreements --accept-source-agreements --silent -e --id Git.Git --source winget",
384
+ "windows:choco": "choco upgrade -y --accept-license --no-progress git",
385
+ "macos:ports": "sudo port -N upgrade git",
386
+ "macos:brew": "sudo brew upgrade git",
387
+ "linux:apt": "sudo apt install --only-upgrade -y git",
388
+ "linux:apk": "sudo apk upgrade --no-interactive git"
389
+ });
390
+ info("update Node.js");
391
+ executeCommand({
392
+ "windows:winget": "winget upgrade --accept-package-agreements --accept-source-agreements --silent -e --id OpenJS.NodeJS.LTS",
393
+ "windows:choco": "choco upgrade -y --accept-license --no-progress nodejs",
394
+ "macos:ports": "sudo port -N upgrade nodejs24 npm11",
395
+ "macos:brew": "sudo brew upgrade node",
396
+ "linux:apt": "sudo apt install --only-upgrade -y nodejs",
397
+ "linux:apk": "sudo apk upgrade --no-interactive nodejs npm"
398
+ });
399
+ info("update ANSI-Recolor");
400
+ executeCommand({
401
+ "windows:*": "npm install -g ansi-recolor",
402
+ "macos:*": "sudo npm install -g ansi-recolor",
403
+ "linux:*": "sudo npm install -g ansi-recolor"
404
+ });
405
+ info("update TypeScript-Language-Server");
406
+ executeCommand({
407
+ "windows:*": "npm install -g typescript-language-server",
408
+ "macos:*": "sudo npm install -g typescript-language-server",
409
+ "linux:*": "sudo npm install -g typescript-language-server"
410
+ });
411
+ info("update Claude Code");
412
+ if (process.platform !== "win32") {
413
+ ensureTool("bash");
414
+ await execa("bash", ["-c", `PATH="${HOME}/.local/bin:$PATH"; ${HOME}/.local/bin/claude update`], {
415
+ stdio: "inherit", reject: false
416
+ });
417
+ /* prune obsolete versions only after successful update */
418
+ pruneClaudeVersions(detectActiveClaudeVersion("claude"));
419
+ }
420
+ else {
421
+ if (!process.env.PSModulePath)
422
+ fatal("on Windows the \"update\" command has to be run from within a PowerShell session");
423
+ ensureTool("powershell");
424
+ await execa("powershell", ["-NoProfile", "-Command", "claude update"], {
425
+ stdio: "inherit", reject: false
426
+ });
427
+ /* prune obsolete versions only after successful update */
428
+ pruneClaudeVersions(detectActiveClaudeVersion("claude.exe"));
429
+ }
430
+ }
431
+ };
432
+ /* action: internal "tmux" -- spawn tmux with our generated configuration.
433
+ The tmux.conf bind-keys for new claude panes embed the parent invocation's
434
+ pass-through flags (e.g. "-R") so panes inherit the user's choice; flags
435
+ are transported via the CLAUDEX_FLAGS env var (set by actionDefault when
436
+ entering tmux mode). */
437
+ const actionInternalTmux = (args) => {
438
+ ensureTool("tmux");
439
+ const claudexFlags = process.env.CLAUDEX_FLAGS ?? "";
440
+ const conf = fs.readFileSync(path.join(basedir, "tmux.conf"), "utf8")
441
+ .replace(/@SELFPATH@/g, selfPath)
442
+ .replace(/@CLAUDEXFLAGS@/g, claudexFlags);
443
+ const confFile = path.join(os.tmpdir(), `claudex-tmux-${process.pid}.conf`);
444
+ fs.writeFileSync(confFile, conf, { mode: 0o600 });
445
+ const r = execaSync("tmux", [
446
+ "-f", confFile,
447
+ ...args
448
+ ], {
449
+ stdio: "inherit",
450
+ reject: false,
451
+ windowsHide: false
452
+ });
453
+ try {
454
+ fs.unlinkSync(confFile);
455
+ }
456
+ catch (_e) {
457
+ /* ignore */
458
+ }
459
+ return process.exit(r.exitCode ?? 0);
460
+ };
461
+ /* action: internal "shell" -- spawn an interactive login shell */
462
+ const actionInternalShell = (args) => {
463
+ if (process.platform === "win32") {
464
+ const shell = process.env.SHELL ?? process.env.ComSpec ?? "powershell";
465
+ const name = path.basename(shell).toLowerCase().replace(/\.exe$/, "");
466
+ if (name === "powershell" || name === "pwsh") {
467
+ ensureTool(name);
468
+ return execInherit(name, ["-NoLogo", "-NoProfile", ...args]);
469
+ }
470
+ else {
471
+ ensureTool(shell);
472
+ return execInherit(shell, args);
473
+ }
474
+ }
475
+ else {
476
+ const shell = process.env.SHELL ?? "bash";
477
+ ensureTool(shell);
478
+ return execInherit(shell, ["-l", ...args]);
479
+ }
480
+ };
481
+ /* action: internal "ase-task-edit" -- edit the ASE task associated with the current tmux pane */
482
+ const actionInternalAseTaskEdit = async () => {
483
+ ensureTool("ase");
484
+ let tid = "";
485
+ const r1 = execaSync("tmux", ["display-message", "-p", "#{@ase_task_id}"], { reject: false });
486
+ tid = (r1.stdout ?? "").trim();
487
+ if (tid !== "")
488
+ execInherit("ase", ["task", "edit", tid]);
489
+ else {
490
+ process.stderr.write("no ASE task id known for this pane yet\n");
491
+ await new Promise((resolve) => setTimeout(resolve, 2000));
492
+ }
493
+ };
494
+ /* action: internal "lazygit" -- spawn lazygit (recolored) */
495
+ const actionInternalLazygit = (args) => {
496
+ ensureTool("ansi-recolor");
497
+ ensureTool("git");
498
+ ensureTool("lazygit");
499
+ const env = { ...process.env, TERM: "xterm-color" };
500
+ return execInherit("ansi-recolor", [
501
+ "-c", path.join(basedir, "ansi-recolor.conf"),
502
+ "-m",
503
+ "-n", "lazygit",
504
+ "-t", path.join(HOME, "ansi-recolor.txt"),
505
+ "lazygit", "-ucf", path.join(basedir, "lazygit.yaml"),
506
+ ...args
507
+ ], { env });
508
+ };
509
+ /* action: internal "capsula" -- enter/start a Capsula container with the curated env-var/dotfile setup */
510
+ const actionInternalCapsula = (args) => {
511
+ /* sanity check environment */
512
+ ensureTool("capsula");
513
+ if (ENVIRONMENT === "capsula")
514
+ fatal("cannot execute \"internal capsula\" command from within Capsula environment");
515
+ /* define list of environment variables */
516
+ const envs = ["TERM", "HOME"];
517
+ const envOpts = ["-e", "!"];
518
+ for (const e of envs)
519
+ envOpts.push("-e", e);
520
+ /* find list of dot-files (relative to $HOME) */
521
+ const dotfiles = [
522
+ ".inputrc",
523
+ ".dotfiles/inputrc",
524
+ ".bash_login",
525
+ ".bash_logout",
526
+ ".bashrc",
527
+ ".dotfiles/bashrc",
528
+ ".ssh/authorized_keys",
529
+ ".ssh/known_hosts!",
530
+ ".ssh/config",
531
+ ".dotfiles/sshconfig",
532
+ ".vimrc",
533
+ ".dotfiles/vimrc",
534
+ ".vim",
535
+ ".tmux.conf",
536
+ ".dotfiles/tmux.conf",
537
+ ".gitconfig",
538
+ ".dotfiles/gitconfig",
539
+ ".npmrc",
540
+ ".npm!",
541
+ ".cache!",
542
+ ".claude!",
543
+ ".claude.json!"
544
+ ];
545
+ const dotfileOpts = ["-m", "!"];
546
+ for (const dotfile of dotfiles) {
547
+ const p = dotfile.endsWith("!") ? dotfile.slice(0, -1) : dotfile;
548
+ if (fs.existsSync(path.join(HOME, p)))
549
+ dotfileOpts.push("-m", dotfile);
550
+ }
551
+ /* find all sensitive ".env" files from current working
552
+ directory up to root directory for hiding */
553
+ const nullOpts = ["-n", "!"];
554
+ let dir = process.cwd();
555
+ while (true) {
556
+ const envFile = path.join(dir, ".env");
557
+ if (fs.existsSync(envFile) && fs.statSync(envFile).isFile())
558
+ nullOpts.push("-n", envFile);
559
+ const parent = path.dirname(dir);
560
+ if (parent === dir)
561
+ break;
562
+ dir = parent;
563
+ }
564
+ /* execute */
565
+ return execInherit("capsula", [
566
+ "-c", "claude",
567
+ "-t", "debian",
568
+ "-P", "linux/arm64",
569
+ ...envOpts,
570
+ ...dotfileOpts,
571
+ ...nullOpts,
572
+ "-p", "!",
573
+ "-e", `CLAUDE_MODEL=${process.env.CLAUDE_MODEL ?? ""}`,
574
+ "-e", `CLAUDEX=${basedir}`,
575
+ "-b", basedir,
576
+ ...args
577
+ ]);
578
+ };
579
+ /* action: internal sub-dispatch (tmux, shell, ase-task-edit, lazygit, capsula) */
580
+ const actionInternal = async (args) => {
581
+ const util = args[0];
582
+ const rest = args.slice(1);
583
+ switch (util) {
584
+ case "tmux": return actionInternalTmux(rest);
585
+ case "shell": return actionInternalShell(rest);
586
+ case "ase-task-edit": return actionInternalAseTaskEdit();
587
+ case "lazygit": return actionInternalLazygit(rest);
588
+ case "capsula": return actionInternalCapsula(rest);
589
+ default:
590
+ fatal(`invalid internal command "${util ?? ""}"`);
591
+ }
592
+ };
593
+ /* action: top-level command -- run "claude" */
594
+ const actionDefault = (opts, args) => {
595
+ /* build the inner self-invocation flag list. Pass-through "-R" only,
596
+ as "-C" and "-T" are consumed at the outer layer to avoid recursion. */
597
+ const innerFlags = [];
598
+ if (opts.recolor)
599
+ innerFlags.push("-R");
600
+ /* branch: tmux mode (with or without capsula) */
601
+ if (opts.tmux) {
602
+ /* sanity check environment */
603
+ if (ENVIRONMENT === "capsula")
604
+ fatal("cannot execute tmux mode from within Capsula environment");
605
+ /* determine session name (from "-T <name>" option value, or auto-detected) */
606
+ let session;
607
+ if (typeof opts.tmux === "string" && opts.tmux !== "")
608
+ session = opts.tmux;
609
+ else
610
+ session = detectSessionName();
611
+ const rest = args;
612
+ /* build the in-pane self-invocation shell string (recolor pass-through) */
613
+ const inPane = [shq(selfPath), ...innerFlags.map(shq), ...rest.map(shq)].join(" ");
614
+ /* propagate the chosen pass-through flags to "internal tmux" so its
615
+ tmux.conf bind-keys spawn new claude panes with the same flags */
616
+ const claudexFlags = innerFlags.join(" ");
617
+ process.env.CLAUDEX_FLAGS = claudexFlags;
618
+ /* dispatch according to global options */
619
+ if (opts.capsula) {
620
+ /* enter/start container, then run tmux inside it */
621
+ ensureTool("docker");
622
+ const container = `capsula-${USER}-debian-claude-${session}`;
623
+ const inspect = execaSync("docker", ["inspect", container], { reject: false, stdio: "ignore" });
624
+ if (inspect.exitCode === 0) {
625
+ /* enter already running container and run tmux */
626
+ return execInherit("docker", [
627
+ "exec", "-i", "-t", container,
628
+ "bash", "-c",
629
+ `TERM=${shq(TERM)} HOME=${shq(HOME)} CLAUDEX_FLAGS=${shq(claudexFlags)} sudo -E -u ${shq(USER)} ${shq(selfPath)} internal tmux new-session -A -s ${shq(session)}`
630
+ ]);
464
631
  }
465
632
  else {
466
- /* enter/start plain claude */
467
- await execInherit(selfPath, ["claude", ...argv]);
633
+ /* start a new container and run tmux */
634
+ return execInherit(process.execPath, [
635
+ selfPathJS, "internal", "capsula",
636
+ "-e", `CLAUDEX_FLAGS=${claudexFlags}`,
637
+ "-C", container, selfPath, "internal", "tmux",
638
+ "new-session", "-A", "-s", session, "-n", "claude", inPane
639
+ ]);
468
640
  }
469
- break;
470
641
  }
471
- case "shell": {
472
- /* sanity check environment */
473
- ensureTool("capsula");
474
- if (ENVIRONMENT === "capsula")
475
- fatal("cannot execute \"shell\" command from within Capsula environment");
476
- /* define list of environment variables */
477
- const envs = ["TERM", "HOME"];
478
- const envOpts = ["-e", "!"];
479
- for (const e of envs)
480
- envOpts.push("-e", e);
481
- /* find list of dot-files (relative to $HOME) */
482
- const dotfiles = [
483
- ".inputrc",
484
- ".dotfiles/inputrc",
485
- ".bash_login",
486
- ".bash_logout",
487
- ".bashrc",
488
- ".dotfiles/bashrc",
489
- ".ssh/authorized_keys",
490
- ".ssh/known_hosts!",
491
- ".ssh/config",
492
- ".dotfiles/sshconfig",
493
- ".vimrc",
494
- ".dotfiles/vimrc",
495
- ".vim",
496
- ".tmux.conf",
497
- ".dotfiles/tmux.conf",
498
- ".gitconfig",
499
- ".dotfiles/gitconfig",
500
- ".npmrc",
501
- ".npm!",
502
- ".cache!",
503
- ".claude!",
504
- ".claude.json!"
505
- ];
506
- const dotfileOpts = ["-m", "!"];
507
- for (const dotfile of dotfiles) {
508
- const p = dotfile.endsWith("!") ? dotfile.slice(0, -1) : dotfile;
509
- if (fs.existsSync(path.join(HOME, p)))
510
- dotfileOpts.push("-m", dotfile);
511
- }
512
- /* find all sensitive ".env" files from current working
513
- directory up to root directory for hiding */
514
- const nullOpts = ["-n", "!"];
515
- let dir = process.cwd();
516
- while (true) {
517
- const envFile = path.join(dir, ".env");
518
- if (fs.existsSync(envFile) && fs.statSync(envFile).isFile())
519
- nullOpts.push("-n", envFile);
520
- const parent = path.dirname(dir);
521
- if (parent === dir)
522
- break;
523
- dir = parent;
524
- }
525
- /* execute */
526
- await execInherit("capsula", [
527
- "-c", "claude",
528
- "-t", "debian",
529
- "-P", "linux/arm64",
530
- ...envOpts,
531
- ...dotfileOpts,
532
- ...nullOpts,
533
- "-p", "!",
534
- "-e", `CLAUDE_MODEL=${process.env.CLAUDE_MODEL ?? ""}`,
535
- "-e", `CLAUDEX=${basedir}`,
536
- "-b", basedir,
537
- ...argv
642
+ else {
643
+ /* enter/start plain tmux */
644
+ return execInherit(selfPath, [
645
+ "internal", "tmux", "new-session", "-A", "-s", session, "-n", "claude", inPane
538
646
  ]);
539
- break;
540
647
  }
541
- case "claude": {
542
- /* execute Claude Code */
543
- process.env.PATH = `${HOME}/.local/bin:${process.env.PATH ?? ""}`;
544
- ensureTool("ansi-recolor");
545
- ensureTool("claude");
546
- const env = { ...process.env };
547
- const claudeModel = process.env.CLAUDE_MODEL ?? "";
548
- if (/^ollama:/.test(claudeModel)) {
549
- /* parse ollama[://<host>[:<port>]]/<model>[?[context=<size>],[capabilities=<list>]] */
550
- let remainder = claudeModel.slice("ollama:".length);
551
- let ohost = "localhost:11434";
552
- if (remainder.startsWith("//")) {
553
- remainder = remainder.slice(2);
554
- const slash = remainder.indexOf("/");
555
- if (slash >= 0) {
556
- ohost = remainder.slice(0, slash);
557
- remainder = remainder.slice(slash + 1);
558
- }
559
- else {
560
- ohost = remainder;
561
- remainder = "";
562
- }
563
- }
564
- else if (remainder.startsWith("/"))
565
- remainder = remainder.slice(1);
566
- const qIdx = remainder.indexOf("?");
567
- const model = qIdx >= 0 ? remainder.slice(0, qIdx) : remainder;
568
- let context = "200k";
569
- let capabilities = "";
570
- if (qIdx >= 0) {
571
- const query = remainder.slice(qIdx + 1);
572
- for (const pair of query.split(",")) {
573
- const eq = pair.indexOf("=");
574
- const key = eq >= 0 ? pair.slice(0, eq) : pair;
575
- const val = eq >= 0 ? pair.slice(eq + 1) : "";
576
- if (key === "context")
577
- context = val;
578
- else if (key === "capabilities")
579
- capabilities = val;
580
- }
581
- }
582
- /* override Claude Code configuration */
583
- env.ANTHROPIC_API_KEY = "";
584
- env.ANTHROPIC_AUTH_TOKEN = "ollama";
585
- env.ANTHROPIC_BASE_URL = `http://${ohost}`;
586
- env.ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES = capabilities;
587
- env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model;
588
- env.ANTHROPIC_DEFAULT_OPUS_MODEL = model;
589
- env.ANTHROPIC_DEFAULT_SONNET_MODEL = model;
590
- env.CLAUDE_CODE_ATTRIBUTION_HEADER = "0";
591
- env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = context;
592
- env.CLAUDE_CODE_SUBAGENT_MODEL = model;
593
- env.DISABLE_LOGIN_COMMAND = "1";
594
- env.DISABLE_LOGOUT_COMMAND = "1";
595
- }
596
- /* override ASE configuration (for its diagram rendering) */
597
- if (process.env.ASE_TERM_WIDTH === undefined) {
598
- let width = 0;
599
- if (process.stdout.isTTY) {
600
- const cols = process.stdout.columns;
601
- if (typeof cols === "number" && cols > 0)
602
- width = cols;
603
- }
604
- process.env.ASE_TERM_WIDTH = `${width}`;
648
+ }
649
+ /* branch: capsula-only mode */
650
+ if (opts.capsula) {
651
+ if (ENVIRONMENT === "capsula")
652
+ fatal("cannot execute capsula mode from within Capsula environment");
653
+ ensureTool("docker");
654
+ const session = detectSessionName();
655
+ const container = `capsula-${USER}-debian-claude-${session}`;
656
+ const inspect = execaSync("docker", ["inspect", container], { reject: false, stdio: "ignore" });
657
+ if (inspect.exitCode === 0) {
658
+ /* enter already running container and run claude (single-quote shell-escape) */
659
+ const passthru = [...innerFlags, ...args].map(shq).join(" ");
660
+ return execInherit("docker", [
661
+ "exec", "-i", "-t", container,
662
+ "bash", "-c",
663
+ `TERM=${shq(TERM)} HOME=${shq(HOME)} sudo -E -u ${shq(USER)} ${shq(selfPath)} ${passthru}`
664
+ ]);
665
+ }
666
+ else {
667
+ /* start a new container and run claude */
668
+ return execInherit(process.execPath, [
669
+ selfPathJS, "internal", "capsula", "-C", container, selfPath, ...innerFlags, ...args
670
+ ]);
671
+ }
672
+ }
673
+ /* branch: plain claude -- execute Claude Code, optionally
674
+ wrapped with ansi-recolor when "-R" was given */
675
+ const recolor = opts.recolor === true;
676
+ if (recolor)
677
+ ensureTool("ansi-recolor");
678
+ process.env.PATH = `${HOME}/.local/bin:${process.env.PATH ?? ""}`;
679
+ ensureTool("claude");
680
+ const env = { ...process.env };
681
+ const claudeModel = process.env.CLAUDE_MODEL ?? "";
682
+ if (/^ollama:/.test(claudeModel)) {
683
+ /* parse ollama[://<host>[:<port>]]/<model>[?[context=<size>],[capabilities=<list>]] */
684
+ let remainder = claudeModel.slice("ollama:".length);
685
+ let ohost = "localhost:11434";
686
+ if (remainder.startsWith("//")) {
687
+ remainder = remainder.slice(2);
688
+ const slash = remainder.indexOf("/");
689
+ if (slash >= 0) {
690
+ ohost = remainder.slice(0, slash);
691
+ remainder = remainder.slice(slash + 1);
605
692
  }
606
- if (process.env.ASE_TERM_COLORS === undefined) {
607
- let colorMode = "none";
608
- try {
609
- const { stdout } = execaSync("tput", ["colors"], { reject: false });
610
- const n = parseInt(stdout.trim(), 10);
611
- if (!Number.isNaN(n) && n >= 256)
612
- colorMode = "ansi256";
613
- else if (!Number.isNaN(n) && n >= 16)
614
- colorMode = "ansi16";
615
- }
616
- catch (_e) {
617
- /* ignore */
618
- }
619
- process.env.ASE_TERM_COLORS = `${colorMode}`;
693
+ else {
694
+ ohost = remainder;
695
+ remainder = "";
620
696
  }
621
- const settingsRaw = fs.readFileSync(path.join(basedir, "claude-settings.json"), "utf8");
622
- const settings = settingsRaw.replace(/@BASEDIR@/g, basedir);
623
- await execInherit("ansi-recolor", [
624
- "-c", path.join(basedir, "ansi-recolor.conf"),
625
- "-m",
626
- "-n", "claude",
627
- "-t", path.join(HOME, "ansi-recolor.txt"),
628
- path.join(HOME, ".local/bin/claude"),
629
- "--settings", settings,
630
- ...argv
631
- ], { env });
632
- break;
633
697
  }
634
- case "util": {
635
- const util = argv[0];
636
- argv = argv.slice(1);
637
- switch (util) {
638
- case "tmux": {
639
- ensureTool("tmux");
640
- await execInherit("tmux", [
641
- "-f", path.join(basedir, "tmux.conf"),
642
- "bind-key", "c", "new-window", "-c", "#{pane_current_path}", "-n", "claude", `${selfPath} claude`, ";",
643
- "bind-key", "|", "split-window", "-c", "#{pane_current_path}", "-h", `${selfPath} claude`, ";",
644
- "bind-key", "-", "split-window", "-c", "#{pane_current_path}", "-v", `${selfPath} claude`, ";",
645
- "bind-key", "g", "display-popup", "-E", "-w", "95%", "-h", "95%",
646
- "-T", "─◀#[reverse] ⧉ Version Control (lazygit) #[noreverse]▶", `${selfPath} util lazygit`, ";",
647
- "bind-key", "b", "display-popup", "-E", "-w", "95%", "-h", "95%",
648
- "-T", "─◀#[reverse] ⧉ Shell (bash) #[noreverse]▶", `${selfPath} util bash`, ";",
649
- "bind-key", "q", "display-popup", "-E", "-w", "95%", "-h", "95%",
650
- "-T", "─◀#[reverse] ⧉ Task Edit (ase task edit) #[noreverse]▶", `${selfPath} util ase-task-edit`, ";",
651
- ...argv
652
- ]);
653
- break;
654
- }
655
- case "bash": {
656
- ensureTool("bash");
657
- await execInherit("bash", ["-l", ...argv]);
658
- break;
659
- }
660
- case "ase-task-edit": {
661
- ensureTool("ase");
662
- let tid = "";
663
- const r1 = execaSync("tmux", ["display-message", "-p", "#{@ase_task_id}"], { reject: false });
664
- tid = (r1.stdout ?? "").trim();
665
- if (tid !== "")
666
- await execInherit("ase", ["task", "edit", tid]);
667
- else {
668
- process.stderr.write("no ASE task id known for this pane yet\n");
669
- await new Promise((resolve) => setTimeout(resolve, 2000));
670
- }
671
- break;
672
- }
673
- case "lazygit": {
674
- ensureTool("ansi-recolor");
675
- ensureTool("git");
676
- ensureTool("lazygit");
677
- ensureTool("vim", { optional: true });
678
- const env = { ...process.env, TERM: "xterm-color" };
679
- await execInherit("ansi-recolor", [
680
- "-c", path.join(basedir, "ansi-recolor.conf"),
681
- "-m",
682
- "-n", "lazygit",
683
- "-t", path.join(HOME, "ansi-recolor.txt"),
684
- "lazygit", "-ucf", path.join(basedir, "lazygit.yaml"),
685
- ...argv
686
- ], { env });
687
- break;
688
- }
689
- default:
690
- fatal(`invalid util "${util ?? ""}"`);
698
+ else if (remainder.startsWith("/"))
699
+ remainder = remainder.slice(1);
700
+ const qIdx = remainder.indexOf("?");
701
+ const model = qIdx >= 0 ? remainder.slice(0, qIdx) : remainder;
702
+ if (model === "")
703
+ fatal("invalid CLAUDE_MODEL: missing model name in " +
704
+ `"${claudeModel}" (expected: ollama:[//host[:port]]/<model>[?...])`);
705
+ let context = "200k";
706
+ let capabilities = "";
707
+ if (qIdx >= 0) {
708
+ const query = remainder.slice(qIdx + 1);
709
+ for (const pair of query.split(",")) {
710
+ const eq = pair.indexOf("=");
711
+ const key = eq >= 0 ? pair.slice(0, eq) : pair;
712
+ const val = eq >= 0 ? pair.slice(eq + 1) : "";
713
+ if (key === "context")
714
+ context = val;
715
+ else if (key === "capabilities")
716
+ capabilities = val;
691
717
  }
692
- break;
693
718
  }
694
- default:
695
- fatal(`invalid command "${cmd}"`);
719
+ /* override Claude Code configuration */
720
+ env.ANTHROPIC_API_KEY = "";
721
+ env.ANTHROPIC_AUTH_TOKEN = "ollama";
722
+ env.ANTHROPIC_BASE_URL = `http://${ohost}`;
723
+ env.ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES = capabilities;
724
+ env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model;
725
+ env.ANTHROPIC_DEFAULT_OPUS_MODEL = model;
726
+ env.ANTHROPIC_DEFAULT_SONNET_MODEL = model;
727
+ env.CLAUDE_CODE_ATTRIBUTION_HEADER = "0";
728
+ env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = context;
729
+ env.CLAUDE_CODE_SUBAGENT_MODEL = model;
730
+ env.DISABLE_LOGIN_COMMAND = "1";
731
+ env.DISABLE_LOGOUT_COMMAND = "1";
732
+ }
733
+ /* override ASE configuration (for its diagram rendering) */
734
+ if (process.env.ASE_TERM_WIDTH === undefined) {
735
+ let width = 0;
736
+ if (process.stdout.isTTY) {
737
+ const cols = process.stdout.columns;
738
+ if (typeof cols === "number" && cols > 0)
739
+ width = cols;
740
+ }
741
+ process.env.ASE_TERM_WIDTH = `${width}`;
696
742
  }
743
+ if (process.env.ASE_TERM_COLORS === undefined) {
744
+ let colorMode = "none";
745
+ try {
746
+ const { stdout } = execaSync("tput", ["colors"], { reject: false });
747
+ const n = parseInt(stdout.trim(), 10);
748
+ if (!Number.isNaN(n) && n >= 256)
749
+ colorMode = "ansi256";
750
+ else if (!Number.isNaN(n) && n >= 16)
751
+ colorMode = "ansi16";
752
+ }
753
+ catch (_e) {
754
+ /* ignore */
755
+ }
756
+ process.env.ASE_TERM_COLORS = `${colorMode}`;
757
+ }
758
+ /* execute "claude" */
759
+ const settings = fs.readFileSync(path.join(basedir, "claude-settings.json"), "utf8");
760
+ const claudeBin = path.join(HOME, ".local/bin/claude");
761
+ if (recolor) {
762
+ return execInherit("ansi-recolor", [
763
+ "-c", path.join(basedir, "ansi-recolor.conf"),
764
+ "-m",
765
+ "-n", "claude",
766
+ "-t", path.join(HOME, "ansi-recolor.txt"),
767
+ claudeBin,
768
+ "--settings", settings,
769
+ ...args
770
+ ], { env });
771
+ }
772
+ else {
773
+ return execInherit(claudeBin, [
774
+ "--settings", settings,
775
+ ...args
776
+ ], { env });
777
+ }
778
+ };
779
+ /* action: top-level "-h/--help" */
780
+ const actionHelp = () => {
781
+ /* run "claude --help" */
782
+ process.env.PATH = `${HOME}/.local/bin:${process.env.PATH ?? ""}`;
783
+ ensureTool("claude");
784
+ const claudeBin = path.join(HOME, ".local/bin/claude");
785
+ execaSync(claudeBin, ["--help"], { reject: false, stdio: ["ignore", "inherit", "inherit"] });
786
+ /* append our claudeX extension information */
787
+ process.stdout.write("\n" +
788
+ "claudeX extension options (honored before claude):\n" +
789
+ " -C, --capsula execute Claude Code inside a Capsula sandbox container\n" +
790
+ " -R, --recolor wrap Claude Code with ANSI recoloring for improved theming\n" +
791
+ " -T, --tmux [session] wrap Claude Code in a Tmux terminal multiplexing session (optional session name)\n" +
792
+ "\n" +
793
+ "claudeX extension subcommands (honored before claude):\n" +
794
+ " install install host-side or in-container dependencies\n" +
795
+ " update update host-side or in-container dependencies\n" +
796
+ " internal … internal command dispatcher (internal use only)\n");
797
+ process.exit(0);
798
+ };
799
+ /* the main procedure -- builds and dispatches according to options and commands */
800
+ const main = async () => {
801
+ /* intercept top-level "-h/--help" before commander grabs it, so we can
802
+ pass-through to "claude --help" and append our extension info */
803
+ const topArgs = process.argv.slice(2);
804
+ const firstNonFlag = topArgs.findIndex((a) => !a.startsWith("-"));
805
+ const headFlags = firstNonFlag < 0 ? topArgs : topArgs.slice(0, firstNonFlag);
806
+ const subcmd = firstNonFlag < 0 ? "" : topArgs[firstNonFlag];
807
+ if ((headFlags.includes("-h") || headFlags.includes("--help"))
808
+ && subcmd !== "install" && subcmd !== "update" && subcmd !== "internal")
809
+ actionHelp();
810
+ /* dispatch main command */
811
+ const program = new Command();
812
+ program
813
+ .name("claudex")
814
+ .description("Claude Code eXtended")
815
+ .version(JSON.parse(fs.readFileSync(path.join(basedir, "package.json"), "utf8")).version, "-V, --version")
816
+ .enablePositionalOptions()
817
+ .passThroughOptions()
818
+ .allowUnknownOption()
819
+ .helpOption(false)
820
+ .option("-C, --capsula", "execute Claude Code inside a Capsula sandbox container")
821
+ .option("-R, --recolor", "wrap Claude Code with ANSI recoloing for improved theming")
822
+ .option("-T, --tmux [session]", "wrap Claude Code in a Tmux terminal multiplexing session (optional session name)")
823
+ .argument("[args...]", "arguments passed unparsed to Claude Code")
824
+ .action((args, opts) => {
825
+ actionDefault(opts, args);
826
+ });
827
+ /* dispatch "install" sub-command */
828
+ program
829
+ .command("install")
830
+ .description("install host-side or in-container dependencies")
831
+ .helpOption("-h, --help", "display help for command")
832
+ .action(async (_opts, cmd) => {
833
+ const capsula = cmd.parent?.opts().capsula === true;
834
+ await actionInstall(capsula);
835
+ });
836
+ /* dispatch "update" sub-command */
837
+ program
838
+ .command("update")
839
+ .description("update host-side or in-container dependencies")
840
+ .helpOption("-h, --help", "display help for command")
841
+ .action(async (_opts, cmd) => {
842
+ const capsula = cmd.parent?.opts().capsula === true;
843
+ await actionUpdate(capsula);
844
+ });
845
+ /* dispatch "internal" sub-command */
846
+ program
847
+ .command("internal")
848
+ .description("internal command dispatcher (tmux, shell, lazygit, ase-task-edit, capsula)")
849
+ .helpOption("-h, --help", "display help for command")
850
+ .allowUnknownOption()
851
+ .argument("[args...]", "internal command name and its arguments")
852
+ .action(async (args) => {
853
+ await actionInternal(args);
854
+ });
855
+ await program.parseAsync(process.argv);
697
856
  };
698
857
  main().catch((err) => {
699
858
  const msg = err instanceof Error ? err.message : String(err);