@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,281 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { fileURLToPath } from "node:url";
4
+ import { loadConfig } from "./config.js";
5
+ let cachedRex;
6
+ export function detectRexIdentity() {
7
+ if (cachedRex !== undefined)
8
+ return cachedRex;
9
+ if (!process.env.REX_BLOCK && !process.env.REX_SERVER) {
10
+ cachedRex = null;
11
+ return null;
12
+ }
13
+ try {
14
+ const out = execFileSync("rex", ["whoami", "--json"], {
15
+ encoding: "utf8",
16
+ timeout: 1500,
17
+ stdio: ["ignore", "pipe", "ignore"],
18
+ });
19
+ const parsed = JSON.parse(out);
20
+ cachedRex = {
21
+ sessionId: parsed.session_id,
22
+ windowId: parsed.window_id,
23
+ blockId: parsed.block_id ?? process.env.REX_BLOCK,
24
+ };
25
+ return cachedRex;
26
+ }
27
+ catch {
28
+ cachedRex = process.env.REX_BLOCK ? { blockId: process.env.REX_BLOCK } : null;
29
+ return cachedRex;
30
+ }
31
+ }
32
+ export function detectTmuxWindow() {
33
+ if (!process.env.TMUX)
34
+ return null;
35
+ try {
36
+ const out = execFileSync("tmux", ["display-message", "-p", "#{session_id}:#{window_id}|#{pane_id}"], {
37
+ encoding: "utf8",
38
+ timeout: 1500,
39
+ stdio: ["ignore", "pipe", "ignore"],
40
+ }).trim();
41
+ const [win, pane] = out.split("|");
42
+ if (win) {
43
+ return { windowId: win, paneId: pane || process.env.TMUX_PANE || "" };
44
+ }
45
+ }
46
+ catch {
47
+ // Fallback to TMUX_PANE below.
48
+ }
49
+ if (process.env.TMUX_PANE) {
50
+ return { windowId: process.env.TMUX_PANE, paneId: process.env.TMUX_PANE };
51
+ }
52
+ return null;
53
+ }
54
+ function sanitizeKey(raw) {
55
+ return raw.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 72);
56
+ }
57
+ /**
58
+ * Resolves the workspace session key in priority order:
59
+ * 1. explicit `--session` or `BYPANE_SESSION`
60
+ * 2. current Rex window (`rex whoami --json` -> `window_id`)
61
+ * 3. current tmux window (`session_id:window_id`)
62
+ * 4. stable short hash of `$PWD`
63
+ */
64
+ export function resolveSessionKey(explicit) {
65
+ const chosen = explicit || process.env.BYPANE_SESSION;
66
+ if (chosen)
67
+ return sanitizeKey(chosen);
68
+ const rex = detectRexIdentity();
69
+ if (rex?.windowId)
70
+ return `rex-${sanitizeKey(rex.windowId)}`;
71
+ if (rex?.blockId)
72
+ return `rex-${sanitizeKey(rex.blockId)}`;
73
+ const tmux = detectTmuxWindow();
74
+ if (tmux?.windowId)
75
+ return `tmux-${sanitizeKey(tmux.windowId)}`;
76
+ const cwdHash = createHash("sha256").update(process.cwd()).digest("hex").slice(0, 12);
77
+ return `cwd-${cwdHash}`;
78
+ }
79
+ export function detectCallerOrigin(label) {
80
+ const rex = detectRexIdentity();
81
+ if (rex?.blockId) {
82
+ return {
83
+ mux: "rex",
84
+ paneId: rex.blockId,
85
+ label,
86
+ cwd: process.cwd(),
87
+ };
88
+ }
89
+ const tmux = detectTmuxWindow();
90
+ if (tmux?.paneId) {
91
+ return {
92
+ mux: "tmux",
93
+ paneId: tmux.paneId,
94
+ label,
95
+ cwd: process.cwd(),
96
+ };
97
+ }
98
+ return {
99
+ mux: "standalone",
100
+ label,
101
+ cwd: process.cwd(),
102
+ };
103
+ }
104
+ /**
105
+ * Resolves the argv needed to spawn another instance of this same `bypane` program,
106
+ * working both under `node src/cli.ts` and as a `scriptc`-compiled native binary.
107
+ */
108
+ function selfLaunchArgs(session) {
109
+ const selfUrl = import.meta.url;
110
+ const isTs = selfUrl.endsWith(".ts");
111
+ const isJs = selfUrl.endsWith(".js") || selfUrl.endsWith(".mjs");
112
+ if (isTs || isJs) {
113
+ const cliPath = fileURLToPath(new URL(isTs ? "./cli.ts" : "./cli.js", selfUrl));
114
+ return { cmd: process.execPath, args: [cliPath, "--session", session] };
115
+ }
116
+ return { cmd: process.execPath, args: ["--session", session] };
117
+ }
118
+ export function canAutoDock() {
119
+ return Boolean(process.env.REX_BLOCK || process.env.REX_SERVER || process.env.TMUX);
120
+ }
121
+ /**
122
+ * Auto-splits a companion pane in Rex or tmux without stealing focus from the agent pane.
123
+ */
124
+ export function autoDockPane(session) {
125
+ const cfg = loadConfig();
126
+ const launch = selfLaunchArgs(session);
127
+ if (process.env.REX_BLOCK || process.env.REX_SERVER) {
128
+ try {
129
+ const rexArgs = [
130
+ "split",
131
+ `--split=${cfg.splitDirection}`,
132
+ `--ratio=${cfg.splitRatio}`,
133
+ "--focus=false",
134
+ "--label=bypane",
135
+ "--shell=none",
136
+ ];
137
+ if (process.env.REX_BLOCK) {
138
+ rexArgs.push("-b", process.env.REX_BLOCK);
139
+ }
140
+ rexArgs.push("--", launch.cmd, ...launch.args);
141
+ execFileSync("rex", rexArgs, {
142
+ encoding: "utf8",
143
+ timeout: 4000,
144
+ stdio: ["ignore", "pipe", "pipe"],
145
+ });
146
+ return { ok: true, via: "rex" };
147
+ }
148
+ catch (err) {
149
+ return { ok: false, error: `rex split failed: ${err.message}` };
150
+ }
151
+ }
152
+ if (process.env.TMUX) {
153
+ try {
154
+ const dirFlag = cfg.splitDirection === "below" || cfg.splitDirection === "above" ? "-v" : "-h";
155
+ const beforeFlag = cfg.splitDirection === "left" || cfg.splitDirection === "above" ? ["-b"] : [];
156
+ const cmdArgs = [
157
+ "split-window",
158
+ dirFlag,
159
+ ...beforeFlag,
160
+ "-d",
161
+ "-p",
162
+ String(cfg.splitRatio),
163
+ launch.cmd,
164
+ ...launch.args,
165
+ ];
166
+ execFileSync("tmux", cmdArgs, {
167
+ encoding: "utf8",
168
+ timeout: 4000,
169
+ stdio: ["ignore", "pipe", "pipe"],
170
+ });
171
+ return { ok: true, via: "tmux" };
172
+ }
173
+ catch (err) {
174
+ return { ok: false, error: `tmux split-window failed: ${err.message}` };
175
+ }
176
+ }
177
+ return { ok: false, error: "Not inside Rex or tmux; start `bypane` in another split." };
178
+ }
179
+ /**
180
+ * Opens a file or URL on the user's machine (`rex open` on remote Rex hosts, `open`/`xdg-open` locally).
181
+ */
182
+ export function openExternally(target) {
183
+ if (process.env.REX_BLOCK || process.env.REX_SERVER) {
184
+ try {
185
+ const child = spawn("rex", ["open", target], {
186
+ detached: true,
187
+ stdio: "ignore",
188
+ });
189
+ child.unref();
190
+ return { ok: true, via: "rex open" };
191
+ }
192
+ catch (err) {
193
+ return { ok: false, via: "rex open", error: err.message };
194
+ }
195
+ }
196
+ const opener = process.platform === "darwin"
197
+ ? "open"
198
+ : process.platform === "win32"
199
+ ? "cmd"
200
+ : "xdg-open";
201
+ const args = process.platform === "win32" ? ["/c", "start", "", target] : [target];
202
+ try {
203
+ const child = spawn(opener, args, {
204
+ detached: true,
205
+ stdio: "ignore",
206
+ });
207
+ child.unref();
208
+ return { ok: true, via: opener };
209
+ }
210
+ catch (err) {
211
+ return { ok: false, via: opener, error: err.message };
212
+ }
213
+ }
214
+ /**
215
+ * Sends feedback text back to the originating pane (without pressing Enter so the user stays in control).
216
+ */
217
+ export function sendToOriginPane(origin, text) {
218
+ const mux = origin?.mux;
219
+ const paneId = origin?.paneId;
220
+ // End with a blank line so consecutive push-backs never glue onto the previous line in chat composers.
221
+ const payload = text.endsWith("\n") ? text : `${text}\n\n`;
222
+ if (mux === "rex" && paneId) {
223
+ try {
224
+ execFileSync("rex", ["send", "-b", paneId, payload], {
225
+ encoding: "utf8",
226
+ timeout: 3000,
227
+ stdio: ["ignore", "pipe", "pipe"],
228
+ });
229
+ return { ok: true, via: `rex send (${paneId.slice(0, 14)}…)` };
230
+ }
231
+ catch (err) {
232
+ return { ok: false, via: "rex send", error: err.message };
233
+ }
234
+ }
235
+ if (mux === "tmux" && paneId) {
236
+ try {
237
+ execFileSync("tmux", ["send-keys", "-t", paneId, "-l", payload], {
238
+ encoding: "utf8",
239
+ timeout: 3000,
240
+ stdio: ["ignore", "pipe", "pipe"],
241
+ });
242
+ return { ok: true, via: `tmux send-keys (${paneId})` };
243
+ }
244
+ catch (err) {
245
+ return { ok: false, via: "tmux send-keys", error: err.message };
246
+ }
247
+ }
248
+ return { ok: false, via: "clipboard", error: "No originating mux pane" };
249
+ }
250
+ /**
251
+ * Jumps focus back to the originating Rex/tmux pane.
252
+ */
253
+ export function focusOriginPane(origin) {
254
+ if (origin?.mux === "rex" && origin.paneId) {
255
+ try {
256
+ execFileSync("rex", ["focus", origin.paneId], {
257
+ encoding: "utf8",
258
+ timeout: 3000,
259
+ stdio: ["ignore", "pipe", "pipe"],
260
+ });
261
+ return { ok: true, via: "rex focus" };
262
+ }
263
+ catch (err) {
264
+ return { ok: false, via: "rex focus", error: err.message };
265
+ }
266
+ }
267
+ if (origin?.mux === "tmux" && origin.paneId) {
268
+ try {
269
+ execFileSync("tmux", ["select-pane", "-t", origin.paneId], {
270
+ encoding: "utf8",
271
+ timeout: 3000,
272
+ stdio: ["ignore", "pipe", "pipe"],
273
+ });
274
+ return { ok: true, via: "tmux select-pane" };
275
+ }
276
+ catch (err) {
277
+ return { ok: false, via: "tmux select-pane", error: err.message };
278
+ }
279
+ }
280
+ return { ok: false, via: "none", error: "No originating pane recorded" };
281
+ }
package/dist/png.js ADDED
@@ -0,0 +1,208 @@
1
+ import { inflateSync } from "node:zlib";
2
+ const PNG_SIG = [137, 80, 78, 71, 13, 10, 26, 10];
3
+ function u32be(buf, offset) {
4
+ return (((buf[offset] << 24) |
5
+ (buf[offset + 1] << 16) |
6
+ (buf[offset + 2] << 8) |
7
+ buf[offset + 3]) >>>
8
+ 0);
9
+ }
10
+ function paeth(a, b, c) {
11
+ const p = a + b - c;
12
+ const pa = Math.abs(p - a);
13
+ const pb = Math.abs(p - b);
14
+ const pc = Math.abs(p - c);
15
+ if (pa <= pb && pa <= pc)
16
+ return a;
17
+ if (pb <= pc)
18
+ return b;
19
+ return c;
20
+ }
21
+ /**
22
+ * Minimal pure-TypeScript PNG decoder (8-bit RGB, RGBA, Grayscale, Grayscale+Alpha, Indexed PLTE).
23
+ * Returns RGBA bytes suitable for `tui`'s `createImage(rgba, width, height)`.
24
+ */
25
+ export function decodePng(data) {
26
+ if (data.length < 33) {
27
+ throw new Error("File is too small to be a PNG image");
28
+ }
29
+ for (let i = 0; i < 8; i++) {
30
+ if (data[i] !== PNG_SIG[i]) {
31
+ throw new Error("Not a PNG image (invalid signature)");
32
+ }
33
+ }
34
+ let width = 0;
35
+ let height = 0;
36
+ let bitDepth = 0;
37
+ let colorType = 0;
38
+ let interlace = 0;
39
+ let palette = null;
40
+ let trns = null;
41
+ const idatChunks = [];
42
+ let pos = 8;
43
+ while (pos + 12 <= data.length) {
44
+ const length = u32be(data, pos);
45
+ const type = String.fromCharCode(data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7]);
46
+ const start = pos + 8;
47
+ const end = start + length;
48
+ if (end + 4 > data.length) {
49
+ throw new Error("Truncated PNG chunk");
50
+ }
51
+ const chunk = data.subarray(start, end);
52
+ if (type === "IHDR") {
53
+ width = u32be(chunk, 0);
54
+ height = u32be(chunk, 4);
55
+ bitDepth = chunk[8];
56
+ colorType = chunk[9];
57
+ const compression = chunk[10];
58
+ const filterMethod = chunk[11];
59
+ interlace = chunk[12];
60
+ if (compression !== 0 || filterMethod !== 0) {
61
+ throw new Error("Unsupported PNG compression or filter method");
62
+ }
63
+ if (interlace !== 0) {
64
+ throw new Error("Interlaced PNGs are not supported yet (press 'o' to open externally)");
65
+ }
66
+ if (bitDepth !== 8 && bitDepth !== 16) {
67
+ throw new Error(`Unsupported PNG bit depth ${bitDepth} (press 'o' to open externally)`);
68
+ }
69
+ }
70
+ else if (type === "PLTE") {
71
+ palette = chunk;
72
+ }
73
+ else if (type === "tRNS") {
74
+ trns = chunk;
75
+ }
76
+ else if (type === "IDAT") {
77
+ idatChunks.push(chunk);
78
+ }
79
+ else if (type === "IEND") {
80
+ break;
81
+ }
82
+ pos = end + 4;
83
+ }
84
+ if (width <= 0 || height <= 0 || idatChunks.length === 0) {
85
+ throw new Error("Incomplete PNG image data");
86
+ }
87
+ let totalLen = 0;
88
+ for (const c of idatChunks)
89
+ totalLen += c.length;
90
+ const compressed = new Uint8Array(totalLen);
91
+ let offset = 0;
92
+ for (const c of idatChunks) {
93
+ compressed.set(c, offset);
94
+ offset += c.length;
95
+ }
96
+ const raw = inflateSync(compressed);
97
+ const channels = colorType === 0
98
+ ? 1
99
+ : colorType === 2
100
+ ? 3
101
+ : colorType === 3
102
+ ? 1
103
+ : colorType === 4
104
+ ? 2
105
+ : colorType === 6
106
+ ? 4
107
+ : 0;
108
+ if (channels === 0) {
109
+ throw new Error(`Unsupported PNG color type ${colorType}`);
110
+ }
111
+ const bytesPerSample = bitDepth === 16 ? 2 : 1;
112
+ const bpp = channels * bytesPerSample;
113
+ const stride = width * bpp;
114
+ if (raw.length < height * (stride + 1)) {
115
+ throw new Error("Decompressed PNG buffer is smaller than expected");
116
+ }
117
+ const scanlines = new Uint8Array(height * stride);
118
+ for (let y = 0; y < height; y++) {
119
+ const filter = raw[y * (stride + 1)];
120
+ const srcRow = y * (stride + 1) + 1;
121
+ const dstRow = y * stride;
122
+ for (let x = 0; x < stride; x++) {
123
+ const val = raw[srcRow + x];
124
+ const left = x >= bpp ? scanlines[dstRow + x - bpp] : 0;
125
+ const up = y > 0 ? scanlines[dstRow - stride + x] : 0;
126
+ const upLeft = y > 0 && x >= bpp ? scanlines[dstRow - stride + x - bpp] : 0;
127
+ let recon = val;
128
+ if (filter === 1)
129
+ recon = (val + left) & 0xff;
130
+ else if (filter === 2)
131
+ recon = (val + up) & 0xff;
132
+ else if (filter === 3)
133
+ recon = (val + ((left + up) >> 1)) & 0xff;
134
+ else if (filter === 4)
135
+ recon = (val + paeth(left, up, upLeft)) & 0xff;
136
+ else if (filter !== 0) {
137
+ throw new Error(`Unknown PNG filter type ${filter}`);
138
+ }
139
+ scanlines[dstRow + x] = recon;
140
+ }
141
+ }
142
+ // Downsample huge images gently (max 640px wide/tall) so terminal rendering stays instant & low-RAM.
143
+ const maxDim = 640;
144
+ const scale = Math.max(1, Math.ceil(Math.max(width, height) / maxDim));
145
+ const outW = Math.max(1, Math.floor(width / scale));
146
+ const outH = Math.max(1, Math.floor(height / scale));
147
+ const rgba = new Uint8Array(outW * outH * 4);
148
+ for (let oy = 0; oy < outH; oy++) {
149
+ const sy = Math.min(height - 1, oy * scale);
150
+ const rowOff = sy * stride;
151
+ for (let ox = 0; ox < outW; ox++) {
152
+ const sx = Math.min(width - 1, ox * scale);
153
+ const px = rowOff + sx * bpp;
154
+ const di = (oy * outW + ox) * 4;
155
+ if (colorType === 6) {
156
+ rgba[di] = scanlines[px];
157
+ rgba[di + 1] = scanlines[px + bytesPerSample];
158
+ rgba[di + 2] = scanlines[px + 2 * bytesPerSample];
159
+ rgba[di + 3] = scanlines[px + 3 * bytesPerSample];
160
+ }
161
+ else if (colorType === 2) {
162
+ rgba[di] = scanlines[px];
163
+ rgba[di + 1] = scanlines[px + bytesPerSample];
164
+ rgba[di + 2] = scanlines[px + 2 * bytesPerSample];
165
+ rgba[di + 3] = 255;
166
+ }
167
+ else if (colorType === 0) {
168
+ const g = scanlines[px];
169
+ rgba[di] = g;
170
+ rgba[di + 1] = g;
171
+ rgba[di + 2] = g;
172
+ rgba[di + 3] = 255;
173
+ }
174
+ else if (colorType === 4) {
175
+ const g = scanlines[px];
176
+ rgba[di] = g;
177
+ rgba[di + 1] = g;
178
+ rgba[di + 2] = g;
179
+ rgba[di + 3] = scanlines[px + bytesPerSample];
180
+ }
181
+ else if (colorType === 3) {
182
+ const idx = scanlines[px];
183
+ if (!palette || idx * 3 + 2 >= palette.length) {
184
+ rgba[di] = 0;
185
+ rgba[di + 1] = 0;
186
+ rgba[di + 2] = 0;
187
+ rgba[di + 3] = 255;
188
+ }
189
+ else {
190
+ rgba[di] = palette[idx * 3];
191
+ rgba[di + 1] = palette[idx * 3 + 1];
192
+ rgba[di + 2] = palette[idx * 3 + 2];
193
+ rgba[di + 3] = trns && idx < trns.length ? trns[idx] : 255;
194
+ }
195
+ }
196
+ }
197
+ }
198
+ return { width: outW, height: outH, rgba };
199
+ }
200
+ export function isPngBuffer(buf) {
201
+ if (buf.length < 8)
202
+ return false;
203
+ for (let i = 0; i < 8; i++) {
204
+ if (buf[i] !== PNG_SIG[i])
205
+ return false;
206
+ }
207
+ return true;
208
+ }