@rse/claudex 0.9.13 → 0.9.15

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