@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/mcp.js ADDED
@@ -0,0 +1,307 @@
1
+ import { sendIpc } from "./ipc.js";
2
+ import { detectCallerOrigin } from "./multiplexer.js";
3
+ const PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
4
+ const TOOLS = [
5
+ {
6
+ name: "bypane_present",
7
+ description: "Show or update a visual surface in the user's companion bypane terminal pane (auto-opens a split pane in Rex or tmux if not running). Supports markdown (with interactive checkboxes), file (code/text/binary QuickLook), image (inline PNG), table, chart (braille), and log.",
8
+ inputSchema: {
9
+ type: "object",
10
+ required: ["kind"],
11
+ properties: {
12
+ id: { type: "string", description: "Stable surface ID to update an existing tab in place." },
13
+ kind: { type: "string", enum: ["markdown", "file", "image", "table", "chart", "log"] },
14
+ title: { type: "string", description: "Short tab title." },
15
+ focus: { type: "boolean", description: "Whether to focus this tab (default true for new tabs)." },
16
+ content: { type: "string", description: "Markdown or inline text content (for kind=markdown or file)." },
17
+ path: { type: "string", description: "File or image path (for kind=file or image)." },
18
+ caption: { type: "string", description: "Optional caption (for kind=image or chart)." },
19
+ highlightStart: { type: "number", description: "1-based start line to highlight (for kind=file)." },
20
+ highlightEnd: { type: "number", description: "1-based end line to highlight (for kind=file)." },
21
+ columns: {
22
+ type: "array",
23
+ description: "Table columns as strings or { key, label, width?, align? } (for kind=table).",
24
+ items: {},
25
+ },
26
+ rows: {
27
+ type: "array",
28
+ description: "Table rows as string arrays or objects keyed by column key (for kind=table).",
29
+ items: {},
30
+ },
31
+ series: {
32
+ type: "array",
33
+ description: "Chart series [{ name, values: number[], color? }] (for kind=chart).",
34
+ items: {
35
+ type: "object",
36
+ required: ["name", "values"],
37
+ properties: {
38
+ name: { type: "string" },
39
+ values: { type: "array", items: { type: "number" } },
40
+ color: { type: "string" },
41
+ },
42
+ },
43
+ },
44
+ unit: { type: "string", description: "Unit suffix for chart values (e.g. 'ms', '%')." },
45
+ min: { type: "number" },
46
+ max: { type: "number" },
47
+ lines: { type: "array", items: { type: "string" }, description: "Log lines (for kind=log)." },
48
+ append: { type: "boolean", description: "Append lines instead of replacing (for kind=log)." },
49
+ },
50
+ },
51
+ annotations: { readOnlyHint: false, destructiveHint: false },
52
+ },
53
+ {
54
+ name: "bypane_append_log",
55
+ description: "Append one or more lines to an existing bypane log surface.",
56
+ inputSchema: {
57
+ type: "object",
58
+ required: ["surfaceId", "lines"],
59
+ properties: {
60
+ surfaceId: { type: "string" },
61
+ lines: { type: "array", items: { type: "string" } },
62
+ },
63
+ },
64
+ annotations: { readOnlyHint: false, destructiveHint: false },
65
+ },
66
+ {
67
+ name: "bypane_ask",
68
+ description: "Present an interactive human-only decision prompt (select, multiselect, text, or confirm) in bypane. By default waits until the user submits or cancels; agents cannot submit on the user's behalf.",
69
+ inputSchema: {
70
+ type: "object",
71
+ required: ["mode", "prompt"],
72
+ properties: {
73
+ id: { type: "string" },
74
+ title: { type: "string" },
75
+ mode: { type: "string", enum: ["select", "multiselect", "text", "confirm"] },
76
+ prompt: { type: "string", description: "Clear question for the user." },
77
+ context: { type: "string", description: "Optional Markdown context shown above the prompt." },
78
+ options: {
79
+ type: "array",
80
+ description: "Choices as strings or { value, label } (for select/multiselect).",
81
+ items: {},
82
+ },
83
+ defaultValue: { description: "Default option value (string) or values (string[])." },
84
+ placeholder: { type: "string" },
85
+ confirmLabel: { type: "string" },
86
+ cancelLabel: { type: "string" },
87
+ wait: { type: "boolean", description: "Block until human submits (default true)." },
88
+ timeoutMs: { type: "number", description: "Optional wait timeout in milliseconds." },
89
+ },
90
+ },
91
+ annotations: { readOnlyHint: false, destructiveHint: false },
92
+ },
93
+ {
94
+ name: "bypane_list",
95
+ description: "List all open surfaces/tabs in the user's bypane workspace.",
96
+ inputSchema: { type: "object", properties: {} },
97
+ annotations: { readOnlyHint: true, destructiveHint: false },
98
+ },
99
+ {
100
+ name: "bypane_state",
101
+ description: "Read the current interactive state of a surface (or the entire active workspace): checked Markdown tasks, human-added notes, selected table rows, active filters, and ask answers.",
102
+ inputSchema: {
103
+ type: "object",
104
+ properties: {
105
+ surfaceId: { type: "string", description: "Optional surface ID; omits to return workspace + active surface." },
106
+ },
107
+ },
108
+ annotations: { readOnlyHint: true, destructiveHint: false },
109
+ },
110
+ {
111
+ name: "bypane_close",
112
+ description: "Close a surface tab by ID (or the currently active tab).",
113
+ inputSchema: {
114
+ type: "object",
115
+ properties: {
116
+ surfaceId: { type: "string" },
117
+ },
118
+ },
119
+ annotations: { readOnlyHint: false, destructiveHint: true },
120
+ },
121
+ {
122
+ name: "bypane_snapshot",
123
+ description: "Read the live rendered TUI screen and interactive component tree via tui/agent.",
124
+ inputSchema: { type: "object", properties: {} },
125
+ annotations: { readOnlyHint: true, destructiveHint: false },
126
+ },
127
+ {
128
+ name: "bypane_act",
129
+ description: "Perform non-destructive UI actions on visible bypane components (e.g. open tab, scroll, filter, pre-highlight). Human-gated ask submissions and notes are strictly blocked.",
130
+ inputSchema: {
131
+ type: "object",
132
+ required: ["steps"],
133
+ properties: {
134
+ steps: {
135
+ type: "array",
136
+ items: {
137
+ type: "object",
138
+ required: ["ref", "action"],
139
+ properties: {
140
+ ref: { type: "string" },
141
+ action: { type: "string" },
142
+ args: { type: "array", items: { type: "string" } },
143
+ },
144
+ },
145
+ },
146
+ },
147
+ },
148
+ annotations: { readOnlyHint: false, destructiveHint: false },
149
+ },
150
+ ];
151
+ function isObj(v) {
152
+ return v !== null && typeof v === "object" && !Array.isArray(v);
153
+ }
154
+ export async function handleMcpToolCall(session, toolName, rawArgs, autoDock = true) {
155
+ const args = isObj(rawArgs) ? rawArgs : {};
156
+ const reqId = `mcp-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
157
+ const origin = detectCallerOrigin("mcp");
158
+ let ipcReq;
159
+ if (toolName === "bypane_present") {
160
+ const payload = { ...args, origin };
161
+ ipcReq = { id: reqId, op: "present", payload };
162
+ }
163
+ else if (toolName === "bypane_append_log") {
164
+ const surfaceId = String(args.surfaceId ?? "");
165
+ const lines = Array.isArray(args.lines) ? args.lines.map((l) => String(l)) : [];
166
+ ipcReq = { id: reqId, op: "append_log", surfaceId, lines };
167
+ }
168
+ else if (toolName === "bypane_ask") {
169
+ const payload = {
170
+ id: typeof args.id === "string" ? args.id : undefined,
171
+ kind: "ask",
172
+ title: typeof args.title === "string" ? args.title : "Decision",
173
+ mode: args.mode || "select",
174
+ prompt: String(args.prompt ?? ""),
175
+ context: typeof args.context === "string" ? args.context : undefined,
176
+ options: Array.isArray(args.options) ? args.options : undefined,
177
+ defaultValue: args.defaultValue,
178
+ placeholder: typeof args.placeholder === "string" ? args.placeholder : undefined,
179
+ confirmLabel: typeof args.confirmLabel === "string" ? args.confirmLabel : undefined,
180
+ cancelLabel: typeof args.cancelLabel === "string" ? args.cancelLabel : undefined,
181
+ origin,
182
+ focus: true,
183
+ };
184
+ const wait = args.wait !== false;
185
+ if (wait) {
186
+ ipcReq = {
187
+ id: reqId,
188
+ op: "ask_wait",
189
+ payload,
190
+ timeoutMs: typeof args.timeoutMs === "number" ? args.timeoutMs : undefined,
191
+ };
192
+ }
193
+ else {
194
+ ipcReq = { id: reqId, op: "present", payload };
195
+ }
196
+ }
197
+ else if (toolName === "bypane_list") {
198
+ ipcReq = { id: reqId, op: "list" };
199
+ }
200
+ else if (toolName === "bypane_state") {
201
+ ipcReq = {
202
+ id: reqId,
203
+ op: "get_state",
204
+ surfaceId: typeof args.surfaceId === "string" ? args.surfaceId : undefined,
205
+ };
206
+ }
207
+ else if (toolName === "bypane_close") {
208
+ ipcReq = {
209
+ id: reqId,
210
+ op: "close",
211
+ surfaceId: typeof args.surfaceId === "string" ? args.surfaceId : undefined,
212
+ };
213
+ }
214
+ else if (toolName === "bypane_snapshot") {
215
+ ipcReq = { id: reqId, op: "snapshot" };
216
+ }
217
+ else if (toolName === "bypane_act") {
218
+ const steps = Array.isArray(args.steps)
219
+ ? args.steps.map((s) => {
220
+ const obj = isObj(s) ? s : {};
221
+ return {
222
+ ref: String(obj.ref ?? ""),
223
+ action: String(obj.action ?? ""),
224
+ args: Array.isArray(obj.args) ? obj.args.map((a) => String(a)) : [],
225
+ };
226
+ })
227
+ : [];
228
+ ipcReq = { id: reqId, op: "act", steps };
229
+ }
230
+ else {
231
+ return { text: `Unknown tool "${toolName}"`, isError: true };
232
+ }
233
+ try {
234
+ const res = await sendIpc(session, ipcReq, {
235
+ autoDock: autoDock && (toolName === "bypane_present" || toolName === "bypane_ask"),
236
+ });
237
+ if (!res.ok) {
238
+ return { text: res.error || "bypane error", isError: true };
239
+ }
240
+ return { text: JSON.stringify(res.data ?? { ok: true }, null, 2), isError: false };
241
+ }
242
+ catch (err) {
243
+ return { text: err.message, isError: true };
244
+ }
245
+ }
246
+ export function serveMcpStdio(session) {
247
+ const send = (msg) => process.stdout.write(`${msg}\n`);
248
+ const reply = (id, result) => send(JSON.stringify({ jsonrpc: "2.0", id, result }));
249
+ const fail = (id, code, message) => send(JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } }));
250
+ const decoder = new TextDecoder();
251
+ let buf = "";
252
+ process.stdin.on("data", (chunk) => {
253
+ buf += decoder.decode(chunk, { stream: true });
254
+ let nl = buf.indexOf("\n");
255
+ while (nl >= 0) {
256
+ const line = buf.slice(0, nl).trim();
257
+ buf = buf.slice(nl + 1);
258
+ if (line)
259
+ void onMessage(line);
260
+ nl = buf.indexOf("\n");
261
+ }
262
+ });
263
+ async function onMessage(line) {
264
+ let parsed;
265
+ try {
266
+ parsed = JSON.parse(line);
267
+ }
268
+ catch {
269
+ fail(null, -32700, "Invalid JSON");
270
+ return;
271
+ }
272
+ if (!isObj(parsed) || typeof parsed.method !== "string")
273
+ return;
274
+ const method = parsed.method;
275
+ const id = parsed.id ?? null;
276
+ const params = isObj(parsed.params) ? parsed.params : {};
277
+ if (id === null)
278
+ return;
279
+ if (method === "initialize") {
280
+ const asked = typeof params.protocolVersion === "string" ? params.protocolVersion : "";
281
+ const version = PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0];
282
+ reply(id, {
283
+ protocolVersion: version,
284
+ capabilities: { tools: {} },
285
+ serverInfo: { name: "bypane", title: "bypane", version: "0.1.0" },
286
+ instructions: "bypane is a visual companion terminal pane beside the user's chat. Use bypane_present to show Markdown plans/checklists, files/images, tables, charts, or logs, and bypane_ask for interactive human-only decisions. Use bypane_state to read back checked items and notes.",
287
+ });
288
+ }
289
+ else if (method === "ping") {
290
+ reply(id, {});
291
+ }
292
+ else if (method === "tools/list") {
293
+ reply(id, { tools: TOOLS });
294
+ }
295
+ else if (method === "tools/call") {
296
+ const toolName = typeof params.name === "string" ? params.name : "";
297
+ const result = await handleMcpToolCall(session, toolName, params.arguments);
298
+ reply(id, {
299
+ content: [{ type: "text", text: result.text }],
300
+ isError: result.isError,
301
+ });
302
+ }
303
+ else {
304
+ fail(id, -32601, `Unknown method "${method}"`);
305
+ }
306
+ }
307
+ }
@@ -0,0 +1,279 @@
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
+ if (mux === "rex" && paneId) {
221
+ try {
222
+ execFileSync("rex", ["send", "-b", paneId, text], {
223
+ encoding: "utf8",
224
+ timeout: 3000,
225
+ stdio: ["ignore", "pipe", "pipe"],
226
+ });
227
+ return { ok: true, via: `rex send (${paneId.slice(0, 14)}…)` };
228
+ }
229
+ catch (err) {
230
+ return { ok: false, via: "rex send", error: err.message };
231
+ }
232
+ }
233
+ if (mux === "tmux" && paneId) {
234
+ try {
235
+ execFileSync("tmux", ["send-keys", "-t", paneId, "-l", text], {
236
+ encoding: "utf8",
237
+ timeout: 3000,
238
+ stdio: ["ignore", "pipe", "pipe"],
239
+ });
240
+ return { ok: true, via: `tmux send-keys (${paneId})` };
241
+ }
242
+ catch (err) {
243
+ return { ok: false, via: "tmux send-keys", error: err.message };
244
+ }
245
+ }
246
+ return { ok: false, via: "clipboard", error: "No originating mux pane" };
247
+ }
248
+ /**
249
+ * Jumps focus back to the originating Rex/tmux pane.
250
+ */
251
+ export function focusOriginPane(origin) {
252
+ if (origin?.mux === "rex" && origin.paneId) {
253
+ try {
254
+ execFileSync("rex", ["focus", origin.paneId], {
255
+ encoding: "utf8",
256
+ timeout: 3000,
257
+ stdio: ["ignore", "pipe", "pipe"],
258
+ });
259
+ return { ok: true, via: "rex focus" };
260
+ }
261
+ catch (err) {
262
+ return { ok: false, via: "rex focus", error: err.message };
263
+ }
264
+ }
265
+ if (origin?.mux === "tmux" && origin.paneId) {
266
+ try {
267
+ execFileSync("tmux", ["select-pane", "-t", origin.paneId], {
268
+ encoding: "utf8",
269
+ timeout: 3000,
270
+ stdio: ["ignore", "pipe", "pipe"],
271
+ });
272
+ return { ok: true, via: "tmux select-pane" };
273
+ }
274
+ catch (err) {
275
+ return { ok: false, via: "tmux select-pane", error: err.message };
276
+ }
277
+ }
278
+ return { ok: false, via: "none", error: "No originating pane recorded" };
279
+ }