@bypane/cli 0.0.0-stage → 0.1.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/config.js ADDED
@@ -0,0 +1,42 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ export const DEFAULT_CONFIG = {
5
+ autoDock: true,
6
+ splitDirection: "right",
7
+ splitRatio: 44,
8
+ };
9
+ export function configPath(overrideHome) {
10
+ const xdg = !overrideHome ? process.env.XDG_CONFIG_HOME : undefined;
11
+ const base = xdg || join(overrideHome || process.env.HOME || homedir(), ".config");
12
+ return join(base, "bypane", "config.json");
13
+ }
14
+ export function loadConfig(overrideHome) {
15
+ const path = configPath(overrideHome);
16
+ if (!existsSync(path))
17
+ return { ...DEFAULT_CONFIG };
18
+ try {
19
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
20
+ const dir = parsed.splitDirection;
21
+ const validDir = dir === "right" || dir === "left" || dir === "below" || dir === "above"
22
+ ? dir
23
+ : DEFAULT_CONFIG.splitDirection;
24
+ const ratio = typeof parsed.splitRatio === "number" && parsed.splitRatio >= 20 && parsed.splitRatio <= 80
25
+ ? Math.round(parsed.splitRatio)
26
+ : DEFAULT_CONFIG.splitRatio;
27
+ return {
28
+ autoDock: typeof parsed.autoDock === "boolean" ? parsed.autoDock : DEFAULT_CONFIG.autoDock,
29
+ splitDirection: validDir,
30
+ splitRatio: ratio,
31
+ };
32
+ }
33
+ catch {
34
+ return { ...DEFAULT_CONFIG };
35
+ }
36
+ }
37
+ export function saveConfig(config, overrideHome) {
38
+ const path = configPath(overrideHome);
39
+ mkdirSync(dirname(path), { recursive: true });
40
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, "utf8");
41
+ return path;
42
+ }
package/dist/demo.js ADDED
@@ -0,0 +1,166 @@
1
+ import { deflateSync } from "node:zlib";
2
+ import { writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ /** Generates a crisp synthetic PNG gradient + geometric card so the demo works anywhere offline. */
6
+ function crc32(buf) {
7
+ let c = 0xffffffff;
8
+ for (let i = 0; i < buf.length; i++) {
9
+ c ^= buf[i];
10
+ for (let k = 0; k < 8; k++) {
11
+ c = (c >>> 1) ^ (0xedb88320 & -(c & 1));
12
+ }
13
+ }
14
+ return (c ^ 0xffffffff) >>> 0;
15
+ }
16
+ function pngChunk(type, data) {
17
+ const out = new Uint8Array(12 + data.length);
18
+ const dv = new DataView(out.buffer);
19
+ dv.setUint32(0, data.length);
20
+ for (let i = 0; i < 4; i++)
21
+ out[4 + i] = type.charCodeAt(i);
22
+ out.set(data, 8);
23
+ dv.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)));
24
+ return out;
25
+ }
26
+ export function createDemoPng(width = 160, height = 96) {
27
+ const stride = width * 4;
28
+ const raw = new Uint8Array(height * (stride + 1));
29
+ for (let y = 0; y < height; y++) {
30
+ const rowStart = y * (stride + 1);
31
+ raw[rowStart] = 0;
32
+ for (let x = 0; x < width; x++) {
33
+ const i = rowStart + 1 + x * 4;
34
+ const nx = x / width;
35
+ const ny = y / height;
36
+ // Clean dark-slate backdrop with soft indigo/mint radial glow and crisp frame accents
37
+ const dx1 = nx - 0.32;
38
+ const dy1 = ny - 0.42;
39
+ const g1 = Math.exp(-(dx1 * dx1 + dy1 * dy1) * 9);
40
+ const dx2 = nx - 0.72;
41
+ const dy2 = ny - 0.62;
42
+ const g2 = Math.exp(-(dx2 * dx2 + dy2 * dy2) * 10);
43
+ let r = 18 + g1 * 90 + g2 * 35;
44
+ let g = 22 + g1 * 125 + g2 * 175;
45
+ let b = 34 + g1 * 215 + g2 * 120;
46
+ // Subtle geometric rings
47
+ const dist = Math.hypot((nx - 0.5) * (width / height), ny - 0.5);
48
+ if (Math.abs(dist - 0.28) < 0.015 || Math.abs(dist - 0.14) < 0.012) {
49
+ r = 225;
50
+ g = 236;
51
+ b = 255;
52
+ }
53
+ raw[i] = Math.min(255, Math.round(r));
54
+ raw[i + 1] = Math.min(255, Math.round(g));
55
+ raw[i + 2] = Math.min(255, Math.round(b));
56
+ raw[i + 3] = 255;
57
+ }
58
+ }
59
+ const ihdr = new Uint8Array(13);
60
+ const dv = new DataView(ihdr.buffer);
61
+ dv.setUint32(0, width);
62
+ dv.setUint32(4, height);
63
+ ihdr[8] = 8;
64
+ ihdr[9] = 6; // RGBA
65
+ const idat = deflateSync(raw);
66
+ const sig = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
67
+ const c1 = pngChunk("IHDR", ihdr);
68
+ const c2 = pngChunk("IDAT", idat);
69
+ const c3 = pngChunk("IEND", new Uint8Array(0));
70
+ const out = new Uint8Array(sig.length + c1.length + c2.length + c3.length);
71
+ let off = 0;
72
+ for (const part of [sig, c1, c2, c3]) {
73
+ out.set(part, off);
74
+ off += part.length;
75
+ }
76
+ return out;
77
+ }
78
+ export function loadDemoSurfaces(store) {
79
+ const demoPngPath = join(tmpdir(), `bypane-demo-${process.getuid?.() ?? 0}.png`);
80
+ try {
81
+ writeFileSync(demoPngPath, createDemoPng());
82
+ }
83
+ catch {
84
+ // Ignore if tmp write fails; image card will display fallback error gracefully.
85
+ }
86
+ store.present({
87
+ id: "demo-plan",
88
+ kind: "markdown",
89
+ title: "Release Plan",
90
+ focus: true,
91
+ origin: { mux: "standalone", label: "demo-agent" },
92
+ content: [
93
+ "# bypane v0.1 Release Checklist",
94
+ "",
95
+ "Toggle tasks below with **Space** (or click) — agents read your checked state via `bypane_state`, or press **`s`** to push feedback straight back to your agent pane.",
96
+ "",
97
+ "- [x] Per-session Unix socket IPC & Rex/tmux auto-dock",
98
+ "- [x] MCP stdio server (`bypane mcp`) with human-only `ask` gates",
99
+ "- [ ] Review latency benchmark table on tab `3`",
100
+ "- [ ] Confirm rollout target on tab `5`",
101
+ "",
102
+ "## Why a companion pane?",
103
+ "",
104
+ "Chat stays conversational in your main pane while plans, QuickLook images/files, filterable tables, braille charts, and interactive approvals stay spatial and persistent here.",
105
+ ].join("\n"),
106
+ });
107
+ store.present({
108
+ id: "demo-image",
109
+ kind: "image",
110
+ title: "preview.png",
111
+ path: demoPngPath,
112
+ caption: "Inline PNG rendered via Kitty/Ghostty graphics (half-block fallback elsewhere). Press 'o' to open on host.",
113
+ origin: { mux: "standalone", label: "demo-agent" },
114
+ focus: false,
115
+ });
116
+ store.present({
117
+ id: "demo-table",
118
+ kind: "table",
119
+ title: "Benchmarks",
120
+ origin: { mux: "standalone", label: "demo-agent" },
121
+ focus: false,
122
+ columns: [
123
+ { key: "runtime", label: "Runtime", width: 18 },
124
+ { key: "startup", label: "Startup", align: "right", width: 10 },
125
+ { key: "memory", label: "Peak RAM", align: "right", width: 10 },
126
+ { key: "binary", label: "Size", align: "right", width: 10 },
127
+ { key: "notes", label: "Notes" },
128
+ ],
129
+ rows: [
130
+ { id: "scriptc", runtime: "bypane (scriptc)", startup: "1.8 ms", memory: "3.9 MB", binary: "1.9 MB", notes: "Native binary, zero runtime" },
131
+ { id: "node24", runtime: "bypane (Node 24)", startup: "89 ms", memory: "96 MB", binary: "123 MB", notes: "Instant dev iteration" },
132
+ { id: "ink", runtime: "Ink / React TUI", startup: "240 ms", memory: "148 MB", binary: "160 MB", notes: "Virtual DOM overhead" },
133
+ { id: "electron", runtime: "Electron Sidecar", startup: "1450 ms", memory: "380 MB", binary: "210 MB", notes: "Heavy desktop shell" },
134
+ ],
135
+ });
136
+ store.present({
137
+ id: "demo-chart",
138
+ kind: "chart",
139
+ title: "Frame Timing",
140
+ unit: "ms",
141
+ caption: "Render + cell-diff latency per frame (braille dots)",
142
+ origin: { mux: "standalone", label: "demo-agent" },
143
+ focus: false,
144
+ series: [
145
+ { name: "p50", color: "#5fd787", values: [0.18, 0.16, 0.15, 0.17, 0.14, 0.13, 0.14, 0.13, 0.12, 0.13, 0.13, 0.12] },
146
+ { name: "p99", color: "#7aa2ff", values: [0.42, 0.39, 0.45, 0.36, 0.34, 0.31, 0.35, 0.29, 0.28, 0.30, 0.27, 0.26] },
147
+ ],
148
+ });
149
+ store.present({
150
+ id: "demo-ask",
151
+ kind: "ask",
152
+ title: "Deploy Target",
153
+ mode: "select",
154
+ prompt: "Which distribution channel should we publish first?",
155
+ context: "Agents can pre-highlight an option, but **`allow` blocks agents from submitting**. Only your keypress or click resolves this gate.",
156
+ options: [
157
+ { value: "npm", label: "npm + npx bypane (fastest JS onboarding)" },
158
+ { value: "brew", label: "Homebrew tap + prebuilt scriptc binaries (~2 ms)" },
159
+ { value: "both", label: "Both npm and GitHub Release native binaries" },
160
+ ],
161
+ defaultValue: "both",
162
+ origin: { mux: "standalone", label: "demo-agent" },
163
+ focus: false,
164
+ });
165
+ store.focus("demo-plan");
166
+ }
package/dist/ipc.js ADDED
@@ -0,0 +1,201 @@
1
+ import { chmodSync, existsSync, mkdirSync, unlinkSync } from "node:fs";
2
+ import { createConnection, createServer } from "node:net";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { loadConfig } from "./config.js";
6
+ import { autoDockPane, canAutoDock } from "./multiplexer.js";
7
+ export function socketDir() {
8
+ const uid = process.getuid?.() ?? 0;
9
+ const dir = join(tmpdir(), `bypane-${uid}`);
10
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
11
+ try {
12
+ chmodSync(dir, 0o700);
13
+ }
14
+ catch {
15
+ // Ignore on platforms that disallow chmod.
16
+ }
17
+ return dir;
18
+ }
19
+ export function socketPathFor(session) {
20
+ const safe = session.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 72);
21
+ return join(socketDir(), `${safe}.sock`);
22
+ }
23
+ function createLineParser(onLine) {
24
+ const decoder = new TextDecoder();
25
+ let buf = "";
26
+ return (chunk) => {
27
+ buf += decoder.decode(chunk, { stream: true });
28
+ let nl = buf.indexOf("\n");
29
+ while (nl >= 0) {
30
+ const line = buf.slice(0, nl).trim();
31
+ buf = buf.slice(nl + 1);
32
+ if (line)
33
+ onLine(line);
34
+ nl = buf.indexOf("\n");
35
+ }
36
+ };
37
+ }
38
+ export function startIpcServer(session, handler) {
39
+ const path = socketPathFor(session);
40
+ try {
41
+ if (existsSync(path))
42
+ unlinkSync(path);
43
+ }
44
+ catch {
45
+ // Ignore stale unlink races.
46
+ }
47
+ const server = createServer((socket) => {
48
+ socket.on("data", createLineParser((line) => {
49
+ let parsed;
50
+ try {
51
+ parsed = JSON.parse(line);
52
+ }
53
+ catch {
54
+ const errRes = { id: "", ok: false, error: "Invalid JSON request" };
55
+ socket.write(`${JSON.stringify(errRes)}\n`);
56
+ return;
57
+ }
58
+ Promise.resolve(handler(parsed))
59
+ .then((res) => {
60
+ if (!socket.destroyed) {
61
+ socket.write(`${JSON.stringify(res)}\n`);
62
+ }
63
+ })
64
+ .catch((err) => {
65
+ if (!socket.destroyed) {
66
+ const errRes = {
67
+ id: parsed.id ?? "",
68
+ ok: false,
69
+ error: err.message,
70
+ };
71
+ socket.write(`${JSON.stringify(errRes)}\n`);
72
+ }
73
+ });
74
+ }));
75
+ socket.on("error", () => {
76
+ // Client disconnected mid-request; ignore cleanly.
77
+ });
78
+ });
79
+ server.listen(path, () => {
80
+ try {
81
+ chmodSync(path, 0o600);
82
+ }
83
+ catch {
84
+ // Ignore chmod failure.
85
+ }
86
+ });
87
+ let closed = false;
88
+ const close = () => {
89
+ if (closed)
90
+ return;
91
+ closed = true;
92
+ try {
93
+ server.close();
94
+ }
95
+ catch {
96
+ // Ignore.
97
+ }
98
+ try {
99
+ if (existsSync(path))
100
+ unlinkSync(path);
101
+ }
102
+ catch {
103
+ // Ignore.
104
+ }
105
+ };
106
+ process.once("exit", close);
107
+ return { path, close };
108
+ }
109
+ function sendOnce(path, req, timeoutMs) {
110
+ return new Promise((resolvePromise, rejectPromise) => {
111
+ const socket = createConnection(path);
112
+ let settled = false;
113
+ const timer = timeoutMs > 0
114
+ ? setTimeout(() => {
115
+ if (!settled) {
116
+ settled = true;
117
+ socket.destroy();
118
+ rejectPromise(new Error(`bypane request timed out after ${timeoutMs}ms`));
119
+ }
120
+ }, timeoutMs)
121
+ : null;
122
+ const finish = (fn) => {
123
+ if (settled)
124
+ return;
125
+ settled = true;
126
+ if (timer)
127
+ clearTimeout(timer);
128
+ fn();
129
+ };
130
+ socket.on("data", createLineParser((line) => {
131
+ finish(() => {
132
+ socket.end();
133
+ try {
134
+ resolvePromise(JSON.parse(line));
135
+ }
136
+ catch {
137
+ rejectPromise(new Error("Malformed JSON response from bypane"));
138
+ }
139
+ });
140
+ }));
141
+ socket.on("error", (err) => {
142
+ finish(() => rejectPromise(err));
143
+ });
144
+ socket.on("close", () => {
145
+ finish(() => rejectPromise(new Error("bypane closed connection before responding")));
146
+ });
147
+ socket.write(`${JSON.stringify(req)}\n`);
148
+ });
149
+ }
150
+ function sleep(ms) {
151
+ return new Promise((r) => setTimeout(r, ms));
152
+ }
153
+ /**
154
+ * Sends a request to the running `bypane` instance for `session`.
155
+ * If no instance is running and `autoDock` is enabled inside Rex/tmux, automatically splits
156
+ * a companion pane, waits briefly for its socket, and retries.
157
+ */
158
+ export async function sendIpc(session, req, options = {}) {
159
+ const path = socketPathFor(session);
160
+ const timeoutMs = options.timeoutMs ?? (req.op === "ask_wait" ? 0 : 5000);
161
+ try {
162
+ return await sendOnce(path, req, timeoutMs);
163
+ }
164
+ catch (err) {
165
+ const code = err.code;
166
+ const notRunning = code === "ENOENT" || code === "ECONNREFUSED";
167
+ if (!notRunning)
168
+ throw err;
169
+ if (code === "ECONNREFUSED") {
170
+ try {
171
+ unlinkSync(path);
172
+ }
173
+ catch {
174
+ // Stale socket cleanup.
175
+ }
176
+ }
177
+ const cfg = loadConfig();
178
+ if (options.autoDock !== false && cfg.autoDock && canAutoDock()) {
179
+ const docked = autoDockPane(session);
180
+ if (!docked.ok) {
181
+ throw new Error(`bypane is not running for session "${session}" and auto-dock failed (${docked.error}). Start \`bypane --session ${session}\` in another pane.`);
182
+ }
183
+ const deadline = Date.now() + 4000;
184
+ while (Date.now() < deadline) {
185
+ await sleep(60);
186
+ if (!existsSync(path))
187
+ continue;
188
+ try {
189
+ return await sendOnce(path, req, timeoutMs);
190
+ }
191
+ catch (retryErr) {
192
+ const rc = retryErr.code;
193
+ if (rc !== "ENOENT" && rc !== "ECONNREFUSED")
194
+ throw retryErr;
195
+ }
196
+ }
197
+ throw new Error(`Auto-docked bypane via ${docked.via}, but socket did not become ready within 4s.`);
198
+ }
199
+ throw new Error(`bypane is not running for session "${session}". Run \`bypane\` in a split pane first.`);
200
+ }
201
+ }