@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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,101 @@
1
1
  # @termwire/cli
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 59dbb4d: Option+click on a path in any workspace pane opens it in the workspace Neovim at that line. Turn it on with `termwire install --mouse` or `"mouse": { "openPath": "M-MouseDown1Pane" }` in the global config; `up` installs the tmux binding. The tmux adapter gains `listKeys`, `bindKey`, `unbindKey` and `setSessionOption`.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [59dbb4d]
12
+ - @termwire/tmux@0.7.0
13
+ - @termwire/nvim@0.7.0
14
+
15
+ ## 0.6.0
16
+
17
+ ### Minor Changes
18
+
19
+ - cfdcc19: `termwire ls` and `termwire down`: the workspaces you have, and a way to put one away.
20
+
21
+ A tool that creates workspaces owes you a way to see them and a way to remove them.
22
+ Until now tearing one down was `tmux kill-session` plus `git worktree remove`, typed
23
+ by hand, and there was nothing at all that answered "what is running where".
24
+
25
+ ```
26
+ $ termwire ls
27
+ SESSION A BRANCH DIRECTORY PROCS RSS
28
+ termwire-dev * master ~/projects/termwire 7 1.2G
29
+ termwire-demo demo ~/projects/termwire-demo 4 780M
30
+ ```
31
+
32
+ One row per workspace, printed once and then done: `ls` is not a monitor. `A` marks an
33
+ attached session, `BRANCH` is the Git branch of the session directory — a short sha on a
34
+ detached `HEAD`, `-` outside a repository — and `PROCS` and `RSS` count the processes
35
+ still carrying `TERMWIRE_SESSION=<session>`, from the same scan the reap uses, so a
36
+ background agent job is counted as well as a pane. A session whose directory is gone is
37
+ listed and marked `(missing)` rather than crashing the command, and no workspaces prints
38
+ `no termwire workspaces` and exits 0. `--json` prints the same rows for machines, with
39
+ absolute directories.
40
+
41
+ A session counts as a workspace when its tmux session environment carries
42
+ `TERMWIRE_SESSION`, never because its name looks like `<project>-<name>`: you pick the
43
+ name and `up` sets the label, so a session of your own is never listed by its name alone.
44
+ Nothing is read from disk — the list is derived from tmux and Git, so identity stays
45
+ stateless and there is no file to go stale.
46
+
47
+ ```bash
48
+ termwire down dev # kill the workspace session
49
+ termwire down # kill the workspace this shell is in
50
+ termwire down dev -w # and remove the worktree it sits in
51
+ termwire down dev -w --force # even with uncommitted changes
52
+ ```
53
+
54
+ `down` resolves `[name]` exactly as `up` does, so `up dev` and `down dev` always mean one
55
+ session, and it hunts no processes: the `session-closed` hook already reaps that session.
56
+
57
+ Without a name the target is the workspace the command runs in, read from the inherited
58
+ `TERMWIRE_SESSION` — the same environment-based identity `open` uses. Inside a worktree
59
+ workspace that bare form is the only one that works, because there the Git root is the
60
+ worktree, so `down feat` would look for `<worktree>-feat` and find nothing. Outside a
61
+ workspace a bare `down` fails with `not inside a termwire workspace`.
62
+
63
+ `-w` removes the worktree the session was created in, and refuses the main checkout, the
64
+ directory the command is running in, and a worktree holding uncommitted changes unless
65
+ `--force` is given. A refusal removes nothing at all, the session included. The branch is
66
+ never deleted: a branch outlives its workspace. Ignored files are not uncommitted
67
+ changes, so a worktree carrying only `.env` or `node_modules` counts as clean and is
68
+ removed with them.
69
+
70
+ Tearing down your _own_ workspace with `-w` inverts the order: the worktree is removed
71
+ first and the session killed last, because the kill ends the process that would otherwise
72
+ do the removal — and the command steps out of the worktree before removing it, since a
73
+ spawn from a deleted working directory fails with ENOENT. The refusal to remove the
74
+ directory it runs in does not apply there: the shell standing in it dies with the session
75
+ a moment later.
76
+
77
+ The tmux adapter gained `listSessions` and `showEnvironment` on `createTmux`, and the
78
+ process scan now reports resident memory, so `ProcessEntry` carries `rss` in KiB and one
79
+ walk over the process table answers for every workspace at once.
80
+
81
+ Process scanning also became platform-agnostic above the seam. `process-scan.ts` keeps
82
+ only the `SessionScanner` type and the contract a platform has to honour, while
83
+ `process-scan-darwin.ts` and `process-scan-linux.ts` each take their own dependencies;
84
+ `runtime.ts` picks one. Supporting another platform is a new module plus a branch there,
85
+ and `reap` and `ls` do not change, because they depend on the type.
86
+
87
+ Moving the scanner reshapes `CliRuntime`: it gained `createScanner`, a lazy factory so an
88
+ unsupported platform fails the commands that scan instead of every command, and lost
89
+ `exec`, `host.platform`, `host.uid` and `fs.readdir`, which existed only to feed it. It also
90
+ gained `host.chdir`, and `ProgramDependencies` gained `ls`, `down` and `homedir` — so
91
+ anything that builds a runtime or the command set by hand has to follow.
92
+
93
+ ### Patch Changes
94
+
95
+ - Updated dependencies [cfdcc19]
96
+ - @termwire/tmux@0.6.0
97
+ - @termwire/nvim@0.6.0
98
+
3
99
  ## 0.5.0
