@mizchi/vlmkit-ai 0.9.1 → 0.11.1

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
@@ -1,8 +1,8 @@
1
1
  import { VrtConfigError, VrtConfigErrorCode } from "./errors.mjs";
2
2
  import { CreateImageGenClientOptions, ImageGenBackground, ImageGenClient, ImageGenModel, ImageGenOutputFormat, ImageGenQuality, ImageGenRequest, ImageGenRequestBody, ImageGenResponse, ImageGenSize, ImageGenUsage, ParsedGeneration, buildGenerationBody, createImageGenClient, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel } from "./image-gen-client.mjs";
3
3
  import { LLMProvider, buildIntent, buildIntentWithLLM, buildReasoningPrompt, extractDiffSemantics, parseDiff } from "./intent.mjs";
4
- import { CreateLLMProviderOptions, ImageContent, LLMClientOptions, LLMProviderName, LLMResponse, MessageContent, TextContent, UnifiedLLMClient, createLLMProvider, createUnifiedLLMClient } from "./llm-client.mjs";
4
+ import { CreateLLMProviderOptions, ImageContent, LLMClientOptions, LLMProviderName, LLMResponse, MessageContent, OPENAI_DEFAULT_MODEL, TextContent, UnifiedLLMClient, createLLMProvider, createUnifiedLLMClient } from "./llm-client.mjs";
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, 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
+ 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 };
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import { VrtConfigError } from "./errors.mjs";
2
2
  import { buildGenerationBody, createImageGenClient, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel } from "./image-gen-client.mjs";
3
- import { createLLMProvider, createUnifiedLLMClient } from "./llm-client.mjs";
3
+ import { OPENAI_DEFAULT_MODEL, createLLMProvider, createUnifiedLLMClient } from "./llm-client.mjs";
4
4
  import { createVlmClient, fetchVisionModels, isGeminiDirectModel, listGeminiModels, listModels, resolveGeminiModel, resolveModel } from "./vlm-client.mjs";
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 { VrtConfigError, buildGenerationBody, buildIntent, buildIntentWithLLM, buildReasoningPrompt, createImageGenClient, createLLMProvider, createReasoningPipeline, createUnifiedLLMClient, createVlmClient, estimateImageGenCost, extractDiffSemantics, fetchVisionModels, isGeminiDirectModel, listGeminiModels, listImageGenModels, listModels, parseDiff, parseGenerationResponse, reasonAboutChanges, resolveGeminiModel, resolveImageGenModel, resolveModel };
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 };
@@ -55,6 +55,20 @@ interface UnifiedLLMClient {
55
55
  model: string;
56
56
  }
57
57
  type LLMProviderName = "gemini" | "anthropic" | "openrouter";
58
+ /**
59
+ * The OpenAI model this project reaches for by default, and the one place its id is written.
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.
65
+ *
66
+ * Exported so the docs can be pinned to it. `tests/agent-model-defaults.test.mjs` asserts that
67
+ * `AGENTS.md`, `.claude/CLAUDE.md` and `docs/configuration.md` all name this exact model, because
68
+ * the defect this constant came from was an agent reading a document and picking something the
69
+ * code does not accept.
70
+ */
71
+ declare const OPENAI_DEFAULT_MODEL = "openai/gpt-5.6-luna";
58
72
  /**
59
73
  * Create a unified LLM client.
60
74
  *
@@ -84,4 +98,4 @@ interface CreateLLMProviderOptions {
84
98
  */
85
99
  declare function createLLMProvider(options?: CreateLLMProviderOptions): LLMProvider | null;
86
100
  //#endregion
87
- export { CreateLLMProviderOptions, ImageContent, LLMClientOptions, LLMProviderName, LLMResponse, MessageContent, TextContent, UnifiedLLMClient, createLLMProvider, createUnifiedLLMClient };
101
+ export { CreateLLMProviderOptions, ImageContent, LLMClientOptions, LLMProviderName, LLMResponse, MessageContent, OPENAI_DEFAULT_MODEL, TextContent, UnifiedLLMClient, createLLMProvider, createUnifiedLLMClient };
@@ -217,6 +217,29 @@ const VALID_PROVIDERS = new Set([
217
217
  "openrouter"
218
218
  ]);
