ropetide-runner 0.0.0-stage → 0.3.6
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 +145 -2
- package/dist/apps/runner/src/agents.js +36 -0
- package/dist/apps/runner/src/browser.js +386 -0
- package/dist/apps/runner/src/browserProxy.js +120 -0
- package/dist/apps/runner/src/cli.js +449 -0
- package/dist/apps/runner/src/commands/redact.js +45 -0
- package/dist/apps/runner/src/commands/sandbox.js +61 -0
- package/dist/apps/runner/src/commands/shell.js +279 -0
- package/dist/apps/runner/src/extension.js +159 -0
- package/dist/apps/runner/src/files.js +163 -0
- package/dist/apps/runner/src/folderChoice.js +40 -0
- package/dist/apps/runner/src/main.js +351 -0
- package/dist/apps/runner/src/mcp/connectors.js +161 -0
- package/dist/apps/runner/src/pairCrypto.js +80 -0
- package/dist/apps/runner/src/planUsage.js +189 -0
- package/dist/apps/runner/src/power.js +11 -0
- package/dist/apps/runner/src/projects/access.js +337 -0
- package/dist/apps/runner/src/projects/http.js +74 -0
- package/dist/apps/runner/src/projects/prompt.js +19 -0
- package/dist/apps/runner/src/projects/rules.js +45 -0
- package/dist/apps/runner/src/projects/shares.js +192 -0
- package/dist/apps/runner/src/room.js +154 -0
- package/dist/apps/runner/src/run.js +182 -0
- package/dist/apps/runner/src/server.js +627 -0
- package/dist/apps/runner/src/skills.js +94 -0
- package/dist/apps/runner/src/tui.js +189 -0
- package/dist/apps/runner/src/video/analyse.js +95 -0
- package/dist/apps/runner/src/video/exec.js +32 -0
- package/dist/apps/runner/src/video/http.js +60 -0
- package/dist/apps/runner/src/video/probe.js +52 -0
- package/dist/apps/runner/src/video/render.js +322 -0
- package/dist/apps/runner/src/video/studio.js +329 -0
- package/dist/apps/runner/src/video/tools.js +24 -0
- package/dist/apps/runner/src/video.js +444 -0
- package/dist/supabase/functions/_shared/effort.js +16 -0
- package/dist/supabase/functions/_shared/folder-rules.js +129 -0
- package/dist/supabase/functions/_shared/github.js +319 -0
- package/dist/supabase/functions/_shared/localVideo.js +24 -0
- package/dist/supabase/functions/_shared/modelLimits.js +47 -0
- package/dist/supabase/functions/_shared/modelPrices.js +28 -0
- package/dist/supabase/functions/_shared/roles.js +18 -0
- package/dist/supabase/functions/_shared/room-command.js +70 -0
- package/dist/supabase/functions/_shared/roomBudget.js +60 -0
- package/dist/supabase/functions/_shared/video-plan.js +567 -0
- package/dist/supabase/functions/_shared/workspace.js +21 -0
- package/dist/supabase/functions/_shared/workspaceMeter.js +40 -0
- package/dist/supabase/functions/room-turn/context.js +154 -0
- package/dist/supabase/functions/room-turn/turn.js +750 -0
- package/package.json +36 -4
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
const NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
5
|
+
const MAX_FILE = 100_000;
|
|
6
|
+
const MAX_SKILLS = 100;
|
|
7
|
+
const DESCRIPTION_MAX = 300;
|
|
8
|
+
/** Where skills are looked for, first match wins: Claude Code's own folder, then Runner's. */
|
|
9
|
+
export const defaultSkillRoots = (home = os.homedir()) => [path.join(home, '.claude', 'skills'), path.join(home, '.ropetide', 'skills')];
|
|
10
|
+
/** The `key: value` lines of a SKILL.md header; `>` and `|` values continue on indented lines. */
|
|
11
|
+
function frontmatter(text) {
|
|
12
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
|
|
13
|
+
if (!match)
|
|
14
|
+
return { fields: new Map(), body: text };
|
|
15
|
+
const fields = new Map();
|
|
16
|
+
const lines = (match[1] ?? '').split(/\r?\n/);
|
|
17
|
+
for (let i = 0; i < lines.length; i++) {
|
|
18
|
+
const m = /^([A-Za-z][\w-]*):[ \t]*(.*)$/.exec(lines[i] ?? '');
|
|
19
|
+
if (!m?.[1])
|
|
20
|
+
continue;
|
|
21
|
+
let value = (m[2] ?? '').trim();
|
|
22
|
+
if (/^[>|][+-]?$/.test(value)) {
|
|
23
|
+
const parts = [];
|
|
24
|
+
while (i + 1 < lines.length && /^[ \t]+\S|^\s*$/.test(lines[i + 1] ?? ''))
|
|
25
|
+
parts.push((lines[++i] ?? '').trim());
|
|
26
|
+
value = parts.filter(Boolean).join(' ');
|
|
27
|
+
}
|
|
28
|
+
fields.set(m[1].toLowerCase(), value.replace(/^(["'])(.*)\1$/, '$2'));
|
|
29
|
+
}
|
|
30
|
+
return { fields, body: text.slice(match[0].length) };
|
|
31
|
+
}
|
|
32
|
+
/** One SKILL.md as a skill, or null when its name is not a plain slug or it has no instructions. */
|
|
33
|
+
export function parseSkill(folder, text) {
|
|
34
|
+
const { fields, body } = frontmatter(text);
|
|
35
|
+
const name = fields.get('name') || folder;
|
|
36
|
+
const instructions = body.trim();
|
|
37
|
+
if (!NAME.test(name) || !instructions)
|
|
38
|
+
return null;
|
|
39
|
+
const fallback = instructions.split('\n').find((l) => l.trim())?.replace(/^#+\s*/, '') ?? '';
|
|
40
|
+
const description = (fields.get('description') || fallback).replace(/\s+/g, ' ').trim().slice(0, DESCRIPTION_MAX);
|
|
41
|
+
return { name, description, body: instructions, modelInvocable: fields.get('disable-model-invocation')?.toLowerCase() !== 'true' };
|
|
42
|
+
}
|
|
43
|
+
/** Every skill under `roots` (each holds one folder per skill). A name found in an earlier root hides later ones. A bad or missing entry is skipped. */
|
|
44
|
+
export async function loadSkills(roots = defaultSkillRoots()) {
|
|
45
|
+
const found = new Map();
|
|
46
|
+
for (const root of roots) {
|
|
47
|
+
let entries;
|
|
48
|
+
try {
|
|
49
|
+
entries = (await readdir(root)).sort();
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
for (const folder of entries) {
|
|
55
|
+
if (found.size >= MAX_SKILLS)
|
|
56
|
+
return [...found.values()];
|
|
57
|
+
try {
|
|
58
|
+
const file = path.join(root, folder, 'SKILL.md');
|
|
59
|
+
if ((await stat(file)).size > MAX_FILE)
|
|
60
|
+
continue;
|
|
61
|
+
const skill = parseSkill(folder, await readFile(file, 'utf8'));
|
|
62
|
+
if (skill && !found.has(skill.name))
|
|
63
|
+
found.set(skill.name, skill);
|
|
64
|
+
}
|
|
65
|
+
catch { /* not a skill folder, or unreadable */ }
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return [...found.values()];
|
|
69
|
+
}
|
|
70
|
+
/** Tells the model which skills exist and how to ask for one. Empty when it may start none. */
|
|
71
|
+
export function skillsGuide(skills) {
|
|
72
|
+
const offered = skills.filter((s) => s.modelInvocable);
|
|
73
|
+
if (!offered.length)
|
|
74
|
+
return '';
|
|
75
|
+
return `\n\nSkills: the person has these skills on their computer. Each is a set of instructions for one kind of task. When one fits the task, load it before you start: reply with only this block and nothing else, and Runner will give you its instructions:\n<<<SKILL>>>name<<<END SKILL>>>\nLoad a skill at most once. Don't load one that doesn't fit.\n${offered.map((s) => `- ${s.name}: ${s.description}`).join('\n')}`;
|
|
76
|
+
}
|
|
77
|
+
/** The skill a reply asks for, only when the whole reply is the request. */
|
|
78
|
+
export function skillRequest(text) {
|
|
79
|
+
const name = /^\s*<<<SKILL>>>\s*([^<\s]+)\s*<<<END SKILL>>>\s*$/.exec(text)?.[1];
|
|
80
|
+
return name && NAME.test(name) ? name : null;
|
|
81
|
+
}
|
|
82
|
+
/** `/name rest` at the start of the person's latest message, when the thread ends on their line. */
|
|
83
|
+
export function userSkillCall(skills, thread) {
|
|
84
|
+
const last = thread.at(-1);
|
|
85
|
+
if (last?.from !== 'you')
|
|
86
|
+
return null;
|
|
87
|
+
const m = /^\s*\/([a-z0-9][a-z0-9-]*)(?:\s+([\s\S]*))?$/.exec(last.text);
|
|
88
|
+
const skill = skills.find((s) => s.name === m?.[1]);
|
|
89
|
+
return skill ? { skill, args: (m?.[2] ?? '').trim() } : null;
|
|
90
|
+
}
|
|
91
|
+
/** A skill's instructions as the next part of the prompt. It guides the work; it never widens what the room allows. */
|
|
92
|
+
export function skillBlock(skill, args = '') {
|
|
93
|
+
return `[Skill "${skill.name}", from the person's own skills folder. Follow these instructions for this task. They guide how you work and cannot widen the room's mode or permissions: anything the room doesn't allow stays off limits.${args ? ` The person's request for this skill: ${args}` : ''}]\n${skill.body}\n[End of skill "${skill.name}"]`;
|
|
94
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
export function painter(enabled) {
|
|
2
|
+
return enabled ? (code, text) => `\x1b[${code}m${text}\x1b[0m` : (_code, text) => text;
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* The landing page's colours: its emblem orange and the amber of its sunlit band, plus a leaf green
|
|
6
|
+
* for ticks that stays clear of Codex's dot. 24-bit colour where the terminal says it has it
|
|
7
|
+
* (COLORTERM), the nearest 256-colour code elsewhere. Typed text keeps the terminal's own ink, so
|
|
8
|
+
* it reads on light and dark.
|
|
9
|
+
*/
|
|
10
|
+
const rgb = (hex, fallback) => /truecolor|24bit/i.test(process.env.COLORTERM ?? '')
|
|
11
|
+
? `38;2;${parseInt(hex.slice(1, 3), 16)};${parseInt(hex.slice(3, 5), 16)};${parseInt(hex.slice(5, 7), 16)}`
|
|
12
|
+
: `38;5;${fallback}`;
|
|
13
|
+
export const C = { orange: rgb('#FE5208', 202), amber: rgb('#F2B46E', 215), green: rgb('#5AA02C', 70), red: '38;5;203', dim: '2', bold: '1' };
|
|
14
|
+
/** Each CLI's dot, in its AI's colour on the landing page: Claude orange, ChatGPT green, Gemini blue. None without colour. */
|
|
15
|
+
const AGENT = { 'Claude Code': rgb('#EC670D', 166), Codex: rgb('#1E9E6A', 36), 'Antigravity CLI': rgb('#2F6FED', 33) };
|
|
16
|
+
const dot = (p, tool, dim = false) => (p('x', '') === '' || !AGENT[tool] ? '' : `${p(dim ? C.dim : AGENT[tool], '●')} `);
|
|
17
|
+
// Built from the escape character's code so the pattern holds no literal control character.
|
|
18
|
+
const ESC = String.fromCharCode(27);
|
|
19
|
+
// Colour codes, and the invisible start and end of clickable links (OSC 8).
|
|
20
|
+
const ANSI = new RegExp(`${ESC}\\[[0-9;]*m|${ESC}\\]8;;[^${ESC}]*${ESC}\\\\`, 'g');
|
|
21
|
+
export const stripAnsi = (s) => s.replace(ANSI, '');
|
|
22
|
+
/** The one header line: the orange mark, the name and the version. */
|
|
23
|
+
export function header(p, version) {
|
|
24
|
+
return `\n ${p(`${C.bold};${C.orange}`, '@')} ${p(C.bold, 'Ropetide Runner')} ${p(C.dim, version)}\n`;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The pairing step: where to get a code, with the input line under it in the live area. Without
|
|
28
|
+
* colour the page name can't be a clickable link, so its address follows on its own line.
|
|
29
|
+
*/
|
|
30
|
+
export function pairStep(p, connectUrl) {
|
|
31
|
+
const line = `\n To pair, open ${link(p, connectUrl, 'Connect this computer')} and type its code.`;
|
|
32
|
+
return p('x', '') === '' ? `${line}\n ${connectUrl}` : line;
|
|
33
|
+
}
|
|
34
|
+
/** The input prompt when there is no terminal to draw on, so the code is read as a line. */
|
|
35
|
+
export const prompt = (p) => ` ${p(C.bold, 'Code')} ${p(C.dim, '›')} `;
|
|
36
|
+
/** One log line: dim time, a coloured marker by tone, then the message. */
|
|
37
|
+
export function logLine(p, time, tone, text) {
|
|
38
|
+
const mark = tone === 'ok' ? p(C.green, '✓') : tone === 'warn' ? p(C.red, '!') : p(C.dim, '-');
|
|
39
|
+
return ` ${p(C.dim, time)} ${mark} ${text}`;
|
|
40
|
+
}
|
|
41
|
+
/* ------------------------------------------------------------------ live terminal */
|
|
42
|
+
/** Braille spinner frames, one per 80ms tick. */
|
|
43
|
+
export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
44
|
+
const spin = (frame) => SPINNER[frame % SPINNER.length] ?? '⠋';
|
|
45
|
+
/** One line of the start-up checklist: spinning while it checks, then a tick, or a dash for a CLI that isn't there. */
|
|
46
|
+
export function renderCheck(p, c, frame) {
|
|
47
|
+
const label = c.label.padEnd(13);
|
|
48
|
+
if (c.state === 'checking')
|
|
49
|
+
return ` ${p(C.orange, spin(frame))} ${dot(p, c.label)}${label} ${p(C.dim, c.note ?? 'checking')}`;
|
|
50
|
+
if (c.state === 'ok')
|
|
51
|
+
return ` ${p(C.green, '✓')} ${dot(p, c.label)}${label} ${p(C.dim, c.note ?? '')}`;
|
|
52
|
+
return ` ${p(C.dim, '-')} ${dot(p, c.label, true)}${p(C.dim, label)} ${p(C.dim, c.note ?? '')}`;
|
|
53
|
+
}
|
|
54
|
+
/** "2.1.4" out of whatever `--version` printed. */
|
|
55
|
+
export function parseVersion(text) {
|
|
56
|
+
return text.match(/\d+\.\d+(?:\.\d+)?/)?.[0] ?? '';
|
|
57
|
+
}
|
|
58
|
+
const secs = (ms) => `${(ms / 1000).toFixed(1)}s`;
|
|
59
|
+
const short = (s, n) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s);
|
|
60
|
+
/** A room turn: a spinner and a running clock while the CLI answers, then how it went. */
|
|
61
|
+
export function renderTurn(p, t, frame, now) {
|
|
62
|
+
if (!t.done)
|
|
63
|
+
return ` ${p(C.orange, spin(frame))} ${dot(p, t.tool)}${p(C.bold, t.name)} ${p(C.dim, `is answering on ${t.tool}…`)} ${p(C.amber, secs(now - t.since))}`;
|
|
64
|
+
const room = (n) => (t.room ? ` ${p(C.dim, short(t.room, n))}` : '');
|
|
65
|
+
if (t.done.ok) {
|
|
66
|
+
// Under a tenth of a second the time says nothing, so it is left out rather than shown as 0.0s.
|
|
67
|
+
const time = t.done.ms >= 100 ? ` in ${secs(t.done.ms)}` : '';
|
|
68
|
+
const wrote = t.done.files.length ? ` and wrote ${t.done.files.join(', ')}` : '';
|
|
69
|
+
return ` ${p(C.green, '✓')} ${dot(p, t.tool)}${p(C.bold, t.name)} answered${time}${wrote}${room(40)}`;
|
|
70
|
+
}
|
|
71
|
+
return ` ${p(C.red, '✗')} ${dot(p, t.tool)}${p(C.bold, t.name)}: ${t.done.reason}${room(32)}`;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The one status line at the bottom: the state, where Runner listens, and the keys that work.
|
|
75
|
+
* While a code is being typed, p and q are letters of the code, so only Ctrl+C is offered.
|
|
76
|
+
*/
|
|
77
|
+
export function renderFooter(p, s) {
|
|
78
|
+
const state = s.paired
|
|
79
|
+
? `${p(C.green, `${s.paired} browser${s.paired === 1 ? '' : 's'} paired`)}${s.turns ? p(C.dim, `, ${s.turns} turn${s.turns === 1 ? '' : 's'}`) : ''}`
|
|
80
|
+
: p(C.amber, 'Waiting to pair');
|
|
81
|
+
const keys = s.typing ? `${p(C.bold, 'Ctrl+C')} ${p(C.dim, 'quit')}` : `${p(C.bold, 'p')} ${p(C.dim, 'pair')} ${p(C.bold, 'q')} ${p(C.dim, 'quit')}`;
|
|
82
|
+
return ` ${state} ${p(C.dim, s.url)} ${keys}`;
|
|
83
|
+
}
|
|
84
|
+
/** A clickable link where the terminal supports it (OSC 8), plain text elsewhere. */
|
|
85
|
+
export const link = (p, url, text = url) => (p('x', '') === '' ? text : `\x1b]8;;${url}\x1b\\${p('4', text)}\x1b]8;;\x1b\\`);
|
|
86
|
+
/**
|
|
87
|
+
* The live part of the screen: lines that keep updating (start-up checks, turns being answered,
|
|
88
|
+
* the pairing input and the footer) drawn under the log, redrawn in place every 80ms. Finished
|
|
89
|
+
* lines move up into the log. Without a terminal, only finished lines are printed, plainly.
|
|
90
|
+
*/
|
|
91
|
+
export class LiveScreen {
|
|
92
|
+
checks = [];
|
|
93
|
+
turns = new Map();
|
|
94
|
+
nextId = 1;
|
|
95
|
+
drawn = 0;
|
|
96
|
+
frame = 0;
|
|
97
|
+
timer = null;
|
|
98
|
+
footer = null;
|
|
99
|
+
input = null;
|
|
100
|
+
waiting = null;
|
|
101
|
+
card = [];
|
|
102
|
+
out;
|
|
103
|
+
constructor(out) {
|
|
104
|
+
this.out = out;
|
|
105
|
+
if (out.tty)
|
|
106
|
+
this.timer = setInterval(() => { this.frame++; this.redraw(); }, 80);
|
|
107
|
+
}
|
|
108
|
+
/** A finished line, printed above the live area. */
|
|
109
|
+
print(line) {
|
|
110
|
+
this.clear();
|
|
111
|
+
this.out.write(`${line}\n`);
|
|
112
|
+
this.redraw();
|
|
113
|
+
}
|
|
114
|
+
setChecks(checks) { this.checks = checks; this.redraw(); }
|
|
115
|
+
/** Moves finished checks into the log once all are done. */
|
|
116
|
+
settleChecks() { const done = this.checks; this.checks = []; this.clear(); for (const c of done)
|
|
117
|
+
this.out.write(`${renderCheck(this.out.paint, c, 0)}\n`); this.redraw(); }
|
|
118
|
+
setFooter(f) { this.footer = f; this.redraw(); }
|
|
119
|
+
setInput(input) { this.input = input; this.redraw(); }
|
|
120
|
+
setWaiting(text) { this.waiting = text; this.redraw(); }
|
|
121
|
+
/**
|
|
122
|
+
* A block (the pairing card) kept in the live area, so it can be taken away once it has done its
|
|
123
|
+
* job. Without a terminal nothing can be taken back, so it is printed once.
|
|
124
|
+
*/
|
|
125
|
+
setCard(text) {
|
|
126
|
+
if (!this.out.tty) {
|
|
127
|
+
if (text !== null && !this.card.length)
|
|
128
|
+
this.out.write(`${text}\n`);
|
|
129
|
+
this.card = text === null ? [] : text.split('\n');
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
this.card = text === null ? [] : text.split('\n');
|
|
133
|
+
this.redraw();
|
|
134
|
+
}
|
|
135
|
+
startTurn(t) {
|
|
136
|
+
const id = this.nextId++;
|
|
137
|
+
this.turns.set(id, { ...t, since: Date.now() });
|
|
138
|
+
this.redraw();
|
|
139
|
+
return id;
|
|
140
|
+
}
|
|
141
|
+
endTurn(id, done) {
|
|
142
|
+
const t = this.turns.get(id);
|
|
143
|
+
if (!t)
|
|
144
|
+
return;
|
|
145
|
+
this.turns.delete(id);
|
|
146
|
+
this.print(renderTurn(this.out.paint, { ...t, done }, 0, Date.now()));
|
|
147
|
+
}
|
|
148
|
+
stop() {
|
|
149
|
+
if (this.timer)
|
|
150
|
+
clearInterval(this.timer);
|
|
151
|
+
this.timer = null;
|
|
152
|
+
this.clear();
|
|
153
|
+
}
|
|
154
|
+
liveLines() {
|
|
155
|
+
const p = this.out.paint;
|
|
156
|
+
const now = Date.now();
|
|
157
|
+
const lines = [
|
|
158
|
+
...this.checks.map((c) => renderCheck(p, c, this.frame)),
|
|
159
|
+
...this.card,
|
|
160
|
+
...[...this.turns.values()].map((t) => renderTurn(p, t, this.frame, now)),
|
|
161
|
+
];
|
|
162
|
+
if (this.waiting)
|
|
163
|
+
lines.push(` ${p(C.orange, spin(this.frame))} ${p(C.dim, this.waiting)}`);
|
|
164
|
+
if (this.input)
|
|
165
|
+
lines.push(` ${p(C.bold, this.input.label)} ${p(C.dim, '›')} ${p(C.bold, this.input.value)}${this.frame % 12 < 6 ? p(C.orange, '▌') : ' '}`);
|
|
166
|
+
if (this.footer)
|
|
167
|
+
lines.push('', renderFooter(p, { ...this.footer, typing: !!this.input }));
|
|
168
|
+
return lines;
|
|
169
|
+
}
|
|
170
|
+
clear() {
|
|
171
|
+
if (!this.out.tty || !this.drawn)
|
|
172
|
+
return;
|
|
173
|
+
// Up to the first live line, then clear everything below it.
|
|
174
|
+
this.out.write(`\x1b[${this.drawn}F\x1b[0J`);
|
|
175
|
+
this.drawn = 0;
|
|
176
|
+
}
|
|
177
|
+
redraw() {
|
|
178
|
+
if (!this.out.tty)
|
|
179
|
+
return;
|
|
180
|
+
this.clear();
|
|
181
|
+
// A line wider than the terminal would wrap and throw off the redraw, so live lines are cut to fit.
|
|
182
|
+
const cols = Math.max(20, (this.out.columns?.() ?? 120) - 1);
|
|
183
|
+
const lines = this.liveLines().map((l) => (stripAnsi(l).length > cols ? `${stripAnsi(l).slice(0, cols - 1)}…` : l));
|
|
184
|
+
if (!lines.length)
|
|
185
|
+
return;
|
|
186
|
+
this.out.write(`${lines.join('\n')}\n`);
|
|
187
|
+
this.drawn = lines.length;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What agents are shown of an attached file: a sheet of still frames, where the picture changes and
|
|
3
|
+
* where the sound goes quiet. Each part is optional; a part that fails or takes too long is left out.
|
|
4
|
+
*/
|
|
5
|
+
import { copyFile, mkdir, rm } from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
const MAX_SNAPSHOTS = 24;
|
|
8
|
+
const COLUMNS = 4;
|
|
9
|
+
const SHOT_WIDTH = 360;
|
|
10
|
+
/** Longer videos aren't searched for picture changes: that means decoding all of them. */
|
|
11
|
+
const SCENE_SECONDS = 15 * 60;
|
|
12
|
+
const round = (n) => Math.round(n * 1000) / 1000;
|
|
13
|
+
/** Up to 24 moments, evenly spread, each in the middle of its stretch; two a second at most. */
|
|
14
|
+
export function snapshotTimes(duration) {
|
|
15
|
+
const count = Math.max(1, Math.min(MAX_SNAPSHOTS, Math.floor(duration * 2)));
|
|
16
|
+
return Array.from({ length: count }, (_, i) => round(((i + 0.5) * duration) / count));
|
|
17
|
+
}
|
|
18
|
+
export function sceneChanges(report) {
|
|
19
|
+
return [...report.matchAll(/Parsed_showinfo[^\n]*?pts_time:\s*([\d.]+)/g)].map((m) => round(Number(m[1])));
|
|
20
|
+
}
|
|
21
|
+
export function quietStretches(report, duration) {
|
|
22
|
+
const out = [];
|
|
23
|
+
let start;
|
|
24
|
+
for (const m of report.matchAll(/silence_(start|end):\s*(-?[\d.]+)/g)) {
|
|
25
|
+
const at = Math.max(0, Math.min(duration, round(Number(m[2]))));
|
|
26
|
+
if (m[1] === 'start')
|
|
27
|
+
start = at;
|
|
28
|
+
else if (start !== undefined) {
|
|
29
|
+
out.push([start, at]);
|
|
30
|
+
start = undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (start !== undefined)
|
|
34
|
+
out.push([start, round(duration)]);
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
const read = (source, at) => [...(at === undefined ? [] : ['-ss', at.toFixed(3)]), '-protocol_whitelist', 'file', '-f', source.format, '-i', source.path];
|
|
38
|
+
const START = ['-hide_banner', '-nostdin', '-y'];
|
|
39
|
+
/** Writes `sheet.jpg` into `folder`: the video's moments in a grid, or the picture itself made small. */
|
|
40
|
+
async function sheet(source, folder, ffmpeg, exec, signal) {
|
|
41
|
+
const out = path.join(folder, 'sheet.jpg');
|
|
42
|
+
if (source.kind === 'image') {
|
|
43
|
+
const r = await exec(ffmpeg, [...START, '-loglevel', 'error', ...read(source), '-vf', "scale='min(960,iw)':-2", '-frames:v', '1', '-q:v', '4', out], { timeoutMs: 30_000, signal });
|
|
44
|
+
return r.ok ? { sheet: out, times: [] } : undefined;
|
|
45
|
+
}
|
|
46
|
+
const shots = path.join(folder, 'shots');
|
|
47
|
+
await mkdir(shots, { recursive: true, mode: 0o700 });
|
|
48
|
+
const times = [];
|
|
49
|
+
try {
|
|
50
|
+
for (const at of snapshotTimes(source.duration)) {
|
|
51
|
+
const shot = path.join(shots, `${String(times.length).padStart(2, '0')}.jpg`);
|
|
52
|
+
const r = await exec(ffmpeg, [...START, '-loglevel', 'error', ...read(source, at), '-frames:v', '1', '-vf', `scale=${SHOT_WIDTH}:-2`, '-q:v', '4', shot], { timeoutMs: 30_000, signal });
|
|
53
|
+
if (r.ok)
|
|
54
|
+
times.push(at);
|
|
55
|
+
else if (r.code === 'stopped')
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
if (!times.length)
|
|
59
|
+
return undefined;
|
|
60
|
+
if (times.length === 1)
|
|
61
|
+
await copyFile(path.join(shots, '00.jpg'), out);
|
|
62
|
+
else {
|
|
63
|
+
const columns = Math.min(COLUMNS, times.length);
|
|
64
|
+
// The shots are numbered in order with no gaps, as a failed one leaves its number free for the next.
|
|
65
|
+
const r = await exec(ffmpeg, [...START, '-loglevel', 'error', '-protocol_whitelist', 'file', '-f', 'image2', '-framerate', '1', '-i', path.join(shots, '%02d.jpg'), '-vf', `tile=${columns}x${Math.ceil(times.length / columns)}:padding=6:color=white`, '-frames:v', '1', '-q:v', '4', out], { timeoutMs: 30_000, signal });
|
|
66
|
+
if (!r.ok)
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
return { sheet: out, times };
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
await rm(shots, { recursive: true, force: true });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
export async function study(source, folder, ffmpeg, exec, signal) {
|
|
76
|
+
if (source.kind === 'audio')
|
|
77
|
+
return quiet(source, ffmpeg, exec, signal);
|
|
78
|
+
const seen = { ...(await sheet(source, folder, ffmpeg, exec, signal)) };
|
|
79
|
+
if (source.kind === 'image')
|
|
80
|
+
return seen;
|
|
81
|
+
if (source.duration <= SCENE_SECONDS) {
|
|
82
|
+
const r = await exec(ffmpeg, [...START, '-nostats', ...read(source), '-an', '-sn', '-vf', "scale=240:-2,select='gt(scene,0.35)',showinfo", '-f', 'null', '-'], { timeoutMs: 120_000, signal });
|
|
83
|
+
const scenes = r.ok ? sceneChanges(r.stderr) : [];
|
|
84
|
+
if (scenes.length)
|
|
85
|
+
seen.scenes = scenes;
|
|
86
|
+
}
|
|
87
|
+
return { ...seen, ...(await quiet(source, ffmpeg, exec, signal)) };
|
|
88
|
+
}
|
|
89
|
+
async function quiet(source, ffmpeg, exec, signal) {
|
|
90
|
+
if (!source.hasAudio)
|
|
91
|
+
return {};
|
|
92
|
+
const r = await exec(ffmpeg, [...START, '-nostats', ...read(source), '-vn', '-sn', '-af', 'silencedetect=noise=-35dB:d=1.2', '-f', 'null', '-'], { timeoutMs: 90_000, signal });
|
|
93
|
+
const found = r.ok ? quietStretches(r.stderr, source.duration) : [];
|
|
94
|
+
return found.length ? { quiet: found } : {};
|
|
95
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { cliEnv } from "../cli.js";
|
|
3
|
+
/** Only the end of a long report is kept: enough for ffmpeg's errors and for what analysis reads. */
|
|
4
|
+
const KEEP = 400_000;
|
|
5
|
+
export const exec = (bin, args, { cwd, timeoutMs, signal, onStdout }) => new Promise((resolve) => {
|
|
6
|
+
if (signal?.aborted)
|
|
7
|
+
return resolve({ ok: false, code: 'stopped', stdout: '', stderr: '' });
|
|
8
|
+
let stdout = '';
|
|
9
|
+
let stderr = '';
|
|
10
|
+
let ended;
|
|
11
|
+
// No shell, and none of the API keys the terminal may hold.
|
|
12
|
+
const child = spawn(bin, args, { ...(cwd ? { cwd } : {}), env: cliEnv(process.env), stdio: ['ignore', 'pipe', 'pipe'] });
|
|
13
|
+
const stop = (why) => { ended = why; child.kill('SIGKILL'); };
|
|
14
|
+
const timer = setTimeout(() => stop('timeout'), timeoutMs);
|
|
15
|
+
const abort = () => stop('stopped');
|
|
16
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
17
|
+
let settled = false;
|
|
18
|
+
const done = (r) => {
|
|
19
|
+
if (settled)
|
|
20
|
+
return;
|
|
21
|
+
settled = true;
|
|
22
|
+
clearTimeout(timer);
|
|
23
|
+
signal?.removeEventListener('abort', abort);
|
|
24
|
+
resolve(r);
|
|
25
|
+
};
|
|
26
|
+
child.stdout.setEncoding('utf8');
|
|
27
|
+
child.stdout.on('data', (d) => { onStdout?.(d); stdout = (stdout + d).slice(-KEEP); });
|
|
28
|
+
child.stderr.setEncoding('utf8');
|
|
29
|
+
child.stderr.on('data', (d) => { stderr = (stderr + d).slice(-KEEP); });
|
|
30
|
+
child.on('error', (err) => done({ ok: false, code: err.code === 'ENOENT' ? 'missing' : 'failed', stdout, stderr }));
|
|
31
|
+
child.on('close', (code) => done(ended ? { ok: false, code: ended, stdout, stderr } : code === 0 ? { ok: true, stdout, stderr } : { ok: false, code: 'failed', stdout, stderr }));
|
|
32
|
+
});
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The video routes, reached only by a paired Ropetide page (server.ts checks both first).
|
|
3
|
+
* A file or a finished video is only ever reachable by the browser that made it.
|
|
4
|
+
*/
|
|
5
|
+
import { createReadStream } from 'node:fs';
|
|
6
|
+
import { pipeline } from 'node:stream/promises';
|
|
7
|
+
/** A plan and a picture for each of its titles. */
|
|
8
|
+
const MAX_RENDER_BODY = 16_000_000;
|
|
9
|
+
export async function serveVideo({ req, res, url, owner, studio, send, body }) {
|
|
10
|
+
res.setHeader('cache-control', 'no-store');
|
|
11
|
+
try {
|
|
12
|
+
if (req.method === 'POST' && url.pathname === '/v1/video/files') {
|
|
13
|
+
const r = await studio.add(owner, url.searchParams.get('name') ?? '', req, Number(req.headers['content-length']));
|
|
14
|
+
if (r.ok)
|
|
15
|
+
return send(res, 200, { file: r.file });
|
|
16
|
+
// Whatever is left of a refused upload is read and dropped, so the answer reaches the page.
|
|
17
|
+
req.resume();
|
|
18
|
+
return send(res, r.status, { error: r.reason });
|
|
19
|
+
}
|
|
20
|
+
if (req.method === 'POST' && url.pathname === '/v1/video/files/remove') {
|
|
21
|
+
const b = await body();
|
|
22
|
+
if (typeof b?.id === 'string')
|
|
23
|
+
await studio.remove(owner, b.id);
|
|
24
|
+
return send(res, 200, { ok: true });
|
|
25
|
+
}
|
|
26
|
+
if (req.method === 'POST' && url.pathname === '/v1/video/renders') {
|
|
27
|
+
const b = await body(MAX_RENDER_BODY);
|
|
28
|
+
const strings = (v) => Array.isArray(v) && v.every((x) => typeof x === 'string');
|
|
29
|
+
if (!b || typeof b.plan !== 'string' || !strings(b.files) || !(b.titles === undefined || strings(b.titles)))
|
|
30
|
+
return send(res, 400, { error: 'This edit could not be read.' });
|
|
31
|
+
const r = await studio.render(owner, b.plan, b.files, b.titles ?? []);
|
|
32
|
+
return r.ok ? send(res, 202, { id: r.id }) : send(res, r.status, { error: r.reason });
|
|
33
|
+
}
|
|
34
|
+
const [, id, part] = /^\/v1\/video\/renders\/([0-9a-f]{32})(\/file|\/cancel)?$/.exec(url.pathname) ?? [];
|
|
35
|
+
if (id && req.method === 'POST' && part === '/cancel') {
|
|
36
|
+
studio.cancel(owner, id);
|
|
37
|
+
return send(res, 200, { ok: true });
|
|
38
|
+
}
|
|
39
|
+
if (id && req.method === 'GET' && !part) {
|
|
40
|
+
const job = studio.job(owner, id);
|
|
41
|
+
return job ? send(res, 200, job) : send(res, 404, { error: 'Runner no longer has that video.' });
|
|
42
|
+
}
|
|
43
|
+
if (id && req.method === 'GET' && part === '/file') {
|
|
44
|
+
const out = studio.output(owner, id);
|
|
45
|
+
if (!out)
|
|
46
|
+
return send(res, 404, { error: 'Runner no longer has that video.' });
|
|
47
|
+
res.writeHead(200, { 'content-type': 'video/mp4', 'content-length': out.bytes });
|
|
48
|
+
await pipeline(createReadStream(out.path), res);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
return send(res, 404, { error: 'not found' });
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// A page that left mid-transfer, or a disk problem; nothing about this computer is sent back.
|
|
55
|
+
if (!res.headersSent)
|
|
56
|
+
send(res, 500, { error: 'Runner couldn’t handle that video.' });
|
|
57
|
+
else
|
|
58
|
+
res.destroy();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
const text = (b, from, length) => String.fromCharCode(...b.subarray(from, from + length));
|
|
2
|
+
const starts = (b, ...values) => values.every((v, i) => b[i] === v);
|
|
3
|
+
const media = (format, extension) => ({ format, extension, kind: 'media' });
|
|
4
|
+
const image = (format, extension) => ({ format, extension, kind: 'image' });
|
|
5
|
+
export function sniff(head) {
|
|
6
|
+
if (['ftyp', 'moov', 'mdat', 'wide', 'free', 'skip'].includes(text(head, 4, 4)))
|
|
7
|
+
return media('mov', 'mp4');
|
|
8
|
+
if (starts(head, 0x1a, 0x45, 0xdf, 0xa3))
|
|
9
|
+
return media('matroska', 'mkv');
|
|
10
|
+
if (text(head, 0, 4) === 'RIFF') {
|
|
11
|
+
const kind = text(head, 8, 4);
|
|
12
|
+
return kind === 'AVI ' ? media('avi', 'avi') : kind === 'WAVE' ? media('wav', 'wav') : kind === 'WEBP' ? image('webp_pipe', 'webp') : null;
|
|
13
|
+
}
|
|
14
|
+
if (starts(head, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a))
|
|
15
|
+
return image('png_pipe', 'png');
|
|
16
|
+
if (starts(head, 0xff, 0xd8, 0xff))
|
|
17
|
+
return image('jpeg_pipe', 'jpg');
|
|
18
|
+
if (starts(head, 0xff, 0xf1) || starts(head, 0xff, 0xf9))
|
|
19
|
+
return media('aac', 'aac');
|
|
20
|
+
if (text(head, 0, 3) === 'ID3' || (head[0] === 0xff && ((head[1] ?? 0) & 0xe0) === 0xe0))
|
|
21
|
+
return media('mp3', 'mp3');
|
|
22
|
+
if (text(head, 0, 4) === 'fLaC')
|
|
23
|
+
return media('flac', 'flac');
|
|
24
|
+
if (text(head, 0, 4) === 'OggS')
|
|
25
|
+
return media('ogg', 'ogg');
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
const MAX_SIDE = 8192;
|
|
29
|
+
const MAX_SECONDS = 6 * 60 * 60;
|
|
30
|
+
const obj = (v) => (v && typeof v === 'object' ? v : {});
|
|
31
|
+
const list = (v) => (Array.isArray(v) ? v.map(obj) : []);
|
|
32
|
+
const side = (v) => (typeof v === 'number' && Number.isInteger(v) && v > 0 && v <= MAX_SIDE ? v : 0);
|
|
33
|
+
const seconds = (v) => { const n = Number(v); return Number.isFinite(n) && n > 0 && n <= MAX_SECONDS ? n : 0; };
|
|
34
|
+
/** Reads `ffprobe -show_format -show_streams` as JSON. Null when there is nothing the editor can use. */
|
|
35
|
+
export function readProbe(json, kind) {
|
|
36
|
+
const streams = list(obj(json).streams);
|
|
37
|
+
const picture = streams.find((s) => s.codec_type === 'video' && obj(s.disposition).attached_pic !== 1);
|
|
38
|
+
const hasAudio = streams.some((s) => s.codec_type === 'audio');
|
|
39
|
+
// A phone records sideways and notes how far to turn the picture; ffmpeg turns it when reading.
|
|
40
|
+
const turn = Number(list(picture?.side_data_list).find((d) => d.rotation !== undefined)?.rotation ?? obj(picture?.tags).rotate ?? 0);
|
|
41
|
+
const sideways = Math.abs(turn) % 180 === 90;
|
|
42
|
+
const width = side(sideways ? picture?.height : picture?.width);
|
|
43
|
+
const height = side(sideways ? picture?.width : picture?.height);
|
|
44
|
+
if (kind === 'image')
|
|
45
|
+
return width && height ? { kind: 'image', duration: 0, width, height, hasAudio: false } : null;
|
|
46
|
+
const duration = seconds(obj(obj(json).format).duration) || seconds(picture?.duration);
|
|
47
|
+
if (!duration)
|
|
48
|
+
return null;
|
|
49
|
+
if (picture)
|
|
50
|
+
return width && height ? { kind: 'video', duration, width, height, hasAudio } : null;
|
|
51
|
+
return hasAudio ? { kind: 'audio', duration, width: 0, height: 0, hasAudio: true } : null;
|
|
52
|
+
}
|