@mizchi/vlmkit-ai 0.23.2 → 0.28.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.
@@ -0,0 +1,146 @@
1
+ // src/jev-client.ts
2
+ /**
3
+ * TypeSafe's Jev (System One): typed questions about a state, typed answers back. No prose.
4
+ *
5
+ * Jev generates no text. A request is a `state` (text, objects, images) and a map of questions,
6
+ * each one of four types, and every answer is a value the caller can use as is:
7
+ *
8
+ * - `box` → one bounding box, edges as fractions of the image (0-1, top-left origin) + confidence
9
+ * - `noul` → the probability a statement is true (0-1)
10
+ * - `choice` → one option key + a probability per option + confidence
11
+ * - `score` → a position on an ordered rubric + a probability per level + confidence
12
+ *
13
+ * That shape is why it fits vlmkit's judges and benches: nothing here parses a reply. Images and
14
+ * `box` are behind `TypeSafe-Danger-Zone-Images: true` (Jev 1.14 for `box`); docs
15
+ * https://docs.typesafe.ai/go/images and https://docs.typesafe.ai/go/box.
16
+ *
17
+ * Images are referenced, not inlined: each asset has a key, and any string in `state`,
18
+ * `instructions` or `criteria` that equals (or contains) the key becomes that image. Every asset
19
+ * must be referenced, and each reference adds a copy to what the model reads — put a shared image
20
+ * in `state` once rather than in every question's instructions.
21
+ */
22
+ const JEV_ENDPOINT = "https://api.typesafe.ai/v1/systemone";
23
+ const JEV_DEFAULT_MODEL = "jev-1.14.0";
24
+ /** USD per input token ($42 per billion, 2026-10). Output tokens are free. */
25
+ const JEV_INPUT_USD_PER_TOKEN = 42e-9;
26
+ /** Images outside these are rejected by the API, not resized (docs.typesafe.ai/go/images). */
27
+ const JEV_IMAGE_LIMITS = {
28
+ minEdge: 280,
29
+ maxEdge: 1568,
30
+ minPixels: 78400,
31
+ maxPixels: 2458624,
32
+ maxFileBytes: 16777216
33
+ };
34
+ var JevApiError = class extends Error {
35
+ status;
36
+ body;
37
+ constructor(status, body) {
38
+ super(`Jev API ${status}: ${body.slice(0, 500)}`);
39
+ this.status = status;
40
+ this.body = body;
41
+ this.name = "JevApiError";
42
+ }
43
+ };
44
+ /** Why an image would be refused, or null. Checked locally so a bench fails before it spends. */
45
+ function jevImageProblem(width, height, bytes) {
46
+ const L = JEV_IMAGE_LIMITS;
47
+ if (width < L.minEdge || height < L.minEdge) return `${width}x${height}: each edge must be >= ${L.minEdge}px`;
48
+ if (width > L.maxEdge || height > L.maxEdge) return `${width}x${height}: each edge must be <= ${L.maxEdge}px`;
49
+ const px = width * height;
50
+ if (px < L.minPixels || px > L.maxPixels) return `${width}x${height}: ${px} pixels outside ${L.minPixels}-${L.maxPixels}`;
51
+ if (bytes !== void 0 && bytes > L.maxFileBytes) return `${bytes} bytes exceeds ${L.maxFileBytes}`;
52
+ return null;
53
+ }
54
+ function pngImage(bytes) {
55
+ return {
56
+ bytes,
57
+ format: "png"
58
+ };
59
+ }
60
+ /** Width and height from a PNG's IHDR, without decoding it. */
61
+ function pngSize(bytes) {
62
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
63
+ return {
64
+ width: view.getUint32(16),
65
+ height: view.getUint32(20)
66
+ };
67
+ }
68
+ /** A box answer in the pixel space of an image of `width` x `height`. */
69
+ function jevBoxToPixels(box, width, height) {
70
+ return {
71
+ x1: box.left * width,
72
+ y1: box.top * height,
73
+ x2: box.right * width,
74
+ y2: box.bottom * height
75
+ };
76
+ }
77
+ /** The multipart body: a `request` JSON part, then one file part per asset (`a0`, `a1`, …). */
78
+ function buildJevForm(req) {
79
+ const assets = {};
80
+ const form = new FormData();
81
+ const files = [];
82
+ Object.entries(req.assets ?? {}).forEach(([key, img], i) => {
83
+ const part = `a${i}`;
84
+ assets[key] = {
85
+ type: "image",
86
+ part
87
+ };
88
+ const mime = img.format === "png" ? "image/png" : "image/jpeg";
89
+ files.push([part, new Blob([img.bytes], { type: mime })]);
90
+ });
91
+ const body = {
92
+ model: req.model ?? "jev-1.14.0",
93
+ state: req.state,
94
+ assets,
95
+ questions: req.questions
96
+ };
97
+ form.append("request", new Blob([JSON.stringify(body)], { type: "application/json" }));
98
+ for (const [part, blob] of files) form.append(part, blob, part);
99
+ return form;
100
+ }
101
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
102
+ async function askJev(req, options = {}) {
103
+ const apiKey = options.apiKey ?? process.env.TYPESAFEAI_API_KEY ?? process.env.TYPESAFE_API_KEY;
104
+ if (!apiKey) throw new Error("Jev needs TYPESAFEAI_API_KEY (console.typesafe.ai/keys)");
105
+ const hasImages = Object.keys(req.assets ?? {}).length > 0;
106
+ const hasBox = Object.values(req.questions).some((q) => q.type === "box");
107
+ const headers = {
108
+ Authorization: `Bearer ${apiKey}`,
109
+ ...options.headers
110
+ };
111
+ if (hasImages || hasBox) headers["TypeSafe-Danger-Zone-Images"] = "true";
112
+ const doFetch = options.fetch ?? fetch;
113
+ const retries = options.retries ?? 3;
114
+ for (let attempt = 0;; attempt++) {
115
+ const started = performance.now();
116
+ const res = await doFetch(options.endpoint ?? "https://api.typesafe.ai/v1/systemone", {
117
+ method: "POST",
118
+ headers,
119
+ body: buildJevForm(req),
120
+ signal: options.signal
121
+ });
122
+ const latencyMs = performance.now() - started;
123
+ if (res.ok) {
124
+ const json = await res.json();
125
+ return {
126
+ ...json,
127
+ latencyMs,
128
+ costUsd: json.usage.input_tokens * JEV_INPUT_USD_PER_TOKEN
129
+ };
130
+ }
131
+ const text = await res.text();
132
+ if (attempt < retries && (res.status === 429 || res.status >= 500)) {
133
+ const after = Number(res.headers.get("retry-after"));
134
+ await sleep(Number.isFinite(after) && after > 0 ? after * 1e3 : 1e3 * 2 ** attempt);
135
+ continue;
136
+ }
137
+ throw new JevApiError(res.status, text);
138
+ }
139
+ }
140
+ /** Decode-free sanity: a PNG Buffer that Jev would accept, or the reason it would not. */
141
+ function checkPngForJev(bytes) {
142
+ if (bytes.length < 24 || bytes[0] !== 137 || bytes[1] !== 80) return "not a PNG";
143
+ const { width, height } = pngSize(bytes);
144
+ return jevImageProblem(width, height, bytes.length);
145
+ }
146
+ export { JEV_DEFAULT_MODEL, JEV_ENDPOINT, JEV_IMAGE_LIMITS, JEV_INPUT_USD_PER_TOKEN, JevApiError, askJev, buildJevForm, checkPngForJev, jevBoxToPixels, jevImageProblem, pngImage, pngSize };
@@ -1,7 +1,5 @@
1
1
  import { LLMProvider } from "./intent.mjs";
