vibecode-anything 0.0.0-stage → 0.3.0
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/LICENSE +21 -0
- package/README.md +235 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +452 -0
- package/dist/core/adapters.d.ts +8 -0
- package/dist/core/adapters.js +92 -0
- package/dist/core/diff.d.ts +10 -0
- package/dist/core/diff.js +207 -0
- package/dist/core/doctor.d.ts +50 -0
- package/dist/core/doctor.js +312 -0
- package/dist/core/errors.d.ts +32 -0
- package/dist/core/errors.js +81 -0
- package/dist/core/exec.d.ts +14 -0
- package/dist/core/exec.js +109 -0
- package/dist/core/parity.d.ts +9 -0
- package/dist/core/parity.js +138 -0
- package/dist/core/png.d.ts +7 -0
- package/dist/core/png.js +303 -0
- package/dist/core/schema.d.ts +17 -0
- package/dist/core/schema.js +614 -0
- package/dist/core/slices.d.ts +24 -0
- package/dist/core/slices.js +294 -0
- package/dist/core/store.d.ts +17 -0
- package/dist/core/store.js +97 -0
- package/dist/core/types.d.ts +751 -0
- package/dist/core/types.js +4 -0
- package/dist/core/visual.d.ts +34 -0
- package/dist/core/visual.js +459 -0
- package/dist/core/watch.d.ts +53 -0
- package/dist/core/watch.js +285 -0
- package/dist/ingestors/api-repo.d.ts +5 -0
- package/dist/ingestors/api-repo.js +722 -0
- package/dist/ingestors/bridges.d.ts +3 -0
- package/dist/ingestors/bridges.js +562 -0
- package/dist/ingestors/cli.d.ts +9 -0
- package/dist/ingestors/cli.js +266 -0
- package/dist/ingestors/image.d.ts +2 -0
- package/dist/ingestors/image.js +147 -0
- package/dist/ingestors/index.d.ts +5 -0
- package/dist/ingestors/index.js +97 -0
- package/dist/ingestors/video.d.ts +47 -0
- package/dist/ingestors/video.js +605 -0
- package/dist/ingestors/web.d.ts +25 -0
- package/dist/ingestors/web.js +397 -0
- package/dist/mcp/server.d.ts +2 -0
- package/dist/mcp/server.js +504 -0
- package/dist/oracles/api-repo.d.ts +2 -0
- package/dist/oracles/api-repo.js +214 -0
- package/dist/oracles/cli.d.ts +2 -0
- package/dist/oracles/cli.js +157 -0
- package/dist/oracles/image.d.ts +2 -0
- package/dist/oracles/image.js +279 -0
- package/dist/oracles/index.d.ts +4 -0
- package/dist/oracles/index.js +91 -0
- package/dist/oracles/video.d.ts +21 -0
- package/dist/oracles/video.js +411 -0
- package/dist/oracles/web.d.ts +2 -0
- package/dist/oracles/web.js +480 -0
- package/dist/setup/index.d.ts +7 -0
- package/dist/setup/index.js +186 -0
- package/package.json +47 -6
- package/skills/vibecode-anything/SKILL.md +52 -0
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { VibecodeError } from "../core/errors.js";
|
|
5
|
+
import { findFfmpeg } from "../core/adapters.js";
|
|
6
|
+
import { decodeImage, computeSSIM, computeDHash, hammingDistanceHex, computePixelDiff, extractPalette, extractLayoutRegions } from "../core/visual.js";
|
|
7
|
+
import { ensureDir, saveArtifact, resolveWorkspace } from "../core/store.js";
|
|
8
|
+
export const VIDEO_EXTS = new Set([".mp4", ".mov", ".webm", ".mkv", ".gif", ".avi", ".m4v"]);
|
|
9
|
+
export const IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".webp"]);
|
|
10
|
+
const DEDUPE_SSIM = 0.985;
|
|
11
|
+
/* ------------------------------------------------------------------ *
|
|
12
|
+
* Subtitle parsing (.srt / .vtt)
|
|
13
|
+
* ------------------------------------------------------------------ */
|
|
14
|
+
function parseTimestamp(ts) {
|
|
15
|
+
// HH:MM:SS.mmm | HH:MM:SS,mmm | MM:SS.mmm
|
|
16
|
+
const m = String(ts).trim().match(/^(?:(\d{2,}):)?(\d{2}):(\d{2})[,.](\d{1,3})$/);
|
|
17
|
+
if (!m)
|
|
18
|
+
return null;
|
|
19
|
+
const hh = Number(m[1] || 0);
|
|
20
|
+
const ms = Number(m[4].padEnd(3, "0"));
|
|
21
|
+
return ((hh * 60 + Number(m[2])) * 60 + Number(m[3])) * 1000 + ms;
|
|
22
|
+
}
|
|
23
|
+
export function parseCues(text) {
|
|
24
|
+
const body = String(text)
|
|
25
|
+
.replace(/\r\n/g, "\n")
|
|
26
|
+
.replace(/^\uFEFF/, "")
|
|
27
|
+
.replace(/^WEBVTT[^\n]*\n+/, "");
|
|
28
|
+
const cues = [];
|
|
29
|
+
for (const block of body.split(/\n{2,}/)) {
|
|
30
|
+
const lines = block.split("\n").map((l) => l.trimEnd()).filter((l) => l.trim() !== "");
|
|
31
|
+
if (lines.length < 2)
|
|
32
|
+
continue;
|
|
33
|
+
// Timing is on line 0, or line 1 when preceded by an SRT index / VTT cue id.
|
|
34
|
+
const timingIndex = lines[0].includes("-->") ? 0 : lines[1]?.includes("-->") ? 1 : -1;
|
|
35
|
+
if (timingIndex < 0)
|
|
36
|
+
continue;
|
|
37
|
+
const tm = lines[timingIndex].match(/^(.+?)\s+-->\s+(.+?)(?:\s+(?:align|position|line|size|region|vertical):.*)?$/);
|
|
38
|
+
if (!tm)
|
|
39
|
+
continue;
|
|
40
|
+
const startMs = parseTimestamp(tm[1]);
|
|
41
|
+
const endMs = parseTimestamp(tm[2]);
|
|
42
|
+
if (startMs == null || endMs == null)
|
|
43
|
+
continue;
|
|
44
|
+
const textLines = lines
|
|
45
|
+
.slice(timingIndex + 1)
|
|
46
|
+
.map((l) => l.replace(/<[^>]+>/g, "").trim())
|
|
47
|
+
.filter(Boolean);
|
|
48
|
+
if (textLines.length === 0)
|
|
49
|
+
continue;
|
|
50
|
+
cues.push({ startMs, endMs, text: textLines.join(" ") });
|
|
51
|
+
}
|
|
52
|
+
return cues;
|
|
53
|
+
}
|
|
54
|
+
export const parseSrt = parseCues;
|
|
55
|
+
export const parseVtt = parseCues;
|
|
56
|
+
export function readSubtitles(filePath) {
|
|
57
|
+
if (!filePath || !fs.existsSync(filePath))
|
|
58
|
+
return [];
|
|
59
|
+
return parseCues(fs.readFileSync(filePath, "utf8"));
|
|
60
|
+
}
|
|
61
|
+
function findSidecarSubtitles(sourcePath) {
|
|
62
|
+
const base = sourcePath.replace(/\.[^.\\/]+$/, "");
|
|
63
|
+
for (const ext of [".srt", ".vtt"]) {
|
|
64
|
+
if (fs.existsSync(base + ext))
|
|
65
|
+
return base + ext;
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
export function cueAt(cues, timestampMs) {
|
|
70
|
+
if (!Array.isArray(cues) || cues.length === 0)
|
|
71
|
+
return null;
|
|
72
|
+
const hit = cues.find((c) => timestampMs >= c.startMs && timestampMs <= c.endMs);
|
|
73
|
+
if (hit)
|
|
74
|
+
return hit.text;
|
|
75
|
+
let best = null;
|
|
76
|
+
let bestDist = Infinity;
|
|
77
|
+
for (const c of cues) {
|
|
78
|
+
const dist = timestampMs < c.startMs ? c.startMs - timestampMs : timestampMs - c.endMs;
|
|
79
|
+
if (dist < bestDist) {
|
|
80
|
+
bestDist = dist;
|
|
81
|
+
best = c;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return best && bestDist <= 1500 ? best.text : null;
|
|
85
|
+
}
|
|
86
|
+
/* ------------------------------------------------------------------ *
|
|
87
|
+
* ffmpeg adapter (optional, injectable for tests)
|
|
88
|
+
* ------------------------------------------------------------------ */
|
|
89
|
+
function quoteWindowsCmdArg(arg) {
|
|
90
|
+
if (arg.length === 0)
|
|
91
|
+
return '""';
|
|
92
|
+
if (!/[\s"&|<>^(),;=%!]/.test(arg))
|
|
93
|
+
return arg;
|
|
94
|
+
const escaped = arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1");
|
|
95
|
+
return `"${escaped}"`;
|
|
96
|
+
}
|
|
97
|
+
function tailDiagnostic(text, maxLen = 600) {
|
|
98
|
+
if (text == null)
|
|
99
|
+
return "";
|
|
100
|
+
const lines = String(text)
|
|
101
|
+
.replace(/\r\n?/g, "\n")
|
|
102
|
+
.split("\n")
|
|
103
|
+
.map((l) => l.trim())
|
|
104
|
+
.filter(Boolean);
|
|
105
|
+
const joined = lines.join("\n");
|
|
106
|
+
return joined.length > maxLen ? joined.slice(-maxLen) : joined;
|
|
107
|
+
}
|
|
108
|
+
function cleanStaleFrames(outDir) {
|
|
109
|
+
ensureDir(outDir);
|
|
110
|
+
for (const entry of fs.readdirSync(outDir)) {
|
|
111
|
+
if (/^frame-\d+\.png$/i.test(entry)) {
|
|
112
|
+
fs.rmSync(path.join(outDir, entry), { force: true });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function spawnCapture(cmd, args) {
|
|
117
|
+
const opts = {
|
|
118
|
+
encoding: "utf8",
|
|
119
|
+
timeout: 120000,
|
|
120
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
121
|
+
windowsHide: true
|
|
122
|
+
};
|
|
123
|
+
const isWinCmd = process.platform === "win32" && /\.(cmd|bat)$/i.test(cmd);
|
|
124
|
+
const res = isWinCmd
|
|
125
|
+
? spawnSync(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", `"${[quoteWindowsCmdArg(cmd), ...args.map(quoteWindowsCmdArg)].join(" ")}"`], { ...opts, windowsVerbatimArguments: true })
|
|
126
|
+
: spawnSync(cmd, args, { ...opts, shell: false });
|
|
127
|
+
if (res.error) {
|
|
128
|
+
const errCode = res.error.code;
|
|
129
|
+
const stderr = tailDiagnostic(res.stderr);
|
|
130
|
+
throw new VibecodeError("EXEC_ERROR", `Failed to execute ${path.basename(cmd)}${errCode ? ` (${errCode})` : ""}: ${res.error.message}`, {
|
|
131
|
+
adapter: "ffmpeg",
|
|
132
|
+
fallbackHint: "Pass a directory of PNG keyframes with --source ./frames/",
|
|
133
|
+
details: {
|
|
134
|
+
command: cmd,
|
|
135
|
+
args: [...args],
|
|
136
|
+
errorCode: errCode || null,
|
|
137
|
+
signal: res.signal || null,
|
|
138
|
+
stderr
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
return res;
|
|
143
|
+
}
|
|
144
|
+
/** Parse `showinfo` scene timestamps from ffmpeg stderr/stdout. */
|
|
145
|
+
export function parseSceneTimestamps(logText) {
|
|
146
|
+
if (logText == null)
|
|
147
|
+
return [];
|
|
148
|
+
const normalized = String(logText).replace(/\r\n?/g, "\n");
|
|
149
|
+
const times = [];
|
|
150
|
+
const re = /pts_time:\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)(?=$|[\s,;])/g;
|
|
151
|
+
let m;
|
|
152
|
+
while ((m = re.exec(normalized))) {
|
|
153
|
+
const sec = Number(m[1]);
|
|
154
|
+
if (!Number.isFinite(sec))
|
|
155
|
+
continue;
|
|
156
|
+
const ms = sec <= 0 ? 0 : Math.round(sec * 1000);
|
|
157
|
+
times.push(ms);
|
|
158
|
+
}
|
|
159
|
+
return [...new Set(times)].sort((a, b) => a - b);
|
|
160
|
+
}
|
|
161
|
+
function parseNonNegativeSecondsMs(value) {
|
|
162
|
+
if (typeof value === "number") {
|
|
163
|
+
return Number.isFinite(value) && value >= 0 ? (value === 0 ? 0 : Math.round(value * 1000)) : null;
|
|
164
|
+
}
|
|
165
|
+
if (typeof value !== "string")
|
|
166
|
+
return null;
|
|
167
|
+
const s = value.replace(/\r/g, "").trim();
|
|
168
|
+
if (!s || /^n\/a$/i.test(s))
|
|
169
|
+
return null;
|
|
170
|
+
const sec = Number(s);
|
|
171
|
+
if (!Number.isFinite(sec) || sec < 0)
|
|
172
|
+
return null;
|
|
173
|
+
return sec === 0 ? 0 : Math.round(sec * 1000);
|
|
174
|
+
}
|
|
175
|
+
export function parseFfprobeDurationMs(stdout) {
|
|
176
|
+
if (stdout == null)
|
|
177
|
+
return null;
|
|
178
|
+
const text = String(stdout).replace(/\r/g, "").trim();
|
|
179
|
+
if (!text)
|
|
180
|
+
return null;
|
|
181
|
+
// supports plain multi-line output and JSON `{"format":{"duration":"6.400000"},"streams":[...]}`
|
|
182
|
+
if (text.startsWith("{")) {
|
|
183
|
+
try {
|
|
184
|
+
const parsed = JSON.parse(text);
|
|
185
|
+
const formatMs = parseNonNegativeSecondsMs(parsed?.format?.duration);
|
|
186
|
+
if (formatMs !== null)
|
|
187
|
+
return formatMs;
|
|
188
|
+
if (Array.isArray(parsed?.streams)) {
|
|
189
|
+
for (const stream of parsed.streams) {
|
|
190
|
+
const streamMs = parseNonNegativeSecondsMs(stream?.duration);
|
|
191
|
+
if (streamMs !== null)
|
|
192
|
+
return streamMs;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
for (const line of text.split("\n")) {
|
|
202
|
+
const ms = parseNonNegativeSecondsMs(line);
|
|
203
|
+
if (ms !== null)
|
|
204
|
+
return ms;
|
|
205
|
+
}
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
function periodicTimestamps(durationMs, maxFrames) {
|
|
209
|
+
const hasDuration = Number.isFinite(durationMs) && durationMs > 0;
|
|
210
|
+
const rawTotal = hasDuration ? durationMs : maxFrames * 1000;
|
|
211
|
+
const count = Math.max(1, maxFrames);
|
|
212
|
+
if (count === 1)
|
|
213
|
+
return [0];
|
|
214
|
+
const endMs = hasDuration && durationMs > 100 ? Math.max(0, durationMs - 50) : rawTotal;
|
|
215
|
+
const step = endMs / (count - 1);
|
|
216
|
+
const raw = Array.from({ length: count }, (_, i) => (i === count - 1 ? Math.round(endMs) : Math.round(i * step)));
|
|
217
|
+
return [...new Set(raw)].sort((a, b) => a - b);
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Resolve the ffmpeg adapter.
|
|
221
|
+
* - `deps.ffmpegAdapter` explicitly set (object or `null`) wins — `null` models "absent" in tests.
|
|
222
|
+
* - Otherwise probe the real binaries.
|
|
223
|
+
*/
|
|
224
|
+
export function resolveFfmpegAdapter(deps = {}) {
|
|
225
|
+
if (Object.prototype.hasOwnProperty.call(deps, "ffmpegAdapter"))
|
|
226
|
+
return deps.ffmpegAdapter || null;
|
|
227
|
+
const bins = findFfmpeg(deps);
|
|
228
|
+
if (!bins.ffmpeg || !bins.ffprobe)
|
|
229
|
+
return null;
|
|
230
|
+
const ffmpegBin = bins.ffmpeg;
|
|
231
|
+
const ffprobeBin = bins.ffprobe;
|
|
232
|
+
return {
|
|
233
|
+
ffmpeg: ffmpegBin,
|
|
234
|
+
ffprobe: ffprobeBin,
|
|
235
|
+
probeDuration: (src) => {
|
|
236
|
+
const res = spawnCapture(ffprobeBin, [
|
|
237
|
+
"-v", "error",
|
|
238
|
+
"-show_entries", "format=duration:stream=duration",
|
|
239
|
+
"-of", "json",
|
|
240
|
+
src
|
|
241
|
+
]);
|
|
242
|
+
return res.status === 0 ? parseFfprobeDurationMs(res.stdout) : null;
|
|
243
|
+
},
|
|
244
|
+
probeScenes: (src, sceneThreshold, maxFrames) => {
|
|
245
|
+
const res = spawnCapture(ffmpegBin, [
|
|
246
|
+
"-hide_banner", "-i", src,
|
|
247
|
+
"-vf", `select='gt(scene\\,${sceneThreshold})',showinfo`,
|
|
248
|
+
"-f", "null", "-"
|
|
249
|
+
]);
|
|
250
|
+
const times = parseSceneTimestamps(`${res.stderr || ""}\n${res.stdout || ""}`);
|
|
251
|
+
if (res.status !== 0 && times.length === 0) {
|
|
252
|
+
const stderr = tailDiagnostic(res.stderr);
|
|
253
|
+
throw new VibecodeError("EXEC_ERROR", `ffmpeg scene detection failed (exit ${res.status ?? "unknown"})${stderr ? `: ${stderr}` : ""}`, {
|
|
254
|
+
adapter: "ffmpeg",
|
|
255
|
+
fallbackHint: "Pass a directory of PNG keyframes with --source ./frames/",
|
|
256
|
+
details: {
|
|
257
|
+
exitCode: res.status,
|
|
258
|
+
signal: res.signal || null,
|
|
259
|
+
stderr,
|
|
260
|
+
source: src
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
return times.length ? times.slice(0, maxFrames) : null;
|
|
265
|
+
},
|
|
266
|
+
extractFrames: (src, timestampsMs, outDir) => {
|
|
267
|
+
cleanStaleFrames(outDir);
|
|
268
|
+
const out = [];
|
|
269
|
+
let lastExitCode = null;
|
|
270
|
+
let lastStderr = "";
|
|
271
|
+
for (let i = 0; i < timestampsMs.length; i++) {
|
|
272
|
+
const tsMs = Math.max(0, timestampsMs[i]);
|
|
273
|
+
const file = path.join(outDir, `frame-${String(i).padStart(3, "0")}.png`);
|
|
274
|
+
const res = spawnCapture(ffmpegBin, [
|
|
275
|
+
"-hide_banner", "-loglevel", "error", "-y",
|
|
276
|
+
"-ss", String(tsMs / 1000),
|
|
277
|
+
"-i", src, "-frames:v", "1", file
|
|
278
|
+
]);
|
|
279
|
+
if (res.status !== 0) {
|
|
280
|
+
lastExitCode = res.status;
|
|
281
|
+
const diag = tailDiagnostic(res.stderr);
|
|
282
|
+
if (diag)
|
|
283
|
+
lastStderr = diag;
|
|
284
|
+
break;
|
|
285
|
+
}
|
|
286
|
+
if (!fs.existsSync(file) && tsMs > 0) {
|
|
287
|
+
const retryMs = Math.max(0, tsMs - 150);
|
|
288
|
+
const retryRes = spawnCapture(ffmpegBin, [
|
|
289
|
+
"-hide_banner", "-loglevel", "error", "-y",
|
|
290
|
+
"-ss", String(retryMs / 1000),
|
|
291
|
+
"-i", src, "-frames:v", "1", file
|
|
292
|
+
]);
|
|
293
|
+
if (retryRes.status !== 0) {
|
|
294
|
+
lastExitCode = retryRes.status;
|
|
295
|
+
const diag = tailDiagnostic(retryRes.stderr);
|
|
296
|
+
if (diag)
|
|
297
|
+
lastStderr = diag;
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
const retryDiag = tailDiagnostic(retryRes.stderr);
|
|
301
|
+
if (retryDiag)
|
|
302
|
+
lastStderr = retryDiag;
|
|
303
|
+
}
|
|
304
|
+
if (fs.existsSync(file)) {
|
|
305
|
+
out.push({ path: file, timestampMs: tsMs });
|
|
306
|
+
}
|
|
307
|
+
else {
|
|
308
|
+
const diag = tailDiagnostic(res.stderr);
|
|
309
|
+
if (diag)
|
|
310
|
+
lastStderr = diag;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
if (out.length === 0) {
|
|
314
|
+
throw new VibecodeError("EXEC_ERROR", `ffmpeg did not produce any keyframe images${lastExitCode != null ? ` (exit ${lastExitCode})` : ""}${lastStderr ? `: ${lastStderr}` : "."}`, {
|
|
315
|
+
adapter: "ffmpeg",
|
|
316
|
+
fallbackHint: "Pass a directory of PNG keyframes with --source ./frames/",
|
|
317
|
+
details: { exitCode: lastExitCode, stderr: lastStderr, source: src }
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
return out;
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
export function ffmpegMissingError() {
|
|
325
|
+
return new VibecodeError("ADAPTER_MISSING", "ffmpeg/ffprobe are required to ingest video files.", {
|
|
326
|
+
adapter: "ffmpeg",
|
|
327
|
+
installHint: "Install ffmpeg and ensure ffmpeg/ffprobe are on PATH (or set VIBECODE_FFMPEG_PATH/VIBECODE_FFPROBE_PATH).",
|
|
328
|
+
fallbackHint: "Pass a directory of PNG keyframes with --source ./frames/"
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
/** Extract ordered keyframe files + duration from a video file via the adapter. */
|
|
332
|
+
export function extractVideoFrames(absSource, { cwd, sceneThreshold = 0.18, maxFrames = 12, cacheKey = "ingest" }, adapter) {
|
|
333
|
+
if (!adapter)
|
|
334
|
+
throw ffmpegMissingError();
|
|
335
|
+
const rawDuration = adapter.probeDuration(absSource);
|
|
336
|
+
const durationMs = typeof rawDuration === "number" && Number.isFinite(rawDuration) && rawDuration > 0 ? rawDuration : 0;
|
|
337
|
+
let timestamps = adapter.probeScenes(absSource, sceneThreshold, maxFrames);
|
|
338
|
+
if (!Array.isArray(timestamps) || timestamps.length === 0) {
|
|
339
|
+
timestamps = periodicTimestamps(durationMs, Math.min(maxFrames, 4));
|
|
340
|
+
}
|
|
341
|
+
if (!timestamps.includes(0))
|
|
342
|
+
timestamps = [0, ...timestamps];
|
|
343
|
+
const maxTs = durationMs > 20 ? Math.max(0, durationMs - 20) : null;
|
|
344
|
+
timestamps = [
|
|
345
|
+
...new Set(timestamps.map((t) => {
|
|
346
|
+
const nonNeg = Number.isFinite(t) ? Math.max(0, Math.round(t)) : 0;
|
|
347
|
+
return maxTs !== null ? Math.min(maxTs, nonNeg) : nonNeg;
|
|
348
|
+
}))
|
|
349
|
+
]
|
|
350
|
+
.sort((a, b) => a - b)
|
|
351
|
+
.slice(0, maxFrames);
|
|
352
|
+
const { cacheDir } = resolveWorkspace(cwd);
|
|
353
|
+
const outDir = path.join(cacheDir, "video-frames", String(cacheKey).replace(/[^A-Za-z0-9_.-]+/g, "-"));
|
|
354
|
+
cleanStaleFrames(outDir);
|
|
355
|
+
const frames = adapter.extractFrames(absSource, timestamps, outDir) || [];
|
|
356
|
+
if (frames.length === 0) {
|
|
357
|
+
throw new VibecodeError("EXEC_ERROR", "ffmpeg did not produce any keyframe images.", {
|
|
358
|
+
adapter: "ffmpeg",
|
|
359
|
+
fallbackHint: "Pass a directory of PNG keyframes with --source ./frames/",
|
|
360
|
+
details: { exitCode: null, stderr: "", source: absSource }
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
return { frames, durationMs };
|
|
364
|
+
}
|
|
365
|
+
/* ------------------------------------------------------------------ *
|
|
366
|
+
* Frame directory + state extraction
|
|
367
|
+
* ------------------------------------------------------------------ */
|
|
368
|
+
export function listFrameFiles(dir) {
|
|
369
|
+
return fs
|
|
370
|
+
.readdirSync(dir)
|
|
371
|
+
.filter((f) => IMAGE_EXTS.has(path.extname(f).toLowerCase()))
|
|
372
|
+
.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }))
|
|
373
|
+
.map((f) => path.join(dir, f));
|
|
374
|
+
}
|
|
375
|
+
export function bboxFromDiffMask(diffMask) {
|
|
376
|
+
const { width, height, data } = diffMask;
|
|
377
|
+
let minX = width;
|
|
378
|
+
let minY = height;
|
|
379
|
+
let maxX = -1;
|
|
380
|
+
let maxY = -1;
|
|
381
|
+
for (let y = 0; y < height; y++) {
|
|
382
|
+
for (let x = 0; x < width; x++) {
|
|
383
|
+
const i = (y * width + x) * 4;
|
|
384
|
+
// computePixelDiff paints changed pixels pure red
|
|
385
|
+
if (data[i] === 255 && data[i + 1] === 0 && data[i + 2] === 0 && data[i + 3] === 255) {
|
|
386
|
+
if (x < minX)
|
|
387
|
+
minX = x;
|
|
388
|
+
if (y < minY)
|
|
389
|
+
minY = y;
|
|
390
|
+
if (x > maxX)
|
|
391
|
+
maxX = x;
|
|
392
|
+
if (y > maxY)
|
|
393
|
+
maxY = y;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
if (maxX < minX || maxY < minY)
|
|
398
|
+
return { x: 0, y: 0, w: 0, h: 0 };
|
|
399
|
+
return {
|
|
400
|
+
x: minX / width,
|
|
401
|
+
y: minY / height,
|
|
402
|
+
w: (maxX - minX + 1) / width,
|
|
403
|
+
h: (maxY - minY + 1) / height
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
export function changedRegionBetween(imgA, imgB, { colorDelta = 0.1 } = {}) {
|
|
407
|
+
const diff = computePixelDiff(imgA, imgB, { colorDelta });
|
|
408
|
+
return { changedRegion: bboxFromDiffMask(diff.diffMask), diffRatio: diff.diffRatio };
|
|
409
|
+
}
|
|
410
|
+
/** Decode + dedupe frames (SSIM > 0.985) into an ordered state timeline. */
|
|
411
|
+
export async function extractStates(frames, { cues = [], deps = {}, colorDelta = 0.1 } = {}) {
|
|
412
|
+
const decoded = [];
|
|
413
|
+
for (const frame of frames) {
|
|
414
|
+
decoded.push({ ...frame, img: await decodeImage(frame.path, deps) });
|
|
415
|
+
}
|
|
416
|
+
if (decoded.length === 0)
|
|
417
|
+
return { states: [], transitions: [] };
|
|
418
|
+
const kept = [decoded[0]];
|
|
419
|
+
for (let i = 1; i < decoded.length; i++) {
|
|
420
|
+
const cur = decoded[i];
|
|
421
|
+
if (computeSSIM(kept[kept.length - 1].img, cur.img).ssim > DEDUPE_SSIM)
|
|
422
|
+
continue;
|
|
423
|
+
kept.push(cur);
|
|
424
|
+
}
|
|
425
|
+
const states = kept.map((frame, i) => ({
|
|
426
|
+
id: `state-${i}`,
|
|
427
|
+
timestampMs: Number.isFinite(frame.timestampMs) ? frame.timestampMs : i * 1000,
|
|
428
|
+
path: frame.path,
|
|
429
|
+
img: frame.img,
|
|
430
|
+
dHash: computeDHash(frame.img),
|
|
431
|
+
palette: extractPalette(frame.img, 6),
|
|
432
|
+
regions: extractLayoutRegions(frame.img, { maxDepth: 2 }),
|
|
433
|
+
subtitleCue: cueAt(cues, Number.isFinite(frame.timestampMs) ? frame.timestampMs : i * 1000)
|
|
434
|
+
}));
|
|
435
|
+
const transitions = [];
|
|
436
|
+
for (let i = 0; i < states.length - 1; i++) {
|
|
437
|
+
const a = states[i];
|
|
438
|
+
const b = states[i + 1];
|
|
439
|
+
const { changedRegion, diffRatio } = changedRegionBetween(a.img, b.img, { colorDelta });
|
|
440
|
+
const ssimDelta = 1 - computeSSIM(a.img, b.img).ssim;
|
|
441
|
+
transitions.push({
|
|
442
|
+
from: a.id,
|
|
443
|
+
to: b.id,
|
|
444
|
+
changedRegion,
|
|
445
|
+
minDeltaSSIM: Number(Math.max(0, ssimDelta).toFixed(4)),
|
|
446
|
+
eventHint: diffRatio > 0.2 ? "screen_transition" : "minor_change",
|
|
447
|
+
audioCue: null,
|
|
448
|
+
subtitleCue: b.subtitleCue || null
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
return { states, transitions };
|
|
452
|
+
}
|
|
453
|
+
/* ------------------------------------------------------------------ *
|
|
454
|
+
* Ingestor entrypoint
|
|
455
|
+
* ------------------------------------------------------------------ */
|
|
456
|
+
export async function ingest(options = {}, deps = {}) {
|
|
457
|
+
const source = options.source;
|
|
458
|
+
if (!source || typeof source !== "string") {
|
|
459
|
+
throw new VibecodeError("TARGET_MISSING", "Video ingestor requires --source <video-file-or-frames-dir>");
|
|
460
|
+
}
|
|
461
|
+
const cwd = options.cwd || process.cwd();
|
|
462
|
+
const absSource = path.resolve(cwd, source);
|
|
463
|
+
if (!fs.existsSync(absSource)) {
|
|
464
|
+
throw new VibecodeError("TARGET_MISSING", `Video source not found: ${source}`);
|
|
465
|
+
}
|
|
466
|
+
const sceneThreshold = typeof options.sceneThreshold === "number" ? options.sceneThreshold : 0.18;
|
|
467
|
+
const maxFrames = typeof options.maxFrames === "number" && Number.isFinite(options.maxFrames) && options.maxFrames > 0
|
|
468
|
+
? Math.floor(options.maxFrames)
|
|
469
|
+
: 12;
|
|
470
|
+
let frames = [];
|
|
471
|
+
let cues = [];
|
|
472
|
+
let durationMs = 0;
|
|
473
|
+
const warnings = [];
|
|
474
|
+
if (fs.statSync(absSource).isDirectory()) {
|
|
475
|
+
const files = listFrameFiles(absSource);
|
|
476
|
+
if (files.length === 0) {
|
|
477
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `No PNG/JPEG frames found in directory: ${source}`, {
|
|
478
|
+
fallbackHint: "Pass a directory of ordered PNG keyframes with --source ./frames/"
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
frames = files.map((p, i) => ({ path: p, timestampMs: i * 1000 }));
|
|
482
|
+
let sidecar = findSidecarSubtitles(path.join(absSource, "captions")) || findSidecarSubtitles(path.join(absSource, "subtitles"));
|
|
483
|
+
if (!sidecar) {
|
|
484
|
+
const anySub = fs
|
|
485
|
+
.readdirSync(absSource)
|
|
486
|
+
.filter((f) => /\.(srt|vtt)$/i.test(f))
|
|
487
|
+
.sort()[0];
|
|
488
|
+
if (anySub)
|
|
489
|
+
sidecar = path.join(absSource, anySub);
|
|
490
|
+
}
|
|
491
|
+
if (sidecar)
|
|
492
|
+
cues = readSubtitles(sidecar);
|
|
493
|
+
}
|
|
494
|
+
else {
|
|
495
|
+
const ext = path.extname(absSource).toLowerCase();
|
|
496
|
+
if (!VIDEO_EXTS.has(ext)) {
|
|
497
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported video source format: ${ext || "(none)"}`, {
|
|
498
|
+
fallbackHint: "Pass a directory of PNG keyframes with --source ./frames/"
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
const adapter = resolveFfmpegAdapter(deps);
|
|
502
|
+
if (!adapter)
|
|
503
|
+
throw ffmpegMissingError();
|
|
504
|
+
const extracted = extractVideoFrames(absSource, { cwd, sceneThreshold, maxFrames }, adapter);
|
|
505
|
+
frames = extracted.frames;
|
|
506
|
+
durationMs = extracted.durationMs;
|
|
507
|
+
const sidecar = findSidecarSubtitles(absSource);
|
|
508
|
+
if (sidecar)
|
|
509
|
+
cues = readSubtitles(sidecar);
|
|
510
|
+
}
|
|
511
|
+
const { states, transitions } = await extractStates(frames, { cues, deps });
|
|
512
|
+
if (states.length === 0) {
|
|
513
|
+
warnings.push({ code: "ADAPTER_DEGRADED", message: "Video ingestor produced no states." });
|
|
514
|
+
}
|
|
515
|
+
if (!durationMs)
|
|
516
|
+
durationMs = states.length ? states[states.length - 1].timestampMs : 0;
|
|
517
|
+
const { artifactsDir } = resolveWorkspace(cwd);
|
|
518
|
+
ensureDir(artifactsDir);
|
|
519
|
+
const artifacts = {};
|
|
520
|
+
const publicStates = states.map((s, i) => {
|
|
521
|
+
const artKey = `frame-${String(i).padStart(3, "0")}`;
|
|
522
|
+
const ext = path.extname(s.path).toLowerCase() || ".png";
|
|
523
|
+
artifacts[artKey] = saveArtifact(fs.readFileSync(s.path), `frames/${artKey}${ext}`, cwd);
|
|
524
|
+
return {
|
|
525
|
+
id: s.id,
|
|
526
|
+
timestampMs: s.timestampMs,
|
|
527
|
+
keyframeArtifact: artKey,
|
|
528
|
+
dHash: s.dHash,
|
|
529
|
+
palette: s.palette,
|
|
530
|
+
regions: s.regions,
|
|
531
|
+
subtitleCue: s.subtitleCue,
|
|
532
|
+
required: true
|
|
533
|
+
};
|
|
534
|
+
});
|
|
535
|
+
// Adaptive stateMatchFloor: prevent distinct states with shared UI backgrounds
|
|
536
|
+
// (e.g. modals/dashboards) from masquerading as each other when reordered.
|
|
537
|
+
let maxCrossSim = 0;
|
|
538
|
+
for (let i = 0; i < states.length; i++) {
|
|
539
|
+
for (let j = i + 1; j < states.length; j++) {
|
|
540
|
+
const ssim = computeSSIM(states[i].img, states[j].img).ssim;
|
|
541
|
+
const hashSim = Math.max(0, 1 - hammingDistanceHex(states[i].dHash, states[j].dHash) / 64);
|
|
542
|
+
const sim = 0.7 * ssim + 0.3 * hashSim;
|
|
543
|
+
if (sim > maxCrossSim)
|
|
544
|
+
maxCrossSim = sim;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
const stateMatchFloor = maxCrossSim >= 0.68
|
|
548
|
+
? Math.min(0.95, Number((maxCrossSim + (1 - maxCrossSim) * 0.2).toFixed(4)))
|
|
549
|
+
: 0.7;
|
|
550
|
+
const tolerance = {
|
|
551
|
+
stateMatchFloor,
|
|
552
|
+
minKeyframeSSIM: 0.85,
|
|
553
|
+
maxHammingDistance: 14,
|
|
554
|
+
minMotionRegionIoU: 0.55
|
|
555
|
+
};
|
|
556
|
+
const invariants = [];
|
|
557
|
+
if (publicStates.length > 0) {
|
|
558
|
+
invariants.push({
|
|
559
|
+
id: "inv-vid-timeline",
|
|
560
|
+
domain: "video",
|
|
561
|
+
type: "video_timeline",
|
|
562
|
+
severity: "hard",
|
|
563
|
+
description: "Video state sequence matches the reference in strictly monotonic order",
|
|
564
|
+
tags: ["video", "timeline", "hard"],
|
|
565
|
+
sourceId: "src-1",
|
|
566
|
+
input: { orderMode: "monotonic_subsequence" },
|
|
567
|
+
expected: { durationMs, states: publicStates, transitions },
|
|
568
|
+
tolerance
|
|
569
|
+
});
|
|
570
|
+
invariants.push({
|
|
571
|
+
id: "inv-vid-perceptual",
|
|
572
|
+
domain: "video",
|
|
573
|
+
type: "video_timeline",
|
|
574
|
+
severity: "soft",
|
|
575
|
+
description: "Keyframe perceptual similarity (SSIM/palette) and motion regions match reference",
|
|
576
|
+
tags: ["video", "perceptual", "soft"],
|
|
577
|
+
sourceId: "src-1",
|
|
578
|
+
input: { orderMode: "monotonic_subsequence", perceptualOnly: true },
|
|
579
|
+
expected: {
|
|
580
|
+
states: publicStates.map((s) => ({ id: s.id, keyframeArtifact: s.keyframeArtifact, dHash: s.dHash, palette: s.palette })),
|
|
581
|
+
transitions
|
|
582
|
+
},
|
|
583
|
+
tolerance
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
return {
|
|
587
|
+
domain: "video",
|
|
588
|
+
sources: [
|
|
589
|
+
{
|
|
590
|
+
id: "src-1",
|
|
591
|
+
kind: "video",
|
|
592
|
+
ref: source,
|
|
593
|
+
meta: {
|
|
594
|
+
frameCount: frames.length,
|
|
595
|
+
stateCount: publicStates.length,
|
|
596
|
+
durationMs,
|
|
597
|
+
hasSubtitles: cues.length > 0
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
],
|
|
601
|
+
artifacts: { root: ".vibecode/artifacts", files: artifacts },
|
|
602
|
+
invariants,
|
|
603
|
+
warnings
|
|
604
|
+
};
|
|
605
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { IngestDeps, IngestOptions, IngestResult, JsonSchema, WebLandmark, WebNetworkExpectation, WebRouteOption } from "../core/types.js";
|
|
2
|
+
type WebRouteInput = WebRouteOption & {
|
|
3
|
+
timeoutMs?: number;
|
|
4
|
+
};
|
|
5
|
+
type WebIngestOptions = Omit<IngestOptions, "routes"> & {
|
|
6
|
+
routes?: Array<string | WebRouteInput>;
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
};
|
|
9
|
+
declare function stripTags(html: unknown): string;
|
|
10
|
+
declare function extractTitle(html: string): string;
|
|
11
|
+
declare function extractAllLandmarks(html: string): Array<{
|
|
12
|
+
tag: string;
|
|
13
|
+
text: string;
|
|
14
|
+
}>;
|
|
15
|
+
declare function extractLandmarks(html: string): WebLandmark[];
|
|
16
|
+
declare function normalizeNetworkEntry(entry: {
|
|
17
|
+
method?: string;
|
|
18
|
+
pathPattern?: string;
|
|
19
|
+
path?: string;
|
|
20
|
+
status?: number;
|
|
21
|
+
contentType?: string;
|
|
22
|
+
jsonSchema?: JsonSchema;
|
|
23
|
+
}): WebNetworkExpectation;
|
|
24
|
+
export declare function ingest(options?: WebIngestOptions, deps?: IngestDeps): Promise<IngestResult>;
|
|
25
|
+
export { stripTags, extractTitle, extractLandmarks, extractAllLandmarks, normalizeNetworkEntry };
|