219
219
  /**
220
+ * The OpenAI model this project reaches for by default, and the one place its id is written.
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.
226
+ *
227
+ * Exported so the docs can be pinned to it. `tests/agent-model-defaults.test.mjs` asserts that
228
+ * `AGENTS.md`, `.claude/CLAUDE.md` and `docs/configuration.md` all name this exact model, because
229
+ * the defect this constant came from was an agent reading a document and picking something the
230
+ * code does not accept.
231
+ */
232
+ const OPENAI_DEFAULT_MODEL = "openai/gpt-5.6-luna";
233
+ /**
234
+ * Names an agent reaches for when it wants OpenAI and finds no `openai` provider.
235
+ *
236
+ * Measured, not guessed: an OpenAI-based agent working in this repo set
237
+ * `VLMKIT_LLM_PROVIDER=openai`, got `Expected: gemini | anthropic | openrouter`, and stopped —
238
+ * the message listed the three valid names and said nothing about where OpenAI models live, so
239
+ * there was nothing to act on. `o\d` covers the reasoning line (`o3`, `o4-mini`).
240
+ */
241
+ const OPENAI_SHAPED_NAME = /^(openai|oai|gpt|chatgpt|codex|o\d)/i;
242
+ /**
220
243
  * Resolve provider and key from environment variables.
221
244
  *
222
245
  * VLMKIT_LLM_PROVIDER: gemini (default) | anthropic | openrouter
@@ -224,16 +247,39 @@ const VALID_PROVIDERS = new Set([
224
247
  *
225
248
  * Returns a config, or describes why no config was available. The
226
249
  * factory decides whether to throw based on `throwIfMissing`.
250
+ *
251
+ * ## An unrequested provider is chosen from the keys you have
252
+ *
253
+ * This used to be `options?.provider ?? readEnv("LLM_PROVIDER") ?? "gemini"` with no
254
+ * regard for which keys existed, so a caller that expressed no preference got gemini and
255
+ * then a `MISSING_KEY` naming a key it did not need. Measured with exactly one key set:
256
+ *
257
+ * ANTHROPIC_API_KEY only → MISSING_KEY: GEMINI_API_KEY (or GOOGLE_AI_API_KEY) is required
258
+ * OPENROUTER_API_KEY only → MISSING_KEY: GEMINI_API_KEY (or GOOGLE_AI_API_KEY) is required
259
+ *
260
+ * while `createLLMProvider`, twenty lines further down this same file, returned a working
261
+ * client for both. Being told to obtain a key you do not need, while the one you have is
262
+ * ignored, sends the reader to the wrong fix.
263
+ *
264
+ * Every caller had already worked around it, in four different ways, which is what made
265
+ * this worth changing rather than leaving: `createLLMProvider` and
266
+ * `reasoning-pipeline.ts` each carry a byte-identical `["gemini", "anthropic",
267
+ * "openrouter"]` retry loop, and `vlmkit-plan` and `vlmkit-generate` each carry a
268
+ * byte-identical `resolveDefaultProvider` that picks by key presence before calling in.
269
+ * Four workarounds for one missing behaviour is the shared function being wrong, and the
270
+ * fifth caller is the one that pays for it — the same shape as eight modules hand-rolling
271
+ * `isUrlSource`.
272
+ *
273
+ * **An explicit request is still honoured exactly.** `{ provider: "gemini" }` or
274
+ * `VLMKIT_LLM_PROVIDER=gemini` with no Gemini key is a `MISSING_KEY` for *gemini*, not a
275
+ * silent substitution — asking for a specific provider and quietly getting another is its
276
+ * own kind of wrong answer. `createLLMProvider` deliberately does substitute, which is
277
+ * why its retry loop survives this change and is not redundant.
278
+ *
279
+ * The documented default is unchanged: gemini is first in the preference order, so a
280
+ * Gemini key present still means gemini.
227
281
  */
