@termwire/cli 0.5.0 → 0.7.0

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +125 -4
  3. package/dist/click.d.ts +52 -0
  4. package/dist/click.js +138 -0
  5. package/dist/config-schema.d.ts +7 -0
  6. package/dist/config-schema.js +19 -0
  7. package/dist/config-validation.d.ts +2 -0
  8. package/dist/config-validation.js +14 -0
  9. package/dist/config-writer.d.ts +4 -2
  10. package/dist/config-writer.js +15 -3
  11. package/dist/down.d.ts +40 -0
  12. package/dist/down.js +99 -0
  13. package/dist/identity.js +4 -1
  14. package/dist/install-prompt.js +7 -0
  15. package/dist/install.d.ts +6 -0
  16. package/dist/install.js +101 -25
  17. package/dist/mouse-binding.d.ts +60 -0
  18. package/dist/mouse-binding.js +91 -0
  19. package/dist/mouse-config.d.ts +17 -0
  20. package/dist/mouse-config.js +63 -0
  21. package/dist/process-scan-darwin.d.ts +24 -0
  22. package/dist/process-scan-darwin.js +102 -0
  23. package/dist/process-scan-linux.d.ts +13 -0
  24. package/dist/process-scan-linux.js +66 -0
  25. package/dist/process-scan.d.ts +37 -23
  26. package/dist/process-scan.js +30 -131
  27. package/dist/program.d.ts +14 -1
  28. package/dist/program.js +174 -38
  29. package/dist/reap-hook.js +1 -19
  30. package/dist/reap.d.ts +0 -5
  31. package/dist/reap.js +3 -10
  32. package/dist/runtime.d.ts +20 -5
  33. package/dist/runtime.js +44 -5
  34. package/dist/shell-quote.d.ts +6 -0
  35. package/dist/shell-quote.js +19 -0
  36. package/dist/state-log.d.ts +8 -0
  37. package/dist/state-log.js +12 -0
  38. package/dist/up.d.ts +5 -2
  39. package/dist/up.js +5 -5
  40. package/dist/workspaces.d.ts +45 -0
  41. package/dist/workspaces.js +116 -0
  42. package/dist/worktree.d.ts +16 -1
  43. package/dist/worktree.js +66 -9
  44. package/package.json +21 -7
