@termwire/cli 0.4.1 → 0.5.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,87 @@
1
1
  # @termwire/cli
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 4d655c7: `termwire install` sets up a layout and teaches your agents to open files.
8
+
9
+ Two things were documentation-only before. A layout meant copying JSONC out of the
10
+ cookbook by hand, and only Claude Code had a documented line for letting an agent put a
11
+ file in front of you.
12
+
13
+ `termwire install`, reachable as `npx @termwire/cli install` before anything is installed,
14
+ picks one of the four cookbook layouts and writes it globally or into the repository, then
15
+ installs a `termwire-open` skill for the agents you select. It is interactive by default,
16
+ with the window layout drawn beside the list as you move through it, and silent once the
17
+ flags leave nothing to ask: `--yes`, or `--layout` together with `--agents`.
18
+
19
+ The skill teaches an agent to run `termwire open <path>:<line>`, which costs no process.
20
+ That is the point: the `@termwire/mcp` server does the same job but lives as one process
21
+ per agent session for as long as the session does — on a machine running a dozen agents,
22
+ a dozen idle processes. The server is still published for agents that may not run shell
23
+ commands; `install` no longer registers it.
24
+
25
+ Skills go where each agent reads them — `~/.claude/skills/termwire-open/SKILL.md` and
26
+ `$XDG_CONFIG_HOME/opencode/skills/termwire-open/SKILL.md`. The file is shipped as Markdown
27
+ in the package, so you can read exactly what your agent was told. Codex has no skills, so
28
+ it gets the one line to add to `~/.codex/AGENTS.md` printed for you; its own files are
29
+ never edited, and neither is any other agent's configuration.
30
+
31
+ `CliRuntime` gained the members the command needs — `fs.writeFile`, `fs.rename`,
32
+ `host.randomId`, `host.isTerminal` and `createPrompter` — so anything that builds a runtime
33
+ by hand has to supply them. `fs.isExecutable` is gone with the agent-binary probe it served.
34
+
35
+ Re-running changes nothing that is already in place. A skill this command wrote carries a
36
+ marker line and is upgraded silently; delete the line and the file is yours, kept until
37
+ `--force` says otherwise. An
38
+ existing Termwire config is likewise kept unless you name a layout, and every question is
39
+ asked before the plan is confirmed.
40
+
41
+ - 29af197: Package entries export their API instead of every internal, and `run` takes a runtime.
42
+
43
+ Each `index.ts` had grown by reflex: a new module meant a new re-export. Counted against
44
+ real imports, `@termwire/cli` exported 48 names of which exactly one was used, and
45
+ `@termwire/mcp` exported twelve that nothing imported at all. The barrel was a promise
46
+ nobody asked for, and it made every rename a breaking change.
47
+
48
+ **`@termwire/cli` has one breaking change beyond the exports.** `run(argv)` is now
49
+ `run(argv, runtime)`, and the runtime is required — the CLI no longer builds real
50
+ filesystem and process bindings behind the caller's back. A caller does what
51
+ `bin/termwire.ts` does:
52
+
53
+ ```ts
54
+ import { createNodeRuntime, run } from "@termwire/cli";
55
+
56
+ process.exitCode = await run(process.argv.slice(2), createNodeRuntime());
57
+ ```
58
+
59
+ Calling `run(argv)` with nothing else now throws `run needs a runtime: pass
60
+ createNodeRuntime()`. The `termwire` binary itself is unaffected.
61
+
62
+ The entries now carry the factories, the types naming their arguments and results, and
63
+ the error classes a caller catches:
64
+
65
+ - `@termwire/cli`: `run`, `createNodeRuntime`, `createAdapters`, and the `CliRuntime`,
66
+ `RuntimeHost`, `RuntimeFileSystem`, `ProgramDependencies`, `Exec`, `ExecOptions`,
67
+ `ExecResult`, `GitExec`, `ReapSignal` and `KillOutcome` types.
68
+ - `@termwire/tmux` and `@termwire/nvim`: `createTmux` / `createNvim`, their option and
69
+ result types, and `CommandError` / `ValidationError`.
70
+ - `@termwire/mcp`: `createTermwireMcpServer`, `createOpenFileHandler`, and the types those
71
+ two name.
72
+
73
+ What is gone is the per-command functions the factories already expose as methods
74
+ (`killSession`, `respawnPane`, `setEnvironment`, `setHook`, `showHooks`, `unsetHook`,
75
+ `selectLayout`, `openFile`), plus three things that were never methods: `parseHooks`, the
76
+ `tmuxLayouts` constant, and the MCP tool's Zod schemas. Those move to `@termwire/tmux`
77
+ and `@termwire/mcp` internals; if you depended on one, open an issue and say what for.
78
+
79
+ ### Patch Changes
80
+
81
+ - Updated dependencies [29af197]
82
+ - @termwire/tmux@0.5.0
83
+ - @termwire/nvim@0.5.0
84
+
3
85
  ## 0.4.1