4
100
 
5
101
  ### Minor Changes
package/README.md CHANGED
@@ -11,6 +11,8 @@ termwire --help
11
11
  termwire --version
12
12
  termwire up dev
13
13
  termwire open src/app.ts:42
14
+ termwire ls
15
+ termwire down dev
14
16
  ```
15
17
 
16
18
  Workspace identity is stateless. It lives in the environment variables that
@@ -36,8 +38,9 @@ half-specified run still stops for the confirmation.
36
38
  | `-l, --layout <name>` | `default`, `three-window`, `focused`, `full-stack`, or `none` |
37
39
  | `-p, --project` | write `.termwire.jsonc` in the Git root instead of the global config |
38
40
  | `-a, --agents <list>` | comma-separated `claude`, `codex`, `opencode`, or `none` |
41
+ | `--mouse`, `--no-mouse` | turn [Option+click](#optionclick) on or off in the global config |
39
42
  | `-f, --force` | replace an existing config, or a skill file you own |
40
- | `-y, --yes` | never prompt: default layout, and no agents unless `--agents` says so |
43
+ | `-y, --yes` | never prompt: default layout, and no agents or mouse unless a flag says so |
41
44
 
42
45
  ### The layout
43
46
 
@@ -46,7 +49,9 @@ you get is what is documented. A config that is already there is kept unless you
46
49
  name a layout: a run meant for the agents does not fail over a file nobody asked to
47
50
  replace. `--agents` without `--layout` leaves the configuration out of the run
48
51
  entirely, so such a run never creates one either. Naming one and passing `--force` replaces it through a temporary file
49
- and a single rename, so a crash cannot leave `up` reading half a config.
52
+ and a single rename, so a crash cannot leave `up` reading half a config. A config
53
+ that is a symlink is replaced where it points, and the `mouse.openPath` the old
54
+ config carried goes into the new one in the same write.
50
55
 
51
56
  ### The skill
52
57
 
@@ -99,6 +104,70 @@ Git branch names and replaced only in filesystem-safe worktree directory names.
99
104
  is changed only when `--branch` is present. Existing tmux sessions attach without Git mutations or
100
105
  rereading/reconciling configuration.
101
106
 
107
+ ## `ls`
108
+
109
+ ```
110
+ SESSION A BRANCH DIRECTORY PROCS RSS
111
+ termwire-dev * master ~/projects/termwire 7 1.2G
112
+ termwire-demo demo ~/projects/termwire-demo 4 780M
113
+ ```
114
+
115
+ One row per workspace on this machine, printed once: `ls` is not a monitor. `A`
116
+ marks an attached session. `DIRECTORY` is where the session was created, with
117
+ `$HOME` shortened to `~`; a directory that is gone is marked `(missing)` rather
118
+ than fatal. `BRANCH` is the Git branch there, a short sha on a detached `HEAD`,
119
+ or `-` outside a repository. `PROCS` and `RSS` count the processes still carrying
120
+ `TERMWIRE_SESSION=<session>` and their resident memory, from the same scan the
121
+ reap uses, so they cover background jobs and not just panes.
122
+
123
+ A session counts as a workspace when its tmux session environment carries
124
+ `TERMWIRE_SESSION`, never because its name looks like `<project>-<name>`. The
125
+ user picks the name and `up` sets the label, so a session of your own is never
126
+ listed by its name alone. Nothing is read from disk: the list comes from tmux and
127
+ Git, so there is no state file to go stale.
128
+
129
+ No workspaces prints `no termwire workspaces` and exits 0. `--json` prints the
130
+ same rows for machines, with absolute directories and `rssKib` in KiB.
131
+
132
+ ## `down`
133
+
134
+ ```bash
135
+ termwire down dev # kill the workspace session
136
+ termwire down # kill the workspace this shell is in
137
+ termwire down dev -w # and remove the worktree it sits in
138
+ termwire down dev -w --force # even with uncommitted changes
139
+ ```
140
+
141
+ `[name]` resolves exactly as it does for `up`, so `up dev` and `down dev` always
142
+ mean one session. `down` kills it and hunts no processes: the `session-closed`
143
+ hook already runs the reap for exactly that session.
144
+
145
+ Without a name the target is the workspace the command runs in, read from the
146
+ inherited `TERMWIRE_SESSION`; outside a workspace it fails with `not inside a
147
+ termwire workspace`. Inside a **worktree** workspace this bare form is the only
148
+ one that works: there the Git root is the worktree itself, so `down <name>` would
149
+ build `<worktree>-<name>` and find no such session.
150
+
151
+ `-w` removes the worktree the session was created in, as tmux reports it, and
152
+ refuses the main checkout, the directory you are standing in, and a worktree
153
+ holding uncommitted changes unless `--force` is given. A refusal removes nothing
154
+ at all, the session included. The branch is never deleted: a branch outlives its
155
+ workspace.
156
+
157
+ Ignored files are not uncommitted changes, so a worktree carrying only `.env` or
158
+ `node_modules` counts as clean and `git worktree remove` deletes them with it. A
159
+ symlinked `.env` is unlinked, leaving the file it points at alone; a real copy is
160
+ gone for good, because Git never had it.
161
+
162
+ Tearing down **your own** workspace with `-w` inverts the order: the worktree is
163
+ removed first and the session killed last. The kill takes this process with it,
164
+ so a removal after it would never run, and a spawn from a deleted working
165
+ directory fails — the command steps out of the worktree before removing it. The
166
+ usual refusal to remove the directory it runs in does not apply here, because the
167
+ shell standing there dies with the session a moment later.
168
+
169
+ An unknown session fails with `no workspace session named <project>-<name>`.
170
+
102
171
  ## Session cleanup
103
172
 
104
173
  `up` installs one global tmux hook, `session-closed`, that runs a hidden
@@ -148,6 +217,55 @@ tmux show-hooks -g | grep TERMWIRE_REAP_HOOK # e.g. session-closed[1]
148
217
  tmux set-hook -gu 'session-closed[1]'
149
218
  ```