@@ -0,0 +1,45 @@
1
+ import { type SessionScanner } from "./process-scan.js";
2
+ import type { GitExec } from "./worktree.js";
3
+ /** What `ls` knows about one workspace. Collected from tmux and Git, never from disk. */
4
+ export interface Workspace {
5
+ session: string;
6
+ attached: boolean;
7
+ /** The Git branch, a short sha on a detached HEAD, or `-` outside a repository. */
8
+ branch: string;
9
+ /** The session path, absolute: shortening to `~` is for the table, not for machines. */
10
+ directory: string;
11
+ /** The session outlived its directory, which is listed and marked rather than fatal. */
12
+ missing: boolean;
13
+ procs: number;
14
+ rssKib: number;
15
+ }
16
+ /** The fields of a tmux session this module reads, as the adapter reports them. */
17
+ export interface WorkspaceSession {
18
+ name: string;
19
+ attached: boolean;
20
+ path: string;
21
+ }
22
+ export interface WorkspacesDependencies {
23
+ listSessions: () => Promise<WorkspaceSession[]>;
24
+ showEnvironment: (session: string) => Promise<Record<string, string>>;
25
+ git: GitExec;
26
+ pathExists: (path: string) => Promise<boolean>;
27
+ /** One walk over the process table, asked for every workspace at once. */
28
+ scan: SessionScanner;
29
+ }
30
+ /**
31
+ * A session is a workspace when its tmux environment carries `TERMWIRE_SESSION`,
32
+ * never because its name looks like `<project>-<name>`: the user picks the name and
33
+ * `up` sets the label, so a session of their own is never mistaken for ours.
34
+ */
35
+ export declare function collectWorkspaces({ listSessions, showEnvironment, git, pathExists, scan, }: WorkspacesDependencies): Promise<Workspace[]>;
36
+ /** Git answers through `-C`, so a directory that is gone fails instead of the spawn. */
37
+ export declare function readBranch(git: GitExec, directory: string): Promise<string>;
38
+ /** `$HOME` as `~`. A path that lies elsewhere, or an unknown home, is left alone. */
39
+ export declare function shortenHome(path: string, home: string): string;
40
+ /** KiB as the column shows it: K under a megabyte, M under a gigabyte, then one decimal. */
41
+ export declare function formatRss(kib: number): string;
42
+ /** The table `ls` prints, padded to its own contents. */
43
+ export declare function formatWorkspaceTable(workspaces: readonly Workspace[], home: string): string;
44
+ /** The same rows for machines: absolute directories, and `rssKib` in KiB. */
45
+ export declare function formatWorkspacesJson(workspaces: readonly Workspace[]): string;
@@ -0,0 +1,116 @@
1
+ import { sep } from "node:path";
2
+ import { sessionVariable } from "./process-scan.js";
3
+ const unknownBranch = "-";
4
+ /**
5
+ * A session is a workspace when its tmux environment carries `TERMWIRE_SESSION`,
6
+ * never because its name looks like `<project>-<name>`: the user picks the name and
7
+ * `up` sets the label, so a session of their own is never mistaken for ours.
8
+ */
9
+ export async function collectWorkspaces({ listSessions, showEnvironment, git, pathExists, scan, }) {
10
+ const sessions = await listSessions();
11
+ const labeled = [];
12
+ for (const session of sessions) {
13
+ const environment = await showEnvironment(session.name);
14
+ if (environment[sessionVariable] !== undefined)
15
+ labeled.push(session);
16
+ }
17
+ if (labeled.length === 0)
18
+ return [];
19
+ const usage = await measureSessions(scan, labeled.map((session) => session.name));
20
+ return await Promise.all(labeled.map((session) => describeWorkspace(session, usage.get(session.name) ?? noUsage, { git, pathExists })));
21
+ }
22
+ async function describeWorkspace(session, usage, { git, pathExists }) {
23
+ const exists = await pathExists(session.path);
24
+ return {
25
+ session: session.name,
26
+ attached: session.attached,
27
+ branch: exists ? await readBranch(git, session.path) : unknownBranch,
28
+ directory: session.path,
29
+ missing: !exists,
30
+ ...usage,
31
+ };
32
+ }
33
+ /** Git answers through `-C`, so a directory that is gone fails instead of the spawn. */
34
+ export async function readBranch(git, directory) {
35
+ const current = await git(["git", "-C", directory, "branch", "--show-current"]);
36
+ if (current.exitCode !== 0)
37
+ return unknownBranch;
38
+ const branch = current.stdout.trim();
39
+ if (branch.length > 0)
40
+ return branch;
41
+ // No current branch: a detached HEAD, which the short sha names.
42
+ const head = await git(["git", "-C", directory, "rev-parse", "--short", "HEAD"]);
43
+ const sha = head.stdout.trim();
44
+ return head.exitCode === 0 && sha.length > 0 ? sha : unknownBranch;
45
+ }
46
+ const noUsage = { procs: 0, rssKib: 0 };
47
+ async function measureSessions(scan, sessions) {
48
+ const { processes, labeled } = await scan(sessions);
49
+ const resident = new Map(processes.map(({ pid, rss }) => [pid, rss]));
50
+ const usage = new Map();
51
+ for (const [session, pids] of labeled) {
52
+ let rssKib = 0;
53
+ for (const pid of pids)
54
+ rssKib += resident.get(pid) ?? 0;
55
+ usage.set(session, { procs: pids.length, rssKib });
56
+ }
57
+ return usage;
58
+ }
59
+ /** `$HOME` as `~`. A path that lies elsewhere, or an unknown home, is left alone. */
60
+ export function shortenHome(path, home) {
61
+ const root = home.endsWith(sep) ? home.slice(0, -sep.length) : home;
62
+ if (root.length === 0)
63
+ return path;
64
+ if (path === root)
65
+ return "~";
66
+ return path.startsWith(`${root}${sep}`) ? `~${path.slice(root.length)}` : path;
67
+ }
68
+ /** KiB as the column shows it: K under a megabyte, M under a gigabyte, then one decimal. */
69
+ export function formatRss(kib) {
70
+ if (kib < 1024)
71
+ return `${kib}K`;
72
+ const mib = kib / 1024;
73
+ if (mib < 1024)
74
+ return `${Math.round(mib)}M`;
75
+ return `${(mib / 1024).toFixed(1)}G`;
76
+ }
77
+ /**
78
+ * One column: its header, how it pads, and where its value comes from. Each column
79
+ * carries its own cell so the header row and the data rows cannot fall out of step.
80
+ */
81
+ const columns = [
82
+ { header: "SESSION", align: "left", cell: ({ session }) => session },
83
+ { header: "A", align: "left", cell: ({ attached }) => (attached ? "*" : "") },
84
+ { header: "BRANCH", align: "left", cell: ({ branch }) => branch },
85
+ { header: "DIRECTORY", align: "left", cell: formatDirectory },
86
+ { header: "PROCS", align: "right", cell: ({ procs }) => String(procs) },
87
+ { header: "RSS", align: "right", cell: ({ rssKib }) => formatRss(rssKib) },
88
+ ];
89
+ /** Empty is not an error: nothing running is a normal answer. */
90
+ const noWorkspaces = "no termwire workspaces";
91
+ /** The table `ls` prints, padded to its own contents. */
92
+ export function formatWorkspaceTable(workspaces, home) {
93
+ if (workspaces.length === 0)
94
+ return `${noWorkspaces}\n`;
95
+ const rows = workspaces.map((workspace) => columns.map(({ cell }) => cell(workspace, home)));
96
+ const widths = columns.map(({ header }, index) => rows.reduce((width, cells) => Math.max(width, cells[index].length), header.length));
97
+ const lines = [columns.map(({ header }) => header), ...rows].map((cells) => formatRow(cells, widths));
98
+ return `${lines.join("\n")}\n`;
99
+ }
100
+ /** The same rows for machines: absolute directories, and `rssKib` in KiB. */
101
+ export function formatWorkspacesJson(workspaces) {
102
+ return `${JSON.stringify(workspaces, null, 2)}\n`;
103
+ }
104
+ function formatDirectory(workspace, home) {
105
+ const directory = shortenHome(workspace.directory, home);
106
+ return workspace.missing ? `${directory} (missing)` : directory;
107
+ }
108
+ function formatRow(cells, widths) {
109
+ return cells
110
+ .map((cell, index) => pad(cell, widths[index], columns[index].align))
111
+ .join(" ")
112
+ .trimEnd();
113
+ }
114
+ function pad(cell, width, align) {
115
+ return align === "right" ? cell.padStart(width) : cell.padEnd(width);
116
+ }
@@ -18,9 +18,24 @@ export declare function parseWorktreeList(output: string): WorktreeEntry[];
18
18
  export declare function prepareWorktree(options: {
19
19
  exec: GitExec;
20
20
  pathExists: (path: string) => Promise<boolean>;
21
- realpath?: (path: string) => Promise<string>;
21
+ realpath: (path: string) => Promise<string>;
22
22
  gitRoot: string;
23
23
  project: string;
24
24
  name: string;
25
25
  branch?: string;
26
26
  }): Promise<string>;
