@termwire/cli 0.4.1 → 0.6.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,171 @@
1
1
  # @termwire/cli
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - cfdcc19: `termwire ls` and `termwire down`: the workspaces you have, and a way to put one away.
8
+
9
+ A tool that creates workspaces owes you a way to see them and a way to remove them.
10
+ Until now tearing one down was `tmux kill-session` plus `git worktree remove`, typed
11
+ by hand, and there was nothing at all that answered "what is running where".
12
+
13
+ ```
14
+ $ termwire ls
15
+ SESSION A BRANCH DIRECTORY PROCS RSS
16
+ termwire-dev * master ~/projects/termwire 7 1.2G
17
+ termwire-demo demo ~/projects/termwire-demo 4 780M
18
+ ```
19
+
20
+ One row per workspace, printed once and then done: `ls` is not a monitor. `A` marks an
21
+ attached session, `BRANCH` is the Git branch of the session directory — a short sha on a
22
+ detached `HEAD`, `-` outside a repository — and `PROCS` and `RSS` count the processes
23
+ still carrying `TERMWIRE_SESSION=<session>`, from the same scan the reap uses, so a
24
+ background agent job is counted as well as a pane. A session whose directory is gone is
25
+ listed and marked `(missing)` rather than crashing the command, and no workspaces prints
26
+ `no termwire workspaces` and exits 0. `--json` prints the same rows for machines, with
27
+ absolute directories.
28
+
29
+ A session counts as a workspace when its tmux session environment carries
30
+ `TERMWIRE_SESSION`, never because its name looks like `<project>-<name>`: you pick the
31
+ name and `up` sets the label, so a session of your own is never listed by its name alone.
32
+ Nothing is read from disk — the list is derived from tmux and Git, so identity stays
33
+ stateless and there is no file to go stale.
34
+
35
+ ```bash
36
+ termwire down dev # kill the workspace session
37
+ termwire down # kill the workspace this shell is in
38
+ termwire down dev -w # and remove the worktree it sits in
39
+ termwire down dev -w --force # even with uncommitted changes
40
+ ```
41
+
42
+ `down` resolves `[name]` exactly as `up` does, so `up dev` and `down dev` always mean one
43
+ session, and it hunts no processes: the `session-closed` hook already reaps that session.
44
+
45
+ Without a name the target is the workspace the command runs in, read from the inherited
46
+ `TERMWIRE_SESSION` — the same environment-based identity `open` uses. Inside a worktree
47
+ workspace that bare form is the only one that works, because there the Git root is the
48
+ worktree, so `down feat` would look for `<worktree>-feat` and find nothing. Outside a
49
+ workspace a bare `down` fails with `not inside a termwire workspace`.
50
+
51
+ `-w` removes the worktree the session was created in, and refuses the main checkout, the
52
+ directory the command is running in, and a worktree holding uncommitted changes unless
53
+ `--force` is given. A refusal removes nothing at all, the session included. The branch is
54
+ never deleted: a branch outlives its workspace. Ignored files are not uncommitted
55
+ changes, so a worktree carrying only `.env` or `node_modules` counts as clean and is
56
+ removed with them.
57
+
58
+ Tearing down your _own_ workspace with `-w` inverts the order: the worktree is removed
59
+ first and the session killed last, because the kill ends the process that would otherwise
60
+ do the removal — and the command steps out of the worktree before removing it, since a
61
+ spawn from a deleted working directory fails with ENOENT. The refusal to remove the
62
+ directory it runs in does not apply there: the shell standing in it dies with the session
63
+ a moment later.
64
+
65
+ The tmux adapter gained `listSessions` and `showEnvironment` on `createTmux`, and the
66
+ process scan now reports resident memory, so `ProcessEntry` carries `rss` in KiB and one
67
+ walk over the process table answers for every workspace at once.
68
+
69
+ Process scanning also became platform-agnostic above the seam. `process-scan.ts` keeps
70
+ only the `SessionScanner` type and the contract a platform has to honour, while
71
+ `process-scan-darwin.ts` and `process-scan-linux.ts` each take their own dependencies;
72
+ `runtime.ts` picks one. Supporting another platform is a new module plus a branch there,
73
+ and `reap` and `ls` do not change, because they depend on the type.
74
+
75
+ Moving the scanner reshapes `CliRuntime`: it gained `createScanner`, a lazy factory so an
76
+ unsupported platform fails the commands that scan instead of every command, and lost
77
+ `exec`, `host.platform`, `host.uid` and `fs.readdir`, which existed only to feed it. It also
78
+ gained `host.chdir`, and `ProgramDependencies` gained `ls`, `down` and `homedir` — so
79
+ anything that builds a runtime or the command set by hand has to follow.
80
+
81
+ ### Patch Changes
82
+
83
+ - Updated dependencies [cfdcc19]
84
+ - @termwire/tmux@0.6.0
85
+ - @termwire/nvim@0.6.0
86
+
87
+ ## 0.5.0
88
+
89
+ ### Minor Changes
90
+
91
+ - 4d655c7: `termwire install` sets up a layout and teaches your agents to open files.
92
+
93
+ Two things were documentation-only before. A layout meant copying JSONC out of the
94
+ cookbook by hand, and only Claude Code had a documented line for letting an agent put a
95
+ file in front of you.
96
+
97
+ `termwire install`, reachable as `npx @termwire/cli install` before anything is installed,
98
+ picks one of the four cookbook layouts and writes it globally or into the repository, then
99
+ installs a `termwire-open` skill for the agents you select. It is interactive by default,
100
+ with the window layout drawn beside the list as you move through it, and silent once the
101
+ flags leave nothing to ask: `--yes`, or `--layout` together with `--agents`.
102
+
103
+ The skill teaches an agent to run `termwire open <path>:<line>`, which costs no process.
104
+ That is the point: the `@termwire/mcp` server does the same job but lives as one process
105
+ per agent session for as long as the session does — on a machine running a dozen agents,
106
+ a dozen idle processes. The server is still published for agents that may not run shell
107
+ commands; `install` no longer registers it.
108
+
109
+ Skills go where each agent reads them — `~/.claude/skills/termwire-open/SKILL.md` and
110
+ `$XDG_CONFIG_HOME/opencode/skills/termwire-open/SKILL.md`. The file is shipped as Markdown
111
+ in the package, so you can read exactly what your agent was told. Codex has no skills, so
112
+ it gets the one line to add to `~/.codex/AGENTS.md` printed for you; its own files are
113
+ never edited, and neither is any other agent's configuration.
114
+
115
+ `CliRuntime` gained the members the command needs — `fs.writeFile`, `fs.rename`,
116
+ `host.randomId`, `host.isTerminal` and `createPrompter` — so anything that builds a runtime
117
+ by hand has to supply them. `fs.isExecutable` is gone with the agent-binary probe it served.
118
+
119
+ Re-running changes nothing that is already in place. A skill this command wrote carries a
120
+ marker line and is upgraded silently; delete the line and the file is yours, kept until
121
+ `--force` says otherwise. An
122
+ existing Termwire config is likewise kept unless you name a layout, and every question is
123
+ asked before the plan is confirmed.
124
+
125
+ - 29af197: Package entries export their API instead of every internal, and `run` takes a runtime.
126
+
127
+ Each `index.ts` had grown by reflex: a new module meant a new re-export. Counted against
128
+ real imports, `@termwire/cli` exported 48 names of which exactly one was used, and
129
+ `@termwire/mcp` exported twelve that nothing imported at all. The barrel was a promise
130
+ nobody asked for, and it made every rename a breaking change.
131
+
132
+ **`@termwire/cli` has one breaking change beyond the exports.** `run(argv)` is now
133
+ `run(argv, runtime)`, and the runtime is required — the CLI no longer builds real
134
+ filesystem and process bindings behind the caller's back. A caller does what
135
+ `bin/termwire.ts` does:
136
+
137
+ ```ts
138
+ import { createNodeRuntime, run } from "@termwire/cli";
139
+
140
+ process.exitCode = await run(process.argv.slice(2), createNodeRuntime());
141
+ ```
142
+
143
+ Calling `run(argv)` with nothing else now throws `run needs a runtime: pass
144
+ createNodeRuntime()`. The `termwire` binary itself is unaffected.
145
+
146
+ The entries now carry the factories, the types naming their arguments and results, and
147
+ the error classes a caller catches:
148
+
149
+ - `@termwire/cli`: `run`, `createNodeRuntime`, `createAdapters`, and the `CliRuntime`,
150
+ `RuntimeHost`, `RuntimeFileSystem`, `ProgramDependencies`, `Exec`, `ExecOptions`,
151
+ `ExecResult`, `GitExec`, `ReapSignal` and `KillOutcome` types.
152
+ - `@termwire/tmux` and `@termwire/nvim`: `createTmux` / `createNvim`, their option and
153
+ result types, and `CommandError` / `ValidationError`.
154
+ - `@termwire/mcp`: `createTermwireMcpServer`, `createOpenFileHandler`, and the types those
155
+ two name.
156
+
157
+ What is gone is the per-command functions the factories already expose as methods
158
+ (`killSession`, `respawnPane`, `setEnvironment`, `setHook`, `showHooks`, `unsetHook`,
159
+ `selectLayout`, `openFile`), plus three things that were never methods: `parseHooks`, the
160
+ `tmuxLayouts` constant, and the MCP tool's Zod schemas. Those move to `@termwire/tmux`
161
+ and `@termwire/mcp` internals; if you depended on one, open an issue and say what for.
162
+
163
+ ### Patch Changes
164
+
165
+ - Updated dependencies [29af197]
166
+ - @termwire/tmux@0.5.0
167
+ - @termwire/nvim@0.5.0
168
+
3
169
  ## 0.4.1
