@eserstack/mux 0.0.0-bootstrap.0 → 5.0.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.
Files changed (57) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +151 -0
  3. package/dist/engine/effects.d.ts +52 -0
  4. package/dist/engine/effects.js +2 -0
  5. package/dist/engine/geometry.d.ts +57 -0
  6. package/dist/engine/geometry.js +170 -0
  7. package/dist/engine/mod.d.ts +13 -0
  8. package/dist/engine/mod.js +5 -0
  9. package/dist/engine/reducer.d.ts +15 -0
  10. package/dist/engine/reducer.js +325 -0
  11. package/dist/engine/sanitize.d.ts +60 -0
  12. package/dist/engine/sanitize.js +64 -0
  13. package/dist/engine/split-tree.d.ts +41 -0
  14. package/dist/engine/split-tree.js +117 -0
  15. package/dist/engine/types.d.ts +192 -0
  16. package/dist/engine/types.js +2 -0
  17. package/dist/frontends/frontend.d.ts +17 -0
  18. package/dist/frontends/frontend.js +2 -0
  19. package/dist/frontends/tui/compositor.d.ts +23 -0
  20. package/dist/frontends/tui/compositor.js +72 -0
  21. package/dist/frontends/tui/frame.d.ts +9 -0
  22. package/dist/frontends/tui/frame.js +2 -0
  23. package/dist/frontends/tui/input-source.d.ts +21 -0
  24. package/dist/frontends/tui/input-source.js +40 -0
  25. package/dist/frontends/tui/tui-frontend.d.ts +36 -0
  26. package/dist/frontends/tui/tui-frontend.js +188 -0
  27. package/dist/ipc/protocol.d.ts +41 -0
  28. package/dist/ipc/protocol.js +2 -0
  29. package/dist/ipc/transport-inprocess.d.ts +9 -0
  30. package/dist/ipc/transport-inprocess.js +35 -0
  31. package/dist/ipc/transport-ws.d.ts +19 -0
  32. package/dist/ipc/transport-ws.js +37 -0
  33. package/dist/keybindings/defaults.d.ts +3 -0
  34. package/dist/keybindings/defaults.js +80 -0
  35. package/dist/keybindings/mod.d.ts +10 -0
  36. package/dist/keybindings/mod.js +4 -0
  37. package/dist/keybindings/modes.d.ts +19 -0
  38. package/dist/keybindings/modes.js +18 -0
  39. package/dist/keybindings/registry.d.ts +20 -0
  40. package/dist/keybindings/registry.js +37 -0
  41. package/dist/mod.d.ts +28 -0
  42. package/dist/mod.js +21 -0
  43. package/dist/render/scheduler.d.ts +18 -0
  44. package/dist/render/scheduler.js +33 -0
  45. package/dist/runner/inprocess.d.ts +10 -0
  46. package/dist/runner/inprocess.js +60 -0
  47. package/dist/scene/diff.d.ts +26 -0
  48. package/dist/scene/diff.js +83 -0
  49. package/dist/scene/mod.d.ts +9 -0
  50. package/dist/scene/mod.js +3 -0
  51. package/dist/scene/scene.d.ts +30 -0
  52. package/dist/scene/scene.js +54 -0
  53. package/dist/server/pty-host.d.ts +25 -0
  54. package/dist/server/pty-host.js +81 -0
  55. package/dist/server/server.d.ts +58 -0
  56. package/dist/server/server.js +204 -0
  57. package/package.json +51 -1
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Core data model for the multiplexer engine.
3
+ *
4
+ * The model is fully serializable: panes are plain descriptors and the layout
5
+ * is a binary split tree. Live objects (PtyProcess, VTerminal) are owned by the
6
+ * server and keyed by {@link PaneId}, never stored here — so {@link MuxState}
7
+ * can be diffed, persisted, and sent over IPC unchanged.
8
+ *
9
+ * @module
10
+ */
11
+ /** Stable identifier for a pane (e.g. "pane-3"). */
12
+ export type PaneId = string;
13
+ /** Stable identifier for a tab (e.g. "tab-2"). */
14
+ export type TabId = string;
15
+ /**
16
+ * A terminal pane runs a shell/command.
17
+ *
18
+ * `"agent"` is DEAD and has never been used: nothing sets it, nothing branches
19
+ * on it, and every agent tab in this repo is dispatched as an ordinary terminal
20
+ * pane whose binary was resolved by the caller.
21
+ *
22
+ * It is deliberately not a hook for ACP-backed panes. A pane has exactly one
23
+ * content channel — VT bytes, via the `output` frame — and both renderers write
24
+ * unconditionally into a VT screen. An ACP session emits structured
25
+ * session/update events with no VT representation, so backing a pane with one
26
+ * would mean inventing a second content channel, a second renderer, and a
27
+ * `ScenePane.kind` wire change shared by the TUI, the browser and the daemon
28
+ * relay. Agent sessions already run over ACP through the daemon
29
+ * (noskillsserverfx WorkerHandle kind="acp"), which is where structured events
30
+ * have somewhere to go.
31
+ *
32
+ * If `kind` should ever mean something, the question is which binary runs in a
33
+ * VT pane — a spawn-resolution concern, not an ACP one.
34
+ */
35
+ export type PaneKind = "terminal" | "agent";
36
+ /** Absolute, 1-based-friendly rectangle in terminal cells (0-based here). */
37
+ export type Geom = {
38
+ readonly x: number;
39
+ readonly y: number;
40
+ readonly width: number;
41
+ readonly height: number;
42
+ };
43
+ /** A client's terminal size in character cells. */
44
+ export type Viewport = {
45
+ readonly cols: number;
46
+ readonly rows: number;
47
+ };
48
+ /**
49
+ * Serializable pane descriptor. No live PTY/VTerminal — those live in the
50
+ * server keyed by `id`.
51
+ */
52
+ export type Pane = {
53
+ readonly id: PaneId;
54
+ readonly kind: PaneKind;
55
+ readonly title: string;
56
+ readonly cwd?: string;
57
+ /** Command to spawn; when omitted the server uses its default shell. */
58
+ readonly command?: string;
59
+ readonly args?: readonly string[];
60
+ /** Free-form metadata for consumers (e.g. noskills session id / spec). */
61
+ readonly meta?: Readonly<Record<string, string>>;
62
+ /** Set once the underlying process has exited. */
63
+ readonly exited?: boolean;
64
+ };
65
+ /**
66
+ * Split arrangement.
67
+ *
68
+ * - `"vertical"` — a vertical divider, panes side by side (left/right) →
69
+ * maps to a flex `"row"`.
70
+ * - `"horizontal"` — a horizontal divider, panes stacked (top/bottom) →
71
+ * maps to a flex `"column"`.
72
+ *
73
+ * This single mapping is applied in `geometry.ts`; document it here so the
74
+ * confusion that bit the old hand-rolled layout never recurs.
75
+ */
76
+ export type SplitDirection = "vertical" | "horizontal";
77
+ /** Binary split tree: a leaf holds one pane, a branch splits two children. */
78
+ export type SplitNode = {
79
+ readonly kind: "leaf";
80
+ readonly pane: PaneId;
81
+ } | {
82
+ readonly kind: "branch";
83
+ readonly direction: SplitDirection;
84
+ readonly first: SplitNode;
85
+ readonly second: SplitNode;
86
+ /** Fraction of the parent allotted to `first` (0..1). */
87
+ readonly ratio: number;
88
+ };
89
+ /** A tab is a named workspace holding a split tree of panes. */
90
+ export type Tab = {
91
+ readonly id: TabId;
92
+ readonly name: string;
93
+ readonly root: SplitNode;
94
+ readonly focusedPane: PaneId;
95
+ /** When set, only this pane is rendered (zoom). */
96
+ readonly fullscreenPane?: PaneId;
97
+ };
98
+ /** Cardinal direction for focus movement and resizing. */
99
+ export type Direction = "up" | "down" | "left" | "right";
100
+ /** Scrollback navigation action. */
101
+ export type ScrollAction = "up" | "down" | "pageUp" | "pageDown" | "home" | "end";
102
+ /** Keybinding mode (determines how keys are interpreted). */
103
+ export type InputMode = "normal" | "pane" | "tab" | "resize" | "scroll" | "locked";
104
+ /** The full, serializable engine state. */
105
+ export type MuxState = {
106
+ readonly panes: Readonly<Record<PaneId, Pane>>;
107
+ readonly tabs: readonly Tab[];
108
+ readonly activeTab: number;
109
+ readonly mode: InputMode;
110
+ readonly viewport: Viewport;
111
+ readonly running: boolean;
112
+ readonly nextPaneSeq: number;
113
+ readonly nextTabSeq: number;
114
+ };
115
+ /**
116
+ * Engine vocabulary. Frontends translate raw input (keys, mouse) into actions;
117
+ * the reducer is the single place that interprets them.
118
+ */
119
+ export type Action = {
120
+ readonly type: "switchMode";
121
+ readonly mode: InputMode;
122
+ } | {
123
+ readonly type: "splitPane";
124
+ readonly direction: SplitDirection;
125
+ } | {
126
+ readonly type: "newPane";
127
+ readonly direction?: SplitDirection;
128
+ readonly kind?: PaneKind;
129
+ readonly command?: string;
130
+ readonly args?: readonly string[];
131
+ readonly cwd?: string;
132
+ readonly title?: string;
133
+ readonly meta?: Readonly<Record<string, string>>;
134
+ } | {
135
+ readonly type: "closeFocusedPane";
136
+ } | {
137
+ readonly type: "focusDirection";
138
+ readonly direction: Direction;
139
+ } | {
140
+ readonly type: "focusNext";
141
+ } | {
142
+ readonly type: "focusPrev";
143
+ } | {
144
+ readonly type: "focusPane";
145
+ readonly pane: PaneId;
146
+ } | {
147
+ readonly type: "toggleFullscreen";
148
+ } | {
149
+ readonly type: "resizePane";
150
+ readonly direction: Direction;
151
+ readonly step?: number;
152
+ } | {
153
+ readonly type: "newTab";
154
+ readonly kind?: PaneKind;
155
+ readonly command?: string;
156
+ readonly args?: readonly string[];
157
+ readonly cwd?: string;
158
+ readonly title?: string;
159
+ readonly meta?: Readonly<Record<string, string>>;
160
+ } | {
161
+ readonly type: "closeTab";
162
+ readonly index?: number;
163
+ } | {
164
+ readonly type: "gotoTab";
165
+ readonly index: number;
166
+ } | {
167
+ readonly type: "nextTab";
168
+ } | {
169
+ readonly type: "prevTab";
170
+ } | {
171
+ readonly type: "scroll";
172
+ readonly action: ScrollAction;
173
+ } | {
174
+ readonly type: "writeInput";
175
+ readonly data: string;
176
+ } | {
177
+ readonly type: "writeToPane";
178
+ readonly pane: PaneId;
179
+ readonly data: string;
180
+ } | {
181
+ readonly type: "resizeViewport";
182
+ readonly cols: number;
183
+ readonly rows: number;
184
+ } | {
185
+ readonly type: "paneExited";
186
+ readonly pane: PaneId;
187
+ readonly code: number;
188
+ } | {
189
+ readonly type: "detach";
190
+ } | {
191
+ readonly type: "quit";
192
+ };
@@ -0,0 +1,2 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ export {};
@@ -0,0 +1,17 @@
1
+ /**
2
+ * A frontend consumes the neutral server feed (scene + output) and produces
3
+ * input actions. The TUI and web frontends both implement this contract.
4
+ *
5
+ * @module
6
+ */
7
+ import type { ServerToFrontend } from "../ipc/protocol.ts";
8
+ export type Frontend = {
9
+ /** Apply a message from the server (scene delta / output / exit). */
10
+ handle(msg: ServerToFrontend): void;
11
+ /** Enter raw mode, attach, and pump input until stopped. Resolves on exit. */
12
+ run(): Promise<void>;
13
+ /** Restore the terminal and tear down. */
14
+ stop(): void;
15
+ /** Request a re-render (e.g. after decoration data changed). */
16
+ refresh(): void;
17
+ };
@@ -0,0 +1,2 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ export {};
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The TUI compositor: turns a neutral {@link Scene} plus per-pane terminal
3
+ * widgets into one ANSI {@link Frame}.
4
+ *
5
+ * Coordinate convention (matching the existing widgets): pane `Geom` is 0-based;
6
+ * a box is drawn with its top-left at the 1-based `(geom.y+1, geom.x+1)`, and
7
+ * `VTermWidget.render` insets one cell for the border. The tab bar occupies
8
+ * row 1; the status bar the last row.
9
+ *
10
+ * @module
11
+ */
12
+ import * as tui from "@eserstack/shell/tui";
13
+ import type { PaneId } from "../../engine/types.ts";
14
+ import type { Scene } from "../../scene/scene.ts";
15
+ import type { Frame } from "./frame.ts";
16
+ /** Live terminal widgets the compositor reads pane contents from. */
17
+ export type CompositorDeps = {
18
+ getWidget(pane: PaneId): tui.VTermWidget | undefined;
19
+ };
20
+ export declare const composite: (scene: Scene, deps: CompositorDeps, opts: {
21
+ readonly fullRedraw: boolean;
22
+ readonly statusText?: string;
23
+ }) => Frame;
@@ -0,0 +1,72 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * The TUI compositor: turns a neutral {@link Scene} plus per-pane terminal
4
+ * widgets into one ANSI {@link Frame}.
5
+ *
6
+ * Coordinate convention (matching the existing widgets): pane `Geom` is 0-based;
7
+ * a box is drawn with its top-left at the 1-based `(geom.y+1, geom.x+1)`, and
8
+ * `VTermWidget.render` insets one cell for the border. The tab bar occupies
9
+ * row 1; the status bar the last row.
10
+ *
11
+ * @module
12
+ */
13
+ import * as tui from "@eserstack/shell/tui";
14
+ const MODE_HINTS = {
15
+ normal: "ctrl+p pane · ctrl+t tab · ctrl+n resize · ctrl+s scroll · ctrl+q quit",
16
+ pane: "PANE: n new · v|s split · x close · f full · hjkl focus · esc",
17
+ tab: "TAB: n new · x close · h/l switch · 1-9 goto · esc",
18
+ resize: "RESIZE: hjkl/arrows · esc",
19
+ scroll: "SCROLL: j/k · g/G · esc",
20
+ locked: "LOCKED: ctrl+g to unlock",
21
+ };
22
+ const statusBar = (scene, override) => {
23
+ const cols = scene.viewport.cols;
24
+ const text = override ?? ` ${scene.mode.toUpperCase()} ${MODE_HINTS[scene.mode]}`;
25
+ const visible = tui.ansi.visibleLength(text);
26
+ const padded = tui.ansi.truncate(text, cols) + " ".repeat(Math.max(0, cols - visible));
27
+ return tui.ansi.moveTo(scene.viewport.rows, 1) + tui.ansi.inverse(padded);
28
+ };
29
+ export const composite = (scene, deps, opts) => {
30
+ const buf = [];
31
+ if (opts.fullRedraw)
32
+ buf.push(tui.terminal.clearScreenSeq());
33
+ // Tab bar (row 1).
34
+ const tabBar = tui.tabBar.renderTabBar({
35
+ tabs: scene.tabs.map((t) => ({ id: t.id, label: t.name })),
36
+ activeIndex: scene.activeTab,
37
+ maxWidth: scene.viewport.cols,
38
+ });
39
+ buf.push(tui.ansi.moveTo(1, 1) + tabBar);
40
+ let cursor = { row: scene.viewport.rows, col: 1, visible: false };
41
+ for (const pane of scene.panes) {
42
+ // Too small to draw a bordered box — skip rather than emit garbage.
43
+ if (pane.geom.width < 2 || pane.geom.height < 2)
44
+ continue;
45
+ const boxPanel = {
46
+ id: pane.id,
47
+ x: pane.geom.x + 1,
48
+ y: pane.geom.y + 1,
49
+ width: pane.geom.width,
50
+ height: pane.geom.height,
51
+ };
52
+ buf.push(tui.box.drawBox({
53
+ ...boxPanel,
54
+ title: pane.title,
55
+ borderStyle: pane.focused ? "double" : "single",
56
+ skipInterior: true,
57
+ }));
58
+ const widget = deps.getWidget(pane.id);
59
+ if (widget !== undefined) {
60
+ buf.push(widget.render(boxPanel, opts.fullRedraw));
61
+ if (pane.focused) {
62
+ cursor = {
63
+ row: boxPanel.y + 1 + widget.terminal.cursorRow,
64
+ col: boxPanel.x + 1 + widget.terminal.cursorCol,
65
+ visible: true,
66
+ };
67
+ }
68
+ }
69
+ }
70
+ buf.push(statusBar(scene, opts.statusText));
71
+ return { data: buf.join(""), cursor };
72
+ };
@@ -0,0 +1,9 @@
1
+ /** A composited terminal frame: the ANSI byte stream plus final cursor placement. */
2
+ export type Frame = {
3
+ readonly data: string;
4
+ readonly cursor: {
5
+ readonly row: number;
6
+ readonly col: number;
7
+ readonly visible: boolean;
8
+ };
9
+ };
@@ -0,0 +1,2 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ export {};
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Pure mapping from raw terminal input to {@link FrontendToServer} messages.
3
+ *
4
+ * Keeping this pure makes the keybinding/passthrough rules unit-testable without
5
+ * a real terminal. The frontend runs the actual `readInput` loop and calls these.
6
+ *
7
+ * @module
8
+ */
9
+ import type * as tui from "@eserstack/shell/tui";
10
+ import type { InputMode } from "../../engine/types.ts";
11
+ import type { Keymap } from "../../keybindings/mod.ts";
12
+ import type { FrontendToServer } from "../../ipc/protocol.ts";
13
+ import type { Scene } from "../../scene/scene.ts";
14
+ /**
15
+ * Translate a key event into messages. Bound chords dispatch their actions; an
16
+ * unbound key in `normal`/`locked` mode is forwarded raw to the focused
17
+ * terminal (the passthrough rule). In a command mode, an unbound key is dropped.
18
+ */
19
+ export declare const keyToMessages: (key: tui.KeypressEvent, mode: InputMode, keymap: Keymap) => FrontendToServer[];
20
+ /** Translate a mouse event into messages (click-to-focus for now). */
21
+ export declare const mouseToMessages: (ev: tui.mouse.MouseEvent, scene: Scene | null) => FrontendToServer[];
@@ -0,0 +1,40 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ import * as keybindings from "../../keybindings/mod.js";
3
+ const decoder = new TextDecoder();
4
+ /**
5
+ * Translate a key event into messages. Bound chords dispatch their actions; an
6
+ * unbound key in `normal`/`locked` mode is forwarded raw to the focused
7
+ * terminal (the passthrough rule). In a command mode, an unbound key is dropped.
8
+ */
9
+ export const keyToMessages = (key, mode, keymap) => {
10
+ const actions = keybindings.lookup(keymap, mode, keybindings.parseChord(key));
11
+ if (actions !== undefined) {
12
+ return actions.map((action) => ({ t: "action", action }));
13
+ }
14
+ if (mode === "normal" || mode === "locked") {
15
+ return [
16
+ {
17
+ t: "action",
18
+ action: { type: "writeInput", data: decoder.decode(key.raw) },
19
+ },
20
+ ];
21
+ }
22
+ return [];
23
+ };
24
+ /** Translate a mouse event into messages (click-to-focus for now). */
25
+ export const mouseToMessages = (ev, scene) => {
26
+ if (scene === null || ev.type !== "mousedown")
27
+ return [];
28
+ // SGR coords are 1-based; pane boxes start at geom.(x|y)+1.
29
+ for (const pane of scene.panes) {
30
+ const x0 = pane.geom.x + 1;
31
+ const y0 = pane.geom.y + 1;
32
+ if (ev.x >= x0 &&
33
+ ev.x < x0 + pane.geom.width &&
34
+ ev.y >= y0 &&
35
+ ev.y < y0 + pane.geom.height) {
36
+ return [{ t: "action", action: { type: "focusPane", pane: pane.id } }];
37
+ }
38
+ }
39
+ return [];
40
+ };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The ANSI TUI frontend.
3
+ *
4
+ * Owns a {@link VTermWidget} per pane (fed by the server's raw output stream),
5
+ * composites them with the scene into a frame on a single coalescing scheduler,
6
+ * and writes to stdout. Raw input is mapped to actions and sent back. It only
7
+ * ever talks to the server through the neutral protocol, so the same server can
8
+ * just as well drive a browser frontend.
9
+ *
10
+ * @module
11
+ */
12
+ import * as tui from "@eserstack/shell/tui";
13
+ import type { DecorationRegions } from "../../engine/geometry.ts";
14
+ import type { Keymap } from "../../keybindings/mod.ts";
15
+ import type { FrontendToServer, ServerToFrontend, Transport } from "../../ipc/protocol.ts";
16
+ import type { Scene } from "../../scene/scene.ts";
17
+ import type { Frontend } from "../frontend.ts";
18
+ /** Render extra content into the chrome's reserved regions (sidebars/strips). */
19
+ export type DecorateFn = (ctx: {
20
+ readonly regions: DecorationRegions;
21
+ readonly scene: Scene;
22
+ }) => string;
23
+ export type TuiFrontendOptions = {
24
+ readonly transport: Transport<FrontendToServer, ServerToFrontend>;
25
+ readonly keymap: Keymap;
26
+ readonly sizePollMs?: number;
27
+ /** Draw consumer decorations (e.g. a spec-list sidebar) each frame. */
28
+ readonly decorate?: DecorateFn;
29
+ /** Intercept a key before default handling; return true if handled (consumed). */
30
+ readonly onKey?: (key: tui.KeypressEvent, scene: Scene | null) => boolean;
31
+ /** Intercept a mouse event before default handling; return true if handled. */
32
+ readonly onMouse?: (ev: tui.mouse.MouseEvent, scene: Scene | null) => boolean;
33
+ /** Override the status-bar text (otherwise mux's mode hints are shown). */
34
+ readonly statusText?: string;
35
+ };
36
+ export declare const createTuiFrontend: (opts: TuiFrontendOptions) => Frontend;
@@ -0,0 +1,188 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * The ANSI TUI frontend.
4
+ *
5
+ * Owns a {@link VTermWidget} per pane (fed by the server's raw output stream),
6
+ * composites them with the scene into a frame on a single coalescing scheduler,
7
+ * and writes to stdout. Raw input is mapped to actions and sent back. It only
8
+ * ever talks to the server through the neutral protocol, so the same server can
9
+ * just as well drive a browser frontend.
10
+ *
11
+ * @module
12
+ */
13
+ import * as tui from "@eserstack/shell/tui";
14
+ import { runtime } from "@eserstack/standards/cross-runtime";
15
+ import * as geometry from "../../engine/geometry.js";
16
+ import * as scheduler from "../../render/scheduler.js";
17
+ import * as compositor from "./compositor.js";
18
+ import * as inputSource from "./input-source.js";
19
+ const encoder = new TextEncoder();
20
+ export const createTuiFrontend = (opts) => {
21
+ const { transport, keymap } = opts;
22
+ const widgets = new Map();
23
+ let scene = null;
24
+ let running = false;
25
+ let stopped = false;
26
+ let abort = null;
27
+ let sizeTimer = null;
28
+ let lastViewport = { cols: 80, rows: 24 };
29
+ const write = (s) => runtime.process.writeToStdout(encoder.encode(s));
30
+ const ensureWidget = (id) => {
31
+ const existing = widgets.get(id);
32
+ if (existing !== undefined)
33
+ return existing;
34
+ const p = scene?.panes.find((pp) => pp.id === id);
35
+ const cols = p ? Math.max(1, p.geom.width - 2) : 80;
36
+ const rows = p ? Math.max(1, p.geom.height - 2) : 24;
37
+ const widget = new tui.VTermWidget(rows, cols);
38
+ widgets.set(id, widget);
39
+ return widget;
40
+ };
41
+ const reconcileWidgets = () => {
42
+ if (scene === null)
43
+ return;
44
+ const live = new Set();
45
+ for (const p of scene.panes) {
46
+ live.add(p.id);
47
+ const cols = Math.max(1, p.geom.width - 2);
48
+ const rows = Math.max(1, p.geom.height - 2);
49
+ const w = widgets.get(p.id);
50
+ if (w === undefined) {
51
+ widgets.set(p.id, new tui.VTermWidget(rows, cols));
52
+ }
53
+ else if (w.terminal.rows !== rows || w.terminal.cols !== cols) {
54
+ w.resize(rows, cols);
55
+ }
56
+ }
57
+ for (const id of [...widgets.keys()]) {
58
+ if (!live.has(id))
59
+ widgets.delete(id);
60
+ }
61
+ };
62
+ const render = (fullRedraw) => {
63
+ if (stopped || scene === null)
64
+ return;
65
+ const frame = compositor.composite(scene, { getWidget: (id) => widgets.get(id) }, { fullRedraw, statusText: opts.statusText });
66
+ let out = tui.terminal.hideCursorSeq() + frame.data;
67
+ if (opts.decorate !== undefined) {
68
+ out += opts.decorate({
69
+ regions: geometry.decorationRegions(scene.viewport, scene.chrome),
70
+ scene,
71
+ });
72
+ }
73
+ out +=
74
+ tui.ansi.moveTo(frame.cursor.row, frame.cursor.col) +
75
+ (frame.cursor.visible ? tui.terminal.showCursorSeq() : "");
76
+ write(out);
77
+ };
78
+ const frameScheduler = scheduler.createScheduler(render);
79
+ const handle = (msg) => {
80
+ switch (msg.t) {
81
+ case "scene": {
82
+ const prev = scene;
83
+ const d = msg.delta;
84
+ scene = {
85
+ tabs: d.tabs ?? prev?.tabs ?? [],
86
+ activeTab: d.activeTab ?? prev?.activeTab ?? 0,
87
+ mode: d.mode ?? prev?.mode ?? "normal",
88
+ viewport: d.viewport ?? prev?.viewport ?? lastViewport,
89
+ focusedPane: d.focusedPane !== undefined
90
+ ? d.focusedPane
91
+ : (prev?.focusedPane ?? null),
92
+ panes: d.panes ?? prev?.panes ?? [],
93
+ chrome: d.chrome ?? prev?.chrome ?? geometry.DEFAULT_CHROME,
94
+ };
95
+ const structural = msg.full ||
96
+ d.panes !== undefined ||
97
+ d.tabs !== undefined ||
98
+ d.viewport !== undefined ||
99
+ d.chrome !== undefined;
100
+ if (structural)
101
+ reconcileWidgets();
102
+ if (structural)
103
+ frameScheduler.requestFull();
104
+ else
105
+ frameScheduler.schedule();
106
+ break;
107
+ }
108
+ case "output":
109
+ ensureWidget(msg.pane).write(msg.data);
110
+ frameScheduler.schedule();
111
+ break;
112
+ case "exit":
113
+ stop();
114
+ break;
115
+ }
116
+ };
117
+ const startSizePoll = () => {
118
+ sizeTimer = setInterval(() => {
119
+ const s = tui.terminal.getTerminalSize();
120
+ if (s.cols !== lastViewport.cols || s.rows !== lastViewport.rows) {
121
+ lastViewport = { cols: s.cols, rows: s.rows };
122
+ transport.send({ t: "resize", viewport: lastViewport });
123
+ }
124
+ }, opts.sizePollMs ?? 250);
125
+ };
126
+ const stop = () => {
127
+ if (!running)
128
+ return;
129
+ running = false;
130
+ stopped = true; // make any late refresh()/render() a no-op
131
+ abort?.abort();
132
+ if (sizeTimer !== null)
133
+ clearInterval(sizeTimer);
134
+ frameScheduler.stop();
135
+ write(tui.mouse.disableMouse() +
136
+ tui.terminal.showCursorSeq() +
137
+ tui.terminal.exitAlternateScreen());
138
+ transport.close();
139
+ };
140
+ const run = async () => {
141
+ running = true;
142
+ transport.onMessage(handle);
143
+ write(tui.terminal.enterAlternateScreen() +
144
+ tui.terminal.hideCursorSeq() +
145
+ tui.terminal.clearScreenSeq() +
146
+ tui.mouse.enableMouse());
147
+ const vp = tui.terminal.getTerminalSize();
148
+ lastViewport = { cols: vp.cols, rows: vp.rows };
149
+ transport.send({ t: "attach", viewport: lastViewport });
150
+ startSizePoll();
151
+ abort = new AbortController();
152
+ await tui.withRawMode(async () => {
153
+ for await (const ev of tui.readInput(runtime.process.stdin, abort.signal)) {
154
+ if (!running)
155
+ break;
156
+ // A throwing consumer interceptor must not kill the input pump.
157
+ try {
158
+ if (ev.kind === "mouse") {
159
+ if (opts.onMouse?.(ev.event, scene) === true)
160
+ continue;
161
+ for (const m of inputSource.mouseToMessages(ev.event, scene)) {
162
+ transport.send(m);
163
+ }
164
+ }
165
+ else {
166
+ if (opts.onKey?.(ev.event, scene) === true)
167
+ continue;
168
+ for (const m of inputSource.keyToMessages(ev.event, scene?.mode ?? "normal", keymap)) {
169
+ transport.send(m);
170
+ }
171
+ }
172
+ }
173
+ catch {
174
+ // ignore a bad interceptor / dispatch and keep reading input
175
+ }
176
+ }
177
+ });
178
+ };
179
+ return {
180
+ handle,
181
+ run,
182
+ stop,
183
+ refresh: () => {
184
+ if (!stopped)
185
+ frameScheduler.schedule();
186
+ },
187
+ };
188
+ };
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The neutral wire protocol between a mux server and a frontend.
3
+ *
4
+ * The same messages flow whether the transport is an in-process channel, a
5
+ * local socket / named pipe, or a WebSocket — so the server never knows or
6
+ * cares which kind of frontend (ANSI TUI, browser xterm.js) it is feeding.
7
+ *
8
+ * @module
9
+ */
10
+ import type { Action, PaneId, Viewport } from "../engine/types.ts";
11
+ import type { SceneDelta } from "../scene/diff.ts";
12
+ /** Server → frontend. */
13
+ export type ServerToFrontend = {
14
+ readonly t: "scene";
15
+ readonly full: boolean;
16
+ readonly delta: SceneDelta;
17
+ } | {
18
+ readonly t: "output";
19
+ readonly pane: PaneId;
20
+ readonly data: string;
21
+ } | {
22
+ readonly t: "exit";
23
+ readonly code: number;
24
+ };
25
+ /** Frontend → server. */
26
+ export type FrontendToServer = {
27
+ readonly t: "attach";
28
+ readonly viewport: Viewport;
29
+ } | {
30
+ readonly t: "action";
31
+ readonly action: Action;
32
+ } | {
33
+ readonly t: "resize";
34
+ readonly viewport: Viewport;
35
+ };
36
+ /** A bidirectional message channel. In-process or serialized — same shape. */
37
+ export type Transport<Out, In> = {
38
+ send(msg: Out): void;
39
+ onMessage(handler: (msg: In) => void): void;
40
+ close(): void;
41
+ };
@@ -0,0 +1,2 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ export {};
@@ -0,0 +1,9 @@
1
+ /**
2
+ * In-process transport: a pair of directly-wired channels with no
3
+ * serialization, for running the server and a frontend in one process.
4
+ *
5
+ * @module
6
+ */
7
+ import type { Transport } from "./protocol.ts";
8
+ /** Create a connected [a, b] transport pair; a.send is delivered to b's handler. */
9
+ export declare const createInProcessPair: <A, B>() => readonly [Transport<A, B>, Transport<B, A>];