visual-ai-assertions 0.8.0 → 0.10.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/README.md +55 -12
- package/dist/index.cjs +629 -51
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +176 -25
- package/dist/index.d.ts +176 -25
- package/dist/index.js +628 -51
- package/dist/index.js.map +1 -1
- package/package.json +40 -12
package/dist/index.js
CHANGED
|
@@ -115,6 +115,12 @@ var VisualAIImageError = class extends VisualAIError {
|
|
|
115
115
|
this.name = "VisualAIImageError";
|
|
116
116
|
}
|
|
117
117
|
};
|
|
118
|
+
var VisualAIVideoError = class extends VisualAIError {
|
|
119
|
+
constructor(message) {
|
|
120
|
+
super(message, "VIDEO_INVALID");
|
|
121
|
+
this.name = "VisualAIVideoError";
|
|
122
|
+
}
|
|
123
|
+
};
|
|
118
124
|
var VisualAIResponseParseError = class extends VisualAIError {
|
|
119
125
|
rawResponse;
|
|
120
126
|
constructor(message, rawResponse) {
|
|
@@ -148,7 +154,7 @@ var VisualAIAssertionError = class extends VisualAIError {
|
|
|
148
154
|
}
|
|
149
155
|
};
|
|
150
156
|
function isVisualAIKnownError(error) {
|
|
151
|
-
return error instanceof VisualAIAuthError || error instanceof VisualAIRateLimitError || error instanceof VisualAIProviderError || error instanceof VisualAIImageError || error instanceof VisualAIResponseParseError || error instanceof VisualAITruncationError || error instanceof VisualAIConfigError || error instanceof VisualAIAssertionError;
|
|
157
|
+
return error instanceof VisualAIAuthError || error instanceof VisualAIRateLimitError || error instanceof VisualAIProviderError || error instanceof VisualAIImageError || error instanceof VisualAIVideoError || error instanceof VisualAIResponseParseError || error instanceof VisualAITruncationError || error instanceof VisualAIConfigError || error instanceof VisualAIAssertionError;
|
|
152
158
|
}
|
|
153
159
|
|
|
154
160
|
// src/core/prompt.ts
|
|
@@ -162,7 +168,7 @@ Each issue must have:
|
|
|
162
168
|
- "description": what the issue is
|
|
163
169
|
- "suggestion": how to fix or improve it
|
|
164
170
|
`;
|
|
165
|
-
var
|
|
171
|
+
var CHECK_OUTPUT_SCHEMA_IMAGE = `IMPORTANT: Follow this evaluation order:
|
|
166
172
|
1. First, evaluate EACH statement independently and populate the "statements" array
|
|
167
173
|
2. Then, set "pass" to true ONLY if every statement passed (logical AND of all statement results)
|
|
168
174
|
3. Write "reasoning" as a brief overall summary of the evaluation
|
|
@@ -202,7 +208,46 @@ Example for a failing check:
|
|
|
202
208
|
]
|
|
203
209
|
}
|
|
204
210
|
${JSON_INSTRUCTIONS}`;
|
|
205
|
-
var
|
|
211
|
+
var CHECK_OUTPUT_SCHEMA_VIDEO = `IMPORTANT: Follow this evaluation order:
|
|
212
|
+
1. First, evaluate EACH statement independently across the entire timeline and populate the "statements" array
|
|
213
|
+
2. A statement passes if it is true at ANY frame of the timeline, unless the wording explicitly says otherwise (e.g. "throughout", "at all times")
|
|
214
|
+
3. For each statement that passes, set "timestampSeconds" to the timestamp of the frame that most clearly demonstrates it (or where it first becomes true). Use null when the statement fails or applies across the whole clip.
|
|
215
|
+
4. Then, set "pass" to true ONLY if every statement passed (logical AND of all statement results)
|
|
216
|
+
5. Write "reasoning" as a brief overall summary of the evaluation
|
|
217
|
+
6. Include "issues" only for statements that failed
|
|
218
|
+
|
|
219
|
+
Respond with a JSON object matching this exact structure:
|
|
220
|
+
{
|
|
221
|
+
"pass": boolean, // true ONLY if ALL statements passed \u2014 derive from statements array
|
|
222
|
+
"reasoning": string, // brief overall summary of the evaluation
|
|
223
|
+
"issues": [...], // one issue per failing statement (empty if all pass)
|
|
224
|
+
"statements": [ // one entry per statement, in order \u2014 evaluate these FIRST
|
|
225
|
+
{
|
|
226
|
+
"statement": string, // the original statement text
|
|
227
|
+
"pass": boolean, // whether this statement is true at any point in the timeline
|
|
228
|
+
"reasoning": string, // explanation for this statement, citing frame timestamps where relevant
|
|
229
|
+
"confidence": "high" | "medium" | "low",
|
|
230
|
+
"timestampSeconds": number | null
|
|
231
|
+
// seconds from the start of the clip where the statement is most clearly true,
|
|
232
|
+
// or null if it failed / applies across the whole clip
|
|
233
|
+
}
|
|
234
|
+
]
|
|
235
|
+
}
|
|
236
|
+
${ISSUE_SCHEMA_INSTRUCTIONS}
|
|
237
|
+
|
|
238
|
+
Only include issues for statements that fail. If all statements pass, issues should be an empty array.
|
|
239
|
+
|
|
240
|
+
Example for a passing video check:
|
|
241
|
+
{
|
|
242
|
+
"pass": true,
|
|
243
|
+
"reasoning": "The success toast appeared briefly around 3.5s.",
|
|
244
|
+
"issues": [],
|
|
245
|
+
"statements": [
|
|
246
|
+
{ "statement": "A success toast with text 'Saved' appears", "pass": true, "reasoning": "A green toast labeled 'Saved' is visible in the bottom-right at the 3.5s frame", "confidence": "high", "timestampSeconds": 3.5 }
|
|
247
|
+
]
|
|
248
|
+
}
|
|
249
|
+
${JSON_INSTRUCTIONS}`;
|
|
250
|
+
var ASK_OUTPUT_SCHEMA_IMAGE = `Respond with a JSON object matching this exact structure:
|
|
206
251
|
{
|
|
207
252
|
"summary": string, // high-level analysis summary
|
|
208
253
|
"issues": [...] // list of issues/findings, can be empty
|
|
@@ -223,6 +268,17 @@ Example:
|
|
|
223
268
|
]
|
|
224
269
|
}
|
|
225
270
|
${JSON_INSTRUCTIONS}`;
|
|
271
|
+
var ASK_OUTPUT_SCHEMA_VIDEO = `Respond with a JSON object matching this exact structure:
|
|
272
|
+
{
|
|
273
|
+
"summary": string, // high-level summary of what happens across the timeline
|
|
274
|
+
"issues": [...], // list of issues/findings, can be empty
|
|
275
|
+
"frameReferences": number[] // 0-based indices of frames the answer relies on (in order)
|
|
276
|
+
}
|
|
277
|
+
${ISSUE_SCHEMA_INSTRUCTIONS}
|
|
278
|
+
|
|
279
|
+
Prioritize issues by severity (critical / major / minor) as for image input.
|
|
280
|
+
Cite frame indices in "frameReferences" so the user can locate the moments you describe.
|
|
281
|
+
${JSON_INSTRUCTIONS}`;
|
|
226
282
|
var COMPARE_OUTPUT_SCHEMA = `Respond with a JSON object matching this exact structure:
|
|
227
283
|
{
|
|
228
284
|
"pass": boolean, // true if no critical or major changes found
|
|
@@ -241,7 +297,19 @@ var COMPARE_OUTPUT_SCHEMA = `Respond with a JSON object matching this exact stru
|
|
|
241
297
|
If the images appear identical, set pass to true, explain in reasoning, and return an empty changes array.
|
|
242
298
|
${JSON_INSTRUCTIONS}`;
|
|
243
299
|
var DEFAULT_CHECK_ROLE = "You are a visual QA assistant. Evaluate the provided image precisely and objectively.";
|
|
300
|
+
var DEFAULT_CHECK_ROLE_VIDEO = "You are a visual QA assistant. Evaluate the provided sequence of video frames precisely and objectively, treating them as a chronological timeline.";
|
|
244
301
|
var DEFAULT_ASK_ROLE = "You are a visual QA assistant. Analyze the provided image based on the user's request.";
|
|
302
|
+
var DEFAULT_ASK_ROLE_VIDEO = "You are a visual QA assistant. Analyze the provided sequence of video frames as a chronological timeline based on the user's request.";
|
|
303
|
+
function buildVideoTimelineSection(frameTimestamps, durationSeconds) {
|
|
304
|
+
const formatted = frameTimestamps.map((t, i) => ` ${i}: ${t.toFixed(2)}s`).join("\n");
|
|
305
|
+
return `Video timeline:
|
|
306
|
+
- Total duration: ${durationSeconds.toFixed(2)}s
|
|
307
|
+
- ${frameTimestamps.length} frames sampled (in chronological order)
|
|
308
|
+
- Frame index \u2192 timestamp:
|
|
309
|
+
${formatted}
|
|
310
|
+
|
|
311
|
+
Treat the attached images as a chronological timeline. The first image is the earliest frame, the last is the latest. Refer to frames by timestamp where helpful.`;
|
|
312
|
+
}
|
|
245
313
|
var COMPARE_ROLE = "You are performing a visual regression test. Compare the BEFORE image (baseline) to the AFTER image (current) and identify all visual differences. Flag changes that appear unintentional or problematic.";
|
|
246
314
|
var COMPARE_EDGE_RULES = [
|
|
247
315
|
"The BEFORE image is the baseline/expected state.",
|
|
@@ -254,22 +322,31 @@ function buildInstructionsSection(instructions) {
|
|
|
254
322
|
function buildCheckPrompt(statements, options) {
|
|
255
323
|
const stmts = Array.isArray(statements) ? statements : [statements];
|
|
256
324
|
const statementsBlock = stmts.map((s, i) => `${i + 1}. "${s}"`).join("\n");
|
|
257
|
-
const
|
|
325
|
+
const media = options?.media;
|
|
326
|
+
const defaultRole = media?.kind === "video" ? DEFAULT_CHECK_ROLE_VIDEO : DEFAULT_CHECK_ROLE;
|
|
327
|
+
const sections = [options?.role ?? defaultRole];
|
|
328
|
+
if (media?.kind === "video") {
|
|
329
|
+
sections.push(buildVideoTimelineSection(media.frameTimestamps, media.durationSeconds));
|
|
330
|
+
}
|
|
258
331
|
if (options?.instructions && options.instructions.length > 0) {
|
|
259
332
|
sections.push(buildInstructionsSection(options.instructions));
|
|
260
333
|
}
|
|
261
334
|
sections.push(`Statements to evaluate:
|
|
262
335
|
${statementsBlock}`);
|
|
263
|
-
sections.push(
|
|
336
|
+
sections.push(media?.kind === "video" ? CHECK_OUTPUT_SCHEMA_VIDEO : CHECK_OUTPUT_SCHEMA_IMAGE);
|
|
264
337
|
return sections.join("\n\n");
|
|
265
338
|
}
|
|
266
339
|
function buildAskPrompt(userPrompt, options) {
|
|
267
|
-
const
|
|
340
|
+
const media = options?.media;
|
|
341
|
+
const sections = [media?.kind === "video" ? DEFAULT_ASK_ROLE_VIDEO : DEFAULT_ASK_ROLE];
|
|
342
|
+
if (media?.kind === "video") {
|
|
343
|
+
sections.push(buildVideoTimelineSection(media.frameTimestamps, media.durationSeconds));
|
|
344
|
+
}
|
|
268
345
|
if (options?.instructions && options.instructions.length > 0) {
|
|
269
346
|
sections.push(buildInstructionsSection(options.instructions));
|
|
270
347
|
}
|
|
271
348
|
sections.push(`User request: ${userPrompt}`);
|
|
272
|
-
sections.push(
|
|
349
|
+
sections.push(media?.kind === "video" ? ASK_OUTPUT_SCHEMA_VIDEO : ASK_OUTPUT_SCHEMA_IMAGE);
|
|
273
350
|
return sections.join("\n\n");
|
|
274
351
|
}
|
|
275
352
|
function buildAiDiffPrompt() {
|
|
@@ -964,6 +1041,51 @@ async function generateAiDiff(imgA, imgB, model, driver) {
|
|
|
964
1041
|
import { readFile } from "fs/promises";
|
|
965
1042
|
import { extname } from "path";
|
|
966
1043
|
import sharp2 from "sharp";
|
|
1044
|
+
|
|
1045
|
+
// src/core/input-detect.ts
|
|
1046
|
+
function isFilePath(input) {
|
|
1047
|
+
return input.startsWith("/") || input.startsWith("./") || input.startsWith("../") || input.includes("\\");
|
|
1048
|
+
}
|
|
1049
|
+
function isUrl(input) {
|
|
1050
|
+
return input.startsWith("http://") || input.startsWith("https://");
|
|
1051
|
+
}
|
|
1052
|
+
function isDataUrl(input) {
|
|
1053
|
+
return input.startsWith("data:");
|
|
1054
|
+
}
|
|
1055
|
+
function parseDataUrl(input) {
|
|
1056
|
+
const match = /^data:([^;]+);base64,(.+)$/.exec(input);
|
|
1057
|
+
if (!match?.[1] || !match[2]) return null;
|
|
1058
|
+
return { mimeType: match[1], base64Payload: match[2] };
|
|
1059
|
+
}
|
|
1060
|
+
function decodeBase64(payload) {
|
|
1061
|
+
if (!/^[A-Za-z0-9+/\n\r]+=*$/.test(payload)) {
|
|
1062
|
+
throw new Error("Invalid base64 string");
|
|
1063
|
+
}
|
|
1064
|
+
return Buffer.from(payload, "base64");
|
|
1065
|
+
}
|
|
1066
|
+
function looksLikeImageBase64(input) {
|
|
1067
|
+
return input.startsWith("iVBOR") || // PNG (0x89 0x50 0x4E 0x47)
|
|
1068
|
+
input.startsWith("/9j/") || // JPEG (0xFF 0xD8 0xFF)
|
|
1069
|
+
input.startsWith("R0lGOD") || // GIF (0x47 0x49 0x46)
|
|
1070
|
+
input.startsWith("UklGR");
|
|
1071
|
+
}
|
|
1072
|
+
function looksLikeVideoBase64(input) {
|
|
1073
|
+
return input.startsWith("GkXf") || input.startsWith("AAAA");
|
|
1074
|
+
}
|
|
1075
|
+
async function fetchToBuffer(url, timeoutMs) {
|
|
1076
|
+
const response = await fetch(url, {
|
|
1077
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
1078
|
+
});
|
|
1079
|
+
if (!response.ok) {
|
|
1080
|
+
throw new Error(`HTTP ${response.status}`);
|
|
1081
|
+
}
|
|
1082
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
1083
|
+
const data = Buffer.from(arrayBuffer);
|
|
1084
|
+
const contentType = response.headers.get("content-type")?.split(";")[0]?.trim() ?? null;
|
|
1085
|
+
return { data, contentType };
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
// src/core/image.ts
|
|
967
1089
|
var SUPPORTED_FORMATS = /* @__PURE__ */ new Set([
|
|
968
1090
|
"image/jpeg",
|
|
969
1091
|
"image/png",
|
|
@@ -986,18 +1108,6 @@ function getMimeFromExtension(filePath) {
|
|
|
986
1108
|
const ext = extname(filePath).toLowerCase();
|
|
987
1109
|
return EXTENSION_TO_MIME[ext];
|
|
988
1110
|
}
|
|
989
|
-
function isFilePath(input) {
|
|
990
|
-
return input.startsWith("/") || input.startsWith("./") || input.startsWith("../") || input.includes("\\");
|
|
991
|
-
}
|
|
992
|
-
function isUrl(input) {
|
|
993
|
-
return input.startsWith("http://") || input.startsWith("https://");
|
|
994
|
-
}
|
|
995
|
-
function isBase64Image(input) {
|
|
996
|
-
return input.startsWith("iVBOR") || // PNG (0x89 0x50 0x4E 0x47)
|
|
997
|
-
input.startsWith("/9j/") || // JPEG (0xFF 0xD8 0xFF)
|
|
998
|
-
input.startsWith("R0lGOD") || // GIF (0x47 0x49 0x46)
|
|
999
|
-
input.startsWith("UklGR");
|
|
1000
|
-
}
|
|
1001
1111
|
function detectMimeType(data) {
|
|
1002
1112
|
if (data[0] === 255 && data[1] === 216 && data[2] === 255) {
|
|
1003
1113
|
return "image/jpeg";
|
|
@@ -1051,45 +1161,38 @@ async function loadFromFilePath(filePath) {
|
|
|
1051
1161
|
return { data: fileData, mimeType };
|
|
1052
1162
|
}
|
|
1053
1163
|
async function loadFromUrl(url) {
|
|
1054
|
-
let
|
|
1164
|
+
let result;
|
|
1055
1165
|
try {
|
|
1056
|
-
|
|
1057
|
-
signal: AbortSignal.timeout(URL_FETCH_TIMEOUT_MS)
|
|
1058
|
-
});
|
|
1166
|
+
result = await fetchToBuffer(url, URL_FETCH_TIMEOUT_MS);
|
|
1059
1167
|
} catch (err) {
|
|
1060
1168
|
throw new VisualAIImageError(
|
|
1061
1169
|
`Failed to fetch image from URL: ${url} \u2014 ${err instanceof Error ? err.message : String(err)}`
|
|
1062
1170
|
);
|
|
1063
1171
|
}
|
|
1064
|
-
|
|
1065
|
-
throw new VisualAIImageError(
|
|
1066
|
-
`Failed to fetch image from URL: ${url} \u2014 HTTP ${response.status}`
|
|
1067
|
-
);
|
|
1068
|
-
}
|
|
1069
|
-
const arrayBuffer = await response.arrayBuffer();
|
|
1070
|
-
const data = Buffer.from(arrayBuffer);
|
|
1071
|
-
const contentType = response.headers.get("content-type")?.split(";")[0]?.trim() ?? null;
|
|
1172
|
+
const { data, contentType } = result;
|
|
1072
1173
|
const mimeType = contentType && isSupportedMimeType(contentType) ? contentType : detectMimeType(data);
|
|
1073
1174
|
return { data, mimeType };
|
|
1074
1175
|
}
|
|
1075
1176
|
function loadFromBase64(input) {
|
|
1076
1177
|
let base64Data = input;
|
|
1077
1178
|
let mimeType;
|
|
1078
|
-
if (input
|
|
1079
|
-
const
|
|
1080
|
-
if (!
|
|
1179
|
+
if (isDataUrl(input)) {
|
|
1180
|
+
const parsed = parseDataUrl(input);
|
|
1181
|
+
if (!parsed) {
|
|
1081
1182
|
throw new VisualAIImageError("Invalid data URL format");
|
|
1082
1183
|
}
|
|
1083
|
-
if (!isSupportedMimeType(
|
|
1084
|
-
throw new VisualAIImageError(`Unsupported image format: ${
|
|
1184
|
+
if (!isSupportedMimeType(parsed.mimeType)) {
|
|
1185
|
+
throw new VisualAIImageError(`Unsupported image format: ${parsed.mimeType}`);
|
|
1085
1186
|
}
|
|
1086
|
-
mimeType =
|
|
1087
|
-
base64Data =
|
|
1187
|
+
mimeType = parsed.mimeType;
|
|
1188
|
+
base64Data = parsed.base64Payload;
|
|
1088
1189
|
}
|
|
1089
|
-
|
|
1190
|
+
let data;
|
|
1191
|
+
try {
|
|
1192
|
+
data = decodeBase64(base64Data);
|
|
1193
|
+
} catch {
|
|
1090
1194
|
throw new VisualAIImageError("Invalid base64 string");
|
|
1091
1195
|
}
|
|
1092
|
-
const data = Buffer.from(base64Data, "base64");
|
|
1093
1196
|
if (data.length === 0) {
|
|
1094
1197
|
throw new VisualAIImageError("Empty image data after base64 decode");
|
|
1095
1198
|
}
|
|
@@ -1108,9 +1211,9 @@ async function normalizeImage(input) {
|
|
|
1108
1211
|
} else if (typeof input === "string") {
|
|
1109
1212
|
if (isUrl(input)) {
|
|
1110
1213
|
({ data, mimeType } = await loadFromUrl(input));
|
|
1111
|
-
} else if (input
|
|
1214
|
+
} else if (isDataUrl(input)) {
|
|
1112
1215
|
({ data, mimeType } = loadFromBase64(input));
|
|
1113
|
-
} else if (
|
|
1216
|
+
} else if (looksLikeImageBase64(input)) {
|
|
1114
1217
|
({ data, mimeType } = loadFromBase64(input));
|
|
1115
1218
|
} else if (isFilePath(input)) {
|
|
1116
1219
|
({ data, mimeType } = await loadFromFilePath(input));
|
|
@@ -1138,6 +1241,435 @@ async function normalizeImage(input) {
|
|
|
1138
1241
|
};
|
|
1139
1242
|
}
|
|
1140
1243
|
|
|
1244
|
+
// src/core/debug-frames.ts
|
|
1245
|
+
import { randomBytes } from "crypto";
|
|
1246
|
+
import { mkdir, writeFile } from "fs/promises";
|
|
1247
|
+
import { join, resolve } from "path";
|
|
1248
|
+
var DEBUG_FRAMES_ENV = "VISUAL_AI_DEBUG_FRAMES";
|
|
1249
|
+
var DEBUG_FRAMES_DIR_ENV = "VISUAL_AI_DEBUG_FRAMES_DIR";
|
|
1250
|
+
var DEFAULT_DIR_NAME = "visual-ai-debug-frames";
|
|
1251
|
+
function isEnabled(env) {
|
|
1252
|
+
const raw = env[DEBUG_FRAMES_ENV];
|
|
1253
|
+
if (raw === void 0 || raw === "") return false;
|
|
1254
|
+
const lower = raw.toLowerCase();
|
|
1255
|
+
return lower === "true" || lower === "1";
|
|
1256
|
+
}
|
|
1257
|
+
function timestampSlug(date) {
|
|
1258
|
+
return date.toISOString().replace(/[:.]/g, "-");
|
|
1259
|
+
}
|
|
1260
|
+
function paddedIndex(value, total) {
|
|
1261
|
+
const width = Math.max(2, String(total - 1).length);
|
|
1262
|
+
return String(value).padStart(width, "0");
|
|
1263
|
+
}
|
|
1264
|
+
function extensionFromMimeType(mimeType) {
|
|
1265
|
+
if (mimeType === "image/png") return ".png";
|
|
1266
|
+
if (mimeType === "image/webp") return ".webp";
|
|
1267
|
+
return ".jpg";
|
|
1268
|
+
}
|
|
1269
|
+
async function saveDebugFrames(frames, env = process.env) {
|
|
1270
|
+
if (!isEnabled(env)) return void 0;
|
|
1271
|
+
if (frames.length === 0) return void 0;
|
|
1272
|
+
const baseDir = env[DEBUG_FRAMES_DIR_ENV]?.trim() || DEFAULT_DIR_NAME;
|
|
1273
|
+
const runDir = resolve(baseDir, `${timestampSlug(/* @__PURE__ */ new Date())}-${randomBytes(3).toString("hex")}`);
|
|
1274
|
+
try {
|
|
1275
|
+
await mkdir(runDir, { recursive: true });
|
|
1276
|
+
await Promise.all(
|
|
1277
|
+
frames.map((frame) => {
|
|
1278
|
+
const idx = paddedIndex(frame.index, frames.length);
|
|
1279
|
+
const ts = frame.timestampSeconds.toFixed(2);
|
|
1280
|
+
const ext = extensionFromMimeType(frame.mimeType);
|
|
1281
|
+
const filename = `frame-${idx}-t${ts}s${ext}`;
|
|
1282
|
+
return writeFile(join(runDir, filename), frame.data);
|
|
1283
|
+
})
|
|
1284
|
+
);
|
|
1285
|
+
} catch (err) {
|
|
1286
|
+
process.stderr.write(
|
|
1287
|
+
`[visual-ai-assertions] warning: failed to save debug frames to ${runDir}: ${err instanceof Error ? err.message : String(err)}
|
|
1288
|
+
`
|
|
1289
|
+
);
|
|
1290
|
+
return void 0;
|
|
1291
|
+
}
|
|
1292
|
+
process.stderr.write(
|
|
1293
|
+
`[visual-ai-assertions] Saved ${frames.length} debug frame(s) to ${runDir}
|
|
1294
|
+
`
|
|
1295
|
+
);
|
|
1296
|
+
return runDir;
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
// src/core/video.ts
|
|
1300
|
+
import { mkdtemp, readFile as readFile2, readdir, rm, writeFile as writeFile2 } from "fs/promises";
|
|
1301
|
+
import { tmpdir } from "os";
|
|
1302
|
+
import { extname as extname2, join as join2 } from "path";
|
|
1303
|
+
var FRAME_MAX_DIMENSION = 1568;
|
|
1304
|
+
var DEFAULT_FPS = 1;
|
|
1305
|
+
var DEFAULT_MAX_FRAMES = 10;
|
|
1306
|
+
var DEFAULT_MAX_DURATION_SECONDS = 10;
|
|
1307
|
+
var MAX_FRAMES_HARD_CAP = 60;
|
|
1308
|
+
var FFPROBE_TIMEOUT_MS = 15e3;
|
|
1309
|
+
var FFMPEG_RUN_TIMEOUT_MS = 6e4;
|
|
1310
|
+
var VIDEO_EXTENSIONS = {
|
|
1311
|
+
".mp4": "video/mp4",
|
|
1312
|
+
".m4v": "video/mp4",
|
|
1313
|
+
".webm": "video/webm",
|
|
1314
|
+
".mov": "video/quicktime",
|
|
1315
|
+
".qt": "video/quicktime",
|
|
1316
|
+
".mkv": "video/x-matroska"
|
|
1317
|
+
};
|
|
1318
|
+
var VIDEO_MIME_TYPES = /* @__PURE__ */ new Set([
|
|
1319
|
+
"video/mp4",
|
|
1320
|
+
"video/webm",
|
|
1321
|
+
"video/quicktime",
|
|
1322
|
+
"video/x-matroska"
|
|
1323
|
+
]);
|
|
1324
|
+
function isSupportedVideoMimeType(value) {
|
|
1325
|
+
return VIDEO_MIME_TYPES.has(value);
|
|
1326
|
+
}
|
|
1327
|
+
function getVideoMimeFromExtension(filePath) {
|
|
1328
|
+
const ext = extname2(filePath).toLowerCase();
|
|
1329
|
+
return VIDEO_EXTENSIONS[ext];
|
|
1330
|
+
}
|
|
1331
|
+
function detectVideoMimeType(data) {
|
|
1332
|
+
if (data.length < 12) return null;
|
|
1333
|
+
if (data[4] === 102 && data[5] === 116 && data[6] === 121 && data[7] === 112) {
|
|
1334
|
+
if (data[8] === 113 && data[9] === 116 && data[10] === 32 && data[11] === 32) {
|
|
1335
|
+
return "video/quicktime";
|
|
1336
|
+
}
|
|
1337
|
+
return "video/mp4";
|
|
1338
|
+
}
|
|
1339
|
+
if (data[0] === 26 && data[1] === 69 && data[2] === 223 && data[3] === 163) {
|
|
1340
|
+
return "video/webm";
|
|
1341
|
+
}
|
|
1342
|
+
return null;
|
|
1343
|
+
}
|
|
1344
|
+
async function resolveVideoToPath(input) {
|
|
1345
|
+
if (Buffer.isBuffer(input) || input instanceof Uint8Array) {
|
|
1346
|
+
const buf2 = Buffer.isBuffer(input) ? input : Buffer.from(input);
|
|
1347
|
+
const mimeType2 = detectVideoMimeType(buf2);
|
|
1348
|
+
if (!mimeType2) {
|
|
1349
|
+
throw new VisualAIVideoError("Unable to detect video format from buffer contents");
|
|
1350
|
+
}
|
|
1351
|
+
return writeBufferToTemp(buf2, mimeType2);
|
|
1352
|
+
}
|
|
1353
|
+
if (typeof input !== "string") {
|
|
1354
|
+
throw new VisualAIVideoError(
|
|
1355
|
+
"Invalid video input: expected Buffer, Uint8Array, file path, data URL, or base64 string"
|
|
1356
|
+
);
|
|
1357
|
+
}
|
|
1358
|
+
if (isDataUrl(input)) {
|
|
1359
|
+
const parsed = parseDataUrl(input);
|
|
1360
|
+
if (!parsed) {
|
|
1361
|
+
throw new VisualAIVideoError("Invalid data URL format");
|
|
1362
|
+
}
|
|
1363
|
+
if (!isSupportedVideoMimeType(parsed.mimeType)) {
|
|
1364
|
+
throw new VisualAIVideoError(`Unsupported video format: ${parsed.mimeType}`);
|
|
1365
|
+
}
|
|
1366
|
+
let buf2;
|
|
1367
|
+
try {
|
|
1368
|
+
buf2 = decodeBase64(parsed.base64Payload);
|
|
1369
|
+
} catch {
|
|
1370
|
+
throw new VisualAIVideoError("Invalid base64 payload in data URL");
|
|
1371
|
+
}
|
|
1372
|
+
return writeBufferToTemp(buf2, parsed.mimeType);
|
|
1373
|
+
}
|
|
1374
|
+
if (isFilePath(input)) {
|
|
1375
|
+
const mimeType2 = getVideoMimeFromExtension(input);
|
|
1376
|
+
if (!mimeType2) {
|
|
1377
|
+
throw new VisualAIVideoError(
|
|
1378
|
+
`Unsupported video file extension: ${input}. Supported: .mp4, .webm, .mov, .mkv`
|
|
1379
|
+
);
|
|
1380
|
+
}
|
|
1381
|
+
return { path: input, mimeType: mimeType2, cleanup: async () => {
|
|
1382
|
+
} };
|
|
1383
|
+
}
|
|
1384
|
+
let buf;
|
|
1385
|
+
try {
|
|
1386
|
+
buf = decodeBase64(input);
|
|
1387
|
+
} catch {
|
|
1388
|
+
throw new VisualAIVideoError(
|
|
1389
|
+
`Unrecognized video input: "${input.slice(0, 80)}". Expected a file path, data URL, or base64-encoded video string.`
|
|
1390
|
+
);
|
|
1391
|
+
}
|
|
1392
|
+
const mimeType = detectVideoMimeType(buf);
|
|
1393
|
+
if (!mimeType) {
|
|
1394
|
+
throw new VisualAIVideoError(
|
|
1395
|
+
`Unrecognized video input: "${input.slice(0, 80)}". Expected a file path, data URL, or base64-encoded video string.`
|
|
1396
|
+
);
|
|
1397
|
+
}
|
|
1398
|
+
return writeBufferToTemp(buf, mimeType);
|
|
1399
|
+
}
|
|
1400
|
+
async function writeBufferToTemp(data, mimeType) {
|
|
1401
|
+
const dir = await mkdtemp(join2(tmpdir(), "visual-ai-video-"));
|
|
1402
|
+
try {
|
|
1403
|
+
const ext = extensionFor(mimeType);
|
|
1404
|
+
const path = join2(dir, `input${ext}`);
|
|
1405
|
+
await writeFile2(path, data);
|
|
1406
|
+
return {
|
|
1407
|
+
path,
|
|
1408
|
+
mimeType,
|
|
1409
|
+
cleanup: async () => {
|
|
1410
|
+
try {
|
|
1411
|
+
await rm(dir, { recursive: true, force: true });
|
|
1412
|
+
} catch {
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
};
|
|
1416
|
+
} catch (err) {
|
|
1417
|
+
try {
|
|
1418
|
+
await rm(dir, { recursive: true, force: true });
|
|
1419
|
+
} catch {
|
|
1420
|
+
}
|
|
1421
|
+
throw err;
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
function extensionFor(mimeType) {
|
|
1425
|
+
switch (mimeType) {
|
|
1426
|
+
case "video/mp4":
|
|
1427
|
+
return ".mp4";
|
|
1428
|
+
case "video/webm":
|
|
1429
|
+
return ".webm";
|
|
1430
|
+
case "video/quicktime":
|
|
1431
|
+
return ".mov";
|
|
1432
|
+
case "video/x-matroska":
|
|
1433
|
+
return ".mkv";
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
var cachedFactoryPromise;
|
|
1437
|
+
async function loadFfmpegFactory() {
|
|
1438
|
+
if (cachedFactoryPromise) return cachedFactoryPromise;
|
|
1439
|
+
cachedFactoryPromise = (async () => {
|
|
1440
|
+
let ffmpegModule;
|
|
1441
|
+
try {
|
|
1442
|
+
ffmpegModule = await import("fluent-ffmpeg");
|
|
1443
|
+
} catch (err) {
|
|
1444
|
+
const code = err?.code;
|
|
1445
|
+
if (code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND") {
|
|
1446
|
+
throw new VisualAIVideoError(
|
|
1447
|
+
"Could not load fluent-ffmpeg. It ships as a dependency of visual-ai-assertions, so this usually means the install was pruned or the platform-specific binary is unavailable. Reinstall the package or run: pnpm add fluent-ffmpeg @ffmpeg-installer/ffmpeg @ffprobe-installer/ffprobe"
|
|
1448
|
+
);
|
|
1449
|
+
}
|
|
1450
|
+
throw new VisualAIVideoError(
|
|
1451
|
+
`Failed to load fluent-ffmpeg: ${err instanceof Error ? err.message : String(err)}`
|
|
1452
|
+
);
|
|
1453
|
+
}
|
|
1454
|
+
const factory = ffmpegModule.default ?? ffmpegModule;
|
|
1455
|
+
try {
|
|
1456
|
+
const installer = await import("@ffmpeg-installer/ffmpeg");
|
|
1457
|
+
const path = (installer.default ?? installer).path;
|
|
1458
|
+
if (path) factory.setFfmpegPath(path);
|
|
1459
|
+
} catch (err) {
|
|
1460
|
+
const code = err?.code;
|
|
1461
|
+
if (code !== "ERR_MODULE_NOT_FOUND" && code !== "MODULE_NOT_FOUND") {
|
|
1462
|
+
process.stderr.write(
|
|
1463
|
+
`[visual-ai-assertions] warning: @ffmpeg-installer/ffmpeg failed to load: ${err instanceof Error ? err.message : String(err)}
|
|
1464
|
+
`
|
|
1465
|
+
);
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
try {
|
|
1469
|
+
const installer = await import("@ffprobe-installer/ffprobe");
|
|
1470
|
+
const path = (installer.default ?? installer).path;
|
|
1471
|
+
if (path) factory.setFfprobePath(path);
|
|
1472
|
+
} catch (err) {
|
|
1473
|
+
const code = err?.code;
|
|
1474
|
+
if (code !== "ERR_MODULE_NOT_FOUND" && code !== "MODULE_NOT_FOUND") {
|
|
1475
|
+
process.stderr.write(
|
|
1476
|
+
`[visual-ai-assertions] warning: @ffprobe-installer/ffprobe failed to load: ${err instanceof Error ? err.message : String(err)}
|
|
1477
|
+
`
|
|
1478
|
+
);
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
return factory;
|
|
1482
|
+
})();
|
|
1483
|
+
try {
|
|
1484
|
+
return await cachedFactoryPromise;
|
|
1485
|
+
} catch (err) {
|
|
1486
|
+
cachedFactoryPromise = void 0;
|
|
1487
|
+
throw err;
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
async function probeDurationSeconds(videoPath) {
|
|
1491
|
+
const ffmpeg = await loadFfmpegFactory();
|
|
1492
|
+
return new Promise((resolve2, reject) => {
|
|
1493
|
+
let settled = false;
|
|
1494
|
+
const finish = (fn) => {
|
|
1495
|
+
if (settled) return;
|
|
1496
|
+
settled = true;
|
|
1497
|
+
clearTimeout(timer);
|
|
1498
|
+
fn();
|
|
1499
|
+
};
|
|
1500
|
+
const timer = setTimeout(() => {
|
|
1501
|
+
finish(() => {
|
|
1502
|
+
reject(
|
|
1503
|
+
new VisualAIVideoError(
|
|
1504
|
+
`ffprobe timed out after ${FFPROBE_TIMEOUT_MS}ms while probing ${videoPath}`
|
|
1505
|
+
)
|
|
1506
|
+
);
|
|
1507
|
+
});
|
|
1508
|
+
}, FFPROBE_TIMEOUT_MS);
|
|
1509
|
+
ffmpeg.ffprobe(videoPath, (err, data) => {
|
|
1510
|
+
if (err) {
|
|
1511
|
+
finish(() => {
|
|
1512
|
+
reject(
|
|
1513
|
+
new VisualAIVideoError(
|
|
1514
|
+
`Failed to probe video metadata: ${err.message}. Ensure ffprobe is installed (e.g. via @ffprobe-installer/ffprobe).`
|
|
1515
|
+
)
|
|
1516
|
+
);
|
|
1517
|
+
});
|
|
1518
|
+
return;
|
|
1519
|
+
}
|
|
1520
|
+
const raw = data.format?.duration;
|
|
1521
|
+
const duration = typeof raw === "string" ? Number(raw) : raw;
|
|
1522
|
+
if (!duration || !Number.isFinite(duration) || duration <= 0) {
|
|
1523
|
+
finish(() => {
|
|
1524
|
+
reject(new VisualAIVideoError("Video duration could not be determined"));
|
|
1525
|
+
});
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1528
|
+
finish(() => {
|
|
1529
|
+
resolve2(duration);
|
|
1530
|
+
});
|
|
1531
|
+
});
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
async function extractFrames(videoPath, options = {}) {
|
|
1535
|
+
const fps = options.fps ?? DEFAULT_FPS;
|
|
1536
|
+
const maxFrames = options.maxFrames ?? DEFAULT_MAX_FRAMES;
|
|
1537
|
+
const maxDurationSeconds = options.maxDurationSeconds ?? DEFAULT_MAX_DURATION_SECONDS;
|
|
1538
|
+
if (!Number.isFinite(fps) || fps <= 0) {
|
|
1539
|
+
throw new VisualAIVideoError(`Invalid fps: ${fps}. Must be a finite number > 0.`);
|
|
1540
|
+
}
|
|
1541
|
+
if (!Number.isFinite(maxFrames) || maxFrames <= 0) {
|
|
1542
|
+
throw new VisualAIVideoError(`Invalid maxFrames: ${maxFrames}. Must be a finite number > 0.`);
|
|
1543
|
+
}
|
|
1544
|
+
if (maxFrames > MAX_FRAMES_HARD_CAP) {
|
|
1545
|
+
throw new VisualAIVideoError(
|
|
1546
|
+
`maxFrames ${maxFrames} exceeds the hard cap of ${MAX_FRAMES_HARD_CAP}. Lower maxFrames or open an issue if you need a larger limit.`
|
|
1547
|
+
);
|
|
1548
|
+
}
|
|
1549
|
+
if (!Number.isFinite(maxDurationSeconds) || maxDurationSeconds <= 0) {
|
|
1550
|
+
throw new VisualAIVideoError(
|
|
1551
|
+
`Invalid maxDurationSeconds: ${maxDurationSeconds}. Must be a finite number > 0.`
|
|
1552
|
+
);
|
|
1553
|
+
}
|
|
1554
|
+
const ffmpeg = await loadFfmpegFactory();
|
|
1555
|
+
const durationSeconds = await probeDurationSeconds(videoPath);
|
|
1556
|
+
if (durationSeconds > maxDurationSeconds) {
|
|
1557
|
+
throw new VisualAIVideoError(
|
|
1558
|
+
`Video duration ${durationSeconds.toFixed(2)}s exceeds limit of ${maxDurationSeconds}s. Pass { maxDurationSeconds: N } to override, or trim the source video.`
|
|
1559
|
+
);
|
|
1560
|
+
}
|
|
1561
|
+
const outputDir = await mkdtemp(join2(tmpdir(), "visual-ai-frames-"));
|
|
1562
|
+
try {
|
|
1563
|
+
const filter = `fps=${fps},scale='if(gt(iw,ih),min(${FRAME_MAX_DIMENSION},iw),-2)':'if(gt(iw,ih),-2,min(${FRAME_MAX_DIMENSION},ih))':flags=area`;
|
|
1564
|
+
await new Promise((resolve2, reject) => {
|
|
1565
|
+
let settled = false;
|
|
1566
|
+
const cmd = ffmpeg(videoPath);
|
|
1567
|
+
const finish = (fn) => {
|
|
1568
|
+
if (settled) return;
|
|
1569
|
+
settled = true;
|
|
1570
|
+
clearTimeout(timer);
|
|
1571
|
+
fn();
|
|
1572
|
+
};
|
|
1573
|
+
const timer = setTimeout(() => {
|
|
1574
|
+
try {
|
|
1575
|
+
cmd.kill("SIGKILL");
|
|
1576
|
+
} catch {
|
|
1577
|
+
}
|
|
1578
|
+
finish(() => {
|
|
1579
|
+
reject(
|
|
1580
|
+
new VisualAIVideoError(
|
|
1581
|
+
`ffmpeg frame extraction timed out after ${FFMPEG_RUN_TIMEOUT_MS}ms`
|
|
1582
|
+
)
|
|
1583
|
+
);
|
|
1584
|
+
});
|
|
1585
|
+
}, FFMPEG_RUN_TIMEOUT_MS);
|
|
1586
|
+
cmd.outputOptions(["-vf", filter, "-vframes", String(maxFrames), "-q:v", "3"]).output(join2(outputDir, "frame-%04d.jpg")).on("end", () => {
|
|
1587
|
+
finish(() => {
|
|
1588
|
+
resolve2();
|
|
1589
|
+
});
|
|
1590
|
+
}).on("error", (err) => {
|
|
1591
|
+
finish(() => {
|
|
1592
|
+
reject(new VisualAIVideoError(`ffmpeg frame extraction failed: ${err.message}`));
|
|
1593
|
+
});
|
|
1594
|
+
}).run();
|
|
1595
|
+
});
|
|
1596
|
+
const files = (await readdir(outputDir)).filter((name) => name.endsWith(".jpg")).sort();
|
|
1597
|
+
if (files.length === 0) {
|
|
1598
|
+
throw new VisualAIVideoError(
|
|
1599
|
+
"No frames could be extracted from the video. The source may be corrupt or empty."
|
|
1600
|
+
);
|
|
1601
|
+
}
|
|
1602
|
+
const frames = await Promise.all(
|
|
1603
|
+
files.map(async (name, index) => {
|
|
1604
|
+
const data = await readFile2(join2(outputDir, name));
|
|
1605
|
+
const timestampSeconds = Math.min(durationSeconds, (index + 0.5) / fps);
|
|
1606
|
+
let cachedBase64;
|
|
1607
|
+
return {
|
|
1608
|
+
data,
|
|
1609
|
+
mimeType: "image/jpeg",
|
|
1610
|
+
get base64() {
|
|
1611
|
+
if (cachedBase64 === void 0) {
|
|
1612
|
+
cachedBase64 = data.toString("base64");
|
|
1613
|
+
}
|
|
1614
|
+
return cachedBase64;
|
|
1615
|
+
},
|
|
1616
|
+
timestampSeconds,
|
|
1617
|
+
index
|
|
1618
|
+
};
|
|
1619
|
+
})
|
|
1620
|
+
);
|
|
1621
|
+
return { frames, durationSeconds };
|
|
1622
|
+
} finally {
|
|
1623
|
+
try {
|
|
1624
|
+
await rm(outputDir, { recursive: true, force: true });
|
|
1625
|
+
} catch {
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
// src/core/media.ts
|
|
1631
|
+
var VIDEO_MAGIC_BYTE_PREFIX_LEN = 16;
|
|
1632
|
+
function isVideoInput(input) {
|
|
1633
|
+
if (Buffer.isBuffer(input) || input instanceof Uint8Array) {
|
|
1634
|
+
const buf = Buffer.isBuffer(input) ? input : Buffer.from(input);
|
|
1635
|
+
return detectVideoMimeType(buf) !== null;
|
|
1636
|
+
}
|
|
1637
|
+
if (typeof input !== "string") return false;
|
|
1638
|
+
if (isDataUrl(input)) {
|
|
1639
|
+
const parsed = parseDataUrl(input);
|
|
1640
|
+
return parsed?.mimeType.startsWith("video/") ?? false;
|
|
1641
|
+
}
|
|
1642
|
+
if (isFilePath(input)) {
|
|
1643
|
+
return getVideoMimeFromExtension(input) !== void 0;
|
|
1644
|
+
}
|
|
1645
|
+
if (looksLikeVideoBase64(input)) {
|
|
1646
|
+
try {
|
|
1647
|
+
const buf = decodeBase64(input.slice(0, VIDEO_MAGIC_BYTE_PREFIX_LEN));
|
|
1648
|
+
return detectVideoMimeType(buf) !== null;
|
|
1649
|
+
} catch {
|
|
1650
|
+
return false;
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
return false;
|
|
1654
|
+
}
|
|
1655
|
+
async function normalizeMedia(input, videoOptions) {
|
|
1656
|
+
if (isVideoInput(input)) {
|
|
1657
|
+
const { path, cleanup } = await resolveVideoToPath(input);
|
|
1658
|
+
try {
|
|
1659
|
+
const { frames, durationSeconds } = await extractFrames(path, videoOptions);
|
|
1660
|
+
await saveDebugFrames(frames);
|
|
1661
|
+
return { kind: "video", frames, durationSeconds };
|
|
1662
|
+
} finally {
|
|
1663
|
+
try {
|
|
1664
|
+
await cleanup();
|
|
1665
|
+
} catch {
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
const image = await normalizeImage(input);
|
|
1670
|
+
return { kind: "image", image };
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1141
1673
|
// src/types.ts
|
|
1142
1674
|
import { z } from "zod";
|
|
1143
1675
|
var IssuePrioritySchema = z.enum(["critical", "major", "minor"]);
|
|
@@ -1162,7 +1694,13 @@ var StatementResultSchema = z.object({
|
|
|
1162
1694
|
statement: z.string(),
|
|
1163
1695
|
pass: z.boolean(),
|
|
1164
1696
|
reasoning: z.string(),
|
|
1165
|
-
confidence: ConfidenceSchema.optional()
|
|
1697
|
+
confidence: ConfidenceSchema.optional(),
|
|
1698
|
+
/**
|
|
1699
|
+
* For video inputs, the approximate timestamp (in seconds, from the start of the clip)
|
|
1700
|
+
* of the frame that most clearly demonstrates the statement. `null` when the statement
|
|
1701
|
+
* fails or applies across the whole clip. Always omitted for image inputs.
|
|
1702
|
+
*/
|
|
1703
|
+
timestampSeconds: z.number().nonnegative().nullable().optional()
|
|
1166
1704
|
});
|
|
1167
1705
|
var UsageInfoSchema = z.object({
|
|
1168
1706
|
inputTokens: z.number(),
|
|
@@ -1191,6 +1729,11 @@ var CompareResultSchema = BaseResultSchema.extend({
|
|
|
1191
1729
|
var AskResultSchema = z.object({
|
|
1192
1730
|
summary: z.string(),
|
|
1193
1731
|
issues: z.array(IssueSchema),
|
|
1732
|
+
/**
|
|
1733
|
+
* For video inputs, the indices of frames the model relied on to answer.
|
|
1734
|
+
* Indices are 0-based and refer to entries in `frames.timestampsSeconds`.
|
|
1735
|
+
*/
|
|
1736
|
+
frameReferences: z.array(z.number().int().nonnegative()).optional(),
|
|
1194
1737
|
usage: UsageInfoSchema.optional()
|
|
1195
1738
|
});
|
|
1196
1739
|
|
|
@@ -1266,6 +1809,29 @@ function createDriver(provider, config) {
|
|
|
1266
1809
|
var checkSchemaOptions = toSchemaOptions(CheckResponseSchema);
|
|
1267
1810
|
var askSchemaOptions = toSchemaOptions(AskResponseSchema);
|
|
1268
1811
|
var compareSchemaOptions = toSchemaOptions(CompareResponseSchema);
|
|
1812
|
+
function mediaToProviderInputs(media) {
|
|
1813
|
+
if (media.kind === "image") {
|
|
1814
|
+
return {
|
|
1815
|
+
images: [media.image],
|
|
1816
|
+
mediaContext: { kind: "image" },
|
|
1817
|
+
framesMetadata: void 0
|
|
1818
|
+
};
|
|
1819
|
+
}
|
|
1820
|
+
const timestamps = media.frames.map((f) => f.timestampSeconds);
|
|
1821
|
+
return {
|
|
1822
|
+
images: media.frames,
|
|
1823
|
+
mediaContext: {
|
|
1824
|
+
kind: "video",
|
|
1825
|
+
frameTimestamps: timestamps,
|
|
1826
|
+
durationSeconds: media.durationSeconds
|
|
1827
|
+
},
|
|
1828
|
+
framesMetadata: {
|
|
1829
|
+
count: media.frames.length,
|
|
1830
|
+
timestampsSeconds: timestamps,
|
|
1831
|
+
durationSeconds: media.durationSeconds
|
|
1832
|
+
}
|
|
1833
|
+
};
|
|
1834
|
+
}
|
|
1269
1835
|
function visualAI(config = {}) {
|
|
1270
1836
|
const resolvedConfig = resolveConfig(config);
|
|
1271
1837
|
const driverConfig = {
|
|
@@ -1294,34 +1860,44 @@ function visualAI(config = {}) {
|
|
|
1294
1860
|
});
|
|
1295
1861
|
}
|
|
1296
1862
|
return {
|
|
1297
|
-
async check(
|
|
1863
|
+
async check(input, statements, options) {
|
|
1298
1864
|
const stmts = Array.isArray(statements) ? statements : [statements];
|
|
1299
1865
|
if (stmts.length === 0) {
|
|
1300
1866
|
throw new VisualAIConfigError("At least one statement is required for check()");
|
|
1301
1867
|
}
|
|
1302
1868
|
return withErrorDebug(resolvedConfig, "check", async () => {
|
|
1303
|
-
const
|
|
1304
|
-
const
|
|
1869
|
+
const media = await normalizeMedia(input, options?.video);
|
|
1870
|
+
const { images, mediaContext, framesMetadata } = mediaToProviderInputs(media);
|
|
1871
|
+
const prompt = buildCheckPrompt(stmts, {
|
|
1872
|
+
instructions: options?.instructions,
|
|
1873
|
+
media: mediaContext
|
|
1874
|
+
});
|
|
1305
1875
|
debugLog(resolvedConfig, "check prompt", prompt, "prompt");
|
|
1306
|
-
const response = await timedSendMessage(driver,
|
|
1876
|
+
const response = await timedSendMessage(driver, images, prompt, checkSchemaOptions);
|
|
1307
1877
|
debugLog(resolvedConfig, "check response", response.text, "response");
|
|
1308
1878
|
const result = parseCheckResponse(response.text);
|
|
1309
1879
|
return {
|
|
1310
1880
|
...result,
|
|
1881
|
+
...framesMetadata ? { frames: framesMetadata } : {},
|
|
1311
1882
|
usage: processUsage("check", response.usage, response.durationSeconds, resolvedConfig)
|
|
1312
1883
|
};
|
|
1313
1884
|
});
|
|
1314
1885
|
},
|
|
1315
|
-
async ask(
|
|
1886
|
+
async ask(input, userPrompt, options) {
|
|
1316
1887
|
return withErrorDebug(resolvedConfig, "ask", async () => {
|
|
1317
|
-
const
|
|
1318
|
-
const
|
|
1888
|
+
const media = await normalizeMedia(input, options?.video);
|
|
1889
|
+
const { images, mediaContext, framesMetadata } = mediaToProviderInputs(media);
|
|
1890
|
+
const prompt = buildAskPrompt(userPrompt, {
|
|
1891
|
+
instructions: options?.instructions,
|
|
1892
|
+
media: mediaContext
|
|
1893
|
+
});
|
|
1319
1894
|
debugLog(resolvedConfig, "ask prompt", prompt, "prompt");
|
|
1320
|
-
const response = await timedSendMessage(driver,
|
|
1895
|
+
const response = await timedSendMessage(driver, images, prompt, askSchemaOptions);
|
|
1321
1896
|
debugLog(resolvedConfig, "ask response", response.text, "response");
|
|
1322
1897
|
const result = parseAskResponse(response.text);
|
|
1323
1898
|
return {
|
|
1324
1899
|
...result,
|
|
1900
|
+
...framesMetadata ? { frames: framesMetadata } : {},
|
|
1325
1901
|
usage: processUsage("ask", response.usage, response.durationSeconds, resolvedConfig)
|
|
1326
1902
|
};
|
|
1327
1903
|
});
|
|
@@ -1509,6 +2085,7 @@ export {
|
|
|
1509
2085
|
VisualAIRateLimitError,
|
|
1510
2086
|
VisualAIResponseParseError,
|
|
1511
2087
|
VisualAITruncationError,
|
|
2088
|
+
VisualAIVideoError,
|
|
1512
2089
|
assertVisualCompareResult,
|
|
1513
2090
|
assertVisualResult,
|
|
1514
2091
|
formatCheckResult,
|