2
-
3
- //#region src/llm-client.d.ts
4
- interface LLMClientOptions {
2
+ export interface LLMClientOptions {
5
3
  /** Whether vision support is needed */
6
4
  vision?: boolean;
7
5
  /** Max tokens */
@@ -16,17 +14,17 @@ interface LLMClientOptions {
16
14
  */
17
15
  throwIfMissing?: boolean;
18
16
  }
19
- interface ImageContent {
17
+ export interface ImageContent {
20
18
  type: "image";
21
19
  base64: string;
22
20
  mimeType?: string;
23
21
  }
24
- interface TextContent {
22
+ export interface TextContent {
25
23
  type: "text";
26
24
  text: string;
27
25
  }
28
- type MessageContent = string | Array<TextContent | ImageContent>;
29
- interface LLMResponse {
26
+ export type MessageContent = string | Array<TextContent | ImageContent>;
27
+ export interface LLMResponse {
30
28
  content: string;
31
29
  model: string;
32
30
  provider: string;
@@ -35,7 +33,7 @@ interface LLMResponse {
35
33
  costUsd: number;
36
34
  latencyMs: number;
37
35
  }
38
- interface UnifiedLLMClient {
36
+ export interface UnifiedLLMClient {
39
37
  /** Text only (backwards-compatible) */
40
38
  complete(prompt: string): Promise<string>;
41
39
  /** Text + images */
@@ -54,7 +52,7 @@ interface UnifiedLLMClient {
54
52
  provider: string;
55
53
  model: string;
56
54
  }
57
- type LLMProviderName = "gemini" | "anthropic" | "openrouter";
55
+ export type LLMProviderName = "gemini" | "anthropic" | "openrouter";
58
56
  /**
59
57
  * The OpenAI model this project reaches for by default, and the one place its id is written.
60
58
  *
@@ -68,7 +66,7 @@ type LLMProviderName = "gemini" | "anthropic" | "openrouter";
68
66
  * the defect this constant came from was an agent reading a document and picking something the
69
67
  * code does not accept.
70
68
  */
71
- declare const OPENAI_DEFAULT_MODEL = "openai/gpt-5.6-luna";
69
+ export declare const OPENAI_DEFAULT_MODEL = "openai/gpt-5.6-luna";
72
70
  /**
73
71
  * Create a unified LLM client.
74
72
  *
@@ -79,8 +77,8 @@ declare const OPENAI_DEFAULT_MODEL = "openai/gpt-5.6-luna";
79
77
  * (`code: "INVALID_PROVIDER"`). Pass `{ throwIfMissing: false }` for
80
78
  * legacy `T | null` return.
81
79
  */
82
- declare function createUnifiedLLMClient(options?: LLMClientOptions): UnifiedLLMClient | null;
83
- interface CreateLLMProviderOptions {
80
+ export declare function createUnifiedLLMClient(options?: LLMClientOptions): UnifiedLLMClient | null;
81
+ export interface CreateLLMProviderOptions {
84
82
  /**
85
83
  * When `false`, returns `null` instead of throwing `VrtConfigError`
86
84
  * if no provider has an API key. Default: `true`.
@@ -96,6 +94,4 @@ interface CreateLLMProviderOptions {
96
94
  * provider in the fallback chain has an API key. Pass
97
95
  * `{ throwIfMissing: false }` for the legacy `T | null` return.
98
96
  */
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 };
97
+ export declare function createLLMProvider(options?: CreateLLMProviderOptions): LLMProvider | null;
@@ -1,6 +1,6 @@
1
1
  import { VrtConfigError } from "./errors.mjs";
2
2
  import { readEnv } from "@mizchi/vlmkit-core/project-config.ts";
3
- //#region src/llm-client.ts
3
+ // src/llm-client.ts
4
4
  function createAnthropicClient(apiKey, model) {
5
5
  const modelId = model ?? "claude-sonnet-4-6";
6
6
  async function call(content, maxTokens) {
@@ -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"
@@ -381,5 +384,4 @@ function createLLMProvider(options) {
381
384
  if (throwIfMissing) throw new VrtConfigError("NO_PROVIDER_AVAILABLE", "No LLM provider available. Set one of: GEMINI_API_KEY, ANTHROPIC_API_KEY, OPENROUTER_API_KEY.");
382
385
  return null;
383
386
  }
384
- //#endregion
385
387
  export { OPENAI_DEFAULT_MODEL, createLLMProvider, createUnifiedLLMClient };
@@ -0,0 +1,67 @@
1
+ import { JevClientOptions, JevRequest, JevResponse } from "./jev-client.mjs";
2
+ export interface LocatedBox {
3
+ x: number;
4
+ y: number;
5
+ width: number;
6
+ height: number;
7
+ }
8
+ export interface LocateResult {
9
+ /** `presence >= presenceThreshold`, or always true with `presence: false`. */
10
+ found: boolean;
11
+ /** The `noul` "the screenshot shows …", 0-1. Null when presence was not asked. */
12
+ presence: number | null;
13
+ /** In the original image's pixels: the refined box when refined, else the first look's. */
14
+ box: LocatedBox;
15
+ /** The box's centre, where a click lands. */
16
+ point: {
17
+ x: number;
18
+ y: number;
19
+ };
20
+ /** The first look's box, in the original's pixels. */
21
+ firstBox: LocatedBox;
22
+ /** Whether `box` came from the second, magnified look. */
23
+ refined: boolean;
24
+ model: string;
25
+ calls: number;
26
+ costUsd: number;
27
+ }
28
+ export type JevAsk = <Q extends JevRequest["questions"]>(req: JevRequest<Q>) => Promise<JevResponse<Q>>;
29
+ export interface LocateOptions {
30
+ /** Ask presence first and report not-found below the threshold (default true). */
31
+ presence?: boolean;
32
+ /** Default 0.5: at it, 95% of real targets and 0% of decoys were accepted. */
33
+ presenceThreshold?: number;
34
+ /** Ask a second `box` on a magnified crop (default true). */
35
+ refine?: boolean;
36
+ model?: string;
37
+ /** Injected for tests; defaults to `askJev` with `client`. */
38
+ ask?: JevAsk;
39
+ client?: JevClientOptions;
40
+ }
41
+ type Win = {
42
+ x1: number;
43
+ y1: number;
44
+ x2: number;
45
+ y2: number;
46
+ };
47
+ /**
48
+ * The scale the whole screenshot is shown at: 1 when it already fits Jev's limits, smaller for a
49
+ * capture over 1568px (a 2x screenshot), larger for one under 280px. Null for a strip no scale
50
+ * fits (an edge ratio over 5.6).
51
+ */
52
+ export declare function firstLookScale(width: number, height: number): number | null;
53
+ /**
54
+ * The crop for the second look: the first box padded by its own size on each side (at least
55
+ * 16px), grown about its centre to 280px where the image allows, inside the image. The bench's
56
+ * window: padded 1x, the crop held the whole target 87% of the time from one look.
57
+ */
58
+ export declare function refineWindow(box: LocatedBox, image: {
59
+ width: number;
60
+ height: number;
61
+ }): Win;
62
+ export declare class LocateError extends Error {
63
+ constructor(message: string);
64
+ }
65
+ /** Locate `description` on a PNG screenshot. `description` names one thing: "the Save button". */
66
+ export declare function locateByDescription(png: Uint8Array, description: string, options?: LocateOptions): Promise<LocateResult>;
67
+ export {};
@@ -0,0 +1,158 @@
1
+ import { JEV_IMAGE_LIMITS, askJev, jevBoxToPixels, pngImage } from "./jev-client.mjs";
2
+ import { regionKindScale, regionKindView } from "./region-kind.mjs";
3
+ import { decodeImage, encodePngImage } from "./zoom-image.mjs";
4
+ // 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
+ export { LocateError, firstLookScale, locateByDescription, refineWindow };