worktrust 0.11.0 → 0.11.2
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/README.md +18 -0
- package/engine-release.json +1 -1
- package/package-release.json +1 -1
- package/package.json +10 -1
- package/remote-adapter-claude-code.mjs +5 -3
- package/remote-adapter-codex.mjs +45 -5
- package/remote-adapter-terminal.mjs +248 -0
- package/remote-approval-bridge.mjs +30 -7
- package/remote-approvals.mjs +13 -3
- package/remote-cdp.mjs +60 -0
- package/remote-cli.mjs +25 -6
- package/remote-daemon.mjs +28 -4
- package/remote-endorse.mjs +43 -0
- package/remote-inventory.mjs +14 -3
- package/remote-live-preview.mjs +205 -0
- package/remote-protocol.mjs +542 -338
- package/remote-run.mjs +21 -3
- package/remote-screen-approvals.mjs +79 -0
- package/remote-screen-push.mjs +76 -0
- package/remote-screen-states.mjs +113 -0
- package/remote-session-list.mjs +25 -2
- package/remote-sessions.mjs +10 -21
- package/remote-store.mjs +11 -4
- package/remote-terminal-cli.mjs +85 -0
- package/remote-terminal-sessions.mjs +291 -0
- package/worktrust.mjs +2 -2
package/remote-approvals.mjs
CHANGED
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
* This file is the only place that may send agent.approval_required (scripts/check-remote-cli.mjs holds it). The same
|
|
12
12
|
* socket takes the session's planning calls (`{ token, plan: { op, args } }`, 2026-11-08) and hands them to ctx.plan,
|
|
13
13
|
* the release queue's: they never reach the approval path and never run anything.
|
|
14
|
+
*
|
|
15
|
+
* A terminal session's dialog (release 19, remote-screen-approvals.mjs) comes in with its action already classified by the
|
|
16
|
+
* same policy (`preset`); the same gate decides it, and `onPhone` hears only a decision a phone signed (a timeout, a lost
|
|
17
|
+
* phone or the computer's own refusal answers nothing on the screen).
|
|
14
18
|
*/
|
|
15
19
|
import { createServer } from "node:net";
|
|
16
20
|
import { chmodSync, existsSync, mkdirSync, rmSync } from "node:fs";
|
|
@@ -36,9 +40,9 @@ export function createApprovals(ctx) {
|
|
|
36
40
|
};
|
|
37
41
|
|
|
38
42
|
/** One permission request from the bridge → the answer the bridge gives Claude Code. */
|
|
39
|
-
async function request(session, toolName, input) {
|
|
43
|
+
async function request(session, toolName, input, preset = null) {
|
|
40
44
|
if (ctx.paused()) return deny("WorkTrust remote is paused on this computer; denied");
|
|
41
|
-
const { action, reason } = classifyAction(session.adapter, toolName, input, session.projectPath);
|
|
45
|
+
const { action, reason } = preset ?? classifyAction(session.adapter, toolName, input, session.projectPath);
|
|
42
46
|
if (!phoneMayDecide(action)) {
|
|
43
47
|
ctx.emit(session.session_id, "agent.output_delta", { stream: "tool", offset: 0, text: `Denied on the computer (${action.tool}): ${reason}` }, session.command_id);
|
|
44
48
|
return deny(`WorkTrust remote: ${reason}`);
|
|
@@ -49,7 +53,7 @@ export function createApprovals(ctx) {
|
|
|
49
53
|
const record = { approval_id, session_id: session.session_id, computer_device_id: ctx.deviceId, action_hash, class: action.class, expires_at };
|
|
50
54
|
const answer = new Promise((resolve) => {
|
|
51
55
|
const timer = setTimeout(() => finish(approval_id, deny("WorkTrust remote: no decision in time; denied")), Math.max(0, expires_at - ctx.now()));
|
|
52
|
-
pending.set(approval_id, { record, resolve, timer, session_id: session.session_id, input });
|
|
56
|
+
pending.set(approval_id, { record, resolve, timer, session_id: session.session_id, input, onPhone: preset?.onPhone ?? null });
|
|
53
57
|
});
|
|
54
58
|
ctx.onApprovalOpened?.(session.session_id, approval_id);
|
|
55
59
|
ctx.emit(session.session_id, "agent.approval_required", { approval_id, action, action_hash, expires_at }, session.command_id, "needs_you");
|
|
@@ -75,9 +79,12 @@ export function createApprovals(ctx) {
|
|
|
75
79
|
if (!checked.ok) return checked;
|
|
76
80
|
const open = pending.get(checked.value.approval_id);
|
|
77
81
|
ctx.journal.spend(checked.value.approval_id, ctx.now());
|
|
82
|
+
open.onPhone?.(checked.value.decision);
|
|
78
83
|
finish(checked.value.approval_id, checked.value.decision === "approve" ? { behavior: "allow", updatedInput: open.input } : deny("WorkTrust remote: denied on your phone"));
|
|
79
84
|
return checked;
|
|
80
85
|
},
|
|
86
|
+
/** A session's open approvals answered "no" without any phone (a terminal dialog the person answered at the desk). */
|
|
87
|
+
withdraw(sessionId, message) { for (const [id, p] of pending) if (p.session_id === sessionId) finish(id, deny(`WorkTrust remote: ${message}`)); },
|
|
81
88
|
denyAll() { for (const id of [...pending.keys()]) finish(id, deny("WorkTrust remote: the daemon stopped; denied")); },
|
|
82
89
|
async listen(dir) {
|
|
83
90
|
let path;
|
|
@@ -107,8 +114,11 @@ export function createApprovals(ctx) {
|
|
|
107
114
|
conn.end(`${JSON.stringify(planned)}\n`);
|
|
108
115
|
return;
|
|
109
116
|
}
|
|
117
|
+
// Codex asks through its app-server (remote-adapter-codex.mjs); its bridge carries the planning tools only, so an
|
|
118
|
+
// approval over the socket with a Codex session's token is no request of Codex's (2026-11-09).
|
|
110
119
|
const answer = !session || typeof msg.tool_name !== "string" || !msg.input || typeof msg.input !== "object"
|
|
111
120
|
? deny("WorkTrust remote: unknown session; denied")
|
|
121
|
+
: session.adapter === "codex" ? deny("WorkTrust remote: Codex asks through its app-server; denied")
|
|
112
122
|
: await request(session, msg.tool_name, msg.input);
|
|
113
123
|
conn.end(`${JSON.stringify(answer)}\n`);
|
|
114
124
|
});
|
package/remote-cdp.mjs
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE DEVTOOLS PROTOCOL OVER A PIPE (release 19, 2026-11-09; the live preview, remote-live-preview.mjs). Chrome is started
|
|
3
|
+
* with `--remote-debugging-pipe`: it reads commands from its file descriptor 3 and writes answers and events to 4, each
|
|
4
|
+
* message JSON ending in a NUL byte. NO DEBUGGING PORT IS EVER OPENED: no `--remote-debugging-port`, no TCP listener a
|
|
5
|
+
* page, another process or another computer could reach (held by test-remote-live-preview and check-remote-cli rule F).
|
|
6
|
+
*
|
|
7
|
+
* `createCdp({ write, onEvent })` is the client over any pair of pipes (a fake one in the tests): `send(method, params,
|
|
8
|
+
* sessionId)` resolves with the result or rejects with the error; `feed(chunk)` takes what the browser wrote.
|
|
9
|
+
*/
|
|
10
|
+
import { spawn } from "node:child_process";
|
|
11
|
+
|
|
12
|
+
export const MAX_MESSAGE = 32 * 1024 * 1024;
|
|
13
|
+
const CALL_MS = 15_000;
|
|
14
|
+
|
|
15
|
+
/** The browser on pipes: stdio 0-2 closed to us, 3 for commands, 4 for answers. Never a shell, never a port. */
|
|
16
|
+
export function spawnBrowserOnPipe(file, args, env) {
|
|
17
|
+
if (args.some((a) => /^--remote-debugging-(port|address)/.test(a))) throw new Error("a debugging port is never opened");
|
|
18
|
+
if (!args.includes("--remote-debugging-pipe")) throw new Error("the browser is driven over its pipe only");
|
|
19
|
+
const child = spawn(file, args, { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true, env });
|
|
20
|
+
const exited = new Promise((resolve) => { child.on("exit", (code) => resolve(code)); child.on("error", () => resolve(-1)); });
|
|
21
|
+
return {
|
|
22
|
+
pid: child.pid,
|
|
23
|
+
write: (data) => { try { child.stdio[3].write(data); } catch { /* gone */ } },
|
|
24
|
+
onData: (fn) => { child.stdio[4].setEncoding("utf8"); child.stdio[4].on("data", fn); }, // utf8: a title split across chunks stays whole
|
|
25
|
+
exited,
|
|
26
|
+
kill: (signal = "SIGTERM") => { try { if (process.platform === "win32") child.kill(signal); else process.kill(-child.pid, signal); } catch { /* gone */ } },
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function createCdp({ write, onEvent }) {
|
|
31
|
+
let next = 0, buffer = "", closed = false;
|
|
32
|
+
const waiting = new Map();
|
|
33
|
+
return {
|
|
34
|
+
send(method, params = {}, sessionId = undefined) {
|
|
35
|
+
if (closed) return Promise.reject(new Error("closed"));
|
|
36
|
+
const id = ++next;
|
|
37
|
+
write(`${JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })}\0`);
|
|
38
|
+
return new Promise((resolve, reject) => {
|
|
39
|
+
const timer = setTimeout(() => { waiting.delete(id); reject(new Error(`${method}: no answer`)); }, CALL_MS);
|
|
40
|
+
timer.unref?.();
|
|
41
|
+
waiting.set(id, { resolve, reject, timer });
|
|
42
|
+
});
|
|
43
|
+
},
|
|
44
|
+
feed(chunk) {
|
|
45
|
+
buffer += String(chunk);
|
|
46
|
+
if (buffer.length > MAX_MESSAGE) { buffer = ""; return; }
|
|
47
|
+
let end;
|
|
48
|
+
while ((end = buffer.indexOf("\0")) >= 0) {
|
|
49
|
+
const raw = buffer.slice(0, end); buffer = buffer.slice(end + 1);
|
|
50
|
+
let msg = null;
|
|
51
|
+
try { msg = JSON.parse(raw); } catch { continue; }
|
|
52
|
+
if (typeof msg?.id === "number" && waiting.has(msg.id)) {
|
|
53
|
+
const w = waiting.get(msg.id); waiting.delete(msg.id); clearTimeout(w.timer);
|
|
54
|
+
if (msg.error) w.reject(new Error(String(msg.error.message ?? "error"))); else w.resolve(msg.result ?? {});
|
|
55
|
+
} else if (typeof msg?.method === "string") onEvent(msg.method, msg.params ?? {}, msg.sessionId ?? null);
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
close() { closed = true; for (const w of waiting.values()) { clearTimeout(w.timer); w.reject(new Error("closed")); } waiting.clear(); },
|
|
59
|
+
};
|
|
60
|
+
}
|
package/remote-cli.mjs
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* remote pause | resume refuse every command for now | take them again
|
|
10
10
|
* remote disable [--forget] the hard off: the service removed; --forget also deletes the keys
|
|
11
11
|
* remote phones [confirm <id> | remove <id>] phones: pending ones are confirmed here, at the keyboard
|
|
12
|
+
* remote phones allow-endorse on|off may a confirmed phone add a browser it scanned (default off)
|
|
12
13
|
* remote projects add <folder> | remove <id> | list the folders a phone may steer an agent in
|
|
13
14
|
* remote run the daemon in the foreground (Windows runs only this way)
|
|
14
15
|
* remote pipeline review <folder> | status read a granted folder's .worktrust/pipeline.json, show every stage
|
|
@@ -21,6 +22,9 @@
|
|
|
21
22
|
* deems safe without asking, which the person accepts here
|
|
22
23
|
* remote releases [released <number>] the releases on this computer; mark a ready one released (the
|
|
23
24
|
* phone never can: publishing stays at the desk)
|
|
25
|
+
* remote terminal on | off | list | start [<folder>] and remote attach <id> terminal sessions (release 19): Claude Code
|
|
26
|
+
* in tmux on WorkTrust's own socket, seen on the phone, attached here
|
|
27
|
+
* (remote-terminal-cli.mjs; off by default)
|
|
24
28
|
*/
|
|
25
29
|
import { basename } from "node:path";
|
|
26
30
|
import { hostname } from "node:os";
|
|
@@ -43,7 +47,7 @@ import { checkRoot, MAX_ROOTS, rootIdOf, rootLabel } from "./remote-projects.mjs
|
|
|
43
47
|
const fingerprintOf = (keys) => P.deviceFingerprint(keys.public);
|
|
44
48
|
const pretty = (code) => `${code.slice(0, 4)}-${code.slice(4)}`;
|
|
45
49
|
/** A question only a person at this keyboard answers: a terminal, a typed "yes"; --yes and Enter are No. */
|
|
46
|
-
async function askTyped(question) {
|
|
50
|
+
export async function askTyped(question) {
|
|
47
51
|
if (!process.stdin.isTTY) return false;
|
|
48
52
|
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
49
53
|
const answer = (await prompt.question(` ${question} Type yes to confirm: `)).trim().toLowerCase();
|
|
@@ -140,6 +144,15 @@ async function phones(io, rest) {
|
|
|
140
144
|
io.say(` ✓ Confirmed: phone · ${phone.fingerprint}`);
|
|
141
145
|
return;
|
|
142
146
|
}
|
|
147
|
+
if (rest[0] === "allow-endorse") {
|
|
148
|
+
// At this keyboard only (2026-11-09, remote-endorse.mjs): a phone confirmed here may then add a browser it scanned.
|
|
149
|
+
if (rest[1] !== "on" && rest[1] !== "off") io.fail("npx worktrust remote phones allow-endorse on|off");
|
|
150
|
+
if (rest[1] === "on" && !process.stdin.isTTY) io.fail("endorsements are allowed at this keyboard, in a terminal");
|
|
151
|
+
if (rest[1] === "on" && !(await askTyped(" A phone confirmed here may then add a browser it scanned as a controller of this computer. Allow it?"))) { io.say(" Not changed."); return; }
|
|
152
|
+
saveSettings({ ...loadSettings(), allow_endorse: rest[1] === "on" });
|
|
153
|
+
io.say(rest[1] === "on" ? " ✓ Your confirmed phones may add a browser. Each one is listed here with the phone that added it." : " ✓ No phone may add a browser. Browsers already added stay until you remove them.");
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
143
156
|
if (rest[0] === "remove") {
|
|
144
157
|
const phone = find(rest[1]);
|
|
145
158
|
if (!phone) io.fail("no phone by that fingerprint or id");
|
|
@@ -149,7 +162,10 @@ async function phones(io, rest) {
|
|
|
149
162
|
return;
|
|
150
163
|
}
|
|
151
164
|
io.say(` Confirmed phones (${list.confirmed.length}):`);
|
|
152
|
-
|
|
165
|
+
const when = (ms) => new Date(ms).toISOString().slice(0, 16).replace("T", " ");
|
|
166
|
+
const how = (p) => p.how === "endorsed" ? `a browser, added by phone ${p.endorsed_by?.fingerprint ?? "?"}${[...list.confirmed, ...list.removed].some((x) => x.device_id === p.endorsed_by?.device_id && !list.confirmed.includes(x)) ? " (since removed)" : ""} on ${when(p.confirmed_at)}` : p.how === "qr" ? "scanned the QR" : "confirmed at the keyboard";
|
|
167
|
+
for (const p of list.confirmed) io.say(` ${p.fingerprint} ${p.device_id} (${how(p)})`);
|
|
168
|
+
io.say(` Phones may add a browser: ${loadSettings().allow_endorse ? "yes" : "no"} (npx worktrust remote phones allow-endorse on|off)`);
|
|
153
169
|
io.say(` Pending phones (${list.pending.length}):`);
|
|
154
170
|
for (const p of list.pending) io.say(` ${p.fingerprint} ${p.device_id} confirm: npx worktrust remote phones confirm ${p.fingerprint}`);
|
|
155
171
|
if (list.removed.length > 0) {
|
|
@@ -258,14 +274,15 @@ function status(io) {
|
|
|
258
274
|
const settings = loadSettings(), identity = loadIdentity(), keys = identity ? loadKeys() : null, phonesList = loadPhones(), service = serviceState();
|
|
259
275
|
const agents = inventory({ env: { ...process.env, PATH: settings.agent_path ?? process.env.PATH } }).reports.filter((r) => r.installed);
|
|
260
276
|
const summary = { enabled: settings.enabled, paused: settings.paused, paired: Boolean(identity), device_id: identity?.device_id ?? null, fingerprint: keys ? fingerprintOf(keys) : null,
|
|
261
|
-
gateway: settings.gateway, service, node_websocket: webSocketAvailable(), phones: { confirmed: phonesList.confirmed.length, pending: phonesList.pending.length }, projects: loadProjects().length,
|
|
277
|
+
gateway: settings.gateway, service, node_websocket: webSocketAvailable(), phones: { confirmed: phonesList.confirmed.length, pending: phonesList.pending.length, browsers_added: phonesList.confirmed.filter((p) => p.how === "endorsed").length, allow_endorse: settings.allow_endorse === true }, projects: loadProjects().length,
|
|
262
278
|
agents: agents.map((a) => ({ adapter: a.adapter, version: a.version, adapter_ready: a.capabilities.start, models: a.models === null ? "not listed" : a.models.length })), invite_open: Boolean(readJson("invite.json")?.used === false) };
|
|
263
279
|
if (io.has("json")) { io.say(JSON.stringify(summary, null, 2)); return; }
|
|
264
280
|
io.say(` Remote: ${settings.enabled ? (settings.paused ? `paused (${settings.paused === "desk" ? "here" : "from a phone"})` : "on") : "off"}`);
|
|
265
281
|
io.say(` Paired: ${identity ? `${identity.device_id} · key ${summary.fingerprint}` : "no"}`);
|
|
266
282
|
io.say(` Gateway: ${settings.gateway ?? "none set"}${settings.gateway && isLoopbackGateway(settings.gateway) ? " (this computer: dev relay)" : ""}`);
|
|
267
283
|
io.say(` Service: ${service.kind === "foreground" ? "none on this system: run `npx worktrust remote run`" : `${service.installed ? "installed" : "not installed"}, ${service.running ? "running" : "not running"}`}`);
|
|
268
|
-
io.say(` Phones: ${summary.phones.confirmed} confirmed, ${summary.phones.pending} pending · Folders granted: ${summary.projects}`);
|
|
284
|
+
io.say(` Phones: ${summary.phones.confirmed} confirmed (${summary.phones.browsers_added} browsers added by a phone), ${summary.phones.pending} pending · Folders granted: ${summary.projects}`);
|
|
285
|
+
io.say(` Phones may add a browser: ${summary.phones.allow_endorse ? "yes" : "no"}`);
|
|
269
286
|
for (const a of summary.agents) io.say(` Agent: ${a.adapter} ${a.version ?? ""} · ${a.adapter_ready ? "remote adapter ready" : "installed, no adapter yet"} · models: ${a.models}`);
|
|
270
287
|
}
|
|
271
288
|
|
|
@@ -279,7 +296,7 @@ export async function remoteCommand(args, io) {
|
|
|
279
296
|
const s = loadSettings();
|
|
280
297
|
saveSettings({ ...s, enabled: false, paused: null });
|
|
281
298
|
io.say(` Off. The service is removed (${removeService()}); the daemon stops by itself within seconds.`);
|
|
282
|
-
if (io.has("forget")) { for (const f of ["remote-keys.json", "identity.json", "channels.json", "phones.json", "invite.json", "journal.jsonl", "projects.json", "pipelines.json", "released.json", "roots.json", "previews.json"]) removeFile(f); io.say(" The remote keys, phones, folders and journal are deleted. The steered-session ledger stays, so earlier remote work stays out of your AI Hours."); }
|
|
299
|
+
if (io.has("forget")) { for (const f of ["remote-keys.json", "identity.json", "channels.json", "phones.json", "endorsements.json", "invite.json", "journal.jsonl", "projects.json", "pipelines.json", "released.json", "roots.json", "previews.json"]) removeFile(f); io.say(" The remote keys, phones, folders and journal are deleted. The steered-session ledger stays, so earlier remote work stays out of your AI Hours."); }
|
|
283
300
|
return;
|
|
284
301
|
}
|
|
285
302
|
if (sub === "phones") return phones(io, rest);
|
|
@@ -321,5 +338,7 @@ export async function remoteCommand(args, io) {
|
|
|
321
338
|
return;
|
|
322
339
|
}
|
|
323
340
|
if (sub === "releases") return releasesCommand(io, rest);
|
|
324
|
-
|
|
341
|
+
if (sub === "terminal") return (await import("./remote-terminal-cli.mjs")).terminalCommand(io, rest, askTyped);
|
|
342
|
+
if (sub === "attach") return (await import("./remote-terminal-cli.mjs")).attachCommand(io, rest);
|
|
343
|
+
io.say(" npx worktrust remote enable | pair | status | pause | resume | disable [--forget] | phones [confirm|remove <id>|allow-endorse on|off] | projects add|remove|list | run | pipeline review <folder>|status | roots add|remove|list | preview allow|deny|list | codex on|off | terminal on|off|list|start | attach <id> | releases [released <n>]");
|
|
325
344
|
}
|
package/remote-daemon.mjs
CHANGED
|
@@ -12,10 +12,12 @@
|
|
|
12
12
|
*/
|
|
13
13
|
import { basename } from "node:path";
|
|
14
14
|
import * as P from "./remote-protocol.mjs";
|
|
15
|
-
import { confirmedFingerprints, controllerKeys, loadChannels, loadPhones, loadProjects, loadRoots, loadSettings, readJson, saveChannels, savePhones, saveProjects, saveSettings, writeJson } from "./remote-store.mjs";
|
|
15
|
+
import { confirmedFingerprints, controllerKeys, loadChannels, loadEndorsements, loadPhones, loadProjects, loadRoots, loadSettings, readJson, saveChannels, saveEndorsements, savePhones, saveProjects, saveSettings, writeJson } from "./remote-store.mjs";
|
|
16
|
+
import { acceptEndorsement } from "./remote-endorse.mjs";
|
|
16
17
|
import { createProject, rootLabel, worktreeMain } from "./remote-projects.mjs";
|
|
17
18
|
|
|
18
19
|
// What a paused computer still answers: reading, configuring, disconnecting, and taking work away (a pipeline's cancel).
|
|
20
|
+
const LIVE_COMMANDS = new Set(["preview.live_start", "preview.live_input", "preview.live_viewport", "preview.live_follow"]);
|
|
19
21
|
const DEVICE_COMMANDS = new Set(["inventory.get", "device.configure", "status.get", "pairing.revoke", "release.list", "pipeline.cancel"]);
|
|
20
22
|
const KEEP_REMOVED = 20;
|
|
21
23
|
const MAX_PENDING_PHONES = 10;
|
|
@@ -31,7 +33,7 @@ export function createDaemonCore(o) {
|
|
|
31
33
|
function sealAll(record) {
|
|
32
34
|
for (const [id, channel] of channels) {
|
|
33
35
|
if (!confirmed().has(channel.peer_fingerprint)) { channels.delete(id); continue; } // a revoked phone hears nothing
|
|
34
|
-
const draft = { protocol_version: channel.protocol_version, session_id: record.session_id, device_id: self, event_seq: record.event_seq, type: record.type, occurred_at: record.occurred_at, command_id: record.command_id, notify: record.notify };
|
|
36
|
+
const draft = { protocol_version: channel.protocol_version, session_id: record.session_id, device_id: self, event_seq: record.event_seq, type: record.type, occurred_at: record.occurred_at, command_id: record.command_id, notify: record.notify, ...(record.lane ? { lane: record.lane } : {}) };
|
|
35
37
|
const sealed = P.sealEvent(channel, draft, record.body, o.random);
|
|
36
38
|
if (!sealed.ok) { o.log("seal_refused", { type: record.type, code: sealed.code }); continue; }
|
|
37
39
|
channels.set(id, sealed.value.channel);
|
|
@@ -40,7 +42,13 @@ export function createDaemonCore(o) {
|
|
|
40
42
|
persist();
|
|
41
43
|
}
|
|
42
44
|
|
|
43
|
-
|
|
45
|
+
/**
|
|
46
|
+
* `transient` (release 19; a pushed terminal screen, remote-screen-push.mjs): the session's TRANSIENT LANE
|
|
47
|
+
* (envelopes.ts), sealed for the phones and never journaled, so a replay never brings back a stale screen and the
|
|
48
|
+
* session's own sequence has no number missing. Its numbers rise per session from this computer's clock.
|
|
49
|
+
*/
|
|
50
|
+
const laneSeq = new Map();
|
|
51
|
+
function emit(sessionId, type, body, commandId = null, notify = "none", { transient = false } = {}) {
|
|
44
52
|
let shaped = P.validateEventBody(type, body);
|
|
45
53
|
if (!shaped.ok && type === "agent.completed" && body.result) {
|
|
46
54
|
// A result over its caps keeps the reply and names the files; the diffs are said to be cut.
|
|
@@ -49,6 +57,11 @@ export function createDaemonCore(o) {
|
|
|
49
57
|
shaped = P.validateEventBody(type, body);
|
|
50
58
|
}
|
|
51
59
|
if (!shaped.ok) { o.log("event_refused", { type, detail: shaped.code }); return; }
|
|
60
|
+
if (transient) {
|
|
61
|
+
const seq = Math.max((laneSeq.get(sessionId) ?? 0) + 1, o.now());
|
|
62
|
+
laneSeq.set(sessionId, seq);
|
|
63
|
+
return sealAll({ session_id: sessionId, event_seq: seq, type, occurred_at: o.now(), command_id: null, notify: "none", lane: "transient", body });
|
|
64
|
+
}
|
|
52
65
|
const record = { session_id: sessionId, event_seq: o.journal.nextSeq(sessionId), type, occurred_at: o.now(), command_id: commandId, notify, body };
|
|
53
66
|
o.journal.recordEvent(record);
|
|
54
67
|
sealAll(record);
|
|
@@ -136,11 +149,22 @@ export function createDaemonCore(o) {
|
|
|
136
149
|
o.log("project_created", { git: made.git });
|
|
137
150
|
return "taken";
|
|
138
151
|
}
|
|
152
|
+
if (env.type === "browser.endorse") {
|
|
153
|
+
// A confirmed phone adds a browser it scanned (remote-endorse.mjs): only with this computer's opt-in, for its own account.
|
|
154
|
+
const decided = acceptEndorsement({ allowed: settings.allow_endorse, phones: loadPhones(), spent: loadEndorsements().spent, sender: env.sender_device_id, payload, issuerKeys: o.issuerKeys, account: o.local.claims.sub, now: o.now() });
|
|
155
|
+
if (!decided.ok) { o.log("endorse_refused", { reason: decided.reason }); return decided.reason; }
|
|
156
|
+
saveEndorsements({ spent: decided.spent });
|
|
157
|
+
if (decided.added) { savePhones(decided.phones); o.log("browser_endorsed", { device_id: decided.added.device_id, fingerprint: decided.added.fingerprint, by: decided.added.endorsed_by.device_id }); }
|
|
158
|
+
return "taken";
|
|
159
|
+
}
|
|
139
160
|
if (env.type === "approval.decision") return approvals.decide(payload.decision_token).ok ? "taken" : "approval_invalid";
|
|
140
161
|
if (P.RELEASE_COMMANDS.has(env.type)) return releases ? releases.handle(env, payload) : "unsupported"; // remote-releases.mjs
|
|
141
162
|
if (env.type === "attachment.put" || env.type === "attachment.clear") return o.attachments ? o.attachments.handle(env, payload) : "unsupported"; // remote-attachments.mjs
|
|
142
163
|
if (env.type === "preview.targets" || env.type === "preview.render") return o.preview ? o.preview.handle(env, payload) : "unsupported"; // remote-preview.mjs
|
|
143
|
-
return
|
|
164
|
+
if (LIVE_COMMANDS.has(env.type)) return o.live ? o.live.handle(env, payload) : "unsupported"; // remote-live-preview.mjs
|
|
165
|
+
const handled = await sessions.handle(env, payload);
|
|
166
|
+
if (env.type === "session.close") await o.live?.sessionClosed(env.session_id); // its live preview ends with it
|
|
167
|
+
return handled;
|
|
144
168
|
}
|
|
145
169
|
|
|
146
170
|
/** The order of this function is the at-most-once rule (see the header). */
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A PHONE ADDS A BROWSER TO THIS COMPUTER (2026-11-09, docs/remote-agents/PROTOCOL.md §A phone endorses a browser). The
|
|
3
|
+
* daemon's decision on a sealed `browser.endorse`, pure: it takes the state and answers the next state, so
|
|
4
|
+
* scripts/check-remote-cli.mjs proves each refusal on its own. The browser becomes a controller ONLY when all hold:
|
|
5
|
+
* 1. this computer allowed endorsements at its keyboard (`worktrust remote phones allow-endorse on`; default off);
|
|
6
|
+
* 2. the sender is a controller confirmed here at the keyboard or by a scanned QR, never one added by endorsement (no
|
|
7
|
+
* chains: an endorsed browser endorses nobody);
|
|
8
|
+
* 3. the browser's issuer binding verifies, as a controller, for THIS computer's own account (crypto/endorse.ts);
|
|
9
|
+
* 4. the endorsement is in time (five minutes at most) and its nonce was never spent here (single use).
|
|
10
|
+
* The browser is listed with who added it and when; removing the endorsing phone later does not remove the browsers it
|
|
11
|
+
* added (each stays revocable here and in WorkTrust, and `remote phones` names the phone that added it).
|
|
12
|
+
*/
|
|
13
|
+
import * as P from "./remote-protocol.mjs";
|
|
14
|
+
|
|
15
|
+
const KEEP_SPENT_MS = (P.ENDORSE_LIFETIME_S * 1000) + 10 * 60_000;
|
|
16
|
+
const MAX_SPENT = 200;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* → { ok: true, phones, spent, added } | { ok: false, reason } where reason is a protocol reject reason:
|
|
20
|
+
* `not_allowed` (no opt-in, a sender that may not, another account, a binding that does not verify), `expired`, `conflict`
|
|
21
|
+
* (a nonce already spent). An endorsement of a browser already confirmed is taken again without a change.
|
|
22
|
+
*/
|
|
23
|
+
export function acceptEndorsement({ allowed, phones, spent, sender, payload, issuerKeys, account, now }) {
|
|
24
|
+
if (allowed !== true) return { ok: false, reason: "not_allowed" };
|
|
25
|
+
const from = phones.confirmed.find((p) => p.device_id === sender);
|
|
26
|
+
if (!from || (from.how !== "keyboard" && from.how !== "qr")) return { ok: false, reason: "not_allowed" };
|
|
27
|
+
const checked = P.checkEndorsement(payload, { issuerKeys, now, account });
|
|
28
|
+
if (!checked.ok) return { ok: false, reason: checked.code === "expired" ? "expired" : "not_allowed" };
|
|
29
|
+
const live = (spent ?? []).filter((s) => s.at + KEEP_SPENT_MS > now);
|
|
30
|
+
if (live.some((s) => s.nonce === checked.value.nonce)) return { ok: false, reason: "conflict" };
|
|
31
|
+
const b = checked.value;
|
|
32
|
+
const nextSpent = [...live, { nonce: b.nonce, at: now }].slice(-MAX_SPENT);
|
|
33
|
+
if (phones.confirmed.some((p) => p.fingerprint === b.fingerprint)) return { ok: true, phones, spent: nextSpent, added: null };
|
|
34
|
+
const browser = { device_id: b.device_id, fingerprint: b.fingerprint, ed25519_pub: b.keys.ed25519_pub, x25519_pub: b.keys.x25519_pub, how: "endorsed", confirmed_at: now,
|
|
35
|
+
endorsed_by: { device_id: from.device_id, fingerprint: from.fingerprint } };
|
|
36
|
+
return {
|
|
37
|
+
ok: true,
|
|
38
|
+
spent: nextSpent,
|
|
39
|
+
added: browser,
|
|
40
|
+
phones: { ...phones, pending: phones.pending.filter((p) => p.fingerprint !== b.fingerprint), removed: (phones.removed ?? []).filter((p) => p.device_id !== b.device_id),
|
|
41
|
+
confirmed: [...phones.confirmed.filter((p) => p.fingerprint !== b.fingerprint), browser] },
|
|
42
|
+
};
|
|
43
|
+
}
|
package/remote-inventory.mjs
CHANGED
|
@@ -16,6 +16,8 @@ import { existsSync, statSync } from "node:fs";
|
|
|
16
16
|
import { delimiter, join } from "node:path";
|
|
17
17
|
import * as P from "./remote-protocol.mjs";
|
|
18
18
|
import { codexReport } from "./remote-adapter-codex.mjs";
|
|
19
|
+
import { terminalReport, tmuxVersion } from "./remote-adapter-terminal.mjs";
|
|
20
|
+
import { typingTrusted } from "./remote-screen-states.mjs";
|
|
19
21
|
|
|
20
22
|
const NO = Object.freeze({ start: false, attach: false, prompt: false, steer: false, pause: false, resume: false, stop: false, structured_events: false, screen: false, focus: false, resume_by_id: false, permission_modes: ["ask"], approvals: "none", acceptance: "acknowledged" });
|
|
21
23
|
export const AGENTS = Object.freeze({ "claude-code": "claude", codex: "codex", "cursor-agent": "cursor-agent", opencode: "opencode" });
|
|
@@ -115,7 +117,12 @@ export function inventory({ env = process.env, refresh = false, now = Date.now()
|
|
|
115
117
|
const checked = P.validateAdapterReport(report);
|
|
116
118
|
if (!checked.ok) throw new Error(`inventory: ${report.adapter}: ${checked.detail}`);
|
|
117
119
|
}
|
|
118
|
-
|
|
120
|
+
// Claude Code in a terminal (release 19): tmux on its own socket. Kept beside the reports, sent only when turned on (offered).
|
|
121
|
+
const tmux = findOnPath("tmux", env.PATH), claude = reports.find((r) => r.adapter === "claude-code");
|
|
122
|
+
const terminal = terminalReport({ claude: claude?.installed ? { ...claude, features: features["claude-code"] } : null, tmux: tmux ? tmuxVersion(probe(tmux, ["-V"], env)) : null });
|
|
123
|
+
const checkedTerminal = P.validateAdapterReport(terminal);
|
|
124
|
+
if (!checkedTerminal.ok) throw new Error(`inventory: claude-code (terminal): ${checkedTerminal.detail}`);
|
|
125
|
+
cache = { reports, features, terminal, files: { ...Object.fromEntries(Object.keys(AGENTS).map((a) => [a, findOnPath(AGENTS[a], env.PATH)])), tmux }, at: now };
|
|
119
126
|
return cache;
|
|
120
127
|
}
|
|
121
128
|
export const adapterOf = (inv, id) => inv.reports.find((r) => r.adapter === id);
|
|
@@ -127,6 +134,10 @@ export const adapterOf = (inv, id) => inv.reports.find((r) => r.adapter === id);
|
|
|
127
134
|
* listed as installed and offered nothing.
|
|
128
135
|
*/
|
|
129
136
|
export function offered(inv, settings) {
|
|
130
|
-
|
|
131
|
-
|
|
137
|
+
const reports = settings?.codex === true ? inv.reports : inv.reports.map((r) => (r.adapter === "codex" && r.capabilities.start ? { ...r, capabilities: NO } : r));
|
|
138
|
+
// Terminal sessions (release 19) only after `worktrust remote terminal on`: an older phone refuses a second report of one adapter.
|
|
139
|
+
// Typing from a phone only on a screen detector whose fixtures were recorded from the real agent (remote-screen-states.mjs).
|
|
140
|
+
// Answering its dialogs from a phone (screen-hash approvals) needs the same: approvals "screen" only then.
|
|
141
|
+
const terminal = inv.terminal?.capabilities.start && typingTrusted("claude-code") ? { ...inv.terminal, capabilities: { ...inv.terminal.capabilities, prompt: true, approvals: "screen" } } : inv.terminal;
|
|
142
|
+
return { ...inv, reports: settings?.terminal === true && terminal ? [...reports, terminal] : reports };
|
|
132
143
|
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE LIVE PREVIEW (release 19, 2026-11-09; owner's preview option A; PROTOCOL.md "The live preview"). The session's
|
|
3
|
+
* granted dev page, live and touchable on the phone: the person's own Chrome, headless, in a throw-away profile, driven over
|
|
4
|
+
* its PIPE (remote-cdp.mjs: never a debugging port), its screencast sent as JPEG frames on the session's transient lane, the
|
|
5
|
+
* phone's taps, scrolls and literal text applied as input events.
|
|
6
|
+
*
|
|
7
|
+
* THE PAGE STAYS ON THE GRANTED ORIGIN, held three ways (each one tested):
|
|
8
|
+
* 1. the network: every request goes to a dead proxy except the granted origin (`--proxy-server` with
|
|
9
|
+
* `--proxy-bypass-list=<-loopback>;127.0.0.1:<port>`), so nothing else is reachable, not even another local port;
|
|
10
|
+
* 2. the DevTools protocol: every request of every frame and worker is paused (Fetch) and continued only for the granted
|
|
11
|
+
* origin; anything else is failed and counted (a document as a navigation, the rest as requests); a page that still
|
|
12
|
+
* lands elsewhere (file://, a scheme) is sent back and counted; a new page (a popup) is closed; a download is denied;
|
|
13
|
+
* a dialog is dismissed; permission prompts are denied by the browser's own switch;
|
|
14
|
+
* 3. the phone: it names a PATH on the granted target, never a URL; input coordinates must lie inside the viewport;
|
|
15
|
+
* text is inserted literally; keys come from a list of three.
|
|
16
|
+
* One live preview per computer. It stops when nobody follows it (LIVE_FOLLOW_MS), when its session closes, when the
|
|
17
|
+
* browser exits, or on follow:false; the browser is ended and its profile and the file server removed.
|
|
18
|
+
*/
|
|
19
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
20
|
+
import { tmpdir } from "node:os";
|
|
21
|
+
import { join } from "node:path";
|
|
22
|
+
import * as P from "./remote-protocol.mjs";
|
|
23
|
+
import { createCdp, spawnBrowserOnPipe } from "./remote-cdp.mjs";
|
|
24
|
+
import { findBrowser, listening, serveProject } from "./remote-preview.mjs";
|
|
25
|
+
|
|
26
|
+
export const FRAME_MS = 200;
|
|
27
|
+
export const LIVE_FOLLOW_MS = 90_000;
|
|
28
|
+
const KEYCODE = { Enter: 13, Backspace: 8, Tab: 9 };
|
|
29
|
+
|
|
30
|
+
/** The command line: headless, its own profile, on its pipe, and a network that reaches the granted origin only. */
|
|
31
|
+
export function liveArgs({ profile, port }) {
|
|
32
|
+
return ["--headless=new", "--remote-debugging-pipe", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", "--disable-extensions", "--disable-sync",
|
|
33
|
+
"--mute-audio", "--hide-scrollbars", "--disable-background-networking", "--disable-component-update", "--disable-default-apps", "--deny-permission-prompts", "--block-new-web-contents",
|
|
34
|
+
"--proxy-server=127.0.0.1:9", `--proxy-bypass-list=<-loopback>;127.0.0.1:${port}`, "about:blank"];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The one origin a page may load from: http, 127.0.0.1, the granted (or file server's) port. */
|
|
38
|
+
export const originOk = (url, port) => { try { const u = new URL(url); return u.protocol === "http:" && u.hostname === "127.0.0.1" && u.port === String(port); } catch { return false; } };
|
|
39
|
+
const toB64Url = (s) => s.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
40
|
+
|
|
41
|
+
// ctx: { emit, projects(), grants(), sessionProject(id), env(), log, now, spawnBrowser?, browser?(), listening?(port), serve?(root), followMs?, frameMs? }
|
|
42
|
+
export function createLivePreview(ctx) {
|
|
43
|
+
let live = null; // one per computer
|
|
44
|
+
const followMs = ctx.followMs ?? LIVE_FOLLOW_MS, frameMs = ctx.frameMs ?? FRAME_MS;
|
|
45
|
+
const later = (fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t; };
|
|
46
|
+
const state = (l, s, reason = null) => {
|
|
47
|
+
l.state = s;
|
|
48
|
+
ctx.emit(l.session_id, "preview.live", { state: s, viewport: l.viewport, width: l.vp.width, height: l.vp.height, title: l.title, path: l.path, blocked: { ...l.blocked }, reason }, null);
|
|
49
|
+
};
|
|
50
|
+
const block = (l, kind) => { l.blocked[kind] += 1; if (!l.stopped) l.dirty(); };
|
|
51
|
+
|
|
52
|
+
async function stop(l, reason) {
|
|
53
|
+
if (!l || l.stopped) return;
|
|
54
|
+
l.stopped = true;
|
|
55
|
+
clearTimeout(l.expiry); clearTimeout(l.frameTimer);
|
|
56
|
+
if (live === l) live = null;
|
|
57
|
+
// The browser first, then its files: it asked to close, then its process group ended, each with a grace, and only
|
|
58
|
+
// once it is gone the profile is removed (a browser still writing into it would leave it behind).
|
|
59
|
+
const gone = (ms) => { let t; return Promise.race([l.proc.exited.then(() => true), new Promise((r) => { t = setTimeout(() => r(false), ms); })]).finally(() => clearTimeout(t)); }; // held: a stop finishes
|
|
60
|
+
await Promise.race([l.cdp.send("Browser.close").catch(() => {}), gone(2000)]);
|
|
61
|
+
l.cdp.close();
|
|
62
|
+
if (!(await gone(2000))) { l.proc.kill("SIGTERM"); if (!(await gone(2000))) { l.proc.kill("SIGKILL"); await gone(2000); } }
|
|
63
|
+
l.proc.kill("SIGKILL"); // what is left of its group (a renderer, a helper)
|
|
64
|
+
l.server?.close();
|
|
65
|
+
try { rmSync(l.profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch { ctx.log("live_profile_left", {}); }
|
|
66
|
+
state(l, reason === "browser_exited" || reason === "failed" ? "failed" : "stopped", reason);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Newest frame wins; at most one per frameMs; none unless someone follows (an expired follow stops the preview). */
|
|
70
|
+
function offerFrame(l, frame) {
|
|
71
|
+
l.frame = frame;
|
|
72
|
+
if (l.frameTimer) return;
|
|
73
|
+
const wait = l.sentAt + frameMs - ctx.now();
|
|
74
|
+
const go = () => { l.frameTimer = null; const f = l.frame; l.frame = null; if (!f || l.stopped) return; l.sentAt = ctx.now(); ctx.emit(l.session_id, "preview.frame", f, null, "none", { transient: true }); };
|
|
75
|
+
if (wait <= 0) go(); else l.frameTimer = later(go, wait);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function onEvent(l, method, p, sessionId) {
|
|
79
|
+
const cdp = l.cdp;
|
|
80
|
+
if (method === "Target.attachedToTarget") {
|
|
81
|
+
const sid = p.sessionId, info = p.targetInfo ?? {};
|
|
82
|
+
// The browser's own first page (no opener) is the preview's page; any other page is a popup, closed.
|
|
83
|
+
if (info.type === "page" && !l.targetId && !info.openerId) l.targetId = info.targetId;
|
|
84
|
+
else if (info.type === "page" && info.targetId !== l.targetId) { block(l, "popup"); await cdp.send("Target.closeTarget", { targetId: info.targetId }).catch(() => {}); return; }
|
|
85
|
+
// Every frame and worker of the page passes the same interception, and so do the ones they start.
|
|
86
|
+
await cdp.send("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, sid).catch(() => {});
|
|
87
|
+
await cdp.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }, sid).catch(() => {});
|
|
88
|
+
if (info.targetId === l.targetId && !l.pageSession) await page(l, sid);
|
|
89
|
+
await cdp.send("Runtime.runIfWaitingForDebugger", {}, sid).catch(() => {});
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (method === "Fetch.requestPaused") {
|
|
93
|
+
if (originOk(p.request?.url, l.port)) return void cdp.send("Fetch.continueRequest", { requestId: p.requestId }, sessionId).catch(() => {});
|
|
94
|
+
block(l, p.resourceType === "Document" ? "navigation" : "request");
|
|
95
|
+
return void cdp.send("Fetch.failRequest", { requestId: p.requestId, errorReason: "BlockedByClient" }, sessionId).catch(() => {});
|
|
96
|
+
}
|
|
97
|
+
if (method === "Page.frameNavigated" && sessionId === l.pageSession && !p.frame?.parentId) {
|
|
98
|
+
const url = String(p.frame?.url ?? "");
|
|
99
|
+
if (url === "about:blank") return;
|
|
100
|
+
if (originOk(url, l.port)) { l.path = new URL(url).pathname.slice(0, 300) || "/"; l.good = url; return; }
|
|
101
|
+
// A navigation the interception failed lands on the browser's error page: back, counted once (by the interception).
|
|
102
|
+
if (!url.startsWith("chrome-error:")) block(l, url.startsWith("file:") ? "file" : "navigation");
|
|
103
|
+
return void cdp.send("Page.navigate", { url: l.good }, l.pageSession).catch(() => {});
|
|
104
|
+
}
|
|
105
|
+
if (method === "Page.screencastFrame" && sessionId === l.pageSession) {
|
|
106
|
+
cdp.send("Page.screencastFrameAck", { sessionId: p.sessionId }, l.pageSession).catch(() => {});
|
|
107
|
+
const data = toB64Url(String(p.data ?? ""));
|
|
108
|
+
if (Math.floor(data.length * 3 / 4) > P.MAX_FRAME_BYTES) return ctx.log("live_frame_dropped", {});
|
|
109
|
+
const m = p.metadata ?? {};
|
|
110
|
+
offerFrame(l, { width: Math.max(1, Math.min(4096, Math.round(m.deviceWidth ?? l.vp.width))), height: Math.max(1, Math.min(16_384, Math.round(m.deviceHeight ?? l.vp.height))), data });
|
|
111
|
+
if (l.state !== "live") { l.state = "live"; l.dirty(); }
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (method === "Page.loadEventFired" && sessionId === l.pageSession) {
|
|
115
|
+
const r = await cdp.send("Runtime.evaluate", { expression: "document.title", returnByValue: true }, l.pageSession).catch(() => null);
|
|
116
|
+
const t = typeof r?.result?.value === "string" ? r.result.value.trim().slice(0, 300) : "";
|
|
117
|
+
l.title = t || null; l.dirty();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (method === "Page.javascriptDialogOpening" && sessionId === l.pageSession) { block(l, "popup"); return void cdp.send("Page.handleJavaScriptDialog", { accept: false }, l.pageSession).catch(() => {}); }
|
|
121
|
+
if (method === "Browser.downloadWillBegin") block(l, "download");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function viewportOf(l) {
|
|
125
|
+
const mobile = l.viewport !== "desktop";
|
|
126
|
+
await l.cdp.send("Page.stopScreencast", {}, l.pageSession).catch(() => {}); // a second start alone keeps the old size
|
|
127
|
+
await l.cdp.send("Emulation.setDeviceMetricsOverride", { width: l.vp.width, height: l.vp.height, deviceScaleFactor: 1, mobile }, l.pageSession).catch(() => {});
|
|
128
|
+
await l.cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: l.vp.width, maxHeight: l.vp.height, everyNthFrame: 1 }, l.pageSession).catch(() => {});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function page(l, sid) {
|
|
132
|
+
l.pageSession = sid;
|
|
133
|
+
await l.cdp.send("Page.enable", {}, sid).catch(() => {});
|
|
134
|
+
await viewportOf(l);
|
|
135
|
+
l.cdp.send("Page.navigate", { url: l.url }, sid).catch(() => {});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function start(env, p) {
|
|
139
|
+
const project = ctx.sessionProject(env.session_id);
|
|
140
|
+
if (!project) return "not_found";
|
|
141
|
+
const g = ctx.grants()[project.project_id] ?? { ports: [], files: [] };
|
|
142
|
+
if (p.target === "port" ? !(g.ports ?? []).includes(p.port) : !(g.files ?? []).includes(p.path)) return "unsupported"; // granted at the keyboard only
|
|
143
|
+
const browser = (ctx.browser ?? (() => findBrowser(ctx.env())))();
|
|
144
|
+
if (!browser) return "unsupported";
|
|
145
|
+
if (live && live.session_id !== env.session_id) return "busy"; // one live preview per computer
|
|
146
|
+
if (live) await stop(live, "stopped");
|
|
147
|
+
if (p.target === "port" && !(await (ctx.listening ?? listening)(p.port))) return "not_found";
|
|
148
|
+
const server = p.target === "file" ? await (ctx.serve ?? serveProject)(project.path) : null;
|
|
149
|
+
const port = p.target === "port" ? p.port : server.port;
|
|
150
|
+
const profile = mkdtempSync(join(tmpdir(), "wt-live-"));
|
|
151
|
+
const l = { session_id: env.session_id, viewport: p.viewport, vp: P.PREVIEW_VIEWPORTS[p.viewport], port, server, profile, title: null, path: p.target === "port" ? p.path : `/${p.path}`, url: `http://127.0.0.1:${port}${p.target === "port" ? p.path : `/${p.path}`}`,
|
|
152
|
+
good: "about:blank", blocked: { ...P.NO_BLOCKS }, state: "starting", stopped: false, sentAt: -Infinity, frame: null, frameTimer: null, expiry: null, pageSession: null, targetId: null };
|
|
153
|
+
let dirtyTimer = null;
|
|
154
|
+
l.dirty = () => { if (!dirtyTimer) dirtyTimer = later(() => { dirtyTimer = null; if (!l.stopped) state(l, l.state); }, 250); };
|
|
155
|
+
l.proc = (ctx.spawnBrowser ?? spawnBrowserOnPipe)(browser, liveArgs({ profile: join(profile, "p"), port }), ctx.env());
|
|
156
|
+
l.cdp = createCdp({ write: l.proc.write, onEvent: (m, params, sid) => { onEvent(l, m, params, sid).catch(() => {}); } });
|
|
157
|
+
l.proc.onData((chunk) => l.cdp.feed(chunk));
|
|
158
|
+
l.proc.exited.then(() => { if (!l.stopped) stop(l, "browser_exited"); });
|
|
159
|
+
live = l;
|
|
160
|
+
l.expiry = later(() => stop(l, "unfollowed"), followMs);
|
|
161
|
+
state(l, "starting");
|
|
162
|
+
try {
|
|
163
|
+
await l.cdp.send("Browser.setDownloadBehavior", { behavior: "deny", eventsEnabled: true });
|
|
164
|
+
await l.cdp.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
|
|
165
|
+
// A browser that attached no first page of its own is given one (its attach event makes it the preview's page).
|
|
166
|
+
later(() => { if (!l.targetId && !l.stopped) l.cdp.send("Target.createTarget", { url: "about:blank" }).catch(() => {}); }, 1500);
|
|
167
|
+
} catch { await stop(l, "failed"); return "unsupported"; }
|
|
168
|
+
return "taken";
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function input(l, i) {
|
|
172
|
+
if (i.kind === "tap" || i.kind === "scroll") {
|
|
173
|
+
if (i.x >= l.vp.width || i.y >= l.vp.height) return "unsupported"; // inside the viewport only
|
|
174
|
+
if (i.kind === "scroll") return (await l.cdp.send("Input.dispatchMouseEvent", { type: "mouseWheel", x: i.x, y: i.y, deltaX: 0, deltaY: i.dy }, l.pageSession).then(() => "taken", () => "not_found"));
|
|
175
|
+
for (const type of ["mousePressed", "mouseReleased"]) await l.cdp.send("Input.dispatchMouseEvent", { type, x: i.x, y: i.y, button: "left", clickCount: 1 }, l.pageSession).catch(() => {});
|
|
176
|
+
return "taken";
|
|
177
|
+
}
|
|
178
|
+
if (i.kind === "text") { if (!P.liveTextOk(i.text)) return "unsupported"; return l.cdp.send("Input.insertText", { text: i.text }, l.pageSession).then(() => "taken", () => "not_found"); }
|
|
179
|
+
if (!Object.hasOwn(KEYCODE, i.key)) return "unsupported";
|
|
180
|
+
const code = KEYCODE[i.key];
|
|
181
|
+
await l.cdp.send("Input.dispatchKeyEvent", { type: "keyDown", key: i.key, code: i.key, windowsVirtualKeyCode: code, ...(i.key === "Enter" ? { text: "\r" } : {}) }, l.pageSession).catch(() => {});
|
|
182
|
+
await l.cdp.send("Input.dispatchKeyEvent", { type: "keyUp", key: i.key, code: i.key, windowsVirtualKeyCode: code }, l.pageSession).catch(() => {});
|
|
183
|
+
return "taken";
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
current: () => live,
|
|
188
|
+
async handle(env, payload) {
|
|
189
|
+
if (env.type === "preview.live_start") return start(env, payload);
|
|
190
|
+
const l = live && live.session_id === env.session_id ? live : null;
|
|
191
|
+
if (!l || l.stopped) return "not_found";
|
|
192
|
+
if (env.type === "preview.live_follow") {
|
|
193
|
+
if (!payload.follow) { await stop(l, "stopped"); return "taken"; }
|
|
194
|
+
clearTimeout(l.expiry); l.expiry = later(() => stop(l, "unfollowed"), followMs);
|
|
195
|
+
return "taken";
|
|
196
|
+
}
|
|
197
|
+
if (env.type === "preview.live_viewport") { l.viewport = payload.viewport; l.vp = P.PREVIEW_VIEWPORTS[payload.viewport]; await viewportOf(l); l.dirty(); return "taken"; }
|
|
198
|
+
if (env.type === "preview.live_input") return input(l, payload);
|
|
199
|
+
return "unsupported";
|
|
200
|
+
},
|
|
201
|
+
/** The session closed: its live preview ends. */
|
|
202
|
+
sessionClosed: (sessionId) => (live && live.session_id === sessionId ? stop(live, "closed") : undefined),
|
|
203
|
+
stopAll: () => (live ? stop(live, "stopped") : undefined),
|
|
204
|
+
};
|
|
205
|
+
}
|