4
170
 
5
171
  ### Patch 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
@@ -18,6 +20,69 @@ Workspace identity is stateless. It lives in the environment variables that
18
20
  configuration is optional JSONC read when a session is created; it is not
19
21
  workspace state.
20
22
 
23
+ ## `install`
24
+
25
+ ```bash
26
+ npx @termwire/cli install # before anything is installed
27
+ termwire install # after
28
+ ```
29
+
30
+ Writes a layout configuration and installs a `termwire-open` skill for the agents
31
+ you pick. Interactive by default, with each layout's windows drawn beside the list
32
+ as you move through it, and silent once the flags leave nothing to ask: `--yes`, or
33
+ `--layout` together with `--agents`. A script wants the silent form, because a
34
+ half-specified run still stops for the confirmation.
35
+
36
+ | Option | Meaning |
37
+ | --- | --- |
38
+ | `-l, --layout <name>` | `default`, `three-window`, `focused`, `full-stack`, or `none` |
39
+ | `-p, --project` | write `.termwire.jsonc` in the Git root instead of the global config |
40
+ | `-a, --agents <list>` | comma-separated `claude`, `codex`, `opencode`, or `none` |
41
+ | `-f, --force` | replace an existing config, or a skill file you own |
42
+ | `-y, --yes` | never prompt: default layout, and no agents unless `--agents` says so |
43
+
44
+ ### The layout
45
+
46
+ The templates are the layouts from the cookbook below, comments included, so what
47
+ you get is what is documented. A config that is already there is kept unless you
48
+ name a layout: a run meant for the agents does not fail over a file nobody asked to
49
+ replace. `--agents` without `--layout` leaves the configuration out of the run
50
+ entirely, so such a run never creates one either. Naming one and passing `--force` replaces it through a temporary file
51
+ and a single rename, so a crash cannot leave `up` reading half a config.
52
+
53
+ ### The skill
54
+
55
+ The skill teaches the agent one command, `termwire open <path>:<line>`. It costs
56
+ no process, which is the whole reason it replaced registering `@termwire/mcp`: an
57
+ MCP server lives for as long as the agent session, so a machine running a dozen
58
+ agents carried a dozen of them. The server is still published for an agent that
59
+ may not run shell commands; this command no longer registers it.
60
+
61
+ | Agent | Where the skill goes |
62
+ | --- | --- |
63
+ | Claude Code | `~/.claude/skills/termwire-open/SKILL.md` |
64
+ | OpenCode | `$XDG_CONFIG_HOME/opencode/skills/termwire-open/SKILL.md` |
65
+ | Codex | no skills — the line to add to `~/.codex/AGENTS.md` is printed |
66
+
67
+ An agent is offered only when its own directory exists, which is what proves it is
68
+ set up here; a name on `PATH` is not, because a version manager's shim outlives the
69
+ binary behind it. Nothing is ever written into an agent's configuration — the skill
70
+ is our own file in a directory the agent reads, and Codex's instructions stay yours
71
+ to edit.
72
+
73
+ The file ships as Markdown in this package, so you can read exactly what your agent
74
+ was told, and it ends with a marker line. A skill carrying that marker is ours and
75
+ gets upgraded silently when this package changes it — including a copy you edited but
76
+ left the marker in. Delete the line and the file becomes yours: `install` keeps it and
77
+ says so, and only `--force` replaces it.
78
+
79
+ ### What it will not do
80
+
81
+ It cannot install the CLI itself, because `npx` runs from a cache it does not own,
82
+ and it does not touch the tmux cleanup hook, which `up` installs from a stable
83
+ path. Every question is asked before the plan is confirmed, and nothing is written
84
+ until then. Re-running changes only what has actually changed.
85
+
21
86
  ## `up`
