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