@mizchi/vlmkit-ai 0.23.2 → 0.24.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.
@@ -1,7 +1,6 @@
1
1
  import { LLMProvider } from "./intent.mjs";
2
-
3
2
  //#region src/llm-client.d.ts
4
- interface LLMClientOptions {
3
+ export interface LLMClientOptions {
5
4
  /** Whether vision support is needed */
6
5
  vision?: boolean;
7
6
  /** Max tokens */
@@ -16,17 +15,17 @@ interface LLMClientOptions {
16
15
  */
17
16
  throwIfMissing?: boolean;
18
17
  }
19
- interface ImageContent {
18
+ export interface ImageContent {
20
19
  type: "image";
21
20
  base64: string;
22
21
  mimeType?: string;
23
22
  }
24
- interface TextContent {
23
+ export interface TextContent {
25
24
  type: "text";
26
25
  text: string;
27
26
  }
28
- type MessageContent = string | Array<TextContent | ImageContent>;
29
- interface LLMResponse {
27
+ export type MessageContent = string | Array<TextContent | ImageContent>;
28
+ export interface LLMResponse {
30
29
  content: string;
31
30
  model: string;
32
31
  provider: string;
@@ -35,7 +34,7 @@ interface LLMResponse {
35
34
  costUsd: number;
36
35
  latencyMs: number;
37
36
  }
38
- interface UnifiedLLMClient {
37
+ export interface UnifiedLLMClient {
39
38
  /** Text only (backwards-compatible) */
40
39
  complete(prompt: string): Promise<string>;
41
40
  /** Text + images */
@@ -54,7 +53,7 @@ interface UnifiedLLMClient {
54
53
  provider: string;
55
54
  model: string;
56
55
  }
57
- type LLMProviderName = "gemini" | "anthropic" | "openrouter";
56
+ export type LLMProviderName = "gemini" | "anthropic" | "openrouter";
58
57
  /**
59
58
  * The OpenAI model this project reaches for by default, and the one place its id is written.
60
59
  *
@@ -68,7 +67,7 @@ type LLMProviderName = "gemini" | "anthropic" | "openrouter";
68
67
  * the defect this constant came from was an agent reading a document and picking something the
69
68
  * code does not accept.
70
69
  */
71
- declare const OPENAI_DEFAULT_MODEL = "openai/gpt-5.6-luna";
70
+ export declare const OPENAI_DEFAULT_MODEL = "openai/gpt-5.6-luna";
72
71
  /**
73
72
  * Create a unified LLM client.
74
73
  *
@@ -79,8 +78,8 @@ declare const OPENAI_DEFAULT_MODEL = "openai/gpt-5.6-luna";
79
78
  * (`code: "INVALID_PROVIDER"`). Pass `{ throwIfMissing: false }` for
80
79
  * legacy `T | null` return.
81
80
  */
82
- declare function createUnifiedLLMClient(options?: LLMClientOptions): UnifiedLLMClient | null;
83
- interface CreateLLMProviderOptions {
81
+ export declare function createUnifiedLLMClient(options?: LLMClientOptions): UnifiedLLMClient | null;
82
+ export interface CreateLLMProviderOptions {
84
83
  /**
85
84
  * When `false`, returns `null` instead of throwing `VrtConfigError`
86
85
  * if no provider has an API key. Default: `true`.
@@ -96,6 +95,5 @@ interface CreateLLMProviderOptions {
96
95
  * provider in the fallback chain has an API key. Pass
97
96
  * `{ throwIfMissing: false }` for the legacy `T | null` return.
98
97
  */
99
- declare function createLLMProvider(options?: CreateLLMProviderOptions): LLMProvider | null;
100
- //#endregion
101
- export { CreateLLMProviderOptions, ImageContent, LLMClientOptions, LLMProviderName, LLMResponse, MessageContent, OPENAI_DEFAULT_MODEL, TextContent, UnifiedLLMClient, createLLMProvider, createUnifiedLLMClient };
98
+ export declare function createLLMProvider(options?: CreateLLMProviderOptions): LLMProvider | null;
99
+ //#endregion
@@ -41,12 +41,15 @@ function createAnthropicClient(apiKey, model) {
41
41
  }
42
42
  const data = await res.json();
43
43
  const latencyMs = Date.now() - start;
44
+ const text = data.content.filter((c) => c.type === "text").map((c) => c.text).join("");
45
+ const promptTokens = data.usage?.input_tokens ?? 0;
46
+ const completionTokens = data.usage?.output_tokens ?? 0;
44
47
  return {
45
- content: data.content.filter((c) => c.type === "text").map((c) => c.text).join(""),
48
+ content: text,
46
49
  model: modelId,
47
50
  provider: "anthropic",
48
- promptTokens: data.usage?.input_tokens ?? 0,
49
- completionTokens: data.usage?.output_tokens ?? 0,
51
+ promptTokens,
52
+ completionTokens,
50
53
  costUsd: 0,
51
54
  latencyMs
52
55
  };
@@ -130,7 +133,7 @@ function createOpenRouterLLMClient(apiKey, model) {
130
133
  method: "POST",
131
134
  headers: {
132
135
  "Content-Type": "application/json",
133
- "Authorization": `Bearer ${apiKey}`,
136
+ Authorization: `Bearer ${apiKey}`,
134
137
  "HTTP-Referer": "https://github.com/mizchi/vrt"
135
138
  },
136
139
  body: JSON.stringify({
@@ -211,7 +214,7 @@ function buildDiffContent(options) {
211
214
  });
212
215
  return parts;
213
216
  }
214
- const VALID_PROVIDERS = new Set([
217
+ const VALID_PROVIDERS = /* @__PURE__ */ new Set([
215
218
  "gemini",
216
219
  "anthropic",
217
220
  "openrouter"
@@ -0,0 +1,68 @@
1
+ import { JevClientOptions, JevRequest, JevResponse } from "./jev-client.mjs";
2
+ //#region src/locate.d.ts
3
+ export interface LocatedBox {
4
+ x: number;
5
+ y: number;
6
+ width: number;
7
+ height: number;
8
+ }
9
+ export interface LocateResult {
10
+ /** `presence >= presenceThreshold`, or always true with `presence: false`. */
11
+ found: boolean;
12
+ /** The `noul` "the screenshot shows …", 0-1. Null when presence was not asked. */
13
+ presence: number | null;
14
+ /** In the original image's pixels: the refined box when refined, else the first look's. */
15
+ box: LocatedBox;
16
+ /** The box's centre, where a click lands. */
17
+ point: {
18
+ x: number;
19
+ y: number;
20
+ };
21
+ /** The first look's box, in the original's pixels. */
22
+ firstBox: LocatedBox;
23
+ /** Whether `box` came from the second, magnified look. */
24
+ refined: boolean;
25
+ model: string;
26
+ calls: number;
27
+ costUsd: number;
28
+ }
29
+ export type JevAsk = <Q extends JevRequest["questions"]>(req: JevRequest<Q>) => Promise<JevResponse<Q>>;
30
+ export interface LocateOptions {
31
+ /** Ask presence first and report not-found below the threshold (default true). */
32
+ presence?: boolean;
33
+ /** Default 0.5: at it, 95% of real targets and 0% of decoys were accepted. */
34
+ presenceThreshold?: number;
35
+ /** Ask a second `box` on a magnified crop (default true). */
36
+ refine?: boolean;
37
+ model?: string;
38
+ /** Injected for tests; defaults to `askJev` with `client`. */
39
+ ask?: JevAsk;
40
+ client?: JevClientOptions;
41
+ }
42
+ type Win = {
43
+ x1: number;
44
+ y1: number;
45
+ x2: number;
46
+ y2: number;
47
+ };
48
+ /**
49
+ * The scale the whole screenshot is shown at: 1 when it already fits Jev's limits, smaller for a
50
+ * capture over 1568px (a 2x screenshot), larger for one under 280px. Null for a strip no scale
51
+ * fits (an edge ratio over 5.6).
52
+ */
53
+ export declare function firstLookScale(width: number, height: number): number | null;
54
+ /**
55
+ * The crop for the second look: the first box padded by its own size on each side (at least
56
+ * 16px), grown about its centre to 280px where the image allows, inside the image. The bench's
57
+ * window: padded 1x, the crop held the whole target 87% of the time from one look.
58
+ */
59
+ export declare function refineWindow(box: LocatedBox, image: {
60
+ width: number;
61
+ height: number;
62
+ }): Win;
63
+ export declare class LocateError extends Error {
64
+ constructor(message: string);
65
+ }
66
+ /** Locate `description` on a PNG screenshot. `description` names one thing: "the Save button". */
67
+ export declare function locateByDescription(png: Uint8Array, description: string, options?: LocateOptions): Promise<LocateResult>;
68
+ //#endregion
@@ -0,0 +1,159 @@
1
+ import { JEV_IMAGE_LIMITS, askJev, jevBoxToPixels, pngImage } from "./jev-client.mjs";
2
+ import { decodeImage, encodePngImage } from "./zoom-image.mjs";
3
+ import { regionKindScale, regionKindView } from "./region-kind.mjs";
4
+ //#region src/locate.ts
5
+ /**
6
+ * Find an element on a screenshot from a description ("the Save button"), with no DOM.
7
+ *
8
+ * For apps whose pixels are the only interface: Flutter web paints a canvas, an Android or macOS
9
+ * capture is a frame. One request asks Jev two typed questions about the whole screenshot: a
10
+ * `noul` (is it shown at all?) and a `box` (where?). If it is shown, a second `box` is asked on
11
+ * a magnified crop around the first, and that answer is mapped back to the original's pixels.
12
+ *
13
+ * Measured 2026-10-16 (`docs/reports/2026-10-16-jev-box-bench.md`, 85 named elements on 9
14
+ * fixtures), not to re-learn:
15
+ *
16
+ * - `box` edges come back at two decimals, so one look is a 12.8px grid on a 1280px image:
17
+ * 89% of box centres on the target, 12px median edge error. The crop takes it to 96% and 5px.
18
+ * - `box` has no "not found" and its `confidence` does not separate hits from misses (AUROC
19
+ * 0.56), so absence is the `noul`'s job: AUROC 0.98, 0 of 85 decoys accepted at 0.5.
20
+ * - The `noul` reads text in a field's placeholder as not shown (3 of 3, noul ≤ 0.01) while
21
+ * `box` still found them. Describe fields by their label, or pass `presence: false`.
22
+ */
23
+ /**
24
+ * The scale the whole screenshot is shown at: 1 when it already fits Jev's limits, smaller for a
25
+ * capture over 1568px (a 2x screenshot), larger for one under 280px. Null for a strip no scale
26
+ * fits (an edge ratio over 5.6).
27
+ */
28
+ function firstLookScale(width, height) {
29
+ const L = JEV_IMAGE_LIMITS;
30
+ const limit = Math.min(L.maxEdge / Math.max(width, height), Math.sqrt(L.maxPixels / (width * height)));
31
+ const min = L.minEdge / Math.min(width, height);
32
+ if (min > limit + 1e-9) return null;
33
+ return Math.max(min, Math.min(1, limit));
34
+ }
35
+ /**
36
+ * The crop for the second look: the first box padded by its own size on each side (at least
37
+ * 16px), grown about its centre to 280px where the image allows, inside the image. The bench's
38
+ * window: padded 1x, the crop held the whole target 87% of the time from one look.
39
+ */
40
+ function refineWindow(box, image) {
41
+ const grow = (lo, size, limit) => {
42
+ const pad = Math.max(16, size);
43
+ let a = lo - pad;
44
+ let z = lo + size + pad;
45
+ const need = Math.max(0, JEV_IMAGE_LIMITS.minEdge - (z - a));
46
+ a -= need / 2;
47
+ z += need / 2;
48
+ if (a < 0) [a, z] = [0, z - a];
49
+ if (z > limit) [a, z] = [Math.max(0, a - (z - limit)), limit];
50
+ return [Math.max(0, Math.floor(a)), Math.min(limit, Math.ceil(z))];
51
+ };
52
+ const [x1, x2] = grow(box.x, box.width, image.width);
53
+ const [y1, y2] = grow(box.y, box.height, image.height);
54
+ return {
55
+ x1,
56
+ y1,
57
+ x2,
58
+ y2
59
+ };
60
+ }
61
+ const toBox = (p) => ({
62
+ x: p.x1,
63
+ y: p.y1,
64
+ width: p.x2 - p.x1,
65
+ height: p.y2 - p.y1
66
+ });
67
+ function view(img, win, scale) {
68
+ return encodePngImage(regionKindView(img, win, scale));
69
+ }
70
+ var LocateError = class extends Error {
71
+ constructor(message) {
72
+ super(message);
73
+ this.name = "LocateError";
74
+ }
75
+ };
76
+ /** Locate `description` on a PNG screenshot. `description` names one thing: "the Save button". */
77
+ async function locateByDescription(png, description, options = {}) {
78
+ const ask = options.ask ?? ((req) => askJev(req, options.client));
79
+ const model = options.model ?? "jev-1.14.0";
80
+ const img = decodeImage(Buffer.from(png));
81
+ const whole = {
82
+ x1: 0,
83
+ y1: 0,
84
+ x2: img.width,
85
+ y2: img.height
86
+ };
87
+ const s1 = firstLookScale(img.width, img.height);
88
+ if (s1 === null) throw new LocateError(`${img.width}x${img.height} cannot be shown within Jev's 280-1568px edges at any scale: crop it to the part to search`);
89
+ const askPresence = options.presence ?? true;
90
+ const what = description.trim().replace(/[.\s]+$/, "");
91
+ let calls = 0;
92
+ let costUsd = 0;
93
+ const first = await ask({
94
+ model,
95
+ state: { screenshot: "SHOT" },
96
+ assets: { SHOT: pngImage(s1 === 1 ? png : view(img, whole, s1)) },
97
+ questions: {
98
+ where: {
99
+ type: "box",
100
+ instructions: `${what} in \`screenshot\`.`
101
+ },
102
+ ...askPresence ? { present: {
103
+ type: "noul",
104
+ instructions: `\`screenshot\` shows ${what}.`
105
+ } } : {}
106
+ }
107
+ });
108
+ calls++;
109
+ costUsd += first.costUsd;
110
+ const answers = first.answers;
111
+ const where = answers.where;
112
+ const firstBox = toBox(jevBoxToPixels(where.box, img.width, img.height));
113
+ const presence = askPresence ? answers.present.noul : null;
114
+ const found = presence === null || presence >= (options.presenceThreshold ?? .5);
115
+ let box = firstBox;
116
+ let refined = false;
117
+ if (found && (options.refine ?? true)) {
118
+ const win = refineWindow(firstBox, img);
119
+ const s2 = regionKindScale(win.x2 - win.x1, win.y2 - win.y1);
120
+ if (s2 !== null) {
121
+ const second = await ask({
122
+ model,
123
+ state: { crop: "CROP" },
124
+ assets: { CROP: pngImage(view(img, win, s2)) },
125
+ questions: { where: {
126
+ type: "box",
127
+ instructions: `${what} in \`crop\`.`
128
+ } }
129
+ });
130
+ calls++;
131
+ costUsd += second.costUsd;
132
+ const b = second.answers.where;
133
+ const p = jevBoxToPixels(b.box, win.x2 - win.x1, win.y2 - win.y1);
134
+ box = toBox({
135
+ x1: win.x1 + p.x1,
136
+ y1: win.y1 + p.y1,
137
+ x2: win.x1 + p.x2,
138
+ y2: win.y1 + p.y2
139
+ });
140
+ refined = true;
141
+ }
142
+ }
143
+ return {
144
+ found,
145
+ presence,
146
+ box,
147
+ point: {
148
+ x: box.x + box.width / 2,
149
+ y: box.y + box.height / 2
150
+ },
151
+ firstBox,
152
+ refined,
153
+ model: first.model,
154
+ calls,
155
+ costUsd
156
+ };
157
+ }
158
+ //#endregion
159
+ export { LocateError, firstLookScale, locateByDescription, refineWindow };
@@ -0,0 +1,156 @@
1
+ import { JevClientOptions } from "./jev-client.mjs";
2
+ import { JevAsk } from "./locate.mjs";
3
+ import { EasingName, MotionDirection, MotionPathReport, MotionSegment, OriginName } from "@mizchi/vlmkit-judge/motion-path.ts";
4
+ //#region src/motion-check.d.ts
5
+ /** A target measured by the page at a frame: border box (frame pixels), rendered opacity, transform scale. */
6
+ export interface MotionDom {
7
+ box: {
8
+ x: number;
9
+ y: number;
10
+ width: number;
11
+ height: number;
12
+ };
13
+ opacity: number;
14
+ scale: number;
15
+ /** Its own animation's progress in time, 0-1 (delay and duration its own), when it has one. */
16
+ t?: number | null;
17
+ /**
18
+ * Share of its box, within the viewport, where it is the topmost thing painted (0-1): what a
19
+ * clip, a cover or a stacking mistake leaves of it. What `jev: false` judges presence from.
20
+ */
21
+ visible?: number;
22
+ /** Why it is not seen, when the page could tell: "clipped by header.topbar (overflow: hidden)…". */
23
+ hiddenBy?: string;
24
+ /** How long its own animation has been active (ms, negative in its delay): when it begins. */
25
+ elapsedMs?: number | null;
26
+ scaleX?: number;
27
+ scaleY?: number;
28
+ durationMs?: number;
29
+ iterations?: number | null;
30
+ /** The share of its box inside the viewport (0-1). */
31
+ onScreen?: number;
32
+ /** Its own opacity, before its ancestors': unchanged while it fades, the fade is theirs. */
33
+ ownOpacity?: number;
34
+ /** The ancestor with the lowest opacity under 1 at this frame. */
35
+ fadeBy?: string;
36
+ /** No layout box at all (display: none on it or an ancestor). */
37
+ notRendered?: boolean;
38
+ /** Every colour it paints (background stops, text, border), RGBA in order. */
39
+ paint?: number[];
40
+ /** Its transition on background runs over a gradient (which steps: gradients do not interpolate). */
41
+ discreteBg?: boolean;
42
+ /** It takes a click at its centre as the page is. */
43
+ catches?: boolean;
44
+ /** An SVG element inside an <svg> (transform-origin from the viewBox by default). */
45
+ svg?: boolean;
46
+ }
47
+ export interface MotionFrame {
48
+ atMs: number;
49
+ png: Uint8Array;
50
+ /** Per target, in order, when the page could measure it (`--selector`); null for one it could not. */
51
+ dom?: (MotionDom | null)[];
52
+ }
53
+ export interface MotionCheckOptions {
54
+ /** What moves, in words, as a person would point at it: "the blue 'Saved' toast". */
55
+ targets: readonly string[];
56
+ /** Statements no frame may show: "text overlapping other text so that it is hard to read". */
57
+ forbid?: readonly string[];
58
+ /** The motion runs over [startMs, endMs]; frames after `endMs` show it at rest. */
59
+ startMs: number;
60
+ endMs: number;
61
+ /** Spans some animation runs in (entrance, exit…): each is fitted and searched for jumps alone. */
62
+ segments?: readonly MotionSegment[];
63
+ /** The targets are meant to leave by the end (a dismissed toast): gone at rest is not a fail. */
64
+ exits?: boolean;
65
+ /** Per target in order: this one is meant to leave (a flip card's front face, turned away). */
66
+ exitsFor?: readonly boolean[];
67
+ /** The timing function the author meant, for every segment or per segment in order. */
68
+ expectEasing?: EasingName | readonly EasingName[];
69
+ /** Per target, in order, overriding `expectEasing` for that target (cards ease-out, a bar ease-in-out). */
70
+ targetEasing?: readonly (EasingName | readonly EasingName[] | undefined)[];
71
+ /** The point a scale grows from: every target's, or per target in order. */
72
+ expectOrigin?: OriginName | readonly (OriginName | undefined)[];
73
+ /** When each target's own animation begins (page ms), per target in order. */
74
+ expectStartMs?: readonly (number | undefined)[];
75
+ /**
76
+ * Consecutive targets begin this far apart (ms), in the order given: each one's start is the
77
+ * first target's (or its --expect-start) plus k times this.
78
+ */
79
+ expectStaggerMs?: number;
80
+ /** How long one run takes (ms) and how many runs (null: infinite): one for all, or per target. */
81
+ expectDurationMs?: readonly number[];
82
+ expectIterations?: readonly (number | null)[];
83
+ /** Which way each target's first segment moves: one for all, or per target. */
84
+ expectDirection?: readonly MotionDirection[];
85
+ /** Every target's centre must not move: only its size and opacity change. */
86
+ expectStill?: boolean;
87
+ /** Per target in order: this one's centre must not move. */
88
+ expectStillFor?: readonly boolean[];
89
+ /** Animations that change layout on the page ("div.notice animates margin-top"). */
90
+ layoutMovers?: readonly string[];
91
+ /** A statement is true at or above this (default 0.5). */
92
+ threshold?: number;
93
+ /** Within this of the threshold an answer is `uncertain` (default 0.3). */
94
+ uncertainBand?: number;
95
+ model?: string;
96
+ /**
97
+ * Ask Jev (default true). False judges from the page alone: every frame must carry every
98
+ * target's `dom` (`--selector`), presence is its `visible` share, and no statement is asked.
99
+ */
100
+ jev?: boolean;
101
+ ask?: JevAsk;
102
+ client?: JevClientOptions;
103
+ /**
104
+ * Ask each target's box a second time on a magnified crop of the region it moves through
105
+ * (default true): a first look's edges are 1% steps, 12.8px on a 1280px frame, which is a jump's
106
+ * size on a short travel; magnified, they were ~5px in the jev-box bench. One more request per
107
+ * frame that shows a target.
108
+ */
109
+ refine?: boolean;
110
+ /** Requests in flight at once (default 4). */
111
+ concurrency?: number;
112
+ }
113
+ export interface MotionFrameAnswer {
114
+ atMs: number;
115
+ rest: boolean;
116
+ targets: {
117
+ present: number;
118
+ box: {
119
+ x: number;
120
+ y: number;
121
+ width: number;
122
+ height: number;
123
+ };
124
+ refined?: boolean;
125
+ /** Its box coincides with another target's in this frame: one of them is the wrong element. */
126
+ unsure?: boolean;
127
+ }[];
128
+ forbid: number[];
129
+ }
130
+ export interface ForbidFinding {
131
+ statement: string;
132
+ /** Fail when it is seen once the motion stops, warn when only mid-motion. */
133
+ severity: "fail" | "warn";
134
+ /** Frames that show it, with Jev's noul. */
135
+ frames: {
136
+ atMs: number;
137
+ noul: number;
138
+ uncertain: boolean;
139
+ }[];
140
+ atRest: boolean;
141
+ }
142
+ export interface MotionCheckReport {
143
+ frames: MotionFrameAnswer[];
144
+ targets: (MotionPathReport & {
145
+ target: string;
146
+ })[];
147
+ forbidden: ForbidFinding[];
148
+ /** No fail finding on any target and no forbidden statement seen at rest. */
149
+ passed: boolean;
150
+ model: string;
151
+ calls: number;
152
+ costUsd: number;
153
+ inputTokens: number;
154
+ }
155
+ export declare function checkMotionFrames(frames: readonly MotionFrame[], options: MotionCheckOptions): Promise<MotionCheckReport>;
156
+ //#endregion