228
282
  function resolveProviderConfig(options) {
229
- const rawProvider = options?.provider ?? readEnv("LLM_PROVIDER") ?? "gemini";
230
- if (!VALID_PROVIDERS.has(rawProvider)) return {
231
- ok: false,
232
- code: "INVALID_PROVIDER",
233
- message: `Unknown VLMKIT_LLM_PROVIDER "${rawProvider}". Expected: gemini | anthropic | openrouter.`
234
- };
235
- const provider = rawProvider;
236
- const model = options?.model ?? readEnv("LLM_MODEL") ?? void 0;
237
283
  const keyMap = {
238
284
  gemini: process.env.GEMINI_API_KEY ?? process.env.GOOGLE_AI_API_KEY,
239
285
  anthropic: process.env.ANTHROPIC_API_KEY,
@@ -244,6 +290,34 @@ function resolveProviderConfig(options) {
244
290
  anthropic: "ANTHROPIC_API_KEY",
245
291
  openrouter: "OPENROUTER_API_KEY"
246
292
  };
293
+ /** Gemini first, so the documented default wins whenever its key is present. */
294
+ const PREFERENCE = [
295
+ "gemini",
296
+ "anthropic",
297
+ "openrouter"
298
+ ];
299
+ const requested = options?.provider ?? readEnv("LLM_PROVIDER");
300
+ const model = options?.model ?? readEnv("LLM_MODEL") ?? void 0;
301
+ if (requested === void 0) {
302
+ const provider = PREFERENCE.find((p) => keyMap[p]);
303
+ if (!provider) return {
304
+ ok: false,
305
+ code: "MISSING_KEY",
306
+ message: `No LLM API key found. Set one of: ${PREFERENCE.map((p) => envVarName[p]).join(", ")} — or pick a provider explicitly with VLMKIT_LLM_PROVIDER.`
307
+ };
308
+ return {
309
+ ok: true,
310
+ provider,
311
+ key: keyMap[provider],
312
+ model
313
+ };
314
+ }
315
+ if (!VALID_PROVIDERS.has(requested)) return {
316
+ ok: false,
317
+ code: "INVALID_PROVIDER",
318
+ message: `Unknown VLMKIT_LLM_PROVIDER "${requested}". Expected: gemini | anthropic | openrouter.${OPENAI_SHAPED_NAME.test(String(requested)) ? ` OpenAI models are served through OpenRouter, not by a provider of their own: VLMKIT_LLM_PROVIDER=openrouter VLMKIT_LLM_MODEL=${OPENAI_DEFAULT_MODEL} (needs OPENROUTER_API_KEY).` : ""}`
319
+ };
320
+ const provider = requested;
247
321
  const key = keyMap[provider];
248
322
  if (!key) return {
249
323
  ok: false,
@@ -308,4 +382,4 @@ function createLLMProvider(options) {
308
382
  return null;
309
383
  }
310
384
  //#endregion
311
- export { createLLMProvider, createUnifiedLLMClient };
385
+ export { OPENAI_DEFAULT_MODEL, createLLMProvider, createUnifiedLLMClient };
@@ -28,6 +28,15 @@ interface VlmClient {
28
28
  maxTokens?: number;
29
29
  }): Promise<VlmResponse>;
30
30
  }
31
+ /**
32
+ * Drop the cached OpenRouter model list.
33
+ *
34
+ * The cache is process-wide and had no way out, which matters beyond tests: the API server
35
+ * (`src/api/`) and a `--loop` run are long-lived, so a model added or repriced upstream is
36
+ * invisible to them until restart. Named after `resetGateRegistryCache`, which exists for the
37
+ * same reason on the same kind of lazily-built module state.
38
+ */
39
+ declare function resetVisionModelCache(): void;
31
40
  declare function fetchVisionModels(): Promise<VlmModel[]>;
32
41
  declare function listModels(options?: {
33
42
  maxCost?: number;
@@ -60,4 +69,4 @@ interface CreateVlmClientOptions {
60
69
  */
61
70
  declare function createVlmClient(model: VlmModel, options?: CreateVlmClientOptions): Promise<VlmClient | null>;
62
71
  //#endregion
63
- export { CreateVlmClientOptions, VlmClient, VlmModel, VlmResponse, createVlmClient, fetchVisionModels, isClaudeDirectModel, isGeminiDirectModel, listClaudeModels, listGeminiModels, listModels, resolveClaudeModel, resolveGeminiModel, resolveModel };
72
+ export { CreateVlmClientOptions, VlmClient, VlmModel, VlmResponse, createVlmClient, fetchVisionModels, isClaudeDirectModel, isGeminiDirectModel, listClaudeModels, listGeminiModels, listModels, resetVisionModelCache, resolveClaudeModel, resolveGeminiModel, resolveModel };
@@ -11,6 +11,17 @@ import { readFile } from "node:fs/promises";
11
11
  * Model list is fetched dynamically from the API.
12
12
  */
13
13
  let _cachedModels = null;
14
+ /**
15
+ * Drop the cached OpenRouter model list.
16
+ *
17
+ * The cache is process-wide and had no way out, which matters beyond tests: the API server
18
+ * (`src/api/`) and a `--loop` run are long-lived, so a model added or repriced upstream is
19
+ * invisible to them until restart. Named after `resetGateRegistryCache`, which exists for the
20
+ * same reason on the same kind of lazily-built module state.
21
+ */
22
+ function resetVisionModelCache() {
23
+ _cachedModels = null;
24
+ }
14
25
  async function fetchVisionModels() {
15
26
  if (_cachedModels) return _cachedModels;
16
27
  const res = await fetch("https://openrouter.ai/api/v1/models");
@@ -50,9 +61,9 @@ async function resolveModel(idOrIndex) {
50
61
  const partial = models.filter((m) => m.id.includes(idOrIndex));
51
62
  if (partial.length === 1) return partial[0];
52
63
  if (partial.length > 1) {
53
- const sorted = partial.sort((a, b) => a.id.length - b.id.length);
54
- if (sorted[0].id.endsWith(idOrIndex) || sorted[0].id.includes(`/${idOrIndex}`)) return sorted[0];
55
- throw new VrtConfigError("MULTIPLE_MATCHES", `Ambiguous model "${idOrIndex}". Matches: ${partial.slice(0, 5).map((m) => m.id).join(", ")}\nTip: use more specific ID, e.g. "${partial[0].id}"`);
64
+ const segmentMatches = partial.filter((m) => m.id.split("/").includes(idOrIndex));
65
+ if (segmentMatches.length === 1) return segmentMatches[0];
66
+ throw new VrtConfigError("MULTIPLE_MATCHES", `Ambiguous model "${idOrIndex}". Matches: ${(segmentMatches.length > 1 ? segmentMatches : partial).slice(0, 5).map((m) => m.id).join(", ")}\nTip: use more specific ID, e.g. "${(segmentMatches[0] ?? partial[0]).id}"`);
56
67
  }
57
68
  const idx = parseInt(idOrIndex, 10);
58
69
  if (!isNaN(idx) && idx >= 0 && idx < models.length) return models[idx];
@@ -364,8 +375,7 @@ async function createVlmClient(model, options) {
364
375
  const latencyMs = Date.now() - start;
365
376
  const usage = data.usage ?? {
366
377
  prompt_tokens: 0,
367
- completion_tokens: 0,
368
- total_tokens: 0
378
+ completion_tokens: 0
369
379
  };
370
380
  const costUsd = usage.prompt_tokens / 1e3 * model.promptCostPer1k + usage.completion_tokens / 1e3 * model.completionCostPer1k;
371
381
  return {
@@ -373,7 +383,7 @@ async function createVlmClient(model, options) {
373
383
  model: model.id,
374
384
  promptTokens: usage.prompt_tokens,
375
385
  completionTokens: usage.completion_tokens,
376
- totalTokens: usage.total_tokens,
386
+ totalTokens: usage.total_tokens ?? usage.prompt_tokens + usage.completion_tokens,
377
387
  costUsd,
378
388
  latencyMs
379
389
  };
@@ -427,4 +437,4 @@ async function createVlmClient(model, options) {
427
437
  return orClient;
428
438
  }
429
439
  //#endregion
430
- export { createVlmClient, fetchVisionModels, isClaudeDirectModel, isGeminiDirectModel, listClaudeModels, listGeminiModels, listModels, resolveClaudeModel, resolveGeminiModel, resolveModel };
440
+ export { createVlmClient, fetchVisionModels, isClaudeDirectModel, isGeminiDirectModel, listClaudeModels, listGeminiModels, listModels, resetVisionModelCache, resolveClaudeModel, resolveGeminiModel, resolveModel };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mizchi/vlmkit-ai",
3
- "version": "0.9.1",
3
+ "version": "0.11.1",
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,10 +37,10 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "@google/generative-ai": "^0.24.1",
40
- "@mizchi/vlmkit-core": "0.9.1"
40
+ "@mizchi/vlmkit-core": "0.11.1"
41
41
  },
42
42
  "scripts": {
43
43
  "build": "pnpm --dir ../.. exec tsdown --config tsdown.packages.config.ts --filter @mizchi/vlmkit-ai",
44
- "test": "node --test 'src/**/*.test.ts'"
44
+ "test": "pnpm --dir ../.. exec vitest run packages/vlmkit-ai/src"
45
45
  }
46
46
  }