22
87
 
23
88
  | Command | Workspace | Branch |
@@ -36,6 +101,70 @@ Git branch names and replaced only in filesystem-safe worktree directory names.
36
101
  is changed only when `--branch` is present. Existing tmux sessions attach without Git mutations or
37
102
  rereading/reconciling configuration.
38
103
 
104
+ ## `ls`
105
+
106
+ ```
107
+ SESSION A BRANCH DIRECTORY PROCS RSS
108
+ termwire-dev * master ~/projects/termwire 7 1.2G
109
+ termwire-demo demo ~/projects/termwire-demo 4 780M
110
+ ```
111
+
112
+ One row per workspace on this machine, printed once: `ls` is not a monitor. `A`
113
+ marks an attached session. `DIRECTORY` is where the session was created, with
114
+ `$HOME` shortened to `~`; a directory that is gone is marked `(missing)` rather
115
+ than fatal. `BRANCH` is the Git branch there, a short sha on a detached `HEAD`,
116
+ or `-` outside a repository. `PROCS` and `RSS` count the processes still carrying
117
+ `TERMWIRE_SESSION=<session>` and their resident memory, from the same scan the
118
+ reap uses, so they cover background jobs and not just panes.
119
+
120
+ A session counts as a workspace when its tmux session environment carries
121
+ `TERMWIRE_SESSION`, never because its name looks like `<project>-<name>`. The
122
+ user picks the name and `up` sets the label, so a session of your own is never
123
+ listed by its name alone. Nothing is read from disk: the list comes from tmux and
124
+ Git, so there is no state file to go stale.
125
+
126
+ No workspaces prints `no termwire workspaces` and exits 0. `--json` prints the
127
+ same rows for machines, with absolute directories and `rssKib` in KiB.
128
+
129
+ ## `down`
130
+
131
+ ```bash
132
+ termwire down dev # kill the workspace session
133
+ termwire down # kill the workspace this shell is in
134
+ termwire down dev -w # and remove the worktree it sits in
135
+ termwire down dev -w --force # even with uncommitted changes
136
+ ```
137
+
138
+ `[name]` resolves exactly as it does for `up`, so `up dev` and `down dev` always
139
+ mean one session. `down` kills it and hunts no processes: the `session-closed`
140
+ hook already runs the reap for exactly that session.
141
+
142
+ Without a name the target is the workspace the command runs in, read from the
143
+ inherited `TERMWIRE_SESSION`; outside a workspace it fails with `not inside a
144
+ termwire workspace`. Inside a **worktree** workspace this bare form is the only
145
+ one that works: there the Git root is the worktree itself, so `down <name>` would
146
+ build `<worktree>-<name>` and find no such session.
147
+
148
+ `-w` removes the worktree the session was created in, as tmux reports it, and
149
+ refuses the main checkout, the directory you are standing in, and a worktree
150
+ holding uncommitted changes unless `--force` is given. A refusal removes nothing
151
+ at all, the session included. The branch is never deleted: a branch outlives its
152
+ workspace.
153
+
154
+ Ignored files are not uncommitted changes, so a worktree carrying only `.env` or
155
+ `node_modules` counts as clean and `git worktree remove` deletes them with it. A
156
+ symlinked `.env` is unlinked, leaving the file it points at alone; a real copy is
157
+ gone for good, because Git never had it.
158
+
159
+ Tearing down **your own** workspace with `-w` inverts the order: the worktree is
160
+ removed first and the session killed last. The kill takes this process with it,
161
+ so a removal after it would never run, and a spawn from a deleted working
162
+ directory fails — the command steps out of the worktree before removing it. The
163
+ usual refusal to remove the directory it runs in does not apply here, because the
164
+ shell standing there dies with the session a moment later.
165
+
166
+ An unknown session fails with `no workspace session named <project>-<name>`.
167
+
39
168
  ## Session cleanup
