ropetide-runner 0.0.0-stage → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +145 -2
  2. package/dist/apps/runner/src/agents.js +36 -0
  3. package/dist/apps/runner/src/browser.js +386 -0
  4. package/dist/apps/runner/src/browserProxy.js +120 -0
  5. package/dist/apps/runner/src/cli.js +449 -0
  6. package/dist/apps/runner/src/commands/redact.js +45 -0
  7. package/dist/apps/runner/src/commands/sandbox.js +61 -0
  8. package/dist/apps/runner/src/commands/shell.js +279 -0
  9. package/dist/apps/runner/src/extension.js +159 -0
  10. package/dist/apps/runner/src/files.js +163 -0
  11. package/dist/apps/runner/src/folderChoice.js +40 -0
  12. package/dist/apps/runner/src/main.js +351 -0
  13. package/dist/apps/runner/src/mcp/connectors.js +161 -0
  14. package/dist/apps/runner/src/pairCrypto.js +80 -0
  15. package/dist/apps/runner/src/planUsage.js +189 -0
  16. package/dist/apps/runner/src/power.js +11 -0
  17. package/dist/apps/runner/src/projects/access.js +337 -0
  18. package/dist/apps/runner/src/projects/http.js +74 -0
  19. package/dist/apps/runner/src/projects/prompt.js +19 -0
  20. package/dist/apps/runner/src/projects/rules.js +45 -0
  21. package/dist/apps/runner/src/projects/shares.js +192 -0
  22. package/dist/apps/runner/src/room.js +154 -0
  23. package/dist/apps/runner/src/run.js +182 -0
  24. package/dist/apps/runner/src/server.js +627 -0
  25. package/dist/apps/runner/src/skills.js +94 -0
  26. package/dist/apps/runner/src/tui.js +189 -0
  27. package/dist/apps/runner/src/video/analyse.js +95 -0
  28. package/dist/apps/runner/src/video/exec.js +32 -0
  29. package/dist/apps/runner/src/video/http.js +60 -0
  30. package/dist/apps/runner/src/video/probe.js +52 -0
  31. package/dist/apps/runner/src/video/render.js +322 -0
  32. package/dist/apps/runner/src/video/studio.js +329 -0
  33. package/dist/apps/runner/src/video/tools.js +24 -0
  34. package/dist/apps/runner/src/video.js +444 -0
  35. package/dist/supabase/functions/_shared/effort.js +16 -0
  36. package/dist/supabase/functions/_shared/folder-rules.js +129 -0
  37. package/dist/supabase/functions/_shared/github.js +319 -0
  38. package/dist/supabase/functions/_shared/localVideo.js +24 -0
  39. package/dist/supabase/functions/_shared/modelLimits.js +47 -0
  40. package/dist/supabase/functions/_shared/modelPrices.js +28 -0
  41. package/dist/supabase/functions/_shared/roles.js +18 -0
  42. package/dist/supabase/functions/_shared/room-command.js +70 -0
  43. package/dist/supabase/functions/_shared/roomBudget.js +60 -0
  44. package/dist/supabase/functions/_shared/video-plan.js +567 -0
  45. package/dist/supabase/functions/_shared/workspace.js +21 -0
  46. package/dist/supabase/functions/_shared/workspaceMeter.js +40 -0
  47. package/dist/supabase/functions/room-turn/context.js +154 -0
  48. package/dist/supabase/functions/room-turn/turn.js +750 -0
  49. package/package.json +36 -4
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The macOS sandbox (Seatbelt) a room's command runs in. Everything is refused unless named here.
3
+ * A command may read the project folder, the system and installed developer tools, and write only
4
+ * to the project folder and its own temporary folder. It has no network at all, this computer
5
+ * included: a rule letting it reach local ports while blocking Runner's was tried and held for
6
+ * some port numbers and not others. Paths arrive as parameters, never as text in the profile.
7
+ */
8
+ /** A regex fragment that matches `name` in any case: macOS file names ignore case. */
9
+ const anyCase = (name) => name.replace(/[a-z]/g, (c) => `[${c}${c.toUpperCase()}]`);
10
+ const alternatives = (names) => `(${names.map(anyCase).join('|')})`;
11
+ /** Files that usually hold keys or passwords. A command can neither read nor change them. */
12
+ export const SECRET_PATTERNS = [
13
+ `/${anyCase('.env')}($|\\.)`,
14
+ `/${alternatives(['.npmrc', '.netrc', '.pypirc', '.htpasswd'])}$`,
15
+ `/${alternatives(['.ssh', '.aws', '.gnupg'])}(/|$)`,
16
+ `\\.${alternatives(['pem', 'key', 'p8', 'p12', 'pfx', 'keystore', 'jks', 'kdbx'])}$`,
17
+ `/${anyCase('id_')}${alternatives(['rsa', 'dsa', 'ecdsa', 'ed25519'])}[^/]*$`,
18
+ `/${alternatives(['secret', 'secrets', 'credential', 'credentials'])}([._-][^/]*)?\\.${alternatives(['json', 'yaml', 'yml', 'toml', 'ini', 'txt', 'xml', 'properties'])}$`,
19
+ `/[^/]*${anyCase('service')}[-_ ]?${anyCase('account')}[^/]*\\.${anyCase('json')}$`,
20
+ ];
21
+ /**
22
+ * Files that run, or give an AI tool orders, outside this sandbox: Git hooks and settings, CI
23
+ * workflows, editor tasks, shell hooks and agent instructions. Readable, never writable.
24
+ */
25
+ const AUTORUN_PATTERNS = [
26
+ `/${alternatives(['.git', '.husky', '.githooks', '.github', '.vscode', '.idea', '.claude', '.codex', '.cursor', '.gemini', '.devcontainer'])}(/|$)`,
27
+ `/${alternatives(['.envrc', '.mcp.json', '.yarnrc', '.yarnrc.yml', '.pnpmfile.cjs', 'claude.md', 'claude.local.md', 'agents.md', 'agents.override.md', 'gemini.md'])}$`,
28
+ ];
29
+ /** What macOS programs need to read in order to start. */
30
+ const SYSTEM_READS = [
31
+ '(literal "/")', '(subpath "/bin")', '(subpath "/sbin")', '(subpath "/usr")', '(subpath "/opt")', '(subpath "/System")',
32
+ '(subpath "/Library/Developer")', '(subpath "/Library/Frameworks")', '(subpath "/Library/Apple")', '(literal "/Library/Preferences/com.apple.dt.Xcode.plist")',
33
+ '(subpath "/Applications/Xcode.app")', '(subpath "/private/etc")', '(subpath "/private/var/db/dyld")', '(subpath "/private/var/db/timezone")', '(subpath "/private/var/select")',
34
+ '(literal "/dev/null")', '(literal "/dev/zero")', '(literal "/dev/random")', '(literal "/dev/urandom")', '(literal "/dev/dtracehelper")', '(subpath "/dev/fd")',
35
+ ];
36
+ const inFolder = (pattern) => `(require-all (subpath (param "FOLDER")) (regex #"${pattern}"))`;
37
+ /** `toolDirs` is how many TOOL0, TOOL1, … parameters name developer tools to read. */
38
+ export function seatbeltProfile({ toolDirs }) {
39
+ const tools = Array.from({ length: toolDirs }, (_, i) => `(subpath (param "TOOL${i}"))`);
40
+ return [
41
+ '(version 1)',
42
+ '(deny default)',
43
+ '(allow process-exec)',
44
+ '(allow process-fork)',
45
+ '(allow signal (target same-sandbox))',
46
+ '(allow process-info* (target same-sandbox))',
47
+ '(allow sysctl-read)',
48
+ // Names and sizes only, which finding files by path needs; contents are limited below.
49
+ '(allow file-read-metadata)',
50
+ `(allow file-read* ${[...SYSTEM_READS, '(subpath (param "FOLDER"))', '(subpath (param "TMP"))', ...tools].join(' ')})`,
51
+ '(allow file-write* (subpath (param "FOLDER")) (subpath (param "TMP")))',
52
+ '(allow file-write-data (literal "/dev/null") (literal "/dev/zero") (literal "/dev/dtracehelper"))',
53
+ '(allow file-ioctl (literal "/dev/null") (literal "/dev/dtracehelper"))',
54
+ // User and group names, nothing else: no app launching, scripting, clipboard or Keychain.
55
+ '(allow mach-lookup (global-name "com.apple.system.opendirectoryd.libinfo"))',
56
+ '(allow ipc-posix-sem)',
57
+ // Refusing every kind of access also hides these files from tools that only check they exist.
58
+ ...SECRET_PATTERNS.map((p) => `(deny file-read* file-write* ${inFolder(p)})`),
59
+ ...AUTORUN_PATTERNS.map((p) => `(deny file-write* ${inFolder(p)})`),
60
+ ].join('\n');
61
+ }
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Runs a room's commands in one folder on this computer, which the person names when they start
3
+ * Runner. Each command is one the person allowed in the room; it runs in the sandbox (sandbox.ts)
4
+ * with a clean environment and an empty home folder, one at a time, and everything it started is
5
+ * stopped when it ends. Only macOS has a sandbox here, so other systems refuse.
6
+ */
7
+ import { spawn } from 'node:child_process';
8
+ import { existsSync } from 'node:fs';
9
+ import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises';
10
+ import { createServer } from 'node:net';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { commandRefusal } from "../../../../supabase/functions/_shared/room-command.js";
14
+ import { chooseFolder, shownPath, within } from "../folderChoice.js";
15
+ import { redactOutput } from "./redact.js";
16
+ import { seatbeltProfile } from "./sandbox.js";
17
+ const SANDBOX = '/usr/bin/sandbox-exec';
18
+ /** Under the browser's own limit on one request. */
19
+ export const COMMAND_TIMEOUT_MS = 240_000;
20
+ /** The most output sent back: the start, and more of the end, where errors and totals are. */
21
+ const SENT_HEAD = 800;
22
+ const SENT_TAIL = 2200;
23
+ /** What is held while a command runs: this much of the start and of the end. */
24
+ const HELD = 100_000;
25
+ /** How long to wait for output after a command ends, if something it started still holds it open. */
26
+ const DRAIN_MS = 1000;
27
+ /** Stopping a command's processes: how long between signals, and how many rounds of each at most. */
28
+ const SWEEP_MS = 20;
29
+ const FREEZES = 3;
30
+ const KILLS = 100;
31
+ /** Signals a process group. False once nothing is left in it. */
32
+ function signalGroup(group, name) {
33
+ try {
34
+ process.kill(-group, name);
35
+ }
36
+ catch (e) {
37
+ return !(e instanceof Error && 'code' in e && e.code === 'ESRCH');
38
+ }
39
+ return true;
40
+ }
41
+ /**
42
+ * Stops everything in a process group. It is frozen first, over a few rounds, then killed until
43
+ * empty: a process being started as a signal lands is missed by it, and a shell whose child was
44
+ * killed first would carry on to its next step.
45
+ */
46
+ async function sweep(group) {
47
+ const pause = () => new Promise((r) => setTimeout(r, SWEEP_MS));
48
+ for (let i = 0; i < FREEZES; i++) {
49
+ if (!signalGroup(group, 'SIGSTOP'))
50
+ return;
51
+ await pause();
52
+ }
53
+ for (let i = 0; i < KILLS; i++) {
54
+ if (!signalGroup(group, 'SIGKILL'))
55
+ return;
56
+ await pause();
57
+ }
58
+ }
59
+ /** The folder commands may run in, resolved, or why it can't be used (see folderChoice.ts). */
60
+ export const commandFolder = (wanted, home) => chooseFolder(wanted, home, {
61
+ empty: 'Name a folder for commands.',
62
+ hidden: 'Commands can’t run in a hidden folder or one inside it. Use a copy somewhere else.',
63
+ library: 'Library holds app data, so commands can’t run there.',
64
+ system: 'System folders can’t be used for commands.',
65
+ });
66
+ /** Developer tools people install in their home folder, read-only. Never the folders that hold their logins. */
67
+ const HOME_TOOLS = [
68
+ '.nvm/versions', '.volta/bin', '.volta/tools', '.fnm/node-versions', '.local/share/fnm/node-versions', 'Library/Application Support/fnm/node-versions',
69
+ '.asdf/installs', '.asdf/shims', '.asdf/plugins', '.pyenv/versions', '.pyenv/shims', '.rbenv/versions', '.rbenv/shims', '.local/share/mise/installs', '.local/share/mise/shims',
70
+ '.local/share/uv/python', '.cargo/bin', '.rustup', '.bun/bin', '.deno/bin', 'go/pkg/mod', 'Library/pnpm', '.local/share/pnpm', '.cache/node/corepack', 'Library/Caches/node/corepack',
71
+ ];
72
+ async function toolFolders(home, node) {
73
+ // The Node that runs Runner, when it was installed under home.
74
+ const own = path.dirname(path.dirname(node));
75
+ const wanted = [...HOME_TOOLS.map((p) => path.join(home, p)), ...(within(home, own) && own !== home ? [own] : [])];
76
+ const found = await Promise.all(wanted.map((p) => realpath(p).catch(() => '')));
77
+ return [...new Set(found.filter((p) => p && !within(p, home)))];
78
+ }
79
+ /** Only what tools need to find themselves: no keys, tokens or settings from the terminal. */
80
+ function commandEnv(env, home, tmp) {
81
+ const paths = (env.PATH ?? '/usr/bin:/bin').split(':').filter((p) => path.isAbsolute(p));
82
+ // Apple's git and compilers, ahead of the /usr/bin stand-ins that try to write caches first.
83
+ const developer = '/Applications/Xcode.app/Contents/Developer/usr/bin';
84
+ const system = paths.indexOf('/usr/bin');
85
+ if (existsSync(developer))
86
+ paths.splice(system < 0 ? paths.length : system, 0, developer);
87
+ const out = {
88
+ PATH: paths.join(':'),
89
+ HOME: path.join(tmp, 'home'),
90
+ TMPDIR: tmp,
91
+ SHELL: '/bin/bash',
92
+ LANG: env.LANG ?? 'en_US.UTF-8',
93
+ TERM: 'dumb',
94
+ // Test runners run once and plainly, instead of watching or drawing.
95
+ CI: '1',
96
+ NO_COLOR: '1',
97
+ COREPACK_ENABLE_NETWORK: '0',
98
+ GOCACHE: path.join(tmp, 'go-cache'),
99
+ };
100
+ const tools = [['PNPM_HOME', 'Library/pnpm'], ['RUSTUP_HOME', '.rustup'], ['PYENV_ROOT', '.pyenv'], ['RBENV_ROOT', '.rbenv'], ['ASDF_DATA_DIR', '.asdf'], ['VOLTA_HOME', '.volta'], ['NVM_DIR', '.nvm'], ['GOPATH', 'go'], ['COREPACK_HOME', env.COREPACK_HOME ?? '.cache/node/corepack']];
101
+ for (const [name, dir] of tools) {
102
+ const full = path.resolve(home, dir);
103
+ if (existsSync(full))
104
+ out[name] = full;
105
+ }
106
+ return out;
107
+ }
108
+ // Terminal control sequences are exactly what these two take out.
109
+ // eslint-disable-next-line no-control-regex
110
+ const ESCAPES = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|.)/g;
111
+ const CONTROLS = /[^\P{Cc}\n\t]/gu;
112
+ /** Output as the room shows it: plain text, without this computer's paths or anything shaped like a key. */
113
+ function presented(raw, folder, home) {
114
+ const plain = raw.replace(ESCAPES, '').replace(/\r\n?/g, '\n').replace(CONTROLS, '');
115
+ const text = redactOutput(plain.replaceAll(folder, '.').replaceAll(home, '~')).trim();
116
+ if (text.length <= SENT_HEAD + SENT_TAIL)
117
+ return { output: text, leftOut: 0 };
118
+ const leftOut = text.length - SENT_HEAD - SENT_TAIL;
119
+ return { output: `${text.slice(0, SENT_HEAD)}\n[… ${leftOut.toLocaleString('en-US')} characters left out …]\n${text.slice(-SENT_TAIL)}`, leftOut };
120
+ }
121
+ /**
122
+ * Tries a sandbox profile against throwaway files and a local listener. True only when a command
123
+ * ran inside it and could not read outside its folder, read an .env file, write outside or into
124
+ * .git, or connect.
125
+ */
126
+ export async function sandboxHolds(profile) {
127
+ let root = '';
128
+ const listener = createServer((socket) => socket.end());
129
+ try {
130
+ root = await realpath(await mkdtemp(path.join(os.tmpdir(), 'ropetide-check-')));
131
+ const folder = path.join(root, 'folder');
132
+ const tmp = path.join(root, 'tmp');
133
+ await Promise.all([mkdir(path.join(folder, '.git'), { recursive: true }), mkdir(tmp)]);
134
+ await writeFile(path.join(root, 'outside'), 'LEAK-outside');
135
+ await writeFile(path.join(folder, '.env'), 'LEAK-env');
136
+ await new Promise((ok, fail) => listener.once('error', fail).listen(0, '127.0.0.1', ok));
137
+ const address = listener.address();
138
+ if (!address || typeof address === 'string')
139
+ return false;
140
+ const probe = `echo ran; cat ../outside .env; echo x > ../written; echo x > .git/planted; (exec 3<>/dev/tcp/127.0.0.1/${address.port}) && echo LEAK-network`;
141
+ const output = await new Promise((resolve) => {
142
+ let said = '';
143
+ const child = spawn(SANDBOX, ['-p', profile, '-D', `FOLDER=${folder}`, '-D', `TMP=${tmp}`, '/bin/bash', '--noprofile', '--norc', '-c', probe], { cwd: folder, env: { PATH: '/usr/bin:/bin', HOME: tmp, TMPDIR: tmp }, stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000, killSignal: 'SIGKILL' });
144
+ child.stdout.on('data', (d) => { said += String(d); });
145
+ child.stderr.on('data', (d) => { said += String(d); });
146
+ child.on('error', () => resolve(''));
147
+ child.on('close', () => resolve(said));
148
+ });
149
+ return output.startsWith('ran') && !output.includes('LEAK-') && !existsSync(path.join(root, 'written')) && !existsSync(path.join(folder, '.git', 'planted'));
150
+ }
151
+ catch {
152
+ return false;
153
+ }
154
+ finally {
155
+ listener.close();
156
+ if (root)
157
+ await rm(root, { recursive: true, force: true }).catch(() => { });
158
+ }
159
+ }
160
+ export async function commandShell(opts) {
161
+ const platform = opts.platform ?? process.platform;
162
+ if (platform !== 'darwin' || !existsSync(SANDBOX))
163
+ return { ok: false, reason: 'Commands need the macOS sandbox, so they aren’t available on this system yet.' };
164
+ const home = await realpath(opts.home ?? os.homedir()).catch(() => opts.home ?? os.homedir());
165
+ const chosen = await commandFolder(opts.folder, home);
166
+ if (!chosen.ok)
167
+ return chosen;
168
+ const { folder } = chosen;
169
+ const tools = await toolFolders(home, process.execPath);
170
+ const profile = seatbeltProfile({ toolDirs: tools.length });
171
+ // The sandbox's behaviour belongs to macOS and can change with it, so it is tried before it is trusted.
172
+ if (!(await sandboxHolds(seatbeltProfile({ toolDirs: 0 }))))
173
+ return { ok: false, reason: 'The macOS sandbox on this computer didn’t hold when Runner tested it, so commands stay off.' };
174
+ const timeoutMs = opts.timeoutMs ?? COMMAND_TIMEOUT_MS;
175
+ let running = null;
176
+ let busy = false;
177
+ let closed = false;
178
+ const execute = (command, tmp, signal) => new Promise((resolve) => {
179
+ const started = opts.now();
180
+ const params = [`FOLDER=${folder}`, `TMP=${tmp}`, ...tools.map((t, i) => `TOOL${i}=${t}`)].flatMap((p) => ['-D', p]);
181
+ // Its own process group, so stopping it also stops what it started.
182
+ const child = spawn(SANDBOX, ['-p', profile, ...params, '/bin/bash', '--noprofile', '--norc', '-c', command], { cwd: folder, env: commandEnv(opts.env, home, tmp), stdio: ['ignore', 'pipe', 'pipe'], detached: true });
183
+ let head = '';
184
+ let tail = '';
185
+ let total = 0;
186
+ const take = (d) => {
187
+ total += d.length;
188
+ if (head.length < HELD) {
189
+ const room = HELD - head.length;
190
+ head += d.slice(0, room);
191
+ d = d.slice(room);
192
+ }
193
+ if (d)
194
+ tail = (tail + d).slice(-HELD);
195
+ };
196
+ let timedOut = false;
197
+ let stopped = false;
198
+ let settled = false;
199
+ let drain;
200
+ let swept;
201
+ // Each call starts a fresh sweep after the last, so a late one still covers what appeared since.
202
+ const kill = () => { const group = child.pid; if (group)
203
+ swept = (swept ?? Promise.resolve()).then(() => sweep(group)); };
204
+ const timer = setTimeout(() => { timedOut = true; kill(); }, timeoutMs);
205
+ const abort = () => { stopped = true; kill(); };
206
+ signal?.addEventListener('abort', abort, { once: true });
207
+ const done = (exitCode) => {
208
+ if (settled)
209
+ return;
210
+ settled = true;
211
+ clearTimeout(timer);
212
+ clearTimeout(drain);
213
+ signal?.removeEventListener('abort', abort);
214
+ const ms = opts.now() - started;
215
+ // Answered only once everything it started is gone, so the next command starts alone.
216
+ void (swept ?? Promise.resolve()).then(() => {
217
+ running = null;
218
+ const gap = total - head.length - tail.length;
219
+ const shown = presented(head + (gap > 0 ? '\n' : '') + tail, folder, home);
220
+ resolve({ ok: true, exitCode: timedOut || stopped ? null : exitCode, ms, timedOut, stopped, output: shown.output, leftOut: shown.leftOut + Math.max(0, gap) });
221
+ });
222
+ };
223
+ child.stdout.setEncoding('utf8');
224
+ child.stderr.setEncoding('utf8');
225
+ child.stdout.on('data', take);
226
+ child.stderr.on('data', take);
227
+ child.on('error', () => { if (settled)
228
+ return; settled = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); running = null; resolve({ ok: false, code: 'failed', reason: 'The command could not be started.' }); });
229
+ let code = null;
230
+ child.on('exit', (exit) => {
231
+ code = exit;
232
+ // Anything it left in the background goes with it.
233
+ kill();
234
+ drain = setTimeout(() => { child.stdout.destroy(); child.stderr.destroy(); done(code); }, DRAIN_MS);
235
+ });
236
+ child.on('close', () => done(code));
237
+ const ended = new Promise((ok) => child.once('close', () => ok()));
238
+ running = { stop: abort, ended };
239
+ if (signal?.aborted)
240
+ abort();
241
+ });
242
+ const shell = {
243
+ info: { name: path.basename(folder), path: shownPath(folder, home) },
244
+ async run(command, signal) {
245
+ const why = commandRefusal(command);
246
+ if (why)
247
+ return { ok: false, code: 'refused', reason: why };
248
+ if (closed)
249
+ return { ok: false, code: 'refused', reason: 'Runner is stopping.' };
250
+ if (busy)
251
+ return { ok: false, code: 'busy', reason: 'Another command is still running.' };
252
+ busy = true;
253
+ let tmp = '';
254
+ try {
255
+ tmp = await realpath(await mkdtemp(path.join(os.tmpdir(), 'ropetide-command-')));
256
+ await mkdir(path.join(tmp, 'home'), { mode: 0o700 });
257
+ if (closed)
258
+ return { ok: false, code: 'refused', reason: 'Runner is stopping.' };
259
+ // An abort that arrived while preparing is seen as the command starts.
260
+ return await execute(command, tmp, signal);
261
+ }
262
+ catch {
263
+ return { ok: false, code: 'failed', reason: 'The command could not be started.' };
264
+ }
265
+ finally {
266
+ if (tmp)
267
+ await rm(tmp, { recursive: true, force: true }).catch(() => { });
268
+ busy = false;
269
+ }
270
+ },
271
+ async close() {
272
+ closed = true;
273
+ const current = running;
274
+ current?.stop();
275
+ await current?.ended;
276
+ },
277
+ };
278
+ return { ok: true, shell };
279
+ }
@@ -0,0 +1,159 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ /**
3
+ * The Ropetide Chrome extension as the room's browser (Runner started with --chrome).
4
+ *
5
+ * The extension's side panel pairs with Runner the same way the website does (a code typed into
6
+ * Runner, see pairCrypto.ts), with its own pairing and token, so a website token can't drive the
7
+ * extension and an extension token can't start room turns. Once paired, the panel asks Runner for
8
+ * work by long polling (/v1/extension/next) and posts each result back (/v1/extension/result).
9
+ * While the panel is closed nothing polls, and every action fails with a reason the agent can read.
10
+ *
11
+ * Runner keeps every rule it has for its own browser: clicks and form entry still need
12
+ * Auto-approve, and the extension asks the person again before each one. The page text the
13
+ * extension sends back is untrusted, exactly like the Playwright browser's.
14
+ */
15
+ /** Only Chrome extension pages may use the extension routes: chrome-extension:// and a 32-letter id. */
16
+ export function extensionOrigin(origin) {
17
+ return typeof origin === 'string' && /^chrome-extension:\/\/[a-p]{32}$/.test(origin);
18
+ }
19
+ const NOT_OPEN = 'The Ropetide panel in Chrome is closed. Ask the person to open it (the Ropetide button in Chrome’s toolbar), then try again.';
20
+ const MAX_SCREENSHOT = 3_000_000;
21
+ /** A view from the extension, checked field by field; anything else is refused. */
22
+ export function parseView(value) {
23
+ if (!value || typeof value !== 'object')
24
+ return null;
25
+ const v = value;
26
+ const str = (x, max) => (typeof x === 'string' && x.length <= max ? x : null);
27
+ const url = str(v.url, 2000);
28
+ const title = str(v.title, 300);
29
+ const text = str(v.text, 24000);
30
+ // A JPEG as base64, or nothing when the agent window wasn't showing its page.
31
+ const screenshot = str(v.screenshot, MAX_SCREENSHOT);
32
+ if (url === null || title === null || text === null || screenshot === null)
33
+ return null;
34
+ if (screenshot && !/^[A-Za-z0-9+/]+={0,2}$/.test(screenshot))
35
+ return null;
36
+ const activity = Array.isArray(v.activity) && v.activity.length <= 15 && v.activity.every((a) => typeof a === 'string' && a.length <= 80) ? v.activity : null;
37
+ if (!activity)
38
+ return null;
39
+ return { url, title, text, screenshot, activity };
40
+ }
41
+ /** A result from the extension, or a refusal when it isn't one. Reasons are shortened, never trusted as instructions. */
42
+ export function parseResult(value) {
43
+ if (!value || typeof value !== 'object')
44
+ return { ok: false, reason: 'Chrome sent back something Runner could not read.' };
45
+ const r = value;
46
+ if (r.ok === true) {
47
+ const view = parseView(r.view);
48
+ return view ? { ok: true, view } : { ok: false, reason: 'Chrome sent back a page Runner could not read.' };
49
+ }
50
+ const reason = typeof r.reason === 'string' && r.reason.trim() ? r.reason.trim().slice(0, 300) : 'The action did not complete in Chrome.';
51
+ return { ok: false, reason };
52
+ }
53
+ export class ExtensionBridge {
54
+ queue = [];
55
+ waiting = new Map();
56
+ poller = null;
57
+ lastPoll = Number.NEGATIVE_INFINITY;
58
+ now;
59
+ actMs;
60
+ /** `actMs` covers the person's Allow or Deny in the panel; the room turn has its own deadline on top. */
61
+ constructor(opts = {}) {
62
+ this.now = opts.now ?? (() => Date.now());
63
+ this.actMs = opts.actMs ?? 90_000;
64
+ }
65
+ /** Whether the panel has asked for work lately: it polls again at most a few seconds after each answer. */
66
+ get connected() {
67
+ // Polling now, polled a moment ago, or busy with a step (the person may be deciding on it).
68
+ return !!this.poller || this.waiting.size > 0 || this.now() - this.lastPoll < 10_000;
69
+ }
70
+ /** The panel's long poll: the next request, or null after `waitMs` with nothing to do. One panel at a time. */
71
+ next(waitMs) {
72
+ this.lastPoll = this.now();
73
+ // A newer poll replaces an older one (the panel reloaded); the older gets nothing.
74
+ if (this.poller) {
75
+ clearTimeout(this.poller.timer);
76
+ this.poller.resolve(null);
77
+ this.poller = null;
78
+ }
79
+ const ready = this.queue.shift();
80
+ if (ready)
81
+ return Promise.resolve(ready);
82
+ return new Promise((resolve) => {
83
+ const poller = {
84
+ resolve,
85
+ timer: setTimeout(() => { if (this.poller === poller)
86
+ this.poller = null; this.lastPoll = this.now(); resolve(null); }, waitMs),
87
+ };
88
+ this.poller = poller;
89
+ });
90
+ }
91
+ /** The panel's answer to one request. Unknown or late ids are ignored. */
92
+ result(id, value) {
93
+ if (typeof id !== 'string')
94
+ return false;
95
+ const w = this.waiting.get(id);
96
+ if (!w)
97
+ return false;
98
+ this.waiting.delete(id);
99
+ clearTimeout(w.timer);
100
+ w.resolve(parseResult(value));
101
+ return true;
102
+ }
103
+ /** The panel closed or unpaired: everything waiting on it fails now rather than at its deadline. */
104
+ disconnect() {
105
+ this.lastPoll = Number.NEGATIVE_INFINITY;
106
+ if (this.poller) {
107
+ clearTimeout(this.poller.timer);
108
+ this.poller.resolve(null);
109
+ this.poller = null;
110
+ }
111
+ this.queue = [];
112
+ for (const [id, w] of this.waiting) {
113
+ clearTimeout(w.timer);
114
+ this.waiting.delete(id);
115
+ w.resolve({ ok: false, reason: 'Chrome disconnected from Runner.' });
116
+ }
117
+ }
118
+ push(request) {
119
+ if (this.poller) {
120
+ const p = this.poller;
121
+ this.poller = null;
122
+ this.lastPoll = this.now();
123
+ clearTimeout(p.timer);
124
+ p.resolve(request);
125
+ }
126
+ else
127
+ this.queue.push(request);
128
+ }
129
+ send(session, action, allowInteraction) {
130
+ if (!this.connected)
131
+ return Promise.resolve({ ok: false, reason: NOT_OPEN });
132
+ const id = randomBytes(16).toString('hex');
133
+ return new Promise((resolve) => {
134
+ const timer = setTimeout(() => {
135
+ this.waiting.delete(id);
136
+ this.queue = this.queue.filter((q) => q.id !== id);
137
+ resolve({ ok: false, reason: 'Chrome did not answer in time. The person may not have allowed the step, or the panel was closed.' });
138
+ }, this.actMs);
139
+ this.waiting.set(id, { resolve, timer });
140
+ this.push({ id, kind: 'act', session, action, allowInteraction });
141
+ });
142
+ }
143
+ /** A room browser backed by the extension, for BrowserSessions. Each one is its own session in Chrome. */
144
+ async open() {
145
+ const session = randomBytes(8).toString('hex');
146
+ return {
147
+ act: (action, allowInteraction) => {
148
+ if ((action.action === 'click' || action.action === 'fill') && !allowInteraction) {
149
+ return Promise.resolve({ ok: false, reason: 'Clicks and form entry require Auto-approve. You can still read and navigate by URL.' });
150
+ }
151
+ return this.send(session, action, allowInteraction);
152
+ },
153
+ close: async () => { if (this.connected)
154
+ this.push({ id: randomBytes(16).toString('hex'), kind: 'close', session }); },
155
+ };
156
+ }
157
+ }
158
+ /** A line added to the browser instructions when the room's browser is the person's own Chrome. */
159
+ export const CHROME_NOTE = `This browser is the person's own Chrome, opened in a separate Ropetide window. Sites may be signed in to their real accounts. Stay on what the person asked for, never change account settings, and expect each click and typing step to wait for the person to allow it in Chrome; if they deny it, do not try the same step another way.`;
@@ -0,0 +1,163 @@
1
+ import { lstat, mkdir, readdir, readFile, realpath, stat, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { sharedPathRefusal, textRefusal } from "./projects/rules.js";
4
+ const MAX_READ_BYTES = 200_000;
5
+ const MAX_WRITE_BYTES = 1_000_000;
6
+ const MAX_LIST = 200;
7
+ const refused = (why) => ({ ok: false, reason: `Runner won’t use that: ${why}.` });
8
+ const SECOND_NAME = 'it has a second name somewhere else (a hard link)';
9
+ const namesBelow = (root, full) => path.relative(root, full).split(path.sep).filter(Boolean);
10
+ /** Resolves `--share` arguments to real, existing directories with unique display names. */
11
+ export async function resolveShares(specs) {
12
+ const out = [];
13
+ for (const spec of specs) {
14
+ const rw = spec.endsWith(':rw');
15
+ const raw = rw ? spec.slice(0, -3) : spec;
16
+ const expanded = raw.startsWith('~') ? path.join(process.env.HOME ?? '', raw.slice(1)) : raw;
17
+ const root = await realpath(path.resolve(expanded));
18
+ if (!(await stat(root)).isDirectory())
19
+ throw new Error(`${raw} is not a folder`);
20
+ let name = path.basename(root) || root;
21
+ while (out.some((f) => f.name === name))
22
+ name = `${name}-${out.length + 1}`;
23
+ out.push({ name, root, mode: rw ? 'read-write' : 'read' });
24
+ }
25
+ return out;
26
+ }
27
+ /**
28
+ * Maps an agent-supplied path like "Invoices/contract.txt" to a real path inside a
29
+ * shared folder. The first segment names the folder. Anything that escapes the
30
+ * folder, including through a symlink, is refused. So is any path through a symlink
31
+ * that cannot be resolved (missing target or loop), wherever it points. Hidden files, key files
32
+ * and secret folders are refused both by the name asked for and by where a link leads.
33
+ */
34
+ export async function locate(folders, given, forWrite) {
35
+ const clean = given.replace(/\\/g, '/').replace(/^\/+/, '');
36
+ const [head, ...rest] = clean.split('/');
37
+ const folder = folders.find((f) => f.name === head);
38
+ if (!folder)
39
+ return { ok: false, reason: `"${head ?? ''}" is not a shared folder. Shared folders: ${folders.map((f) => f.name).join(', ') || 'none'}.` };
40
+ if (forWrite && folder.mode !== 'read-write')
41
+ return { ok: false, reason: `${folder.name} is shared read-only.` };
42
+ const target = path.resolve(folder.root, ...rest);
43
+ const inside = (p) => p === folder.root || p.startsWith(folder.root + path.sep);
44
+ if (!inside(target))
45
+ return { ok: false, reason: 'That path is outside the shared folder.' };
46
+ const use = forWrite ? 'write' : 'read';
47
+ const named = sharedPathRefusal(namesBelow(folder.root, target), use);
48
+ if (named)
49
+ return refused(named);
50
+ // Resolve symlinks on the deepest part that exists, so a link cannot point outside.
51
+ let probe = target;
52
+ for (;;) {
53
+ try {
54
+ const real = await realpath(probe);
55
+ if (!inside(real))
56
+ return { ok: false, reason: 'That path leads outside the shared folder.' };
57
+ const led = sharedPathRefusal(namesBelow(folder.root, path.join(real, path.relative(probe, target))), use);
58
+ if (led)
59
+ return refused(led);
60
+ break;
61
+ }
62
+ catch {
63
+ // realpath also fails on a link whose target is missing, and a write would follow
64
+ // that link. Only step up past a part that is truly absent.
65
+ try {
66
+ await lstat(probe);
67
+ return { ok: false, reason: 'That path goes through a link Runner cannot resolve.' };
68
+ }
69
+ catch (err) {
70
+ const code = err.code;
71
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
72
+ return { ok: false, reason: 'Runner could not check that path.' };
73
+ }
74
+ const parent = path.dirname(probe);
75
+ if (parent === probe)
76
+ return { ok: false, reason: 'That path does not exist.' };
77
+ probe = parent;
78
+ }
79
+ }
80
+ return { ok: true, folder, full: target };
81
+ }
82
+ export async function listFiles(folders, given) {
83
+ if (!given || given === '/' || given === '.') {
84
+ return { ok: true, value: folders.map((f) => `${f.name}/ (${f.mode})`).join('\n') || 'No folders are shared.' };
85
+ }
86
+ const at = await locate(folders, given, false);
87
+ if (!at.ok)
88
+ return at;
89
+ try {
90
+ const entries = await readdir(at.full, { withFileTypes: true });
91
+ const lines = entries
92
+ .filter((e) => !sharedPathRefusal([...namesBelow(at.folder.root, at.full), e.name], 'read'))
93
+ .slice(0, MAX_LIST)
94
+ .map((e) => (e.isDirectory() ? `${e.name}/` : e.name));
95
+ return { ok: true, value: lines.join('\n') || '(empty folder)' };
96
+ }
97
+ catch {
98
+ return { ok: false, reason: 'That is not a folder Runner can list.' };
99
+ }
100
+ }
101
+ export async function readText(folders, given) {
102
+ const at = await locate(folders, given, false);
103
+ if (!at.ok)
104
+ return at;
105
+ try {
106
+ const info = await stat(at.full);
107
+ if (!info.isFile())
108
+ return { ok: false, reason: 'That is a folder, not a file.' };
109
+ if (info.nlink !== 1)
110
+ return refused(SECOND_NAME);
111
+ if (info.size > MAX_READ_BYTES)
112
+ return { ok: false, reason: `That file is ${Math.round(info.size / 1000)} KB; Runner reads files up to ${MAX_READ_BYTES / 1000} KB.` };
113
+ const buf = await readFile(at.full);
114
+ if (buf.includes(0))
115
+ return { ok: false, reason: 'That looks like a binary file (PDF, image or similar). Runner can only read text files for now.' };
116
+ const text = buf.toString('utf8');
117
+ const why = textRefusal(text);
118
+ return why ? refused(why) : { ok: true, value: text };
119
+ }
120
+ catch {
121
+ return { ok: false, reason: 'That file does not exist.' };
122
+ }
123
+ }
124
+ /** Why an existing file mustn't be replaced, or null, also when there is no file yet. */
125
+ async function replaceRefusal(full) {
126
+ let info;
127
+ try {
128
+ info = await stat(full);
129
+ }
130
+ catch (err) {
131
+ if (err.code === 'ENOENT')
132
+ return null;
133
+ throw err;
134
+ }
135
+ if (!info.isFile())
136
+ return null;
137
+ if (info.nlink !== 1)
138
+ return SECOND_NAME;
139
+ if (info.size > MAX_WRITE_BYTES)
140
+ return 'the file there is too large to check';
141
+ return textRefusal(await readFile(full, 'utf8'));
142
+ }
143
+ export async function writeText(folders, given, content) {
144
+ if (Buffer.byteLength(content) > MAX_WRITE_BYTES)
145
+ return { ok: false, reason: 'That file is too large to write.' };
146
+ const at = await locate(folders, given, true);
147
+ if (!at.ok)
148
+ return at;
149
+ const why = textRefusal(content);
150
+ if (why)
151
+ return refused(why);
152
+ try {
153
+ const kept = await replaceRefusal(at.full);
154
+ if (kept)
155
+ return refused(kept);
156
+ await mkdir(path.dirname(at.full), { recursive: true });
157
+ await writeFile(at.full, content, 'utf8');
158
+ return { ok: true, value: `Saved ${path.relative(at.folder.root, at.full)} in ${at.folder.name}.` };
159
+ }
160
+ catch {
161
+ return { ok: false, reason: 'Runner could not write that file.' };
162
+ }
163
+ }