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