@mizchi/vlmkit-ai 0.11.1 → 0.23.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/dist/index.d.mts CHANGED
@@ -5,4 +5,8 @@ import { CreateLLMProviderOptions, ImageContent, LLMClientOptions, LLMProviderNa
5
5
  import { CreateVlmClientOptions, VlmClient, VlmModel, VlmResponse, createVlmClient, fetchVisionModels, isGeminiDirectModel, listGeminiModels, listModels, resolveGeminiModel, resolveModel } from "./vlm-client.mjs";
6
6
  import { AnalyzeOptions, CssFix, FixSuggestion, PipelineConfig, ReasoningPipeline, StructuredDiffReport, VisualChange, createReasoningPipeline } from "./reasoning-pipeline.mjs";
7
7
  import { ActualChange, ExpectationMapping, ReasoningChain, reasonAboutChanges } from "./reasoning.mjs";
8
- export { type ActualChange, type AnalyzeOptions, type CreateImageGenClientOptions, type CreateLLMProviderOptions, type CreateVlmClientOptions, type CssFix, type ExpectationMapping, type FixSuggestion, type ImageContent, type ImageGenBackground, type ImageGenClient, type ImageGenModel, type ImageGenOutputFormat, type ImageGenQuality, type ImageGenRequest, type ImageGenRequestBody, type ImageGenResponse, type ImageGenSize, type ImageGenUsage, type LLMClientOptions, type LLMProvider, type LLMProviderName, type LLMResponse, type MessageContent, OPENAI_DEFAULT_MODEL, type ParsedGeneration, type PipelineConfig, type ReasoningChain, type ReasoningPipeline, type StructuredDiffReport, type TextContent, type UnifiedLLMClient, type VisualChange, type VlmClient, type VlmModel, type VlmResponse, VrtConfigError, type VrtConfigErrorCode, buildGenerationBody, buildIntent, buildIntentWithLLM, buildReasoningPrompt, createImageGenClient, createLLMProvider, createReasoningPipeline, createUnifiedLLMClient, createVlmClient, estimateImageGenCost, extractDiffSemantics, fetchVisionModels, isGeminiDirectModel, listGeminiModels, listImageGenModels, listModels, parseDiff, parseGenerationResponse, reasonAboutChanges, resolveGeminiModel, resolveImageGenModel, resolveModel };
8
+ import { DEFAULT_IMAGE_BUDGET, ImageBudget, ZoomCoordinates } from "./zoom-geometry.mjs";
9
+ import { SingleLookResult, VisionChatDriver, ZoomLoopOptions, ZoomLoopResult, parseZoomRequests, runSingleLook, runZoomLoop } from "./zoom-loop.mjs";
10
+ import { anthropicDriver, geminiDriver, openAiCompatibleDriver } from "./zoom-drivers.mjs";
11
+ import { ZoomAnalysis, analyzeWithZoom, createZoomDriver } from "./zoom.mjs";
12
+ export { type ActualChange, type AnalyzeOptions, type CreateImageGenClientOptions, type CreateLLMProviderOptions, type CreateVlmClientOptions, type CssFix, DEFAULT_IMAGE_BUDGET, type ExpectationMapping, type FixSuggestion, type ImageBudget, type ImageContent, type ImageGenBackground, type ImageGenClient, type ImageGenModel, type ImageGenOutputFormat, type ImageGenQuality, type ImageGenRequest, type ImageGenRequestBody, type ImageGenResponse, type ImageGenSize, type ImageGenUsage, type LLMClientOptions, type LLMProvider, type LLMProviderName, type LLMResponse, type MessageContent, OPENAI_DEFAULT_MODEL, type ParsedGeneration, type PipelineConfig, type ReasoningChain, type ReasoningPipeline, type SingleLookResult, type StructuredDiffReport, type TextContent, type UnifiedLLMClient, type VisionChatDriver, type VisualChange, type VlmClient, type VlmModel, type VlmResponse, VrtConfigError, type VrtConfigErrorCode, type ZoomAnalysis, type ZoomCoordinates, type ZoomLoopOptions, type ZoomLoopResult, analyzeWithZoom, anthropicDriver, buildGenerationBody, buildIntent, buildIntentWithLLM, buildReasoningPrompt, createImageGenClient, createLLMProvider, createReasoningPipeline, createUnifiedLLMClient, createVlmClient, createZoomDriver, estimateImageGenCost, extractDiffSemantics, fetchVisionModels, geminiDriver, isGeminiDirectModel, listGeminiModels, listImageGenModels, listModels, openAiCompatibleDriver, parseDiff, parseGenerationResponse, parseZoomRequests, reasonAboutChanges, resolveGeminiModel, resolveImageGenModel, resolveModel, runSingleLook, runZoomLoop };
package/dist/index.mjs CHANGED
@@ -5,4 +5,8 @@ import { createVlmClient, fetchVisionModels, isGeminiDirectModel, listGeminiMode
5
5
  import { createReasoningPipeline } from "./reasoning-pipeline.mjs";
6
6
  import { reasonAboutChanges } from "./reasoning.mjs";
7
7
  import { buildIntent, buildIntentWithLLM, buildReasoningPrompt, extractDiffSemantics, parseDiff } from "./intent.mjs";
8
- export { OPENAI_DEFAULT_MODEL, VrtConfigError, buildGenerationBody, buildIntent, buildIntentWithLLM, buildReasoningPrompt, createImageGenClient, createLLMProvider, createReasoningPipeline, createUnifiedLLMClient, createVlmClient, estimateImageGenCost, extractDiffSemantics, fetchVisionModels, isGeminiDirectModel, listGeminiModels, listImageGenModels, listModels, parseDiff, parseGenerationResponse, reasonAboutChanges, resolveGeminiModel, resolveImageGenModel, resolveModel };
8
+ import { DEFAULT_IMAGE_BUDGET } from "./zoom-geometry.mjs";
9
+ import { parseZoomRequests, runSingleLook, runZoomLoop } from "./zoom-loop.mjs";
10
+ import { anthropicDriver, geminiDriver, openAiCompatibleDriver } from "./zoom-drivers.mjs";
11
+ import { analyzeWithZoom, createZoomDriver } from "./zoom.mjs";
12
+ export { DEFAULT_IMAGE_BUDGET, OPENAI_DEFAULT_MODEL, VrtConfigError, analyzeWithZoom, anthropicDriver, buildGenerationBody, buildIntent, buildIntentWithLLM, buildReasoningPrompt, createImageGenClient, createLLMProvider, createReasoningPipeline, createUnifiedLLMClient, createVlmClient, createZoomDriver, estimateImageGenCost, extractDiffSemantics, fetchVisionModels, geminiDriver, isGeminiDirectModel, listGeminiModels, listImageGenModels, listModels, openAiCompatibleDriver, parseDiff, parseGenerationResponse, parseZoomRequests, reasonAboutChanges, resolveGeminiModel, resolveImageGenModel, resolveModel, runSingleLook, runZoomLoop };
@@ -58,10 +58,10 @@ type LLMProviderName = "gemini" | "anthropic" | "openrouter";
58
58
  /**
59
59
  * The OpenAI model this project reaches for by default, and the one place its id is written.
60
60
  *
61
- * OpenAI is **not** a provider name here — there is no `api.openai.com` client and no
62
- * `OPENAI_API_KEY` anywhere in the codebase. Its models are served through OpenRouter, which is
63
- * why the id carries the `openai/` prefix: that string is an OpenRouter catalogue id, not an
64
- * OpenAI one.
61
+ * OpenAI is **not** an LLM provider name here. This client serves its OpenAI models through
62
+ * OpenRouter, which is why the id carries the `openai/` prefix: that string is an OpenRouter
63
+ * catalogue id. The separate image-generation client calls `api.openai.com` and reads
64
+ * `OPENAI_API_KEY`.
65
65
  *
66
66
  * Exported so the docs can be pinned to it. `tests/agent-model-defaults.test.mjs` asserts that
67
67
  * `AGENTS.md`, `.claude/CLAUDE.md` and `docs/configuration.md` all name this exact model, because
@@ -219,10 +219,10 @@ const VALID_PROVIDERS = new Set([
219
219
  /**
220
220
  * The OpenAI model this project reaches for by default, and the one place its id is written.
221
221
  *
222
- * OpenAI is **not** a provider name here — there is no `api.openai.com` client and no
223
- * `OPENAI_API_KEY` anywhere in the codebase. Its models are served through OpenRouter, which is
224
- * why the id carries the `openai/` prefix: that string is an OpenRouter catalogue id, not an
225
- * OpenAI one.
222
+ * OpenAI is **not** an LLM provider name here. This client serves its OpenAI models through
223
+ * OpenRouter, which is why the id carries the `openai/` prefix: that string is an OpenRouter
224
+ * catalogue id. The separate image-generation client calls `api.openai.com` and reads
225
+ * `OPENAI_API_KEY`.
226
226
  *
227
227
  * Exported so the docs can be pinned to it. `tests/agent-model-defaults.test.mjs` asserts that
228
228
  * `AGENTS.md`, `.claude/CLAUDE.md` and `docs/configuration.md` all name this exact model, because
@@ -0,0 +1,33 @@
1
+ import { VisionChatDriver, ZoomToolSpec } from "./zoom-loop.mjs";
2
+
3
+ //#region src/zoom-drivers.d.ts
4
+ type Fetch = typeof fetch;
5
+ interface OpenAiCompatibleDriverOptions {
6
+ model: string;
7
+ apiKey?: string;
8
+ /** Chat Completions URL (default OpenRouter's). */
9
+ url?: string;
10
+ headers?: Record<string, string>;
11
+ /** False for a server without function calling: the loop then uses the text protocol. */
12
+ nativeTools?: boolean;
13
+ fetch?: Fetch;
14
+ }
15
+ declare function openAiCompatibleDriver(options: OpenAiCompatibleDriverOptions): VisionChatDriver;
16
+ interface AnthropicDriverOptions {
17
+ model: string;
18
+ apiKey: string;
19
+ /** Default https://api.anthropic.com (or ANTHROPIC_BASE_URL when the caller passes it). */
20
+ baseUrl?: string;
21
+ fetch?: Fetch;
22
+ }
23
+ declare function anthropicDriver(options: AnthropicDriverOptions): VisionChatDriver;
24
+ interface GeminiDriverOptions {
25
+ /** e.g. `gemini-2.5-flash` (no `gemini:` prefix). */
26
+ model: string;
27
+ apiKey: string;
28
+ baseUrl?: string;
29
+ fetch?: Fetch;
30
+ }
31
+ declare function geminiDriver(options: GeminiDriverOptions): VisionChatDriver;
32
+ //#endregion
33
+ export { AnthropicDriverOptions, GeminiDriverOptions, OpenAiCompatibleDriverOptions, type ZoomToolSpec, anthropicDriver, geminiDriver, openAiCompatibleDriver };
@@ -0,0 +1,316 @@
1
+ import { zoomCallFromArgs } from "./zoom-loop.mjs";
2
+ //#region src/zoom-drivers.ts
3
+ async function postJson(fetcher, url, headers, body, provider) {
4
+ const res = await fetcher(url, {
5
+ method: "POST",
6
+ headers: {
7
+ "Content-Type": "application/json",
8
+ ...headers
9
+ },
10
+ body: JSON.stringify(body)
11
+ });
12
+ if (!res.ok) {
13
+ const text = await res.text();
14
+ throw new Error(`${provider} API error: ${res.status} ${text.slice(0, 300)}`);
15
+ }
16
+ return await res.json();
17
+ }
18
+ /** A call the provider made whose arguments did not parse still needs an answer; this one says why. */
19
+ function callsFrom(parsed) {
20
+ const calls = [];
21
+ const broken = [];
22
+ for (const p of parsed) ("error" in p ? broken : calls).push(p);
23
+ return {
24
+ calls,
25
+ broken
26
+ };
27
+ }
28
+ /** Merge adjacent messages of one role: every provider accepts that, not every one accepts the split. */
29
+ function mergeAdjacent(messages, join) {
30
+ const out = [];
31
+ for (const m of messages) {
32
+ const last = out[out.length - 1];
33
+ if (last && last.role === m.role) out[out.length - 1] = join(last, m);
34
+ else out.push(m);
35
+ }
36
+ return out;
37
+ }
38
+ const b64 = (png) => png.toString("base64");
39
+ function openAiCompatibleDriver(options) {
40
+ const url = options.url ?? "https://openrouter.ai/api/v1/chat/completions";
41
+ const fetcher = options.fetch ?? fetch;
42
+ const headers = {
43
+ ...options.apiKey ? { Authorization: `Bearer ${options.apiKey}` } : {},
44
+ ...options.headers
45
+ };
46
+ const content = (parts) => parts.map((p) => p.type === "text" ? {
47
+ type: "text",
48
+ text: p.text
49
+ } : {
50
+ type: "image_url",
51
+ image_url: { url: `data:image/png;base64,${b64(p.png)}` }
52
+ });
53
+ const render = (transcript) => {
54
+ const out = [];
55
+ for (const t of transcript) if (t.role === "user") out.push({
56
+ role: "user",
57
+ content: content(t.parts)
58
+ });
59
+ else if (t.role === "assistant") out.push(t.raw !== void 0 ? t.raw : {
60
+ role: "assistant",
61
+ content: t.text
62
+ });
63
+ else if (t.native) {
64
+ const images = [];
65
+ for (const r of t.results) {
66
+ out.push({
67
+ role: "tool",
68
+ tool_call_id: r.callId,
69
+ content: textOf(r)
70
+ });
71
+ const img = r.parts.filter((p) => p.type === "image");
72
+ if (img.length > 0) images.push({
73
+ type: "text",
74
+ text: `Zoom result for call ${r.callId}:`
75
+ }, ...img);
76
+ }
77
+ if (images.length > 0) out.push({
78
+ role: "user",
79
+ content: content(images)
80
+ });
81
+ } else out.push({
82
+ role: "user",
83
+ content: content(t.results.flatMap((r) => r.parts))
84
+ });
85
+ return out;
86
+ };
87
+ return {
88
+ model: options.model,
89
+ nativeTools: options.nativeTools ?? true,
90
+ async turn(transcript, { tool, maxTokens }) {
91
+ const data = await postJson(fetcher, url, headers, {
92
+ model: options.model,
93
+ max_tokens: maxTokens,
94
+ messages: render(transcript),
95
+ ...tool ? { tools: [{
96
+ type: "function",
97
+ function: {
98
+ name: tool.name,
99
+ description: tool.description,
100
+ parameters: tool.parameters
101
+ }
102
+ }] } : {}
103
+ }, "OpenAI-compatible");
104
+ const choice = data.choices?.[0];
105
+ const message = choice?.message ?? {};
106
+ const toolCalls = message.tool_calls ?? [];
107
+ const { calls, broken } = callsFrom(toolCalls.filter((c) => c.function?.name === "zoom").map((c) => zoomCallFromArgs(c.id, c.function?.arguments)));
108
+ return withBroken({
109
+ text: typeof message.content === "string" ? message.content : "",
110
+ calls,
111
+ raw: {
112
+ role: "assistant",
113
+ content: message.content ?? null,
114
+ ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
115
+ },
116
+ usage: {
117
+ promptTokens: data.usage?.prompt_tokens ?? 0,
118
+ completionTokens: data.usage?.completion_tokens ?? 0
119
+ },
120
+ ...choice?.finish_reason && !["stop", "tool_calls"].includes(choice.finish_reason) ? { stop: choice.finish_reason } : {}
121
+ }, broken);
122
+ }
123
+ };
124
+ }
125
+ function anthropicDriver(options) {
126
+ const url = `${(options.baseUrl ?? "https://api.anthropic.com").replace(/\/$/, "")}/v1/messages`;
127
+ const fetcher = options.fetch ?? fetch;
128
+ const blocks = (parts) => parts.map((p) => p.type === "text" ? {
129
+ type: "text",
130
+ text: p.text
131
+ } : {
132
+ type: "image",
133
+ source: {
134
+ type: "base64",
135
+ media_type: "image/png",
136
+ data: b64(p.png)
137
+ }
138
+ });
139
+ const render = (transcript) => {
140
+ const out = [];
141
+ for (const t of transcript) if (t.role === "user") out.push({
142
+ role: "user",
143
+ content: blocks(t.parts)
144
+ });
145
+ else if (t.role === "assistant") out.push({
146
+ role: "assistant",
147
+ content: t.raw !== void 0 ? t.raw : [...t.text ? [{
148
+ type: "text",
149
+ text: t.text
150
+ }] : [], ...t.calls.filter((c) => !c.id.startsWith("text-")).map((c) => ({
151
+ type: "tool_use",
152
+ id: c.id,
153
+ name: "zoom",
154
+ input: {
155
+ image_index: c.imageIndex,
156
+ ...c.box
157
+ }
158
+ }))]
159
+ });
160
+ else if (t.native) out.push({
161
+ role: "user",
162
+ content: t.results.map((r) => ({
163
+ type: "tool_result",
164
+ tool_use_id: r.callId,
165
+ content: blocks(r.parts),
166
+ ...r.isError ? { is_error: true } : {}
167
+ }))
168
+ });
169
+ else out.push({
170
+ role: "user",
171
+ content: blocks(t.results.flatMap((r) => r.parts))
172
+ });
173
+ return mergeAdjacent(out, (a, b) => ({
174
+ role: a.role,
175
+ content: [...a.content, ...b.content]
176
+ }));
177
+ };
178
+ return {
179
+ model: options.model,
180
+ nativeTools: true,
181
+ async turn(transcript, { tool, maxTokens }) {
182
+ const data = await postJson(fetcher, url, {
183
+ "x-api-key": options.apiKey,
184
+ "anthropic-version": "2023-06-01"
185
+ }, {
186
+ model: options.model,
187
+ max_tokens: maxTokens,
188
+ messages: render(transcript),
189
+ ...tool ? { tools: [{
190
+ name: tool.name,
191
+ description: tool.description,
192
+ input_schema: tool.parameters
193
+ }] } : {}
194
+ }, "Anthropic");
195
+ const content = data.content ?? [];
196
+ const { calls, broken } = callsFrom(content.filter((b) => b.type === "tool_use" && b.name === "zoom").map((b) => zoomCallFromArgs(b.id, b.input)));
197
+ return withBroken({
198
+ text: content.filter((b) => b.type === "text").map((b) => b.text ?? "").join(""),
199
+ calls,
200
+ raw: content,
201
+ usage: {
202
+ promptTokens: data.usage?.input_tokens ?? 0,
203
+ completionTokens: data.usage?.output_tokens ?? 0
204
+ },
205
+ ...data.stop_reason && ![
206
+ "end_turn",
207
+ "tool_use",
208
+ "stop_sequence"
209
+ ].includes(data.stop_reason) ? { stop: data.stop_reason } : {}
210
+ }, broken);
211
+ }
212
+ };
213
+ }
214
+ /** Gemini's function schemas are an OpenAPI subset without `additionalProperties`. */
215
+ function geminiSchema(schema) {
216
+ const { additionalProperties: _drop, ...rest } = schema;
217
+ return rest;
218
+ }
219
+ function geminiDriver(options) {
220
+ const url = `${(options.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta").replace(/\/$/, "")}/models/${encodeURIComponent(options.model)}:generateContent`;
221
+ const fetcher = options.fetch ?? fetch;
222
+ const parts = (ps) => ps.map((p) => p.type === "text" ? { text: p.text } : { inlineData: {
223
+ mimeType: "image/png",
224
+ data: b64(p.png)
225
+ } });
226
+ const render = (transcript) => {
227
+ const out = [];
228
+ for (const t of transcript) if (t.role === "user") out.push({
229
+ role: "user",
230
+ parts: parts(t.parts)
231
+ });
232
+ else if (t.role === "assistant") out.push({
233
+ role: "model",
234
+ parts: t.raw !== void 0 ? t.raw : [...t.text ? [{ text: t.text }] : [], ...t.calls.filter((c) => !c.id.startsWith("text-")).map((c) => ({ functionCall: {
235
+ name: "zoom",
236
+ args: {
237
+ image_index: c.imageIndex,
238
+ ...c.box
239
+ }
240
+ } }))]
241
+ });
242
+ else if (t.native) out.push({
243
+ role: "user",
244
+ parts: t.results.flatMap((r) => [{ functionResponse: {
245
+ name: "zoom",
246
+ response: {
247
+ result: textOf(r),
248
+ ...r.isError ? { error: true } : {}
249
+ }
250
+ } }, ...parts(r.parts.filter((p) => p.type === "image"))])
251
+ });
252
+ else out.push({
253
+ role: "user",
254
+ parts: parts(t.results.flatMap((r) => r.parts))
255
+ });
256
+ return mergeAdjacent(out, (a, b) => ({
257
+ role: a.role,
258
+ parts: [...a.parts, ...b.parts]
259
+ }));
260
+ };
261
+ return {
262
+ model: options.model,
263
+ nativeTools: true,
264
+ async turn(transcript, { tool, maxTokens }) {
265
+ const data = await postJson(fetcher, url, { "x-goog-api-key": options.apiKey }, {
266
+ contents: render(transcript),
267
+ generationConfig: { maxOutputTokens: maxTokens },
268
+ ...tool ? { tools: [{ functionDeclarations: [{
269
+ name: tool.name,
270
+ description: tool.description,
271
+ parameters: geminiSchema(tool.parameters)
272
+ }] }] } : {}
273
+ }, "Gemini");
274
+ const candidate = data.candidates?.[0];
275
+ const ps = candidate?.content?.parts ?? [];
276
+ const { calls, broken } = callsFrom(ps.filter((p) => p.functionCall?.name === "zoom").map((p, i) => zoomCallFromArgs(`gemini-${i}`, p.functionCall.args)));
277
+ return withBroken({
278
+ text: ps.map((p) => p.text ?? "").join(""),
279
+ calls,
280
+ raw: ps,
281
+ usage: {
282
+ promptTokens: data.usageMetadata?.promptTokenCount ?? 0,
283
+ completionTokens: data.usageMetadata?.candidatesTokenCount ?? 0
284
+ },
285
+ ...candidate?.finishReason && candidate.finishReason !== "STOP" ? { stop: candidate.finishReason } : {}
286
+ }, broken);
287
+ }
288
+ };
289
+ }
290
+ function textOf(r) {
291
+ return r.parts.filter((p) => p.type === "text").map((p) => p.text).join("\n");
292
+ }
293
+ /**
294
+ * A native call whose arguments did not parse still travels as a call, carrying its error, so
295
+ * the loop answers it with a message the model can act on instead of dropping it — an
296
+ * unanswered tool call is a 400 on the next request with every provider.
297
+ */
298
+ function withBroken(turn, broken) {
299
+ if (broken.length === 0) return turn;
300
+ return {
301
+ ...turn,
302
+ calls: [...turn.calls, ...broken.map((b) => ({
303
+ id: b.id,
304
+ imageIndex: 0,
305
+ box: {
306
+ x1: 0,
307
+ y1: 0,
308
+ x2: 0,
309
+ y2: 0
310
+ },
311
+ error: b.error
312
+ }))]
313
+ };
314
+ }
315
+ //#endregion
316
+ export { anthropicDriver, geminiDriver, openAiCompatibleDriver };
@@ -0,0 +1,85 @@
1
+ //#region src/zoom-geometry.d.ts
2
+ /**
3
+ * The arithmetic of letting a vision model zoom: which size it sees, which pixels a box it
4
+ * names refers to, and how large the magnified crop comes back. Pure — no image bytes here.
5
+ *
6
+ * The technique is the one Anthropic's multimodal cookbook measured (a chart question went from
7
+ * 36/40 wrong to 40/40 right once the model could crop and magnify), taken without anything
8
+ * provider-specific. Its one load-bearing idea: **the caller, not the provider, decides the size
9
+ * the model sees.** Every provider downscales a large image before the model reads it, by rules
10
+ * that differ between providers and change between releases; a box the model names is in *that*
11
+ * image's pixels, and mapping it back needs to know the size exactly. So the image is resized
12
+ * here to fit a budget below any provider's own limit (`fitToBudget`), the model is told its
13
+ * size in pixels, and a box it names is mapped onto the full-resolution original
14
+ * (`viewBoxToOriginal`) — the crop always comes from the original, never from the view.
15
+ */
16
+ /** How large an image one message may carry. Providers differ; stay under all of them. */
17
+ interface ImageBudget {
18
+ /** Longest edge, px. */
19
+ maxEdge: number;
20
+ /** Width × height, px². Tile-counting providers bill by area; this bounds the bill too. */
21
+ maxPixels: number;
22
+ }
23
+ /**
24
+ * 1568px on the long edge and about 1.15 megapixels: the size below which Anthropic documents
25
+ * that it does not resize. Other providers resize by their own rules (OpenAI's high-detail path
26
+ * rescales the short side to 768px; Gemini tiles), and a model reading a resized copy may name
27
+ * boxes in that copy's pixels — which is why the loop also offers normalized coordinates
28
+ * (`coordinates: "normalized"`, 0–1000 on each axis), invariant to any resize. Pass a budget
29
+ * that matches the model you use; nothing here assumes this one.
30
+ */
31
+ declare const DEFAULT_IMAGE_BUDGET: ImageBudget;
32
+ /**
33
+ * How the model states a box. `pixels`: absolute pixels of the view it was shown (the cookbook's
34
+ * form; exact when the provider does not resize the view again). `normalized`: 0–1000 of the
35
+ * view's width and height, the form several vision models are trained to emit for boxes, and
36
+ * correct whatever size the provider actually showed the model.
37
+ */
38
+ type ZoomCoordinates = "pixels" | "normalized";
39
+ /** A box as the model stated it, in the view's pixel space. */
40
+ declare function toViewBox(box: Box, view: Size, coordinates: ZoomCoordinates): Box;
41
+ interface Size {
42
+ width: number;
43
+ height: number;
44
+ }
45
+ /** A box in some image's pixel space, x2 > x1 and y2 > y1 (half-open: x1 <= x < x2). */
46
+ interface Box {
47
+ x1: number;
48
+ y1: number;
49
+ x2: number;
50
+ y2: number;
51
+ }
52
+ /**
53
+ * The largest aspect-preserving size within the budget, never larger than the input. An image
54
+ * that already fits is returned unchanged, so a small screenshot is shown at 1:1.
55
+ */
56
+ declare function fitToBudget(size: Size, budget?: ImageBudget): Size;
57
+ /**
58
+ * The size a crop is magnified to: the largest aspect-preserving size within the budget, even
59
+ * when that means enlarging it — a 60×20 region comes back filling the budget, which is the
60
+ * point. (Magnifying past the original's own pixels adds no detail, but it does make each
61
+ * original pixel several of the model's, which is what lets it read an 8px gap.)
62
+ */
63
+ declare function zoomSize(crop: Size, budget?: ImageBudget): Size;
64
+ type BoxProblem = {
65
+ ok: false;
66
+ reason: string;
67
+ };
68
+ /**
69
+ * Clamp a box the model named to the view it saw, and reject one with no area left. Models
70
+ * name boxes past the edge routinely (x2 = 1600 on a 1568px view); clamping is the honest
71
+ * reading. A box that is empty after clamping is an error the model is told about, so it can
72
+ * try again, rather than a crash.
73
+ */
74
+ declare function clampBox(box: Box, view: Size): {
75
+ ok: true;
76
+ box: Box;
77
+ } | BoxProblem;
78
+ /**
79
+ * The original's pixels a view box covers. Scales on each axis separately (the view's integer
80
+ * size is not an exact multiple of the original's), rounds outward so a 1px feature on the
81
+ * box's edge is kept, and never returns an empty box.
82
+ */
83
+ declare function viewBoxToOriginal(box: Box, view: Size, original: Size): Box;
84
+ //#endregion
85
+ export { Box, BoxProblem, DEFAULT_IMAGE_BUDGET, ImageBudget, Size, ZoomCoordinates, clampBox, fitToBudget, toViewBox, viewBoxToOriginal, zoomSize };
@@ -0,0 +1,103 @@
1
+ //#region src/zoom-geometry.ts
2
+ /**
3
+ * 1568px on the long edge and about 1.15 megapixels: the size below which Anthropic documents
4
+ * that it does not resize. Other providers resize by their own rules (OpenAI's high-detail path
5
+ * rescales the short side to 768px; Gemini tiles), and a model reading a resized copy may name
6
+ * boxes in that copy's pixels — which is why the loop also offers normalized coordinates
7
+ * (`coordinates: "normalized"`, 0–1000 on each axis), invariant to any resize. Pass a budget
8
+ * that matches the model you use; nothing here assumes this one.
9
+ */
10
+ const DEFAULT_IMAGE_BUDGET = {
11
+ maxEdge: 1568,
12
+ maxPixels: 115e4
13
+ };
14
+ /** A box as the model stated it, in the view's pixel space. */
15
+ function toViewBox(box, view, coordinates) {
16
+ if (coordinates === "pixels") return box;
17
+ return {
18
+ x1: box.x1 / 1e3 * view.width,
19
+ y1: box.y1 / 1e3 * view.height,
20
+ x2: box.x2 / 1e3 * view.width,
21
+ y2: box.y2 / 1e3 * view.height
22
+ };
23
+ }
24
+ /**
25
+ * The largest aspect-preserving size within the budget, never larger than the input. An image
26
+ * that already fits is returned unchanged, so a small screenshot is shown at 1:1.
27
+ */
28
+ function fitToBudget(size, budget = DEFAULT_IMAGE_BUDGET) {
29
+ const { width, height } = size;
30
+ if (width <= 0 || height <= 0) throw new RangeError(`not an image size: ${width}x${height}`);
31
+ const scale = Math.min(1, budget.maxEdge / Math.max(width, height), Math.sqrt(budget.maxPixels / (width * height)));
32
+ if (scale >= 1) return {
33
+ width,
34
+ height
35
+ };
36
+ return scaled(size, scale);
37
+ }
38
+ /**
39
+ * The size a crop is magnified to: the largest aspect-preserving size within the budget, even
40
+ * when that means enlarging it — a 60×20 region comes back filling the budget, which is the
41
+ * point. (Magnifying past the original's own pixels adds no detail, but it does make each
42
+ * original pixel several of the model's, which is what lets it read an 8px gap.)
43
+ */
44
+ function zoomSize(crop, budget = DEFAULT_IMAGE_BUDGET) {
45
+ return scaled(crop, Math.min(budget.maxEdge / Math.max(crop.width, crop.height), Math.sqrt(budget.maxPixels / (crop.width * crop.height))));
46
+ }
47
+ /** Floor with a hair of tolerance: 3000 × (1568 / 3000) is 1567.9999… in floating point, and it means 1568. */
48
+ function scaled(size, scale) {
49
+ return {
50
+ width: Math.max(1, Math.floor(size.width * scale + 1e-6)),
51
+ height: Math.max(1, Math.floor(size.height * scale + 1e-6))
52
+ };
53
+ }
54
+ /**
55
+ * Clamp a box the model named to the view it saw, and reject one with no area left. Models
56
+ * name boxes past the edge routinely (x2 = 1600 on a 1568px view); clamping is the honest
57
+ * reading. A box that is empty after clamping is an error the model is told about, so it can
58
+ * try again, rather than a crash.
59
+ */
60
+ function clampBox(box, view) {
61
+ if (![
62
+ box.x1,
63
+ box.y1,
64
+ box.x2,
65
+ box.y2
66
+ ].every((n) => Number.isFinite(n))) return {
67
+ ok: false,
68
+ reason: "coordinates must be numbers"
69
+ };
70
+ const clamped = {
71
+ x1: Math.max(0, Math.min(Math.round(box.x1), view.width)),
72
+ y1: Math.max(0, Math.min(Math.round(box.y1), view.height)),
73
+ x2: Math.max(0, Math.min(Math.round(box.x2), view.width)),
74
+ y2: Math.max(0, Math.min(Math.round(box.y2), view.height))
75
+ };
76
+ if (clamped.x1 >= clamped.x2 || clamped.y1 >= clamped.y2) return {
77
+ ok: false,
78
+ reason: `invalid region (need x1 < x2 and y1 < y2 inside the ${view.width}x${view.height} image)`
79
+ };
80
+ return {
81
+ ok: true,
82
+ box: clamped
83
+ };
84
+ }
85
+ /**
86
+ * The original's pixels a view box covers. Scales on each axis separately (the view's integer
87
+ * size is not an exact multiple of the original's), rounds outward so a 1px feature on the
88
+ * box's edge is kept, and never returns an empty box.
89
+ */
90
+ function viewBoxToOriginal(box, view, original) {
91
+ const sx = original.width / view.width;
92
+ const sy = original.height / view.height;
93
+ const x1 = Math.max(0, Math.floor(box.x1 * sx));
94
+ const y1 = Math.max(0, Math.floor(box.y1 * sy));
95
+ return {
96
+ x1,
97
+ y1,
98
+ x2: Math.min(original.width, Math.max(x1 + 1, Math.ceil(box.x2 * sx))),
99
+ y2: Math.min(original.height, Math.max(y1 + 1, Math.ceil(box.y2 * sy)))
100
+ };
101
+ }
102
+ //#endregion
103
+ export { DEFAULT_IMAGE_BUDGET, clampBox, fitToBudget, toViewBox, viewBoxToOriginal, zoomSize };
@@ -0,0 +1,42 @@
1
+ import { Box, ImageBudget, Size } from "./zoom-geometry.mjs";
2
+
3
+ //#region src/zoom-image.d.ts
4
+ interface RgbaImage {
5
+ width: number;
6
+ height: number;
7
+ /** RGBA, row-major, 4 bytes per pixel, alpha always 255 after decode. */
8
+ data: Uint8Array;
9
+ }
10
+ /** Decode a PNG and flatten it onto white. Anything else is refused with the reason. */
11
+ declare function decodeImage(buf: Buffer): RgbaImage;
12
+ declare function encodePngImage(img: RgbaImage): Buffer;
13
+ declare function cropImage(img: RgbaImage, box: Box): RgbaImage;
14
+ /** Resize to exactly `size`: area-average on each axis that shrinks, bilinear on one that grows. */
15
+ declare function resample(img: RgbaImage, size: Size): RgbaImage;
16
+ /** One image as the zoom loop holds it: the full-resolution original and the view the model sees. */
17
+ interface ZoomSource {
18
+ original: RgbaImage;
19
+ view: RgbaImage;
20
+ /** The view, encoded — what is actually sent. */
21
+ viewPng: Buffer;
22
+ }
23
+ declare function prepareZoomSource(png: Buffer, budget?: ImageBudget): ZoomSource;
24
+ type ZoomOutcome = {
25
+ ok: true; /** The box in view pixels after clamping. */
26
+ viewBox: Box; /** The original's pixels that were cropped. */
27
+ originalBox: Box; /** The magnified crop, encoded. */
28
+ png: Buffer;
29
+ size: Size; /** What to tell the model alongside the image. */
30
+ text: string;
31
+ } | {
32
+ ok: false;
33
+ text: string;
34
+ };
35
+ /**
36
+ * Crop the original under a view box and magnify it to the budget. The text states both
37
+ * spaces, so the model can place what it sees in the zoom back onto the view it is reasoning
38
+ * about ("…a 180x60px region of the original, returned at 1568x522px").
39
+ */
40
+ declare function zoomInto(source: ZoomSource, box: Box, budget?: ImageBudget): ZoomOutcome;
41
+ //#endregion
42
+ export { RgbaImage, ZoomOutcome, ZoomSource, cropImage, decodeImage, encodePngImage, prepareZoomSource, resample, zoomInto };
@@ -0,0 +1,147 @@
1
+ import { DEFAULT_IMAGE_BUDGET, clampBox, fitToBudget, viewBoxToOriginal, zoomSize } from "./zoom-geometry.mjs";
2
+ import { PNG } from "pngjs";
3
+ //#region src/zoom-image.ts
4
+ /**
5
+ * The image half of zooming: make the view the model sees, and cut and magnify a region of
6
+ * the original when it asks. PNG in, PNG out, through `pngjs` only, so no native image library
7
+ * is needed — screenshots are what vlmkit feeds a vision model, and they are PNGs.
8
+ *
9
+ * Resampling is a box (area-average) filter when shrinking, which keeps 1px rules visible in
10
+ * the view instead of dropping them between samples, and bilinear when magnifying. Transparent
11
+ * pixels are composited onto white first: a transparent region encoded as black is the classic
12
+ * way a crop "turns dark" in front of a model.
13
+ */
14
+ const PNG_SIGNATURE = Buffer.from([
15
+ 137,
16
+ 80,
17
+ 78,
18
+ 71,
19
+ 13,
20
+ 10,
21
+ 26,
22
+ 10
23
+ ]);
24
+ /** Decode a PNG and flatten it onto white. Anything else is refused with the reason. */
25
+ function decodeImage(buf) {
26
+ if (buf.length < 8 || !buf.subarray(0, 8).equals(PNG_SIGNATURE)) throw new Error("zoom reads PNG images only (screenshots); convert JPEG/WebP to PNG first");
27
+ const png = PNG.sync.read(buf);
28
+ const data = new Uint8Array(png.width * png.height * 4);
29
+ for (let i = 0; i < data.length; i += 4) {
30
+ const a = png.data[i + 3] / 255;
31
+ data[i] = Math.round(png.data[i] * a + 255 * (1 - a));
32
+ data[i + 1] = Math.round(png.data[i + 1] * a + 255 * (1 - a));
33
+ data[i + 2] = Math.round(png.data[i + 2] * a + 255 * (1 - a));
34
+ data[i + 3] = 255;
35
+ }
36
+ return {
37
+ width: png.width,
38
+ height: png.height,
39
+ data
40
+ };
41
+ }
42
+ function encodePngImage(img) {
43
+ const png = new PNG({
44
+ width: img.width,
45
+ height: img.height
46
+ });
47
+ png.data = Buffer.from(img.data.buffer, img.data.byteOffset, img.data.byteLength);
48
+ return PNG.sync.write(png);
49
+ }
50
+ function cropImage(img, box) {
51
+ const width = box.x2 - box.x1;
52
+ const height = box.y2 - box.y1;
53
+ const data = new Uint8Array(width * height * 4);
54
+ for (let y = 0; y < height; y++) {
55
+ const from = ((box.y1 + y) * img.width + box.x1) * 4;
56
+ data.set(img.data.subarray(from, from + width * 4), y * width * 4);
57
+ }
58
+ return {
59
+ width,
60
+ height,
61
+ data
62
+ };
63
+ }
64
+ /** Resize to exactly `size`: area-average on each axis that shrinks, bilinear on one that grows. */
65
+ function resample(img, size) {
66
+ if (size.width === img.width && size.height === img.height) return img;
67
+ const out = new Uint8Array(size.width * size.height * 4);
68
+ const sx = img.width / size.width;
69
+ const sy = img.height / size.height;
70
+ const px = (x, y, c) => img.data[(y * img.width + x) * 4 + c];
71
+ for (let oy = 0; oy < size.height; oy++) for (let ox = 0; ox < size.width; ox++) {
72
+ const o = (oy * size.width + ox) * 4;
73
+ if (sx > 1 || sy > 1) {
74
+ const x0 = ox * sx, x1 = Math.min(img.width, (ox + 1) * sx);
75
+ const y0 = oy * sy, y1 = Math.min(img.height, (oy + 1) * sy);
76
+ const acc = [
77
+ 0,
78
+ 0,
79
+ 0
80
+ ];
81
+ let total = 0;
82
+ for (let y = Math.floor(y0); y < Math.ceil(y1); y++) {
83
+ const wy = Math.min(y + 1, y1) - Math.max(y, y0);
84
+ for (let x = Math.floor(x0); x < Math.ceil(x1); x++) {
85
+ const w = wy * (Math.min(x + 1, x1) - Math.max(x, x0));
86
+ if (w <= 0) continue;
87
+ for (let c = 0; c < 3; c++) acc[c] += px(x, y, c) * w;
88
+ total += w;
89
+ }
90
+ }
91
+ for (let c = 0; c < 3; c++) out[o + c] = Math.round(acc[c] / total);
92
+ } else {
93
+ const fx = Math.max(0, Math.min(img.width - 1, (ox + .5) * sx - .5));
94
+ const fy = Math.max(0, Math.min(img.height - 1, (oy + .5) * sy - .5));
95
+ const x0 = Math.floor(fx), y0 = Math.floor(fy);
96
+ const x1 = Math.min(img.width - 1, x0 + 1), y1 = Math.min(img.height - 1, y0 + 1);
97
+ const tx = fx - x0, ty = fy - y0;
98
+ for (let c = 0; c < 3; c++) {
99
+ const top = px(x0, y0, c) * (1 - tx) + px(x1, y0, c) * tx;
100
+ const bottom = px(x0, y1, c) * (1 - tx) + px(x1, y1, c) * tx;
101
+ out[o + c] = Math.round(top * (1 - ty) + bottom * ty);
102
+ }
103
+ }
104
+ out[o + 3] = 255;
105
+ }
106
+ return {
107
+ width: size.width,
108
+ height: size.height,
109
+ data: out
110
+ };
111
+ }
112
+ function prepareZoomSource(png, budget = DEFAULT_IMAGE_BUDGET) {
113
+ const original = decodeImage(png);
114
+ const view = resample(original, fitToBudget(original, budget));
115
+ return {
116
+ original,
117
+ view,
118
+ viewPng: encodePngImage(view)
119
+ };
120
+ }
121
+ /**
122
+ * Crop the original under a view box and magnify it to the budget. The text states both
123
+ * spaces, so the model can place what it sees in the zoom back onto the view it is reasoning
124
+ * about ("…a 180x60px region of the original, returned at 1568x522px").
125
+ */
126
+ function zoomInto(source, box, budget = DEFAULT_IMAGE_BUDGET) {
127
+ const clamped = clampBox(box, source.view);
128
+ if (!clamped.ok) return {
129
+ ok: false,
130
+ text: `Error: ${clamped.reason}`
131
+ };
132
+ const originalBox = viewBoxToOriginal(clamped.box, source.view, source.original);
133
+ const crop = cropImage(source.original, originalBox);
134
+ const size = zoomSize(crop, budget);
135
+ const zoomed = resample(crop, size);
136
+ const b = clamped.box;
137
+ return {
138
+ ok: true,
139
+ viewBox: b,
140
+ originalBox,
141
+ png: encodePngImage(zoomed),
142
+ size,
143
+ text: `Zoomed into (${b.x1},${b.y1})-(${b.x2},${b.y2}) of the image you see at ${source.view.width}x${source.view.height}px: a ${crop.width}x${crop.height}px region of the original, returned magnified to ${size.width}x${size.height}px.`
144
+ };
145
+ }
146
+ //#endregion
147
+ export { cropImage, decodeImage, encodePngImage, prepareZoomSource, resample, zoomInto };
@@ -0,0 +1,129 @@
1
+ import { Box, ImageBudget, ZoomCoordinates } from "./zoom-geometry.mjs";
2
+
3
+ //#region src/zoom-loop.d.ts
4
+ type ZoomPart = {
5
+ type: "text";
6
+ text: string;
7
+ } | {
8
+ type: "image";
9
+ png: Buffer;
10
+ };
11
+ interface ZoomCall {
12
+ /** Provider call id (native), or a synthetic one (text protocol). */
13
+ id: string;
14
+ imageIndex: number;
15
+ box: Box;
16
+ /** Set when the provider's arguments did not parse; the loop answers with it. */
17
+ error?: string;
18
+ }
19
+ interface ZoomResult {
20
+ callId: string;
21
+ /** Text first, then the magnified crop when the zoom succeeded. */
22
+ parts: ZoomPart[];
23
+ isError: boolean;
24
+ }
25
+ type ZoomTurn = {
26
+ role: "user";
27
+ parts: ZoomPart[];
28
+ } | {
29
+ role: "assistant";
30
+ text: string;
31
+ calls: ZoomCall[]; /** The provider's own assistant message, so a driver can replay it verbatim. */
32
+ raw?: unknown;
33
+ } | {
34
+ role: "tool"; /** True when the results answer native function calls; false for the text protocol. */
35
+ native: boolean;
36
+ results: ZoomResult[];
37
+ };
38
+ interface ZoomUsage {
39
+ promptTokens: number;
40
+ completionTokens: number;
41
+ }
42
+ interface DriverTurn {
43
+ text: string;
44
+ calls: ZoomCall[];
45
+ raw?: unknown;
46
+ usage?: ZoomUsage;
47
+ /** The provider stopped for its own reason (length, refusal) — not a finished answer. */
48
+ stop?: string;
49
+ }
50
+ interface ZoomToolSpec {
51
+ name: "zoom";
52
+ description: string;
53
+ /** JSON Schema of the arguments. */
54
+ parameters: Record<string, unknown>;
55
+ }
56
+ interface VisionChatDriver {
57
+ model: string;
58
+ /** True when the driver maps `ZoomToolSpec` onto the provider's function calling. */
59
+ nativeTools: boolean;
60
+ /** `tool` is omitted on the wrap-up turn, when the model must answer from what it has seen. */
61
+ turn(transcript: readonly ZoomTurn[], options: {
62
+ tool?: ZoomToolSpec;
63
+ maxTokens: number;
64
+ }): Promise<DriverTurn>;
65
+ }
66
+ interface ZoomImageInput {
67
+ png: Buffer;
68
+ /** Shown before the image, e.g. "Baseline screenshot". */
69
+ label?: string;
70
+ }
71
+ interface ZoomLoopOptions {
72
+ /** Zoom calls allowed before the model must answer (default 6). */
73
+ maxZooms?: number;
74
+ maxTokens?: number;
75
+ budget?: ImageBudget;
76
+ coordinates?: ZoomCoordinates;
77
+ /** Force the text protocol even when the driver has native tools. */
78
+ protocol?: "native" | "text";
79
+ }
80
+ interface ZoomLoopResult {
81
+ answer: string;
82
+ zooms: {
83
+ imageIndex: number;
84
+ viewBox: Box;
85
+ originalBox: Box;
86
+ }[];
87
+ /** Calls the loop refused (bad box, unknown image) — told to the model, not thrown. */
88
+ rejected: {
89
+ call: ZoomCall;
90
+ reason: string;
91
+ }[];
92
+ turns: number;
93
+ /** True when the zoom budget ran out and the model was asked to answer. */
94
+ wrappedUp: boolean;
95
+ protocol: "native" | "text";
96
+ usage: ZoomUsage;
97
+ /** Set when the provider stopped for its own reason on the last turn. */
98
+ stop?: string;
99
+ }
100
+ declare function zoomToolSpec(imageCount: number, coordinates: ZoomCoordinates): ZoomToolSpec;
101
+ /** Arguments a native call carried, whatever shape the provider gave them in. */
102
+ declare function zoomCallFromArgs(id: string, args: unknown): ZoomCall | {
103
+ id: string;
104
+ error: string;
105
+ };
106
+ /**
107
+ * Zoom requests written in a reply, one `ZOOM <image> <x1> <y1> <x2> <y2>` per line. The
108
+ * image index is always written, even with one image, so the grammar has one shape.
109
+ */
110
+ declare function parseZoomRequests(text: string, turn: number): ZoomCall[];
111
+ interface SingleLookResult {
112
+ answer: string;
113
+ usage: ZoomUsage;
114
+ stop?: string;
115
+ }
116
+ /**
117
+ * The control arm of a zoom measurement: the same driver, the same images resized to the same
118
+ * budget, the same labels and question — and one turn with no tool. Comparing this against
119
+ * `runZoomLoop` isolates what zooming adds; comparing against a different client would also
120
+ * measure the difference between two request builders.
121
+ */
122
+ declare function runSingleLook(driver: VisionChatDriver, images: readonly ZoomImageInput[], question: string, options?: Pick<ZoomLoopOptions, "maxTokens" | "budget" | "coordinates">): Promise<SingleLookResult>;
123
+ /**
124
+ * Run the loop. `images` are PNGs at any size; each is shown at `budget` and labelled with its
125
+ * index and size. The answer is the model's last reply with no zoom request.
126
+ */
127
+ declare function runZoomLoop(driver: VisionChatDriver, images: readonly ZoomImageInput[], question: string, options?: ZoomLoopOptions): Promise<ZoomLoopResult>;
128
+ //#endregion
129
+ export { DriverTurn, SingleLookResult, VisionChatDriver, ZoomCall, ZoomImageInput, ZoomLoopOptions, ZoomLoopResult, ZoomPart, ZoomResult, ZoomToolSpec, ZoomTurn, ZoomUsage, parseZoomRequests, runSingleLook, runZoomLoop, zoomCallFromArgs, zoomToolSpec };
@@ -0,0 +1,314 @@
1
+ import { DEFAULT_IMAGE_BUDGET, toViewBox } from "./zoom-geometry.mjs";
2
+ import { prepareZoomSource, zoomInto } from "./zoom-image.mjs";
3
+ //#region src/zoom-loop.ts
4
+ /**
5
+ * The zoom loop, independent of any provider: show the model its images at a size we chose,
6
+ * give it one tool — `zoom(image, x1, y1, x2, y2)` — and answer each call with a magnified crop
7
+ * of the original, until it answers the question or spends its zoom budget.
8
+ *
9
+ * A provider enters only through `VisionChatDriver`: one function that takes the transcript so
10
+ * far and returns the model's next turn. Two ways for the model to ask for a zoom, so any vision
11
+ * model can use it:
12
+ *
13
+ * - `native`: the provider's own function calling (OpenAI-compatible `tools`, Anthropic
14
+ * `tool_use`, Gemini `functionCall`). The driver declares `nativeTools`.
15
+ * - `text`: a protocol in the reply itself — a line `ZOOM <image> <x1> <y1> <x2> <y2>` —
16
+ * for models with no function calling (most small open VLMs). `parseZoomRequests` reads it.
17
+ *
18
+ * How a result carries its image is the driver's business, because providers disagree: some
19
+ * accept an image inside the tool result, OpenAI-compatible APIs only accept text there, so
20
+ * those drivers send the crop as a user image right after it. The loop hands every driver the
21
+ * same `ZoomResult`.
22
+ */
23
+ function zoomToolSpec(imageCount, coordinates) {
24
+ const unit = coordinates === "pixels" ? "in pixels of the image as you see it (origin top-left, x right, y down)" : "as 0-1000 of the image's width (x) and height (y), origin top-left";
25
+ return {
26
+ name: "zoom",
27
+ description: "Crop a region of an image and see it magnified from the full-resolution original. Use it for any detail too small to read with confidence: small text, thin lines, the exact colour or edge of an element.",
28
+ parameters: {
29
+ type: "object",
30
+ properties: {
31
+ ...imageCount > 1 ? { image_index: {
32
+ type: "integer",
33
+ description: `Which image, counting from 0 (0-${imageCount - 1})`
34
+ } } : {},
35
+ x1: {
36
+ type: "number",
37
+ description: `Left edge, ${unit}`
38
+ },
39
+ y1: {
40
+ type: "number",
41
+ description: "Top edge"
42
+ },
43
+ x2: {
44
+ type: "number",
45
+ description: "Right edge (greater than x1)"
46
+ },
47
+ y2: {
48
+ type: "number",
49
+ description: "Bottom edge (greater than y1)"
50
+ }
51
+ },
52
+ required: [
53
+ "x1",
54
+ "y1",
55
+ "x2",
56
+ "y2"
57
+ ],
58
+ additionalProperties: false
59
+ }
60
+ };
61
+ }
62
+ /** Arguments a native call carried, whatever shape the provider gave them in. */
63
+ function zoomCallFromArgs(id, args) {
64
+ let value = args;
65
+ if (typeof value === "string") try {
66
+ value = JSON.parse(value);
67
+ } catch {
68
+ return {
69
+ id,
70
+ error: "arguments are not valid JSON"
71
+ };
72
+ }
73
+ const a = value ?? {};
74
+ const num = (k) => typeof a[k] === "number" ? a[k] : typeof a[k] === "string" ? Number(a[k]) : NaN;
75
+ const box = {
76
+ x1: num("x1"),
77
+ y1: num("y1"),
78
+ x2: num("x2"),
79
+ y2: num("y2")
80
+ };
81
+ if (![
82
+ box.x1,
83
+ box.y1,
84
+ box.x2,
85
+ box.y2
86
+ ].every(Number.isFinite)) return {
87
+ id,
88
+ error: "x1, y1, x2 and y2 are required numbers"
89
+ };
90
+ const index = a.image_index === void 0 ? 0 : num("image_index");
91
+ return {
92
+ id,
93
+ imageIndex: Number.isFinite(index) ? Math.trunc(index) : NaN,
94
+ box
95
+ };
96
+ }
97
+ const ZOOM_LINE = /^\s*ZOOM\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s*$/gim;
98
+ /**
99
+ * Zoom requests written in a reply, one `ZOOM <image> <x1> <y1> <x2> <y2>` per line. The
100
+ * image index is always written, even with one image, so the grammar has one shape.
101
+ */
102
+ function parseZoomRequests(text, turn) {
103
+ const calls = [];
104
+ for (const m of text.matchAll(ZOOM_LINE)) calls.push({
105
+ id: `text-${turn}-${calls.length}`,
106
+ imageIndex: Math.trunc(Number(m[1])),
107
+ box: {
108
+ x1: Number(m[2]),
109
+ y1: Number(m[3]),
110
+ x2: Number(m[4]),
111
+ y2: Number(m[5])
112
+ }
113
+ });
114
+ return calls;
115
+ }
116
+ function textProtocolInstructions(coordinates) {
117
+ return `You can zoom: to see a region magnified from the full-resolution original, reply with only lines of the form
118
+ ZOOM <image> <x1> <y1> <x2> <y2>
119
+ where <image> counts from 0 and the box is in ${coordinates === "pixels" ? "pixels of the image as you see it" : "0-1000 of the image's width and height"} (origin top-left). You will get the magnified regions back. When you can answer, reply with the answer and no ZOOM line.`;
120
+ }
121
+ /** The opening message: each image labelled with its index and the size it is shown at, then the question. */
122
+ function introParts(images, sources, question, coordinates, instructions) {
123
+ const intro = [];
124
+ sources.forEach((src, i) => {
125
+ const label = images[i].label ? `${images[i].label} — ` : "";
126
+ intro.push({
127
+ type: "text",
128
+ text: `${label}Image ${i} (${src.view.width}x${src.view.height} pixels):`
129
+ });
130
+ intro.push({
131
+ type: "image",
132
+ png: src.viewPng
133
+ });
134
+ });
135
+ const coordNote = coordinates === "pixels" ? "Coordinates are absolute pixels of the image as shown, origin top-left." : "Coordinates are 0-1000 of each image's width and height, origin top-left.";
136
+ intro.push({
137
+ type: "text",
138
+ text: `${question}\n\n${coordNote}${instructions ? ` ${instructions}` : ""}`
139
+ });
140
+ return intro;
141
+ }
142
+ /**
143
+ * The control arm of a zoom measurement: the same driver, the same images resized to the same
144
+ * budget, the same labels and question — and one turn with no tool. Comparing this against
145
+ * `runZoomLoop` isolates what zooming adds; comparing against a different client would also
146
+ * measure the difference between two request builders.
147
+ */
148
+ async function runSingleLook(driver, images, question, options = {}) {
149
+ if (images.length === 0) throw new RangeError("runSingleLook needs at least one image");
150
+ const budget = options.budget ?? DEFAULT_IMAGE_BUDGET;
151
+ const intro = introParts(images, images.map((img) => prepareZoomSource(img.png, budget)), question, options.coordinates ?? "pixels", "");
152
+ const reply = await driver.turn([{
153
+ role: "user",
154
+ parts: intro
155
+ }], { maxTokens: options.maxTokens ?? 2048 });
156
+ return {
157
+ answer: reply.text.trim(),
158
+ usage: {
159
+ promptTokens: reply.usage?.promptTokens ?? 0,
160
+ completionTokens: reply.usage?.completionTokens ?? 0
161
+ },
162
+ ...reply.stop ? { stop: reply.stop } : {}
163
+ };
164
+ }
165
+ /**
166
+ * Run the loop. `images` are PNGs at any size; each is shown at `budget` and labelled with its
167
+ * index and size. The answer is the model's last reply with no zoom request.
168
+ */
169
+ async function runZoomLoop(driver, images, question, options = {}) {
170
+ if (images.length === 0) throw new RangeError("runZoomLoop needs at least one image");
171
+ const budget = options.budget ?? DEFAULT_IMAGE_BUDGET;
172
+ const coordinates = options.coordinates ?? "pixels";
173
+ const maxZooms = Math.max(0, options.maxZooms ?? 6);
174
+ const maxTokens = options.maxTokens ?? 2048;
175
+ const protocol = options.protocol ?? (driver.nativeTools ? "native" : "text");
176
+ if (protocol === "native" && !driver.nativeTools) throw new Error(`${driver.model}: this driver has no native tools; use protocol "text"`);
177
+ const sources = images.map((img) => prepareZoomSource(img.png, budget));
178
+ const transcript = [{
179
+ role: "user",
180
+ parts: introParts(images, sources, question, coordinates, protocol === "native" ? "Use the zoom tool to examine any detail too small to read confidently." : textProtocolInstructions(coordinates))
181
+ }];
182
+ const tool = zoomToolSpec(images.length, coordinates);
183
+ const usage = {
184
+ promptTokens: 0,
185
+ completionTokens: 0
186
+ };
187
+ const zooms = [];
188
+ const rejected = [];
189
+ let turns = 0;
190
+ let wrappedUp = false;
191
+ for (;;) {
192
+ const offerTool = !wrappedUp;
193
+ const reply = await driver.turn(transcript, {
194
+ ...offerTool && protocol === "native" ? { tool } : {},
195
+ maxTokens
196
+ });
197
+ turns++;
198
+ usage.promptTokens += reply.usage?.promptTokens ?? 0;
199
+ usage.completionTokens += reply.usage?.completionTokens ?? 0;
200
+ const calls = protocol === "native" ? reply.calls : parseZoomRequests(reply.text, turns);
201
+ const done = (answer) => ({
202
+ answer,
203
+ zooms,
204
+ rejected,
205
+ turns,
206
+ wrappedUp,
207
+ protocol,
208
+ usage,
209
+ ...reply.stop ? { stop: reply.stop } : {}
210
+ });
211
+ if (calls.length === 0 || wrappedUp) return done(protocol === "text" ? reply.text.replace(ZOOM_LINE, "").trim() : reply.text.trim());
212
+ transcript.push({
213
+ role: "assistant",
214
+ text: reply.text,
215
+ calls,
216
+ ...reply.raw !== void 0 ? { raw: reply.raw } : {}
217
+ });
218
+ const results = [];
219
+ for (const call of calls) {
220
+ if (zooms.length >= maxZooms) {
221
+ results.push({
222
+ callId: call.id,
223
+ isError: true,
224
+ parts: [{
225
+ type: "text",
226
+ text: "Zoom budget used up; answer from what you have seen."
227
+ }]
228
+ });
229
+ continue;
230
+ }
231
+ if (call.error) {
232
+ rejected.push({
233
+ call,
234
+ reason: call.error
235
+ });
236
+ results.push({
237
+ callId: call.id,
238
+ isError: true,
239
+ parts: [{
240
+ type: "text",
241
+ text: `Error: ${call.error}`
242
+ }]
243
+ });
244
+ continue;
245
+ }
246
+ const source = sources[call.imageIndex];
247
+ if (!source) {
248
+ const reason = `no image ${call.imageIndex} (there are ${sources.length}, counting from 0)`;
249
+ rejected.push({
250
+ call,
251
+ reason
252
+ });
253
+ results.push({
254
+ callId: call.id,
255
+ isError: true,
256
+ parts: [{
257
+ type: "text",
258
+ text: `Error: ${reason}`
259
+ }]
260
+ });
261
+ continue;
262
+ }
263
+ const outcome = zoomInto(source, toViewBox(call.box, source.view, coordinates), budget);
264
+ if (!outcome.ok) {
265
+ rejected.push({
266
+ call,
267
+ reason: outcome.text
268
+ });
269
+ results.push({
270
+ callId: call.id,
271
+ isError: true,
272
+ parts: [{
273
+ type: "text",
274
+ text: outcome.text
275
+ }]
276
+ });
277
+ continue;
278
+ }
279
+ zooms.push({
280
+ imageIndex: call.imageIndex,
281
+ viewBox: outcome.viewBox,
282
+ originalBox: outcome.originalBox
283
+ });
284
+ results.push({
285
+ callId: call.id,
286
+ isError: false,
287
+ parts: [{
288
+ type: "text",
289
+ text: outcome.text
290
+ }, {
291
+ type: "image",
292
+ png: outcome.png
293
+ }]
294
+ });
295
+ }
296
+ transcript.push({
297
+ role: "tool",
298
+ native: protocol === "native",
299
+ results
300
+ });
301
+ if (zooms.length >= maxZooms || turns >= maxZooms + 3) {
302
+ wrappedUp = true;
303
+ transcript.push({
304
+ role: "user",
305
+ parts: [{
306
+ type: "text",
307
+ text: "You have used your zoom budget. Answer the original question now, based on everything you have seen."
308
+ }]
309
+ });
310
+ }
311
+ }
312
+ }
313
+ //#endregion
314
+ export { parseZoomRequests, runSingleLook, runZoomLoop, zoomCallFromArgs, zoomToolSpec };
@@ -0,0 +1,29 @@
1
+ import { VlmModel, VlmResponse } from "./vlm-client.mjs";
2
+ import { Box, BoxProblem, DEFAULT_IMAGE_BUDGET, ImageBudget, Size, ZoomCoordinates, clampBox, fitToBudget, toViewBox, viewBoxToOriginal, zoomSize } from "./zoom-geometry.mjs";
3
+ import { DriverTurn, SingleLookResult, VisionChatDriver, ZoomCall, ZoomImageInput, ZoomLoopOptions, ZoomLoopResult, ZoomPart, ZoomResult, ZoomToolSpec, ZoomTurn, ZoomUsage, parseZoomRequests, runSingleLook, runZoomLoop, zoomCallFromArgs, zoomToolSpec } from "./zoom-loop.mjs";
4
+ import { ZoomOutcome, ZoomSource, prepareZoomSource, zoomInto } from "./zoom-image.mjs";
5
+ import { AnthropicDriverOptions, GeminiDriverOptions, OpenAiCompatibleDriverOptions, anthropicDriver, geminiDriver, openAiCompatibleDriver } from "./zoom-drivers.mjs";
6
+
7
+ //#region src/zoom.d.ts
8
+ interface ZoomDriverOptions {
9
+ /** Overrides the environment key lookup, as in `createVlmClient`. */
10
+ apiKey?: string;
11
+ /** OpenRouter only: false for a model without function calling (the loop then uses the text protocol). */
12
+ nativeTools?: boolean;
13
+ }
14
+ /** A driver for a model id, with the same key lookup and error as `createVlmClient`. */
15
+ declare function createZoomDriver(model: VlmModel, options?: ZoomDriverOptions): VisionChatDriver;
16
+ interface ZoomAnalysis extends VlmResponse {
17
+ zoom: Omit<ZoomLoopResult, "answer" | "usage">;
18
+ }
19
+ /**
20
+ * Ask a question about one or more PNG screenshots, letting the model zoom. Same shape as a
21
+ * `VlmClient` response (content, tokens, cost, latency) plus what the model zoomed into, so a
22
+ * bench can put it beside a single-look answer.
23
+ */
24
+ declare function analyzeWithZoom(model: VlmModel, images: readonly {
25
+ png: Buffer;
26
+ label?: string;
27
+ }[], prompt: string, options?: ZoomLoopOptions & ZoomDriverOptions): Promise<ZoomAnalysis>;
28
+ //#endregion
29
+ export { AnthropicDriverOptions, Box, BoxProblem, DEFAULT_IMAGE_BUDGET, DriverTurn, GeminiDriverOptions, ImageBudget, OpenAiCompatibleDriverOptions, SingleLookResult, Size, VisionChatDriver, ZoomAnalysis, ZoomCall, ZoomCoordinates, ZoomDriverOptions, ZoomImageInput, ZoomLoopOptions, ZoomLoopResult, type ZoomOutcome, ZoomPart, ZoomResult, type ZoomSource, ZoomToolSpec, ZoomTurn, ZoomUsage, analyzeWithZoom, anthropicDriver, clampBox, createZoomDriver, fitToBudget, geminiDriver, openAiCompatibleDriver, parseZoomRequests, prepareZoomSource, runSingleLook, runZoomLoop, toViewBox, viewBoxToOriginal, zoomCallFromArgs, zoomInto, zoomSize, zoomToolSpec };
package/dist/zoom.mjs ADDED
@@ -0,0 +1,61 @@
1
+ import { VrtConfigError } from "./errors.mjs";
2
+ import { isClaudeDirectModel, isGeminiDirectModel } from "./vlm-client.mjs";
3
+ import { DEFAULT_IMAGE_BUDGET, clampBox, fitToBudget, toViewBox, viewBoxToOriginal, zoomSize } from "./zoom-geometry.mjs";
4
+ import { prepareZoomSource, zoomInto } from "./zoom-image.mjs";
5
+ import { parseZoomRequests, runSingleLook, runZoomLoop, zoomCallFromArgs, zoomToolSpec } from "./zoom-loop.mjs";
6
+ import { anthropicDriver, geminiDriver, openAiCompatibleDriver } from "./zoom-drivers.mjs";
7
+ //#region src/zoom.ts
8
+ /**
9
+ * Zoom for any VLM this package already knows: the model ids `createVlmClient` takes
10
+ * (`claude:…`, `gemini:…`, an OpenRouter id) resolve to a zoom driver with the same keys, so a
11
+ * caller switches a question from one look to "look, then zoom where it matters" by changing
12
+ * one call.
13
+ *
14
+ * Also usable with a self-hosted OpenAI-compatible server (vLLM, Ollama, LM Studio): build
15
+ * `openAiCompatibleDriver({ url, model })` and hand it to `runZoomLoop` directly.
16
+ */
17
+ /** A driver for a model id, with the same key lookup and error as `createVlmClient`. */
18
+ function createZoomDriver(model, options = {}) {
19
+ const need = (value, name) => {
20
+ if (!value) throw new VrtConfigError("MISSING_KEY", `${name} is required for ${model.id}`);
21
+ return value;
22
+ };
23
+ if (isGeminiDirectModel(model.id)) return geminiDriver({
24
+ model: model.id.replace("gemini:", ""),
25
+ apiKey: need(options.apiKey ?? process.env.GEMINI_API_KEY ?? process.env.GOOGLE_AI_API_KEY, "GEMINI_API_KEY (or GOOGLE_AI_API_KEY)")
26
+ });
27
+ if (isClaudeDirectModel(model.id)) return anthropicDriver({
28
+ model: model.id.replace("claude:", ""),
29
+ apiKey: need(options.apiKey ?? process.env.ANTHROPIC_API_KEY, "ANTHROPIC_API_KEY")
30
+ });
31
+ return openAiCompatibleDriver({
32
+ model: model.id,
33
+ apiKey: need(options.apiKey ?? process.env.OPENROUTER_API_KEY, "OPENROUTER_API_KEY"),
34
+ headers: {
35
+ "HTTP-Referer": "https://github.com/mizchi/vrt",
36
+ "X-Title": "vrt"
37
+ },
38
+ ...options.nativeTools !== void 0 ? { nativeTools: options.nativeTools } : {}
39
+ });
40
+ }
41
+ /**
42
+ * Ask a question about one or more PNG screenshots, letting the model zoom. Same shape as a
43
+ * `VlmClient` response (content, tokens, cost, latency) plus what the model zoomed into, so a
44
+ * bench can put it beside a single-look answer.
45
+ */
46
+ async function analyzeWithZoom(model, images, prompt, options = {}) {
47
+ const start = Date.now();
48
+ const { answer, usage, ...zoom } = await runZoomLoop(createZoomDriver(model, options), images, prompt, options);
49
+ return {
50
+ content: answer,
51
+ model: model.id,
52
+ promptTokens: usage.promptTokens,
53
+ completionTokens: usage.completionTokens,
54
+ totalTokens: usage.promptTokens + usage.completionTokens,
55
+ costUsd: usage.promptTokens / 1e3 * model.promptCostPer1k + usage.completionTokens / 1e3 * model.completionCostPer1k,
56
+ latencyMs: Date.now() - start,
57
+ zoom
58
+ };
59
+ }
60
+ //#endregion
61
+ export { DEFAULT_IMAGE_BUDGET, analyzeWithZoom, anthropicDriver, clampBox, createZoomDriver, fitToBudget, geminiDriver, openAiCompatibleDriver, parseZoomRequests, prepareZoomSource, runSingleLook, runZoomLoop, toViewBox, viewBoxToOriginal, zoomCallFromArgs, zoomInto, zoomSize, zoomToolSpec };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mizchi/vlmkit-ai",
3
- "version": "0.11.1",
3
+ "version": "0.23.0",
4
4
  "description": "VLM / LLM clients, reasoning pipeline, and NLP helpers used by VRT to interpret diff images and natural-language intent.",
5
5
  "license": "MIT",
6
6
  "author": "mizchi",
@@ -37,7 +37,8 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "@google/generative-ai": "^0.24.1",
40
- "@mizchi/vlmkit-core": "0.11.1"
40
+ "pngjs": "^7.0.0",
41
+ "@mizchi/vlmkit-core": "0.23.0"
41
42
  },
42
43
  "scripts": {
43
44
  "build": "pnpm --dir ../.. exec tsdown --config tsdown.packages.config.ts --filter @mizchi/vlmkit-ai",