longtable 0.1.49 → 0.1.50
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 +1 -1
- package/src/browser.mjs +290 -0
- package/src/claude.mjs +7 -6
- package/src/local.mjs +91 -0
- package/src/repo.mjs +1 -1
- package/src/run.mjs +44 -6
- package/src/terminal.mjs +117 -0
package/package.json
CHANGED
package/src/browser.mjs
ADDED
|
@@ -0,0 +1,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; // { 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
|
+
}
|
package/src/claude.mjs
CHANGED
|
@@ -171,11 +171,11 @@ export const EFFORTS = new Set(["low", "medium", "high", "xhigh", "max"]);
|
|
|
171
171
|
// through the approval server (`full.mcp`, the MCP config that starts it), where the person allows or denies each one.
|
|
172
172
|
// Their "always allow" answers come back as `full.allow`. On Mac and Linux, commands also run in Claude Code's sandbox.
|
|
173
173
|
// A job that only reads may not change files (`edit` false).
|
|
174
|
-
// A run asked for in Auto on an account that cannot use it goes again in Accept edits, rather than failing.
|
|
174
|
+
// A run asked for in Auto or Bypass on an account that cannot use it goes again in Accept edits, rather than failing.
|
|
175
175
|
export function ask(opts) {
|
|
176
176
|
return askOnce(opts).catch((e) => {
|
|
177
177
|
if (!e.noAuto) throw e;
|
|
178
|
-
log(
|
|
178
|
+
log(`${opts.full?.mode} mode is not available to this Claude Code; running in Accept edits`);
|
|
179
179
|
return askOnce({ ...opts, full: { ...opts.full, mode: "acceptEdits" } });
|
|
180
180
|
});
|
|
181
181
|
}
|
|
@@ -193,7 +193,7 @@ function askOnce({ claude, cwd, prompt, system, schema, model, tools = "Read,Gre
|
|
|
193
193
|
const args = full
|
|
194
194
|
? ["-p", "--output-format", "stream-json", "--verbose", "--no-session-persistence",
|
|
195
195
|
// Their own choice of how it asks (manual, accept edits, auto, plan), else as before: edits go ahead in work.
|
|
196
|
-
"--permission-mode", full.mode === "plan" ? "plan" : full.mode === "auto" ? "auto" : full.mode === "manual" ? "default" : full.mode === "acceptEdits" || edit ? "acceptEdits" : "default",
|
|
196
|
+
"--permission-mode", full.mode === "plan" ? "plan" : full.mode === "auto" ? "auto" : full.mode === "bypass" ? "bypassPermissions" : full.mode === "manual" ? "default" : full.mode === "acceptEdits" || edit ? "acceptEdits" : "default",
|
|
197
197
|
"--permission-prompt-tool", "mcp__longtable__approve",
|
|
198
198
|
"--mcp-config", full.mcp, "--max-turns", edit && !long ? "200" : "10000"]
|
|
199
199
|
: ["-p", "--output-format", "stream-json", "--verbose", "--no-session-persistence", "--restricted", "--permission-mode", edit ? "acceptEdits" : "dontAsk",
|
|
@@ -326,11 +326,12 @@ function askOnce({ claude, cwd, prompt, system, schema, model, tools = "Read,Gre
|
|
|
326
326
|
lines.end();
|
|
327
327
|
const procs = [...seen.values()];
|
|
328
328
|
if (ended) return reject(Object.assign(new Error(ended), { procs }));
|
|
329
|
-
// Asked for Auto on an account or model that cannot use it
|
|
330
|
-
|
|
329
|
+
// Asked for Auto or Bypass on an account or model that cannot use it (an organisation can turn Bypass off): said
|
|
330
|
+
// so, so the run is tried again without it.
|
|
331
|
+
const noAuto = (full?.mode === "auto" || full?.mode === "bypass") && (full.mode === "auto" ? /auto/i : /bypass/i).test(`${err} ${result?.is_error ? result.result || "" : ""}`)
|
|
331
332
|
&& /not (available|supported|enabled)|unavailable|unsupported|requires|disabled/i.test(`${err} ${result?.result || ""}`)
|
|
332
333
|
&& (!result || result.is_error);
|
|
333
|
-
if (noAuto) return reject(Object.assign(new Error(
|
|
334
|
+
if (noAuto) return reject(Object.assign(new Error(`${full.mode} mode is not available here`), { noAuto: true }));
|
|
334
335
|
// A session that is gone (deleted, or never written) cannot be picked up: said so, so the request starts a new one.
|
|
335
336
|
if (session?.resume && (!result || result.is_error) && /no conversation found with session id/i.test(`${err} ${result?.result || ""}`)) {
|
|
336
337
|
return reject(Object.assign(new Error("that session could not be picked up"), { noSession: true }));
|
package/src/local.mjs
ADDED
|
@@ -0,0 +1,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
|
+
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
|
+
}
|
package/src/repo.mjs
CHANGED
|
@@ -335,7 +335,7 @@ const LONGTABLE = { ...quiet, GIT_AUTHOR_NAME: "Longtable", GIT_AUTHOR_EMAIL: "l
|
|
|
335
335
|
// Who a copy's own commits (its start, a clean copy, catching up, a take-back) are signed by: the person whose
|
|
336
336
|
// computer makes them, as git already knows them, the same way landWork signs a change. Vercel's free plan refuses
|
|
337
337
|
// to build a private repository's commit whose author is not the account's own, so a copy signed "Longtable" was
|
|
338
|
-
// never put up (found on
|
|
338
|
+
// never put up (found on a real team's preview hosting, 26 Oct 2026). "Longtable" only when this computer has no git identity.
|
|
339
339
|
function signer(G) {
|
|
340
340
|
let name = "";
|
|
341
341
|
let email = "";
|
package/src/run.mjs
CHANGED
|
@@ -23,6 +23,8 @@ import { askCodex, codexLimits, findCodex } from "./codex.mjs";
|
|
|
23
23
|
import { packCode } from "./pack.mjs";
|
|
24
24
|
import { changedSoFar, closeTree, fileFolder, folderChanges, folderState, freshCopy, isAddress, pushPlan, sourceFor, trustedRepo, landTree, landWork, neverCommit, openBranch, openTree, openWork, ownFolder, layTree, tidyTrees, patchOf, realRepo, refreshBranch, safeTable, treeChanges, undoCommit, workBranch } from "./repo.mjs";
|
|
25
25
|
import { alwaysRules } from "./approve-server.mjs";
|
|
26
|
+
import { Browser } from "./browser.mjs";
|
|
27
|
+
import { bridgeKey, startBridge } from "./local.mjs";
|
|
26
28
|
import { fileURLToPath } from "node:url";
|
|
27
29
|
import { cut, hideSecrets, home, loadSecret, log, readConfig, writeWhole } from "./store.mjs";
|
|
28
30
|
|
|
@@ -532,6 +534,9 @@ export function cleanSources(dir, sources) {
|
|
|
532
534
|
return out.slice(0, 6);
|
|
533
535
|
}
|
|
534
536
|
|
|
537
|
+
// The person's browser at the table: their page shows it and their AI uses it (browser.mjs). Started when first used.
|
|
538
|
+
const sharedBrowser = new Browser(home, log);
|
|
539
|
+
|
|
535
540
|
// Whether longtable:// on this computer starts the connection (keepWakeLink, at start).
|
|
536
541
|
let wakeLink = false;
|
|
537
542
|
|
|
@@ -1411,7 +1416,7 @@ async function work(rpc, seat, engines, raw) {
|
|
|
1411
1416
|
} finally {
|
|
1412
1417
|
if (beat) clearInterval(beat);
|
|
1413
1418
|
if (pending) clearTimeout(pending);
|
|
1414
|
-
if (fullRun) { try { rmSync(fullRun.mcp, { force: true }); if (fullRun.browserDir) rmSync(fullRun.browserDir, { recursive: true, force: true }); } catch {} }
|
|
1419
|
+
if (fullRun) { try { rmSync(fullRun.mcp, { force: true }); if (fullRun.browserDir) rmSync(fullRun.browserDir, { recursive: true, force: true }); } catch {} if (fullRun.shared) sharedBrowser.release(); }
|
|
1415
1420
|
if (tree) closeTree(tree);
|
|
1416
1421
|
if (side) { try { rmSync(side, { recursive: true, force: true }); } catch {} }
|
|
1417
1422
|
if (inbox) await inbox.close();
|
|
@@ -1429,10 +1434,12 @@ const PLANNING = "Your person has you in plan mode: read what you need, then ans
|
|
|
1429
1434
|
// own browser profile) and its screenshots kept in a folder of the connection's. Run through npm's own npx beside this
|
|
1430
1435
|
// Node when it is there (a .cmd cannot be started directly on Windows), else npx on the PATH.
|
|
1431
1436
|
export const PLAYWRIGHT_MCP = "@playwright/mcp@0.0.83";
|
|
1432
|
-
|
|
1437
|
+
// With `cdp`, it drives the person's browser at the table (browser.mjs), the one their page shows them, instead of a
|
|
1438
|
+
// fresh one of its own.
|
|
1439
|
+
export function browserServer(out, cdp = null) {
|
|
1433
1440
|
// Beside node.exe on Windows; under lib/ beside the node binary on Mac and Linux.
|
|
1434
1441
|
const npxCli = [join(dirname(process.execPath), "node_modules", "npm", "bin", "npx-cli.js"), join(dirname(process.execPath), "..", "lib", "node_modules", "npm", "bin", "npx-cli.js")].find((p) => existsSync(p));
|
|
1435
|
-
const args = ["-y", PLAYWRIGHT_MCP, "--headless", "--isolated", "--output-dir", out];
|
|
1442
|
+
const args = ["-y", PLAYWRIGHT_MCP, ...(cdp ? ["--cdp-endpoint", cdp] : ["--headless", "--isolated"]), "--output-dir", out];
|
|
1436
1443
|
return npxCli ? { command: process.execPath, args: [npxCli, ...args] } : { command: "npx", args };
|
|
1437
1444
|
}
|
|
1438
1445
|
|
|
@@ -1445,13 +1452,20 @@ async function fullSetup(rpc, seat, job, inFolder = false, workDir = null) {
|
|
|
1445
1452
|
const server = fileURLToPath(new URL("./approve-server.mjs", import.meta.url));
|
|
1446
1453
|
// Screenshots go outside ~/.longtable, which is never shared, so the person's Claude can put one on its answer.
|
|
1447
1454
|
const browserDir = join(tmpdir(), `longtable-browser-${String(job.job_id).replace(/[^a-f0-9-]/gi, "")}`);
|
|
1448
|
-
|
|
1455
|
+
// Their browser at the table when it can be started, so they can watch it and take over; else one of its own.
|
|
1456
|
+
let shared = false;
|
|
1457
|
+
let browser = null;
|
|
1458
|
+
if (job.browser === true) {
|
|
1459
|
+
let port = 0;
|
|
1460
|
+
try { port = await sharedBrowser.hold(); shared = true; } catch (e) { log(`job ${job.job_id}: their browser could not be used, so it gets one of its own: ${e.message}`); }
|
|
1461
|
+
browser = browserServer(browserDir, port ? `http://127.0.0.1:${port}` : null);
|
|
1462
|
+
}
|
|
1449
1463
|
writeWhole(mcp, JSON.stringify({ mcpServers: { longtable: { command: process.execPath, args: [server],
|
|
1450
1464
|
// What it may put on its answer: files in the folder it works in, and its own screenshots. Nothing else.
|
|
1451
1465
|
env: { LT_SUPABASE_URL: rpc.base, LT_KEY: rpc.key, LT_JOB_KEY: key, LT_ALWAYS: always, LT_SHARE_ROOTS: [workDir, browser ? browserDir : null].filter(Boolean).join(delimiter) } }, ...(browser ? { playwright: browser } : {}) } }));
|
|
1452
1466
|
// In their own folder Claude Code reads the project's settings itself, as at home. With their browser on, its tools
|
|
1453
1467
|
// are theirs to use without asking each time, as they turned it on.
|
|
1454
|
-
return { mcp, browserDir: browser ? browserDir : null, allow: [...alwaysRules(always), ...(browser ? ["mcp__playwright"] : [])], project: inFolder ? {} : projectSettings(seat) };
|
|
1468
|
+
return { mcp, shared, browserDir: browser ? browserDir : null, allow: [...alwaysRules(always), ...(browser ? ["mcp__playwright"] : [])], project: inFolder ? {} : projectSettings(seat) };
|
|
1455
1469
|
}
|
|
1456
1470
|
|
|
1457
1471
|
// Their project's own Claude Code settings, from their own folder (shared, then their local ones on top): what their
|
|
@@ -1520,6 +1534,29 @@ async function tellCommands(rpc, seat) {
|
|
|
1520
1534
|
} catch (e) { log(`commands not sent: ${e.message}`); }
|
|
1521
1535
|
}
|
|
1522
1536
|
|
|
1537
|
+
// The bridge for each person's own terminal and browser (local.mjs). Longtable hears where it listens, with a key for
|
|
1538
|
+
// each table, at start and every minute, and says for each whether this connection may serve it there (their own full
|
|
1539
|
+
// Claude Code only). A bridge that cannot open is written down; everything else goes on as before.
|
|
1540
|
+
async function openBridge(rpc, config, seats) {
|
|
1541
|
+
const mine = seats.filter((s) => s.kind === "claude" && !s.gone);
|
|
1542
|
+
if (!mine.length || !config.app) return;
|
|
1543
|
+
for (const s of mine) s.local = { key: bridgeKey(), allowed: false };
|
|
1544
|
+
for (const s of mine) s.terminalFolder = ownFolder(s) || homedir();
|
|
1545
|
+
let bridge;
|
|
1546
|
+
try { bridge = await startBridge({ app: config.app, seats: mine, home: homedir(), browser: sharedBrowser, log }); }
|
|
1547
|
+
catch (e) { return log(`the terminal and browser bridge did not open: ${e.message}`); }
|
|
1548
|
+
process.on("exit", () => bridge.close());
|
|
1549
|
+
const tell = async () => {
|
|
1550
|
+
for (const s of mine) {
|
|
1551
|
+
if (s.gone) continue;
|
|
1552
|
+
try { s.local.allowed = await rpc("runner_local", { token: s.token, port: bridge.port, key: s.local.key }) === true; }
|
|
1553
|
+
catch (e) { log(`bridge not reported: ${e.message}`); }
|
|
1554
|
+
}
|
|
1555
|
+
};
|
|
1556
|
+
await tell();
|
|
1557
|
+
setInterval(tell, 60 * 1000).unref?.();
|
|
1558
|
+
}
|
|
1559
|
+
|
|
1523
1560
|
export async function runLoop({ pollMs = 1000, backup = false } = {}) {
|
|
1524
1561
|
const config = readConfig();
|
|
1525
1562
|
if (!config.connections?.length) throw new Error("Not connected to any table yet.");
|
|
@@ -1538,7 +1575,7 @@ export async function runLoop({ pollMs = 1000, backup = false } = {}) {
|
|
|
1538
1575
|
if (old && old !== process.pid) { endConnection(old); log(`ended the connection that was already running (${old})`); }
|
|
1539
1576
|
writeFileSync(lock, `${process.pid} ${Date.now()}`);
|
|
1540
1577
|
const unlock = () => { try { if (runningConnection() === process.pid) rmSync(lock, { force: true }); } catch {} };
|
|
1541
|
-
process.on("exit", () => { stopAll(); endAllSessions("the connection stopped"); unlock(); });
|
|
1578
|
+
process.on("exit", () => { stopAll(); sharedBrowser.close(); endAllSessions("the connection stopped"); unlock(); });
|
|
1542
1579
|
// Which common tools its Claude will find here, looked for once at start and shown in its AI window.
|
|
1543
1580
|
setTimeout(() => { lookForTools().catch((e) => log(`could not look for tools: ${e.message}`)); }, 2000).unref?.();
|
|
1544
1581
|
// What an earlier connection's sessions left running is stopped, and a session nobody uses for a while ends.
|
|
@@ -1572,6 +1609,7 @@ export async function runLoop({ pollMs = 1000, backup = false } = {}) {
|
|
|
1572
1609
|
}
|
|
1573
1610
|
}
|
|
1574
1611
|
if (seats.every((s) => s.gone)) throw new Error("Every table has taken this connection off. Connect again from Longtable.");
|
|
1612
|
+
openBridge(rpc, config, seats);
|
|
1575
1613
|
// Each minute: nothing is sent unless the list changed (a new command written, or Claude Code's own list learned).
|
|
1576
1614
|
setInterval(() => { for (const s of seats) if (!s.gone) tellCommands(rpc, s); }, 60 * 1000).unref?.();
|
|
1577
1615
|
// Keeping itself up to date: Longtable says which version to run. When it is newer, the connection keeps working and
|
package/src/terminal.mjs
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
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
|
+
}
|