27
+ export interface WorktreeState {
28
+ /** The main checkout, which owns the repository and is never a workspace to remove. */
29
+ main: boolean;
30
+ /** Tracked or untracked changes. Ignored files are not changes, so a `.env` is not. */
31
+ dirty: boolean;
32
+ }
33
+ /**
34
+ * A worktree's own Git directory lives inside the common one, so the two paths are
35
+ * equal only in the main checkout.
36
+ */
37
+ export declare function inspectWorktree(exec: GitExec, path: string): Promise<WorktreeState>;
38
+ /** Removes the worktree and its registration. The branch it held outlives it. */
39
+ export declare function removeWorktree(exec: GitExec, path: string, options: {
40
+ force: boolean;
41
+ }): Promise<void>;
package/dist/worktree.js CHANGED
@@ -1,9 +1,24 @@
1
- import { realpath as resolveRealpath } from "node:fs/promises";
2
1
  import { dirname, isAbsolute, join, resolve } from "node:path";
3
2
  import { sanitizeComponent } from "./identity.js";
3
+ /** Git's own words when the directory is outside a repository, next to exit 128. */
4
+ const notARepository = /not a git repository/i;
5
+ /** `git worktree list --porcelain` separates its records with a blank line. */
6
+ const recordSeparator = /\n\s*\n/;
7
+ /** The `worktree <path>` line that opens every record. */
8
+ const worktreePathLine = /^worktree (.+)$/m;
9
+ /** The `branch refs/heads/<name>` line, absent on a detached HEAD. */
10
+ const branchLine = /^branch refs\/heads\/(.+)$/m;
11
+ /** Flags that stand alone on a line of their own. */
12
+ const bareLine = /^bare$/m;
13
+ const detachedLine = /^detached$/m;
14
+ /** The same two flags, except each may carry a reason after a space. */
15
+ const reasonLines = {
16
+ locked: /^locked(?: (.*))?$/m,
17
+ prunable: /^prunable(?: (.*))?$/m,
18
+ };
4
19
  export async function findGitRoot(exec, cwd) {
5
20
  const result = await exec(["git", "rev-parse", "--show-toplevel"], { cwd });
6
- if (result.exitCode === 128 && /not a git repository/i.test(result.stderr)) {
21
+ if (result.exitCode === 128 && notARepository.test(result.stderr)) {
7
22
  return undefined;
8
23
  }
9
24
  if (result.exitCode !== 0) {
@@ -16,21 +31,21 @@ export function parseWorktreeList(output) {
16
31
  if (trimmed === "") {
17
32
  return [];
18
33
  }
19
- return trimmed.split(/\n\s*\n/).map((record) => {
20
- const path = record.match(/^worktree (.+)$/m)?.[1];
34
+ return trimmed.split(recordSeparator).map((record) => {
35
+ const path = record.match(worktreePathLine)?.[1];
21
36
  if (!path) {
22
37
  throw new Error("Git worktree record is missing a path");
23
38
  }
24
39
  const entry = { path };
25
- const branch = record.match(/^branch refs\/heads\/(.+)$/m)?.[1];
40
+ const branch = record.match(branchLine)?.[1];
26
41
  if (branch)
27
42
  entry.branch = branch;
28
- if (/^bare$/m.test(record))
43
+ if (bareLine.test(record))
29
44
  entry.bare = true;
30
- if (/^detached$/m.test(record))
45
+ if (detachedLine.test(record))
31
46
  entry.detached = true;
32
47
  for (const field of ["locked", "prunable"]) {
33
- const match = record.match(new RegExp(`^${field}(?: (.*))?$`, "m"));
48
+ const match = record.match(reasonLines[field]);
34
49
  if (match)
35
50
  entry[field] = match[1] || true;
36
51
  }
@@ -51,7 +66,7 @@ export async function prepareWorktree(options) {
51
66
  gitRoot: options.gitRoot,
52
67
  exec: options.exec,
53
68
  pathExists: options.pathExists,
54
- realpath: options.realpath ?? resolveRealpath,
69
+ realpath: options.realpath,
55
70
  });
56
71
  }
57
72
  if (await options.pathExists(target)) {
@@ -164,3 +179,45 @@ async function validateRegisteredWorktree(options) {
164
179
  function resolveGitPath(path, cwd) {
165
180
  return isAbsolute(path) ? path : resolve(cwd, path);
166
181
  }
182
+ /**
183
+ * A worktree's own Git directory lives inside the common one, so the two paths are
184
+ * equal only in the main checkout.
185
+ */
186
+ export async function inspectWorktree(exec, path) {
187
+ const directories = await exec([
188
+ "git",
189
+ "-C",
190
+ path,
191
+ "rev-parse",
192
+ "--absolute-git-dir",
193
+ "--git-common-dir",
194
+ ]);
195
+ // Git refusing and Git answering with less than the two paths mean the same thing.
196
+ const [gitDir, commonDir] = directories.stdout.trim().split(/\r?\n/);
197
+ if (directories.exitCode !== 0 || !gitDir || !commonDir) {
198
+ throw new Error(`not a Git worktree: ${path}`);
199
+ }
200
+ const status = await exec(["git", "-C", path, "status", "--porcelain"]);
201
+ if (status.exitCode !== 0) {
202
+ throw new Error(`git status failed: ${status.stderr}`);
203
+ }
204
+ return {
205
+ main: resolveGitPath(gitDir, path) === resolveGitPath(commonDir, path),
206
+ dirty: status.stdout.trim().length > 0,
207
+ };
208
+ }
209
+ /** Removes the worktree and its registration. The branch it held outlives it. */
210
+ export async function removeWorktree(exec, path, options) {
211
+ const removed = await exec([
212
+ "git",
213
+ "-C",
214
+ path,
215
+ "worktree",
216
+ "remove",
217
+ ...(options.force ? ["--force"] : []),
218
+ path,
219
+ ]);
220
+ if (removed.exitCode !== 0) {
221
+ throw new Error(`git worktree remove failed: ${removed.stderr}`);
222
+ }
223
+ }
package/package.json CHANGED
@@ -1,6 +1,20 @@
1
1
  {
2
2
  "name": "@termwire/cli",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
+ "description": "Creates tmux workspaces where a coding agent and Neovim run side by side, and opens files in the workspace editor.",
5
+ "keywords": [
6
+ "tmux",
7
+ "neovim",
8
+ "nvim",
9
+ "coding-agent",
10
+ "ai-agent",
11
+ "claude-code",
12
+ "opencode",
13
+ "git-worktree",
14
+ "workspace",
15
+ "cli",
16
+ "developer-tools"
17
+ ],
4
18
  "type": "module",
5
19
  "main": "./dist/index.js",
6
20
  "types": "./dist/index.d.ts",
@@ -38,12 +52,12 @@
38
52
  "url": "https://github.com/max-konin/termwire/issues"
39
53
  },
40
54
  "dependencies": {
41
- "@clack/core": "^1.5.1",
42
- "@clack/prompts": "^1.8.1",
43
- "@termwire/nvim": "^0.5.0",
44
- "@termwire/tmux": "^0.5.0",
45
- "commander": "^15.0.0",
55
+ "@clack/core": "^1.6.0",
56
+ "@clack/prompts": "^1.9.0",
57
+ "@termwire/nvim": "^0.7.0",
58
+ "@termwire/tmux": "^0.7.0",
59
+ "commander": "^15.1.0",
46
60
  "jsonc-parser": "^3.3.1",
47
- "zod": "^4.0.0"
61
+ "zod": "^4.6.6"
48
62
  }
49
63
  }