@rse/claudex 0.9.13

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 ADDED
@@ -0,0 +1,771 @@
1
+ #!/usr/bin/env node
2
+ /*!
3
+ ** claudeX -- Claude Code eXtended
4
+ ** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
5
+ ** Licensed under MIT <https://spdx.org/licenses/MIT>
6
+ */
7
+
8
+ import * as fs from "node:fs"
9
+ import * as path from "node:path"
10
+ import * as os from "node:os"
11
+ import { execa, execaSync } from "execa"
12
+ import which from "which"
13
+ import chalk from "chalk"
14
+
15
+ /* type for environment variable map */
16
+ type Env = Record<string, string | undefined>
17
+
18
+ /* determine our base directory (handle absolute, relative, PATH, symlinks) */
19
+ const findBaseDir = (): string => {
20
+ const argv1 = process.argv[1] ?? ""
21
+ let resolved = argv1
22
+ try {
23
+ resolved = fs.realpathSync(argv1)
24
+ }
25
+ catch (_e) {
26
+ /* ignore */
27
+ }
28
+ return path.dirname(resolved)
29
+ }
30
+ const basedir = findBaseDir()
31
+
32
+ /* the path used for self-invocation: always the POSIX-sh launcher
33
+ next to the compiled JS, since the JS itself is not executable
34
+ and embedded shell strings (docker/tmux) need a runnable command */
35
+ const selfPath = path.join(basedir, "claudex")
36
+ const selfPathJS = process.argv[1] ?? path.join(basedir, "claudex.js")
37
+
38
+ /* command line arguments (after node and script path) */
39
+ let argv = process.argv.slice(2)
40
+
41
+ /* helper for displaying info messages */
42
+ const info = (msg: string): void => {
43
+ process.stderr.write(`${chalk.blue("claudex: ")}${chalk.blue.bold("INFO:")}${chalk.blue(` ${msg}`)}\n`)
44
+ }
45
+
46
+ /* helper for raising a fatal error */
47
+ const fatal = (msg: string): never => {
48
+ process.stderr.write(`${chalk.red("claudex: ")}${chalk.red.bold("ERROR:")}${chalk.red(` ${msg}`)}\n`)
49
+ process.exit(1)
50
+ }
51
+
52
+ /* helper for detecting the platform and package manager combination */
53
+ const detectPlatform = (): string => {
54
+ const has = (tool: string): boolean => which.sync(tool, { nothrow: true }) !== null
55
+ if (process.platform === "win32" && has("winget"))
56
+ return "windows:winget"
57
+ else if (process.platform === "win32" && has("choco"))
58
+ return "windows:choco"
59
+ else if (process.platform === "darwin" && has("port"))
60
+ return "macos:ports"
61
+ else if (process.platform === "darwin" && has("brew"))
62
+ return "macos:brew"
63
+ else if (process.platform === "linux" && has("apt"))
64
+ return "linux:apt"
65
+ else if (process.platform === "linux" && has("apk"))
66
+ return "linux:apk"
67
+ else
68
+ return fatal(`unsupported platform "${process.platform}" or no known package manager found`)
69
+ }
70
+
71
+ /* helper to spawn a child synchronously inheriting stdio, then exit
72
+ 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, {
75
+ stdio: "inherit",
76
+ env: opts.env,
77
+ reject: false,
78
+ windowsHide: false
79
+ })
80
+ process.exit(r.exitCode ?? 0)
81
+ }
82
+
83
+ /* helper to execute a platform-specific command */
84
+ const executeCommand = (config: { [ platform: string ]: string[] | string }) => {
85
+ const platform = detectPlatform()
86
+ const osName = platform.split(":")[0]
87
+ const command = config[platform] ?? config[`${osName}:*`]
88
+ if (command === undefined)
89
+ return -1
90
+ const cmd = command instanceof Array ? command : command.split(/\s+/)
91
+ info(`execute: $ ${cmd.join(" ")}`)
92
+ const result = execaSync(cmd[0], cmd.slice(1), {
93
+ stdio: "inherit",
94
+ env: process.env,
95
+ reject: false,
96
+ windowsHide: false
97
+ })
98
+ return result.exitCode
99
+ }
100
+
101
+ /* helper to ensure a tool is available */
102
+ const ensureTool = (tool: string | string[], options: {
103
+ install?: { [ platform: string ]: string[] | string },
104
+ hint?: string,
105
+ optional?: boolean
106
+ } = {}): void => {
107
+ const tools = typeof tool === "string" ? [ tool ] : tool
108
+ 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)
114
+ continue
115
+ }
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`)
122
+ }
123
+ }
124
+ }
125
+
126
+ /* re-invoke this same script (mirrors "$0 ..." in Bash) */
127
+ const self = async (...args: string[]): Promise<number> => {
128
+ const r = await execa(process.execPath, [ selfPathJS, ...args ], {
129
+ stdio: "inherit",
130
+ reject: false
131
+ })
132
+ if ((r.exitCode ?? 0) !== 0)
133
+ process.exit(r.exitCode ?? 1)
134
+ return r.exitCode ?? 0
135
+ }
136
+
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
153
+ }
154
+
155
+ /* determine command */
156
+ const cmd = argv[0]
157
+ argv = argv.slice(1)
158
+
159
+ /* determine information */
160
+ const HOME = process.env.HOME ?? os.homedir()
161
+ const USER = process.env.USER ?? ""
162
+ const TERM = process.env.TERM ?? ""
163
+ const ENVIRONMENT = process.env.ENVIRONMENT ?? ""
164
+
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
173
+ }
174
+
175
+ case "install": {
176
+ /* sanity check environment */
177
+ if (ENVIRONMENT === "capsula")
178
+ fatal("cannot execute \"install\" command from within Capsula environment")
179
+
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
+ }
188
+
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")
194
+
195
+ info("install Tmux / LazyGit / Git")
196
+ await self("shell", "-s", "sudo", "-E", "apt", "install", "-qq", "-y", "tmux", "lazygit", "git")
197
+
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")
202
+
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`)
207
+
208
+ info("install ANSI-Recolor")
209
+ await self("shell", "-s", "sudo", "-E", "npm", "install", "-y", "-g", "ansi-recolor")
210
+
211
+ info("install TypeScript LS")
212
+ await self("shell", "-s", "sudo", "-E", "npm", "install", "-y", "-g", "typescript-language-server")
213
+
214
+ info("install Claude wrapper")
215
+ await self("shell", "-s", "sudo", "install", "-c", "-m", "755", `${basedir}/claude`, "/usr/bin/claude")
216
+ }
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
+ }
337
+ }
338
+ break
339
+ }
340
+
341
+ case "update": {
342
+ /* sanity check environment */
343
+ if (ENVIRONMENT === "capsula")
344
+ fatal("cannot execute \"update\" command from within Capsula environment")
345
+
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
+ }
354
+
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")
360
+
361
+ info("update Claude Code")
362
+ await self("shell", "bash", "-c", `PATH="${HOME}/.local/bin:$PATH"; ${HOME}/.local/bin/claude update`)
363
+
364
+ info("update ANSI-Recolor")
365
+ await self("shell", "-s", "sudo", "-E", "npm", "install", "-y", "-g", "ansi-recolor")
366
+
367
+ info("update TypeScript LS")
368
+ await self("shell", "-s", "sudo", "-E", "npm", "install", "-y", "-g", "typescript-language-server")
369
+
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
445
+ }
446
+
447
+ case "session": {
448
+ /* sanity check environment */
449
+ if (ENVIRONMENT === "capsula")
450
+ fatal("cannot execute \"session\" command from within Capsula environment")
451
+
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
+ }
471
+
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
+ }
496
+ break
497
+ }
498
+
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
+ }
524
+ }
525
+ else {
526
+ /* enter/start plain claude */
527
+ await execInherit(selfPath, [ "claude", ...argv ])
528
+ }
529
+ break
530
+ }
531
+
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
603
+ ])
604
+ break
605
+ }
606
+
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"
660
+ }
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}`
671
+ }
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}`
686
+ }
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
+ }
701
+
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
761
+ }
762
+
763
+ default:
764
+ fatal(`invalid command "${cmd}"`)
765
+ }
766
+ }
767
+ main().catch((err: unknown) => {
768
+ const msg = err instanceof Error ? err.message : String(err)
769
+ fatal(msg)
770
+ })
771
+