4
86
 
5
87
  ### Patch Changes
package/README.md CHANGED
@@ -18,6 +18,69 @@ Workspace identity is stateless. It lives in the environment variables that
18
18
  configuration is optional JSONC read when a session is created; it is not
19
19
  workspace state.
20
20
 
21
+ ## `install`
22
+
23
+ ```bash
24
+ npx @termwire/cli install # before anything is installed
25
+ termwire install # after
26
+ ```
27
+
28
+ Writes a layout configuration and installs a `termwire-open` skill for the agents
29
+ you pick. Interactive by default, with each layout's windows drawn beside the list
30
+ as you move through it, and silent once the flags leave nothing to ask: `--yes`, or
31
+ `--layout` together with `--agents`. A script wants the silent form, because a
32
+ half-specified run still stops for the confirmation.
33
+
34
+ | Option | Meaning |
35
+ | --- | --- |
36
+ | `-l, --layout <name>` | `default`, `three-window`, `focused`, `full-stack`, or `none` |
37
+ | `-p, --project` | write `.termwire.jsonc` in the Git root instead of the global config |
38
+ | `-a, --agents <list>` | comma-separated `claude`, `codex`, `opencode`, or `none` |
39
+ | `-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 |
41
+
42
+ ### The layout
43
+
44
+ The templates are the layouts from the cookbook below, comments included, so what
45
+ you get is what is documented. A config that is already there is kept unless you
46
+ name a layout: a run meant for the agents does not fail over a file nobody asked to
47
+ replace. `--agents` without `--layout` leaves the configuration out of the run
48
+ 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.
50
+
51
+ ### The skill
52
+
53
+ The skill teaches the agent one command, `termwire open <path>:<line>`. It costs
54
+ no process, which is the whole reason it replaced registering `@termwire/mcp`: an
55
+ MCP server lives for as long as the agent session, so a machine running a dozen
56
+ agents carried a dozen of them. The server is still published for an agent that
57
+ may not run shell commands; this command no longer registers it.
58
+
59
+ | Agent | Where the skill goes |
60
+ | --- | --- |
61
+ | Claude Code | `~/.claude/skills/termwire-open/SKILL.md` |
62
+ | OpenCode | `$XDG_CONFIG_HOME/opencode/skills/termwire-open/SKILL.md` |
63
+ | Codex | no skills — the line to add to `~/.codex/AGENTS.md` is printed |
64
+
65
+ An agent is offered only when its own directory exists, which is what proves it is
66
+ set up here; a name on `PATH` is not, because a version manager's shim outlives the
67
+ binary behind it. Nothing is ever written into an agent's configuration — the skill
68
+ is our own file in a directory the agent reads, and Codex's instructions stay yours
69
+ to edit.
70
+
71
+ The file ships as Markdown in this package, so you can read exactly what your agent
72
+ was told, and it ends with a marker line. A skill carrying that marker is ours and
73
+ gets upgraded silently when this package changes it — including a copy you edited but
74
+ left the marker in. Delete the line and the file becomes yours: `install` keeps it and
75
+ says so, and only `--force` replaces it.
76
+
77
+ ### What it will not do
78
+
79
+ It cannot install the CLI itself, because `npx` runs from a cache it does not own,
80
+ and it does not touch the tmux cleanup hook, which `up` installs from a stable
81
+ path. Every question is asked before the plan is confirmed, and nothing is written
82
+ until then. Re-running changes only what has actually changed.
83
+
21
84
  ## `up`
22
85
 
23
86
  | Command | Workspace | Branch |
@@ -393,19 +456,27 @@ while preserving the original failure.
393
456
  tmux `session-closed` hook that `up` installs.
394
457
  - `open <target>` resolves the path, checks that Neovim answers on the socket,
395
458
  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.
459
+ - `install` writes files and reads directories; it starts no process of its own and
460
+ runs no other tool's CLI.
461
+ - The CLI does not need to be in `PATH` for the MCP server or the OpenCode plugin,
462
+ which compose the nvim and tmux adapters directly. The skill is the opposite case:
463
+ it tells the agent to run `termwire open`, so there the CLI does have to be on
464
+ `PATH`.
398
465
 
399
466
  ## Dependencies
400
467
 
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.
468
+ Commander 15 parses the commands; `jsonc-parser` handles JSONC parsing and diagnostics;
469
+ Zod 4 provides strict structural config validation; `@clack/prompts` and
470
+ `@clack/core` draw the `install` prompts, loaded only when there is a terminal to
471
+ draw on. All of them are direct runtime dependencies.
404
472
  `@termwire/tmux` and `@termwire/nvim` are thin adapters over their binaries;
405
473
  the CLI owns workspace policy and orchestration.
406
474
 
407
475
  ## Alternatives for opening files
408
476
 
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.
477
+ The skill `install` writes is the cheap path: the agent runs one shell command and
478
+ nothing stays resident. `@termwire/mcp` exposes the same operation as an MCP tool
479
+ and `@termwire/opencode-plugin` as a native OpenCode tool; both remain published
480
+ for an agent that may not run shell commands. The MCP server is the only one that
481
+ costs a process per agent session. Configure exactly one of the three — two means
482
+ 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/exec.d.ts CHANGED
@@ -3,5 +3,13 @@ export interface ExecResult {
3
3
  stdout: string;
4
4
  stderr: string;
5
5
  }
6
- export type Exec = (argv: readonly string[]) => Promise<ExecResult>;
7
- export declare function spawnCapture(argv: readonly string[]): Promise<ExecResult>;
6
+ export interface ExecOptions {
7
+ /**
8
+ * Hands the terminal to the child instead of capturing it. `tmux attach-session`
9
+ * needs it — without a terminal tmux refuses with "open terminal failed" — and so
10
+ * does any command that asks the user its own questions.
11
+ */
12
+ stdio?: "inherit";
13
+ }
14
+ export type Exec = (argv: readonly string[], options?: ExecOptions) => Promise<ExecResult>;
15
+ export declare function spawnCapture(argv: readonly string[], options?: ExecOptions): Promise<ExecResult>;
package/dist/exec.js CHANGED
@@ -1,17 +1,20 @@
1
1
  import { spawn } from "node:child_process";
2
- export async function spawnCapture(argv) {
2
+ export async function spawnCapture(argv, options = {}) {
3
3
  const [command, ...args] = argv;
4
4
  if (command === undefined) {
5
5
  throw new Error("command must not be empty");
6
6
  }
7
+ const inherited = options.stdio === "inherit";
7
8
  return await new Promise((resolve, reject) => {
8
- const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
9
+ const child = spawn(command, args, {
10
+ stdio: inherited ? "inherit" : ["ignore", "pipe", "pipe"],
11
+ });
9
12
  let stdout = "";
10
13
  let stderr = "";
11
- child.stdout.setEncoding("utf8").on("data", (chunk) => {
14
+ child.stdout?.setEncoding("utf8").on("data", (chunk) => {
12
15
  stdout += chunk;
13
16
  });
14
- child.stderr.setEncoding("utf8").on("data", (chunk) => {
17
+ child.stderr?.setEncoding("utf8").on("data", (chunk) => {
15
18
  stderr += chunk;
16
19
  });
17
20
  child.once("error", reject);
package/dist/index.d.ts CHANGED
@@ -1,17 +1,7 @@
1
- export { prepareBranch } from "./branch.js";
2
- export type { Exec, ExecResult } from "./exec.js";
3
- export { spawnCapture } from "./exec.js";
4
- export type { NvimClient, OpenDependencies, OpenRequest, OpenResult, TmuxClient, } from "./open.js";
5
- export { open, parseTarget } from "./open.js";
6
- export type { DarwinProcessRow, DarwinScanDependencies, LinuxScanDependencies, ProcessEntry, ProcessScan, ProcessScanner, ProcessScannerDependencies, } from "./process-scan.js";
7
- export { containsAssignment, createProcessScanner, parseDarwinArguments, parseDarwinProcesses, parseLinuxPpid, sessionVariable, } from "./process-scan.js";
8
- export type { ProgramDependencies, RuntimeDependencies, RuntimeOpenDependencies, RuntimeReapDependencies, } from "./program.js";
9
- export { createProgram, createRuntimeOpen, createRuntimeReap, createRuntimeUp, executeGit, killProcess, removeStaleSocket, run, } from "./program.js";
10
- export type { KillOutcome, ReapDependencies, ReapReport, ReapSignal } from "./reap.js";
11
- export { formatReapFailure, formatReapReport, protectedPids, reapLogPath, reapSession, selectTargets, } from "./reap.js";
12
- export type { ReapHookOutcome, ReapHookPaths, ReapHookTmux } from "./reap-hook.js";
13
- export { createReapHookCommand, ensureReapHook, reapCommandName, reapHookMarker, reapHookName, } from "./reap-hook.js";
14
- export type { UpDependencies, UpRequest } from "./up.js";
15
- export { up } from "./up.js";
16
- export type { GitExec, WorktreeEntry } from "./worktree.js";
17
- export { findGitRoot, parseWorktreeList, prepareWorktree } from "./worktree.js";
1
+ export type { Exec, ExecOptions, ExecResult } from "./exec.js";
2
+ export type { ProgramDependencies } from "./program.js";
3
+ export { run } from "./program.js";
4
+ export type { KillOutcome, ReapSignal } from "./reap.js";
5
+ export type { CliRuntime, RuntimeFileSystem, RuntimeHost } from "./runtime.js";
6
+ export { createAdapters, createNodeRuntime } from "./runtime.js";
7
+ export type { GitExec } from "./worktree.js";
package/dist/index.js CHANGED
@@ -1,9 +1,2 @@
1
- export { prepareBranch } from "./branch.js";
2
- export { spawnCapture } from "./exec.js";
3
- export { open, parseTarget } from "./open.js";
4
- export { containsAssignment, createProcessScanner, parseDarwinArguments, parseDarwinProcesses, parseLinuxPpid, sessionVariable, } from "./process-scan.js";
5
- export { createProgram, createRuntimeOpen, createRuntimeReap, createRuntimeUp, executeGit, killProcess, removeStaleSocket, run, } from "./program.js";
6
- export { formatReapFailure, formatReapReport, protectedPids, reapLogPath, reapSession, selectTargets, } from "./reap.js";
7
- export { createReapHookCommand, ensureReapHook, reapCommandName, reapHookMarker, reapHookName, } from "./reap-hook.js";
8
- export { up } from "./up.js";
9
- export { findGitRoot, parseWorktreeList, prepareWorktree } from "./worktree.js";
1
+ export { run } from "./program.js";
2
+ export { createAdapters, createNodeRuntime } from "./runtime.js";
@@ -0,0 +1,10 @@
1
+ import { type InstallPrompter } from "./install.js";
2
+ /**
3
+ * The only module that talks to a terminal UI. Everything it returns is plain data,
4
+ * so `install` stays testable with a scripted prompter and no rendering.
5
+ */
6
+ export interface ClackPrompterOptions {
7
+ /** Terminal width, which decides whether the drawing fits beside the list. */
8
+ columns: number;
9
+ }
10
+ export declare function createClackPrompter({ columns }: ClackPrompterOptions): InstallPrompter;
@@ -0,0 +1,100 @@
1
+ import { SelectPrompt } from "@clack/core";
2
+ import { cancel, confirm, intro, isCancel, log, multiselect, outro } from "@clack/prompts";
3
+ import { noLayout } from "./install.js";
4
+ import { renderChoices } from "./layout-preview.js";
5
+ export function createClackPrompter({ columns }) {
6
+ return {
7
+ async layout({ templates, path, exists }) {
8
+ intro("termwire install");
9
+ if (exists) {
10
+ log.info(`${path} already exists; you will be asked before it is replaced.`);
11
+ }
12
+ const choices = [
13
+ ...templates.map((template) => ({
14
+ value: template.id,
15
+ label: template.title,
16
+ hint: template.hint,
17
+ preview: template.preview,
18
+ })),
19
+ {
20
+ value: noLayout,
21
+ label: "Skip",
22
+ hint: "leave the configuration alone",
23
+ preview: [],
24
+ },
25
+ ];
26
+ const message = exists ? `Layout to write to ${path}` : `Layout for ${path}`;
27
+ // `select` from @clack/prompts renders one line per option; drawing the windows
28
+ // beside the list needs the core prompt's own render.
29
+ const answer = await new SelectPrompt({
30
+ options: choices,
31
+ initialValue: "default",
32
+ render() {
33
+ return [
34
+ `${bar} ${message}`,
35
+ indent(renderChoices({ choices, cursor: this.cursor, columns: columns - 2 })),
36
+ bar,
37
+ ].join("\n");
38
+ },
39
+ }).prompt();
40
+ return isCancel(answer) ? cancelled() : answer;
41
+ },
42
+ async agents({ candidates }) {
43
+ // Only agents set up on this machine are offered; the rest are named with the
44
+ // reason, so the list is never a menu of things that cannot work.
45
+ const ready = candidates.filter((candidate) => candidate.state === "ready");
46
+ const missing = candidates.filter((candidate) => candidate.state === "missing");
47
+ const manual = candidates.filter((candidate) => candidate.state === "manual");
48
+ if (missing.length > 0) {
49
+ log.info(`Not set up here: ${missing.map((candidate) => candidate.title).join(", ")}`);
50
+ }
51
+ for (const candidate of manual) {
52
+ log.info(`${candidate.title} takes no skills; you will get the line to add by hand`);
53
+ }
54
+ if (ready.length === 0 && manual.length === 0) {
55
+ log.info("No agent found here, skipping.");
56
+ return [];
57
+ }
58
+ const answer = await multiselect({
59
+ message: "Install the termwire-open skill for",
60
+ required: false,
61
+ initialValues: [],
62
+ options: [...ready, ...manual].map((candidate) => ({
63
+ value: candidate.id,
64
+ label: candidate.title,
65
+ ...(candidate.path === undefined ? {} : { hint: candidate.path }),
66
+ })),
67
+ });
68
+ return isCancel(answer) ? cancelled() : answer;
69
+ },
70
+ async replace({ path }) {
71
+ const answer = await confirm({
72
+ message: `Replace ${path}?`,
73
+ initialValue: false,
74
+ });
75
+ return isCancel(answer) ? cancelled() : answer;
76
+ },
77
+ async confirm({ summary }) {
78
+ log.step(`Plan:\n${summary.map((line) => ` ${line}`).join("\n")}`);
79
+ const answer = await confirm({ message: "Apply this?" });
80
+ if (isCancel(answer))
81
+ return cancelled();
82
+ if (!answer) {
83
+ outro("Nothing changed.");
84
+ return false;
85
+ }
86
+ return true;
87
+ },
88
+ };
89
+ }
90
+ const bar = "│";
91
+ function indent(block) {
92
+ return block
93
+ .split("\n")
94
+ .map((line) => (line.length === 0 ? bar : `${bar} ${line}`))
95
+ .join("\n");
96
+ }
97
+ function cancelled() {
98
+ cancel("Cancelled, nothing changed.");
99
+ return undefined;
100
+ }