150
219
 
220
+ ## Option+click
221
+
222
+ With `"mouse": { "openPath": "M-MouseDown1Pane" }` in the global config, `up`
223
+ binds Option+click in tmux: clicking `src/app.ts`, `src/app.ts:42` or
224
+ `src/app.ts:42:7` in any pane of a workspace — agent output, test failures, `rg`
225
+ results, a diff — opens the file in that workspace's Neovim at that line and
226
+ focuses the editor, exactly like `termwire open`. Turn it on with
227
+ `termwire install --mouse`, or answer yes when the interactive install asks.
228
+
229
+ ```jsonc
230
+ {
231
+ "version": 1,
232
+ "mouse": { "openPath": "M-MouseDown1Pane" }, // or false to remove the binding
233
+ }
234
+ ```
235
+
236
+ - The key is a tmux mouse key with at least one modifier, written the way
237
+ `tmux list-keys` prints it: `M-MouseDown1Pane`, `C-MouseDown1Pane`,
238
+ `C-M-MouseUp1Pane`. It is global only: a project config with `mouse` is an
239
+ error, because a tmux binding belongs to the whole server.
240
+ - tmux sees clicks only with `set -g mouse on` in your `~/.tmux.conf`. Termwire
241
+ never edits that file; the binding lives in the running server, and every `up`
242
+ brings it in line with the config — binding it, moving it to a new key, or
243
+ removing it once the key is `false` or gone.
244
+ - A key that already carries a binding of yours is left alone, and `up` warns.
245
+ Ours is recognised by the `TERMWIRE_CLICK=1` marker in its command.
246
+ - The binding only acts in a Termwire workspace. In any other tmux session the
247
+ click goes on to the application in the pane, as if the key were not bound. `up`
248
+ marks the workspace, so one started by an older version needs `termwire up` once.
249
+ - Cmd+click is not an option in Ghostty: the terminal keeps it for its own links
250
+ and tmux never sees it. Hold Option instead.
251
+ - The path is cut out of the clicked line by column, so dots, colons and slashes
252
+ stay in it. Quotes, backticks, brackets and trailing `.`, `,` or `)` are
253
+ dropped, and so is a diff's `a/` or `b/` when the file exists without it.
254
+ `src/app.ts:42:import` from `grep -n` and `src/app.ts(42,7)` from `tsc` open
255
+ line 42. A relative path is looked up from the pane's directory, then from the
256
+ workspace root; a diff path goes the other way round, because git prints it
257
+ from the repository root. `~/` is the home directory. Nothing opens unless the
258
+ result is an existing file.
259
+ - A click on something that is not a file, or while the editor is gone, does
260
+ nothing on screen and appends one line to
261
+ `$XDG_STATE_HOME/termwire/click.log` (`~/.local/state/termwire/click.log`).
262
+ Only a binding that can no longer start Termwire, after a Node version was
263
+ removed say, shows a message in the tmux status line: run `termwire up` again.
264
+ - The clicked line is screen text anyone could have printed. tmux escapes it with
265
+ `#{q:mouse_line}` before the shell sees it, and Termwire treats it as data only.
266
+ - Not handled: a path wrapped onto the next screen line, `file://` URLs and OSC 8
267
+ hyperlinks.
268
+
151
269
  ## `open`