40
169
 
41
170
  `up` installs one global tmux hook, `session-closed`, that runs a hidden
@@ -393,19 +522,27 @@ while preserving the original failure.
393
522
  tmux `session-closed` hook that `up` installs.
394
523
  - `open <target>` resolves the path, checks that Neovim answers on the socket,
395
524
  opens the file, then focuses the editor pane when one is known.
396
- - The CLI does not need to be in `PATH` for the MCP server or the OpenCode
397
- plugin. Both compose the nvim and tmux adapters directly.
525
+ - `install` writes files and reads directories; it starts no process of its own and
526
+ runs no other tool's CLI.
527
+ - The CLI does not need to be in `PATH` for the MCP server or the OpenCode plugin,
528
+ which compose the nvim and tmux adapters directly. The skill is the opposite case:
529
+ it tells the agent to run `termwire open`, so there the CLI does have to be on
530
+ `PATH`.
398
531
 
399
532
  ## Dependencies
400
533
 
401
- Commander 15 parses `up`; `jsonc-parser` handles JSONC parsing and diagnostics;
402
- Zod 4 provides strict structural config validation. All three are direct runtime
403
- dependencies.
534
+ Commander 15 parses the commands; `jsonc-parser` handles JSONC parsing and diagnostics;
535
+ Zod 4 provides strict structural config validation; `@clack/prompts` and
536
+ `@clack/core` draw the `install` prompts, loaded only when there is a terminal to
537
+ draw on. All of them are direct runtime dependencies.
404
538
  `@termwire/tmux` and `@termwire/nvim` are thin adapters over their binaries;
