@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.
package/dist/cli.js ADDED
@@ -0,0 +1,810 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, realpathSync } from "node:fs";
3
+ import { basename, extname, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { runApp } from "tui";
6
+ import { createAgent } from "tui/agent";
7
+ import { loadDemoSurfaces } from "./demo.js";
8
+ import { sendIpc, socketPathFor, startIpcServer } from "./ipc.js";
9
+ import { serveMcpStdio } from "./mcp.js";
10
+ import { detectCallerOrigin, resolveSessionKey } from "./multiplexer.js";
11
+ import { runSetupWizard, runSkillSubcommand } from "./setup.js";
12
+ import { WorkspaceStore } from "./state.js";
13
+ import { bypaneTheme, createBypaneUi } from "./ui.js";
14
+ const HELP_TEXT = `bypane — 2 ms terminal companion pane for coding agents
15
+
16
+ Usage:
17
+ bypane [--session <id>] [--demo] Start the live TUI pane
18
+ bypane setup [--yes] Interactive setup wizard (skills, layout, MCP)
19
+ bypane skill <setup|show|status|remove> Manage the bypane agent skill
20
+ bypane mcp [--session <id>] Start stdio MCP server
21
+ bypane show <file[:start[-end]]> [flags] Show Markdown, code, image, or binary QuickLook
22
+ bypane md [text] [--title <t>] [--id <id>] Show Markdown (arg or stdin)
23
+ bypane table [file] [--title <t>] [--id <id>] Show JSON/CSV/TSV table (file or stdin)
24
+ bypane chart --series name:1,2,3 [flags] Show braille chart (flags or JSON stdin)
25
+ bypane log [--title <t>] [--id <id>] [--append] Stream lines from stdin into a log surface
26
+ bypane ask --prompt <q> [flags] Ask human a gated decision (blocks until submit)
27
+ bypane ui [spec.json] [--wait] [flags] Render a generative UI tree (sliders, timelines, charts…)
28
+ bypane app [file.ts] [--code <ts>] [flags] Run a custom tui-sdk app in an isolated companion worker
29
+ bypane list | state [id] | close [id] | demo Inspect or manage active workspace
30
+
31
+ Global flags:
32
+ --session, -s <name> Override workspace session key (default: Rex/tmux window or cwd hash)
33
+ --no-dock Do not auto-split a Rex/tmux pane when bypane isn't running
34
+ --help, -h Show this help
35
+ `;
36
+ function parseArgv(argv) {
37
+ const flags = {};
38
+ const rest = [];
39
+ const multiFlags = new Set(["option", "series"]);
40
+ const setFlag = (key, val) => {
41
+ if (multiFlags.has(key)) {
42
+ const prev = flags[key];
43
+ const list = Array.isArray(prev) ? prev : prev ? [String(prev)] : [];
44
+ list.push(String(val));
45
+ flags[key] = list;
46
+ }
47
+ else {
48
+ flags[key] = val;
49
+ }
50
+ };
51
+ for (let i = 0; i < argv.length; i++) {
52
+ const arg = argv[i];
53
+ if (arg === "--") {
54
+ rest.push(...argv.slice(i + 1));
55
+ break;
56
+ }
57
+ if (arg.startsWith("--")) {
58
+ const eq = arg.indexOf("=");
59
+ if (eq >= 0) {
60
+ setFlag(arg.slice(2, eq), arg.slice(eq + 1));
61
+ }
62
+ else {
63
+ const key = arg.slice(2);
64
+ const next = argv[i + 1];
65
+ const isBoolFlag = key === "demo" ||
66
+ key === "help" ||
67
+ key === "yes" ||
68
+ key === "force" ||
69
+ key === "append" ||
70
+ key === "wait" ||
71
+ key === "no-wait" ||
72
+ key === "no-dock" ||
73
+ key === "no-focus" ||
74
+ key === "no-install" ||
75
+ key === "raw";
76
+ if (!isBoolFlag && next !== undefined && !next.startsWith("-")) {
77
+ setFlag(key, next);
78
+ i++;
79
+ }
80
+ else {
81
+ setFlag(key, true);
82
+ }
83
+ }
84
+ }
85
+ else if (arg.startsWith("-") && arg.length === 2) {
86
+ const short = arg[1];
87
+ const map = {
88
+ s: "session",
89
+ t: "title",
90
+ h: "help",
91
+ y: "yes",
92
+ m: "mode",
93
+ p: "prompt",
94
+ o: "option",
95
+ u: "unit",
96
+ };
97
+ const key = map[short] ?? short;
98
+ const next = argv[i + 1];
99
+ if (key !== "help" && key !== "yes" && next !== undefined && !next.startsWith("-")) {
100
+ setFlag(key, next);
101
+ i++;
102
+ }
103
+ else {
104
+ setFlag(key, true);
105
+ }
106
+ }
107
+ else {
108
+ rest.push(arg);
109
+ }
110
+ }
111
+ const knownCommands = new Set([
112
+ "setup",
113
+ "skill",
114
+ "mcp",
115
+ "show",
116
+ "md",
117
+ "markdown",
118
+ "table",
119
+ "chart",
120
+ "log",
121
+ "ask",
122
+ "ui",
123
+ "app",
124
+ "list",
125
+ "state",
126
+ "close",
127
+ "snapshot",
128
+ "demo",
129
+ "help",
130
+ ]);
131
+ const first = rest[0];
132
+ if (first && knownCommands.has(first)) {
133
+ return { command: first, positionals: rest.slice(1), flags };
134
+ }
135
+ return { command: "tui", positionals: rest, flags };
136
+ }
137
+ function strFlag(flags, key) {
138
+ const v = flags[key];
139
+ return typeof v === "string" ? v : undefined;
140
+ }
141
+ function listFlag(flags, key) {
142
+ const v = flags[key];
143
+ if (Array.isArray(v))
144
+ return v;
145
+ if (typeof v === "string")
146
+ return [v];
147
+ return [];
148
+ }
149
+ async function readStdinAll() {
150
+ if (process.stdin.isTTY)
151
+ return "";
152
+ const chunks = [];
153
+ for await (const chunk of process.stdin) {
154
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
155
+ }
156
+ return Buffer.concat(chunks).toString("utf8");
157
+ }
158
+ function parseFileTarget(spec) {
159
+ const match = /^(.*):(\d+)(?:-(\d+))?$/.exec(spec);
160
+ if (!match)
161
+ return { path: spec };
162
+ const start = Number(match[2]);
163
+ const end = match[3] ? Number(match[3]) : start;
164
+ return { path: match[1], start, end };
165
+ }
166
+ function parseDelimited(raw, sep) {
167
+ const lines = raw
168
+ .split(/\r?\n/)
169
+ .map((l) => l.trimEnd())
170
+ .filter((l) => l.length > 0);
171
+ if (lines.length === 0)
172
+ return { columns: [], rows: [] };
173
+ const splitLine = (line) => {
174
+ if (sep === "\t")
175
+ return line.split("\t");
176
+ const out = [];
177
+ let cur = "";
178
+ let inQuotes = false;
179
+ for (let i = 0; i < line.length; i++) {
180
+ const ch = line[i];
181
+ if (ch === '"') {
182
+ if (inQuotes && line[i + 1] === '"') {
183
+ cur += '"';
184
+ i++;
185
+ }
186
+ else {
187
+ inQuotes = !inQuotes;
188
+ }
189
+ }
190
+ else if (ch === sep && !inQuotes) {
191
+ out.push(cur.trim());
192
+ cur = "";
193
+ }
194
+ else {
195
+ cur += ch;
196
+ }
197
+ }
198
+ out.push(cur.trim());
199
+ return out;
200
+ };
201
+ const header = splitLine(lines[0]);
202
+ const columns = header.map((h, i) => ({ key: h || `col${i}`, label: h || `Col ${i + 1}` }));
203
+ const rows = lines.slice(1).map(splitLine);
204
+ return { columns, rows };
205
+ }
206
+ function parseTableInput(raw) {
207
+ const trimmed = raw.trim();
208
+ if (!trimmed)
209
+ return { columns: [], rows: [] };
210
+ if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
211
+ try {
212
+ const parsed = JSON.parse(trimmed);
213
+ if (Array.isArray(parsed)) {
214
+ if (parsed.length === 0)
215
+ return { columns: [], rows: [] };
216
+ if (Array.isArray(parsed[0])) {
217
+ const header = parsed[0].map((v, i) => String(v ?? `col${i}`));
218
+ return {
219
+ columns: header.map((h) => ({ key: h, label: h })),
220
+ rows: parsed.slice(1).map((r) => (Array.isArray(r) ? r.map((v) => String(v ?? "")) : [String(r)])),
221
+ };
222
+ }
223
+ const keySet = new Set();
224
+ for (const item of parsed) {
225
+ if (item && typeof item === "object" && !Array.isArray(item)) {
226
+ for (const k of Object.keys(item))
227
+ keySet.add(k);
228
+ }
229
+ }
230
+ const columns = [...keySet].map((k) => ({ key: k, label: k }));
231
+ return { columns, rows: parsed };
232
+ }
233
+ if (parsed && typeof parsed === "object" && "columns" in parsed && "rows" in parsed) {
234
+ const obj = parsed;
235
+ return {
236
+ columns: obj.columns.map((c) => (typeof c === "string" ? { key: c, label: c } : c)),
237
+ rows: obj.rows,
238
+ };
239
+ }
240
+ }
241
+ catch {
242
+ // Fall through to TSV/CSV parser.
243
+ }
244
+ }
245
+ const firstLine = trimmed.split(/\r?\n/)[0] ?? "";
246
+ const sep = firstLine.includes("\t") ? "\t" : ",";
247
+ return parseDelimited(trimmed, sep);
248
+ }
249
+ export function createIpcHandler(store, getAgentDriver, redraw) {
250
+ return async function handleIpc(req) {
251
+ switch (req.op) {
252
+ case "ping":
253
+ return { id: req.id, ok: true, data: { session: store.session, surfaces: store.surfaces.length } };
254
+ case "present": {
255
+ const surface = store.present(req.payload);
256
+ redraw();
257
+ return { id: req.id, ok: true, data: store.serializeSurface(surface) };
258
+ }
259
+ case "append_log": {
260
+ const updated = store.appendLog(req.surfaceId, req.lines);
261
+ if (!updated) {
262
+ return { id: req.id, ok: false, error: `Log surface "${req.surfaceId}" not found` };
263
+ }
264
+ redraw();
265
+ return { id: req.id, ok: true, data: { id: updated.id, lineCount: updated.lines.length } };
266
+ }
267
+ case "ask_wait": {
268
+ const surface = store.present(req.payload);
269
+ redraw();
270
+ const answer = await store.waitForAsk(surface.id, req.timeoutMs);
271
+ return { id: req.id, ok: true, data: { id: surface.id, answer } };
272
+ }
273
+ case "ui_wait": {
274
+ const surface = store.present({ ...req.payload, wait: true });
275
+ redraw();
276
+ const submission = await store.waitForUi(surface.id, req.timeoutMs);
277
+ const latest = store.get(surface.id);
278
+ return {
279
+ id: req.id,
280
+ ok: true,
281
+ data: {
282
+ id: surface.id,
283
+ submission,
284
+ state: latest && latest.kind === "ui" ? latest.state : {},
285
+ notes: latest?.notes ?? [],
286
+ },
287
+ };
288
+ }
289
+ case "app_wait": {
290
+ const surface = store.present({ ...req.payload, wait: true });
291
+ redraw();
292
+ const submission = await store.waitForApp(surface.id, req.timeoutMs);
293
+ const latest = store.get(surface.id);
294
+ return {
295
+ id: req.id,
296
+ ok: true,
297
+ data: {
298
+ id: surface.id,
299
+ submission,
300
+ state: latest && latest.kind === "app" ? latest.state : {},
301
+ notes: latest?.notes ?? [],
302
+ },
303
+ };
304
+ }
305
+ case "list":
306
+ return { id: req.id, ok: true, data: { session: store.session, surfaces: store.listSummaries() } };
307
+ case "get_state":
308
+ return { id: req.id, ok: true, data: store.serializeState(req.surfaceId) };
309
+ case "focus": {
310
+ const ok = store.focus(req.surfaceId);
311
+ redraw();
312
+ return ok
313
+ ? { id: req.id, ok: true, data: { activeId: store.activeId } }
314
+ : { id: req.id, ok: false, error: `Surface "${req.surfaceId}" not found` };
315
+ }
316
+ case "close": {
317
+ const ok = store.close(req.surfaceId);
318
+ redraw();
319
+ return ok
320
+ ? { id: req.id, ok: true, data: { activeId: store.activeId } }
321
+ : { id: req.id, ok: false, error: "Surface not found" };
322
+ }
323
+ case "snapshot": {
324
+ const driver = getAgentDriver();
325
+ if (!driver)
326
+ return { id: req.id, ok: false, error: "Agent driver not initialized" };
327
+ return { id: req.id, ok: true, data: driver.snapshot() };
328
+ }
329
+ case "act": {
330
+ const driver = getAgentDriver();
331
+ if (!driver)
332
+ return { id: req.id, ok: false, error: "Agent driver not initialized" };
333
+ const res = driver.act({ steps: req.steps });
334
+ redraw();
335
+ return { id: req.id, ok: res.ok, data: res, error: res.ok ? undefined : res.error };
336
+ }
337
+ }
338
+ };
339
+ }
340
+ async function pushDemoToSession(session, origin, reqId, autoDock) {
341
+ const tmp = new WorkspaceStore(session);
342
+ loadDemoSurfaces(tmp);
343
+ for (const s of tmp.surfaces) {
344
+ let payload;
345
+ if (s.kind === "markdown") {
346
+ payload = { id: s.id, kind: "markdown", title: s.title, content: s.content, origin, focus: s.id === "demo-plan" };
347
+ }
348
+ else if (s.kind === "image") {
349
+ payload = { id: s.id, kind: "image", title: s.title, path: s.path, caption: s.caption, origin, focus: false };
350
+ }
351
+ else if (s.kind === "table") {
352
+ payload = { id: s.id, kind: "table", title: s.title, columns: s.columns, rows: s.rows.map((r) => r.cells), origin, focus: false };
353
+ }
354
+ else if (s.kind === "chart") {
355
+ payload = { id: s.id, kind: "chart", title: s.title, series: s.series, unit: s.unit, caption: s.caption, origin, focus: false };
356
+ }
357
+ else if (s.kind === "ask") {
358
+ payload = {
359
+ id: s.id,
360
+ kind: "ask",
361
+ title: s.title,
362
+ mode: s.mode,
363
+ prompt: s.prompt,
364
+ context: s.context,
365
+ options: s.options,
366
+ defaultValue: s.defaultValue,
367
+ origin,
368
+ focus: false,
369
+ };
370
+ }
371
+ else if (s.kind === "ui") {
372
+ payload = {
373
+ id: s.id,
374
+ kind: "ui",
375
+ title: s.title,
376
+ root: s.root,
377
+ state: s.state,
378
+ wait: s.submission.status === "pending",
379
+ origin,
380
+ focus: false,
381
+ };
382
+ }
383
+ else {
384
+ continue;
385
+ }
386
+ await sendIpc(session, { id: `${reqId}-${s.id}`, op: "present", payload }, { autoDock });
387
+ }
388
+ process.stdout.write(`Loaded demo surfaces into bypane session "${session}".\n`);
389
+ }
390
+ async function runTuiMode(session, loadDemo) {
391
+ const store = new WorkspaceStore(session);
392
+ if (loadDemo)
393
+ loadDemoSurfaces(store);
394
+ const sockPath = socketPathFor(session);
395
+ let app = null;
396
+ let driver = null;
397
+ const ui = createBypaneUi(store, sockPath, {
398
+ onQuit: () => app?.stop(),
399
+ });
400
+ app = runApp({
401
+ mouse: true,
402
+ theme: bypaneTheme,
403
+ view: ui.view,
404
+ keys: ui.keys,
405
+ });
406
+ driver = createAgent(app, {
407
+ allow: (step) => ui.allowAgentStep(step),
408
+ });
409
+ const unsub = store.subscribe(() => app?.redraw());
410
+ const toastTimer = setInterval(() => {
411
+ if (store.toast && store.toast.until <= Date.now()) {
412
+ store.toast = null;
413
+ app?.redraw();
414
+ }
415
+ }, 400);
416
+ const server = startIpcServer(session, createIpcHandler(store, () => driver, () => app?.redraw()));
417
+ const code = await app.done();
418
+ clearInterval(toastTimer);
419
+ unsub();
420
+ ui.dispose();
421
+ server.close();
422
+ process.exit(code);
423
+ }
424
+ async function main() {
425
+ const parsed = parseArgv(process.argv.slice(2));
426
+ if (parsed.flags.help || parsed.command === "help") {
427
+ process.stdout.write(HELP_TEXT);
428
+ return;
429
+ }
430
+ const session = resolveSessionKey(strFlag(parsed.flags, "session"));
431
+ const autoDock = !parsed.flags["no-dock"];
432
+ const focus = !parsed.flags["no-focus"];
433
+ const origin = detectCallerOrigin("cli");
434
+ const reqId = `cli-${Date.now()}`;
435
+ if (parsed.command === "tui") {
436
+ await runTuiMode(session, Boolean(parsed.flags.demo));
437
+ return;
438
+ }
439
+ if (parsed.command === "mcp") {
440
+ serveMcpStdio(session);
441
+ return;
442
+ }
443
+ if (parsed.command === "setup") {
444
+ await runSetupWizard({
445
+ yes: Boolean(parsed.flags.yes),
446
+ skipInstall: Boolean(parsed.flags["no-install"]),
447
+ onLaunchDemo: async () => {
448
+ await pushDemoToSession(session, origin, reqId, autoDock);
449
+ },
450
+ });
451
+ return;
452
+ }
453
+ if (parsed.command === "skill") {
454
+ const code = runSkillSubcommand(parsed.positionals[0], parsed.flags);
455
+ if (code !== 0)
456
+ process.exit(code);
457
+ return;
458
+ }
459
+ if (parsed.command === "demo") {
460
+ await pushDemoToSession(session, origin, reqId, autoDock);
461
+ return;
462
+ }
463
+ if (parsed.command === "show") {
464
+ const target = parsed.positionals[0];
465
+ if (!target) {
466
+ process.stderr.write("Usage: bypane show <file[:start[-end]]>\n");
467
+ process.exit(1);
468
+ }
469
+ const { path: rawPath, start, end } = parseFileTarget(target);
470
+ const absPath = resolve(rawPath);
471
+ const ext = extname(absPath).toLowerCase();
472
+ const id = strFlag(parsed.flags, "id");
473
+ const title = strFlag(parsed.flags, "title") || basename(absPath);
474
+ let payload;
475
+ if ((ext === ".md" || ext === ".markdown") && start === undefined && !parsed.flags.raw) {
476
+ const content = readFileSync(absPath, "utf8");
477
+ payload = { id, kind: "markdown", title, content, origin, focus };
478
+ }
479
+ else if ([".png", ".jpg", ".jpeg", ".webp", ".gif"].includes(ext)) {
480
+ payload = {
481
+ id,
482
+ kind: "image",
483
+ title,
484
+ path: absPath,
485
+ caption: strFlag(parsed.flags, "caption"),
486
+ origin,
487
+ focus,
488
+ };
489
+ }
490
+ else {
491
+ payload = {
492
+ id,
493
+ kind: "file",
494
+ title,
495
+ path: absPath,
496
+ highlightStart: start,
497
+ highlightEnd: end,
498
+ origin,
499
+ focus,
500
+ };
501
+ }
502
+ const res = await sendIpc(session, { id: reqId, op: "present", payload }, { autoDock });
503
+ if (!res.ok) {
504
+ process.stderr.write(`Error: ${res.error}\n`);
505
+ process.exit(1);
506
+ }
507
+ process.stdout.write(`${JSON.stringify(res.data)}\n`);
508
+ return;
509
+ }
510
+ if (parsed.command === "md" || parsed.command === "markdown") {
511
+ const inline = parsed.positionals.join(" ");
512
+ const content = inline || (await readStdinAll());
513
+ if (!content) {
514
+ process.stderr.write("Usage: bypane md \"# Hello\" or cat plan.md | bypane md\n");
515
+ process.exit(1);
516
+ }
517
+ const res = await sendIpc(session, {
518
+ id: reqId,
519
+ op: "present",
520
+ payload: {
521
+ id: strFlag(parsed.flags, "id"),
522
+ kind: "markdown",
523
+ title: strFlag(parsed.flags, "title") || "Document",
524
+ content,
525
+ origin,
526
+ focus,
527
+ },
528
+ }, { autoDock });
529
+ if (!res.ok) {
530
+ process.stderr.write(`Error: ${res.error}\n`);
531
+ process.exit(1);
532
+ }
533
+ process.stdout.write(`${JSON.stringify(res.data)}\n`);
534
+ return;
535
+ }
536
+ if (parsed.command === "table") {
537
+ const file = parsed.positionals[0];
538
+ const raw = file ? readFileSync(resolve(file), "utf8") : await readStdinAll();
539
+ const { columns, rows } = parseTableInput(raw);
540
+ const res = await sendIpc(session, {
541
+ id: reqId,
542
+ op: "present",
543
+ payload: {
544
+ id: strFlag(parsed.flags, "id"),
545
+ kind: "table",
546
+ title: strFlag(parsed.flags, "title") || (file ? basename(file) : "Table"),
547
+ columns,
548
+ rows,
549
+ origin,
550
+ focus,
551
+ },
552
+ }, { autoDock });
553
+ if (!res.ok) {
554
+ process.stderr.write(`Error: ${res.error}\n`);
555
+ process.exit(1);
556
+ }
557
+ process.stdout.write(`${JSON.stringify(res.data)}\n`);
558
+ return;
559
+ }
560
+ if (parsed.command === "chart") {
561
+ const seriesFlags = listFlag(parsed.flags, "series");
562
+ let series = [];
563
+ if (seriesFlags.length > 0) {
564
+ series = seriesFlags.map((spec, idx) => {
565
+ const colon = spec.indexOf(":");
566
+ const name = colon >= 0 ? spec.slice(0, colon) : `series-${idx + 1}`;
567
+ const nums = (colon >= 0 ? spec.slice(colon + 1) : spec)
568
+ .split(",")
569
+ .map((s) => Number(s.trim()))
570
+ .filter((n) => Number.isFinite(n));
571
+ return { name, values: nums };
572
+ });
573
+ }
574
+ else {
575
+ const raw = (await readStdinAll()).trim();
576
+ if (raw) {
577
+ const parsedJson = JSON.parse(raw);
578
+ if (Array.isArray(parsedJson) && typeof parsedJson[0] === "number") {
579
+ series = [{ name: "value", values: parsedJson }];
580
+ }
581
+ else if (Array.isArray(parsedJson)) {
582
+ series = parsedJson;
583
+ }
584
+ else if (parsedJson && typeof parsedJson === "object" && "series" in parsedJson) {
585
+ series = parsedJson.series;
586
+ }
587
+ }
588
+ }
589
+ const res = await sendIpc(session, {
590
+ id: reqId,
591
+ op: "present",
592
+ payload: {
593
+ id: strFlag(parsed.flags, "id"),
594
+ kind: "chart",
595
+ title: strFlag(parsed.flags, "title") || "Chart",
596
+ series,
597
+ unit: strFlag(parsed.flags, "unit"),
598
+ caption: strFlag(parsed.flags, "caption"),
599
+ origin,
600
+ focus,
601
+ },
602
+ }, { autoDock });
603
+ if (!res.ok) {
604
+ process.stderr.write(`Error: ${res.error}\n`);
605
+ process.exit(1);
606
+ }
607
+ process.stdout.write(`${JSON.stringify(res.data)}\n`);
608
+ return;
609
+ }
610
+ if (parsed.command === "log") {
611
+ const raw = await readStdinAll();
612
+ const lines = raw ? raw.split(/\r?\n/) : parsed.positionals;
613
+ if (lines.length > 0 && lines[lines.length - 1] === "")
614
+ lines.pop();
615
+ const res = await sendIpc(session, {
616
+ id: reqId,
617
+ op: "present",
618
+ payload: {
619
+ id: strFlag(parsed.flags, "id"),
620
+ kind: "log",
621
+ title: strFlag(parsed.flags, "title") || "Log",
622
+ lines,
623
+ append: Boolean(parsed.flags.append),
624
+ origin,
625
+ focus,
626
+ },
627
+ }, { autoDock });
628
+ if (!res.ok) {
629
+ process.stderr.write(`Error: ${res.error}\n`);
630
+ process.exit(1);
631
+ }
632
+ process.stdout.write(`${JSON.stringify(res.data)}\n`);
633
+ return;
634
+ }
635
+ if (parsed.command === "ask") {
636
+ const prompt = strFlag(parsed.flags, "prompt") || parsed.positionals.join(" ");
637
+ if (!prompt) {
638
+ process.stderr.write("Usage: bypane ask --prompt \"Question\" [--mode select|multiselect|text|confirm] [--option a --option b]\n");
639
+ process.exit(1);
640
+ }
641
+ const options = listFlag(parsed.flags, "option");
642
+ const mode = strFlag(parsed.flags, "mode") || (options.length > 0 ? "select" : "confirm");
643
+ const payload = {
644
+ id: strFlag(parsed.flags, "id"),
645
+ kind: "ask",
646
+ title: strFlag(parsed.flags, "title") || "Decision",
647
+ mode,
648
+ prompt,
649
+ context: strFlag(parsed.flags, "context"),
650
+ options: options.length > 0 ? options : undefined,
651
+ defaultValue: strFlag(parsed.flags, "default"),
652
+ placeholder: strFlag(parsed.flags, "placeholder"),
653
+ origin,
654
+ focus: true,
655
+ };
656
+ const wait = !parsed.flags["no-wait"];
657
+ const res = await sendIpc(session, wait ? { id: reqId, op: "ask_wait", payload } : { id: reqId, op: "present", payload }, { autoDock });
658
+ if (!res.ok) {
659
+ process.stderr.write(`Error: ${res.error}\n`);
660
+ process.exit(1);
661
+ }
662
+ process.stdout.write(`${JSON.stringify(res.data)}\n`);
663
+ return;
664
+ }
665
+ if (parsed.command === "ui") {
666
+ const file = parsed.positionals[0];
667
+ const raw = (file ? readFileSync(resolve(file), "utf8") : await readStdinAll()).trim();
668
+ if (!raw) {
669
+ process.stderr.write('Usage: cat ui.json | bypane ui [--id <id>] [--title <t>] [--wait]\n');
670
+ process.exit(1);
671
+ }
672
+ const spec = JSON.parse(raw);
673
+ const isBareNode = typeof spec.type === "string" && !("root" in spec) && !("body" in spec);
674
+ const root = (isBareNode ? spec : (spec.root ?? spec.body));
675
+ if (!root || typeof root !== "object" || typeof root.type !== "string") {
676
+ process.stderr.write("Error: UI spec must include a valid root/body node with a `type` field.\n");
677
+ process.exit(1);
678
+ }
679
+ const wait = Boolean(parsed.flags.wait || spec.wait);
680
+ const payload = {
681
+ id: strFlag(parsed.flags, "id") ?? (typeof spec.id === "string" ? spec.id : undefined),
682
+ kind: "ui",
683
+ title: strFlag(parsed.flags, "title") ?? (typeof spec.title === "string" ? spec.title : "Interactive UI"),
684
+ root,
685
+ state: spec.state && typeof spec.state === "object" && !Array.isArray(spec.state)
686
+ ? spec.state
687
+ : undefined,
688
+ preserveState: typeof spec.preserveState === "boolean" ? spec.preserveState : undefined,
689
+ wait,
690
+ origin,
691
+ focus: wait ? true : focus,
692
+ };
693
+ const res = await sendIpc(session, wait ? { id: reqId, op: "ui_wait", payload } : { id: reqId, op: "present", payload }, { autoDock });
694
+ if (!res.ok) {
695
+ process.stderr.write(`Error: ${res.error}\n`);
696
+ process.exit(1);
697
+ }
698
+ process.stdout.write(`${JSON.stringify(res.data)}\n`);
699
+ return;
700
+ }
701
+ if (parsed.command === "app") {
702
+ const file = parsed.positionals[0];
703
+ const inlineFlag = strFlag(parsed.flags, "code");
704
+ const stateRaw = strFlag(parsed.flags, "state");
705
+ let state;
706
+ if (stateRaw !== undefined) {
707
+ try {
708
+ const parsedState = JSON.parse(stateRaw);
709
+ if (!parsedState || typeof parsedState !== "object" || Array.isArray(parsedState)) {
710
+ throw new Error("--state must be a JSON object");
711
+ }
712
+ state = parsedState;
713
+ }
714
+ catch (err) {
715
+ process.stderr.write(`Error parsing --state JSON: ${err.message}\n`);
716
+ process.exit(1);
717
+ }
718
+ }
719
+ const id = strFlag(parsed.flags, "id");
720
+ const stdinCode = !file && inlineFlag === undefined && !(id && state) ? await readStdinAll() : "";
721
+ const code = inlineFlag !== undefined ? inlineFlag : stdinCode.trim() ? stdinCode : undefined;
722
+ const absPath = file ? resolve(file) : undefined;
723
+ if (!absPath && code === undefined && !(id && state)) {
724
+ process.stderr.write('Usage: bypane app <view.ts> [--id <id>] [--title <t>] [--state \'{"k":1}\'] [--wait]\n' +
725
+ " or: cat view.ts | bypane app --id <id> --title <t>\n" +
726
+ ' or: bypane app --id <existing-id> --state \'{"k":2}\'\n');
727
+ process.exit(1);
728
+ }
729
+ const wait = Boolean(parsed.flags.wait);
730
+ const payload = {
731
+ id,
732
+ kind: "app",
733
+ title: strFlag(parsed.flags, "title"),
734
+ path: absPath,
735
+ code,
736
+ state,
737
+ wait,
738
+ origin,
739
+ focus: wait ? true : focus,
740
+ };
741
+ const res = await sendIpc(session, wait ? { id: reqId, op: "app_wait", payload } : { id: reqId, op: "present", payload }, { autoDock });
742
+ if (!res.ok) {
743
+ process.stderr.write(`Error: ${res.error}\n`);
744
+ process.exit(1);
745
+ }
746
+ process.stdout.write(`${JSON.stringify(res.data)}\n`);
747
+ return;
748
+ }
749
+ if (parsed.command === "list") {
750
+ const res = await sendIpc(session, { id: reqId, op: "list" }, { autoDock: false });
751
+ if (!res.ok) {
752
+ process.stderr.write(`Error: ${res.error}\n`);
753
+ process.exit(1);
754
+ }
755
+ process.stdout.write(`${JSON.stringify(res.data, null, 2)}\n`);
756
+ return;
757
+ }
758
+ if (parsed.command === "state") {
759
+ const res = await sendIpc(session, { id: reqId, op: "get_state", surfaceId: parsed.positionals[0] }, { autoDock: false });
760
+ if (!res.ok) {
761
+ process.stderr.write(`Error: ${res.error}\n`);
762
+ process.exit(1);
763
+ }
764
+ process.stdout.write(`${JSON.stringify(res.data, null, 2)}\n`);
765
+ return;
766
+ }
767
+ if (parsed.command === "close") {
768
+ const res = await sendIpc(session, { id: reqId, op: "close", surfaceId: parsed.positionals[0] }, { autoDock: false });
769
+ if (!res.ok) {
770
+ process.stderr.write(`Error: ${res.error}\n`);
771
+ process.exit(1);
772
+ }
773
+ process.stdout.write(`${JSON.stringify(res.data)}\n`);
774
+ return;
775
+ }
776
+ if (parsed.command === "snapshot") {
777
+ const res = await sendIpc(session, { id: reqId, op: "snapshot" }, { autoDock: false });
778
+ if (!res.ok) {
779
+ process.stderr.write(`Error: ${res.error}\n`);
780
+ process.exit(1);
781
+ }
782
+ process.stdout.write(`${JSON.stringify(res.data, null, 2)}\n`);
783
+ return;
784
+ }
785
+ }
786
+ // Only run CLI when executed directly (allows importing helpers in tests cleanly).
787
+ function isDirectEntry() {
788
+ if (process.env.NODE_TEST_CONTEXT)
789
+ return false;
790
+ const arg1 = process.argv[1];
791
+ if (!arg1)
792
+ return true;
793
+ try {
794
+ return realpathSync(arg1) === realpathSync(fileURLToPath(import.meta.url));
795
+ }
796
+ catch {
797
+ return (arg1.endsWith("/cli.ts") ||
798
+ arg1.endsWith("/cli.js") ||
799
+ arg1.endsWith("\\cli.ts") ||
800
+ arg1.endsWith("\\cli.js") ||
801
+ arg1.endsWith("/bypane") ||
802
+ arg1 === "bypane");
803
+ }
804
+ }
805
+ if (isDirectEntry()) {
806
+ main().catch((err) => {
807
+ process.stderr.write(`bypane: ${err.message}\n`);
808
+ process.exit(1);
809
+ });
810
+ }