152
270
 
153
271
  ```bash
@@ -210,8 +328,9 @@ default is used.
210
328
  ### Schema
211
329
 
212
330
  Each configuration root is an object with required numeric `"version": 1`,
213
- optional nonempty-string `"$schema"` for future compatibility, and optional
214
- `windows`; unknown keys are rejected at every level. `windows`, when provided,
331
+ optional nonempty-string `"$schema"` for future compatibility, optional
332
+ `windows`, and, in the global config only, optional `mouse` (see
333
+ [Option+click](#optionclick)); unknown keys are rejected at every level. `windows`, when provided,
215
334
  is a nonempty array of uniquely named window objects. Each window has only
216
335
  `name` and a nonempty `panes` array. Pane ids are nonempty and unique within
217
336
  their window.
@@ -454,6 +573,8 @@ while preserving the original failure.
454
573
  workspace with tmux after creation.
455
574
  - Closing a workspace session kills the processes it started, through the global
456
575
  tmux `session-closed` hook that `up` installs.
576
+ - With `mouse.openPath` set, `up` also binds that key in tmux's root table to the
577
+ hidden `termwire _click` command, which opens the clicked path.
457
578
  - `open <target>` resolves the path, checks that Neovim answers on the socket,
458
579
  opens the file, then focuses the editor pane when one is known.
459
580
  - `install` writes files and reads directories; it starts no process of its own and
@@ -0,0 +1,52 @@
1
+ export interface ClickTarget {
2
+ path: string;
3
+ line?: number;
4
+ }
5
+ /** What the tmux binding passes, every value straight from a format. */
6
+ export interface ClickRequest {
7
+ session: string;
8
+ paneCwd: string;
9
+ /** `session_path`: the workspace directory `up` created the session in. */
10
+ root: string;
11
+ x: string;
12
+ text: string;
13
+ }
14
+ export interface ClickDependencies {
15
+ showEnvironment: (session: string) => Promise<Record<string, string>>;
16
+ isFile: (path: string) => Promise<boolean>;
17
+ homedir: () => string;
18
+ /** `termwire open` against the clicked session's environment rather than our own. */
19
+ open: (target: {
20
+ path: string;
21
+ line?: number;
22
+ }, context: {
23
+ cwd: string;
24
+ env: Record<string, string>;
25
+ }) => Promise<void>;
26
+ }
27
+ /**
28
+ * The `path`, `path:line` or `path:line:col` under cell `x` of a screen line, with
29
+ * quotes, brackets and trailing punctuation cut off. The column is read and dropped:
30
+ * the editor jumps to a line.
31
+ */
32
+ export declare function findPathAt(text: string, x: number): ClickTarget | undefined;
33
+ /**
34
+ * Absolute paths to try, in order.
35
+ *
36
+ * A diff's `a/` and `b/` go first, so a repository that happens to have an `a`
37
+ * directory still opens the file the diff meant, and from the workspace root first:
38
+ * git prints those paths from the repository root, wherever the pane is. Everything
39
+ * else is looked up from the pane, then the root. The part after `=` goes last, for
40
+ * `--config=src/a.ts`.
41
+ */
42
+ export declare function candidatePaths(path: string, context: {
43
+ paneCwd: string;
44
+ root: string;
45
+ homedir: string;
46
+ }): string[];
47
+ /**
48
+ * Opens the clicked path in the workspace editor and returns one line for the log.
49
+ * Screen text is only ever data here: it becomes a path that has to name an existing
50
+ * file before anything is opened.
51
+ */
52
+ export declare function click(request: ClickRequest, dependencies: ClickDependencies): Promise<string>;
package/dist/click.js ADDED
@@ -0,0 +1,138 @@
1
+ import { isAbsolute, join, resolve } from "node:path";
2
+ import { tabMark } from "./mouse-binding.js";
3
+ import { sessionVariable } from "./process-scan.js";
4
+ /**
5
+ * A run of characters up to whatever ends a path on screen. `[` and `]` do not end
6
+ * one, because route directories like `app/[id]/page.tsx` carry them; a path wrapped
7
+ * in them is unwrapped below instead.
8
+ */
9
+ const wordPattern = /[^\s"'`()<>{}|│,;]+/gu;
10
+ const trailingPunctuation = /[.:!?]+$/;
11
+ /**
12
+ * `path`, `path:line` or `path:line:col`. Once there is a line, whatever follows it is
13
+ * dropped: `grep -n` prints `src/a.ts:12:import` with no space before the match.
14
+ */
15
+ const location = /^(.+?)(?::(\d+)(?::(\d+))?(?::.*)?)?$/;
16
+ /** `src/a.ts(12,5)`, the way tsc prints a position. */
17
+ const parenthesizedPosition = /\((\d+),(\d+)\)/g;
18
+ const digits = /^\d+$/;
19
+ const diffPrefix = /^[ab]\//;
20
+ /**
21
+ * The `path`, `path:line` or `path:line:col` under cell `x` of a screen line, with
22
+ * quotes, brackets and trailing punctuation cut off. The column is read and dropped:
23
+ * the editor jumps to a line.
24
+ */
25
+ export function findPathAt(text, x) {
26
+ // The replacement is exactly as long as what it replaces, so cells do not move.
27
+ const normalized = text.replace(parenthesizedPosition, ":$1:$2 ");
28
+ const word = wordAtCell(normalized, x);
29
+ if (word === undefined)
30
+ return undefined;
31
+ const match = location.exec(stripFraming(word));
32
+ if (match === null)
33
+ return undefined;
34
+ const line = match[2] === undefined ? 0 : Number(match[2]);
35
+ return line > 0 ? { path: match[1], line } : { path: match[1] };
36
+ }
37
+ /**
38
+ * Absolute paths to try, in order.
39
+ *
40
+ * A diff's `a/` and `b/` go first, so a repository that happens to have an `a`
41
+ * directory still opens the file the diff meant, and from the workspace root first:
42
+ * git prints those paths from the repository root, wherever the pane is. Everything
43
+ * else is looked up from the pane, then the root. The part after `=` goes last, for
44
+ * `--config=src/a.ts`.
45
+ */
46
+ export function candidatePaths(path, context) {
47
+ const fromPane = [context.paneCwd, context.root];
48
+ const fromRoot = [context.root, context.paneCwd];
49
+ const candidates = [];
50
+ if (diffPrefix.test(path))
51
+ candidates.push(...locate(path.slice(2), fromRoot, context.homedir));
52
+ candidates.push(...locate(path, fromPane, context.homedir));
53
+ if (path.includes("=")) {
54
+ const value = path.slice(path.lastIndexOf("=") + 1);
55
+ candidates.push(...locate(value, fromPane, context.homedir));
56
+ }
57
+ return candidates;
58
+ }
59
+ /**
60
+ * Where one spelling of a path can be. An empty base is skipped: tmux gives an empty
61
+ * `pane_current_path` when it cannot read one, and resolving against it would silently
62
+ * use this process's own directory.
63
+ */
64
+ function locate(path, bases, homedir) {
65
+ if (path.startsWith("~/"))
66
+ return [join(homedir, path.slice(2))];
67
+ if (isAbsolute(path))
68
+ return [path];
69
+ return bases.filter((base) => base !== "").map((base) => resolve(base, path));
70
+ }
71
+ /**
72
+ * Opens the clicked path in the workspace editor and returns one line for the log.
73
+ * Screen text is only ever data here: it becomes a path that has to name an existing
74
+ * file before anything is opened.
75
+ */
76
+ export async function click(request, dependencies) {
77
+ const env = await dependencies.showEnvironment(request.session);
78
+ if (env[sessionVariable] === undefined)
79
+ return "not a termwire session";
80
+ if (!digits.test(request.x))
81
+ return `no mouse position: ${request.x}`;
82
+ // The binding marks tabs, which tmux's `q` leaves for sh to split on.
83
+ const text = request.text.replaceAll(tabMark, "\t");
84
+ const target = findPathAt(text, Number(request.x));
85
+ if (target === undefined)
86
+ return "no path under the mouse";
87
+ const context = { paneCwd: request.paneCwd, root: request.root, homedir: dependencies.homedir() };
88
+ const path = await findFile(candidatePaths(target.path, context), dependencies.isFile);
89
+ if (path === undefined)
90
+ return `no such file: ${target.path}`;
91
+ await dependencies.open({ ...target, path }, { cwd: request.paneCwd, env });
92
+ return `opened ${path}${target.line === undefined ? "" : `:${target.line}`}`;
93
+ }
94
+ /** The first path that names a file, checked in order. */
95
+ async function findFile(paths, isFile) {
96
+ for (const path of paths) {
97
+ if (await isFile(path))
98
+ return path;
99
+ }
100
+ return undefined;
101
+ }
102
+ /**
103
+ * Drops trailing sentence punctuation and unwraps `[...]`. Only a token wrapped on
104
+ * both ends is unwrapped: `[slug].tsx` and `[id]/page.tsx` are file names.
105
+ */
106
+ function stripFraming(token) {
107
+ const bare = token.replace(trailingPunctuation, "");
108
+ const wrapped = bare.startsWith("[") && bare.endsWith("]");
109
+ return wrapped ? bare.slice(1, -1).replace(trailingPunctuation, "") : bare;
110
+ }
111
+ /** The word drawn over cell `x`, if any. Screen cells, not string offsets. */
112
+ function wordAtCell(text, x) {
113
+ for (const match of text.matchAll(wordPattern)) {
114
+ const start = cells(text.slice(0, match.index));
115
+ const end = start + cells(match[0]);
116
+ if (start <= x && x < end)
117
+ return match[0];
118
+ }
119
+ return undefined;
120
+ }
121
+ /** tmux keeps a tab as one character and draws it up to the next multiple of eight. */
122
+ const tabStop = 8;
123
+ function cells(text) {
124
+ let width = 0;
125
+ for (const char of text) {
126
+ width += char === "\t" ? tabStop - (width % tabStop) : cellWidth(char);
127
+ }
128
+ return width;
129
+ }
130
+ const zeroWidth = /\p{Mn}|\p{Me}|\u200d|[\ufe00-\ufe0f]/u;
131
+ const wide = /\p{Emoji_Presentation}|[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6\u{20000}-\u{3fffd}]/u;
132
+ // ponytail: a few ranges instead of a full wcwidth table; a glyph tmux draws at
133
+ // another width shifts the clicked column on that line only.
134
+ function cellWidth(char) {
135
+ if (zeroWidth.test(char))
136
+ return 0;
137
+ return wide.test(char) ? 2 : 1;
138
+ }
@@ -24,6 +24,10 @@ export declare const windowSchema: z.ZodObject<{
24
24
  sizePercent: z.ZodOptional<z.ZodNumber>;
25
25
  }, z.core.$strict>>;
