-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
1809 lines (1560 loc) · 62.4 KB
/
cli.ts
File metadata and controls
1809 lines (1560 loc) · 62.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env -S node --experimental-strip-types --no-warnings
/**
* ClaudeBox CLI — local-first session orchestrator.
*
* Usage:
* claudebox run [--profile <name>] "fix the flaky test"
* claudebox run --file prompt.md
* claudebox resume session/foo "continue with the fix"
* claudebox list [--user <name>] [--profile <name>]
* claudebox tail session/foo
* claudebox cancel session/foo
* claudebox clean [--force]
* claudebox view [session/foo]
* claudebox server [--port <n>]
* claudebox pull <session-name-or-id>
* claudebox push <session-name-or-id> [--resume <prompt>]
* claudebox guide <session-name-or-id>
* claudebox status
* claudebox profiles
* claudebox config <key> [value]
* claudebox init [--gh-token ...] [--slack-bot-token ...]
* claudebox register
*
* Config: ~/.claudebox/config.json (CLI client config)
* Credentials: ~/.config/claudebox/env (server tokens, managed by 'init')
*/
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync, watch, chmodSync } from "fs";
import { join, dirname, basename } from "path";
import { homedir } from "os";
import { execFileSync } from "child_process";
// ── Config ──────────────────────────────────────────────────────
interface CliConfig {
server?: string;
token?: string;
password?: string; // basic auth password for dashboard/SSE APIs
user?: string; // default username for session pages
}
const CONFIG_DIR = join(homedir(), ".claudebox");
const CONFIG_FILE = join(CONFIG_DIR, "config.json");
function loadConfig(): CliConfig {
try {
if (existsSync(CONFIG_FILE)) {
return JSON.parse(readFileSync(CONFIG_FILE, "utf-8"));
}
} catch {}
return {};
}
function saveConfig(config: CliConfig): void {
mkdirSync(CONFIG_DIR, { recursive: true });
writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2) + "\n");
}
/** Parse --flag and --flag=value args, collecting non-flag args as positional. */
function parseArgs(args: string[], flags: Record<string, boolean>): { opts: Record<string, string>; positional: string[] } {
const opts: Record<string, string> = {};
const positional: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === "--help" || arg === "-h") { opts.help = "true"; continue; }
if (arg === "--follow" || arg === "-f") { opts.follow = "true"; continue; }
if (arg.startsWith("--")) {
const eqIdx = arg.indexOf("=");
if (eqIdx > 0) {
opts[arg.slice(2, eqIdx)] = arg.slice(eqIdx + 1);
} else if (flags[arg.slice(2)]) {
opts[arg.slice(2)] = "true";
} else if (i + 1 < args.length) {
opts[arg.slice(2)] = args[++i];
}
} else {
positional.push(arg);
}
}
return { opts, positional };
}
/** Resolve server connection from args/env/config. */
function resolveServer(opts: Record<string, string>): { url: string; token: string; password: string; user: string } {
const config = loadConfig();
return {
url: (opts.server || config.server || process.env.CLAUDEBOX_SERVER_URL || "").replace(/\/$/, ""),
token: opts.token || config.token || process.env.CLAUDEBOX_SERVER_TOKEN || "",
password: opts.password || config.password || process.env.CLAUDEBOX_SESSION_PASS || "",
user: opts.user || config.user || process.env.CLAUDEBOX_SESSION_USER || "admin",
};
}
function basicAuthHeader(user: string, password: string): string {
return "Basic " + Buffer.from(`${user}:${password}`).toString("base64");
}
// ── Session Name Resolution ─────────────────────────────────────
/**
* Resolve a session name or ID to a worktree ID.
* - Strips "session/" prefix if present
* - Looks up by workspace name first (from worktree meta.json)
* - Falls back to worktree ID matching
* - For remote: queries server API
*/
async function resolveSession(nameOrId: string, opts: { server?: { url: string; token: string; password: string; user: string } } = {}): Promise<string> {
// Strip session/ prefix
const stripped = nameOrId.replace(/^session\//, "");
if (opts.server?.url) {
// Remote mode: try to resolve via server API, fall back to raw ID
return stripped;
}
// Local mode: check session store
const { WorktreeStore } = await import("./packages/libclaudebox/worktree-store.ts");
const store = new WorktreeStore();
// Direct worktree ID match (hex pattern)
if (/^[a-f0-9]{16}$/.test(stripped)) {
const session = store.findByWorktreeId(stripped);
if (session) return stripped;
}
// Search by workspace name in worktree meta.json
const worktreesDir = store.worktreesDir;
if (existsSync(worktreesDir)) {
for (const id of readdirSync(worktreesDir)) {
const meta = store.getWorktreeMeta(id);
if (meta.name && meta.name === stripped) {
return id;
}
}
}
// Search by partial match on workspace name
if (existsSync(worktreesDir)) {
for (const id of readdirSync(worktreesDir)) {
const meta = store.getWorktreeMeta(id);
if (meta.name && meta.name.includes(stripped)) {
return id;
}
}
}
// Fall back to raw value (might be a valid worktree ID we just can't find yet)
return stripped;
}
/** Get the display name for a session (workspace name or worktree ID). */
function getSessionDisplayName(worktreeId: string, meta: Record<string, any>): string {
return meta.name ? `session/${meta.name}` : `session/${worktreeId}`;
}
// ── Activity Tailing ────────────────────────────────────────────
function printActivityEntry(entry: any): void {
const prefix = {
response: "CLAUDE",
tool_use: "TOOL",
artifact: "ARTIFACT",
agent_start: "AGENT",
agent_log: "AGENT",
name: "NAME",
status: "STATUS",
}[entry.type as string] || entry.type?.toUpperCase() || "?";
const text = (entry.text || "").trim();
if (!text) return;
// Truncate very long responses for CLI readability
const maxLen = 500;
const display = text.length > maxLen ? text.slice(0, maxLen) + "..." : text;
console.log(`[${prefix}] ${display}`);
}
/**
* Tail activity.jsonl from a local worktree directory.
* Watches for new lines and prints formatted entries.
* Returns when the session completes or the AbortSignal fires.
*/
async function tailActivity(worktreeId: string, signal?: AbortSignal): Promise<void> {
const { WorktreeStore } = await import("./packages/libclaudebox/worktree-store.ts");
const store = new WorktreeStore();
const activityPath = join(store.worktreesDir, worktreeId, "workspace", "activity.jsonl");
let linesRead = 0;
const readNewLines = () => {
if (!existsSync(activityPath)) return;
try {
const content = readFileSync(activityPath, "utf-8");
const lines = content.split("\n").filter(l => l.trim());
const newLines = lines.slice(linesRead);
for (const line of newLines) {
try {
const entry = JSON.parse(line);
printActivityEntry(entry);
// Print session name when it's set
if (entry.type === "name" && entry.text) {
console.log(`\n --> session/${entry.text}\n`);
}
} catch {}
}
linesRead = lines.length;
} catch {}
};
// Read existing content first
readNewLines();
// Check if session is already done
const checkDone = (): boolean => {
const session = store.findByWorktreeId(worktreeId);
if (session && (session.status === "completed" || session.status === "error" || session.status === "cancelled")) {
readNewLines(); // flush any remaining
console.log(`\n[${session.status.toUpperCase()}] exit=${session.exit_code ?? "?"}`);
return true;
}
return false;
};
if (checkDone()) return;
// Poll for changes (more reliable than fs.watch across filesystems)
return new Promise<void>((resolve) => {
const interval = setInterval(() => {
if (signal?.aborted) {
clearInterval(interval);
resolve();
return;
}
readNewLines();
if (checkDone()) {
clearInterval(interval);
resolve();
}
}, 500);
// Also try fs.watch for faster updates
let watcher: ReturnType<typeof watch> | null = null;
const setupWatcher = () => {
try {
const dir = dirname(activityPath);
if (existsSync(dir)) {
watcher = watch(dir, () => readNewLines());
}
} catch {}
};
// Watch may not work until file exists; retry
if (existsSync(dirname(activityPath))) {
setupWatcher();
} else {
const watchRetry = setInterval(() => {
if (existsSync(dirname(activityPath))) {
setupWatcher();
clearInterval(watchRetry);
}
}, 1000);
signal?.addEventListener("abort", () => clearInterval(watchRetry));
}
signal?.addEventListener("abort", () => {
clearInterval(interval);
watcher?.close();
resolve();
});
});
}
// ── Commands ────────────────────────────────────────────────────
async function runCommand(args: string[]): Promise<void> {
const { opts, positional } = parseArgs(args, { follow: true, detach: true, file: false });
if (opts.help) {
console.log(`Usage: claudebox run [options] <prompt>
Start a new session. By default, blocks and tails activity output.
Ctrl-C detaches from output (session keeps running).
Options:
--profile <name> Profile to run (default: "default")
--model <model> Claude model (e.g. claude-haiku-4-5-20251001)
--file <path> Read prompt from file (or - for stdin)
--detach Start session and return immediately (don't tail)
--worktree <id> Resume an existing worktree
--server <url> ClaudeBox server URL
--token <token> Server API token
--follow, -f Stream session output (remote mode, same as default local)
Config file: ${CONFIG_FILE}
{ "server": "https://claudebox.work", "token": "..." }
`);
return;
}
const profile = opts.profile || "default";
const model = opts.model || "";
const worktreeId = opts.worktree || "";
const detach = opts.detach === "true";
const follow = opts.follow === "true";
const server = resolveServer(opts);
// Read prompt from --file, stdin pipe, or positional args
let prompt = "";
if (opts.file) {
if (opts.file === "-") {
// Read from stdin
prompt = readFileSync("/dev/stdin", "utf-8").trim();
} else {
if (!existsSync(opts.file)) {
console.error(`Error: file not found: ${opts.file}`);
process.exit(1);
}
prompt = readFileSync(opts.file, "utf-8").trim();
}
} else if (!process.stdin.isTTY && positional.length === 0) {
// Piped input
prompt = readFileSync("/dev/stdin", "utf-8").trim();
} else {
prompt = positional.join(" ").trim();
}
if (!prompt) {
console.error("Error: prompt required. Usage: claudebox run [--profile <name>] <prompt>");
console.error(" or: claudebox run --file prompt.md");
process.exit(1);
}
// Remote mode
if (server.url) {
console.log(`Server: ${server.url}`);
console.log(`Profile: ${profile}`);
console.log(`Prompt: ${prompt.slice(0, 100)}${prompt.length > 100 ? "..." : ""}`);
const res = await fetch(`${server.url}/run`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${server.token}`,
},
body: JSON.stringify({
prompt,
profile,
model: model || undefined,
worktree_id: worktreeId || undefined,
user: process.env.USER || "cli",
}),
});
const data = await res.json() as any;
if (!res.ok) {
console.error(`Server error (${res.status}): ${data.error || JSON.stringify(data)}`);
process.exit(1);
}
const sessionWtId = data.worktree_id || worktreeId;
console.log(`Session started.${model ? ` (model: ${model})` : ""}`);
if (data.log_url) console.log(` CI log: ${data.log_url}`);
if (sessionWtId) console.log(` Status: ${server.url}/s/${sessionWtId}`);
if (sessionWtId) console.log(` Resume: claudebox resume session/${sessionWtId} "<prompt>"`);
if (follow && sessionWtId && server.password) {
// Wait briefly for session to start, then stream
await new Promise(r => setTimeout(r, 2000));
await streamLogs(server, sessionWtId);
}
return;
}
// Local mode — pre-flight checks
try {
const gitName = execFileSync("git", ["config", "user.name"], { encoding: "utf-8", timeout: 5_000 }).trim();
const gitEmail = execFileSync("git", ["config", "user.email"], { encoding: "utf-8", timeout: 5_000 }).trim();
if (!gitName || !gitEmail) throw new Error("empty");
} catch {
console.error("Error: git identity not configured. Containers need it for commits.");
console.error(" git config --global user.name \"Your Name\"");
console.error(" git config --global user.email \"you@example.com\"");
process.exit(1);
}
console.log("Running locally.");
console.log(`Profile: ${profile}`);
const rootDir = dirname(import.meta.url.replace("file://", ""));
const { setProfilesDir, loadProfile } = await import("./packages/libclaudebox/profile-loader.ts");
setProfilesDir(join(rootDir, "profiles"));
const profileConfig = await loadProfile(profile);
if (profileConfig.requiresServer) {
console.error(`Error: profile "${profile}" requires a claudebox server.`);
console.error(`Configure one in ${CONFIG_FILE} or pass --server <url>.`);
process.exit(1);
}
const { WorktreeStore } = await import("./packages/libclaudebox/worktree-store.ts");
const { DockerService } = await import("./packages/libclaudebox/docker.ts");
const store = new WorktreeStore();
const docker = new DockerService();
if (detach) {
// Detached mode: start session in background, don't tail
// We need to run in a forked process to avoid blocking
const { spawn } = await import("child_process");
const child = spawn(
process.execPath,
["--experimental-strip-types", "--no-warnings", import.meta.url.replace("file://", ""), "run", "--profile", profile, ...(model ? ["--model", model] : []), ...(worktreeId ? ["--worktree", worktreeId] : []), "--detach-internal", prompt],
{
stdio: ["ignore", "pipe", "pipe"],
detached: true,
env: process.env,
},
);
// Read initial output to get session info
let output = "";
child.stdout?.on("data", (d: Buffer) => { output += d.toString(); });
child.stderr?.on("data", (d: Buffer) => { process.stderr.write(d); });
child.unref();
// Wait a moment for startup info
await new Promise(r => setTimeout(r, 3000));
if (output) process.stdout.write(output);
console.log("\nSession running in background. Use 'claudebox list' to see status.");
return;
}
// Blocking mode: start session and tail activity in parallel
let sessionWorktreeId = worktreeId;
const abortController = new AbortController();
// Handle Ctrl-C: detach from tailing, DON'T kill the container
let detaching = false;
const sigintHandler = () => {
if (detaching) return;
detaching = true;
console.log("\n\nDetaching from session output. Session continues running.");
console.log("Use 'claudebox list' to check status, 'claudebox tail <session>' to reattach.");
abortController.abort();
};
process.on("SIGINT", sigintHandler);
// Start the container session (this blocks until session completes)
const sessionPromise = docker.runContainerSession({
prompt,
userName: process.env.USER || "cli",
worktreeId: worktreeId || undefined,
profile,
model: model || undefined,
}, store, undefined, (logUrl, wId) => {
sessionWorktreeId = wId;
const meta = store.getWorktreeMeta(wId);
const displayName = getSessionDisplayName(wId, meta);
console.log(`${displayName}`);
console.log(`Log: ${logUrl}`);
console.log(`Worktree: ${wId}`);
console.log("");
// Start tailing activity in parallel once we know the worktree ID
tailActivity(wId, abortController.signal).catch(() => {});
});
const exitCode = await sessionPromise;
// Clean up signal handler
process.removeListener("SIGINT", sigintHandler);
if (detaching) {
// We detached, so don't exit with session's code
process.exit(0);
}
// Print final session name
if (sessionWorktreeId) {
const meta = store.getWorktreeMeta(sessionWorktreeId);
const displayName = getSessionDisplayName(sessionWorktreeId, meta);
console.log(`\nSession: ${displayName} (exit=${exitCode})`);
}
process.exit(exitCode);
}
async function resumeCommand(args: string[]): Promise<void> {
const { opts, positional } = parseArgs(args, { follow: true, detach: true });
if (opts.help) {
console.log(`Usage: claudebox resume <session/name-or-id> <prompt>
Resume an existing session with a follow-up prompt.
Options:
--detach Start session and return immediately
--follow, -f Stream session output (remote mode)
`);
return;
}
const server = resolveServer(opts);
const follow = opts.follow === "true";
const detach = opts.detach === "true";
// First positional arg is session name/id, rest is prompt
if (positional.length === 0) {
// No session specified: list recent sessions to pick from
if (!server.url) {
const { WorktreeStore } = await import("./packages/libclaudebox/worktree-store.ts");
const store = new WorktreeStore();
const sessions = store.listAll().slice(0, 10);
if (sessions.length === 0) {
console.log("No sessions found.");
process.exit(1);
}
console.log("Recent sessions:\n");
for (const s of sessions) {
const wtId = s.worktree_id || s._log_id || "?";
const meta = s.worktree_id ? store.getWorktreeMeta(s.worktree_id) : {};
const name = meta.name ? `session/${meta.name}` : `session/${wtId}`;
const status = s.status || "?";
const prompt = (s.prompt || "").slice(0, 50);
console.log(` ${name.padEnd(30)} ${status.padEnd(10)} ${prompt}`);
}
console.log("\nUsage: claudebox resume session/<name> <prompt>");
return;
}
// Remote mode: list from server dashboard API
if (!server.password) {
console.error("Error: --password or config.password required to list sessions.");
process.exit(1);
}
const res = await fetch(`${server.url}/api/dashboard`, {
headers: { Authorization: basicAuthHeader(server.user, server.password) },
});
if (!res.ok) {
console.error(`Server error (${res.status}): ${await res.text()}`);
process.exit(1);
}
const data = await res.json() as any;
const workspaces = (data.workspaces || []).slice(0, 15);
if (workspaces.length === 0) {
console.log("No sessions found.");
return;
}
console.log("Recent sessions:\n");
console.log(" NAME STATUS PROFILE PROMPT");
console.log(" " + "-".repeat(85));
for (const w of workspaces) {
const name = w.name ? `session/${w.name}` : `session/${(w.worktreeId || "?").slice(0, 16)}`;
const status = (w.status || "?").padEnd(10);
const profile = (w.profile || "default").padEnd(12);
const prompt = (w.prompt || "").slice(0, 35);
console.log(` ${name.padEnd(30)} ${status} ${profile} ${prompt}`);
}
console.log("\nUsage: claudebox resume session/<name> <prompt>");
return;
}
const sessionRef = positional[0];
const prompt = positional.slice(1).join(" ").trim();
if (!prompt) {
console.error("Error: prompt required. Usage: claudebox resume session/<name> <prompt>");
process.exit(1);
}
const worktreeId = await resolveSession(sessionRef, { server: server.url ? server : undefined });
if (server.url) {
// Remote resume via POST /run with worktree_id
const res = await fetch(`${server.url}/run`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${server.token}`,
},
body: JSON.stringify({
prompt,
worktree_id: worktreeId,
user: process.env.USER || "cli",
}),
});
const data = await res.json() as any;
if (!res.ok) {
console.error(`Server error (${res.status}): ${data.error || JSON.stringify(data)}`);
process.exit(1);
}
console.log(`Resumed.`);
if (data.log_url) console.log(` CI log: ${data.log_url}`);
console.log(` Status: ${server.url}/s/${worktreeId}`);
if (follow && server.password) {
await new Promise(r => setTimeout(r, 2000));
await streamLogs(server, worktreeId);
}
return;
}
// Local resume
const { WorktreeStore } = await import("./packages/libclaudebox/worktree-store.ts");
const { DockerService } = await import("./packages/libclaudebox/docker.ts");
const store = new WorktreeStore();
const docker = new DockerService();
const session = store.findByWorktreeId(worktreeId);
if (detach) {
const exitCode = await docker.runContainerSession({
prompt,
userName: process.env.USER || "cli",
worktreeId,
profile: session?.profile || undefined,
}, store, undefined, (logUrl, wId) => {
const meta = store.getWorktreeMeta(wId);
console.log(`${getSessionDisplayName(wId, meta)}`);
console.log(`Log: ${logUrl}`);
});
process.exit(exitCode);
}
// Blocking mode with activity tailing (same pattern as run)
const abortController = new AbortController();
let detaching = false;
const sigintHandler = () => {
if (detaching) return;
detaching = true;
console.log("\n\nDetaching from session output. Session continues running.");
abortController.abort();
};
process.on("SIGINT", sigintHandler);
const exitCode = await docker.runContainerSession({
prompt,
userName: process.env.USER || "cli",
worktreeId,
profile: session?.profile || undefined,
}, store, undefined, (logUrl, wId) => {
const meta = store.getWorktreeMeta(wId);
console.log(`${getSessionDisplayName(wId, meta)}`);
console.log(`Log: ${logUrl}`);
console.log("");
tailActivity(wId, abortController.signal).catch(() => {});
});
process.removeListener("SIGINT", sigintHandler);
if (detaching) process.exit(0);
process.exit(exitCode);
}
async function listCommand(args: string[]): Promise<void> {
const { opts } = parseArgs(args, {});
if (opts.help) {
console.log(`Usage: claudebox list [options]
List sessions in table format.
Options:
--user <name> Filter by user
--profile <name> Filter by profile
--limit <n> Number of sessions (default: 20)
`);
return;
}
const server = resolveServer(opts);
const limit = parseInt(opts.limit || "20", 10);
const userFilter = opts.user || "";
const profileFilter = opts.profile || "";
if (server.url) {
if (!server.password) {
console.error("Error: --password or config.password required.");
process.exit(1);
}
const url = new URL(`${server.url}/api/dashboard`);
if (profileFilter) url.searchParams.set("profile", profileFilter);
const res = await fetch(url.toString(), {
headers: { Authorization: basicAuthHeader(server.user, server.password) },
});
if (!res.ok) {
console.error(`Server error (${res.status}): ${await res.text()}`);
process.exit(1);
}
const data = await res.json() as any;
let workspaces = data.workspaces || [];
if (userFilter) {
workspaces = workspaces.filter((w: any) => w.user === userFilter);
}
workspaces = workspaces.slice(0, limit);
if (workspaces.length === 0) {
console.log("No sessions found.");
return;
}
console.log(`Server: ${server.url} (${data.activeCount}/${data.maxConcurrent} active)\n`);
console.log(" NAME PROFILE STATUS CREATED BRANCH");
console.log(" " + "-".repeat(90));
for (const w of workspaces) {
const name = w.name ? `session/${w.name}` : `session/${(w.worktreeId || "?").slice(0, 16)}`;
const profile = (w.profile || "default").padEnd(12);
const status = (w.status || "?").padEnd(10);
const created = w.started ? new Date(w.started).toLocaleDateString() : "?";
const branch = (w.baseBranch || "").padEnd(12);
console.log(` ${name.padEnd(30)} ${profile} ${status} ${created.padEnd(10)} ${branch}`);
}
return;
}
// Local mode
const { WorktreeStore } = await import("./packages/libclaudebox/worktree-store.ts");
const store = new WorktreeStore();
// Build a deduplicated list by worktree (show latest session per worktree)
const allSessions = store.listAll();
const worktreeMap = new Map<string, typeof allSessions[0]>();
for (const s of allSessions) {
const key = s.worktree_id || s._log_id || "";
if (!worktreeMap.has(key)) {
worktreeMap.set(key, s);
}
}
let sessions = [...worktreeMap.values()];
if (userFilter) sessions = sessions.filter(s => s.user === userFilter);
if (profileFilter) sessions = sessions.filter(s => (s.profile || "") === profileFilter);
sessions = sessions.slice(0, limit);
if (sessions.length === 0) {
console.log("No sessions found.");
return;
}
console.log(" NAME PROFILE STATUS CREATED BRANCH");
console.log(" " + "-".repeat(90));
for (const s of sessions) {
const wtId = s.worktree_id || s._log_id || "?";
const meta = s.worktree_id ? store.getWorktreeMeta(s.worktree_id) : {};
const name = meta.name ? `session/${meta.name}` : `session/${wtId.slice(0, 16)}`;
const profile = (s.profile || "default").padEnd(12);
const status = (s.status || "?").padEnd(10);
const created = s.started ? new Date(s.started).toLocaleDateString() : "?";
const branch = (s.base_branch || "").padEnd(12);
console.log(` ${name.padEnd(30)} ${profile} ${status} ${created.padEnd(10)} ${branch}`);
}
}
async function tailCommand(args: string[]): Promise<void> {
const { opts, positional } = parseArgs(args, { follow: true });
if (opts.help || positional.length === 0) {
console.log(`Usage: claudebox tail <session/name-or-id>
Stream activity log for a session. Follows by default.
Ctrl-C stops tailing (session keeps running).
`);
if (!opts.help) process.exit(1);
return;
}
const sessionRef = positional[0];
const server = resolveServer(opts);
if (server.url) {
const worktreeId = await resolveSession(sessionRef, { server });
if (!server.password) {
console.error("Error: --password or config.password required for log streaming.");
process.exit(1);
}
await streamLogs(server, worktreeId);
return;
}
// Local mode: tail the activity.jsonl
const worktreeId = await resolveSession(sessionRef);
const abortController = new AbortController();
process.on("SIGINT", () => {
console.log("\nStopped tailing. Session may still be running.");
abortController.abort();
});
await tailActivity(worktreeId, abortController.signal);
}
async function cancelCommand(args: string[]): Promise<void> {
const { opts, positional } = parseArgs(args, {});
if (opts.help || positional.length === 0) {
console.log(`Usage: claudebox cancel <session/name-or-id>
Gracefully stop a running session.
Sends SIGTERM, waits 10 seconds, then SIGKILL. Worktree is preserved.
`);
if (!opts.help) process.exit(1);
return;
}
const sessionRef = positional[0];
const server = resolveServer(opts);
if (server.url) {
console.error("Error: cancel is only supported in local mode.");
process.exit(1);
}
const worktreeId = await resolveSession(sessionRef);
const { WorktreeStore } = await import("./packages/libclaudebox/worktree-store.ts");
const store = new WorktreeStore();
// Find the running session for this worktree
const sessions = store.listByWorktree(worktreeId);
const running = sessions.find(s => s.status === "running");
if (!running) {
console.log(`No running session found for ${sessionRef}.`);
return;
}
const logId = running._log_id || "";
const containerName = running.container || `claudebox-${logId}`;
const sidecarName = running.sidecar || `claudebox-sidecar-${logId}`;
const networkName = `claudebox-net-${logId}`;
const meta = store.getWorktreeMeta(worktreeId);
const displayName = getSessionDisplayName(worktreeId, meta);
console.log(`Cancelling ${displayName}...`);
// Graceful stop: SIGTERM with 10s timeout, then SIGKILL
try {
console.log(` Stopping container ${containerName} (10s grace)...`);
execFileSync("docker", ["stop", "--time", "10", containerName], { timeout: 30_000, stdio: "pipe" });
} catch {}
// Stop sidecar
try {
execFileSync("docker", ["stop", "--time", "3", sidecarName], { timeout: 15_000, stdio: "pipe" });
} catch {}
// Force remove if still around
try { execFileSync("docker", ["rm", "-f", containerName], { timeout: 10_000, stdio: "pipe" }); } catch {}
try { execFileSync("docker", ["rm", "-f", sidecarName], { timeout: 10_000, stdio: "pipe" }); } catch {}
// Clean up network
try { execFileSync("docker", ["network", "rm", networkName], { timeout: 10_000, stdio: "pipe" }); } catch {}
// Update session status
store.update(logId, {
status: "cancelled",
finished: new Date().toISOString(),
});
console.log(`Cancelled. Worktree preserved at ${join(store.worktreesDir, worktreeId)}`);
}
async function cleanCommand(args: string[]): Promise<void> {
const { opts } = parseArgs(args, { force: true });
if (opts.help) {
console.log(`Usage: claudebox clean [options]
Remove worktrees from completed/cancelled sessions.
Options:
--force Actually delete (default is dry-run)
By default, shows what would be deleted without removing anything.
Running sessions are never cleaned.
`);
return;
}
const force = opts.force === "true";
const { WorktreeStore } = await import("./packages/libclaudebox/worktree-store.ts");
const store = new WorktreeStore();
if (!existsSync(store.worktreesDir)) {
console.log("No worktrees found.");
return;
}
const worktreeIds = readdirSync(store.worktreesDir).filter(id => {
try {
return statSync(join(store.worktreesDir, id)).isDirectory();
} catch { return false; }
});
if (worktreeIds.length === 0) {
console.log("No worktrees found.");
return;
}
// Classify worktrees
const cleanable: { id: string; name: string; status: string; sizeMB: number }[] = [];
const running: string[] = [];
for (const id of worktreeIds) {
const sessions = store.listByWorktree(id);
const latest = sessions[0];
const meta = store.getWorktreeMeta(id);
const displayName = meta.name || id.slice(0, 16);
if (latest?.status === "running") {
running.push(displayName);
continue;
}
// Estimate size
let sizeMB = 0;
const wsDir = join(store.worktreesDir, id, "workspace");
try {
const du = execFileSync("du", ["-sm", wsDir], { encoding: "utf-8", timeout: 10_000 }).trim();
sizeMB = parseInt(du.split("\t")[0]) || 0;
} catch {}
cleanable.push({
id,
name: displayName,
status: latest?.status || "unknown",
sizeMB,
});
}
if (cleanable.length === 0) {
console.log("Nothing to clean.");
if (running.length > 0) {
console.log(` ${running.length} running session(s) skipped.`);
}
return;
}
const totalMB = cleanable.reduce((sum, c) => sum + c.sizeMB, 0);
if (!force) {
console.log("Dry run (use --force to delete):\n");
console.log(" NAME STATUS SIZE");
console.log(" " + "-".repeat(55));
for (const c of cleanable) {
const name = `session/${c.name}`.padEnd(30);
const status = c.status.padEnd(10);
const size = c.sizeMB > 0 ? `${c.sizeMB} MB` : "?";
console.log(` ${name} ${status} ${size}`);
}
console.log(`\n Total: ${cleanable.length} worktree(s), ~${totalMB} MB`);
if (running.length > 0) {
console.log(` ${running.length} running session(s) skipped.`);
}
return;
}
// Actually delete
let deleted = 0;
for (const c of cleanable) {
try {
store.deleteWorktree(c.id);
console.log(` Deleted session/${c.name} (${c.sizeMB} MB)`);
deleted++;
} catch (e: any) {
console.error(` Failed to delete session/${c.name}: ${e.message}`);
}
// Also clean up any orphaned Docker networks
const networkName = `claudebox-net-${c.id}`;
try { execFileSync("docker", ["network", "rm", networkName], { timeout: 10_000, stdio: "pipe" }); } catch {}
}
console.log(`\nCleaned ${deleted} worktree(s), freed ~${totalMB} MB.`);
}
async function viewCommand(args: string[]): Promise<void> {
const { opts, positional } = parseArgs(args, {});
if (opts.help) {
console.log(`Usage: claudebox view [session/name-or-id]
Start an ephemeral local HTTP server and open the dashboard in your browser.
Optionally view a specific session.
Ctrl-C stops the server (does not affect running sessions).
Options:
--port <n> Port (default: 3456)
--password <pass> Dashboard password (or CLAUDEBOX_SESSION_PASS)
`);
return;
}
const port = opts.port || "3456";
const password = opts.password || process.env.CLAUDEBOX_SESSION_PASS || "view";
const sessionRef = positional[0] || "";
// Set env for the server
process.env.CLAUDEBOX_HTTP_PORT = port;
process.env.CLAUDEBOX_SESSION_PASS = password;
process.env.CLAUDEBOX_HTTP_ONLY = "1";
// Start server as child process
const { spawn } = await import("child_process");
const serverPath = join(dirname(import.meta.url.replace("file://", "")), "server.ts");
const proc = spawn(
process.execPath,
["--experimental-strip-types", "--no-warnings", serverPath, "--http-only"],
{