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.
- 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,24 @@
|
|
|
1
|
+
/** Everything the editor uses besides stabilising, which has a fallback. */
|
|
2
|
+
export const REQUIRED_FILTERS = ['scale', 'crop', 'pad', 'fps', 'zoompan', 'xfade', 'acrossfade', 'overlay', 'concat', 'tpad', 'trim', 'atrim', 'apad', 'atempo', 'aresample', 'aformat', 'volume', 'amix', 'asplit', 'afade', 'sidechaincompress', 'alimiter', 'loudnorm', 'afftdn', 'eq', 'hue', 'curves', 'colorbalance', 'colorchannelmixer', 'vignette', 'unsharp', 'reverse', 'areverse', 'loop', 'fade', 'format', 'setpts', 'asetpts', 'settb', 'setsar', 'deshake', 'tile', 'select', 'showinfo', 'silencedetect'];
|
|
3
|
+
const INSTALL = process.platform === 'darwin' ? 'Install it with “brew install ffmpeg”, or from ffmpeg.org' : process.platform === 'win32' ? 'Install it with “winget install ffmpeg”, or from ffmpeg.org' : 'Install it with your package manager, or from ffmpeg.org';
|
|
4
|
+
/** The names in `ffmpeg -filters` or `-encoders`: the second word of each listed line. */
|
|
5
|
+
export function readNames(listing) {
|
|
6
|
+
return new Set(listing.split('\n').flatMap((line) => /^\s*[A-Z.]{2,}\s+([a-z0-9_]+)\s/.exec(line)?.[1] ?? []));
|
|
7
|
+
}
|
|
8
|
+
export async function findTools(env, exec) {
|
|
9
|
+
const ffmpeg = env.ROPETIDE_FFMPEG || 'ffmpeg';
|
|
10
|
+
const ffprobe = env.ROPETIDE_FFPROBE || 'ffprobe';
|
|
11
|
+
const ask = (bin, flag) => exec(bin, ['-hide_banner', flag], { timeoutMs: 15_000 });
|
|
12
|
+
const [filters, encoders, probe] = await Promise.all([ask(ffmpeg, '-filters'), ask(ffmpeg, '-encoders'), ask(ffprobe, '-version')]);
|
|
13
|
+
if (!filters.ok || !encoders.ok || !probe.ok)
|
|
14
|
+
return { ok: false, reason: `Video editing needs ffmpeg (with ffprobe) on this computer. ${INSTALL}, then restart Runner.` };
|
|
15
|
+
const has = readNames(filters.stdout);
|
|
16
|
+
const missing = REQUIRED_FILTERS.filter((f) => !has.has(f));
|
|
17
|
+
if (missing.length)
|
|
18
|
+
return { ok: false, reason: `The ffmpeg on this computer is missing ${missing.slice(0, 5).join(', ')}. Update it. ${INSTALL}.` };
|
|
19
|
+
const codecs = readNames(encoders.stdout);
|
|
20
|
+
const encoder = codecs.has('libx264') ? 'libx264' : codecs.has('h264_videotoolbox') ? 'h264_videotoolbox' : undefined;
|
|
21
|
+
if (!encoder || !codecs.has('aac'))
|
|
22
|
+
return { ok: false, reason: `The ffmpeg on this computer can’t write H.264 video with AAC sound. ${INSTALL}.` };
|
|
23
|
+
return { ok: true, ffmpeg, ffprobe, capabilities: { encoder, stabilizer: has.has('vidstabdetect') && has.has('vidstabtransform') ? 'vidstab' : 'deshake' } };
|
|
24
|
+
}
|
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
import { createHash, randomInt, randomUUID } from 'node:crypto';
|
|
2
|
+
import { COMPACT_VIDEO_PRESETS, VIDEO_PRESETS } from "../../../supabase/functions/_shared/localVideo.js";
|
|
3
|
+
const MODEL = 'wan2.2_ti2v_5B_fp16.safetensors';
|
|
4
|
+
const IMAGE_MODEL = 'wan2.1_fun_inp_1.3B_bf16.safetensors';
|
|
5
|
+
const VAE = 'wan2.2_vae.safetensors';
|
|
6
|
+
const NODES = ['UNETLoader', 'CLIPLoader', 'VAELoader', 'CLIPTextEncode', 'ModelSamplingSD3', 'Wan22ImageToVideoLatent', 'KSampler', 'VAEDecode', 'CreateVideo', 'SaveVideo'];
|
|
7
|
+
const scopeKey = (owner, room) => createHash('sha256').update(owner).update('\0').update(room).digest('hex');
|
|
8
|
+
const record = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
9
|
+
/** Fixed native-node graph based on ComfyOrg's Wan2.2 5B template. No user-supplied graphs,
|
|
10
|
+
* model paths, URLs, custom nodes or output locations are accepted from a browser or an AI. */
|
|
11
|
+
export function videoWorkflow(request, id, encoder, seed, compact = false) {
|
|
12
|
+
const compactRectangle = compact && !!request.aspect && request.aspect !== '1:1';
|
|
13
|
+
// Bound both attention tokens and VAE pixel volume by the validated 512p square profile.
|
|
14
|
+
// Crop eight pixels after decoding to obtain an exact aspect without an upscale.
|
|
15
|
+
const roomSize = request.aspect === '1:1' ? { width: 512, height: 512 }
|
|
16
|
+
: request.aspect === '9:16' ? { width: compactRectangle ? 512 : 576, height: compactRectangle ? 896 : 1024 }
|
|
17
|
+
: { width: compactRectangle ? 896 : 1024, height: compactRectangle ? 512 : 576 };
|
|
18
|
+
const size = request.aspect ? { ...roomSize, frames: compact ? compactRectangle ? 17 : 33 : 81, fps: compact ? compactRectangle ? 4 : 7 : 17 } : (compact ? COMPACT_VIDEO_PRESETS : VIDEO_PRESETS)[request.preset];
|
|
19
|
+
const crop = request.aspect === '9:16' ? { width: 504, height: 896, x: 4, y: 0 } : { width: 896, height: 504, x: 0, y: 4 };
|
|
20
|
+
return {
|
|
21
|
+
'1': { class_type: 'UNETLoader', inputs: { unet_name: compact ? request.image ? IMAGE_MODEL : 'wan2.1_t2v_1.3B_fp16.safetensors' : MODEL, weight_dtype: 'default' } },
|
|
22
|
+
'2': { class_type: 'CLIPLoader', inputs: { clip_name: encoder, type: 'wan', device: compact ? 'cpu' : 'default' } },
|
|
23
|
+
'3': { class_type: 'VAELoader', inputs: { vae_name: compact ? 'wan_2.1_vae.safetensors' : VAE } },
|
|
24
|
+
'4': { class_type: 'CLIPTextEncode', inputs: { clip: ['2', 0], text: request.prompt } },
|
|
25
|
+
'5': { class_type: 'CLIPTextEncode', inputs: { clip: ['2', 0], text: 'blurry, low quality, distorted, subtitles, watermark, static image' } },
|
|
26
|
+
'6': { class_type: 'ModelSamplingSD3', inputs: { model: ['1', 0], shift: 8 } },
|
|
27
|
+
'7': { class_type: compact ? request.image ? 'WanFunInpaintToVideo' : 'EmptyHunyuanLatentVideo' : 'Wan22ImageToVideoLatent', inputs: { ...(!compact || request.image ? { vae: ['3', 0] } : {}), ...(compact && request.image ? { positive: ['4', 0], negative: ['5', 0] } : {}), width: size.width, height: size.height, length: size.frames, batch_size: 1, ...(request.image ? { start_image: ['12', 0] } : {}) } },
|
|
28
|
+
'8': { class_type: 'KSampler', inputs: { model: ['6', 0], positive: compact && request.image ? ['7', 0] : ['4', 0], negative: compact && request.image ? ['7', 1] : ['5', 0], latent_image: ['7', compact && request.image ? 2 : 0], seed, steps: 20, cfg: compact ? 6 : 5, sampler_name: compact ? 'euler' : 'uni_pc', scheduler: 'simple', denoise: 1 } },
|
|
29
|
+
'9': { class_type: 'VAEDecode', inputs: { samples: ['8', 0], vae: ['3', 0] } },
|
|
30
|
+
...(compactRectangle ? { '13': { class_type: 'ImageCrop', inputs: { image: ['9', 0], ...crop } } } : {}),
|
|
31
|
+
'10': { class_type: 'CreateVideo', inputs: { images: [compactRectangle ? '13' : '9', 0], fps: size.fps } },
|
|
32
|
+
...(request.image ? { '12': { class_type: 'LoadImage', inputs: { image: `ropetide-${id}.png` } } } : {}),
|
|
33
|
+
'11': { class_type: 'SaveVideo', inputs: { video: ['10', 0], filename_prefix: `ropetide/${id}`, format: 'mp4', codec: 'h264' } },
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** Bound both declared and streamed response sizes, including chunked responses. */
|
|
37
|
+
async function readBytes(response, limit) {
|
|
38
|
+
if (Number(response.headers.get('content-length')) > limit) {
|
|
39
|
+
await response.body?.cancel();
|
|
40
|
+
throw new Error('response too large');
|
|
41
|
+
}
|
|
42
|
+
const reader = response.body?.getReader();
|
|
43
|
+
if (!reader)
|
|
44
|
+
throw new Error('empty response');
|
|
45
|
+
const parts = [];
|
|
46
|
+
let length = 0;
|
|
47
|
+
try {
|
|
48
|
+
for (;;) {
|
|
49
|
+
const { done, value } = await reader.read();
|
|
50
|
+
if (done)
|
|
51
|
+
break;
|
|
52
|
+
length += value.length;
|
|
53
|
+
if (length > limit) {
|
|
54
|
+
await reader.cancel();
|
|
55
|
+
throw new Error('response too large');
|
|
56
|
+
}
|
|
57
|
+
parts.push(value);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
reader.releaseLock();
|
|
62
|
+
}
|
|
63
|
+
const bytes = new Uint8Array(length);
|
|
64
|
+
let offset = 0;
|
|
65
|
+
for (const part of parts) {
|
|
66
|
+
bytes.set(part, offset);
|
|
67
|
+
offset += part.length;
|
|
68
|
+
}
|
|
69
|
+
return bytes;
|
|
70
|
+
}
|
|
71
|
+
/** One local GPU job at a time; jobs and playback are scoped to a pairing and room. */
|
|
72
|
+
export class LocalVideo {
|
|
73
|
+
entries = new Map();
|
|
74
|
+
active;
|
|
75
|
+
base;
|
|
76
|
+
encoder;
|
|
77
|
+
compact;
|
|
78
|
+
roomVideo;
|
|
79
|
+
clock;
|
|
80
|
+
liveProgress;
|
|
81
|
+
model;
|
|
82
|
+
fetcher;
|
|
83
|
+
stayAwake;
|
|
84
|
+
constructor(options = {}) {
|
|
85
|
+
const port = options.port ?? 8188;
|
|
86
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
87
|
+
throw new Error('Invalid local video port.');
|
|
88
|
+
this.base = `http://127.0.0.1:${port}`;
|
|
89
|
+
this.compact = options.compact ?? false;
|
|
90
|
+
this.roomVideo = options.roomVideo ?? false;
|
|
91
|
+
this.clock = options.clock ?? { now: () => performance.now() };
|
|
92
|
+
this.liveProgress = !options.fetch;
|
|
93
|
+
this.model = this.compact ? 'Wan2.1 T2V 1.3B' : 'Wan2.2 TI2V 5B';
|
|
94
|
+
this.encoder = options.fp16Encoder ? 'umt5_xxl_fp16.safetensors' : 'umt5_xxl_fp8_e4m3fn_scaled.safetensors';
|
|
95
|
+
this.fetcher = options.fetch ?? fetch;
|
|
96
|
+
this.stayAwake = options.stayAwake ?? (() => () => { });
|
|
97
|
+
}
|
|
98
|
+
async response(route, init) {
|
|
99
|
+
return this.fetcher(`${this.base}${route}`, { ...init, redirect: 'error', signal: AbortSignal.timeout(30_000) });
|
|
100
|
+
}
|
|
101
|
+
async json(route, init) {
|
|
102
|
+
const response = await this.response(route, init);
|
|
103
|
+
if (!response.ok) {
|
|
104
|
+
await response.body?.cancel();
|
|
105
|
+
throw new Error('local engine refused');
|
|
106
|
+
}
|
|
107
|
+
return record(JSON.parse(new TextDecoder().decode(await readBytes(response, 4_000_000))));
|
|
108
|
+
}
|
|
109
|
+
async info() {
|
|
110
|
+
try {
|
|
111
|
+
const info = await this.json('/object_info');
|
|
112
|
+
const nodes = [...NODES.map((node) => this.compact && node === 'Wan22ImageToVideoLatent' ? 'EmptyHunyuanLatentVideo' : node), ...(this.compact && this.roomVideo ? ['ImageCrop'] : [])];
|
|
113
|
+
if (nodes.some((node) => !info[node]))
|
|
114
|
+
return { enabled: true, ready: false, model: this.model, reason: 'Update ComfyUI: a required native video node is missing.' };
|
|
115
|
+
const choices = (node, field) => {
|
|
116
|
+
const required = record(record(record(info[node]).input).required);
|
|
117
|
+
const input = required[field];
|
|
118
|
+
return Array.isArray(input) && Array.isArray(input[0]) ? input[0] : [];
|
|
119
|
+
};
|
|
120
|
+
const missing = [[this.compact ? 'wan2.1_t2v_1.3B_fp16.safetensors' : MODEL, choices('UNETLoader', 'unet_name')], [this.compact ? 'wan_2.1_vae.safetensors' : VAE, choices('VAELoader', 'vae_name')], [this.encoder, choices('CLIPLoader', 'clip_name')]]
|
|
121
|
+
.filter(([name, available]) => !Array.isArray(available) || !available.includes(name)).map(([name]) => name);
|
|
122
|
+
return { enabled: true, ready: !missing.length, model: this.model, roomVideo: this.roomVideo, busy: !!this.active, imageVideo: this.roomVideo && !!info.LoadImage && (!this.compact || (!!info.WanFunInpaintToVideo && choices('UNETLoader', 'unet_name').includes(IMAGE_MODEL))), ...(missing.length ? { reason: `Install the local model files: ${missing.join(', ')}.` } : {}) };
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return { enabled: true, ready: false, model: this.model, reason: 'Start ComfyUI on the configured local port, then check again.' };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async create(owner, room, request) {
|
|
129
|
+
const existing = [...this.entries.values()].find((entry) => entry.owner === owner && entry.room === room && entry.request.requestId === request.requestId);
|
|
130
|
+
if (existing)
|
|
131
|
+
return existing.request.prompt === request.prompt && existing.request.preset === request.preset && existing.request.aspect === request.aspect && existing.request.image === request.image
|
|
132
|
+
? { ok: true, value: { ...existing.job } } : { ok: false, reason: 'That request ID already belongs to a different video.' };
|
|
133
|
+
if (request.aspect && !this.roomVideo)
|
|
134
|
+
return { ok: false, reason: 'Local 480p room generation is not enabled. Validate the hardware and start Runner with --video-room.' };
|
|
135
|
+
if (!this.active)
|
|
136
|
+
this.active = [...this.entries.values()].find(entry => ['preparing', 'queued', 'running', 'uncertain'].includes(entry.job.state));
|
|
137
|
+
if (this.active)
|
|
138
|
+
await this.refresh(this.active);
|
|
139
|
+
if (this.active)
|
|
140
|
+
return { ok: false, reason: 'A video is already generating or awaiting confirmation from the local engine. Check its status first.' };
|
|
141
|
+
if (this.entries.size >= 64)
|
|
142
|
+
return { ok: false, reason: 'Runner has reached its 64-video session limit. Download your videos and restart Runner.' };
|
|
143
|
+
const entry = { owner, room, request, job: { id: randomUUID(), state: 'preparing', preset: request.preset, requestId: request.requestId, model: request.image && this.compact ? 'Wan2.1 Fun InP 1.3B' : this.model } };
|
|
144
|
+
// Reserve before readiness checks: concurrent requests cannot both occupy the GPU.
|
|
145
|
+
this.active = entry;
|
|
146
|
+
this.entries.set(entry.job.id, entry);
|
|
147
|
+
entry.releaseAwake = this.stayAwake();
|
|
148
|
+
entry.started = this.clock.now();
|
|
149
|
+
entry.progressed = entry.started;
|
|
150
|
+
if (this.liveProgress) {
|
|
151
|
+
const timer = setInterval(() => { void this.refresh(entry); }, 5000);
|
|
152
|
+
timer.unref();
|
|
153
|
+
entry.watchdog = timer;
|
|
154
|
+
}
|
|
155
|
+
const info = await this.info();
|
|
156
|
+
if (!info.ready) {
|
|
157
|
+
this.fail(entry, info.reason ?? 'The local video model is not ready.');
|
|
158
|
+
return { ok: true, value: { ...entry.job } };
|
|
159
|
+
}
|
|
160
|
+
if (request.image && !info.imageVideo) {
|
|
161
|
+
this.fail(entry, 'Install the Wan Fun 1.3B image model and native inpaint nodes for image-to-video.');
|
|
162
|
+
return { ok: true, value: { ...entry.job } };
|
|
163
|
+
}
|
|
164
|
+
let submitting = false;
|
|
165
|
+
try {
|
|
166
|
+
if (request.image) {
|
|
167
|
+
const bytes = Buffer.from(request.image.slice('data:image/png;base64,'.length), 'base64');
|
|
168
|
+
if (bytes.length < 24 || bytes.length > 5_000_000 || bytes.readUInt32BE(16) > 1280 || bytes.readUInt32BE(20) > 1280 || bytes.readUInt32BE(16) < 64 || bytes.readUInt32BE(20) < 64 || !bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
|
|
169
|
+
this.fail(entry, 'Invalid starting picture.');
|
|
170
|
+
return { ok: true, value: { ...entry.job } };
|
|
171
|
+
}
|
|
172
|
+
const form = new FormData();
|
|
173
|
+
form.set('image', new Blob([bytes], { type: 'image/png' }), `ropetide-${entry.job.id}.png`);
|
|
174
|
+
form.set('overwrite', 'false');
|
|
175
|
+
const uploaded = await this.json('/upload/image', { method: 'POST', body: form });
|
|
176
|
+
if (uploaded.name !== `ropetide-${entry.job.id}.png` || uploaded.subfolder !== '') {
|
|
177
|
+
this.fail(entry, 'Could not prepare the starting picture.');
|
|
178
|
+
return { ok: true, value: { ...entry.job } };
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
submitting = true;
|
|
182
|
+
const graph = videoWorkflow(request, entry.job.id, this.encoder, randomInt(0, 2 ** 48 - 1), this.compact);
|
|
183
|
+
entry.nativeNodes = new Set(Object.keys(graph));
|
|
184
|
+
const response = await this.response('/prompt', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ prompt: graph, client_id: entry.job.id, extra_data: { ropetide_scope: scopeKey(owner, room), ropetide_request_id: request.requestId } }) });
|
|
185
|
+
if (response.status === 400) {
|
|
186
|
+
await response.body?.cancel();
|
|
187
|
+
this.fail(entry, 'ComfyUI rejected the video workflow. Update ComfyUI and check the installed model files.');
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
// A connection failure after sending is ambiguous; never repeat GPU work automatically.
|
|
191
|
+
if (!response.ok) {
|
|
192
|
+
await response.body?.cancel();
|
|
193
|
+
throw new Error('uncertain submission');
|
|
194
|
+
}
|
|
195
|
+
const data = record(JSON.parse(new TextDecoder().decode(await readBytes(response, 1_000_000))));
|
|
196
|
+
if (typeof data.prompt_id !== 'string' || !/^[a-zA-Z0-9-]{1,100}$/.test(data.prompt_id))
|
|
197
|
+
throw new Error('uncertain submission');
|
|
198
|
+
entry.promptId = data.prompt_id;
|
|
199
|
+
entry.job.state = 'queued';
|
|
200
|
+
if (this.liveProgress)
|
|
201
|
+
this.watch(entry);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
if (!submitting) {
|
|
206
|
+
this.fail(entry, 'Could not prepare the starting picture. Check the local engine and retry.');
|
|
207
|
+
return { ok: true, value: { ...entry.job } };
|
|
208
|
+
}
|
|
209
|
+
entry.job.state = 'uncertain';
|
|
210
|
+
entry.job.reason = 'Submission could not be confirmed. Check the ComfyUI queue before restarting Runner; it will not submit this video again.';
|
|
211
|
+
}
|
|
212
|
+
return { ok: true, value: { ...entry.job } };
|
|
213
|
+
}
|
|
214
|
+
cleanup(entry) {
|
|
215
|
+
const release = entry.releaseAwake;
|
|
216
|
+
delete entry.releaseAwake;
|
|
217
|
+
release?.();
|
|
218
|
+
entry.socket?.close();
|
|
219
|
+
delete entry.socket;
|
|
220
|
+
if (entry.watchdog)
|
|
221
|
+
clearInterval(entry.watchdog);
|
|
222
|
+
delete entry.watchdog;
|
|
223
|
+
}
|
|
224
|
+
watch(entry) {
|
|
225
|
+
const socket = new WebSocket(`${this.base.replace('http:', 'ws:')}/ws?clientId=${entry.job.id}`);
|
|
226
|
+
entry.socket = socket;
|
|
227
|
+
socket.addEventListener('error', () => { });
|
|
228
|
+
socket.addEventListener('message', event => {
|
|
229
|
+
try {
|
|
230
|
+
const value = record(JSON.parse(String(event.data)));
|
|
231
|
+
const data = record(value.data);
|
|
232
|
+
if (data.prompt_id !== entry.promptId)
|
|
233
|
+
return;
|
|
234
|
+
if (value.type === 'progress' && typeof data.value === 'number' && typeof data.max === 'number' && data.max > 0) {
|
|
235
|
+
const progress = Math.max(6, Math.min(90, 5 + Math.floor(data.value / data.max * 85)));
|
|
236
|
+
if (progress > (entry.job.progress ?? 0)) {
|
|
237
|
+
entry.job.progress = progress;
|
|
238
|
+
entry.progressed = this.clock.now();
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
else if (value.type === 'executing' && typeof data.node === 'string' && /^(?:[1-9]|1[0-3])$/.test(data.node) && entry.nativeNodes?.has(data.node)) {
|
|
242
|
+
entry.executedNodes ??= new Set();
|
|
243
|
+
if (entry.executedNodes.has(data.node))
|
|
244
|
+
return;
|
|
245
|
+
entry.executedNodes.add(data.node);
|
|
246
|
+
const progress = data.node === '9' ? 92 : data.node === '13' ? 93 : data.node === '10' ? 94 : data.node === '11' ? 95 : Math.min(5, entry.executedNodes.size);
|
|
247
|
+
entry.job.progress = Math.max(entry.job.progress ?? 0, progress);
|
|
248
|
+
entry.progressed = this.clock.now();
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
catch { /* only validated progress updates matter */ }
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
async cancel(owner, room, id) {
|
|
255
|
+
const entry = this.entries.get(id);
|
|
256
|
+
if (!entry || entry.owner !== owner || entry.room !== room)
|
|
257
|
+
return { ok: false, reason: 'Video not found in this room.' };
|
|
258
|
+
if (entry.job.state === 'completed' || entry.job.state === 'failed')
|
|
259
|
+
return { ok: true, value: { ...entry.job } };
|
|
260
|
+
if (!entry.promptId)
|
|
261
|
+
return { ok: false, reason: 'Submission is uncertain. Inspect the engine queue; no global interrupt will be sent.' };
|
|
262
|
+
try {
|
|
263
|
+
// Older ComfyUI versions can ignore prompt_id and interrupt somebody else's job.
|
|
264
|
+
const stats = await this.json('/system_stats');
|
|
265
|
+
if (record(stats.system).comfyui_version !== '0.46.0')
|
|
266
|
+
return { ok: false, reason: 'Targeted cancellation requires the validated ComfyUI 0.46.0 engine.' };
|
|
267
|
+
const interrupt = await this.response('/interrupt', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ prompt_id: entry.promptId }) });
|
|
268
|
+
const remove = await this.response('/queue', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ delete: [entry.promptId] }) });
|
|
269
|
+
await interrupt.body?.cancel();
|
|
270
|
+
await remove.body?.cancel();
|
|
271
|
+
if (!interrupt.ok || !remove.ok)
|
|
272
|
+
throw new Error('Cancellation refused');
|
|
273
|
+
this.fail(entry, 'Local video cancelled. The engine was asked to stop only this job.');
|
|
274
|
+
return { ok: true, value: { ...entry.job } };
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
return { ok: false, reason: 'Local cancellation could not be confirmed. Check the engine queue.' };
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/** Recover accepted work after a lost response or Runner restart, without resubmission. */
|
|
281
|
+
async recover(entry) {
|
|
282
|
+
const matches = (item) => {
|
|
283
|
+
if (!Array.isArray(item) || typeof item[1] !== 'string' || !/^[a-zA-Z0-9-]{1,100}$/.test(item[1]))
|
|
284
|
+
return false;
|
|
285
|
+
const metadata = record(item[3]);
|
|
286
|
+
return metadata.client_id === entry.job.id && metadata.ropetide_scope === scopeKey(entry.owner, entry.room) && metadata.ropetide_request_id === entry.request.requestId;
|
|
287
|
+
};
|
|
288
|
+
try {
|
|
289
|
+
const queue = await this.json('/queue');
|
|
290
|
+
const queued = [...(Array.isArray(queue.queue_running) ? queue.queue_running : []), ...(Array.isArray(queue.queue_pending) ? queue.queue_pending : [])].find(matches);
|
|
291
|
+
let found = queued;
|
|
292
|
+
if (!found) {
|
|
293
|
+
const history = await this.json('/history?max_items=64');
|
|
294
|
+
found = Object.values(history).map(item => record(item).prompt).find(matches);
|
|
295
|
+
}
|
|
296
|
+
if (!found || typeof found[1] !== 'string')
|
|
297
|
+
return false;
|
|
298
|
+
const graph = record(found[2]);
|
|
299
|
+
const output = record(record(graph['11']).inputs);
|
|
300
|
+
const model = record(record(graph['1']).inputs).unet_name;
|
|
301
|
+
if (output.filename_prefix !== `ropetide/${entry.job.id}` || ![MODEL, IMAGE_MODEL, 'wan2.1_t2v_1.3B_fp16.safetensors'].includes(String(model)))
|
|
302
|
+
return false;
|
|
303
|
+
entry.nativeNodes = new Set(Object.keys(graph));
|
|
304
|
+
entry.promptId = found[1];
|
|
305
|
+
entry.job.state = 'queued';
|
|
306
|
+
delete entry.job.reason;
|
|
307
|
+
entry.job.model = model === IMAGE_MODEL ? 'Wan2.1 Fun InP 1.3B' : model === MODEL ? 'Wan2.2 TI2V 5B' : 'Wan2.1 T2V 1.3B';
|
|
308
|
+
if (this.liveProgress)
|
|
309
|
+
this.watch(entry);
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
return false;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
async restore(owner, room, id, requestId) {
|
|
317
|
+
const existing = this.entries.get(id);
|
|
318
|
+
if (existing)
|
|
319
|
+
return existing.owner === owner && existing.room === room ? { ok: true, value: { ...existing.job } } : { ok: false, reason: 'Video not found in this room.' };
|
|
320
|
+
if (!/^[0-9a-f-]{36}$/i.test(id) || !/^[a-zA-Z0-9-]{16,64}$/.test(requestId) || this.entries.size >= 64)
|
|
321
|
+
return { ok: false, reason: 'Invalid video recovery request.' };
|
|
322
|
+
const now = this.clock.now();
|
|
323
|
+
const entry = { owner, room, request: { requestId, prompt: 'Recovered local video', preset: 'standard' }, job: { id, state: 'uncertain', preset: 'standard', requestId }, started: now, progressed: now };
|
|
324
|
+
if (!await this.recover(entry))
|
|
325
|
+
return { ok: false, reason: 'This engine no longer has the video for this pairing and room.' };
|
|
326
|
+
this.entries.set(id, entry);
|
|
327
|
+
await this.refresh(entry);
|
|
328
|
+
if (entry.job.state === 'queued' || entry.job.state === 'running') {
|
|
329
|
+
if (!this.active)
|
|
330
|
+
this.active = entry;
|
|
331
|
+
entry.releaseAwake = this.stayAwake();
|
|
332
|
+
if (this.liveProgress) {
|
|
333
|
+
const timer = setInterval(() => { void this.refresh(entry); }, 5000);
|
|
334
|
+
timer.unref();
|
|
335
|
+
entry.watchdog = timer;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return { ok: true, value: { ...entry.job } };
|
|
339
|
+
}
|
|
340
|
+
fail(entry, reason) {
|
|
341
|
+
this.cleanup(entry);
|
|
342
|
+
entry.job.state = 'failed';
|
|
343
|
+
entry.job.reason = reason;
|
|
344
|
+
if (this.active === entry)
|
|
345
|
+
this.active = undefined;
|
|
346
|
+
}
|
|
347
|
+
async refresh(entry) {
|
|
348
|
+
if (entry.refreshing)
|
|
349
|
+
return entry.refreshing;
|
|
350
|
+
const update = async () => {
|
|
351
|
+
if (!entry.promptId && entry.job.state === 'uncertain')
|
|
352
|
+
await this.recover(entry);
|
|
353
|
+
if (!entry.promptId || !['queued', 'running'].includes(entry.job.state))
|
|
354
|
+
return;
|
|
355
|
+
const now = this.clock.now();
|
|
356
|
+
if (now - (entry.started ?? now) > 30 * 60_000 || now - (entry.progressed ?? now) > 6 * 60_000) {
|
|
357
|
+
const cancelled = await this.cancel(entry.owner, entry.room, entry.job.id);
|
|
358
|
+
if (!cancelled.ok) {
|
|
359
|
+
entry.job.state = 'uncertain';
|
|
360
|
+
entry.job.reason = cancelled.reason;
|
|
361
|
+
this.cleanup(entry);
|
|
362
|
+
}
|
|
363
|
+
else
|
|
364
|
+
entry.job.reason = now - (entry.started ?? now) > 30 * 60_000
|
|
365
|
+
? 'Local video exceeded the 30-minute generation limit; its job was stopped.'
|
|
366
|
+
: 'Local video stopped after six minutes without model progress.';
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
try {
|
|
370
|
+
const history = record((await this.json(`/history/${encodeURIComponent(entry.promptId)}`))[entry.promptId]);
|
|
371
|
+
const status = record(history.status);
|
|
372
|
+
if (status.status_str === 'error') {
|
|
373
|
+
this.fail(entry, 'The local model failed. Check ComfyUI for memory or model compatibility errors.');
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
if (status.completed === true) {
|
|
377
|
+
const images = record(record(history.outputs)['11']).images;
|
|
378
|
+
const output = record(Array.isArray(images) ? images[0] : undefined);
|
|
379
|
+
// Playback can only fetch the output of this job's fixed SaveVideo node.
|
|
380
|
+
if (typeof output.filename !== 'string' || !output.filename.startsWith(`${entry.job.id}_`) || !/^[a-zA-Z0-9_-]+\.mp4$/.test(output.filename) || output.subfolder !== 'ropetide' || output.type !== 'output') {
|
|
381
|
+
this.fail(entry, 'The engine did not return the expected MP4 output.');
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
entry.filename = output.filename;
|
|
385
|
+
entry.job.state = 'completed';
|
|
386
|
+
entry.job.progress = 100;
|
|
387
|
+
this.cleanup(entry);
|
|
388
|
+
delete entry.job.reason;
|
|
389
|
+
if (this.active === entry)
|
|
390
|
+
this.active = undefined;
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const queue = await this.json('/queue');
|
|
394
|
+
const contains = (value) => Array.isArray(value) && value.some((item) => Array.isArray(item) && item[1] === entry.promptId);
|
|
395
|
+
if (contains(queue.queue_running)) {
|
|
396
|
+
entry.job.state = 'running';
|
|
397
|
+
delete entry.job.reason;
|
|
398
|
+
}
|
|
399
|
+
else if (contains(queue.queue_pending)) {
|
|
400
|
+
entry.job.state = 'queued';
|
|
401
|
+
delete entry.job.reason;
|
|
402
|
+
}
|
|
403
|
+
// Empty queues can race completion/history. Retain the lock and permit another poll.
|
|
404
|
+
else
|
|
405
|
+
entry.job.reason = 'Waiting for the local engine to confirm this video. If ComfyUI restarted or its history was cleared, inspect its queue before restarting Runner.';
|
|
406
|
+
}
|
|
407
|
+
catch {
|
|
408
|
+
entry.job.reason = 'The local engine is unreachable. Runner will keep checking without resubmitting.';
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
entry.refreshing = update();
|
|
412
|
+
try {
|
|
413
|
+
await entry.refreshing;
|
|
414
|
+
}
|
|
415
|
+
finally {
|
|
416
|
+
delete entry.refreshing;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
async list(owner, room) {
|
|
420
|
+
const entries = [...this.entries.values()].filter((entry) => entry.owner === owner && entry.room === room);
|
|
421
|
+
await Promise.all(entries.map((entry) => this.refresh(entry)));
|
|
422
|
+
return entries.map((entry) => ({ ...entry.job }));
|
|
423
|
+
}
|
|
424
|
+
async media(owner, room, id) {
|
|
425
|
+
const entry = this.entries.get(id);
|
|
426
|
+
if (!entry || entry.owner !== owner || entry.room !== room || entry.job.state !== 'completed' || !entry.filename)
|
|
427
|
+
return { ok: false, reason: 'Video not found in this room.' };
|
|
428
|
+
try {
|
|
429
|
+
const query = new URLSearchParams({ filename: entry.filename, subfolder: 'ropetide', type: 'output' });
|
|
430
|
+
const response = await this.response(`/view?${query}`);
|
|
431
|
+
if (!response.ok) {
|
|
432
|
+
await response.body?.cancel();
|
|
433
|
+
throw new Error('missing video');
|
|
434
|
+
}
|
|
435
|
+
const bytes = await readBytes(response, 100_000_000);
|
|
436
|
+
if (bytes.length < 12 || new TextDecoder().decode(bytes.slice(4, 8)) !== 'ftyp')
|
|
437
|
+
return { ok: false, reason: 'The local engine returned an invalid MP4.' };
|
|
438
|
+
return { ok: true, value: bytes };
|
|
439
|
+
}
|
|
440
|
+
catch {
|
|
441
|
+
return { ok: false, reason: 'Could not load the MP4 from the local engine. Check that ComfyUI is running and its output file still exists.' };
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const FIVE = ['low', 'medium', 'high', 'xhigh', 'max'];
|
|
2
|
+
const THREE = ['low', 'medium', 'high'];
|
|
3
|
+
// Only levels confirmed for each model are offered, the more restrictive of the two designs that
|
|
4
|
+
// met when web/multiplayer-room was merged (see docs/DECISIONS.md, 2026-11-18): Claude takes all
|
|
5
|
+
// five, ChatGPT up to high, and Gemini's thinking level isn't offered until it is confirmed.
|
|
6
|
+
// Room-level effort (apps/web/src/run/effort.ts, EFFORTS in room-turn/turn.ts) uses the same set.
|
|
7
|
+
const LEVELS = {
|
|
8
|
+
'fable-5.2': FIVE, 'opus-5.5': FIVE, 'sonnet-5.5': FIVE, 'haiku-5.5': FIVE,
|
|
9
|
+
'gpt-6.2-astra': THREE, 'gpt-6.2-sol': THREE, 'gpt-6-astra': THREE, 'gpt-6.1-sol': THREE, 'gpt-6.1-terra': THREE, 'gpt-6-luna': THREE,
|
|
10
|
+
'gemini-4-carbon': [], 'gemini-4-neon': [], 'gemini-4-hydrogen': [],
|
|
11
|
+
};
|
|
12
|
+
export const effortLevels = (model) => Object.hasOwn(LEVELS, model) ? LEVELS[model] ?? [] : [];
|
|
13
|
+
export const supportsEffort = (model, value) => effortLevels(model).some((level) => level === value);
|
|
14
|
+
export const effortLabel = (value) => value === 'xhigh' ? 'Extra high' : value ? value[0]?.toUpperCase() + value.slice(1) : 'Model default';
|
|
15
|
+
/** Output includes thinking. Keep an explicit ceiling even at Max. Legacy requests retain their cap. */
|
|
16
|
+
export const effortTokenFloor = (value) => value === 'max' || value === 'xhigh' ? 32000 : value === 'high' ? 24000 : value ? 16000 : 0;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a folder on someone's computer may share with a room, and how its text files are read and
|
|
3
|
+
* written back. Used by the website for a folder opened in the browser and by Runner for a project
|
|
4
|
+
* folder, so the two can't drift. Plain code with no imports: no model decides anything here.
|
|
5
|
+
*/
|
|
6
|
+
export const FOLDER_CONTEXT_PATH = 'ROPETIDE_FOLDER.md';
|
|
7
|
+
export const REPO_CONTEXT_PATH = 'ROPETIDE_GITHUB_REPO.md';
|
|
8
|
+
export const COMMANDS_CONTEXT_PATH = 'ROPETIDE_COMMANDS.md';
|
|
9
|
+
/** The same rule as the server's isRoomPath: relative, no "..", ordinary characters only. */
|
|
10
|
+
export const isRoomPath = (v) => /^[\w][\w .\-/]*$/.test(v) && v.length <= 120 && !v.split('/').some((p) => p === '..' || p === '');
|
|
11
|
+
/** The room server's own limit on one file: a longer file reaches agents in parts. */
|
|
12
|
+
export const MAX_FOLDER_FILE_CHARS = 40_000;
|
|
13
|
+
/** The longest file in a folder that agents may read, and change with EDIT blocks. */
|
|
14
|
+
export const MAX_LARGE_FILE_CHARS = 120_000;
|
|
15
|
+
/** One part of a long file, small enough that two fit in what the server shows an agent inline. */
|
|
16
|
+
export const FOLDER_PART_CHARS = 30_000;
|
|
17
|
+
/** Parts are sent as room files under this name, which no folder file or reply may use. */
|
|
18
|
+
export const PART_PREFIX = 'ROPETIDE_PART_';
|
|
19
|
+
export const MAX_FILE_BYTES = 480_000;
|
|
20
|
+
export const MAX_LISTED = 2000;
|
|
21
|
+
export const MAX_WALKED = 12_000;
|
|
22
|
+
export const MAX_DEPTH = 12;
|
|
23
|
+
export const MAX_MATCHES = 40;
|
|
24
|
+
/** Dependencies and build output: large, generated, and not what anyone asks an agent to edit. */
|
|
25
|
+
export const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'vendor', 'coverage', 'target', '__pycache__', 'venv', 'bower_components', 'pods', 'deriveddata']);
|
|
26
|
+
const BINARY = /\.(png|jpe?g|gif|webp|avif|ico|icns|bmp|tiff?|psd|mp[34]|m4a|mov|avi|webm|wav|ogg|woff2?|ttf|otf|eot|pdf|zip|gz|tgz|tar|7z|rar|dmg|jar|class|so|dylib|dll|exe|bin|wasm|node|pyc|sqlite3?|db|docx?|xlsx?|pptx?|lock|map|min\.js)$/i;
|
|
27
|
+
/** Names that usually hold keys or passwords. Never listed, read or written. */
|
|
28
|
+
export const SECRET_NAMES = [
|
|
29
|
+
/\.env$/i,
|
|
30
|
+
/^env\.(local|dev|development|test|staging|prod|production)(\.local)?$/i,
|
|
31
|
+
/\.(pem|key|p8|p12|pfx|keystore|jks|der|crt|cer|kdbx)$/i,
|
|
32
|
+
/^id_(rsa|dsa|ecdsa|ed25519)/i,
|
|
33
|
+
/^(secrets?|credentials?)([._-].*)?\.(json|ya?ml|toml|ini|txt|xml|properties)$/i,
|
|
34
|
+
/service[-_ ]?account.*\.json$/i,
|
|
35
|
+
];
|
|
36
|
+
const PRIVATE_KEY = /-----BEGIN [A-Z ]*PRIVATE KEY( BLOCK)?-----/;
|
|
37
|
+
/** Why a path in the folder is off limits to agents, or null when they may use it. */
|
|
38
|
+
export function folderPathRefusal(path) {
|
|
39
|
+
const parts = path.split('/');
|
|
40
|
+
const name = parts.at(-1) ?? '';
|
|
41
|
+
if (path.startsWith('/') || parts.includes('..'))
|
|
42
|
+
return 'it is outside the folder';
|
|
43
|
+
if (path.toUpperCase().startsWith(PART_PREFIX))
|
|
44
|
+
return 'Ropetide uses that name itself';
|
|
45
|
+
if (parts.some((p) => p.startsWith('.')))
|
|
46
|
+
return 'hidden files and folders aren’t shared';
|
|
47
|
+
if (!isRoomPath(path))
|
|
48
|
+
return 'its name has characters Ropetide can’t use yet (letters, numbers, spaces, dots, dashes and underscores work)';
|
|
49
|
+
if (parts.slice(0, -1).some((p) => SKIP_DIRS.has(p.toLowerCase())))
|
|
50
|
+
return 'dependency and build folders aren’t shared';
|
|
51
|
+
if ([FOLDER_CONTEXT_PATH, REPO_CONTEXT_PATH, COMMANDS_CONTEXT_PATH].some((p) => p.toLowerCase() === path.toLowerCase()))
|
|
52
|
+
return 'Ropetide uses that name itself';
|
|
53
|
+
if (SECRET_NAMES.some((r) => r.test(name)))
|
|
54
|
+
return 'it looks like it holds keys or passwords';
|
|
55
|
+
if (BINARY.test(name))
|
|
56
|
+
return 'it isn’t a text file';
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
/** A long file cut into parts at line ends. Joined with newlines, they are the file again. */
|
|
60
|
+
export function fileParts(text) {
|
|
61
|
+
const out = [];
|
|
62
|
+
let held = [];
|
|
63
|
+
let size = 0;
|
|
64
|
+
let firstLine = 1;
|
|
65
|
+
const cut = () => {
|
|
66
|
+
out.push({ number: out.length + 1, firstLine, lastLine: firstLine + held.length - 1, text: held.join('\n') });
|
|
67
|
+
firstLine += held.length;
|
|
68
|
+
held = [];
|
|
69
|
+
size = 0;
|
|
70
|
+
};
|
|
71
|
+
for (const line of text.split('\n')) {
|
|
72
|
+
if (held.length && size + 1 + line.length > FOLDER_PART_CHARS)
|
|
73
|
+
cut();
|
|
74
|
+
size += (held.length ? 1 : 0) + line.length;
|
|
75
|
+
held.push(line);
|
|
76
|
+
}
|
|
77
|
+
cut();
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
/** Why text is too long to share, or null. */
|
|
81
|
+
export function sizeRefusal(text) {
|
|
82
|
+
if (text.length <= MAX_FOLDER_FILE_CHARS)
|
|
83
|
+
return null;
|
|
84
|
+
if (text.length > MAX_LARGE_FILE_CHARS)
|
|
85
|
+
return 'it is larger than 120,000 characters';
|
|
86
|
+
return text.split('\n').some((line) => line.length > FOLDER_PART_CHARS) ? 'it is larger than 40,000 characters and has a line too long to read in parts' : null;
|
|
87
|
+
}
|
|
88
|
+
export function snapshotOf(raw) {
|
|
89
|
+
const bom = raw.startsWith('');
|
|
90
|
+
const body = bom ? raw.slice(1) : raw;
|
|
91
|
+
// Windows line endings are kept only when the whole file uses them.
|
|
92
|
+
const crlf = body.includes('\r\n') && !/(^|[^\r])\n/.test(body);
|
|
93
|
+
const unix = body.replace(/\r\n/g, '\n');
|
|
94
|
+
const finalNewline = unix.endsWith('\n');
|
|
95
|
+
return { raw, text: finalNewline ? unix.slice(0, -1) : unix, bom, crlf, finalNewline };
|
|
96
|
+
}
|
|
97
|
+
/** Room text as file content, in the style of the file it replaces. A new file ends with a newline. */
|
|
98
|
+
export function contentFor(text, like) {
|
|
99
|
+
const ended = !like || like.finalNewline || like.raw === '' ? `${text}\n` : text;
|
|
100
|
+
return `${like?.bom ? '' : ''}${like?.crlf ? ended.replace(/\n/g, '\r\n') : ended}`;
|
|
101
|
+
}
|
|
102
|
+
/** Why text can't be saved over the file as the agents read it. Only a file already long may stay long. */
|
|
103
|
+
export function writeRefusal(text, like) {
|
|
104
|
+
if (text.length > MAX_FOLDER_FILE_CHARS && (like?.text.length ?? 0) <= MAX_FOLDER_FILE_CHARS)
|
|
105
|
+
return 'it is larger than 40,000 characters';
|
|
106
|
+
return sizeRefusal(text);
|
|
107
|
+
}
|
|
108
|
+
/** Why a file's bytes can't be shared as text, or its text when they can. */
|
|
109
|
+
export function folderText(bytes) {
|
|
110
|
+
const no = (reason) => ({ ok: false, reason });
|
|
111
|
+
if (bytes.byteLength > MAX_FILE_BYTES)
|
|
112
|
+
return no('it is larger than 120,000 characters');
|
|
113
|
+
let raw;
|
|
114
|
+
try {
|
|
115
|
+
raw = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return no('it isn’t UTF-8 text');
|
|
119
|
+
}
|
|
120
|
+
if ([...raw].some((c) => { const code = c.charCodeAt(0); return code < 9 || (code > 13 && code < 32) || code === 127; }))
|
|
121
|
+
return no('it isn’t a text file');
|
|
122
|
+
if (PRIVATE_KEY.test(raw))
|
|
123
|
+
return no('it contains a private key');
|
|
124
|
+
const snapshot = snapshotOf(raw);
|
|
125
|
+
const tooLong = sizeRefusal(snapshot.text);
|
|
126
|
+
if (tooLong)
|
|
127
|
+
return no(tooLong);
|
|
128
|
+
return { ok: true, snapshot };
|
|
129
|
+
}
|