405
539
  the CLI owns workspace policy and orchestration.
406
540
 
407
541
  ## Alternatives for opening files
408
542
 
409
- `@termwire/mcp` exposes the same open operation as an MCP tool and
410
- `@termwire/opencode-plugin` as a native OpenCode tool. They exist for agents
411
- that should not run shell commands. Configure one of the three, not several.
543
+ The skill `install` writes is the cheap path: the agent runs one shell command and
544
+ nothing stays resident. `@termwire/mcp` exposes the same operation as an MCP tool
545
+ and `@termwire/opencode-plugin` as a native OpenCode tool; both remain published
546
+ for an agent that may not run shell commands. The MCP server is the only one that
547
+ costs a process per agent session. Configure exactly one of the three — two means
548
+ the agent sees the same tool twice.
@@ -0,0 +1,24 @@
1
+ export declare const agentIds: readonly ["claude", "codex", "opencode"];
2
+ export type AgentId = (typeof agentIds)[number];
3
+ export declare const skillName = "termwire-open";
4
+ export interface AgentPaths {
5
+ home: string;
6
+ /** `$XDG_CONFIG_HOME`, already resolved to an absolute path. */
7
+ configHome: string;
8
+ }
9
+ export interface AgentDefinition {
10
+ id: AgentId;
11
+ title: string;
12
+ /** Existing directory that proves this agent is set up here. */
13
+ home: (paths: AgentPaths) => string;
14
+ /**
15
+ * Where the agent reads user skills from, or undefined when it has no skills. We only
16
+ * ever add our own directory there; the agent's own files stay untouched.
17
+ */
18
+ skillPath: ((paths: AgentPaths) => string) | undefined;
19
+ /** What to do by hand when the agent cannot take a skill. */
20
+ manual: readonly string[];
21
+ }
22
+ export declare function agentDefinitions(): AgentDefinition[];
23
+ export declare function findAgentDefinition(id: string): AgentDefinition | undefined;
24
+ export declare function parseAgentIds(value: string): AgentId[];
package/dist/agents.js ADDED
@@ -0,0 +1,54 @@
1
+ import { join } from "node:path";
2
+ export const agentIds = ["claude", "codex", "opencode"];
3
+ export const skillName = "termwire-open";
4
+ const definitions = [
5
+ {
6
+ id: "claude",
7
+ title: "Claude Code",
8
+ home: ({ home }) => join(home, ".claude"),
9
+ skillPath: ({ home }) => join(home, ".claude", "skills", skillName, "SKILL.md"),
10
+ manual: [],
11
+ },
12
+ {
13
+ id: "codex",
14
+ title: "Codex",
15
+ home: ({ home }) => join(home, ".codex"),
16
+ // Codex has no skills; its instructions live in one file that belongs to the user.
17
+ skillPath: undefined,
18
+ manual: [
19
+ "Codex has no skills. Add one line to ~/.codex/AGENTS.md:",
20
+ "",
21
+ " To show the user a file, run `termwire open <path>:<line>`.",
22
+ ],
23
+ },
24
+ {
25
+ id: "opencode",
26
+ title: "OpenCode",
27
+ home: ({ configHome }) => join(configHome, "opencode"),
28
+ skillPath: ({ configHome }) => join(configHome, "opencode", "skills", skillName, "SKILL.md"),
29
+ manual: [],
30
+ },
31
+ ];
32
+ export function agentDefinitions() {
33
+ return definitions.map((agent) => ({ ...agent }));
34
+ }
35
+ export function findAgentDefinition(id) {
36
+ const agent = definitions.find((candidate) => candidate.id === id);
37
+ return agent === undefined ? undefined : { ...agent };
38
+ }
39
+ export function parseAgentIds(value) {
40
+ const requested = value
41
+ .split(",")
42
+ .map((entry) => entry.trim())
43
+ .filter((entry) => entry.length > 0);
44
+ if (requested.length === 1 && requested[0] === "none")
45
+ return [];
46
+ if (requested.length === 0) {
47
+ throw new Error(`--agents needs one of ${agentIds.join(", ")}, or none`);
48
+ }
49
+ const unknown = requested.filter((entry) => !agentIds.includes(entry));
50
+ if (unknown.length > 0) {
51
+ throw new Error(`unknown agent: ${unknown.join(", ")} (expected ${agentIds.join(", ")})`);
52
+ }
53
+ return [...new Set(requested)];
54
+ }
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import { run } from "../index.js";
3
- process.exitCode = await run(process.argv.slice(2));
2
+ import { createNodeRuntime, run } from "../index.js";
3
+ process.exitCode = await run(process.argv.slice(2), createNodeRuntime());
@@ -9,3 +9,12 @@ export declare function createConfigLoader(dependencies: ConfigLoaderDependencie
9
9
  loadGlobal(): Promise<LoadedConfig | undefined>;
10
10
  loadProject(gitRoot: string): Promise<LoadedConfig | undefined>;
11
11
  };