26
26
  }, z.core.$strict>;
27
+ export declare const defaultMouseKey = "M-MouseDown1Pane";
28
+ export declare const mouseSchema: z.ZodObject<{
29
+ openPath: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodLiteral<false>]>>;
30
+ }, z.core.$strict>;
27
31
  export declare const configV1Schema: z.ZodObject<{
28
32
  version: z.ZodLiteral<1>;
29
33
  $schema: z.ZodOptional<z.ZodString>;
@@ -41,6 +45,9 @@ export declare const configV1Schema: z.ZodObject<{
41
45
  sizePercent: z.ZodOptional<z.ZodNumber>;
42
46
  }, z.core.$strict>>;
43
47
  }, z.core.$strict>>>;
48
+ mouse: z.ZodOptional<z.ZodObject<{
49
+ openPath: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodLiteral<false>]>>;
50
+ }, z.core.$strict>>;
44
51
  }, z.core.$strict>;
45
52
  export type PaneConfig = z.infer<typeof paneSchema>;
46
53
  export type WindowConfig = z.infer<typeof windowSchema>;
@@ -11,8 +11,27 @@ export const windowSchema = z.strictObject({
11
11
  name: z.string().min(1),
12
12
  panes: z.array(paneSchema).min(1),
13
13
  });
14
+ export const defaultMouseKey = "M-MouseDown1Pane";
15
+ /**
16
+ * A tmux mouse key on a pane with at least one modifier, spelled the way `list-keys`
17
+ * prints it (modifiers in C-, M-, S- order), so our binding is found again by name.
18
+ */
19
+ const mouseKey = /^(?=[CMS]-)(?:C-)?(?:M-)?(?:S-)?(?:MouseDown|MouseUp|DoubleClick|TripleClick)[123]Pane$/;
20
+ export const mouseSchema = z.strictObject({
21
+ /** The key that opens the path under the mouse, or `false` to remove the binding. */
22
+ openPath: z
23
+ .union([
24
+ z
25
+ .string()
26
+ .regex(mouseKey, `must be a tmux mouse key with a modifier, like ${defaultMouseKey}`),
27
+ z.literal(false),
28
+ ])
29
+ .optional(),
30
+ });
14
31
  export const configV1Schema = z.strictObject({
15
32
  version: z.literal(1),
16
33
  $schema: z.string().min(1).optional(),
17
34
  windows: z.array(windowSchema).min(1).optional(),
35
+ /** Global config only: a tmux key binding belongs to the whole server. */
36
+ mouse: mouseSchema.optional(),
18
37
  });
