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,189 @@
1
+ import { spawn } from 'node:child_process';
2
+ /**
3
+ * Plan remaining, as each CLI actually reports it. Remaining percent is 100 × (1 − used),
4
+ * never invented: a window is kept only when the CLI gave a used share (or used percent) and,
5
+ * when it gave a reset time, that time.
6
+ *
7
+ * Codex: `used_percent` / `usedPercent` on the 5-hour and weekly windows (headers and
8
+ * `account/rateLimits/read`). Claude Code already reports `utilization` on room turns.
9
+ * Gemini CLI's headless JSON is token stats, not plan quota, so Antigravity stays unreported
10
+ * unless a quota field is actually present.
11
+ */
12
+ const obj = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : null);
13
+ const finite = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
14
+ /** `used_percent` is 0–100; a share already in 0–1 is left as-is only when the field is `used`. */
15
+ function usedFromPercent(v) {
16
+ const n = finite(v);
17
+ if (n === undefined || n < 0)
18
+ return undefined;
19
+ return Math.max(0, Math.min(1, n / 100));
20
+ }
21
+ function resetsAtMs(v) {
22
+ const n = finite(v);
23
+ if (n !== undefined && n > 0)
24
+ return n > 1e12 ? n : n * 1000;
25
+ if (typeof v === 'string' && v.trim()) {
26
+ const t = Date.parse(v);
27
+ return Number.isFinite(t) && t > 0 ? t : undefined;
28
+ }
29
+ return undefined;
30
+ }
31
+ function kindOf(minutes, fallback) {
32
+ if (minutes === 300 || minutes === 299)
33
+ return 'five_hour';
34
+ if (minutes === 10080 || minutes === 10079)
35
+ return 'seven_day';
36
+ return fallback;
37
+ }
38
+ function windowOf(kind, used, resetsAt) {
39
+ // A window with no reset time cannot be kept: the website drops anything without a positive resetsAt.
40
+ if (!kind || !resetsAt)
41
+ return undefined;
42
+ return { kind, used, resetsAt };
43
+ }
44
+ /**
45
+ * Codex rate-limit snapshots, as exec JSONL `token_count` events and
46
+ * `account/rateLimits/read` return them. Primary/secondary slots are classified by window length.
47
+ */
48
+ export function windowsFromRateLimits(v) {
49
+ const root = obj(v);
50
+ const snap = obj(root?.rate_limits) ?? obj(root?.rateLimits) ?? root;
51
+ if (!snap)
52
+ return [];
53
+ const slots = [
54
+ { key: 'primary', fallback: 'five_hour' },
55
+ { key: 'secondary', fallback: 'seven_day' },
56
+ ];
57
+ const out = [];
58
+ for (const { key, fallback } of slots) {
59
+ const w = obj(snap[key]);
60
+ if (!w)
61
+ continue;
62
+ const used = usedFromPercent(w.used_percent ?? w.usedPercent);
63
+ if (used === undefined)
64
+ continue;
65
+ const minutes = finite(w.window_minutes ?? w.windowMinutes ?? w.windowDurationMins);
66
+ const resets = resetsAtMs(w.resets_at ?? w.resetsAt);
67
+ const win = windowOf(kindOf(minutes, fallback), used, resets);
68
+ if (win)
69
+ out.push(win);
70
+ }
71
+ return out.slice(0, 6);
72
+ }
73
+ /** Walk a JSON value for the first Codex rate-limit snapshot that actually has a used percent. */
74
+ export function rateLimitsIn(v, depth = 0) {
75
+ if (depth > 6)
76
+ return [];
77
+ const found = windowsFromRateLimits(v);
78
+ if (found.length)
79
+ return found;
80
+ if (Array.isArray(v)) {
81
+ for (const item of v) {
82
+ const w = rateLimitsIn(item, depth + 1);
83
+ if (w.length)
84
+ return w;
85
+ }
86
+ return [];
87
+ }
88
+ const o = obj(v);
89
+ if (!o)
90
+ return [];
91
+ for (const child of Object.values(o)) {
92
+ const w = rateLimitsIn(child, depth + 1);
93
+ if (w.length)
94
+ return w;
95
+ }
96
+ return [];
97
+ }
98
+ /**
99
+ * Gemini quota, only when remaining and a limit (or a remaining fraction) are present.
100
+ * Headless JSON from Gemini CLI 0.71 does not include these; the parser is here so a later
101
+ * CLI that does report them is not ignored.
102
+ */
103
+ export function windowsFromQuota(v) {
104
+ const root = obj(v);
105
+ if (!root)
106
+ return [];
107
+ const stats = obj(root.stats) ?? root;
108
+ const quota = obj(stats.quota) ?? stats;
109
+ const remaining = finite(quota.pooledRemaining ?? quota.remaining ?? quota.quotaRemaining);
110
+ const limit = finite(quota.pooledLimit ?? quota.limit ?? quota.quotaLimit);
111
+ const fraction = finite(quota.remainingFraction ?? quota.remaining_fraction);
112
+ const resets = resetsAtMs(quota.pooledResetTime ?? quota.resetTime ?? quota.reset_time ?? quota.resetsAt);
113
+ let used;
114
+ if (remaining !== undefined && limit !== undefined && limit > 0)
115
+ used = Math.max(0, Math.min(1, 1 - remaining / limit));
116
+ else if (fraction !== undefined && fraction >= 0 && fraction <= 1)
117
+ used = 1 - fraction;
118
+ if (used === undefined)
119
+ return [];
120
+ const win = windowOf('plan', used, resets);
121
+ return win ? [win] : [];
122
+ }
123
+ const LINE_MAX = 1_000_000;
124
+ /**
125
+ * ChatGPT plan windows from Codex's app-server `account/rateLimits/read`. No model turn.
126
+ * Tests inject a fake; production talks to a local `codex app-server` process.
127
+ */
128
+ export async function readCodexLimits(run = talkToCodexAppServer) {
129
+ try {
130
+ const stdout = await run([
131
+ JSON.stringify({ id: 1, method: 'initialize', params: { clientInfo: { name: 'ropetide-runner', version: '0.2.1' } } }),
132
+ JSON.stringify({ method: 'initialized' }),
133
+ JSON.stringify({ id: 2, method: 'account/rateLimits/read' }),
134
+ ].join('\n') + '\n');
135
+ for (const line of stdout.split('\n')) {
136
+ if (!line.trim().startsWith('{'))
137
+ continue;
138
+ let msg;
139
+ try {
140
+ msg = JSON.parse(line);
141
+ }
142
+ catch {
143
+ continue;
144
+ }
145
+ if (msg.id !== 2 || msg.error)
146
+ continue;
147
+ const windows = rateLimitsIn(msg.result);
148
+ if (windows.length)
149
+ return windows;
150
+ }
151
+ }
152
+ catch {
153
+ /* Codex missing, unsigned-in, or the method absent: nothing true to report. */
154
+ }
155
+ return [];
156
+ }
157
+ /** One short JSON-RPC session with `codex app-server`. Stdin is closed after the requests. */
158
+ function talkToCodexAppServer(stdin) {
159
+ return new Promise((resolve, reject) => {
160
+ const child = spawn('codex', ['app-server'], { stdio: ['pipe', 'pipe', 'pipe'], env: process.env });
161
+ let stdout = '';
162
+ let settled = false;
163
+ const done = (err, out) => {
164
+ if (settled)
165
+ return;
166
+ settled = true;
167
+ clearTimeout(timer);
168
+ child.kill('SIGKILL');
169
+ if (err)
170
+ reject(err);
171
+ else
172
+ resolve(out);
173
+ };
174
+ const timer = setTimeout(() => done(new Error('timeout'), ''), 8000);
175
+ child.stdout.setEncoding('utf8');
176
+ child.stdout.on('data', (d) => {
177
+ if (stdout.length < LINE_MAX)
178
+ stdout += d;
179
+ if (stdout.includes('"id":2') || stdout.includes('"id": 2')) {
180
+ // The rate-limits reply has arrived; don't wait for the process to exit.
181
+ setTimeout(() => done(null, stdout), 50);
182
+ }
183
+ });
184
+ child.on('error', (err) => done(err, ''));
185
+ child.on('close', () => done(null, stdout));
186
+ child.stdin.on('error', () => { });
187
+ child.stdin.end(stdin);
188
+ });
189
+ }
@@ -0,0 +1,11 @@
1
+ import { spawn } from 'node:child_process';
2
+ /** Keep inference alive through idle sleep, without holding the display on or changing settings. */
3
+ export function preventIdleSleep(platform = process.platform, launch = spawn) {
4
+ if (platform !== 'darwin')
5
+ return () => { };
6
+ const child = launch('/usr/bin/caffeinate', ['-i', '-t', '1800', '-w', String(process.pid)], { stdio: 'ignore' });
7
+ child.on('error', () => { });
8
+ child.unref();
9
+ return () => { if (child.exitCode === null && child.signalCode === null)
10
+ child.kill('SIGTERM'); };
11
+ }
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Reading and saving text files in one project folder. Runner's own code is all that keeps this
3
+ * inside the folder, so it refuses every symlink and hard link, opens files with macOS's
4
+ * refuse-all-links flag, and replaces a file only at the version the agents read. Nothing here
5
+ * deletes, renames or runs anything the person made. Reasons never carry a path or file text.
6
+ */
7
+ import { createHash } from 'node:crypto';
8
+ import { constants } from 'node:fs';
9
+ import { link, lstat, mkdir, mkdtemp, open, readdir, realpath, rename, rm, stat, symlink, unlink, writeFile } from 'node:fs/promises';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import { folderText, MAX_DEPTH, MAX_FILE_BYTES, MAX_LISTED, MAX_MATCHES, MAX_WALKED, SKIP_DIRS, snapshotOf, writeRefusal } from "../../../../supabase/functions/_shared/folder-rules.js";
13
+ import { projectPathRefusal, textRefusal } from "./rules.js";
14
+ /** macOS `O_NOFOLLOW_ANY`: open fails if any part of the path is a symlink. Node has no name for it. */
15
+ export const NO_FOLLOW_ANY = 0x20000000;
16
+ /** How long listing or searching may take before it answers with what it has. */
17
+ const WALK_MS = 5000;
18
+ export const MAX_QUERY = 200;
19
+ const fail = (code, reason) => ({ ok: false, code, reason });
20
+ const GONE = () => fail('gone', 'the folder was moved or replaced. Restart Runner with it, then link it again');
21
+ const LINKED = () => fail('refused', 'it goes through a link, and links aren’t followed');
22
+ const NOT_FILE = () => fail('refused', 'that path is a folder, or goes through a file');
23
+ const NO_FILE = () => fail('missing', 'there is no file with that path');
24
+ const DELETED = () => fail('missing', 'it was deleted from the folder after the agents read it');
25
+ const CHANGED = () => fail('changed', 'it changed on disk after the agents read it');
26
+ const EXISTS = () => fail('exists', 'it already exists and the agents haven’t read it');
27
+ const errorCode = (e) => (e && typeof e === 'object' && 'code' in e ? String(e.code) : '');
28
+ const versionOf = (bytes) => createHash('sha256').update(bytes).digest('hex');
29
+ export async function rootOf(folder) {
30
+ const info = await stat(folder, { bigint: true });
31
+ return { path: folder, dev: String(info.dev), ino: String(info.ino) };
32
+ }
33
+ async function sameRoot(root) {
34
+ try {
35
+ const info = await lstat(root.path, { bigint: true });
36
+ return info.isDirectory() && String(info.dev) === root.dev && String(info.ino) === root.ino && (await realpath(root.path)) === root.path;
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ }
42
+ /** True only when opening through a symlink fails with `flag`, and opening a plain file still works. */
43
+ export async function noFollowHolds(flag) {
44
+ let base = '';
45
+ try {
46
+ base = await realpath(await mkdtemp(path.join(os.tmpdir(), 'ropetide-links-')));
47
+ await mkdir(path.join(base, 'real'));
48
+ await writeFile(path.join(base, 'real', 'file'), 'x');
49
+ await symlink(path.join(base, 'real'), path.join(base, 'link'));
50
+ const flags = constants.O_RDONLY | flag;
51
+ await (await open(path.join(base, 'real', 'file'), flags)).close();
52
+ try {
53
+ await (await open(path.join(base, 'link', 'file'), flags)).close();
54
+ return false;
55
+ }
56
+ catch (e) {
57
+ return errorCode(e) === 'ELOOP';
58
+ }
59
+ }
60
+ catch {
61
+ return false;
62
+ }
63
+ finally {
64
+ if (base)
65
+ await rm(base, { recursive: true, force: true }).catch(() => { });
66
+ }
67
+ }
68
+ export function projectFiles(root, opts) {
69
+ const { noFollow, now, random, hooks = {} } = opts;
70
+ const full = (relative) => path.join(root.path, ...relative.split('/'));
71
+ /** Looks at every step from the root to a file: real folders on the way, no links, a plain file at the end. */
72
+ async function look(relative) {
73
+ const parts = relative.split('/');
74
+ let at = root.path;
75
+ for (const [i, part] of parts.entries()) {
76
+ at = path.join(at, part);
77
+ let info;
78
+ try {
79
+ info = await lstat(at);
80
+ }
81
+ catch (e) {
82
+ if (errorCode(e) === 'ENOENT')
83
+ return { ok: true, there: false };
84
+ return fail('failed', 'it couldn’t be checked');
85
+ }
86
+ if (info.isSymbolicLink())
87
+ return LINKED();
88
+ if (i < parts.length - 1 ? !info.isDirectory() : !info.isFile())
89
+ return NOT_FILE();
90
+ }
91
+ return { ok: true, there: true };
92
+ }
93
+ async function load(relative, use) {
94
+ const refusal = projectPathRefusal(relative, use);
95
+ if (refusal)
96
+ return fail('refused', refusal);
97
+ if (!(await sameRoot(root)))
98
+ return GONE();
99
+ const seen = await look(relative);
100
+ if (!seen.ok)
101
+ return seen;
102
+ if (!seen.there)
103
+ return NO_FILE();
104
+ try {
105
+ await hooks.checked?.();
106
+ // Non-blocking, so something that became a pipe can't hold Runner.
107
+ const handle = await open(full(relative), constants.O_RDONLY | constants.O_NONBLOCK | noFollow);
108
+ try {
109
+ const info = await handle.stat();
110
+ if (!info.isFile())
111
+ return NOT_FILE();
112
+ if (info.nlink !== 1)
113
+ return fail('refused', 'it has a second name somewhere else (a hard link)');
114
+ if (info.size > MAX_FILE_BYTES)
115
+ return fail('refused', 'it is larger than 120,000 characters');
116
+ const bytes = await handle.readFile();
117
+ const text = folderText(new Uint8Array(bytes));
118
+ if (!text.ok)
119
+ return fail('refused', text.reason);
120
+ const why = textRefusal(text.snapshot.raw);
121
+ if (why)
122
+ return fail('refused', why);
123
+ return { ok: true, content: text.snapshot.raw, version: versionOf(bytes), mode: info.mode & 0o777 };
124
+ }
125
+ finally {
126
+ await handle.close();
127
+ }
128
+ }
129
+ catch (e) {
130
+ if (errorCode(e) === 'ENOENT')
131
+ return NO_FILE();
132
+ if (errorCode(e) === 'ELOOP')
133
+ return LINKED();
134
+ return fail('failed', 'it couldn’t be read');
135
+ }
136
+ }
137
+ async function walk() {
138
+ if (!(await sameRoot(root)))
139
+ return GONE();
140
+ const files = [];
141
+ const queue = [{ prefix: '', depth: 0 }];
142
+ const until = now() + WALK_MS;
143
+ let walked = 0;
144
+ let truncated = false;
145
+ for (let at = 0; at < queue.length && walked <= MAX_WALKED; at++) {
146
+ const { prefix, depth } = queue[at];
147
+ if (now() > until)
148
+ return { ok: true, files, truncated: true };
149
+ let entries;
150
+ try {
151
+ const dir = prefix ? full(prefix.slice(0, -1)) : root.path;
152
+ // Proves no part of the way there is a link before its names are read.
153
+ await (await open(dir, constants.O_RDONLY | constants.O_NONBLOCK | noFollow)).close();
154
+ entries = await readdir(dir, { withFileTypes: true });
155
+ }
156
+ catch {
157
+ truncated = true;
158
+ continue;
159
+ }
160
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
161
+ if (++walked > MAX_WALKED) {
162
+ truncated = true;
163
+ break;
164
+ }
165
+ const relative = `${prefix}${entry.name}`;
166
+ if (entry.name.startsWith('.'))
167
+ continue;
168
+ if (entry.isDirectory()) {
169
+ if (SKIP_DIRS.has(entry.name.toLowerCase()))
170
+ continue;
171
+ if (depth >= MAX_DEPTH)
172
+ truncated = true;
173
+ else
174
+ queue.push({ prefix: `${relative}/`, depth: depth + 1 });
175
+ }
176
+ else if (entry.isFile() && !projectPathRefusal(relative, 'read')) {
177
+ if (files.length >= MAX_LISTED)
178
+ truncated = true;
179
+ else
180
+ files.push(relative);
181
+ }
182
+ }
183
+ }
184
+ return { ok: true, files, truncated };
185
+ }
186
+ async function search(query) {
187
+ const wanted = query.toLowerCase();
188
+ if (!wanted.trim() || query.length > MAX_QUERY)
189
+ return fail('refused', `search for 1 to ${MAX_QUERY} characters`);
190
+ const listed = await walk();
191
+ if (!listed.ok)
192
+ return listed;
193
+ const matches = [];
194
+ const until = now() + WALK_MS;
195
+ for (const relative of listed.files) {
196
+ if (now() > until)
197
+ break;
198
+ const file = await load(relative, 'read');
199
+ if (!file.ok)
200
+ continue;
201
+ for (const [i, line] of file.content.replace(/\r\n/g, '\n').split('\n').entries()) {
202
+ if (!line.toLowerCase().includes(wanted))
203
+ continue;
204
+ matches.push(`${relative}:${i + 1}: ${line.trim().slice(0, 160)}`);
205
+ if (matches.length >= MAX_MATCHES)
206
+ return { ok: true, matches };
207
+ }
208
+ }
209
+ return { ok: true, matches };
210
+ }
211
+ /** Makes the folders above a new file one at a time, each checked as a real folder. */
212
+ async function makeParents(relative) {
213
+ let at = root.path;
214
+ for (const part of relative.split('/').slice(0, -1)) {
215
+ at = path.join(at, part);
216
+ try {
217
+ await mkdir(at);
218
+ }
219
+ catch (e) {
220
+ if (errorCode(e) !== 'EEXIST')
221
+ return fail('failed', 'it couldn’t be saved');
222
+ }
223
+ const info = await lstat(at);
224
+ if (info.isSymbolicLink())
225
+ return LINKED();
226
+ if (!info.isDirectory())
227
+ return NOT_FILE();
228
+ }
229
+ return null;
230
+ }
231
+ async function save(relative, content, expected) {
232
+ const refusal = projectPathRefusal(relative, 'write');
233
+ if (refusal)
234
+ return fail('refused', refusal);
235
+ const bytes = Buffer.from(content, 'utf8');
236
+ if (bytes.toString('utf8') !== content)
237
+ return fail('refused', 'it isn’t UTF-8 text');
238
+ const text = folderText(new Uint8Array(bytes));
239
+ if (!text.ok)
240
+ return fail('refused', text.reason);
241
+ const tooLong = (like) => {
242
+ const reason = writeRefusal(text.snapshot.text, like === null ? null : snapshotOf(like));
243
+ return reason ? fail('refused', reason) : null;
244
+ };
245
+ const why = textRefusal(content);
246
+ if (why)
247
+ return fail('refused', why);
248
+ if (!(await sameRoot(root)))
249
+ return GONE();
250
+ /** The file as it must still be for a replacement, or the folders and gap a new one needs. */
251
+ const ready = async () => {
252
+ if (expected === null) {
253
+ const long = tooLong(null);
254
+ if (long)
255
+ return long;
256
+ const seen = await look(relative);
257
+ if (!seen.ok)
258
+ return seen;
259
+ return seen.there ? EXISTS() : { ok: true, mode: null };
260
+ }
261
+ const current = await load(relative, 'write');
262
+ if (!current.ok)
263
+ return current.code === 'missing' ? DELETED() : current;
264
+ if (current.version !== expected)
265
+ return CHANGED();
266
+ return tooLong(current.content) ?? { ok: true, mode: current.mode };
267
+ };
268
+ let temp = '';
269
+ try {
270
+ const before = await ready();
271
+ if (!before.ok)
272
+ return before;
273
+ if (before.mode === null) {
274
+ const blocked = await makeParents(relative);
275
+ if (blocked)
276
+ return blocked;
277
+ }
278
+ await hooks.checked?.();
279
+ const target = full(relative);
280
+ const name = path.join(path.dirname(target), `.ropetide-write-${random()}.tmp`);
281
+ // A new file gets ordinary permissions and is never executable.
282
+ const handle = await open(name, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow, before.mode === null ? 0o644 : 0o600);
283
+ temp = name;
284
+ try {
285
+ await handle.writeFile(bytes);
286
+ if (before.mode !== null)
287
+ await handle.chmod(before.mode);
288
+ await handle.sync();
289
+ }
290
+ finally {
291
+ await handle.close();
292
+ }
293
+ await hooks.beforeReplace?.();
294
+ if (before.mode === null) {
295
+ // A hard link fails if anything took the name meanwhile, where a rename would replace it.
296
+ try {
297
+ await link(temp, target);
298
+ }
299
+ catch (e) {
300
+ if (errorCode(e) === 'EEXIST')
301
+ return EXISTS();
302
+ throw e;
303
+ }
304
+ }
305
+ else {
306
+ const again = await ready();
307
+ if (!again.ok)
308
+ return again;
309
+ await rename(temp, target);
310
+ temp = '';
311
+ }
312
+ return { ok: true, version: versionOf(bytes), created: before.mode === null };
313
+ }
314
+ catch (e) {
315
+ return errorCode(e) === 'ELOOP' ? LINKED() : fail('failed', 'it couldn’t be saved');
316
+ }
317
+ finally {
318
+ if (temp)
319
+ await unlink(temp).catch(() => { });
320
+ }
321
+ }
322
+ // One save at a time, so two changes to the same version can't both land.
323
+ let queue = Promise.resolve();
324
+ return {
325
+ list: walk,
326
+ read: async (relative) => {
327
+ const r = await load(relative, 'read');
328
+ return r.ok ? { ok: true, content: r.content, version: r.version } : r;
329
+ },
330
+ search,
331
+ write: (relative, content, expected) => {
332
+ const next = queue.then(() => save(relative, content, expected));
333
+ queue = next.catch(() => undefined);
334
+ return next;
335
+ },
336
+ };
337
+ }
@@ -0,0 +1,74 @@
1
+ /** A 120,000-character file as JSON, at up to three bytes a character. */
2
+ export const MAX_PROJECT_BODY = 400_000;
3
+ const ACTIONS = { grant: ['id'], revoke: ['id'], list: ['id'], read: ['id', 'path'], search: ['id', 'query'], write: ['id', 'path', 'content', 'expected'] };
4
+ const isAction = (v) => Object.hasOwn(ACTIONS, v);
5
+ export async function serveProject({ req, res, url, origin, owner, shares, send, body, begin, saved }) {
6
+ res.setHeader('cache-control', 'no-store');
7
+ const action = url.pathname.slice('/v1/project/'.length);
8
+ const no = (status, code, reason) => send(res, status, { ok: false, code, reason });
9
+ if (req.method !== 'POST' || !isAction(action))
10
+ return no(404, 'unknown', 'Runner has no such route.');
11
+ if (!shares.allowsOrigin(origin))
12
+ return no(403, 'origin', 'This site may not use project folders. Start Runner with --origin for it.');
13
+ // Refused before reading, so an oversized request still gets its answer.
14
+ if (Number(req.headers['content-length'] ?? 0) > MAX_PROJECT_BODY) {
15
+ req.resume();
16
+ return no(400, 'bad_request', 'That request is too large.');
17
+ }
18
+ const b = await body(MAX_PROJECT_BODY);
19
+ const fields = ACTIONS[action];
20
+ if (!b || Object.keys(b).length !== fields.length || !fields.every((k) => Object.hasOwn(b, k)))
21
+ return no(400, 'bad_request', 'That request couldn’t be read.');
22
+ const { id, path, query, content, expected } = b;
23
+ if (typeof id !== 'string')
24
+ return no(400, 'bad_request', 'That request couldn’t be read.');
25
+ if (!shares.has(id))
26
+ return no(404, 'unknown', 'Runner wasn’t started with that folder.');
27
+ if (action === 'grant') {
28
+ const status = shares.request(owner, origin, id);
29
+ return send(res, 200, { ok: true, status });
30
+ }
31
+ if (action === 'revoke') {
32
+ shares.revoke(owner, origin, id);
33
+ return send(res, 200, { ok: true });
34
+ }
35
+ const opened = shares.open(owner, origin, id);
36
+ if (!opened)
37
+ return no(403, 'no_grant', 'Allow this folder in the Runner terminal first.');
38
+ let work;
39
+ if (action === 'list')
40
+ work = () => opened.files.list();
41
+ else if (action === 'read') {
42
+ if (typeof path !== 'string')
43
+ return no(400, 'bad_request', 'That request couldn’t be read.');
44
+ work = () => opened.files.read(path);
45
+ }
46
+ else if (action === 'search') {
47
+ if (typeof query !== 'string')
48
+ return no(400, 'bad_request', 'That request couldn’t be read.');
49
+ work = () => opened.files.search(query);
50
+ }
51
+ else {
52
+ if (typeof path !== 'string' || typeof content !== 'string' || !(expected === null || (typeof expected === 'string' && /^[0-9a-f]{64}$/.test(expected))))
53
+ return no(400, 'bad_request', 'That request couldn’t be read.');
54
+ if (opened.folder.mode !== 'read-write')
55
+ return no(403, 'read_only', 'Runner shares that folder read-only. Start it with :rw to allow changes.');
56
+ work = async () => {
57
+ const result = await opened.files.write(path, content, expected);
58
+ if (result.ok)
59
+ saved(opened.folder.name, path, result.created);
60
+ return result;
61
+ };
62
+ }
63
+ if (!shares.take(owner, action === 'write' ? 'write' : 'read'))
64
+ return no(429, 'rate', 'Too many file requests. Wait a minute.');
65
+ const end = begin();
66
+ if (!end)
67
+ return no(409, 'busy', 'Runner is running a command. Try again when it ends.');
68
+ try {
69
+ return send(res, 200, await work());
70
+ }
71
+ finally {
72
+ end();
73
+ }
74
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The terminal's answer to "may this site use this folder?". Only a whole line saying y, yes, n or
3
+ * no counts, so a pairing code being typed, or a stray key, can't allow anything.
4
+ */
5
+ export function grantInput(line, typed, key) {
6
+ if (key.name === 'escape')
7
+ return { line: '', answer: false };
8
+ if (key.name === 'return' || key.name === 'enter') {
9
+ const said = line.toLowerCase();
10
+ if (said === 'y' || said === 'yes')
11
+ return { line: '', answer: true };
12
+ if (said === 'n' || said === 'no')
13
+ return { line: '', answer: false };
14
+ return { line: '' };
15
+ }
16
+ if (key.name === 'backspace')
17
+ return { line: line.slice(0, -1) };
18
+ return { line: typed && /^[\x20-\x7e]$/.test(typed) && line.length < 20 ? line + typed : line };
19
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * What agents may touch in a project folder. It starts from the rules the browser folder uses and
3
+ * is stricter, because Runner's own code is all that confines a project folder. These are checks of
4
+ * names and well-known key shapes: they can't catch every secret. Plain code decides.
5
+ */
6
+ import { folderPathRefusal, SECRET_NAMES } from "../../../../supabase/functions/_shared/folder-rules.js";
7
+ import { holdsKnownKey } from "../commands/redact.js";
8
+ const SECRET_FOLDERS = new Set(['secrets', 'credentials']);
9
+ const SECRET_FILES = [/\.tfvars(\.json)?$/i, /\.tfstate(\.backup)?$/i, /^kubeconfig(\.[A-Za-z0-9]+)?$/i];
10
+ /** Files AI tools take orders from. Agents may read them and may not change them. */
11
+ const INSTRUCTIONS = new Set(['claude.md', 'claude.local.md', 'agents.md', 'agents.override.md', 'gemini.md']);
12
+ /** Why a path in a project folder is off limits for this use, or null when it is allowed. */
13
+ export function projectPathRefusal(path, use) {
14
+ const refusal = folderPathRefusal(path);
15
+ if (refusal)
16
+ return refusal;
17
+ const parts = path.split('/');
18
+ const name = parts.at(-1) ?? '';
19
+ if (parts.some((p) => p === '' || p.endsWith(' ') || p.endsWith('.')))
20
+ return 'a name in it is empty or ends in a space or a dot';
21
+ if (parts.slice(0, -1).some((p) => SECRET_FOLDERS.has(p.toLowerCase())) || SECRET_FILES.some((r) => r.test(name)))
22
+ return 'it looks like it holds keys or passwords';
23
+ if (use === 'write' && INSTRUCTIONS.has(name.toLowerCase()))
24
+ return 'AI tools take instructions from that file, so agents can’t change it';
25
+ return null;
26
+ }
27
+ /**
28
+ * Why a path under a `--share` folder is off limits, or null. Those folders hold ordinary
29
+ * documents, so any name and file type is fine, but what is hidden, holds keys or gives AI tools
30
+ * their orders is treated as in a project folder. `parts` are the names below the shared folder.
31
+ */
32
+ export function sharedPathRefusal(parts, use) {
33
+ const name = parts.at(-1) ?? '';
34
+ if (parts.some((p) => p.startsWith('.')))
35
+ return 'hidden files and folders aren’t shared';
36
+ if (parts.some((p) => p.endsWith(' ') || p.endsWith('.')))
37
+ return 'a name in it ends in a space or a dot';
38
+ if (parts.some((p) => SECRET_FOLDERS.has(p.toLowerCase())) || [...SECRET_NAMES, ...SECRET_FILES].some((r) => r.test(name)))
39
+ return 'it looks like it holds keys or passwords';
40
+ if (use === 'write' && INSTRUCTIONS.has(name.toLowerCase()))
41
+ return 'AI tools take instructions from that file, so agents can’t change it';
42
+ return null;
43
+ }
44
+ /** Why a file's text must not be read or written, or null. The reason never repeats the text. */
45
+ export const textRefusal = (text) => (holdsKnownKey(text) ? 'it contains what looks like a key or password' : null);