12
+ /** `$XDG_CONFIG_HOME` when it is absolute, `~/.config` otherwise. */
13
+ export declare function configHome(dependencies: {
14
+ env: Record<string, string | undefined>;
15
+ homedir: () => string;
16
+ }): string;
17
+ export declare function globalConfigPath(dependencies: {
18
+ env: Record<string, string | undefined>;
19
+ homedir: () => string;
20
+ }): string;
@@ -10,12 +10,15 @@ export function createConfigLoader(dependencies) {
10
10
  },
11
11
  };
12
12
  }
13
- function globalConfigPath(dependencies) {
13
+ /** `$XDG_CONFIG_HOME` when it is absolute, `~/.config` otherwise. */
14
+ export function configHome(dependencies) {
14
15
  const xdgConfigHome = dependencies.env.XDG_CONFIG_HOME;
15
- const configHome = xdgConfigHome && isAbsolute(xdgConfigHome)
16
+ return xdgConfigHome && isAbsolute(xdgConfigHome)
16
17
  ? xdgConfigHome
17
18
  : join(dependencies.homedir(), ".config");
18
- return join(configHome, "termwire", "config.jsonc");
19
+ }
20
+ export function globalConfigPath(dependencies) {
21
+ return join(configHome(dependencies), "termwire", "config.jsonc");
19
22
  }
20
23
  function lineColumn(text, offset) {
21
24
  let line = 1;
@@ -0,0 +1,17 @@
1
+ import type { RuntimeFileSystem } from "./runtime.js";
2
+ export interface WriteConfigOptions {
3
+ path: string;
4
+ contents: string;
5
+ force: boolean;
6
+ }
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"> {
9
+ suffix: () => string;
10
+ }
11
+ /**
12
+ * Writes a config without ever losing one. Without `force` the file is created
13
+ * exclusively, so a config that appeared since the caller last looked is reported
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.
16
+ */
17
+ export declare function writeConfigFile(options: WriteConfigOptions, dependencies: ConfigWriterDependencies): Promise<void>;
@@ -0,0 +1,46 @@
1
+ import { dirname, join } from "node:path";
2
+ /**
3
+ * Writes a config without ever losing one. Without `force` the file is created
4
+ * exclusively, so a config that appeared since the caller last looked is reported
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.
7
+ */
8
+ export async function writeConfigFile(options, dependencies) {
9
+ await dependencies.mkdir(dirname(options.path));
10
+ if (options.force) {
11
+ await replaceConfigFile(options, dependencies);
12
+ return;
13
+ }
14
+ await createConfigFile(options, dependencies);
15
+ }
16
+ async function createConfigFile(options, dependencies) {
17
+ try {
18
+ await dependencies.writeFile(options.path, options.contents, { flag: "wx" });
19
+ }
20
+ catch (error) {
21
+ if (error.code === "EEXIST") {
22
+ throw new Error(`${options.path} already exists; pass --force to replace it`);
23
+ }
24
+ throw error;
25
+ }
26
+ }
27
+ async function replaceConfigFile(options, dependencies) {
28
+ const temporary = join(dirname(options.path), `.termwire-${dependencies.suffix()}.tmp`);
29
+ try {
30
+ await dependencies.writeFile(temporary, options.contents, { flag: "wx" });
31
+ await dependencies.rename(temporary, options.path);
32
+ }
33
+ catch (error) {
34
+ await removeQuietly(temporary, dependencies);
35
+ throw error;
36
+ }
37
+ }
38
+ /** Cleanup must never replace the failure that caused it. */
39
+ async function removeQuietly(path, dependencies) {
40
+ try {
41
+ await dependencies.unlink(path);
42
+ }
43
+ catch {
44
+ // Nothing to report: the caller is already throwing.
45
+ }
46
+ }
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>;