@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/dist/down.js ADDED
@@ -0,0 +1,99 @@
1
+ import { dirname, resolve, sep } from "node:path";
2
+ import { createIdentity } from "./identity.js";
3
+ import { sessionVariable } from "./process-scan.js";
4
+ /**
5
+ * Teardown. A name goes through `createIdentity`, so `up foo` and `down foo` always
6
+ * mean one session; without a name the inherited `TERMWIRE_SESSION` names it, which is
7
+ * how a workspace tears itself down from the inside. The tmux listing knows where it
8
+ * lives.
9
+ *
10
+ * Processes are not hunted here: the global `session-closed` hook `up` installs runs
11
+ * `_reap` for exactly that.
12
+ */
13
+ export async function down(request, { cwd, chdir, env, findGitRoot, listSessions, killSession, inspectWorktree, removeWorktree, }) {
14
+ const directory = cwd();
15
+ const target = await resolveSession(request, { cwd: directory, env, findGitRoot });
16
+ const sessions = await listSessions();
17
+ const session = sessions.find((entry) => entry.name === target);
18
+ if (session === undefined) {
19
+ throw new Error(`no workspace session named ${target}`);
20
+ }
21
+ if (request.worktree !== true) {
22
+ await killSession(target);
23
+ return { session: target };
24
+ }
25
+ /** Whether the session being torn down is the one this command is running in. */
26
+ const ownSession = env[sessionVariable]?.trim() === target;
27
+ const force = request.force === true;
28
+ // Everything is refused before anything is destroyed, so a refusal leaves the
29
+ // session running and the worktree untouched.
30
+ await assertRemovable({ path: session.path, cwd: directory, force, ownSession, inspectWorktree });
31
+ if (ownSession) {
32
+ // The kill ends this process with its pane, so it goes last. And the kill is a
33
+ // spawn, which fails with ENOENT from a deleted working directory, so step out of
34
+ // the worktree first; the parent of a worktree always outlives it.
35
+ if (contains(session.path, directory))
36
+ chdir(dirname(session.path));
37
+ await removeWorktree(session.path, { force });
38
+ await killSession(target);
39
+ }
40
+ else {
41
+ // Nothing of ours dies here, so the processes go first and their files after them.
42
+ await killSession(target);
43
+ await removeKilledWorktree({ session: target, path: session.path, force, removeWorktree });
44
+ }
45
+ return { session: target, worktree: session.path };
46
+ }
47
+ /**
48
+ * A name is resolved from the current directory, exactly as `up` resolves it. Without
49
+ * one, the session is the workspace this command is running in, which is the only way
50
+ * to name a worktree session from inside it: there the Git root is the worktree, so
51
+ * `createIdentity` would build `<worktree>-<name>` and find nothing.
52
+ */
53
+ async function resolveSession(request, { cwd, env, findGitRoot }) {
54
+ if (request.name === undefined) {
55
+ const session = env[sessionVariable]?.trim();
56
+ if (!session) {
57
+ throw new Error("not inside a termwire workspace");
58
+ }
59
+ return session;
60
+ }
61
+ const gitRoot = await findGitRoot(cwd);
62
+ return createIdentity({ cwd, gitRoot, name: request.name }).session;
63
+ }
64
+ /**
65
+ * The session is already gone by the time the worktree is removed, so a failure here
66
+ * says so: `down` cannot be retried for a session that no longer exists, and the user
67
+ * needs to know that `git worktree remove` is what is left to do.
68
+ */
69
+ async function removeKilledWorktree({ session, path, force, removeWorktree, }) {
70
+ try {
71
+ await removeWorktree(path, { force });
72
+ }
73
+ catch (cause) {
74
+ const message = cause instanceof Error ? cause.message : String(cause);
75
+ throw new Error(`session ${session} was killed, but its worktree was not removed: ${message}`, {
76
+ cause,
77
+ });
78
+ }
79
+ }
80
+ async function assertRemovable({ path, cwd, force, ownSession, inspectWorktree, }) {
81
+ // Sawing off the branch you stand on, unless the shell standing there is itself part
82
+ // of what is being torn down: it dies with the session a moment later.
83
+ if (!ownSession && contains(path, cwd)) {
84
+ throw new Error(`refusing to remove the directory this command runs in: ${path}`);
85
+ }
86
+ const state = await inspectWorktree(path);
87
+ if (state.main) {
88
+ throw new Error(`refusing to remove the main checkout: ${path}`);
89
+ }
90
+ if (state.dirty && !force) {
91
+ throw new Error(`${path} has uncommitted changes: pass --force to remove it anyway`);
92
+ }
93
+ }
94
+ /** Whether `inner` is `outer` itself or lies below it. */
95
+ function contains(outer, inner) {
96
+ const base = resolve(outer);
97
+ const nested = resolve(inner);
98
+ return nested === base || nested.startsWith(`${base}${sep}`);
99
+ }
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
+ }
@@ -0,0 +1,92 @@
1
+ import { type AgentId, type AgentPaths } from "./agents.js";
2
+ import { type LayoutTemplate } from "./templates.js";
3
+ export declare const noLayout = "none";
4
+ export type InstallLayoutChoice = LayoutTemplate["id"] | typeof noLayout;
5
+ export interface InstallRequest {
6
+ layout?: string;
7
+ project?: boolean;
8
+ agents?: readonly AgentId[];
9
+ force?: boolean;
10
+ yes?: boolean;
11
+ }
12
+ /**
13
+ * `ready` takes the skill, `manual` is set up here but has no skills to take it, and
14
+ * `missing` is not installed at all.
15
+ */
16
+ export type AgentState = "ready" | "manual" | "missing";
17
+ export interface AgentCandidate {
18
+ id: AgentId;
19
+ title: string;
20
+ state: AgentState;
21
+ /** Where the skill would go, for the agents that can take one. */
22
+ path?: string;
23
+ }
24
+ /** Every prompt returns `undefined` when the user cancelled. */
25
+ export interface InstallPrompter {
26
+ layout: (options: {
27
+ templates: LayoutTemplate[];
28
+ path: string;
29
+ exists: boolean;
30
+ }) => Promise<InstallLayoutChoice | undefined>;
31
+ agents: (options: {
32
+ candidates: AgentCandidate[];
33
+ }) => Promise<readonly AgentId[] | undefined>;
34
+ /** Asked only when a config is already there and no --force settled it. */
35
+ replace: (options: {
36
+ path: string;
37
+ }) => Promise<boolean | undefined>;
38
+ confirm: (options: {
39
+ summary: string[];
40
+ }) => Promise<boolean | undefined>;
41
+ }
42
+ export interface InstallDependencies {
43
+ cwd: () => string;
44
+ findGitRoot: (cwd: string) => Promise<string | undefined>;
45
+ globalConfigPath: () => string;
46
+ agentPaths: AgentPaths;
47
+ /** The SKILL.md shipped with the package, copied verbatim into each agent. */
48
+ skillSource: string;
49
+ pathExists: (path: string) => Promise<boolean>;
50
+ readFile: (path: string) => Promise<string>;
51
+ /** Shared with the layout config: atomic, and never clobbers without force. */
52
+ writeConfig: (options: {
53
+ path: string;
54
+ contents: string;
55
+ force: boolean;
56
+ }) => Promise<void>;
57
+ write: (message: string) => void;
58
+ /** Absent when nothing can be asked, which makes the run non-interactive. */
59
+ prompt?: InstallPrompter;
60
+ isTerminal: boolean;
61
+ }
62
+ export type AgentOutcomeKind =
63
+ /** The skill was written. */
64
+ "installed"
65
+ /** The same skill was already there, so this run left it alone. */
66
+ | "present"
67
+ /** A different skill was there — edited by hand, most likely — and was kept. */
68
+ | "kept"
69
+ /** Installed here, but takes no skills: the user has to add a line themselves. */
70
+ | "manual" | "unavailable" | "failed";
71
+ export interface AgentOutcome {
72
+ id: AgentId;
73
+ outcome: AgentOutcomeKind;
74
+ detail?: string;
75
+ }
76
+ export interface InstallResult {
77
+ cancelled: boolean;
78
+ configPath?: string;
79
+ configWritten: boolean;
80
+ agents: AgentOutcome[];
81
+ failures: string[];
82
+ }
83
+ export declare function install(request: InstallRequest, dependencies: InstallDependencies): Promise<InstallResult>;
84
+ export type AgentAction = "install" | "replace" | "keep" | "present" | "manual" | "unavailable";
85
+ export interface AgentPlan {
86
+ id: AgentId;
87
+ title: string;
88
+ action: AgentAction;
89
+ path?: string;
90
+ /** Set when the skill could not be read at all. */
91
+ error?: string;
92
+ }