longtable 0.1.50 → 0.1.51

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "longtable",
3
- "version": "0.1.50",
3
+ "version": "0.1.51",
4
4
  "description": "Brings your own Claude Code or Codex to your team's table on longtable.chat, quietly, on your own plan.",
5
5
  "homepage": "https://longtable.chat",
6
6
  "repository": {
package/src/browser.mjs CHANGED
@@ -1,290 +1,340 @@
1
- import { spawn, spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
3
- import { join } from "node:path";
4
-
5
- // The person's browser at the table, like the one in Claude's own app: one Chrome (or Edge, Brave, Chromium) the
6
- // connection runs with no window, its profile kept in ~/.longtable/browser so sign-ins stay. Their own page watches it
7
- // live and passes their clicks and keys in (local.mjs); their AI drives the same one when "Let it open pages" is on, so
8
- // they can watch it and take over. Frames go only to their own page on this computer, never to Longtable.
9
- // It is spoken to through Chrome's DevTools pipe (no WebSocket needed on Node 20), and also listens on a DevTools port
10
- // on 127.0.0.1 only, which is how their AI's browser tools attach to it.
11
-
12
- export function findBrowser(platform = process.platform, env = process.env, exists = existsSync) {
13
- const win = (base, ...rest) => (base ? join(base, ...rest) : null);
14
- const list = platform === "win32" ? [
15
- win(env.PROGRAMFILES, "Google", "Chrome", "Application", "chrome.exe"),
16
- win(env["PROGRAMFILES(X86)"], "Google", "Chrome", "Application", "chrome.exe"),
17
- win(env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe"),
18
- win(env.PROGRAMFILES, "BraveSoftware", "Brave-Browser", "Application", "brave.exe"),
19
- win(env.LOCALAPPDATA, "BraveSoftware", "Brave-Browser", "Application", "brave.exe"),
20
- win(env["PROGRAMFILES(X86)"], "Microsoft", "Edge", "Application", "msedge.exe"),
21
- win(env.PROGRAMFILES, "Microsoft", "Edge", "Application", "msedge.exe"),
22
- ] : platform === "darwin" ? [
23
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
24
- "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
25
- "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
26
- "/Applications/Chromium.app/Contents/MacOS/Chromium",
27
- ] : ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "brave-browser", "microsoft-edge"].map((n) => {
28
- const r = spawnSync("sh", ["-c", `command -v ${n}`], { encoding: "utf8" });
29
- return r.status === 0 ? r.stdout.trim() : null;
30
- });
31
- return list.find((p) => p && exists(p)) || null;
32
- }
33
-
34
- // Only addresses a browser should be sent to from a typed bar: the web, and pages on this computer.
35
- export function addressFor(typed) {
36
- const t = String(typed ?? "").trim();
37
- if (!t) return null;
38
- if (/^about:blank$/i.test(t)) return "about:blank";
39
- const local = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(t);
40
- let url;
41
- try { url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(t) ? t : `${local ? "http" : "https"}://${t}`); } catch { return null; }
42
- return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
43
- }
44
-
45
- // Keys that are not text: their DevTools name, key code and the text they make.
46
- const KEYS = { Enter: [13, "\r"], Backspace: [8], Tab: [9], Escape: [27], Delete: [46], ArrowLeft: [37], ArrowUp: [38], ArrowRight: [39], ArrowDown: [40], Home: [36], End: [35], PageUp: [33], PageDown: [34] };
47
- const EDITS = { a: "selectAll", c: "copy", x: "cut", v: "paste", z: "undo", y: "redo" };
48
- const IDLE_MS = 30 * 60 * 1000;
49
-
50
- export class Browser {
51
- constructor(home, log) {
52
- this.profile = join(home, "browser");
53
- this.log = log;
54
- this.viewers = new Set();
55
- this.users = 0;
56
- this.page = null; // { targetId, sessionId, url, title }
57
- this.size = { w: 1280, h: 800 };
58
- this.fit = null; // the size of the picture on their screen, while someone watches
59
- this.starting = null;
60
- this.proc = null;
61
- }
62
-
63
- // Started on first use; a browser nobody watched or used for half an hour is closed.
64
- start() {
65
- if (this.ready) return Promise.resolve(this.port);
66
- this.starting ??= this.launch().finally(() => { this.starting = null; });
67
- return this.starting;
68
- }
69
-
70
- async launch() {
71
- const exe = findBrowser();
72
- if (!exe) throw new Error("No Chrome, Edge or Brave was found on this computer");
73
- mkdirSync(this.profile, { recursive: true });
74
- const portFile = join(this.profile, "DevToolsActivePort");
75
- rmSync(portFile, { force: true });
76
- const proc = spawn(exe, ["--headless=new", "--remote-debugging-pipe", "--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1",
77
- `--user-data-dir=${this.profile}`, "--no-first-run", "--no-default-browser-check", `--window-size=${this.size.w},${this.size.h}`, "about:blank"],
78
- { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"], windowsHide: true });
79
- this.proc = proc;
80
- this.calls = new Map();
81
- this.next = 1;
82
- let buf = "";
83
- proc.stdio[4].setEncoding("utf8");
84
- proc.stdio[4].on("data", (d) => {
85
- buf += d;
86
- let at;
87
- while ((at = buf.indexOf("\0")) >= 0) {
88
- const msg = buf.slice(0, at);
89
- buf = buf.slice(at + 1);
90
- try { this.got(JSON.parse(msg)); } catch (e) { this.log(`browser: a message could not be read: ${e.message}`); }
91
- }
92
- });
93
- proc.stdio[3].on("error", () => {});
94
- proc.on("exit", () => {
95
- if (this.proc !== proc) return;
96
- clearInterval(this.idle);
97
- this.proc = null;
98
- this.ready = false;
99
- this.port = 0;
100
- this.page = null;
101
- for (const { fail } of this.calls.values()) fail(new Error("the browser closed"));
102
- this.calls.clear();
103
- this.tell({ closed: true });
104
- });
105
- try {
106
- // Chrome writes the port it took once it listens.
107
- for (let i = 0; i < 150 && !this.port; i++) {
108
- await new Promise((r) => setTimeout(r, 100));
109
- if (!this.proc) throw new Error("the browser did not start (is its profile open in another window?)");
110
- try { this.port = Number(readFileSync(portFile, "utf8").split("\n")[0]) || 0; } catch {}
111
- }
112
- if (!this.port) throw new Error("the browser did not say where it listens");
113
- await this.call("Target.setDiscoverTargets", { discover: true });
114
- const { targetInfos } = await this.call("Target.getTargets");
115
- const page = targetInfos.find((t) => t.type === "page");
116
- await this.show(page ? page.targetId : (await this.call("Target.createTarget", { url: "about:blank" })).targetId);
117
- } catch (e) {
118
- this.close();
119
- throw e;
120
- }
121
- this.ready = true;
122
- this.idle = setInterval(() => {
123
- if (!this.viewers.size && !this.users && Date.now() - this.used > IDLE_MS) this.close();
124
- }, 60 * 1000);
125
- this.idle.unref?.();
126
- this.used = Date.now();
127
- this.log("browser: started");
128
- return this.port;
129
- }
130
-
131
- close() {
132
- clearInterval(this.idle);
133
- this.ready = false;
134
- const p = this.proc;
135
- this.proc = null;
136
- this.port = 0;
137
- this.page = null;
138
- if (p) { try { p.kill(); } catch {} }
139
- }
140
-
141
- call(method, params = {}, sessionId) {
142
- if (!this.proc) return Promise.reject(new Error("the browser is not running"));
143
- const id = this.next++;
144
- return new Promise((ok, fail) => {
145
- this.calls.set(id, { ok, fail });
146
- this.proc.stdio[3].write(`${JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })}\0`);
147
- });
148
- }
149
-
150
- got(msg) {
151
- if (msg.id) {
152
- const c = this.calls.get(msg.id);
153
- if (!c) return;
154
- this.calls.delete(msg.id);
155
- return msg.error ? c.fail(new Error(msg.error.message)) : c.ok(msg.result || {});
156
- }
157
- const p = msg.params || {};
158
- if (msg.method === "Page.screencastFrame") {
159
- this.call("Page.screencastFrameAck", { sessionId: p.sessionId }, msg.sessionId).catch(() => {});
160
- if (msg.sessionId !== this.page?.sessionId) return;
161
- this.size = { w: p.metadata.deviceWidth, h: p.metadata.deviceHeight };
162
- return this.tell({ frame: p.data });
163
- }
164
- // A tab their AI opened is the one shown, as it would be in front of them.
165
- if (msg.method === "Target.targetCreated" && this.ready && p.targetInfo?.type === "page" && p.targetInfo.targetId !== this.page?.targetId) {
166
- return this.show(p.targetInfo.targetId).catch((e) => this.log(`browser: could not show a new tab: ${e.message}`));
167
- }
168
- if (msg.method === "Target.targetInfoChanged" && p.targetInfo?.targetId === this.page?.targetId) {
169
- this.page.url = p.targetInfo.url;
170
- this.page.title = p.targetInfo.title;
171
- return this.tell({ url: this.page.url, title: this.page.title });
172
- }
173
- if (msg.method === "Target.targetDestroyed" && p.targetId === this.page?.targetId) {
174
- this.page = null;
175
- return this.call("Target.getTargets").then(({ targetInfos }) => {
176
- const other = targetInfos.find((t) => t.type === "page");
177
- return other ? this.show(other.targetId) : this.call("Target.createTarget", { url: "about:blank" });
178
- }).catch((e) => this.log(`browser: no tab left to show: ${e.message}`));
179
- }
180
- }
181
-
182
- async show(targetId) {
183
- const { sessionId } = await this.call("Target.attachToTarget", { targetId, flatten: true });
184
- const { targetInfo } = await this.call("Target.getTargetInfo", { targetId });
185
- this.page = { targetId, sessionId, url: targetInfo?.url || "", title: targetInfo?.title || "" };
186
- await this.call("Page.enable", {}, sessionId);
187
- this.tell({ url: this.page.url, title: this.page.title });
188
- if (this.viewers.size) { await this.fitTo(); await this.cast(); }
189
- }
190
-
191
- // The page laid out at the size it is shown at, sharp on their screen, as in Claude's own browser. With nobody
192
- // watching it goes back to the browser's own window size, which is what their AI then sees.
193
- async fitTo() {
194
- const s = this.page?.sessionId;
195
- if (!s) return;
196
- if (this.fit && this.viewers.size) await this.call("Emulation.setDeviceMetricsOverride", { width: this.fit.w, height: this.fit.h, deviceScaleFactor: this.fit.dpr, mobile: false }, s);
197
- else await this.call("Emulation.clearDeviceMetricsOverride", {}, s);
198
- }
199
-
200
- // Frames from the tab shown, once (a second start is refused by the browser).
201
- async cast() {
202
- const s = this.page?.sessionId;
203
- if (!s || this.casting === s) return;
204
- this.casting = s;
205
- try { await this.call("Page.startScreencast", { format: "jpeg", quality: 70, maxWidth: 4000, maxHeight: 4000 }, s); }
206
- catch (e) { this.casting = null; throw e; }
207
- }
208
-
209
- tell(event) { for (const v of this.viewers) v(event); }
210
-
211
- // Someone's page watching. It hears where the browser is at once, then every frame.
212
- async watch(viewer) {
213
- this.viewers.add(viewer);
214
- this.used = Date.now();
215
- await this.start();
216
- viewer({ url: this.page?.url || "", title: this.page?.title || "" });
217
- await this.fitTo();
218
- await this.cast();
219
- // A still page sends no new frame, so the one on screen is asked for.
220
- const { data } = await this.call("Page.captureScreenshot", { format: "jpeg", quality: 70 }, this.page.sessionId);
221
- viewer({ frame: data });
222
- }
223
-
224
- unwatch(viewer) {
225
- this.viewers.delete(viewer);
226
- this.used = Date.now();
227
- if (!this.viewers.size && this.page) {
228
- this.casting = null;
229
- this.fit = null;
230
- this.call("Page.stopScreencast", {}, this.page.sessionId).catch(() => {});
231
- this.fitTo().catch(() => {});
232
- }
233
- }
234
-
235
- // Their AI's run uses it: it is started for that, and kept open until the run is done.
236
- async hold() { this.users++; this.used = Date.now(); try { return await this.start(); } catch (e) { this.users--; throw e; } }
237
- release() { this.users = Math.max(0, this.users - 1); this.used = Date.now(); }
238
-
239
- // What their page asks of it. Points are given as fractions of the picture, so any size of screen lands right.
240
- async act(a) {
241
- this.used = Date.now();
242
- // The size it is shown at, which may come before the browser has finished starting: kept, and used when it has.
243
- if (a.do === "size") {
244
- const n = (v) => Math.round(Math.max(200, Math.min(3000, Number(v) || 200)));
245
- this.fit = { w: n(a.w), h: n(a.h), dpr: Math.max(1, Math.min(3, Number(a.dpr) || 1)) };
246
- if (!this.page || !this.viewers.size) return null;
247
- // Frames at the new size: the old ones are stopped and started again.
248
- this.casting = null;
249
- await this.call("Page.stopScreencast", {}, this.page.sessionId).catch(() => {});
250
- await this.fitTo();
251
- return this.cast();
252
- }
253
- if (!this.page) throw new Error("the browser is not open");
254
- const s = this.page.sessionId;
255
- const at = (n, size) => Math.max(0, Math.min(size, Number(n) * size));
256
- switch (a.do) {
257
- case "go": {
258
- const url = addressFor(a.url);
259
- if (!url) throw new Error("that is not a web address");
260
- return this.call("Page.navigate", { url }, s);
261
- }
262
- case "back": case "forward": {
263
- const { currentIndex, entries } = await this.call("Page.getNavigationHistory", {}, s);
264
- const e = entries[currentIndex + (a.do === "back" ? -1 : 1)];
265
- return e ? this.call("Page.navigateToHistoryEntry", { entryId: e.id }, s) : null;
266
- }
267
- case "reload": return this.call("Page.reload", {}, s);
268
- case "click": {
269
- const x = at(a.x, this.size.w), y = at(a.y, this.size.h);
270
- await this.call("Input.dispatchMouseEvent", { type: "mouseMoved", x, y }, s);
271
- await this.call("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "left", clickCount: 1 }, s);
272
- return this.call("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "left", clickCount: 1 }, s);
273
- }
274
- case "scroll":
275
- return this.call("Input.dispatchMouseEvent", { type: "mouseWheel", x: at(a.x, this.size.w), y: at(a.y, this.size.h), deltaX: 0, deltaY: Math.max(-2000, Math.min(2000, Number(a.dy) || 0)) }, s);
276
- case "type": return this.call("Input.insertText", { text: String(a.text ?? "").slice(0, 8000) }, s);
277
- case "key": {
278
- const mods = (a.ctrl ? 2 : 0) | (a.meta ? 4 : 0) | (a.shift ? 8 : 0) | (a.alt ? 1 : 0);
279
- const k = String(a.key ?? "");
280
- const edit = (a.ctrl || a.meta) && EDITS[k.toLowerCase()];
281
- const named = KEYS[k];
282
- if (!named && !edit) return null;
283
- const base = { key: k, code: named ? k : `Key${k.toUpperCase()}`, windowsVirtualKeyCode: named ? named[0] : k.toUpperCase().charCodeAt(0), modifiers: mods };
284
- await this.call("Input.dispatchKeyEvent", { type: "keyDown", ...base, ...(named?.[1] && !mods ? { text: named[1] } : {}), ...(edit ? { commands: [edit] } : {}) }, s);
285
- return this.call("Input.dispatchKeyEvent", { type: "keyUp", ...base }, s);
286
- }
287
- default: throw new Error("unknown browser step");
288
- }
289
- }
290
- }
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ // The person's browser at the table, like the one in Claude's own app: one Chrome (or Edge, Brave, Chromium) the
6
+ // connection runs with no window, its profile kept in ~/.longtable/browser so sign-ins stay. Their own page watches it
7
+ // live and passes their clicks and keys in (local.mjs); their AI drives the same one when "Let it open pages" is on, so
8
+ // they can watch it and take over. Frames go only to their own page on this computer, never to Longtable.
9
+ // It is spoken to through Chrome's DevTools pipe (no WebSocket needed on Node 20), and also listens on a DevTools port
10
+ // on 127.0.0.1 only, which is how their AI's browser tools attach to it.
11
+
12
+ export function findBrowser(platform = process.platform, env = process.env, exists = existsSync) {
13
+ const win = (base, ...rest) => (base ? join(base, ...rest) : null);
14
+ const list = platform === "win32" ? [
15
+ win(env.PROGRAMFILES, "Google", "Chrome", "Application", "chrome.exe"),
16
+ win(env["PROGRAMFILES(X86)"], "Google", "Chrome", "Application", "chrome.exe"),
17
+ win(env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe"),
18
+ win(env.PROGRAMFILES, "BraveSoftware", "Brave-Browser", "Application", "brave.exe"),
19
+ win(env.LOCALAPPDATA, "BraveSoftware", "Brave-Browser", "Application", "brave.exe"),
20
+ win(env["PROGRAMFILES(X86)"], "Microsoft", "Edge", "Application", "msedge.exe"),
21
+ win(env.PROGRAMFILES, "Microsoft", "Edge", "Application", "msedge.exe"),
22
+ ] : platform === "darwin" ? [
23
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
24
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
25
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
26
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
27
+ ] : ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "brave-browser", "microsoft-edge"].map((n) => {
28
+ const r = spawnSync("sh", ["-c", `command -v ${n}`], { encoding: "utf8" });
29
+ return r.status === 0 ? r.stdout.trim() : null;
30
+ });
31
+ return list.find((p) => p && exists(p)) || null;
32
+ }
33
+
34
+ // Only addresses a browser should be sent to from a typed bar: the web, and pages on this computer.
35
+ export function addressFor(typed) {
36
+ const t = String(typed ?? "").trim();
37
+ if (!t) return null;
38
+ if (/^about:blank$/i.test(t)) return "about:blank";
39
+ const local = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(t);
40
+ let url;
41
+ try { url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(t) ? t : `${local ? "http" : "https"}://${t}`); } catch { return null; }
42
+ return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
43
+ }
44
+
45
+ // Keys that are not text: their DevTools name, key code and the text they make.
46
+ const KEYS = { Enter: [13, "\r"], Backspace: [8], Tab: [9], Escape: [27], Delete: [46], ArrowLeft: [37], ArrowUp: [38], ArrowRight: [39], ArrowDown: [40], Home: [36], End: [35], PageUp: [33], PageDown: [34] };
47
+ const EDITS = { a: "selectAll", c: "copy", x: "cut", v: "paste", z: "undo", y: "redo" };
48
+ const IDLE_MS = 30 * 60 * 1000;
49
+
50
+ export class Browser {
51
+ constructor(home, log) {
52
+ this.profile = join(home, "browser");
53
+ this.log = log;
54
+ this.viewers = new Set();
55
+ this.users = 0;
56
+ this.page = null; // the tab shown: { targetId, sessionId, url, title }
57
+ this.tabs = new Map(); // every tab, by id: { id, url, title }; as many as they or their AI open
58
+ this.sessions = new Map(); // tab id -> the session it is spoken to on
59
+ this.size = { w: 1280, h: 800 };
60
+ this.fit = null; // the size of the picture on their screen, while someone watches
61
+ this.starting = null;
62
+ this.proc = null;
63
+ }
64
+
65
+ // Started on first use; a browser nobody watched or used for half an hour is closed.
66
+ start() {
67
+ if (this.ready) return Promise.resolve(this.port);
68
+ this.starting ??= this.launch().finally(() => { this.starting = null; });
69
+ return this.starting;
70
+ }
71
+
72
+ async launch() {
73
+ const exe = findBrowser();
74
+ if (!exe) throw new Error("No Chrome, Edge or Brave was found on this computer");
75
+ mkdirSync(this.profile, { recursive: true });
76
+ const portFile = join(this.profile, "DevToolsActivePort");
77
+ rmSync(portFile, { force: true });
78
+ const proc = spawn(exe, ["--headless=new", "--remote-debugging-pipe", "--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1",
79
+ `--user-data-dir=${this.profile}`, "--no-first-run", "--no-default-browser-check", `--window-size=${this.size.w},${this.size.h}`, "about:blank"],
80
+ { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"], windowsHide: true });
81
+ this.proc = proc;
82
+ this.calls = new Map();
83
+ this.next = 1;
84
+ let buf = "";
85
+ proc.stdio[4].setEncoding("utf8");
86
+ proc.stdio[4].on("data", (d) => {
87
+ buf += d;
88
+ let at;
89
+ while ((at = buf.indexOf("\0")) >= 0) {
90
+ const msg = buf.slice(0, at);
91
+ buf = buf.slice(at + 1);
92
+ try { this.got(JSON.parse(msg)); } catch (e) { this.log(`browser: a message could not be read: ${e.message}`); }
93
+ }
94
+ });
95
+ proc.stdio[3].on("error", () => {});
96
+ proc.on("exit", () => {
97
+ if (this.proc !== proc) return;
98
+ clearInterval(this.idle);
99
+ this.proc = null;
100
+ this.ready = false;
101
+ this.port = 0;
102
+ this.page = null;
103
+ this.tabs.clear();
104
+ this.sessions.clear();
105
+ for (const { fail } of this.calls.values()) fail(new Error("the browser closed"));
106
+ this.calls.clear();
107
+ this.tell({ closed: true });
108
+ });
109
+ try {
110
+ // Chrome writes the port it took once it listens.
111
+ for (let i = 0; i < 150 && !this.port; i++) {
112
+ await new Promise((r) => setTimeout(r, 100));
113
+ if (!this.proc) throw new Error("the browser did not start (is its profile open in another window?)");
114
+ try { this.port = Number(readFileSync(portFile, "utf8").split("\n")[0]) || 0; } catch {}
115
+ }
116
+ if (!this.port) throw new Error("the browser did not say where it listens");
117
+ await this.call("Target.setDiscoverTargets", { discover: true });
118
+ const { targetInfos } = await this.call("Target.getTargets");
119
+ for (const t of targetInfos) this.note(t);
120
+ const page = targetInfos.find((t) => this.tabs.has(t.targetId));
121
+ await this.show(page ? page.targetId : (await this.call("Target.createTarget", { url: "about:blank" })).targetId);
122
+ } catch (e) {
123
+ this.close();
124
+ throw e;
125
+ }
126
+ this.ready = true;
127
+ this.idle = setInterval(() => {
128
+ if (!this.viewers.size && !this.users && Date.now() - this.used > IDLE_MS) this.close();
129
+ }, 60 * 1000);
130
+ this.idle.unref?.();
131
+ this.used = Date.now();
132
+ this.log("browser: started");
133
+ return this.port;
134
+ }
135
+
136
+ close() {
137
+ clearInterval(this.idle);
138
+ this.ready = false;
139
+ const p = this.proc;
140
+ this.proc = null;
141
+ this.port = 0;
142
+ this.page = null;
143
+ this.tabs.clear();
144
+ this.sessions.clear();
145
+ if (p) { try { p.kill(); } catch {} }
146
+ }
147
+
148
+ call(method, params = {}, sessionId) {
149
+ if (!this.proc) return Promise.reject(new Error("the browser is not running"));
150
+ const id = this.next++;
151
+ return new Promise((ok, fail) => {
152
+ this.calls.set(id, { ok, fail });
153
+ this.proc.stdio[3].write(`${JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })}\0`);
154
+ });
155
+ }
156
+
157
+ got(msg) {
158
+ if (msg.id) {
159
+ const c = this.calls.get(msg.id);
160
+ if (!c) return;
161
+ this.calls.delete(msg.id);
162
+ return msg.error ? c.fail(new Error(msg.error.message)) : c.ok(msg.result || {});
163
+ }
164
+ const p = msg.params || {};
165
+ if (msg.method === "Page.screencastFrame") {
166
+ this.call("Page.screencastFrameAck", { sessionId: p.sessionId }, msg.sessionId).catch(() => {});
167
+ if (msg.sessionId !== this.page?.sessionId) return;
168
+ this.size = { w: p.metadata.deviceWidth, h: p.metadata.deviceHeight };
169
+ return this.tell({ frame: p.data });
170
+ }
171
+ // A new tab, theirs or their AI's, is the one shown, as it would be in front of them.
172
+ if (msg.method === "Target.targetCreated" && this.note(p.targetInfo)) {
173
+ this.tellTabs();
174
+ if (this.ready) this.show(p.targetInfo.targetId).catch((e) => this.log(`browser: could not show a new tab: ${e.message}`));
175
+ return;
176
+ }
177
+ if (msg.method === "Target.targetInfoChanged" && this.note(p.targetInfo)) {
178
+ this.tellTabs();
179
+ if (p.targetInfo.targetId === this.page?.targetId) {
180
+ this.page.url = p.targetInfo.url;
181
+ this.page.title = p.targetInfo.title;
182
+ this.tell({ url: this.page.url, title: this.page.title });
183
+ }
184
+ return;
185
+ }
186
+ if (msg.method === "Target.targetDestroyed" && this.tabs.delete(p.targetId)) {
187
+ this.sessions.delete(p.targetId);
188
+ this.tellTabs();
189
+ if (p.targetId !== this.page?.targetId) return;
190
+ this.page = null;
191
+ this.casting = null;
192
+ // The last tab closed: a blank one takes its place, as a browser window would keep one open.
193
+ const next = [...this.tabs.keys()].pop();
194
+ return (next ? this.show(next) : this.call("Target.createTarget", { url: "about:blank" }))
195
+ .catch((e) => this.log(`browser: no tab left to show: ${e.message}`));
196
+ }
197
+ }
198
+
199
+ // A page target is a tab (never the browser's own pages, such as DevTools). Kept with its address and title.
200
+ note(t) {
201
+ if (!t || t.type !== "page" || /^(devtools|chrome-extension):/.test(t.url || "")) return false;
202
+ this.tabs.set(t.targetId, { id: t.targetId, url: t.url || "", title: t.title || "" });
203
+ return true;
204
+ }
205
+
206
+ tellTabs() { this.tell({ tabs: [...this.tabs.values()], active: this.page?.targetId || null }); }
207
+
208
+ // One switch at a time, in the order asked: a tab picked just after others opened is the one left showing.
209
+ show(targetId) {
210
+ this.showing = (this.showing || Promise.resolve()).catch(() => {}).then(() => this.showNow(targetId));
211
+ return this.showing;
212
+ }
213
+
214
+ async showNow(targetId) {
215
+ if (this.page?.targetId === targetId || !this.proc) return;
216
+ // The tab shown before stops sending pictures.
217
+ if (this.page && this.casting) { this.call("Page.stopScreencast", {}, this.page.sessionId).catch(() => {}); this.casting = null; }
218
+ let sessionId = this.sessions.get(targetId);
219
+ if (!sessionId) {
220
+ ({ sessionId } = await this.call("Target.attachToTarget", { targetId, flatten: true }));
221
+ this.sessions.set(targetId, sessionId);
222
+ await this.call("Page.enable", {}, sessionId);
223
+ }
224
+ const { targetInfo } = await this.call("Target.getTargetInfo", { targetId });
225
+ this.page = { targetId, sessionId, url: targetInfo?.url || "", title: targetInfo?.title || "" };
226
+ this.tell({ url: this.page.url, title: this.page.title });
227
+ this.tellTabs();
228
+ if (this.viewers.size) {
229
+ await this.fitTo();
230
+ await this.cast();
231
+ const { data } = await this.call("Page.captureScreenshot", { format: "jpeg", quality: 70 }, sessionId);
232
+ this.tell({ frame: data });
233
+ }
234
+ }
235
+
236
+ // The page laid out at the size it is shown at, sharp on their screen, as in Claude's own browser. With nobody
237
+ // watching it goes back to the browser's own window size, which is what their AI then sees.
238
+ async fitTo() {
239
+ const s = this.page?.sessionId;
240
+ if (!s) return;
241
+ if (this.fit && this.viewers.size) await this.call("Emulation.setDeviceMetricsOverride", { width: this.fit.w, height: this.fit.h, deviceScaleFactor: this.fit.dpr, mobile: false }, s);
242
+ else await this.call("Emulation.clearDeviceMetricsOverride", {}, s);
243
+ }
244
+
245
+ // Frames from the tab shown, once (a second start is refused by the browser).
246
+ async cast() {
247
+ const s = this.page?.sessionId;
248
+ if (!s || this.casting === s) return;
249
+ this.casting = s;
250
+ try { await this.call("Page.startScreencast", { format: "jpeg", quality: 70, maxWidth: 4000, maxHeight: 4000 }, s); }
251
+ catch (e) { this.casting = null; throw e; }
252
+ }
253
+
254
+ tell(event) { for (const v of this.viewers) v(event); }
255
+
256
+ // Someone's page watching. It hears where the browser is at once, then every frame.
257
+ async watch(viewer) {
258
+ this.viewers.add(viewer);
259
+ this.used = Date.now();
260
+ await this.start();
261
+ viewer({ url: this.page?.url || "", title: this.page?.title || "" });
262
+ viewer({ tabs: [...this.tabs.values()], active: this.page?.targetId || null });
263
+ await this.fitTo();
264
+ await this.cast();
265
+ // A still page sends no new frame, so the one on screen is asked for.
266
+ const { data } = await this.call("Page.captureScreenshot", { format: "jpeg", quality: 70 }, this.page.sessionId);
267
+ viewer({ frame: data });
268
+ }
269
+
270
+ unwatch(viewer) {
271
+ this.viewers.delete(viewer);
272
+ this.used = Date.now();
273
+ if (!this.viewers.size && this.page) {
274
+ this.casting = null;
275
+ this.fit = null;
276
+ this.call("Page.stopScreencast", {}, this.page.sessionId).catch(() => {});
277
+ this.fitTo().catch(() => {});
278
+ }
279
+ }
280
+
281
+ // Their AI's run uses it: it is started for that, and kept open until the run is done.
282
+ async hold() { this.users++; this.used = Date.now(); try { return await this.start(); } catch (e) { this.users--; throw e; } }
283
+ release() { this.users = Math.max(0, this.users - 1); this.used = Date.now(); }
284
+
285
+ // What their page asks of it. Points are given as fractions of the picture, so any size of screen lands right.
286
+ async act(a) {
287
+ this.used = Date.now();
288
+ // The size it is shown at, which may come before the browser has finished starting: kept, and used when it has.
289
+ if (a.do === "size") {
290
+ const n = (v) => Math.round(Math.max(200, Math.min(3000, Number(v) || 200)));
291
+ this.fit = { w: n(a.w), h: n(a.h), dpr: Math.max(1, Math.min(3, Number(a.dpr) || 1)) };
292
+ if (!this.page || !this.viewers.size) return null;
293
+ // Frames at the new size: the old ones are stopped and started again.
294
+ this.casting = null;
295
+ await this.call("Page.stopScreencast", {}, this.page.sessionId).catch(() => {});
296
+ await this.fitTo();
297
+ return this.cast();
298
+ }
299
+ if (!this.page) throw new Error("the browser is not open");
300
+ const s = this.page.sessionId;
301
+ const at = (n, size) => Math.max(0, Math.min(size, Number(n) * size));
302
+ switch (a.do) {
303
+ case "go": {
304
+ const url = addressFor(a.url);
305
+ if (!url) throw new Error("that is not a web address");
306
+ return this.call("Page.navigate", { url }, s);
307
+ }
308
+ case "back": case "forward": {
309
+ const { currentIndex, entries } = await this.call("Page.getNavigationHistory", {}, s);
310
+ const e = entries[currentIndex + (a.do === "back" ? -1 : 1)];
311
+ return e ? this.call("Page.navigateToHistoryEntry", { entryId: e.id }, s) : null;
312
+ }
313
+ case "reload": return this.call("Page.reload", {}, s);
314
+ // Tabs, with no limit: their page warns past a sensible number, nothing here refuses one.
315
+ case "tab": return this.tabs.has(a.id) ? this.show(a.id) : null;
316
+ case "newtab": return this.call("Target.createTarget", { url: addressFor(a.url) || "about:blank" });
317
+ case "closetab": return this.tabs.has(a.id) ? this.call("Target.closeTarget", { targetId: a.id }) : null;
318
+ case "click": {
319
+ const x = at(a.x, this.size.w), y = at(a.y, this.size.h);
320
+ await this.call("Input.dispatchMouseEvent", { type: "mouseMoved", x, y }, s);
321
+ await this.call("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "left", clickCount: 1 }, s);
322
+ return this.call("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "left", clickCount: 1 }, s);
323
+ }
324
+ case "scroll":
325
+ return this.call("Input.dispatchMouseEvent", { type: "mouseWheel", x: at(a.x, this.size.w), y: at(a.y, this.size.h), deltaX: 0, deltaY: Math.max(-2000, Math.min(2000, Number(a.dy) || 0)) }, s);
326
+ case "type": return this.call("Input.insertText", { text: String(a.text ?? "").slice(0, 8000) }, s);
327
+ case "key": {
328
+ const mods = (a.ctrl ? 2 : 0) | (a.meta ? 4 : 0) | (a.shift ? 8 : 0) | (a.alt ? 1 : 0);
329
+ const k = String(a.key ?? "");
330
+ const edit = (a.ctrl || a.meta) && EDITS[k.toLowerCase()];
331
+ const named = KEYS[k];
332
+ if (!named && !edit) return null;
333
+ const base = { key: k, code: named ? k : `Key${k.toUpperCase()}`, windowsVirtualKeyCode: named ? named[0] : k.toUpperCase().charCodeAt(0), modifiers: mods };
334
+ await this.call("Input.dispatchKeyEvent", { type: "keyDown", ...base, ...(named?.[1] && !mods ? { text: named[1] } : {}), ...(edit ? { commands: [edit] } : {}) }, s);
335
+ return this.call("Input.dispatchKeyEvent", { type: "keyUp", ...base }, s);
336
+ }
337
+ default: throw new Error("unknown browser step");
338
+ }
339
+ }
340
+ }
package/src/local.mjs CHANGED
@@ -1,91 +1,96 @@
1
- import { createServer } from "node:http";
2
- import { randomBytes, timingSafeEqual } from "node:crypto";
3
- import { Terminal } from "./terminal.mjs";
4
-
5
- // The bridge: a small server on this computer only (127.0.0.1), which the person's own Longtable page reaches
6
- // directly, for their terminal and their browser. Nothing sent through it passes through Longtable, so a password typed
7
- // into the terminal or a sign-in in the browser stays on this computer.
8
- // Who may use it: a page on Longtable's own address (the browser says which site a request comes from, and no site can
9
- // pretend), sent to this computer by name (so a web address made to point here cannot reach it), carrying the key of a
10
- // table whose Longtable says this connection may serve it (runner_local: only their own full Claude Code, which can
11
- // already run commands here with their approval). Each table has its own key, handed only to its own person.
12
-
13
- export function bridgeKey() { return randomBytes(24).toString("base64url"); }
14
-
15
- const same = (a, b) => typeof a === "string" && typeof b === "string" && a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
16
-
17
- // A request from Longtable's own page, sent to this computer by name.
18
- export function fromPage({ host, origin }, { port, app }) {
19
- return (host === `127.0.0.1:${port}` || host === `localhost:${port}`) && !!origin && origin === app;
20
- }
21
- // And carrying the table's key.
22
- export const keyOk = (auth, key) => !!key && same(String(auth || "").replace(/^Bearer /, ""), key);
23
-
24
- export function startBridge({ app, seats, home, browser, log }) {
25
- const origin = new URL(app).origin;
26
- const terms = new Map(); // table id -> { term, listeners }
27
- const termFor = (seat) => {
28
- let t = terms.get(seat.table_id);
29
- if (!t) {
30
- const listeners = new Set();
31
- t = { listeners, term: new Terminal(seat.terminalFolder || home, (e) => { for (const l of listeners) l(e); }) };
32
- terms.set(seat.table_id, t);
33
- }
34
- return t;
35
- };
36
- const cors = { "Access-Control-Allow-Origin": origin, Vary: "Origin", "Access-Control-Allow-Headers": "authorization, content-type",
37
- "Access-Control-Allow-Methods": "GET, POST", "Access-Control-Allow-Private-Network": "true", "Access-Control-Max-Age": "600" };
38
- const send = (res, status, body) => { res.writeHead(status, { ...cors, "Content-Type": "application/json", "Cache-Control": "no-store" }); res.end(JSON.stringify(body)); };
39
- const body = (req) => new Promise((ok, fail) => {
40
- let s = "";
41
- req.setEncoding("utf8");
42
- req.on("data", (d) => { s += d; if (s.length > 64 * 1024) { fail(new Error("too much")); req.destroy(); } });
43
- req.on("end", () => { try { ok(s ? JSON.parse(s) : {}); } catch { fail(new Error("not JSON")); } });
44
- req.on("error", fail);
45
- });
46
- // A stream of lines of JSON, kept open with a blank line now and then.
47
- const stream = (req, res, first, add, remove) => {
48
- res.writeHead(200, { ...cors, "Content-Type": "application/x-ndjson", "Cache-Control": "no-store" });
49
- const write = (e) => { res.write(`${JSON.stringify(e)}\n`); };
50
- const beat = setInterval(() => res.write("\n"), 15000);
51
- if (first) write(first);
52
- const done = () => { clearInterval(beat); remove(write); };
53
- req.on("close", done);
54
- return Promise.resolve(add(write)).catch((e) => { write({ error: e.message }); res.end(); });
55
- };
56
-
57
- const server = createServer(async (req, res) => {
58
- try {
59
- const url = new URL(req.url, "http://127.0.0.1");
60
- const port = server.address().port;
61
- const seat = seats.find((s) => s.table_id === url.searchParams.get("t") && !s.gone && s.local?.allowed);
62
- if (!fromPage(req.headers, { port, app: origin })) { res.writeHead(403); return res.end(); }
63
- if (req.method === "OPTIONS") { res.writeHead(204, cors); return res.end(); }
64
- if (!seat || !keyOk(req.headers.authorization, seat.local.key)) {
65
- return send(res, 401, { error: "not yours" });
66
- }
67
- const path = url.pathname;
68
- if (req.method === "GET" && path === "/term") {
69
- const t = termFor(seat);
70
- return stream(req, res, { state: t.term.state() }, (w) => t.listeners.add(w), (w) => t.listeners.delete(w));
71
- }
72
- if (req.method === "GET" && path === "/browser") {
73
- return stream(req, res, null, (w) => browser.watch(w), (w) => browser.unwatch(w));
74
- }
75
- if (req.method !== "POST") return send(res, 404, { error: "nothing here" });
76
- const b = await body(req);
77
- if (path === "/term") return send(res, 200, termFor(seat).term.run(b.line, { fresh: b.fresh === true }));
78
- if (path === "/term/stop") { termFor(seat).term.stop(); return send(res, 200, { ok: true }); }
79
- if (path === "/browser") { await browser.act(b); return send(res, 200, { ok: true }); }
80
- return send(res, 404, { error: "nothing here" });
81
- } catch (e) {
82
- log(`bridge: ${e.message}`);
83
- if (!res.headersSent) send(res, 500, { error: e.message });
84
- else res.end();
85
- }
86
- });
87
- return new Promise((ok, fail) => {
88
- server.once("error", fail);
89
- server.listen(0, "127.0.0.1", () => ok({ port: server.address().port, close: () => { for (const t of terms.values()) t.term.stop(); server.close(); } }));
90
- });
91
- }
1
+ import { createServer } from "node:http";
2
+ import { randomBytes, timingSafeEqual } from "node:crypto";
3
+ import { Terminal } from "./terminal.mjs";
4
+
5
+ // The bridge: a small server on this computer only (127.0.0.1), which the person's own Longtable page reaches
6
+ // directly, for their terminal and their browser. Nothing sent through it passes through Longtable, so a password typed
7
+ // into the terminal or a sign-in in the browser stays on this computer.
8
+ // Who may use it: a page on Longtable's own address (the browser says which site a request comes from, and no site can
9
+ // pretend), sent to this computer by name (so a web address made to point here cannot reach it), carrying the key of a
10
+ // table whose Longtable says this connection may serve it (runner_local: only their own full Claude Code, which can
11
+ // already run commands here with their approval). Each table has its own key, handed only to its own person.
12
+
13
+ export function bridgeKey() { return randomBytes(24).toString("base64url"); }
14
+
15
+ const same = (a, b) => typeof a === "string" && typeof b === "string" && a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
16
+
17
+ // A request from Longtable's own page, sent to this computer by name.
18
+ export function fromPage({ host, origin }, { port, app }) {
19
+ return (host === `127.0.0.1:${port}` || host === `localhost:${port}`) && !!origin && origin === app;
20
+ }
21
+ // And carrying the table's key.
22
+ export const keyOk = (auth, key) => !!key && same(String(auth || "").replace(/^Bearer /, ""), key);
23
+
24
+ export function startBridge({ app, seats, home, browser, log }) {
25
+ const origin = new URL(app).origin;
26
+ const terms = new Map(); // table id -> { term, listeners }
27
+ const termFor = (seat) => {
28
+ let t = terms.get(seat.table_id);
29
+ if (!t) {
30
+ const listeners = new Set();
31
+ t = { listeners, term: new Terminal(seat.terminalFolder || home, (e) => { for (const l of listeners) l(e); }) };
32
+ terms.set(seat.table_id, t);
33
+ }
34
+ return t;
35
+ };
36
+ const cors = { "Access-Control-Allow-Origin": origin, Vary: "Origin", "Access-Control-Allow-Headers": "authorization, content-type",
37
+ "Access-Control-Allow-Methods": "GET, POST", "Access-Control-Allow-Private-Network": "true", "Access-Control-Max-Age": "600" };
38
+ const send = (res, status, body) => { res.writeHead(status, { ...cors, "Content-Type": "application/json", "Cache-Control": "no-store" }); res.end(JSON.stringify(body)); };
39
+ const body = (req) => new Promise((ok, fail) => {
40
+ let s = "";
41
+ req.setEncoding("utf8");
42
+ req.on("data", (d) => { s += d; if (s.length > 64 * 1024) { fail(new Error("too much")); req.destroy(); } });
43
+ req.on("end", () => { try { ok(s ? JSON.parse(s) : {}); } catch { fail(new Error("not JSON")); } });
44
+ req.on("error", fail);
45
+ });
46
+ // A stream of lines of JSON, kept open with a blank line now and then.
47
+ const stream = (req, res, first, add, remove) => {
48
+ res.writeHead(200, { ...cors, "Content-Type": "application/x-ndjson", "Cache-Control": "no-store" });
49
+ const write = (e) => { res.write(`${JSON.stringify(e)}\n`); };
50
+ const beat = setInterval(() => res.write("\n"), 15000);
51
+ if (first) write(first);
52
+ const done = () => { clearInterval(beat); remove(write); };
53
+ req.on("close", done);
54
+ return Promise.resolve(add(write)).catch((e) => { write({ error: e.message }); res.end(); });
55
+ };
56
+
57
+ const server = createServer(async (req, res) => {
58
+ try {
59
+ const url = new URL(req.url, "http://127.0.0.1");
60
+ const port = server.address().port;
61
+ const seat = seats.find((s) => s.table_id === url.searchParams.get("t") && !s.gone && s.local?.allowed);
62
+ if (!fromPage(req.headers, { port, app: origin })) { res.writeHead(403); return res.end(); }
63
+ if (req.method === "OPTIONS") { res.writeHead(204, cors); return res.end(); }
64
+ if (!seat || !keyOk(req.headers.authorization, seat.local.key)) {
65
+ return send(res, 401, { error: "not yours" });
66
+ }
67
+ const path = url.pathname;
68
+ // The terminal: what it printed so far, then everything it prints. Opening it starts the shell at the page's size.
69
+ if (req.method === "GET" && path === "/term") {
70
+ const t = termFor(seat);
71
+ return stream(req, res, { data: t.term.text, all: true }, async (w) => { t.listeners.add(w); await t.term.open(url.searchParams.get("cols"), url.searchParams.get("rows")); },
72
+ (w) => t.listeners.delete(w));
73
+ }
74
+ if (req.method === "GET" && path === "/browser") {
75
+ return stream(req, res, null, (w) => browser.watch(w), (w) => browser.unwatch(w));
76
+ }
77
+ if (req.method !== "POST") return send(res, 404, { error: "nothing here" });
78
+ const b = await body(req);
79
+ // Keys as typed, or a whole command from the chat's "!".
80
+ if (path === "/term") { const t = termFor(seat).term; await (typeof b.line === "string" ? t.run(b.line) : t.write(b.data)); return send(res, 200, { ok: true }); }
81
+ if (path === "/term/size") { termFor(seat).term.resize(b.cols, b.rows); return send(res, 200, { ok: true }); }
82
+ // Closed from the page: the shell goes, and so does what it printed.
83
+ if (path === "/term/stop") { const t = termFor(seat); t.term.stop(); terms.delete(seat.table_id); return send(res, 200, { ok: true }); }
84
+ if (path === "/browser") { await browser.act(b); return send(res, 200, { ok: true }); }
85
+ return send(res, 404, { error: "nothing here" });
86
+ } catch (e) {
87
+ log(`bridge: ${e.message}`);
88
+ if (!res.headersSent) send(res, 500, { error: e.message });
89
+ else res.end();
90
+ }
91
+ });
92
+ return new Promise((ok, fail) => {
93
+ server.once("error", fail);
94
+ server.listen(0, "127.0.0.1", () => ok({ port: server.address().port, close: () => { for (const t of terms.values()) t.term.stop(); server.close(); } }));
95
+ });
96
+ }
package/src/pty.mjs ADDED
@@ -0,0 +1,60 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join, normalize, sep } from "node:path";
4
+ import { home, log } from "./store.mjs";
5
+ import { fetchChecked, ownDir } from "./update.mjs";
6
+
7
+ // A real terminal needs a pseudo-terminal, which only a small native library can give (ConPTY on Windows, forkpty on
8
+ // Mac and Linux). The connection keeps itself up to date with plain files only, so the library is not inside it: it
9
+ // is loaded from the package's own install when there is one (connecting through npm, or this repository), else
10
+ // fetched once from the npm registry for this computer, at the exact version the connection names, checked against
11
+ // the registry's fingerprint, and kept in ~/.longtable/pty/<version>. Only the one package for this system and
12
+ // processor is fetched: the prebuilt library itself, no install scripts.
13
+
14
+ const NAME = "@lydell/node-pty";
15
+ export const ptyVersion = () => JSON.parse(readFileSync(join(ownDir(), "package.json"), "utf8")).dependencies?.[NAME] || null;
16
+ export const platformPackage = (platform = process.platform, arch = process.arch) => `${NAME}-${platform}-${arch}`;
17
+
18
+ // Only plain paths inside the package.
19
+ function rel(name) {
20
+ if (!name.startsWith("package/")) return null;
21
+ const r = name.slice("package/".length);
22
+ if (!r || r.includes("\\") || r.includes("\0") || r.split("/").some((p) => p === ".." || p === "." || p === "")) return null;
23
+ return r;
24
+ }
25
+
26
+ export async function installPty(version, dir) {
27
+ const files = await fetchChecked(platformPackage(), version, 40 * 1024 * 1024);
28
+ const next = `${dir}-next`;
29
+ rmSync(next, { recursive: true, force: true });
30
+ for (const f of files) {
31
+ const r = rel(f.name);
32
+ if (!r) continue;
33
+ const to = normalize(join(next, ...r.split("/")));
34
+ if (!to.startsWith(next + sep)) throw new Error("a file would land outside its folder");
35
+ mkdirSync(dirname(to), { recursive: true });
36
+ writeFileSync(to, f.data);
37
+ // The helper programs it starts must stay runnable on Mac and Linux.
38
+ if (f.exec && process.platform !== "win32") chmodSync(to, 0o755);
39
+ }
40
+ if (!existsSync(join(next, "package.json"))) throw new Error("the terminal library came without its package");
41
+ rmSync(dir, { recursive: true, force: true });
42
+ renameSync(next, dir);
43
+ }
44
+
45
+ let loading = null;
46
+ // The library, once: from the package's own install, else from the copy kept for this computer, fetched if missing.
47
+ export function loadPty() {
48
+ loading ??= (async () => {
49
+ try { return createRequire(import.meta.url)(NAME); } catch {}
50
+ const version = ptyVersion();
51
+ if (!/^[0-9A-Za-z.-]+$/.test(version || "")) throw new Error("the connection names no terminal library");
52
+ const dir = join(home, "pty", version, platformPackage().split("/")[1]);
53
+ if (!existsSync(join(dir, "package.json"))) {
54
+ log(`terminal: fetching ${platformPackage()} ${version} for this computer`);
55
+ await installPty(version, dir);
56
+ }
57
+ return createRequire(join(dir, "package.json"))(join(dir, "lib", "index.js"));
58
+ })().catch((e) => { loading = null; throw e; });
59
+ return loading;
60
+ }
package/src/terminal.mjs CHANGED
@@ -1,117 +1,85 @@
1
- import { spawn, spawnSync } from "node:child_process";
2
- import { statSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { resolve } from "node:path";
5
-
6
- // A terminal on the person's own computer, reached only from their own page through the bridge (local.mjs). Each line
7
- // runs as its own command in the folder the terminal is in, as Claude Code's own shell tool does: a plain `cd` is kept
8
- // between lines, a running command takes what is typed next as its input, and Stop ends it with everything it started.
9
- // There is no pseudo-terminal (that needs a native package, and the self-updating connection carries only plain
10
- // files), so a program that draws the whole screen does not draw here.
11
-
12
- const KEEP = 200_000; // characters of output kept, for a page opened later
13
- const LINE_MAX = 8000;
14
-
15
- export function shellFor(line, platform = process.platform, env = process.env) {
16
- if (platform === "win32") {
17
- return { cmd: "powershell.exe", args: ["-NoLogo", "-NoProfile", "-Command", `[Console]::OutputEncoding = [Text.Encoding]::UTF8; ${line}`] };
18
- }
19
- return { cmd: env.SHELL || "/bin/bash", args: ["-lc", line] };
20
- }
21
-
22
- // What the commands run with: the person's own environment, minus the connection's own settings, and asked for plain
23
- // text (the page shows no colours).
24
- export function termEnv(env = process.env) {
25
- const out = {};
26
- for (const [k, v] of Object.entries(env)) if (!/^(LONGTABLE_|LT_)/i.test(k)) out[k] = v;
27
- return { ...out, NO_COLOR: "1", FORCE_COLOR: "0", TERM: "dumb" };
28
- }
29
-
30
- // Where a plain `cd` goes, or null when it is not a plain `cd` (a `cd` inside a longer line runs in the shell, and
31
- // the folder after it is not kept).
32
- export function cdTarget(line, cwd, home = homedir()) {
33
- const m = line.trim().match(/^(?:cd|chdir)(?:\s+(?:\/d\s+)?(.+))?$/i);
34
- if (!m || /[;&|<>]/.test(m[1] || "")) return null;
35
- let to = (m[1] || "").trim().replace(/^(["'])(.*)\1$/, "$2");
36
- if (!to) return { show: true };
37
- if (to === "~" || to.startsWith("~/") || to.startsWith("~\\")) to = home + to.slice(1);
38
- return { to: resolve(cwd, to) };
39
- }
40
-
41
- export class Terminal {
42
- constructor(cwd, emit) {
43
- this.cwd = cwd || homedir();
44
- this.text = "";
45
- this.child = null;
46
- this.emit = emit;
47
- }
48
-
49
- state() { return { cwd: this.cwd, running: !!this.child, text: this.text }; }
50
-
51
- out(text) {
52
- this.text = (this.text + text).slice(-KEEP);
53
- this.emit({ text });
54
- }
55
-
56
- // `fresh`: a command from the chat's "!", which never goes into a program already running.
57
- run(raw, { fresh = false } = {}) {
58
- const line = String(raw ?? "").replace(/\r/g, "").slice(0, LINE_MAX);
59
- if (this.child) {
60
- if (fresh) return { busy: true };
61
- this.out(`${line}\n`);
62
- this.child.stdin.write(`${line}\n`, () => {});
63
- return { ok: true };
64
- }
65
- this.out(`${this.cwd}> ${line}\n`);
66
- if (!line.trim()) return { ok: true };
67
- if (/^\s*(clear|cls)\s*$/i.test(line)) { this.text = ""; this.emit({ clear: true }); return { ok: true }; }
68
- const cd = cdTarget(line, this.cwd);
69
- if (cd) {
70
- if (cd.show) this.out(`${this.cwd}\n`);
71
- else {
72
- let dir = false;
73
- try { dir = statSync(cd.to).isDirectory(); } catch {}
74
- if (dir) { this.cwd = cd.to; this.emit({ cwd: this.cwd }); } else this.out(`No such folder: ${cd.to}\n`);
75
- }
76
- return { ok: true };
77
- }
78
- const { cmd, args } = shellFor(line);
79
- let child;
80
- try {
81
- child = spawn(cmd, args, { cwd: this.cwd, env: termEnv(), windowsHide: true, detached: process.platform !== "win32" });
82
- } catch (e) {
83
- this.out(`Could not start it: ${e.message}\n`);
84
- return { ok: false };
85
- }
86
- this.child = child;
87
- this.emit({ running: true });
88
- child.stdout.setEncoding("utf8");
89
- child.stderr.setEncoding("utf8");
90
- child.stdout.on("data", (d) => this.out(d));
91
- child.stderr.on("data", (d) => this.out(d));
92
- child.stdin.on("error", () => {});
93
- let done = false;
94
- const finish = (code, why) => {
95
- if (done) return;
96
- done = true;
97
- if (this.child === child) this.child = null;
98
- if (why) this.out(`${why}\n`);
99
- else if (code) this.out(`(exit ${code})\n`);
100
- this.emit({ running: false });
101
- };
102
- child.on("error", (e) => finish(1, `Could not start it: ${e.message}`));
103
- child.on("close", (code) => finish(code));
104
- return { ok: true };
105
- }
106
-
107
- // Stop, as Ctrl+C would: the command and everything it started.
108
- stop() {
109
- const child = this.child;
110
- if (!child?.pid) return;
111
- try {
112
- if (process.platform === "win32") spawnSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
113
- else process.kill(-child.pid, "SIGTERM");
114
- } catch { try { child.kill(); } catch {} }
115
- this.out("^C\n");
116
- }
117
- }
1
+ import { homedir } from "node:os";
2
+ import { loadPty } from "./pty.mjs";
3
+
4
+ // A terminal on the person's own computer, reached only from their own page through the bridge (local.mjs): their
5
+ // own shell in a real pseudo-terminal (pty.mjs), as in any terminal app. Colours, prompts, arrow keys, Tab completion,
6
+ // Ctrl+C and full-screen programs all work, because the page runs a real terminal (xterm.js) and every key goes
7
+ // straight to the shell. It starts in the folder they connected from and lives until it exits or they close it; what it
8
+ // printed is kept, so a page opened later sees the screen as it was.
9
+
10
+ const KEEP = 400_000; // characters of output kept for a page that opens later
11
+
12
+ export function shellFor(platform = process.platform, env = process.env) {
13
+ if (platform === "win32") return { cmd: "powershell.exe", args: ["-NoLogo"] };
14
+ return { cmd: env.SHELL || "/bin/bash", args: ["-l"] };
15
+ }
16
+
17
+ // What the shell runs with: the person's own environment, minus the connection's own settings, as a colour terminal.
18
+ export function termEnv(env = process.env) {
19
+ const out = {};
20
+ for (const [k, v] of Object.entries(env)) if (!/^(LONGTABLE_|LT_)/i.test(k) && k !== "NO_COLOR" && k !== "FORCE_COLOR") out[k] = v;
21
+ return { ...out, TERM: "xterm-256color", COLORTERM: "truecolor" };
22
+ }
23
+
24
+ const size = (n, lo, hi, d) => Math.max(lo, Math.min(hi, Math.round(Number(n)) || d));
25
+
26
+ export class Terminal {
27
+ constructor(cwd, emit, load = loadPty) {
28
+ this.cwd = cwd || homedir();
29
+ this.emit = emit;
30
+ this.load = load;
31
+ this.text = "";
32
+ this.proc = null;
33
+ this.starting = null;
34
+ this.cols = 100;
35
+ this.rows = 30;
36
+ }
37
+
38
+ // The shell, started when first needed (and again after it exited).
39
+ open(cols, rows) {
40
+ if (cols) this.resize(cols, rows);
41
+ if (this.proc) return Promise.resolve();
42
+ this.starting ??= (async () => {
43
+ const pty = await this.load();
44
+ const { cmd, args } = shellFor();
45
+ const proc = pty.spawn(cmd, args, { name: "xterm-256color", cols: this.cols, rows: this.rows, cwd: this.cwd, env: termEnv() });
46
+ this.proc = proc;
47
+ proc.onData((d) => {
48
+ this.text = (this.text + d).slice(-KEEP);
49
+ this.emit({ data: d });
50
+ });
51
+ proc.onExit(({ exitCode }) => {
52
+ if (this.proc !== proc) return;
53
+ this.proc = null;
54
+ const line = `\r\n[the shell ended${exitCode ? ` with ${exitCode}` : ""}; press a key to start a new one]\r\n`;
55
+ this.text = (this.text + line).slice(-KEEP);
56
+ this.emit({ data: line, exited: true });
57
+ });
58
+ })().finally(() => { this.starting = null; });
59
+ return this.starting;
60
+ }
61
+
62
+ // Keys, exactly as typed (a shell that ended starts again on the next key).
63
+ async write(data) {
64
+ const s = String(data ?? "");
65
+ if (!s) return;
66
+ if (!this.proc) await this.open();
67
+ this.proc.write(s.slice(0, 64 * 1024));
68
+ }
69
+
70
+ // A command from the chat's "!": typed in and run, as if it were typed here.
71
+ run(line) { return this.write(`${String(line ?? "").replace(/[\r\n]+/g, " ").slice(0, 8000)}\r`); }
72
+
73
+ resize(cols, rows) {
74
+ this.cols = size(cols, 20, 500, this.cols);
75
+ this.rows = size(rows, 5, 200, this.rows);
76
+ try { this.proc?.resize(this.cols, this.rows); } catch {}
77
+ }
78
+
79
+ // Closed for good from the page, or when the connection stops: the shell and everything it started.
80
+ stop() {
81
+ const p = this.proc;
82
+ this.proc = null;
83
+ try { p?.kill(); } catch {}
84
+ }
85
+ }
package/src/update.mjs CHANGED
@@ -49,6 +49,7 @@ export function untar(gz) {
49
49
  const head = buf.subarray(pos, pos + 512);
50
50
  if (head.every((b) => b === 0)) break;
51
51
  const size = parseInt(str(head.subarray(124, 136)).trim() || "0", 8);
52
+ const mode = parseInt(str(head.subarray(100, 108)).trim() || "644", 8);
52
53
  if (!Number.isFinite(size) || size < 0) throw new Error("a broken tar header");
53
54
  const type = String.fromCharCode(head[156] || 48);
54
55
  const prefix = str(head.subarray(345, 500));
@@ -59,7 +60,7 @@ export function untar(gz) {
59
60
  longName = null;
60
61
  if (type === "x") { const m = body.toString("utf8").match(/(?:^|\n)\d+ path=([^\n]*)\n/); if (m) longName = m[1]; continue; }
61
62
  if (type === "L") { longName = str(body); continue; }
62
- if (type === "0" || type === "\0" || type === "7") files.push({ name, data: Buffer.from(body) });
63
+ if (type === "0" || type === "\0" || type === "7") files.push({ name, data: Buffer.from(body), exec: (mode & 0o111) !== 0 });
63
64
  }
64
65
  return files;
65
66
  }
@@ -73,25 +74,31 @@ export function keepFile(name) {
73
74
  return null;
74
75
  }
75
76
 
76
- // Fetch that exact version from the registry, checked against the registry's fingerprint. Returns its files.
77
- export async function fetchRelease(version) {
78
- if (!/^\d+\.\d+\.\d+$/.test(version)) throw new Error(`not a version: ${version}`);
79
- const metaRes = await fetch(`${REGISTRY}/${NAME}/${version}`, { headers: { accept: "application/json" } });
80
- if (!metaRes.ok) throw new Error(`the registry has no ${NAME} ${version} yet (${metaRes.status})`);
77
+ // One exact version of one package from the registry, checked against the registry's own sha512 fingerprint and
78
+ // found where the registry keeps that package. Returns the files of its tarball.
79
+ export async function fetchChecked(name, version, max = MAX_TARBALL) {
80
+ const metaRes = await fetch(`${REGISTRY}/${name.replace("/", "%2f")}/${version}`, { headers: { accept: "application/json" } });
81
+ if (!metaRes.ok) throw new Error(`the registry has no ${name} ${version} yet (${metaRes.status})`);
81
82
  const meta = await metaRes.json();
82
83
  const tarball = meta?.dist?.tarball;
83
84
  const integrity = String(meta?.dist?.integrity || "");
84
- if (meta?.name !== NAME || meta?.version !== version) throw new Error("the registry answered for something else");
85
- if (typeof tarball !== "string" || !tarball.startsWith(`${REGISTRY}/${NAME}/-/`)) throw new Error("the package is not where the registry keeps it");
85
+ if (meta?.name !== name || meta?.version !== version) throw new Error("the registry answered for something else");
86
+ if (typeof tarball !== "string" || !tarball.startsWith(`${REGISTRY}/${name}/-/`)) throw new Error("the package is not where the registry keeps it");
86
87
  const want = integrity.match(/^sha512-([A-Za-z0-9+/=]+)$/)?.[1];
87
88
  if (!want) throw new Error("the registry gave no sha512 fingerprint");
88
89
  const res = await fetch(tarball);
89
- if (!res.ok) throw new Error(`could not download ${version} (${res.status})`);
90
+ if (!res.ok) throw new Error(`could not download ${name} ${version} (${res.status})`);
90
91
  const gz = Buffer.from(await res.arrayBuffer());
91
- if (gz.length > MAX_TARBALL) throw new Error("the package is far bigger than it should be");
92
+ if (gz.length > max) throw new Error("the package is far bigger than it should be");
92
93
  if (createHash("sha512").update(gz).digest("base64") !== want) throw new Error("the download does not match the registry's fingerprint");
94
+ return untar(gz);
95
+ }
96
+
97
+ // Fetch that exact version of the connection, keeping only its own parts. Returns its files.
98
+ export async function fetchRelease(version) {
99
+ if (!/^\d+\.\d+\.\d+$/.test(version)) throw new Error(`not a version: ${version}`);
93
100
  const files = [];
94
- for (const f of untar(gz)) { const rel = keepFile(f.name); if (rel) files.push({ rel, data: f.data }); }
101
+ for (const f of await fetchChecked(NAME, version)) { const rel = keepFile(f.name); if (rel) files.push({ rel, data: f.data }); }
95
102
  const pkg = files.find((f) => f.rel === "package.json");
96
103
  if (!pkg || JSON.parse(pkg.data.toString("utf8")).version !== version) throw new Error("the package says it is another version");
97
104
  if (!files.some((f) => f.rel === "bin/longtable.mjs")) throw new Error("the package has no connection in it");