@bypane/cli 0.0.0-stage → 0.2.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.
@@ -0,0 +1,170 @@
1
+ import { clusterAt, clusterEnd, clusterWidth } from "tui";
2
+ export function normalizeSelection(sel) {
3
+ if (sel.anchorRow < sel.focusRow || (sel.anchorRow === sel.focusRow && sel.anchorCol <= sel.focusCol)) {
4
+ return {
5
+ startRow: sel.anchorRow,
6
+ startCol: sel.anchorCol,
7
+ endRow: sel.focusRow,
8
+ endCol: sel.focusCol,
9
+ };
10
+ }
11
+ return {
12
+ startRow: sel.focusRow,
13
+ startCol: sel.focusCol,
14
+ endRow: sel.anchorRow,
15
+ endCol: sel.anchorCol,
16
+ };
17
+ }
18
+ export function markdownLineText(line) {
19
+ let out = "";
20
+ for (const span of line)
21
+ out += span.text;
22
+ return out;
23
+ }
24
+ /**
25
+ * Slices `text` by inclusive display-column range `[startCol, endCol]` using grapheme cluster widths.
26
+ */
27
+ export function sliceByColumns(str, startCol, endCol) {
28
+ if (!str || endCol < startCol || endCol < 0)
29
+ return "";
30
+ const lo = Math.max(0, startCol);
31
+ let col = 0;
32
+ let idx = 0;
33
+ let out = "";
34
+ while (idx < str.length) {
35
+ const packed = clusterAt(str, idx);
36
+ const end = clusterEnd(packed);
37
+ const w = Math.max(1, clusterWidth(packed));
38
+ const nextCol = col + w;
39
+ if (nextCol > lo && col <= endCol) {
40
+ out += str.slice(idx, end);
41
+ }
42
+ col = nextCol;
43
+ idx = end;
44
+ if (col > endCol)
45
+ break;
46
+ }
47
+ return out;
48
+ }
49
+ /**
50
+ * Finds the display-column bounds `[startCol, endCol]` of the word at display column `targetCol`.
51
+ */
52
+ export function wordBoundsAtColumn(str, targetCol) {
53
+ if (!str)
54
+ return null;
55
+ const cells = [];
56
+ let col = 0;
57
+ let idx = 0;
58
+ while (idx < str.length) {
59
+ const packed = clusterAt(str, idx);
60
+ const end = clusterEnd(packed);
61
+ const w = Math.max(1, clusterWidth(packed));
62
+ const ch = str.slice(idx, end);
63
+ const isWord = /[\p{L}\p{N}_\-./]/u.test(ch);
64
+ cells.push({ ch, col, w, isWord });
65
+ col += w;
66
+ idx = end;
67
+ }
68
+ if (cells.length === 0)
69
+ return null;
70
+ let hit = cells.findIndex((c) => targetCol >= c.col && targetCol < c.col + c.w);
71
+ if (hit < 0)
72
+ return null;
73
+ const wantWord = cells[hit].isWord;
74
+ if (!wantWord && /\s/.test(cells[hit].ch))
75
+ return null;
76
+ let left = hit;
77
+ while (left > 0 && cells[left - 1].isWord === wantWord && !/\s/.test(cells[left - 1].ch)) {
78
+ left--;
79
+ }
80
+ let right = hit;
81
+ while (right + 1 < cells.length && cells[right + 1].isWord === wantWord && !/\s/.test(cells[right + 1].ch)) {
82
+ right++;
83
+ }
84
+ return {
85
+ startCol: cells[left].col,
86
+ endCol: cells[right].col + cells[right].w - 1,
87
+ };
88
+ }
89
+ /**
90
+ * Extracts selected text across rendered rows. For wrapped Markdown (`joinWrapped: true`),
91
+ * non-empty adjacent lines join with a single space while blank lines preserve paragraph breaks.
92
+ */
93
+ export function extractSelectionText(lines, sel, joinWrapped) {
94
+ const { startRow, startCol, endRow, endCol } = normalizeSelection(sel);
95
+ const r0 = Math.max(0, Math.min(lines.length - 1, startRow));
96
+ const r1 = Math.max(0, Math.min(lines.length - 1, endRow));
97
+ if (lines.length === 0)
98
+ return { text: "", startRow: r0, endRow: r1 };
99
+ if (r0 === r1) {
100
+ const snippet = sliceByColumns(lines[r0] ?? "", startCol, endCol).trim();
101
+ return { text: snippet, startRow: r0, endRow: r1 };
102
+ }
103
+ const parts = [];
104
+ for (let r = r0; r <= r1; r++) {
105
+ const raw = lines[r] ?? "";
106
+ if (r === r0) {
107
+ parts.push(sliceByColumns(raw, startCol, Number.MAX_SAFE_INTEGER).trimEnd());
108
+ }
109
+ else if (r === r1) {
110
+ parts.push(sliceByColumns(raw, 0, endCol).trimEnd());
111
+ }
112
+ else {
113
+ parts.push(raw.trimEnd());
114
+ }
115
+ }
116
+ if (!joinWrapped) {
117
+ return { text: parts.join("\n").trim(), startRow: r0, endRow: r1 };
118
+ }
119
+ // Join wrapped prose lines smoothly while preserving intentional blank-line paragraph breaks.
120
+ let out = "";
121
+ for (let i = 0; i < parts.length; i++) {
122
+ const p = parts[i].trim();
123
+ if (!p) {
124
+ if (out && !out.endsWith("\n\n"))
125
+ out += "\n\n";
126
+ continue;
127
+ }
128
+ if (!out || out.endsWith("\n")) {
129
+ out += p;
130
+ }
131
+ else {
132
+ out += ` ${p}`;
133
+ }
134
+ }
135
+ return { text: out.trim(), startRow: r0, endRow: r1 };
136
+ }
137
+ /**
138
+ * Overlays selection highlighting onto already-drawn cells inside `rect`, preserving every character.
139
+ */
140
+ export function paintSelectionHighlight(frame, rect, offset, textStartX, sel, lineCount) {
141
+ const { startRow, startCol, endRow, endCol } = normalizeSelection(sel);
142
+ if (startRow === endRow && startCol === endCol && !sel.dragging)
143
+ return;
144
+ if (lineCount <= 0)
145
+ return;
146
+ const hiStyle = frame.styles.style(frame.theme.highlight);
147
+ const cells = frame.cells;
148
+ const maxTextCols = Math.max(0, rect.x + rect.columns - textStartX);
149
+ if (maxTextCols <= 0)
150
+ return;
151
+ for (let vRow = 0; vRow < rect.rows; vRow++) {
152
+ const docRow = offset + vRow;
153
+ if (docRow < startRow || docRow > endRow || docRow >= lineCount)
154
+ continue;
155
+ const y = rect.y + vRow;
156
+ if (y < 0 || y >= cells.rows)
157
+ continue;
158
+ const c0 = docRow === startRow ? Math.max(0, startCol) : 0;
159
+ const c1 = docRow === endRow ? Math.min(maxTextCols - 1, endCol) : maxTextCols - 1;
160
+ if (c1 < c0)
161
+ continue;
162
+ const rowOffset = y * cells.columns;
163
+ for (let col = c0; col <= c1; col++) {
164
+ const x = textStartX + col;
165
+ if (x < textStartX || x >= rect.x + rect.columns || x >= cells.columns)
166
+ continue;
167
+ cells.styles[rowOffset + x] = hiStyle;
168
+ }
169
+ }
170
+ }
package/dist/setup.js ADDED
@@ -0,0 +1,329 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, lstatSync, mkdirSync, symlinkSync, unlinkSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { confirm, multiselect, select, spinner } from "tui/prompt";
7
+ import { loadConfig, saveConfig } from "./config.js";
8
+ import { canAutoDock, detectRexIdentity, detectTmuxWindow } from "./multiplexer.js";
9
+ import { BYPANE_SKILL_MD, discoverSkillTargets, installSkillTo, removeSkillFrom, } from "./skill.js";
10
+ import { bypaneTheme } from "./ui.js";
11
+ const ANSI = {
12
+ reset: "\x1b[0m",
13
+ bold: "\x1b[1m",
14
+ dim: "\x1b[2m",
15
+ accent: "\x1b[38;2;122;162;255m",
16
+ green: "\x1b[38;2;95;215;135m",
17
+ amber: "\x1b[38;2;245;166;35m",
18
+ };
19
+ function styled(code, text) {
20
+ return process.stdout.isTTY ? `${code}${text}${ANSI.reset}` : text;
21
+ }
22
+ function isBypaneOnPath() {
23
+ try {
24
+ execFileSync(process.platform === "win32" ? "where" : "which", ["bypane"], {
25
+ stdio: "ignore",
26
+ timeout: 1500,
27
+ });
28
+ return true;
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ const NPM_PACKAGE = "@bypane/cli";
35
+ export function installBypanePermanently(overrideHome) {
36
+ if (isBypaneOnPath()) {
37
+ return { status: "already_installed" };
38
+ }
39
+ // When running directly from a local TypeScript checkout during dev/tests, skip registry install.
40
+ if (import.meta.url.endsWith(".ts")) {
41
+ return { status: "skipped", via: "dev-source" };
42
+ }
43
+ // 1. Try standard global npm install first.
44
+ try {
45
+ execFileSync("npm", ["install", "-g", NPM_PACKAGE, "--no-audit", "--no-fund"], {
46
+ stdio: ["ignore", "pipe", "pipe"],
47
+ timeout: 45_000,
48
+ });
49
+ if (isBypaneOnPath()) {
50
+ return { status: "installed", via: `npm install -g ${NPM_PACKAGE}` };
51
+ }
52
+ }
53
+ catch {
54
+ // Fall through to user-local prefix install (handles root-owned global npm / EACCES cleanly).
55
+ }
56
+ // 2. Durable user-local fallback (~/.local/share/bypane -> ~/.local/bin/bypane).
57
+ const home = overrideHome || process.env.HOME || homedir();
58
+ const prefix = join(home, ".local", "share", "bypane");
59
+ const binDir = join(home, ".local", "bin");
60
+ const binLink = join(binDir, "bypane");
61
+ const targetBin = join(prefix, "node_modules", ".bin", "bypane");
62
+ try {
63
+ mkdirSync(prefix, { recursive: true });
64
+ execFileSync("npm", ["install", "--prefix", prefix, NPM_PACKAGE, "--no-audit", "--no-fund"], {
65
+ stdio: ["ignore", "pipe", "pipe"],
66
+ timeout: 45_000,
67
+ });
68
+ if (!existsSync(targetBin)) {
69
+ return { status: "failed", error: `Installed prefix missing ${targetBin}` };
70
+ }
71
+ mkdirSync(binDir, { recursive: true });
72
+ try {
73
+ lstatSync(binLink);
74
+ unlinkSync(binLink);
75
+ }
76
+ catch {
77
+ // No existing file/symlink.
78
+ }
79
+ symlinkSync(targetBin, binLink);
80
+ const pathEntries = (process.env.PATH || "").split(delimiter);
81
+ const pathMissing = !pathEntries.includes(binDir);
82
+ return { status: "installed", via: binLink, path: binLink, pathMissing };
83
+ }
84
+ catch (err) {
85
+ return { status: "failed", error: err.message };
86
+ }
87
+ }
88
+ function mcpCommandSpec(cliAvailable) {
89
+ const isTs = import.meta.url.endsWith(".ts");
90
+ if (cliAvailable) {
91
+ return { command: "bypane", args: ["mcp"], shell: "bypane mcp", viaNpx: false };
92
+ }
93
+ if (!isTs) {
94
+ return {
95
+ command: "npx",
96
+ args: ["-y", NPM_PACKAGE, "mcp"],
97
+ shell: `npx -y ${NPM_PACKAGE} mcp`,
98
+ viaNpx: true,
99
+ };
100
+ }
101
+ const cliPath = fileURLToPath(new URL("./cli.ts", import.meta.url));
102
+ return { command: "node", args: [cliPath, "mcp"], shell: `node ${cliPath} mcp`, viaNpx: false };
103
+ }
104
+ export async function runSetupWizard(options = {}) {
105
+ const out = options.writeOut ?? ((s) => process.stdout.write(s));
106
+ const existingConfig = loadConfig(options.overrideHome);
107
+ const targets = discoverSkillTargets(options.overrideHome);
108
+ const rex = detectRexIdentity();
109
+ const tmux = detectTmuxWindow();
110
+ const envParts = [];
111
+ if (rex)
112
+ envParts.push("Rex");
113
+ else if (tmux)
114
+ envParts.push("tmux");
115
+ else
116
+ envParts.push("standalone terminal");
117
+ if (process.env.TERM === "xterm-ghostty")
118
+ envParts.push("Ghostty graphics");
119
+ else if (process.env.TERM === "xterm-kitty")
120
+ envParts.push("Kitty graphics");
121
+ const detectedHarnesses = targets.filter((t) => t.detected && t.id !== "project").map((t) => t.id);
122
+ if (detectedHarnesses.length > 0)
123
+ envParts.push(`skill dirs: ${detectedHarnesses.join(", ")}`);
124
+ out("\n");
125
+ out(`${styled(ANSI.accent + ANSI.bold, "◈ bypane setup")}\n`);
126
+ out(`${styled(ANSI.dim, ` Detected: ${envParts.join(" · ")}`)}\n\n`);
127
+ let chosenSkillIds;
128
+ let layoutChoice;
129
+ let showMcpSnippet;
130
+ let launchDemo = false;
131
+ const wizardTargets = targets.filter((t) => t.id !== "project");
132
+ if (options.yes || !process.stdin.isTTY) {
133
+ chosenSkillIds = wizardTargets
134
+ .filter((t) => t.detected || t.id === "agents")
135
+ .map((t) => t.id);
136
+ layoutChoice = `${existingConfig.splitDirection}:${existingConfig.splitRatio}`;
137
+ showMcpSnippet = true;
138
+ }
139
+ else {
140
+ const defaultSkills = wizardTargets.map((t) => t.id);
141
+ const pickedSkills = await multiselect({
142
+ theme: bypaneTheme,
143
+ message: "Install bypane agent skill?",
144
+ items: wizardTargets.map((t) => ({
145
+ value: t.id,
146
+ label: t.installed ? `${t.label} [installed]` : t.label,
147
+ })),
148
+ defaultValues: defaultSkills,
149
+ });
150
+ if (pickedSkills === null) {
151
+ process.stdout.write(`${styled(ANSI.dim, "Setup cancelled.")}\n`);
152
+ return;
153
+ }
154
+ chosenSkillIds = [...pickedSkills];
155
+ const currentLayout = existingConfig.autoDock
156
+ ? `${existingConfig.splitDirection}:${existingConfig.splitRatio}`
157
+ : "manual";
158
+ const layoutItems = [
159
+ { value: "right:44", label: "Auto-dock on the right (44% width, keep focus on chat)" },
160
+ { value: "right:50", label: "Auto-dock on the right (50% split, keep focus on chat)" },
161
+ { value: "left:42", label: "Auto-dock on the left (42% width, keep focus on chat)" },
162
+ { value: "below:38", label: "Auto-dock below (38% height, keep focus on chat)" },
163
+ { value: "manual", label: "Manual only (never auto-split; I'll run `bypane` myself)" },
164
+ ];
165
+ const defaultLayout = layoutItems.some((i) => i.value === currentLayout)
166
+ ? currentLayout
167
+ : "right:44";
168
+ const pickedLayout = await select({
169
+ theme: bypaneTheme,
170
+ message: "Companion pane auto-dock layout:",
171
+ items: layoutItems,
172
+ defaultValue: defaultLayout,
173
+ });
174
+ if (pickedLayout === null) {
175
+ process.stdout.write(`${styled(ANSI.dim, "Setup cancelled.")}\n`);
176
+ return;
177
+ }
178
+ layoutChoice = pickedLayout;
179
+ const wantMcp = await confirm({
180
+ theme: bypaneTheme,
181
+ message: "Show optional MCP config snippet? (CLI + skill works without MCP)",
182
+ defaultValue: true,
183
+ });
184
+ if (wantMcp === null) {
185
+ process.stdout.write(`${styled(ANSI.dim, "Setup cancelled.")}\n`);
186
+ return;
187
+ }
188
+ showMcpSnippet = wantMcp;
189
+ }
190
+ let nextConfig;
191
+ if (layoutChoice === "manual") {
192
+ nextConfig = { ...existingConfig, autoDock: false };
193
+ }
194
+ else {
195
+ const [dirRaw, ratioRaw] = layoutChoice.split(":");
196
+ const dir = dirRaw || "right";
197
+ const ratio = Number(ratioRaw) || 44;
198
+ nextConfig = { autoDock: true, splitDirection: dir, splitRatio: ratio };
199
+ }
200
+ const spin = process.stdout.isTTY
201
+ ? spinner({ theme: bypaneTheme, message: "Setting up bypane…" })
202
+ : null;
203
+ let installRes = { status: "skipped" };
204
+ if (!options.skipInstall) {
205
+ spin?.update("Installing bypane command on PATH…");
206
+ installRes = options.installCli
207
+ ? options.installCli()
208
+ : installBypanePermanently(options.overrideHome);
209
+ }
210
+ spin?.update("Saving bypane configuration…");
211
+ const savedConfigPath = saveConfig(nextConfig, options.overrideHome);
212
+ const installedPaths = [];
213
+ for (const id of chosenSkillIds) {
214
+ const target = targets.find((t) => t.id === id);
215
+ if (!target)
216
+ continue;
217
+ spin?.update(`Installing skill to ${target.path}…`);
218
+ installedPaths.push(installSkillTo(target.path));
219
+ }
220
+ spin?.stop("bypane configured");
221
+ out("\n");
222
+ if (installRes.status === "installed") {
223
+ out(` ${styled(ANSI.green, "✓")} CLI installed permanently (${installRes.via})\n`);
224
+ if (installRes.pathMissing) {
225
+ out(` ${styled(ANSI.amber, "Note: add ~/.local/bin to your PATH to run `bypane` directly.")}\n`);
226
+ }
227
+ }
228
+ else if (installRes.status === "already_installed") {
229
+ out(` ${styled(ANSI.green, "✓")} CLI ready on PATH (\`bypane\`)\n`);
230
+ }
231
+ else if (installRes.status === "failed") {
232
+ out(` ${styled(ANSI.amber, "!")} Could not install \`bypane\` globally (${installRes.error ?? "offline"}) — falling back to \`npx -y ${NPM_PACKAGE}\`\n`);
233
+ }
234
+ out(` ${styled(ANSI.green, "✓")} Config saved: ${savedConfigPath}\n`);
235
+ out(` ${styled(ANSI.dim, nextConfig.autoDock ? `auto-dock: ${nextConfig.splitDirection} (${nextConfig.splitRatio}%)` : "auto-dock: manual")}\n`);
236
+ if (installedPaths.length > 0) {
237
+ for (const item of installedPaths) {
238
+ out(` ${styled(ANSI.green, "✓")} Skill ${item.status}: ${item.path}\n`);
239
+ }
240
+ }
241
+ else {
242
+ out(` ${styled(ANSI.dim, "·")} No skill files installed (run \`bypane skill setup\` anytime)\n`);
243
+ }
244
+ if (showMcpSnippet) {
245
+ const cliAvailable = installRes.status === "installed" ||
246
+ installRes.status === "already_installed" ||
247
+ isBypaneOnPath();
248
+ const mcp = mcpCommandSpec(cliAvailable);
249
+ out("\n");
250
+ out(`${styled(ANSI.bold, "Optional MCP registration:")}\n`);
251
+ out(` ${styled(ANSI.dim, "# Claude Code")}\n`);
252
+ out(` claude mcp add bypane -- ${mcp.shell}\n`);
253
+ out(` ${styled(ANSI.dim, "# Generic JSON (Codex / OpenCode / Antigravity / Cursor)")}\n`);
254
+ out(` ${JSON.stringify({ mcpServers: { bypane: { command: mcp.command, args: mcp.args } } })}\n`);
255
+ }
256
+ if (!options.yes && process.stdin.isTTY && canAutoDock() && options.onLaunchDemo) {
257
+ out("\n");
258
+ const tryDemo = await confirm({
259
+ theme: bypaneTheme,
260
+ message: "Open a live demo pane right now to test it?",
261
+ defaultValue: true,
262
+ });
263
+ launchDemo = tryDemo === true;
264
+ }
265
+ if (launchDemo && options.onLaunchDemo) {
266
+ await options.onLaunchDemo();
267
+ }
268
+ else {
269
+ out("\n");
270
+ out(`${styled(ANSI.dim, "Next: run `bypane --demo` (or `bypane demo` inside Rex/tmux) to see all surfaces live.")}\n`);
271
+ }
272
+ }
273
+ export function runSkillSubcommand(sub, flags, overrideHome) {
274
+ const action = sub || "status";
275
+ const targets = discoverSkillTargets(overrideHome);
276
+ if (action === "show") {
277
+ process.stdout.write(BYPANE_SKILL_MD);
278
+ return 0;
279
+ }
280
+ if (action === "status") {
281
+ process.stdout.write("bypane skill status:\n");
282
+ for (const t of targets) {
283
+ const state = t.installed
284
+ ? t.managed
285
+ ? "installed (managed)"
286
+ : "installed (custom)"
287
+ : "not installed";
288
+ process.stdout.write(` ${t.id.padEnd(8)} ${state.padEnd(20)} ${t.path}\n`);
289
+ }
290
+ return 0;
291
+ }
292
+ if (action === "setup" || action === "install") {
293
+ const requested = typeof flags.target === "string" ? flags.target : "agents";
294
+ const list = requested === "all"
295
+ ? targets.filter((t) => t.id !== "project" && (t.detected || t.id === "agents"))
296
+ : targets.filter((t) => t.id === requested);
297
+ if (list.length === 0) {
298
+ process.stderr.write(`Unknown skill target "${requested}". Use: agents, claude, codex, project, or all.\n`);
299
+ return 1;
300
+ }
301
+ for (const t of list) {
302
+ const res = installSkillTo(t.path);
303
+ process.stdout.write(`bypane skill ${res.status}: ${res.path}\n`);
304
+ }
305
+ return 0;
306
+ }
307
+ if (action === "remove" || action === "uninstall") {
308
+ const force = Boolean(flags.force);
309
+ const requested = typeof flags.target === "string" ? flags.target : "all";
310
+ const list = requested === "all" ? targets : targets.filter((t) => t.id === requested);
311
+ let removedAny = false;
312
+ for (const t of list) {
313
+ const res = removeSkillFrom(t.path, force);
314
+ if (res.status === "removed") {
315
+ removedAny = true;
316
+ process.stdout.write(`Removed: ${res.path}\n`);
317
+ }
318
+ else if (res.status === "unmanaged") {
319
+ process.stderr.write(`Skipped unmanaged skill (pass --force to remove): ${res.path}\n`);
320
+ }
321
+ }
322
+ if (!removedAny) {
323
+ process.stdout.write("No managed bypane skill installations found.\n");
324
+ }
325
+ return 0;
326
+ }
327
+ process.stderr.write("Usage: bypane skill <setup|show|status|remove> [--target agents|claude|codex|project|all] [--force]\n");
328
+ return 1;
329
+ }