@@ -1,3 +1,5 @@
1
1
  import { type LayoutConfig } from "./config-schema.js";
2
2
  import type { LoadedConfig } from "./config-types.js";
3
3
  export declare function resolveLayout(globalConfig?: LoadedConfig, projectConfig?: LoadedConfig): LayoutConfig;
4
+ /** The key to bind for opening paths, or `undefined` when none should be bound. */
5
+ export declare function resolveMouseKey(globalConfig?: LoadedConfig): string | undefined;
@@ -8,10 +8,18 @@ const defaultLayout = {
8
8
  export function resolveLayout(globalConfig, projectConfig) {
9
9
  const global = globalConfig ? validateConfig(globalConfig) : undefined;
10
10
  const project = projectConfig ? validateConfig(projectConfig) : undefined;
11
+ if (projectConfig && project?.mouse !== undefined) {
12
+ throw new Error(`${projectConfig.source}: $.mouse: is only allowed in the global config`);
13
+ }
11
14
  const globalWindows = global?.windows;
12
15
  const projectWindows = project?.windows;
13
16
  return copyLayout(projectWindows ?? globalWindows ?? defaultLayout.windows);
14
17
  }
18
+ /** The key to bind for opening paths, or `undefined` when none should be bound. */
19
+ export function resolveMouseKey(globalConfig) {
20
+ const openPath = globalConfig ? validateConfig(globalConfig).mouse?.openPath : undefined;
21
+ return openPath === false ? undefined : openPath;
22
+ }
15
23
  function expectUnique(source, path, values, value) {
16
24
  if (values.has(value)) {
17
25
  throw new Error(`${source}: ${path}: must be unique`);
@@ -86,7 +94,12 @@ function validateWindows(source, value) {
86
94
  }
87
95
  expectSingleEditor(source, editors);
88
96
  }
97
+ /** `up` asks for the layout and for the mouse key; one loaded config is checked once. */
98
+ const validated = new WeakMap();
89
99
  function validateConfig(config) {
100
+ const known = validated.get(config);
101
+ if (known !== undefined)
102
+ return known;
90
103
  const result = configV1Schema.safeParse(config.value);
91
104
  if (!result.success) {
92
105
  throw configError(config.source, result.error.issues[0]);
@@ -94,6 +107,7 @@ function validateConfig(config) {
94
107
  if (result.data.windows !== undefined) {
95
108
  validateWindows(config.source, result.data.windows);
96
109
  }
110
+ validated.set(config, result.data);
97
111
  return result.data;
98
112
  }
99
113
  function configError(source, issue) {
@@ -5,13 +5,15 @@ export interface WriteConfigOptions {
5
5
  force: boolean;
6
6
  }
7
7
  /** The filesystem the runtime already describes, plus a name for the temporary file. */
8
- export interface ConfigWriterDependencies extends Pick<RuntimeFileSystem, "mkdir" | "writeFile" | "rename" | "unlink"> {
8
+ export interface ConfigWriterDependencies extends Pick<RuntimeFileSystem, "mkdir" | "writeFile" | "rename" | "unlink" | "realpath"> {
9
9
  suffix: () => string;
10
10
  }
11
11
  /**
12
12
  * Writes a config without ever losing one. Without `force` the file is created
13
13
  * exclusively, so a config that appeared since the caller last looked is reported
14
14
  * rather than replaced. With `force` the replacement goes through a temporary file
15
- * in the same directory and one `rename`, so `up` never reads a half-written file.
15
+ * in the same directory and one `rename`, so `up` never reads a half-written file. A
16
+ * config that is a symlink, into a dotfiles repository say, is replaced where it
17
+ * points: renaming over the link itself would cut it loose.
16
18
  */
17
19
  export declare function writeConfigFile(options: WriteConfigOptions, dependencies: ConfigWriterDependencies): Promise<void>;
@@ -3,7 +3,9 @@ import { dirname, join } from "node:path";
3
3
  * Writes a config without ever losing one. Without `force` the file is created
4
4
  * exclusively, so a config that appeared since the caller last looked is reported
5
5
  * rather than replaced. With `force` the replacement goes through a temporary file
6
- * in the same directory and one `rename`, so `up` never reads a half-written file.
6
+ * in the same directory and one `rename`, so `up` never reads a half-written file. A
7
+ * config that is a symlink, into a dotfiles repository say, is replaced where it
8
+ * points: renaming over the link itself would cut it loose.
7
9
  */
8
10
  export async function writeConfigFile(options, dependencies) {
9
11
  await dependencies.mkdir(dirname(options.path));
@@ -25,16 +27,26 @@ async function createConfigFile(options, dependencies) {
25
27
  }
26
28
  }
27
29
  async function replaceConfigFile(options, dependencies) {
28
- const temporary = join(dirname(options.path), `.termwire-${dependencies.suffix()}.tmp`);
30
+ const target = await resolveTarget(options.path, dependencies);
31
+ const temporary = join(dirname(target), `.termwire-${dependencies.suffix()}.tmp`);
29
32
  try {
30
33
  await dependencies.writeFile(temporary, options.contents, { flag: "wx" });
31
- await dependencies.rename(temporary, options.path);
34
+ await dependencies.rename(temporary, target);
32
35
  }
33
36
  catch (error) {
34
37
  await removeQuietly(temporary, dependencies);
35
38
  throw error;
36
39
  }
37
40
  }
41
+ /** Where the path really is; the path itself when nothing is there yet. */
42
+ async function resolveTarget(path, dependencies) {
43
+ try {
44
+ return await dependencies.realpath(path);
45
+ }
46
+ catch {
47
+ return path;
48
+ }
49
+ }
38
50
  /** Cleanup must never replace the failure that caused it. */
39
51
  async function removeQuietly(path, dependencies) {
40
52
  try {
package/dist/down.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ import type { WorktreeState } from "./worktree.js";
2
+ export interface DownRequest {
3
+ /** Omitted inside a workspace, where the inherited label names the session. */
4
+ name?: string;
5
+ worktree?: true;
6
+ force?: true;
7
+ }
8
+ export interface DownResult {
9
+ session: string;
10
+ /** Present only when a worktree was removed. */
11
+ worktree?: string;
12
+ }
13
+ /** The fields of a tmux session this command reads, as the adapter reports them. */
14
+ export interface DownSession {
15
+ name: string;
16
+ path: string;
17
+ }
18
+ export interface DownDependencies {
19
+ cwd: () => string;
20
+ /** Called before this command's own directory is removed from under it. */
21
+ chdir: (path: string) => void;
22
+ env: Record<string, string | undefined>;
23
+ findGitRoot: (cwd: string) => Promise<string | undefined>;
24
+ listSessions: () => Promise<DownSession[]>;
25
+ killSession: (session: string) => Promise<void>;
26
+ inspectWorktree: (path: string) => Promise<WorktreeState>;
27
+ removeWorktree: (path: string, options: {
28
+ force: boolean;
29
+ }) => Promise<void>;
30
+ }
31
+ /**
32
+ * Teardown. A name goes through `createIdentity`, so `up foo` and `down foo` always
33
+ * mean one session; without a name the inherited `TERMWIRE_SESSION` names it, which is
34
+ * how a workspace tears itself down from the inside. The tmux listing knows where it
35
+ * lives.
36
+ *
37
+ * Processes are not hunted here: the global `session-closed` hook `up` installs runs
38
+ * `_reap` for exactly that.
39
+ */
40
+ export declare function down(request: DownRequest, { cwd, chdir, env, findGitRoot, listSessions, killSession, inspectWorktree, removeWorktree, }: DownDependencies): Promise<DownResult>;