@x12i/ai-profiles 4.4.0 → 4.4.2

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.
Files changed (50) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +1086 -1082
  3. package/dist/browser.d.ts +31 -0
  4. package/dist/browser.d.ts.map +1 -0
  5. package/dist/browser.js +124 -0
  6. package/dist/browser.js.map +1 -0
  7. package/dist/data/models-catalog.json +17393 -17393
  8. package/dist/data/models-profiles.bak.json +2336 -2336
  9. package/dist/data/models-profiles.json +10370 -8746
  10. package/dist/data/models-profiles.schema.json +240 -240
  11. package/dist/data/models-registry.json +11192 -10728
  12. package/dist/index.d.ts +1 -1
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/inferModelFamily.d.ts +2 -0
  17. package/dist/inferModelFamily.d.ts.map +1 -1
  18. package/dist/inferModelFamily.js +32 -1
  19. package/dist/inferModelFamily.js.map +1 -1
  20. package/package.json +90 -85
  21. package/dist/data/openrouter-models-catalog.json +0 -857
  22. package/dist/data/profiles-shortcuts.json +0 -295
  23. package/dist/isKnownProfileInput.d.ts +0 -9
  24. package/dist/isKnownProfileInput.d.ts.map +0 -1
  25. package/dist/isKnownProfileInput.js +0 -14
  26. package/dist/isKnownProfileInput.js.map +0 -1
  27. package/dist/isKnownProfileOrShortcut.d.ts +0 -6
  28. package/dist/isKnownProfileOrShortcut.d.ts.map +0 -1
  29. package/dist/isKnownProfileOrShortcut.js +0 -11
  30. package/dist/isKnownProfileOrShortcut.js.map +0 -1
  31. package/dist/legacyGraphEngineAliasMap.d.ts +0 -13
  32. package/dist/legacyGraphEngineAliasMap.d.ts.map +0 -1
  33. package/dist/legacyGraphEngineAliasMap.js +0 -16
  34. package/dist/legacyGraphEngineAliasMap.js.map +0 -1
  35. package/dist/listAIShortcuts.d.ts +0 -4
  36. package/dist/listAIShortcuts.d.ts.map +0 -1
  37. package/dist/listAIShortcuts.js +0 -12
  38. package/dist/listAIShortcuts.js.map +0 -1
  39. package/dist/profileDiscoveryMatch.d.ts +0 -15
  40. package/dist/profileDiscoveryMatch.d.ts.map +0 -1
  41. package/dist/profileDiscoveryMatch.js +0 -18
  42. package/dist/profileDiscoveryMatch.js.map +0 -1
  43. package/dist/profileInputMatch.d.ts +0 -20
  44. package/dist/profileInputMatch.d.ts.map +0 -1
  45. package/dist/profileInputMatch.js +0 -30
  46. package/dist/profileInputMatch.js.map +0 -1
  47. package/dist/profileModelFallback.d.ts +0 -13
  48. package/dist/profileModelFallback.d.ts.map +0 -1
  49. package/dist/profileModelFallback.js +0 -180
  50. package/dist/profileModelFallback.js.map +0 -1
package/README.md CHANGED
@@ -1,1082 +1,1086 @@
1
- # @x12i/ai-profiles
2
-
3
- Resolve AI profile names into concrete model choices. The package ships JSON in `src/data/` as the offline fallback. By default, registry data is fetched from public assets, validated, and cached in memory.
4
-
5
- > **v4.4** ships production routing (OpenRouter default + vendor-direct), product-line `*-latest-model` vendor routes, Gemini-backed google lanes, and **unversioned** open-assets URLs. Pin **`"@x12i/ai-profiles": "^4.4.0"`**. Upload `models-profiles.json` / `models-catalog.json` to open-assets **without** `.v4` / `.v2` suffixes.
6
- >
7
- > **v4.3** adds **`isConcreteModelId`**, **`isModelProfileReference`**, and **`toOptimixerModelProfile`** so consumers do not invent concrete-vs-profile or reasoning heuristics.
8
- >
9
- > **v3.2** adds **`normalizeInvokeModel`**, **`resolveAndNormalizeInvokeModel`**, and **`resolveAndNormalizeBundledInvokeModel`** for gateway invoke wire shape.
10
- >
11
- > **v3.0** removes legacy resolution inputs: shortcuts, bare profiles, and aliases. Only four resolution forms are accepted — `profile/choice`, vendor slug, gateway wire, and `{ provider, modelId }`. See [CHANGELOG.md](CHANGELOG.md).
12
- >
13
- > **v2.0** (still relevant): every `resolveAIProfile` call must pass `catalogLane` (`"text"`, `"image"`, …). Profile keys `deepseek` and `summarization` are gone — use `vol` and `sum`.
14
-
15
- ## Why AI profiles
16
-
17
- Any system that runs many different AI tasks—classification, architecture review, JSON extraction, tool-using agents—faces the same problem: **tasks are not interchangeable**. They differ in reasoning quality, cost sensitivity, latency, output shape (prose vs schema vs citations), and which provider traits matter (instruction following, long context, tool use).
18
-
19
- Hardcoding one model everywhere leads to one of three failures: overpaying for simple high-volume work, under-serving hard problems with a weak model, or locking the product to a single vendor with no fallback when prices or availability change.
20
-
21
- ### What a profile is
22
-
23
- An **AI profile** is **not** a model. It is a **capability contract**: a stable name for *what kind of work* you need, not *which SKU* fulfills it.
24
-
25
- When a graph node or function asks for `deep`, it means: high reasoning effort, complex work—resolve that intent to a concrete `provider` + `modelId` + runtime defaults **today**, without the caller caring whether that is Claude, GPT, or Gemini. The registry (`models-profiles.json`) is the mapping layer; profiles are the interface tasks depend on.
26
-
27
- ### Profiles vs choices
28
-
29
- | Layer | Role | Example |
30
- |-------|------|---------|
31
- | **Profile** | Semantic intent (cost, speed, reasoning tier, output mode, agentic behavior) | `cheap`, `balanced`, `json`, `agentic` |
32
- | **Choice** | Implementation option within that profile (provider, model, batch vs sync, cost/quality trade-off) | `default`, `google_floor`, `anthropic_cheap` |
33
-
34
- Every profile has a **`defaultChoice`** (recommended) and typically **two alternatives** so operators can tune without changing task code:
35
-
36
- - **Provider diversity** — Anthropic (writing/reasoning), OpenAI (code/instruction following), Google (cost, long context) within the same profile.
37
- - **Cost flexibility** — e.g. `balanced` + `google_balanced` vs `anthropic_balanced` for the same “normal work” intent.
38
- - **Capability variants** — e.g. `google_deep` when the constraint is window size, not reasoning tier alone.
39
- - **Execution mode** — e.g. `cheap` + `google_floor` with `executionMode: batch` for background bulk work.
40
- - **Resilience** — swap choice or fall back within the same profile when a provider is down or rate-limited.
41
-
42
- Tasks should declare **requirements** as explicit `profile/choice` keys (e.g. `cheap/default`), not model names. Use discovery APIs (`listAIProfiles`, `resolveAIProfileByTags`) to pick a profile when the caller does not already have a composite key.
43
-
44
- ### Graph and stored model config
45
-
46
- Graph JSON, studio defaults, and run overrides store **profile slot strings only** — never concrete provider model ids. Each task uses a complete triple:
47
-
48
- | Slot | Example | Phase |
49
- |------|---------|-------|
50
- | `preActionModel` | `deep/default` | PRE (xynthesis / planning) |
51
- | `skillModel` | `balanced/default` | MAIN (skill gateway) |
52
- | `postActionModel` | `cheap/default` | POST (xynthesis / wrap-up) |
53
-
54
- Canonical storage form is **`profile/choice`** (separator `/`). Use **`formatProfileChoiceKey(profile, choice)`** when writing slots and **`isKnownProfileInput(input)`** (or **`isKnownProfileChoice`** / **`matchStrictProfileInput`**) before persist or execute. Always include the choice segment — even for the profile default (`cheap/default`, not bare `cheap`).
55
-
56
- **Classification SSOT (do not re-implement in consumers):**
57
-
58
- | Question | API |
59
- |----------|-----|
60
- | Is this a profile-side authoring ref? | `isModelProfileReference(value)` (or strict `isKnownProfileInput` for `profile/choice` only) |
61
- | Is this a concrete catalog model? | `isConcreteModelId(value)` |
62
- | Reasoning capability? | `isReasoningModel(value)` / `resolved.modelSignals.isReasoningModel` |
63
- | Optimixer `{ provider, model, reasoning }`? | `toOptimixerModelProfile(wire)` |
64
-
65
- Never classify concrete models via vendor keywords (`gpt-`, `claude`, `gemini`) or `looksLike*` helpers — gaps belong upstream in this package.
66
-
67
- ```json
68
- "modelConfig": {
69
- "cases": [
70
- {
71
- "modelConfig": {
72
- "preActionModel": "cyber/default",
73
- "skillModel": "audit/default",
74
- "postActionModel": "cheap/default"
75
- }
76
- }
77
- ]
78
- }
79
- ```
80
-
81
- **At execute time**, hosts pass the stored alias triple unchanged; each phase resolves independently via `resolveAIProfile` (or `resolveAndNormalizeInvokeModel` at the gateway boundary). Do **not** pre-resolve aliases to concrete ids in graph JSON, `runtime.modelConfig`, or `aliasConfig`.
82
-
83
- **Forbidden in stored config:** legacy keys (`xynthesisModel`, `postStrategyModel`), legacy aliases (`default`, `strong`, `weak`), bare profile keys (`cheap`), concrete slugs (`openai/gpt-4o-mini`), and legacy `@` composites (`cheap@anthropic_cheap` — migrate to `cheap/anthropic_cheap` on save).
84
-
85
- ### Profile catalog (bundled)
86
-
87
- Profiles are grouped by **what kind of work** they represent—not only by price/quality tier. Several axes are orthogonal (structured output, agents, research, local inference).
88
-
89
- | Profile | Category | When to use it |
90
- |---------|----------|----------------|
91
- | `cheap` | cost | High-volume, non-critical work: routing, classification, simple transforms. “Cheap” means low-cost selection, not always the absolute cheapest SKU. |
92
- | `fast` | speed | Interactive UX where latency matters more than maximum reasoning depth. |
93
- | `balanced` | standard | Default workhorse: general graph execution, coding, product logic (~80% of tasks). |
94
- | `deep` | reasoning | Hard problems: architecture, planning, analysis, code review—work that needs real reasoning, not pattern matching. |
95
- | `pro` | premium | Critical outputs where quality or a wrong answer has high downstream cost; use sparingly. |
96
- | `json` | output | Strict JSON/schema, extraction, classification—machine-readable pipelines (`outputMode: schema`, low temperature). |
97
- | `agentic` | agentic | Tool use, planning, multi-step execution (`toolPolicy` allows writes with approval). |
98
- | `research` | research | Source-heavy reading, synthesis, citations (read-only tools, web/file search). |
99
- | `cyber` | security | Threat analysis, TPRM, contract verification, security log parsing. |
100
- | `content` | creative | Prose, marketing copy, programmatic SEO, brand voice. |
101
- | `sum` | analysis | Document triage, digests, compressing very large corpora. |
102
- | `vol` | agent | Volume/economic agent lane (Flash default, Pro for hard/final). |
103
- | `coding` | engineering | Software engineering: implementation, refactors, reviews, debugging. |
104
- | `extraction` | extraction | NER, classification, taxonomy mapping, entity extraction, document labeling. |
105
- | `routing` | routing | Intent classification, record routing, workflow branching (cheapest viable). |
106
- | `local` | local | **CPU only** — runtime adapters (llama.cpp, Ollama, LM Studio, vLLM, Transformers.js, ONNX). **No OpenRouter.** |
107
-
108
- ### Typical choices per profile
109
-
110
- Each profile’s `choices` in `models-profiles.json` follow a consistent pattern: **`default`** (recommended), plus variants along cost, provider family, or a specific capability.
111
-
112
- | Profile | Choices (bundled) | What the variants optimize |
113
- |---------|-------------------|------------------------------|
114
- | `cheap` | `default`, `google_floor`, `anthropic_cheap`, `deepseek_cheap`, `minimax_cheap` | Normal cheap vs batch floor vs safer Haiku vs DeepSeek volume floor vs MiniMax M2.5 |
115
- | `fast` | `default`, `google_fast`, `anthropic_fast`, `grok_fast`, `minimax_fast` | Interactive default vs lower cost vs stronger quality vs Grok vs MiniMax M2 |
116
- | `balanced` | `default`, `anthropic_balanced`, `google_balanced`, `minimax_balanced` | General default vs stronger reasoning vs lower cost vs MiniMax M2.5 |
117
- | `deep` | `default`, `openai_deep`, `google_deep`, `deepseek_pro`, `grok_flagship`, `minimax_deep` | High reasoning default vs OpenAI vs long context vs DeepSeek vs Grok vs MiniMax M2.7 |
118
- | `pro` | `default`, `claude_pro`, `anthropic_pro` | Premium default vs Claude premium vs Sonnet-level “pro-like” at lower cost |
119
- | `json` | `default`, `google_json`, `anthropic_json` | Reliable schema output vs volume/cost vs complex extraction needing reasoning |
120
- | `agentic` | `default`, `openai_agentic`, `google_agentic`, `minimax_agentic` | Agent default vs OpenAI orchestration vs lower-cost moderate agents vs MiniMax |
121
- | `research` | `default`, `openai_research`, `google_research` | Synthesis default vs highest quality vs very large context |
122
- | `cyber` | `default`, `log_analysis`, `deep_forensics` | Policy/contract review vs bulk log JSON vs max forensics |
123
- | `content` | `default`, `pseo_bulk`, `brand_voice` | Natural prose vs batch pSEO schema vs premium copy |
124
- | `sum` | `default`, `mega_context` | Fast digest (Haiku) vs multi-hundred-k token compression |
125
- | `vol` | `default`, `flash`, `pro`, `final` | Volume/economic agent lane (Flash default, Pro for hard/final) |
126
- | `local` | `llama_cpp_gguf`, `ollama`, `lmstudio_openai`, `vllm_openai`, `transformersjs_text`, `onnx_runtime` | **CPU / offline adapters** — env-probed local runtimes (no cloud LLM) |
127
-
128
- Every **remote** profile choice must resolve to an active OpenRouter catalog id. Profiles without OpenRouter support are not included (use vendor APIs outside this registry, or add catalog coverage first). The only exception is the **`local`** profile, which is explicitly CPU / self-hosted.
129
-
130
- Vendor-family profiles (`openai`, `claude`, `google`, `grok`, `deepseek`, …) also expose **`default` / `cheapest` / `best`** plus product-line **`<family>-latest-model`** choices (e.g. `google/flash-lite-latest-model`). Those choice *names* are aliases; `modelId` is always a **concrete** pinned SKU refreshed from the catalog.
131
-
132
- ### OpenRouter-only and catalog lanes
133
-
134
- Not every profile is OpenRouter-backed: **`local`** is CPU/self-hosted only (no catalog entry). All other bundled remote choices map to an entry in `models-catalog.json` with an active OpenRouter slug.
135
-
136
- | Option | Purpose |
137
- |--------|---------|
138
- | `requireOpenRouterCatalog: true` | Fail resolution if the chosen model is not in the catalog with an active OpenRouter id (use for production paths that must not call vendor-direct guesses). |
139
- | `catalogLane: "text" \| "image" \| …` | Only resolve profiles declared for that OpenRouter browser lane. Tier profiles (`cheap`, `cyber`, `vol`, …) are **`text`**. Lanes without profiles yet (`image`, `embeddings`, `rerank`, `speech`, `transcription`, …) can be added when you introduce lane-specific profiles. |
140
- | `listAIProfiles({ catalogLane: "text" })` | List only lane-matching profiles. |
141
-
142
- ```ts
143
- await resolveAIProfile("cyber/default", {
144
- catalogLane: "text",
145
- requireOpenRouterCatalog: true,
146
- });
147
-
148
- await listAIProfiles({ catalogLane: "text" });
149
- ```
150
-
151
- ### Cost tiers (optional)
152
-
153
- If you want to restrict model selection by price, you can either set an explicit `costCapPer1M`, or use a named `costTier`.
154
-
155
- ```ts
156
- import { resolveAIProfile } from "@x12i/ai-profiles";
157
-
158
- // Tier-based (default tiers: tier1=$0.5/1M output, tier2=$3, tier3=$10, tier4=$30)
159
- const cheapTier1 = await resolveAIProfile("balanced/default", {
160
- catalogLane: "text",
161
- costTier: "tier1",
162
- });
163
-
164
- // Override tiers (per-tier caps can be maxOutput/maxInput/maxBlended)
165
- const customTier = await resolveAIProfile("balanced", {
166
- catalogLane: "text",
167
- costTier: "budget",
168
- costTiers: [{ key: "budget", cap: { maxOutput: 0.5 } }],
169
- });
170
-
171
- // Explicit caps always win if both are provided
172
- const explicitCap = await resolveAIProfile("balanced", {
173
- catalogLane: "text",
174
- costTier: "tier1",
175
- costCapPer1M: { maxBlended: 2 },
176
- });
177
- ```
178
-
179
- ### Alternatives by cost tier
180
-
181
- When you want a profile’s “same intent, different price points”, use:
182
-
183
- ```ts
184
- import { resolveAIProfileWithCostAlternatives } from "@x12i/ai-profiles";
185
-
186
- const { primary, alternativesByCostTier } =
187
- await resolveAIProfileWithCostAlternatives("deep", {
188
- catalogLane: "text",
189
- tiers: [
190
- { key: "tier1", cap: { maxOutput: 0.5 } },
191
- { key: "tier2", cap: { maxOutput: 3 } },
192
- { key: "tier3", cap: { maxOutput: 10 } },
193
- ],
194
- });
195
-
196
- // alternativesByCostTier: [{ tier, resolved|null, reason? }, ...]
197
- ```
198
-
199
- ### Focus filters (catalog-derived)
200
-
201
- You can filter choices (and optionally profile listings) by catalog-derived capabilities.
202
-
203
- ```ts
204
- import { listAIProfiles, resolveAIProfile } from "@x12i/ai-profiles";
205
-
206
- // Preset focus filter
207
- const reasoningModel = await resolveAIProfile("deep", {
208
- catalogLane: "text",
209
- focus: "reasoning",
210
- });
211
-
212
- // Explicit capability filter
213
- const structured = await resolveAIProfile("json", {
214
- catalogLane: "text",
215
- capabilityFilter: { structuredOutput: true },
216
- });
217
-
218
- // Filter profile discovery to profiles with at least one matching choice
219
- const reasoningProfiles = await listAIProfiles({
220
- source: "bundled",
221
- focus: "reasoning",
222
- });
223
- ```
224
-
225
- ### Reasoning model flag (always communicated)
226
-
227
- Every resolved primary and secondary includes a stable boolean:
228
-
229
- ```ts
230
- const resolved = await resolveAIProfile("cheap/default", {
231
- catalogLane: "text",
232
- includeSecondary: true,
233
- });
234
-
235
- resolved.modelSignals.isReasoningModel; // boolean
236
- resolved.secondary?.modelSignals.isReasoningModel; // boolean
237
- ```
238
-
239
- Registry fields on each choice—`runtime` (`reasoningEffort`, `toolPolicy`, `outputMode`, `instructionTier`, `backend`), `modelStatus` (`verified` | `predicted`), `api` (vendor + OpenRouter slugs), and `reason`—document *why* that model backs the choice. **Pricing and capabilities** come from `models-catalog.json` at resolve time. Profile-level `requiredCapabilities` describes intent for future dynamic selection (Optimixer). Consumers use `resolveAIProfile` to materialize the merged result.
240
-
241
- ## Install
242
-
243
- ```bash
244
- npm install @x12i/ai-profiles
245
- ```
246
-
247
- ## Public API
248
-
249
- ### Profiles and registry loading
250
-
251
- | Export | Sync? | Purpose |
252
- |--------|-------|---------|
253
- | `listAIProfiles(options?)` | No (async) | Profile summaries: primary `profile` key, tags, choices, defaults |
254
- | `getAIRegistryStatistics(options?)` | No (async) | Counts: profiles, choices, providers, catalog models, linkage health |
255
- | `formatRegistryStatistics(stats)` | Yes | Human-readable summary for logs / CLI |
256
- | `loadAIProfilesRegistry(options?)` | No (async) | Raw profiles registry (`auto` / `remote` / `bundled`, 24h memory cache) |
257
- | `loadAIProfilesRegistryWithWarnings(options?)` | No (async) | Same as above, plus `warnings[]` (stale cache, bundled fallback, etc.) |
258
- | `loadModelsCatalog(options?)` | No (async) | Unified models catalog (`auto` / `remote` / `bundled`, same cache pattern as profiles) |
259
- | `loadBundledModelsCatalog()` | Yes | Package-shipped `models-catalog.json` only |
260
- | `loadBundledModelsRegistry()` | Yes | Package-shipped `models-registry.json` (linkage index) |
261
- | `listAIProfileChoices(options?)` | No (async) | List explicit `profile/choice` keys for strict pickers and stored config |
262
- | `formatProfileChoiceKey(profile, choice)` | Yes | Build canonical slot key (`cheap/default`) |
263
- | `parseProfileChoiceKey(input)` | Yes | Parse `profile/choice` (accepts `\` as separator on input) |
264
- | `matchStrictProfileInput(registry, input)` | Yes | Resolve input to profile+choice or `invalidChoice` |
265
- | `isKnownProfileChoice(input)` | Yes (bundled only) | Whether input is a known valid `profile/choice` key |
266
- | `isKnownProfileInput(input)` | Yes (bundled only) | Profile-intent gate: known `profile/choice` → `true`; concrete model ids → `false` |
267
- | `isKnownProfileOrShortcut(input)` | Yes (bundled only) | Alias of `isKnownProfileInput` (shortcuts are not supported) |
268
- | `isModelProfileReference(input)` | Yes (bundled only) | Authoring gate: known `profile/choice`, bare profile key, or legacy `profile@choice` |
269
- | `isConcreteModelId(input)` | Yes (bundled only) | Catalog-backed concrete model gate (no vendor-keyword heuristics) |
270
- | `toOptimixerModelProfile(input)` | Yes (bundled only) | `{ provider, model, reasoning }` from catalog wire (optional profile resolve) |
271
- | `isKnownProfileChoiceInput(registry, input)` | Yes | Same as above with an explicit registry |
272
- | `getBundledRegistry()` | Yes | Sync bundled profiles registry (no network) |
273
- | `resolveBundledAIProfile(input, options)` | Yes | Strict `profile/choice` → model, pricing, runtime (`source: "bundled"`) |
274
- | `resolveBundledInput(input, options)` | Yes | Unified sync resolver: `profile/choice` → registry; vendor slug / gateway wire / `{ provider, modelId }` → catalog |
275
- | `resolveInput(input, options)` | No (async) | Unified async resolver (same order as `resolveBundledInput`; `source: "auto" \| "remote" \| "bundled"`) |
276
- | `resolveBundledCatalogModel(input, options?)` | Yes | Sync strict catalog resolution (exact/high confidence only) |
277
- | `ensureConcreteModel(input, options?)` | Yes | String normalizer: `profile/choice` (strict) or concrete model (catalog best-effort) → invoke-time `{ provider, modelId }` |
278
- | `normalizeInvokeModel(input, options?)` | Yes | Idempotent gateway invoke tuple: strips `openrouter/` display slugs; rejects unresolved `profile/choice` aliases |
279
- | `resolveAndNormalizeInvokeModel(alias, options)` | No (async) | `resolveAIProfile` → `normalizeInvokeModel` for MAIN / handoff paths |
280
- | `resolveAndNormalizeBundledInvokeModel(alias, options)` | Yes | Bundled `resolveAIProfile` → `normalizeInvokeModel` (no network) |
281
- | `calculateInvokeCost(input, options?)` | No (async) | Token → USD from catalog pricing (`costStatus: "priced" \| "unpriced"`) |
282
- | `calculateInvokeCostSync(input, options?)` | Yes | Bundled offline cost calculator |
283
- | `calculateInvokeCostFromRecord(record, options?)` | No (async) | Activix snake_case usage record → USD |
284
- | `buildInvokePricingRecord(input)` | Yes | Build Activix-compatible invoke billing record |
285
- | `lookupBundledCatalogCaps({ provider, modelId })` | Yes | Sync quick caps + pricing summary from bundled catalog |
286
- | `lookupBundledCatalogModel(slug, options?)` | Yes | Sync rich catalog snapshot for a slug (pricing, reasoning, modalities); returns `undefined` on miss |
287
- | `resolveBundledCatalogModelDetails(slug, options?)` | Yes | Same as above but throws `UNKNOWN_MODEL` on miss |
288
- | `resolveCatalogModelDetails(slug, options?)` | No (async) | Rich catalog snapshot with optional remote catalog refresh |
289
- | `isReasoningModel(input, options?)` | Yes | `true`/`false` for supported inputs (throws `UNKNOWN_MODEL` on unknown concrete models) |
290
- | `resolveAIProfile(input, options?)` | No (async) | Resolve an explicit `profile/choice` key → model, pricing, runtime. Pass `includeSecondary: true` to attach `secondary`; `includeCatalog: true` to attach full `catalogModel`. |
291
- | `resolveSecondaryModel(input, options?)` | No (async) | Resolve primary choice + optional companion `secondary` from profile `secondary` refs |
292
- | `getSecondaryForResolvedProfile(resolved, registry, catalog?)` | Yes | Secondary for an already-resolved primary (no extra I/O when catalog is passed) |
293
- | `listProfileSecondaries(profileKey, registry)` | Yes | List per-choice `secondary` declarations on a profile |
294
- | `resolveAIProfileByTags(tags, options?)` | No (async) | Pick best profile by weighted tags (`tagMatch`, excludes discovery by default), then resolve |
295
- | `listAICatalogModels(options?)` | No (async) | Filter/rank catalog models by tags, provider, status, modalities, tools/reasoning; attaches intent `profileChoices` |
296
- | `resolveCatalogModelByTags(tags, options?)` | No (async) | Best catalog model by weighted tags (+ optional profile branch map) |
297
- | `scoreProfileTags` / `rankProfilesByTags` | Yes | Weighted tag scoring for discovery and custom UIs |
298
- | `AIProfilesError` / `AIProfilesErrorCode` | — | Typed errors (`UNKNOWN_PROFILE`, `INVOKE_MODEL_ALIAS_AT_GATEWAY`, `INVOKE_MODEL_SHAPE_INVALID`, …) |
299
-
300
- ### Model identity (vendor + model strings)
301
-
302
- Use these when callers pass **raw model ids or OpenRouter slugs**, not profile names.
303
-
304
- | Export | Sync? | Purpose |
305
- |--------|-------|---------|
306
- | `resolveCatalogModel(input, options?)` | No (async) | Resolve a model SKU or OpenRouter slug via `models-catalog.json` (strict; no profile intent) |
307
- | `resolveModelIdentity(input, options?)` | Yes | Given a bare id or `vendor/slug`, return `{ provider, modelId, invocation? }` via bundled registry + catalog fallback. Returns `null` for known `profile/choice` keys. |
308
- | `buildModelInvocation(provider, modelId)` | Yes | `{ direct, openrouter }` endpoints for a provider hint + model string |
309
- | `buildDirectInvocation(provider, modelId)` | Yes | Vendor-direct `{ provider, modelId }`; splits prefixed slugs for all vendors |
310
- | `buildOpenRouterModelId(provider, modelId)` | Yes | Build an OpenRouter slug (`openai/gpt-5.4`) from registry fields |
311
- | `parseDirectFromOpenRouterSlug(slug, family?)` | Yes | Split `vendor/model` → direct slice (`custom` + bare id when vendor is not a first-class provider) |
312
- | `normalizeAnthropicVersionSlug(slug)` | Yes | Dotted minor versions for Anthropic (`4-6` → `4.6`) |
313
- | `buildRegistryKey(provider, modelId)` | Yes | Stable registry key (`vendor:…`) used in `models-registry.json` |
314
- | `matchOpenRouterCatalog(provider, modelId, index)` | Yes | Match a choice against a catalog index |
315
- | `lookupInvocationForChoice(registry, provider, modelId)` | Yes | Lookup prebuilt invocation from `models-registry.json` |
316
-
317
- **Prefixed slugs:** `buildDirectInvocation("meta-llama", "meta-llama/llama-3.1-8b-instruct")` yields `{ provider: "meta-llama", modelId: "llama-3.1-8b-instruct" }`. Host paths keep the nested id when the provider hint differs (e.g. Together: `together` + `meta-llama/Llama-3.3-70b-instruct`). Bare and prefixed Anthropic inputs normalize to the same direct and OpenRouter ids.
318
-
319
- ### Routing, validation, and maintainer tooling
320
-
321
- | Export | Sync? | Purpose |
322
- |--------|-------|---------|
323
- | `resolvePreferOpenRouter(explicit?)` | Yes | Resolve OpenRouter vs vendor-direct routing (option → env → default) |
324
- | `applyModelRouting(choice, backend, preferOpenRouter, catalog?)` | Yes | Turn a registry choice into invoke-time `{ provider, modelId, routing }` (same rules as `resolveAIProfile`) |
325
- | `normalizeGatewayWireId(input)` | Yes | `openrouter/openai/gpt-5.5` → `{ provider: "openrouter", modelId: "openai/gpt-5.5" }` (profile keys like `cheap/default` are not gateway wires) |
326
- | `validateBundledProfileVendorCoverage(options?)` | Yes | Advisory report of leading-vendor coverage per profile |
327
- | `validateBundledProfileModalityCoverage(options?)` | Yes | Advisory report of profile choice vs required input/output media |
328
- | `isProfileVendorTrimReady(profile, allowedProviders)` | Yes | Whether auto-pick can satisfy a vendor filter |
329
- | `isProfileModalityCoverageReady(profileKey)` | Yes | Whether a profile has at least one modality-compatible choice |
330
- | `listFaultyProfileChoices()` | Yes | Profile choices with faulty OpenRouter catalog linkage |
331
- | `buildModelsRegistry`, `verifyOpenRouterAlignment`, … | Yes | Catalog/registry build and alignment (see scripts below) |
332
-
333
- Registry JSON lives in four bundled assets:
334
-
335
- | File | Schema | Role |
336
- |------|--------|------|
337
- | `models-profiles.json` | `x12i.ai-profiles.model-registry.v4` | Profile intent, lean choices referencing catalog — **no embedded pricing** |
338
- | `models-catalog.json` | `x12i.ai-profiles.models-catalog` (v2.0.0) | Per-model pricing, capabilities, `modelFamily` (OpenRouter-normalized) |
339
- | `models-registry.json` | `x12i.ai-profiles.models-registry` | Built linkage index: vendor keys, OpenRouter slugs, `invocation` pairs |
340
-
341
- **v4 contract:** Each profile choice stores `provider` + **vendor-native** `modelId` as a pointer into `models-catalog.json`, which owns the `direct` and `openrouter` listings. Choice `displayName` / `description` are optional (hydrated from catalog). Never embed `api`, `defaultTransport`, or OpenRouter slugs on profile choices. Vendor-family profiles (`vendorFamily: true`) expose `default` / `cheapest` / `best` / `<family>-latest-model` without hijacking concrete slugs like `openai/gpt-4`. Run `npm run registry:finish` to strip legacy fields, verify linkage, and rebuild `models-registry.json`.
342
-
343
- Validate with `src/data/models-profiles.schema.json`. Maintainer scripts: `npm run catalog:extend-profiles`, `npm run registry:finish` (catalog supplement + verified defaults + linkage rebuild).
344
-
345
- ## Sync bundled resolution (predict / invoke)
346
-
347
- For consumers that need **no network** and a single entry point:
348
-
349
- ```ts
350
- import {
351
- ensureConcreteModel,
352
- isKnownProfileInput,
353
- isReasoningModel,
354
- resolveBundledInput,
355
- resolveBundledAIProfile,
356
- applyModelRouting,
357
- normalizeGatewayWireId,
358
- lookupBundledCatalogCaps,
359
- getBundledRegistry,
360
- } from "@x12i/ai-profiles";
361
-
362
- // Four supported resolution forms:
363
- // 1. profile/choice → registry (strict)
364
- // 2. vendor slug → catalog (strict in resolveBundledCatalogModel; best-effort in ensureConcreteModel)
365
- // 3. gateway wire → catalog
366
- // 4. { provider, modelId } → catalog
367
-
368
- ensureConcreteModel("cheap/default");
369
- // → { provider: "openrouter", modelId: "deepseek/deepseek-v4-flash", profileChoice: { profile: "cheap", choice: "default" } }
370
-
371
- ensureConcreteModel("google/gemini-2.5-flash-lite");
372
- // → { provider: "openrouter", modelId: "google/gemini-2.5-flash-lite", matchConfidence: "exact" }
373
-
374
- ensureConcreteModel("openrouter/openai/gpt-5.5");
375
- // → { provider: "openrouter", modelId: "openai/gpt-5.5" }
376
-
377
- if (isKnownProfileInput("cheap/default")) {
378
- const resolved = resolveBundledInput("cheap/default", { catalogLane: "text" });
379
- // resolved.provider is never "cheap"
380
- }
381
-
382
- const wire = normalizeGatewayWireId("openrouter/openai/gpt-5.5");
383
- // → { provider: "openrouter", modelId: "openai/gpt-5.5" }
384
-
385
- isReasoningModel("deep/default"); // true
386
- isReasoningModel("cheap/default"); // true (catalog marks gemini-2.5-flash-lite reasoning-capable)
387
- isReasoningModel("google/gemini-2.5-flash-lite"); // false
388
-
389
- const caps = lookupBundledCatalogCaps({
390
- provider: "openrouter",
391
- modelId: "google/gemini-2.5-flash-lite",
392
- });
393
-
394
- const registry = getBundledRegistry();
395
- const routed = applyModelRouting(
396
- registry.profiles.cheap.choices.default,
397
- "openrouter",
398
- true,
399
- );
400
- ```
401
-
402
- For the same profile-first order with optional remote registry/catalog (`source: "auto"` / `"remote"` / `"bundled"`), use **`resolveInput`**:
403
-
404
- ```ts
405
- import { resolveInput } from "@x12i/ai-profiles";
406
-
407
- await resolveInput("cheap/default", { catalogLane: "text", source: "auto" });
408
- await resolveInput("google/gemma-3-4b-it", { source: "bundled" });
409
- ```
410
-
411
- `isKnownProfileInput` / `isKnownProfileChoice` return **false** for bare profiles (`cheap`), legacy shortcuts (`cheapest`), and concrete slugs (`google/gemini-2.5-flash-lite`).
412
-
413
- ## Basic usage
414
-
415
- ```ts
416
- import {
417
- listAIProfiles,
418
- listAIProfileChoices,
419
- isKnownProfileInput,
420
- resolveAIProfile,
421
- resolveCatalogModel,
422
- resolveInput,
423
- } from "@x12i/ai-profiles";
424
-
425
- const profiles = await listAIProfiles();
426
- const choices = await listAIProfileChoices();
427
-
428
- // Strict lookup key: profile/choice
429
- const model = await resolveAIProfile("cheap/default", { catalogLane: "text" });
430
- // Or unified async: await resolveInput("cheap/default", { catalogLane: "text" });
431
-
432
- console.log(model.profile); // canonical primary key: cheap
433
- console.log(model.provider); // "openrouter" by default for remote profiles
434
- console.log(model.modelId); // "google/gemini-2.5-flash-lite"
435
- console.log(model.routing); // "openrouter" | "direct"
436
- console.log(model.pricing); // from models-catalog.json
437
- console.log(model.modelStatus); // verified | predicted
438
- console.log(model.requiredCapabilities); // profile intent
439
- console.log(model.capabilities); // contextWindow, supportsTools, …
440
- console.log(model.instructionTier);
441
- console.log(model.backend);
442
-
443
- // SKU lookup (catalog), not a profile
444
- const sku = await resolveCatalogModel("google/gemini-2.5-flash-lite", {
445
- source: "bundled",
446
- preferOpenRouter: false,
447
- });
448
-
449
- console.log(isKnownProfileInput("cheap/default")); // true
450
- console.log(isKnownProfileInput("cheap")); // false
451
- ```
452
-
453
- ## Registry statistics
454
-
455
- Use **`getAIRegistryStatistics()`** for discovery dashboards, CI summaries, and operator tooling. It loads profiles and the models catalog with the same `source` / `refresh` options as `resolveAIProfile`, then returns structured counts.
456
-
457
- ```ts
458
- import {
459
- formatRegistryStatistics,
460
- getAIRegistryStatistics,
461
- } from "@x12i/ai-profiles";
462
-
463
- const { statistics, warnings } = await getAIRegistryStatistics({
464
- source: "bundled", // or "auto" | "remote"
465
- includeCatalog: true,
466
- includeLinkage: true,
467
- });
468
-
469
- console.log(statistics.profiles.total);
470
- console.log(statistics.profiles.providers);
471
- console.log(statistics.catalog?.totalModels);
472
- console.log(statistics.linkage?.faulty);
473
-
474
- console.log(formatRegistryStatistics(statistics));
475
- ```
476
-
477
- CLI (after build): `npm run stats` (text) or `npm run stats:json`.
478
-
479
- ## Supported resolution inputs
480
-
481
- Resolution accepts exactly **four** input forms:
482
-
483
- | Form | Example | Resolver |
484
- |------|---------|----------|
485
- | Profile + choice | `cheap/default` | Registry (`resolveAIProfile`, `resolveBundledAIProfile`) |
486
- | Vendor slug | `google/gemini-2.5-flash-lite` | Catalog (`resolveCatalogModel`, `resolveBundledCatalogModel`) |
487
- | Gateway wire | `openrouter/openai/gpt-5.5` | Catalog (gateway normalization) |
488
- | Object | `{ provider: "google", modelId: "gemini-2.5-flash-lite" }` | Catalog |
489
-
490
- **Not supported:** shortcuts (`cheapest`), bare profiles (`cheap`), aliases (`cost-sensitive`). Use discovery to pick a profile, then resolve an explicit `profile/choice`.
491
-
492
- **Tags exist to filter.** Short codes on profiles and catalog models (`cyb`, `eco`, `cod`, `oai`, …). Get the tag list, then filter:
493
-
494
- ```ts
495
- import {
496
- listAIProfileTags, // all allowed tags (+ labels)
497
- listUsedAIProfileTags, // tags present in the loaded registry
498
- listAIProfiles, // filter profiles by tags
499
- resolveAIProfileByTags, // pick best matching profile → resolve it
500
- listAICatalogModels, // filter catalog models by tags
501
- resolveCatalogModelByTags, // pick best matching model (+ optional profile branch)
502
- } from "@x12i/ai-profiles";
503
-
504
- listAIProfileTags(); // glossary for pickers
505
- await listUsedAIProfileTags({ source: "bundled" }); // what's actually used
506
-
507
- // Filter: keep profiles that have these tags
508
- await listAIProfiles({ tags: ["cyb", "eco"], tagMatch: "any" }); // any of
509
- await listAIProfiles({ tags: ["cyb", "sec"], tagMatch: "all" }); // all of
510
-
511
- // Filter + resolve in one step
512
- await resolveAIProfileByTags(["cyb", "eco", "ds"], { catalogLane: "text" });
513
-
514
- // Catalog models (tags are derived + inherited during registry:finish)
515
- await listAICatalogModels({
516
- tags: ["cod", "eco"],
517
- tagMatch: "all",
518
- provider: "google",
519
- status: "active",
520
- supportsTools: true,
521
- });
522
- await resolveCatalogModelByTags(["cod", "eco"], { catalogLane: "text" });
523
- ```
524
-
525
- `tagMatch: "any"` (default) = match if any requested tag is present. `"all"` = every requested tag must be present. Results are ranked by **weighted** tag score (domain/task 3, capability 2, tier/vendor 1, `wf` 0.25), then coverage ratio, then fewer tags.
526
-
527
- **Discovery exclusion:** by default, tag list/resolve pools skip `vendorFamily` and `category: "discovery"` profiles (`catalog`, `claude`, `grok`, …). Pass `includeDiscovery: true`, or include the `vnd` tag, to include them.
528
-
529
- Input is normalized (trimmed, lowercased) before matching. Composite keys accept **`/` or `\`** as the separator (`cyber\default` → `cyber/default`). **Profile and choice segment names treat `-` and `_` as equivalent** (`cheap/google-floor` → `cheap/google_floor`).
530
-
531
- ### Examples
532
-
533
- ```ts
534
- // Composite key
535
- await resolveAIProfile("balanced/default", { catalogLane: "text" });
536
-
537
- // Tag-based pick (partial overlap OK) → explicit profile/choice
538
- await resolveAIProfileByTags(["cyb", "eco", "ds"], { catalogLane: "text" });
539
-
540
- // Model SKU → catalog, not a profile
541
- await resolveCatalogModel("google/gemini-2.5-flash-lite", { source: "bundled" });
542
-
543
- // String normalizer for invoke-time routing
544
- ensureConcreteModel("cheap/default");
545
- ensureConcreteModel("google/gemini-2.5-flash-lite");
546
- ```
547
-
548
- `listAIProfiles()` returns profile keys, tags, and choices for pickers. `listAIProfileChoices()` lists every valid `profile/choice` composite key.
549
-
550
- ## Invoke wire shape (gateway / HTTP)
551
-
552
- Downstream packages (`ai-tasks`, `ai-skills`, `ai-gateway`, `xynthesis`, `optimixer`) must agree on what is sent on the wire **after** semantic resolution. **Stored graph config** uses `profile/choice` aliases; **gateway / HTTP** uses the invoke tuple below.
553
-
554
- ### Display slug
555
-
556
- A **display slug** is a single string with an `openrouter/` prefix for human-readable UI and logs, e.g. `openrouter/deepseek/deepseek-v4-pro`. Studio pickers, plan previews, and Activix run logs may show this form. It is **not** the shape passed to `ai-gateway` catalog lookup or OpenRouter HTTP — normalize before those boundaries.
557
-
558
- ### Invoke tuple
559
-
560
- An **invoke tuple** is `{ provider, model, routing }` where `provider` is `"openrouter"` (or a vendor for direct routing) and `model` is the **bare** vendor/model slug without a gateway prefix, e.g. `{ provider: "openrouter", model: "deepseek/deepseek-v4-pro", routing: "openrouter" }`. This is what `ai-gateway` uses for catalog lookup and what OpenRouter HTTP expects.
561
-
562
- Call **`normalizeInvokeModel`** at every gateway boundary (idempotent). Profile intent still goes through **`resolveAIProfile`** first, or use **`resolveAndNormalizeInvokeModel`** / **`resolveAndNormalizeBundledInvokeModel`** for the combined path.
563
-
564
- | Export | Sync? | Purpose |
565
- |--------|-------|---------|
566
- | `normalizeInvokeModel(input, options?)` | Yes | Display slug or invoke object → canonical invoke tuple; rejects unresolved `profile/choice` |
567
- | `resolveAndNormalizeInvokeModel(alias, options)` | No (async) | `resolveAIProfile` → `normalizeInvokeModel` |
568
- | `resolveAndNormalizeBundledInvokeModel(alias, options)` | Yes | Bundled `resolveAIProfile` → `normalizeInvokeModel` (no network) |
569
-
570
- ```ts
571
- import {
572
- normalizeInvokeModel,
573
- resolveAndNormalizeInvokeModel,
574
- resolveAndNormalizeBundledInvokeModel,
575
- } from "@x12i/ai-profiles";
576
-
577
- // Display slug → invoke tuple (string or { model } object)
578
- normalizeInvokeModel("openrouter/deepseek/deepseek-v4-pro");
579
- normalizeInvokeModel({ model: "openrouter/deepseek/deepseek-v4-pro" });
580
- // → { provider: "openrouter", model: "deepseek/deepseek-v4-pro", routing: "openrouter", displaySlug: "..." }
581
-
582
- // Already-correct tuple → unchanged (idempotent)
583
- normalizeInvokeModel({ provider: "openrouter", model: "deepseek/deepseek-v4-pro" });
584
-
585
- // Unresolved profile/choice at gateway → INVOKE_MODEL_ALIAS_AT_GATEWAY
586
- normalizeInvokeModel("cheap/default");
587
- normalizeInvokeModel({ model: "cheap/default" }); // same error
588
-
589
- // Profile/choice → resolve, then normalize (gateway catalog-lookup tuple)
590
- await resolveAndNormalizeInvokeModel("cyber/deep_forensics", {
591
- catalogLane: "text",
592
- preferOpenRouter: true,
593
- });
594
- // → { provider: "openrouter", model: "deepseek/deepseek-v4-pro", routing: "openrouter", ... }
595
-
596
- // Sync bundled variant (tests, predict paths)
597
- resolveAndNormalizeBundledInvokeModel("cyber/deep_forensics", {
598
- catalogLane: "text",
599
- preferOpenRouter: true,
600
- });
601
- ```
602
-
603
- **Error codes** (on `AIProfilesError.code`):
604
-
605
- | Code | When |
606
- |------|------|
607
- | `INVOKE_MODEL_ALIAS_AT_GATEWAY` | `profile/choice` reached `normalizeInvokeModel` without prior `resolveAIProfile` |
608
- | `INVOKE_MODEL_SHAPE_INVALID` | Empty model, missing provider, or unparseable composite after normalization |
609
-
610
- `allowAlias: true` exists for rare internal paths; **gateway and HTTP callers should not use it** — resolve aliases first.
611
-
612
- ## Sync validation (bundled registry)
613
-
614
- Use **`isKnownProfileInput(input)`** (or **`isKnownProfileChoice`**) before run/execute or on first paint when the remote registry may not be loaded yet. It reads the **bundled** JSON only (no network, no in-memory cache race).
615
-
616
- ```ts
617
- const canRun =
618
- isKnownProfileInput(aiProfileKey) &&
619
- isKnownProfileInput(fallbackKey);
620
- ```
621
-
622
- Accepts **valid `profile/choice` keys only**. Unknown strings return `false`.
623
-
624
- After validation, call `resolveAIProfile` (usually `source: "auto"` or `"bundled"`) to get the canonical `resolved.profile` and the concrete model details.
625
-
626
- ### UI guidance
627
-
628
- - **Profile picker**: `await listAIProfiles()` → use each row’s `profile` as the value; show `displayName` as the label.
629
- - **Choice picker**: `await listAIProfileChoices({ profile: "cheap" })` or list choices from the profile summary.
630
- - **Stored config**: store `profile/choice` composite keys (e.g. `cheap/default`).
631
-
632
- ## Pick a specific model implementation (choice)
633
-
634
- ```ts
635
- const model = await resolveAIProfile("cheap/anthropic_cheap", {
636
- catalogLane: "text",
637
- });
638
- ```
639
-
640
- ## OpenRouter vs vendor-direct routing
641
-
642
- Remote profiles (anything that is not `local` / on-device) can be resolved for **OpenRouter** or for a **vendor API directly**. Local CPU profiles are always returned as-is.
643
-
644
- ### Resolution priority
645
-
646
- 1. **`options.preferOpenRouter`** when passed to `resolveAIProfile`
647
- 2. **`PREFER_OPENROUTER`** in `.env` / process env
648
- 3. **Default: `true`** (OpenRouter)
649
-
650
- Supported today: **OpenRouter** and **vendor-direct**. Azure and AWS routing are not supported yet.
651
-
652
- ### OpenRouter (default)
653
-
654
- ```ts
655
- const resolved = await resolveAIProfile("cheap/default", { catalogLane: "text" });
656
- // or explicitly:
657
- await resolveAIProfile("cheap/default", { catalogLane: "text", preferOpenRouter: true });
658
-
659
- // resolved.provider === "openrouter"
660
- // resolved.modelId === "google/gemini-3.1-flash-lite"
661
- // resolved.routing === "openrouter"
662
- // resolved.backend === "openrouter"
663
- ```
664
-
665
- Registry choices store vendor-native ids (e.g. `gpt-5.4`, `gemini-2.5-flash-lite`). When routing via OpenRouter, this package rewrites them to full slugs: `{vendor}/{model}` (e.g. `openai/gpt-5.4`, `anthropic/claude-sonnet-4.6`). Anthropic version segments are normalized to dotted form (`4.6`, not `4-6`).
666
-
667
- This applies to any `profile/choice` input that resolves to a remote profile choice.
668
-
669
- ### Avoid hardcoded OpenRouter slugs (especially dated previews)
670
-
671
- Do **not** copy OpenRouter slugs into graph JSON or app config (`preActionModel`, `skillModel`, `postActionModel`, env vars, etc.) and do **not** use `canonicalSlug` from the catalog for API calls. OpenRouter retires dated preview ids (e.g. `google/gemini-2.5-flash-lite-preview-06-17`) while stable ids remain (`google/gemini-2.5-flash-lite`).
672
-
673
- ```ts
674
- // Good — store profile/choice; resolve at execute time
675
- preActionModel: "cheap/default";
676
- skillModel: "balanced/default";
677
- postActionModel: "cheap/default";
678
-
679
- const pre = await resolveAIProfile("cheap/default", { catalogLane: "text" });
680
- // pre.modelId → "google/gemini-2.5-flash-lite" (concrete id only after resolution)
681
-
682
- // Bad — concrete slug in stored config (stale when catalog moves)
683
- preActionModel: "google/gemini-2.5-flash-lite-preview-06-17";
684
- ```
685
-
686
- Use `assertStableOpenRouterSlug(slug)` before outbound OpenRouter calls when you must accept external slug strings. Run `npm run verify:openrouter:live` in CI to catch catalog drift.
687
-
688
- ### Vendor-direct
689
-
690
- ```ts
691
- const resolved = await resolveAIProfile("cheap/default", {
692
- catalogLane: "text",
693
- preferOpenRouter: false,
694
- });
695
-
696
- // resolved.provider === "google"
697
- // resolved.modelId === "gemini-2.5-flash-lite"
698
- // resolved.routing === "direct"
699
- // resolved.backend === "custom"
700
- ```
701
-
702
- Use this when calling OpenAI, Anthropic, Google, etc. APIs directly instead of through OpenRouter.
703
-
704
- ### Rich catalog data (pricing, reasoning, modalities)
705
-
706
- Use the right entry point for your input shape:
707
-
708
- | Input | Function | Returns |
709
- |-------|----------|---------|
710
- | OpenRouter / vendor slug | `resolveCatalogModelDetails(slug)` or sync `lookupBundledCatalogModel(slug)` | `ResolvedCatalogModel` |
711
- | `profile/choice` | `resolveAIProfile(key, { catalogLane, includeCatalog: true })` | `ResolvedAIProfile` + `catalogModel` |
712
- | Post-resolve slug check | `requireCatalogModel(slug, { includeDetails: true })` | presence + optional `catalogModel` |
713
-
714
- ```ts
715
- // Slug → full catalog enrichment
716
- const model = await resolveCatalogModelDetails("google/gemini-2.5-flash-lite", {
717
- source: "bundled",
718
- });
719
- model.pricing?.input; // flattened per-1M rates
720
- model.catalogPricing?.imageInput; // raw OpenRouter pricing slice
721
- model.contextWindow; // e.g. 1048576
722
- model.maxCompletionTokens; // e.g. 65536 (catalog maxCompletionTokens)
723
- model.limits?.maxOutputTokens; // same as maxCompletionTokens
724
- model.modelSignals.isReasoningModel; // true
725
- model.modelSignals.maxOutputTokens; // same as maxCompletionTokens
726
- model.catalogCapabilities?.toolCalling; // true
727
- model.invocation.openrouter?.modelId; // "google/gemini-2.5-flash-lite"
728
- model.capabilities?.supportsOpenRouterReasoningParam; // gateway reasoning.effort
729
- ```
730
-
731
- ### Invoke cost (Activix / FuncX)
732
-
733
- ```ts
734
- import { calculateInvokeCost, buildInvokePricingRecord } from "@x12i/ai-profiles";
735
-
736
- const cost = await calculateInvokeCost(
737
- {
738
- model: "cheap/default",
739
- tokens: { prompt: 1000, completion: 500 },
740
- },
741
- { catalogLane: "text", bundledOnly: true, includeBreakdown: true },
742
- );
743
- // cost.costUsd, cost.costStatus: "priced", cost.breakdown
744
-
745
- // Profile/choice catalog validation
746
- const required = await requireCatalogModel("cheap/default", {
747
- catalogLane: "text",
748
- resolveProfileKeys: true,
749
- bundledOnly: true,
750
- });
751
- // required.found, required.modelId, required.profileChoice
752
- ```
753
-
754
- See `.docs/AI-PROFILES-ACTIVIX-COST-CONTRACT.md` for Activix migration wire.
755
-
756
- **Catalog SOT:** do not use ai-tools' small OpenRouter index for invoke gating — use `requireCatalogModel` / `validateBundledProfileCatalogLinkage` on this package (`npm run validate:linkage`).
757
-
758
- ```ts
759
- // Profile → same enrichment on catalogModel
760
- const resolved = await resolveAIProfile("cheap/default", {
761
- catalogLane: "text",
762
- includeCatalog: true,
763
- includeCatalogEntry: true, // attach full models-catalog.json row
764
- });
765
- resolved.catalogModel?.pricing;
766
- resolved.catalogModel?.catalogEntry;
767
- ```
768
-
769
- ### Env fallback
770
-
771
- Set in `.env` or the process environment:
772
-
773
- ```env
774
- PREFER_OPENROUTER=1 # or true, yes, on → OpenRouter
775
- PREFER_OPENROUTER=0 # or false, no, off → vendor-direct
776
- ```
777
-
778
- When `preferOpenRouter` is omitted from `resolveAIProfile`, the env value is used. An explicit option always wins over env.
779
-
780
- ```ts
781
- process.env.PREFER_OPENROUTER = "0";
782
- await resolveAIProfile("cheap/default", { catalogLane: "text" }); // vendor-direct
783
-
784
- await resolveAIProfile("cheap/default", { catalogLane: "text", preferOpenRouter: true }); // still OpenRouter
785
- ```
786
-
787
- Helper exports:
788
-
789
- ```ts
790
- import {
791
- resolvePreferOpenRouter,
792
- buildOpenRouterModelId,
793
- buildModelInvocation,
794
- resolveModelIdentity,
795
- } from "@x12i/ai-profiles";
796
-
797
- resolvePreferOpenRouter(); // true by default
798
- resolvePreferOpenRouter(false); // explicit override
799
-
800
- buildOpenRouterModelId("openai", "gpt-5.4"); // "openai/gpt-5.4"
801
-
802
- // Same direct + OpenRouter shape whether input is bare or prefixed:
803
- buildModelInvocation("anthropic", "claude-3-5-sonnet-20241022");
804
- buildModelInvocation("anthropic", "anthropic/claude-3-5-sonnet-20241022");
805
-
806
- // Bare model string → vendor + model (no profile name required):
807
- resolveModelIdentity("google/gemini-2.5-flash-lite");
808
- // { provider: "google", modelId: "gemini-2.5-flash-lite", invocation: { … } }
809
-
810
- resolveModelIdentity("google/gemini-2.5-flash-lite", { asOpenRouter: true });
811
- // { provider: "openrouter", modelId: "google/gemini-2.5-flash-lite", … }
812
- ```
813
-
814
- Tests: `test/resolveModelRouting.test.ts`, `test/modelIdentity.test.ts`, `test/resolveModelIdentity.test.ts`.
815
-
816
- ## Use bundled only
817
-
818
- ```ts
819
- const model = await resolveAIProfile("balanced/default", {
820
- catalogLane: "text",
821
- source: "bundled",
822
- });
823
- ```
824
-
825
- ## Force refresh
826
-
827
- ```ts
828
- const model = await resolveAIProfile("balanced/default", {
829
- catalogLane: "text",
830
- refresh: true,
831
- });
832
- ```
833
-
834
- ## Runtime behavior
835
-
836
- **Default (`source: "auto"`):**
837
-
838
- 1. Fetch `models-profiles.json` from the assets URL (see below).
839
- 2. Validate the response; if valid, use it and cache it in process memory for 24 hours.
840
- 3. If fetch or validation fails, use the JSON shipped inside this npm package (bundled fallback).
841
- 4. After TTL, the next call tries fetch again; if that fails but an earlier fetch was cached, reuse the stale cache with a warning.
842
-
843
- **`source: "bundled"`** — package JSON only, no network.
844
-
845
- **`source: "remote"`** — fetch every time (still cached after success); errors propagate, no bundled fallback.
846
-
847
- No database. No disk cache in v1.
848
-
849
- The `version` field in the JSON files (and `registryVersion` on resolved output) is an optional label for humans or external tooling. This package does not compare versions, enforce semver, or pick assets by version number.
850
-
851
- ## Remote assets
852
-
853
- Upload the bundled JSON files **as-is** (no filename version suffix):
854
-
855
- - `https://open-assets.x12i.com/models-profiles.json`
856
- - `https://open-assets.x12i.com/models-catalog.json`
857
-
858
- Older `.v4` / `.v2` URLs are intentionally retired — point every consumer at the unversioned paths above.
859
-
860
- ## Integration example
861
-
862
- ```ts
863
- import { resolveAIProfile, resolveAndNormalizeInvokeModel } from "@x12i/ai-profiles";
864
-
865
- // Graph JSON stores aliases only (merged job defaults + node overrides per task)
866
- const slots = {
867
- preActionModel: node.taskConfiguration.modelConfig?.preActionModel ?? "deep/default",
868
- skillModel: node.taskConfiguration.modelConfig?.skillModel ?? "balanced/default",
869
- postActionModel: node.taskConfiguration.modelConfig?.postActionModel ?? "cheap/default",
870
- };
871
-
872
- // Resolve each phase independently at execute time
873
- const pre = await resolveAIProfile(slots.preActionModel, { catalogLane: "text" });
874
- const main = await resolveAIProfile(slots.skillModel, { catalogLane: "text" });
875
- const post = await resolveAIProfile(slots.postActionModel, { catalogLane: "text" });
876
-
877
- // Gateway handoff: resolve + normalize invoke tuple
878
- const mainInvoke = await resolveAndNormalizeInvokeModel(slots.skillModel, {
879
- catalogLane: "text",
880
- preferOpenRouter: true,
881
- });
882
- // mainInvoke → { provider: "openrouter", model: "openai/gpt-5.6-terra", routing: "openrouter", ... }
883
- ```
884
-
885
- ## Profile matrix (FuncX contract)
886
-
887
- Default choice per profile (vendor-native ids in registry; OpenRouter slugs when `preferOpenRouter` is true):
888
-
889
- | Profile | Inference | Instruction tier | Default choice | Example model |
890
- |---------|-----------|------------------|----------------|---------------|
891
- | `cheap` | Remote | **`default`** | `default` | `deepseek-v4-flash` |
892
- | `fast` | Remote | **`default`** | `default` | `gpt-5.6-luna` |
893
- | `balanced` | Remote | **`default`** | `default` | `gpt-5.6-terra` |
894
- | `deep` | Remote | **`reasoning`** | `default` | `claude-sonnet-5` |
895
- | `pro` | Remote | **`default`** | `default` | `gpt-5.6-sol-pro` |
896
- | `json` | Remote | **`default`** | `default` | `gpt-5.6-luna` (schema output) |
897
- | `agentic` | Remote | **`default`** | `default` | `claude-sonnet-5` |
898
- | `research` | Remote | **`reasoning`** | `default` | `claude-sonnet-5` |
899
- | `cyber` | Remote | **`default`** | `default` | `deepseek-v4-flash` |
900
- | `content` | Remote | **`default`** | `default` | `claude-fable-5` |
901
- | `sum` | Remote | **`default`** | `default` | `claude-haiku-4.5` |
902
- | `vol` | Remote | **`default`** | `default` | `deepseek-v4-flash` |
903
- | `routing` | Remote | **`default`** | `default` | `gemini-2.5-flash-lite` |
904
- | `extraction` | Remote | **`default`** | `default` | `gemini-2.5-flash-lite` |
905
- | `coding` | Remote | **`default`** | `default` | `deepseek-v4-flash` |
906
- | `local` | CPU (no OpenRouter) | **`cpu`** | `llama_cpp_gguf` | `funcx:llama-cpp:gguf` |
907
-
908
- Local CPU choices expose FuncX / runtime env keys in `resolved.metadata` (e.g. `LLAMA_CPP_MODEL_PATH`, `OLLAMA_MODEL`, `VLLM_BASE_URL`).
909
-
910
- ### OpenRouter model ids
911
-
912
- Remote profile choices in `models-profiles.json` use vendor-native `modelId` values (e.g. `gpt-5.6-sol-pro`, `gemini-2.5-flash-lite`). By default, `resolveAIProfile` returns OpenRouter-ready output:
913
-
914
- - `provider`: `"openrouter"`
915
- - `modelId`: full slug such as `openai/gpt-5.6-sol-pro` (with correct OpenRouter prefixes, e.g. `x-ai/…`)
916
- - `routing`: `"openrouter"`
917
-
918
- Pass `preferOpenRouter: false` (or `PREFER_OPENROUTER=0`) to get vendor-native `provider` + `modelId` for direct API calls.
919
-
920
- Every resolved profile includes **`invocation`** with both call shapes:
921
-
922
- ```ts
923
- resolved.invocation.direct // { provider: "openai", modelId: "gpt-5.6-sol-pro" }
924
- resolved.invocation.openrouter // { provider: "openrouter", modelId: "openai/gpt-5.6-sol-pro" } | null
925
- ```
926
-
927
- Top-level `provider` / `modelId` / `routing` remain the **active** path selected by `preferOpenRouter`.
928
-
929
- ### Vendor trimming
930
-
931
- Restrict resolution to specific vendors (auto-picks within the profile when the default is outside the set). **Leading vendors** (`openai`, `anthropic`, `google`, `deepseek`, `minimax`, `xai`) are **preferred** during auto-pick, not forced — explicit `choice` still honors `together` and other providers.
932
-
933
- ```ts
934
- await resolveAIProfile("balanced/default", {
935
- catalogLane: "text",
936
- allowedProviders: ["google", "openai"],
937
- preferLeadingVendors: true, // default
938
- });
939
- ```
940
-
941
- ### Modality filtering (input / output media)
942
-
943
- Every profile declares **required input and output media** in `requiredCapabilities`:
944
-
945
- - Most profiles: `inputModalities: ["text"]`, `outputModalities: ["text"]`
946
- - `vision`: `inputModalities: ["text", "image"]`, `outputModalities: ["text"]`
947
-
948
- Supported values: `text`, `image`, `audio`, `video`, `file` (aligned with `models-catalog.json`).
949
-
950
- During resolution, choices whose catalog modalities do not satisfy the contract are **excluded**. A text-only model cannot be picked for `vision`; a vision-capable model can still serve text profiles.
951
-
952
- ```ts
953
- const resolved = await resolveAIProfile("vision/default", { catalogLane: "image" });
954
- // resolved.requiredModalities.input includes "image"
955
- // resolved.modalities reflects the picked model from catalog
956
-
957
- await resolveAIProfile("cheap/default", {
958
- catalogLane: "text",
959
- inputModalities: ["text", "image"], // override for this call
960
- outputModalities: ["text"],
961
- });
962
- ```
963
-
964
- Override at resolve time with `inputModalities` / `outputModalities`. Incompatible explicit `choice` values throw `NO_MODALITY_MATCH`.
965
-
966
- Registry maintenance:
967
-
968
- ```ts
969
- import { validateBundledProfileModalityCoverage } from "@x12i/ai-profiles";
970
-
971
- validateBundledProfileModalityCoverage(); // { ok, profiles[] } with mismatches
972
- ```
973
-
974
- `npm run catalog:build` writes `MODALITY_MISMATCH` rows to `reports/fault-report.json`.
975
-
976
- ### Cost cap filtering
977
-
978
- Restrict auto-pick to choices whose catalog pricing stays under a USD-per-1M-token ceiling:
979
-
980
- ```ts
981
- // Both input and output rates must be <= $0.20 / 1M tokens
982
- await resolveAIProfile("balanced/default", { catalogLane: "text", costCapPer1M: 0.2 });
983
-
984
- // Finer control
985
- await resolveAIProfile("cheap/minimax_cheap", {
986
- catalogLane: "text",
987
- costCapPer1M: { maxInput: 0.2, maxOutput: 2 },
988
- });
989
- ```
990
-
991
- When the default choice exceeds the cap, resolution auto-picks the next compatible alternative (respecting fallback order and vendor preferences). Explicit `choice` values over the cap throw `NO_COST_CAP_MATCH`. Local/self-hosted choices are treated as zero cost.
992
-
993
- ### Keeping models aligned over time
994
-
995
- Bundled linkage lives in `src/data/models-registry.json`, built from `models-profiles.json` and `src/data/models-catalog.json`.
996
-
997
- Each catalog model has **two explicit call shapes** (never `provider: "openrouter"` with `modelId: "qwen/..."` as the only view):
998
-
999
- - `direct` — vendor-native (`{ provider: "google", modelId: "gemini-3.5-flash" }`)
1000
- - `openrouter` — transport (`{ provider: "openrouter", modelId: "google/gemini-3.5-flash" }`)
1001
-
1002
- Legacy open-assets files named `openrouter-models-catalog.json` are normalized into this shape on `catalog:pull`.
1003
-
1004
- When OpenRouter deprecates or renames a model slug:
1005
-
1006
- 1. Update `src/data/models-profiles.json` to a current vendor-native id (preferred).
1007
- 2. Refresh `src/data/models-catalog.json` via `npm run catalog:pull` (fetched from open-assets, normalized locally).
1008
- 3. Run alignment checks before publishing:
1009
-
1010
- ```bash
1011
- npm run registry:finish # merge profile catalog supplement, verified defaults, rebuild linkage
1012
- npm run catalog:sync # pull catalog, rebuild models-registry.json, verify
1013
- npm run catalog:pull # fetch open-assets catalog into src/data/
1014
- npm run catalog:build # rebuild models-registry.json + reports/fault-report.json
1015
- npm run verify:openrouter # bundled catalog + resolved slug policy (offline-safe)
1016
- npm run verify:openrouter:live # above + live OpenRouter API id check (needs network; retries 3x)
1017
- npm run catalog:verify # registry build / fault report from sync-models-registry
1018
- ```
1019
-
1020
- With the seed catalog (&lt;50 models), choices not yet listed are marked `catalog-miss` in the registry (warnings in `reports/fault-report.json`, not CI failures). A full catalog promotes true `faulty` rows for slug mismatches.
1021
-
1022
- Unit tests in `test/openrouterAlignment.test.ts`, `test/modelIdentity.test.ts`, `test/resolveModelIdentity.test.ts`, and `test/resolveModelRouting.test.ts` guard resolution rules offline.
1023
-
1024
- Vendor-direct-only choices (not routed via OpenRouter) can opt out:
1025
-
1026
- ```json
1027
- "metadata": { "openRouter": "vendor-direct" }
1028
- ```
1029
-
1030
- ## Tests
1031
-
1032
- ```bash
1033
- npm test # build + full suite
1034
- npm run test:unit # source tests only (skip integration/exports)
1035
- npm run test:integration # integration + dist export smoke tests
1036
- npm run pack:check # dry-run npm tarball contents
1037
- ```
1038
-
1039
- ## Publishing to npm
1040
-
1041
- This package is published as a **public** scoped module: `@x12i/ai-profiles` on [npmjs.com](https://www.npmjs.com/).
1042
-
1043
- ### Prerequisites
1044
-
1045
- 1. [npm](https://www.npmjs.com/) account with access to the **`@x12i`** organization/scope
1046
- 2. Authenticated CLI: `npm login` (or set `NPM_TOKEN` — see `.npmrc.example`)
1047
- 3. Git remote: [github.com/x12i/ai-profiles](https://github.com/x12i/ai-profiles)
1048
-
1049
- ### Publish locally
1050
-
1051
- ```bash
1052
- npm run pack:check # verify tarball includes dist/ + JSON data
1053
- npm publish --access public
1054
- ```
1055
-
1056
- `prepublishOnly` runs the full test suite; `prepack` rebuilds `dist/` before packing.
1057
-
1058
- ### Publish via GitHub Actions
1059
-
1060
- Workflow YAML is in [`docs/github-workflows/`](docs/github-workflows/). Copy into `.github/workflows/` and push using a GitHub token with the **`workflow`** scope (see `docs/github-workflows/README.md`).
1061
-
1062
- 1. Add repository secret **`NPM_TOKEN`** (npm automation token with publish rights for `@x12i`)
1063
- 2. Create a **GitHub Release** (tag e.g. `v1.0.0`) — triggers `publish-npm.yml`
1064
- 3. Or run **Publish to npm** workflow manually from the Actions tab
1065
-
1066
- ### After publish
1067
-
1068
- Consumers install with:
1069
-
1070
- ```bash
1071
- npm install @x12i/ai-profiles@^4.2.0
1072
- ```
1073
-
1074
- Peer dependency for downstream repos (graphs-studio, graph-engine, ai-tasks):
1075
-
1076
- ```json
1077
- "@x12i/ai-profiles": "^4.1.0"
1078
- ```
1079
-
1080
- ## License
1081
-
1082
- MIT — see [LICENSE](LICENSE).
1
+ > Part of the **ai-catalog** monorepo. Root docs: [../../README.md](../../README.md) · [../../docs/MONOREPO.md](../../docs/MONOREPO.md)
2
+
3
+ > **v4.4.1** adds `@x12i/ai-profiles/browser` for Vite/UI. Explore via `npm run ui` (AI Profiles tab).
4
+
5
+ # @x12i/ai-profiles
6
+
7
+ Resolve AI profile names into concrete model choices. The package ships JSON in `src/data/` as the offline fallback. By default, registry data is fetched from public assets, validated, and cached in memory.
8
+
9
+ > **v4.4** ships production routing (OpenRouter default + vendor-direct), product-line `*-latest-model` vendor routes, Gemini-backed google lanes, and **unversioned** open-assets URLs. Pin **`"@x12i/ai-profiles": "^4.4.0"`**. Upload `models-profiles.json` / `models-catalog.json` to open-assets **without** `.v4` / `.v2` suffixes.
10
+ >
11
+ > **v4.3** adds **`isConcreteModelId`**, **`isModelProfileReference`**, and **`toOptimixerModelProfile`** so consumers do not invent concrete-vs-profile or reasoning heuristics.
12
+ >
13
+ > **v3.2** adds **`normalizeInvokeModel`**, **`resolveAndNormalizeInvokeModel`**, and **`resolveAndNormalizeBundledInvokeModel`** for gateway invoke wire shape.
14
+ >
15
+ > **v3.0** removes legacy resolution inputs: shortcuts, bare profiles, and aliases. Only four resolution forms are accepted — `profile/choice`, vendor slug, gateway wire, and `{ provider, modelId }`. See [CHANGELOG.md](CHANGELOG.md).
16
+ >
17
+ > **v2.0** (still relevant): every `resolveAIProfile` call must pass `catalogLane` (`"text"`, `"image"`, …). Profile keys `deepseek` and `summarization` are gone — use `vol` and `sum`.
18
+
19
+ ## Why AI profiles
20
+
21
+ Any system that runs many different AI tasks—classification, architecture review, JSON extraction, tool-using agents—faces the same problem: **tasks are not interchangeable**. They differ in reasoning quality, cost sensitivity, latency, output shape (prose vs schema vs citations), and which provider traits matter (instruction following, long context, tool use).
22
+
23
+ Hardcoding one model everywhere leads to one of three failures: overpaying for simple high-volume work, under-serving hard problems with a weak model, or locking the product to a single vendor with no fallback when prices or availability change.
24
+
25
+ ### What a profile is
26
+
27
+ An **AI profile** is **not** a model. It is a **capability contract**: a stable name for *what kind of work* you need, not *which SKU* fulfills it.
28
+
29
+ When a graph node or function asks for `deep`, it means: high reasoning effort, complex work—resolve that intent to a concrete `provider` + `modelId` + runtime defaults **today**, without the caller caring whether that is Claude, GPT, or Gemini. The registry (`models-profiles.json`) is the mapping layer; profiles are the interface tasks depend on.
30
+
31
+ ### Profiles vs choices
32
+
33
+ | Layer | Role | Example |
34
+ |-------|------|---------|
35
+ | **Profile** | Semantic intent (cost, speed, reasoning tier, output mode, agentic behavior) | `cheap`, `balanced`, `json`, `agentic` |
36
+ | **Choice** | Implementation option within that profile (provider, model, batch vs sync, cost/quality trade-off) | `default`, `google_floor`, `anthropic_cheap` |
37
+
38
+ Every profile has a **`defaultChoice`** (recommended) and typically **two alternatives** so operators can tune without changing task code:
39
+
40
+ - **Provider diversity** — Anthropic (writing/reasoning), OpenAI (code/instruction following), Google (cost, long context) within the same profile.
41
+ - **Cost flexibility** — e.g. `balanced` + `google_balanced` vs `anthropic_balanced` for the same “normal work” intent.
42
+ - **Capability variants** — e.g. `google_deep` when the constraint is window size, not reasoning tier alone.
43
+ - **Execution mode** — e.g. `cheap` + `google_floor` with `executionMode: batch` for background bulk work.
44
+ - **Resilience** — swap choice or fall back within the same profile when a provider is down or rate-limited.
45
+
46
+ Tasks should declare **requirements** as explicit `profile/choice` keys (e.g. `cheap/default`), not model names. Use discovery APIs (`listAIProfiles`, `resolveAIProfileByTags`) to pick a profile when the caller does not already have a composite key.
47
+
48
+ ### Graph and stored model config
49
+
50
+ Graph JSON, studio defaults, and run overrides store **profile slot strings only** — never concrete provider model ids. Each task uses a complete triple:
51
+
52
+ | Slot | Example | Phase |
53
+ |------|---------|-------|
54
+ | `preActionModel` | `deep/default` | PRE (xynthesis / planning) |
55
+ | `skillModel` | `balanced/default` | MAIN (skill gateway) |
56
+ | `postActionModel` | `cheap/default` | POST (xynthesis / wrap-up) |
57
+
58
+ Canonical storage form is **`profile/choice`** (separator `/`). Use **`formatProfileChoiceKey(profile, choice)`** when writing slots and **`isKnownProfileInput(input)`** (or **`isKnownProfileChoice`** / **`matchStrictProfileInput`**) before persist or execute. Always include the choice segment — even for the profile default (`cheap/default`, not bare `cheap`).
59
+
60
+ **Classification SSOT (do not re-implement in consumers):**
61
+
62
+ | Question | API |
63
+ |----------|-----|
64
+ | Is this a profile-side authoring ref? | `isModelProfileReference(value)` (or strict `isKnownProfileInput` for `profile/choice` only) |
65
+ | Is this a concrete catalog model? | `isConcreteModelId(value)` |
66
+ | Reasoning capability? | `isReasoningModel(value)` / `resolved.modelSignals.isReasoningModel` |
67
+ | Optimixer `{ provider, model, reasoning }`? | `toOptimixerModelProfile(wire)` |
68
+
69
+ Never classify concrete models via vendor keywords (`gpt-`, `claude`, `gemini`) or `looksLike*` helpers — gaps belong upstream in this package.
70
+
71
+ ```json
72
+ "modelConfig": {
73
+ "cases": [
74
+ {
75
+ "modelConfig": {
76
+ "preActionModel": "cyber/default",
77
+ "skillModel": "audit/default",
78
+ "postActionModel": "cheap/default"
79
+ }
80
+ }
81
+ ]
82
+ }
83
+ ```
84
+
85
+ **At execute time**, hosts pass the stored alias triple unchanged; each phase resolves independently via `resolveAIProfile` (or `resolveAndNormalizeInvokeModel` at the gateway boundary). Do **not** pre-resolve aliases to concrete ids in graph JSON, `runtime.modelConfig`, or `aliasConfig`.
86
+
87
+ **Forbidden in stored config:** legacy keys (`xynthesisModel`, `postStrategyModel`), legacy aliases (`default`, `strong`, `weak`), bare profile keys (`cheap`), concrete slugs (`openai/gpt-4o-mini`), and legacy `@` composites (`cheap@anthropic_cheap` — migrate to `cheap/anthropic_cheap` on save).
88
+
89
+ ### Profile catalog (bundled)
90
+
91
+ Profiles are grouped by **what kind of work** they represent—not only by price/quality tier. Several axes are orthogonal (structured output, agents, research, local inference).
92
+
93
+ | Profile | Category | When to use it |
94
+ |---------|----------|----------------|
95
+ | `cheap` | cost | High-volume, non-critical work: routing, classification, simple transforms. “Cheap” means low-cost selection, not always the absolute cheapest SKU. |
96
+ | `fast` | speed | Interactive UX where latency matters more than maximum reasoning depth. |
97
+ | `balanced` | standard | Default workhorse: general graph execution, coding, product logic (~80% of tasks). |
98
+ | `deep` | reasoning | Hard problems: architecture, planning, analysis, code review—work that needs real reasoning, not pattern matching. |
99
+ | `pro` | premium | Critical outputs where quality or a wrong answer has high downstream cost; use sparingly. |
100
+ | `json` | output | Strict JSON/schema, extraction, classification—machine-readable pipelines (`outputMode: schema`, low temperature). |
101
+ | `agentic` | agentic | Tool use, planning, multi-step execution (`toolPolicy` allows writes with approval). |
102
+ | `research` | research | Source-heavy reading, synthesis, citations (read-only tools, web/file search). |
103
+ | `cyber` | security | Threat analysis, TPRM, contract verification, security log parsing. |
104
+ | `content` | creative | Prose, marketing copy, programmatic SEO, brand voice. |
105
+ | `sum` | analysis | Document triage, digests, compressing very large corpora. |
106
+ | `vol` | agent | Volume/economic agent lane (Flash default, Pro for hard/final). |
107
+ | `coding` | engineering | Software engineering: implementation, refactors, reviews, debugging. |
108
+ | `extraction` | extraction | NER, classification, taxonomy mapping, entity extraction, document labeling. |
109
+ | `routing` | routing | Intent classification, record routing, workflow branching (cheapest viable). |
110
+ | `local` | local | **CPU only** — runtime adapters (llama.cpp, Ollama, LM Studio, vLLM, Transformers.js, ONNX). **No OpenRouter.** |
111
+
112
+ ### Typical choices per profile
113
+
114
+ Each profile’s `choices` in `models-profiles.json` follow a consistent pattern: **`default`** (recommended), plus variants along cost, provider family, or a specific capability.
115
+
116
+ | Profile | Choices (bundled) | What the variants optimize |
117
+ |---------|-------------------|------------------------------|
118
+ | `cheap` | `default`, `google_floor`, `anthropic_cheap`, `deepseek_cheap`, `minimax_cheap` | Normal cheap vs batch floor vs safer Haiku vs DeepSeek volume floor vs MiniMax M2.5 |
119
+ | `fast` | `default`, `google_fast`, `anthropic_fast`, `grok_fast`, `minimax_fast` | Interactive default vs lower cost vs stronger quality vs Grok vs MiniMax M2 |
120
+ | `balanced` | `default`, `anthropic_balanced`, `google_balanced`, `minimax_balanced` | General default vs stronger reasoning vs lower cost vs MiniMax M2.5 |
121
+ | `deep` | `default`, `openai_deep`, `google_deep`, `deepseek_pro`, `grok_flagship`, `minimax_deep` | High reasoning default vs OpenAI vs long context vs DeepSeek vs Grok vs MiniMax M2.7 |
122
+ | `pro` | `default`, `claude_pro`, `anthropic_pro` | Premium default vs Claude premium vs Sonnet-level “pro-like” at lower cost |
123
+ | `json` | `default`, `google_json`, `anthropic_json` | Reliable schema output vs volume/cost vs complex extraction needing reasoning |
124
+ | `agentic` | `default`, `openai_agentic`, `google_agentic`, `minimax_agentic` | Agent default vs OpenAI orchestration vs lower-cost moderate agents vs MiniMax |
125
+ | `research` | `default`, `openai_research`, `google_research` | Synthesis default vs highest quality vs very large context |
126
+ | `cyber` | `default`, `log_analysis`, `deep_forensics` | Policy/contract review vs bulk log JSON vs max forensics |
127
+ | `content` | `default`, `pseo_bulk`, `brand_voice` | Natural prose vs batch pSEO schema vs premium copy |
128
+ | `sum` | `default`, `mega_context` | Fast digest (Haiku) vs multi-hundred-k token compression |
129
+ | `vol` | `default`, `flash`, `pro`, `final` | Volume/economic agent lane (Flash default, Pro for hard/final) |
130
+ | `local` | `llama_cpp_gguf`, `ollama`, `lmstudio_openai`, `vllm_openai`, `transformersjs_text`, `onnx_runtime` | **CPU / offline adapters** — env-probed local runtimes (no cloud LLM) |
131
+
132
+ Every **remote** profile choice must resolve to an active OpenRouter catalog id. Profiles without OpenRouter support are not included (use vendor APIs outside this registry, or add catalog coverage first). The only exception is the **`local`** profile, which is explicitly CPU / self-hosted.
133
+
134
+ Vendor-family profiles (`openai`, `claude`, `google`, `grok`, `deepseek`, …) also expose **`default` / `cheapest` / `best`** plus product-line **`<family>-latest-model`** choices (e.g. `google/flash-lite-latest-model`). Those choice *names* are aliases; `modelId` is always a **concrete** pinned SKU refreshed from the catalog.
135
+
136
+ ### OpenRouter-only and catalog lanes
137
+
138
+ Not every profile is OpenRouter-backed: **`local`** is CPU/self-hosted only (no catalog entry). All other bundled remote choices map to an entry in `models-catalog.json` with an active OpenRouter slug.
139
+
140
+ | Option | Purpose |
141
+ |--------|---------|
142
+ | `requireOpenRouterCatalog: true` | Fail resolution if the chosen model is not in the catalog with an active OpenRouter id (use for production paths that must not call vendor-direct guesses). |
143
+ | `catalogLane: "text" \| "image" \| …` | Only resolve profiles declared for that OpenRouter browser lane. Tier profiles (`cheap`, `cyber`, `vol`, …) are **`text`**. Lanes without profiles yet (`image`, `embeddings`, `rerank`, `speech`, `transcription`, …) can be added when you introduce lane-specific profiles. |
144
+ | `listAIProfiles({ catalogLane: "text" })` | List only lane-matching profiles. |
145
+
146
+ ```ts
147
+ await resolveAIProfile("cyber/default", {
148
+ catalogLane: "text",
149
+ requireOpenRouterCatalog: true,
150
+ });
151
+
152
+ await listAIProfiles({ catalogLane: "text" });
153
+ ```
154
+
155
+ ### Cost tiers (optional)
156
+
157
+ If you want to restrict model selection by price, you can either set an explicit `costCapPer1M`, or use a named `costTier`.
158
+
159
+ ```ts
160
+ import { resolveAIProfile } from "@x12i/ai-profiles";
161
+
162
+ // Tier-based (default tiers: tier1=$0.5/1M output, tier2=$3, tier3=$10, tier4=$30)
163
+ const cheapTier1 = await resolveAIProfile("balanced/default", {
164
+ catalogLane: "text",
165
+ costTier: "tier1",
166
+ });
167
+
168
+ // Override tiers (per-tier caps can be maxOutput/maxInput/maxBlended)
169
+ const customTier = await resolveAIProfile("balanced", {
170
+ catalogLane: "text",
171
+ costTier: "budget",
172
+ costTiers: [{ key: "budget", cap: { maxOutput: 0.5 } }],
173
+ });
174
+
175
+ // Explicit caps always win if both are provided
176
+ const explicitCap = await resolveAIProfile("balanced", {
177
+ catalogLane: "text",
178
+ costTier: "tier1",
179
+ costCapPer1M: { maxBlended: 2 },
180
+ });
181
+ ```
182
+
183
+ ### Alternatives by cost tier
184
+
185
+ When you want a profile’s “same intent, different price points”, use:
186
+
187
+ ```ts
188
+ import { resolveAIProfileWithCostAlternatives } from "@x12i/ai-profiles";
189
+
190
+ const { primary, alternativesByCostTier } =
191
+ await resolveAIProfileWithCostAlternatives("deep", {
192
+ catalogLane: "text",
193
+ tiers: [
194
+ { key: "tier1", cap: { maxOutput: 0.5 } },
195
+ { key: "tier2", cap: { maxOutput: 3 } },
196
+ { key: "tier3", cap: { maxOutput: 10 } },
197
+ ],
198
+ });
199
+
200
+ // alternativesByCostTier: [{ tier, resolved|null, reason? }, ...]
201
+ ```
202
+
203
+ ### Focus filters (catalog-derived)
204
+
205
+ You can filter choices (and optionally profile listings) by catalog-derived capabilities.
206
+
207
+ ```ts
208
+ import { listAIProfiles, resolveAIProfile } from "@x12i/ai-profiles";
209
+
210
+ // Preset focus filter
211
+ const reasoningModel = await resolveAIProfile("deep", {
212
+ catalogLane: "text",
213
+ focus: "reasoning",
214
+ });
215
+
216
+ // Explicit capability filter
217
+ const structured = await resolveAIProfile("json", {
218
+ catalogLane: "text",
219
+ capabilityFilter: { structuredOutput: true },
220
+ });
221
+
222
+ // Filter profile discovery to profiles with at least one matching choice
223
+ const reasoningProfiles = await listAIProfiles({
224
+ source: "bundled",
225
+ focus: "reasoning",
226
+ });
227
+ ```
228
+
229
+ ### Reasoning model flag (always communicated)
230
+
231
+ Every resolved primary and secondary includes a stable boolean:
232
+
233
+ ```ts
234
+ const resolved = await resolveAIProfile("cheap/default", {
235
+ catalogLane: "text",
236
+ includeSecondary: true,
237
+ });
238
+
239
+ resolved.modelSignals.isReasoningModel; // boolean
240
+ resolved.secondary?.modelSignals.isReasoningModel; // boolean
241
+ ```
242
+
243
+ Registry fields on each choice—`runtime` (`reasoningEffort`, `toolPolicy`, `outputMode`, `instructionTier`, `backend`), `modelStatus` (`verified` | `predicted`), `api` (vendor + OpenRouter slugs), and `reason`—document *why* that model backs the choice. **Pricing and capabilities** come from `models-catalog.json` at resolve time. Profile-level `requiredCapabilities` describes intent for future dynamic selection (Optimixer). Consumers use `resolveAIProfile` to materialize the merged result.
244
+
245
+ ## Install
246
+
247
+ ```bash
248
+ npm install @x12i/ai-profiles
249
+ ```
250
+
251
+ ## Public API
252
+
253
+ ### Profiles and registry loading
254
+
255
+ | Export | Sync? | Purpose |
256
+ |--------|-------|---------|
257
+ | `listAIProfiles(options?)` | No (async) | Profile summaries: primary `profile` key, tags, choices, defaults |
258
+ | `getAIRegistryStatistics(options?)` | No (async) | Counts: profiles, choices, providers, catalog models, linkage health |
259
+ | `formatRegistryStatistics(stats)` | Yes | Human-readable summary for logs / CLI |
260
+ | `loadAIProfilesRegistry(options?)` | No (async) | Raw profiles registry (`auto` / `remote` / `bundled`, 24h memory cache) |
261
+ | `loadAIProfilesRegistryWithWarnings(options?)` | No (async) | Same as above, plus `warnings[]` (stale cache, bundled fallback, etc.) |
262
+ | `loadModelsCatalog(options?)` | No (async) | Unified models catalog (`auto` / `remote` / `bundled`, same cache pattern as profiles) |
263
+ | `loadBundledModelsCatalog()` | Yes | Package-shipped `models-catalog.json` only |
264
+ | `loadBundledModelsRegistry()` | Yes | Package-shipped `models-registry.json` (linkage index) |
265
+ | `listAIProfileChoices(options?)` | No (async) | List explicit `profile/choice` keys for strict pickers and stored config |
266
+ | `formatProfileChoiceKey(profile, choice)` | Yes | Build canonical slot key (`cheap/default`) |
267
+ | `parseProfileChoiceKey(input)` | Yes | Parse `profile/choice` (accepts `\` as separator on input) |
268
+ | `matchStrictProfileInput(registry, input)` | Yes | Resolve input to profile+choice or `invalidChoice` |
269
+ | `isKnownProfileChoice(input)` | Yes (bundled only) | Whether input is a known valid `profile/choice` key |
270
+ | `isKnownProfileInput(input)` | Yes (bundled only) | Profile-intent gate: known `profile/choice` → `true`; concrete model ids → `false` |
271
+ | `isKnownProfileOrShortcut(input)` | Yes (bundled only) | Alias of `isKnownProfileInput` (shortcuts are not supported) |
272
+ | `isModelProfileReference(input)` | Yes (bundled only) | Authoring gate: known `profile/choice`, bare profile key, or legacy `profile@choice` |
273
+ | `isConcreteModelId(input)` | Yes (bundled only) | Catalog-backed concrete model gate (no vendor-keyword heuristics) |
274
+ | `toOptimixerModelProfile(input)` | Yes (bundled only) | `{ provider, model, reasoning }` from catalog wire (optional profile resolve) |
275
+ | `isKnownProfileChoiceInput(registry, input)` | Yes | Same as above with an explicit registry |
276
+ | `getBundledRegistry()` | Yes | Sync bundled profiles registry (no network) |
277
+ | `resolveBundledAIProfile(input, options)` | Yes | Strict `profile/choice` → model, pricing, runtime (`source: "bundled"`) |
278
+ | `resolveBundledInput(input, options)` | Yes | Unified sync resolver: `profile/choice` → registry; vendor slug / gateway wire / `{ provider, modelId }` → catalog |
279
+ | `resolveInput(input, options)` | No (async) | Unified async resolver (same order as `resolveBundledInput`; `source: "auto" \| "remote" \| "bundled"`) |
280
+ | `resolveBundledCatalogModel(input, options?)` | Yes | Sync strict catalog resolution (exact/high confidence only) |
281
+ | `ensureConcreteModel(input, options?)` | Yes | String normalizer: `profile/choice` (strict) or concrete model (catalog best-effort) → invoke-time `{ provider, modelId }` |
282
+ | `normalizeInvokeModel(input, options?)` | Yes | Idempotent gateway invoke tuple: strips `openrouter/` display slugs; rejects unresolved `profile/choice` aliases |
283
+ | `resolveAndNormalizeInvokeModel(alias, options)` | No (async) | `resolveAIProfile` → `normalizeInvokeModel` for MAIN / handoff paths |
284
+ | `resolveAndNormalizeBundledInvokeModel(alias, options)` | Yes | Bundled `resolveAIProfile` → `normalizeInvokeModel` (no network) |
285
+ | `calculateInvokeCost(input, options?)` | No (async) | Token → USD from catalog pricing (`costStatus: "priced" \| "unpriced"`) |
286
+ | `calculateInvokeCostSync(input, options?)` | Yes | Bundled offline cost calculator |
287
+ | `calculateInvokeCostFromRecord(record, options?)` | No (async) | Activix snake_case usage record → USD |
288
+ | `buildInvokePricingRecord(input)` | Yes | Build Activix-compatible invoke billing record |
289
+ | `lookupBundledCatalogCaps({ provider, modelId })` | Yes | Sync quick caps + pricing summary from bundled catalog |
290
+ | `lookupBundledCatalogModel(slug, options?)` | Yes | Sync rich catalog snapshot for a slug (pricing, reasoning, modalities); returns `undefined` on miss |
291
+ | `resolveBundledCatalogModelDetails(slug, options?)` | Yes | Same as above but throws `UNKNOWN_MODEL` on miss |
292
+ | `resolveCatalogModelDetails(slug, options?)` | No (async) | Rich catalog snapshot with optional remote catalog refresh |
293
+ | `isReasoningModel(input, options?)` | Yes | `true`/`false` for supported inputs (throws `UNKNOWN_MODEL` on unknown concrete models) |
294
+ | `resolveAIProfile(input, options?)` | No (async) | Resolve an explicit `profile/choice` key → model, pricing, runtime. Pass `includeSecondary: true` to attach `secondary`; `includeCatalog: true` to attach full `catalogModel`. |
295
+ | `resolveSecondaryModel(input, options?)` | No (async) | Resolve primary choice + optional companion `secondary` from profile `secondary` refs |
296
+ | `getSecondaryForResolvedProfile(resolved, registry, catalog?)` | Yes | Secondary for an already-resolved primary (no extra I/O when catalog is passed) |
297
+ | `listProfileSecondaries(profileKey, registry)` | Yes | List per-choice `secondary` declarations on a profile |
298
+ | `resolveAIProfileByTags(tags, options?)` | No (async) | Pick best profile by weighted tags (`tagMatch`, excludes discovery by default), then resolve |
299
+ | `listAICatalogModels(options?)` | No (async) | Filter/rank catalog models by tags, provider, status, modalities, tools/reasoning; attaches intent `profileChoices` |
300
+ | `resolveCatalogModelByTags(tags, options?)` | No (async) | Best catalog model by weighted tags (+ optional profile branch map) |
301
+ | `scoreProfileTags` / `rankProfilesByTags` | Yes | Weighted tag scoring for discovery and custom UIs |
302
+ | `AIProfilesError` / `AIProfilesErrorCode` | — | Typed errors (`UNKNOWN_PROFILE`, `INVOKE_MODEL_ALIAS_AT_GATEWAY`, `INVOKE_MODEL_SHAPE_INVALID`, …) |
303
+
304
+ ### Model identity (vendor + model strings)
305
+
306
+ Use these when callers pass **raw model ids or OpenRouter slugs**, not profile names.
307
+
308
+ | Export | Sync? | Purpose |
309
+ |--------|-------|---------|
310
+ | `resolveCatalogModel(input, options?)` | No (async) | Resolve a model SKU or OpenRouter slug via `models-catalog.json` (strict; no profile intent) |
311
+ | `resolveModelIdentity(input, options?)` | Yes | Given a bare id or `vendor/slug`, return `{ provider, modelId, invocation? }` via bundled registry + catalog fallback. Returns `null` for known `profile/choice` keys. |
312
+ | `buildModelInvocation(provider, modelId)` | Yes | `{ direct, openrouter }` endpoints for a provider hint + model string |
313
+ | `buildDirectInvocation(provider, modelId)` | Yes | Vendor-direct `{ provider, modelId }`; splits prefixed slugs for all vendors |
314
+ | `buildOpenRouterModelId(provider, modelId)` | Yes | Build an OpenRouter slug (`openai/gpt-5.4`) from registry fields |
315
+ | `parseDirectFromOpenRouterSlug(slug, family?)` | Yes | Split `vendor/model` → direct slice (`custom` + bare id when vendor is not a first-class provider) |
316
+ | `normalizeAnthropicVersionSlug(slug)` | Yes | Dotted minor versions for Anthropic (`4-6` → `4.6`) |
317
+ | `buildRegistryKey(provider, modelId)` | Yes | Stable registry key (`vendor:…`) used in `models-registry.json` |
318
+ | `matchOpenRouterCatalog(provider, modelId, index)` | Yes | Match a choice against a catalog index |
319
+ | `lookupInvocationForChoice(registry, provider, modelId)` | Yes | Lookup prebuilt invocation from `models-registry.json` |
320
+
321
+ **Prefixed slugs:** `buildDirectInvocation("meta-llama", "meta-llama/llama-3.1-8b-instruct")` yields `{ provider: "meta-llama", modelId: "llama-3.1-8b-instruct" }`. Host paths keep the nested id when the provider hint differs (e.g. Together: `together` + `meta-llama/Llama-3.3-70b-instruct`). Bare and prefixed Anthropic inputs normalize to the same direct and OpenRouter ids.
322
+
323
+ ### Routing, validation, and maintainer tooling
324
+
325
+ | Export | Sync? | Purpose |
326
+ |--------|-------|---------|
327
+ | `resolvePreferOpenRouter(explicit?)` | Yes | Resolve OpenRouter vs vendor-direct routing (option → env → default) |
328
+ | `applyModelRouting(choice, backend, preferOpenRouter, catalog?)` | Yes | Turn a registry choice into invoke-time `{ provider, modelId, routing }` (same rules as `resolveAIProfile`) |
329
+ | `normalizeGatewayWireId(input)` | Yes | `openrouter/openai/gpt-5.5` → `{ provider: "openrouter", modelId: "openai/gpt-5.5" }` (profile keys like `cheap/default` are not gateway wires) |
330
+ | `validateBundledProfileVendorCoverage(options?)` | Yes | Advisory report of leading-vendor coverage per profile |
331
+ | `validateBundledProfileModalityCoverage(options?)` | Yes | Advisory report of profile choice vs required input/output media |
332
+ | `isProfileVendorTrimReady(profile, allowedProviders)` | Yes | Whether auto-pick can satisfy a vendor filter |
333
+ | `isProfileModalityCoverageReady(profileKey)` | Yes | Whether a profile has at least one modality-compatible choice |
334
+ | `listFaultyProfileChoices()` | Yes | Profile choices with faulty OpenRouter catalog linkage |
335
+ | `buildModelsRegistry`, `verifyOpenRouterAlignment`, … | Yes | Catalog/registry build and alignment (see scripts below) |
336
+
337
+ Registry JSON lives in four bundled assets:
338
+
339
+ | File | Schema | Role |
340
+ |------|--------|------|
341
+ | `models-profiles.json` | `x12i.ai-profiles.model-registry.v4` | Profile intent, lean choices referencing catalog — **no embedded pricing** |
342
+ | `models-catalog.json` | `x12i.ai-profiles.models-catalog` (v2.0.0) | Per-model pricing, capabilities, `modelFamily` (OpenRouter-normalized) |
343
+ | `models-registry.json` | `x12i.ai-profiles.models-registry` | Built linkage index: vendor keys, OpenRouter slugs, `invocation` pairs |
344
+
345
+ **v4 contract:** Each profile choice stores `provider` + **vendor-native** `modelId` as a pointer into `models-catalog.json`, which owns the `direct` and `openrouter` listings. Choice `displayName` / `description` are optional (hydrated from catalog). Never embed `api`, `defaultTransport`, or OpenRouter slugs on profile choices. Vendor-family profiles (`vendorFamily: true`) expose `default` / `cheapest` / `best` / `<family>-latest-model` without hijacking concrete slugs like `openai/gpt-4`. Run `npm run registry:finish` to strip legacy fields, verify linkage, and rebuild `models-registry.json`.
346
+
347
+ Validate with `src/data/models-profiles.schema.json`. Maintainer scripts: `npm run catalog:extend-profiles`, `npm run registry:finish` (catalog supplement + verified defaults + linkage rebuild).
348
+
349
+ ## Sync bundled resolution (predict / invoke)
350
+
351
+ For consumers that need **no network** and a single entry point:
352
+
353
+ ```ts
354
+ import {
355
+ ensureConcreteModel,
356
+ isKnownProfileInput,
357
+ isReasoningModel,
358
+ resolveBundledInput,
359
+ resolveBundledAIProfile,
360
+ applyModelRouting,
361
+ normalizeGatewayWireId,
362
+ lookupBundledCatalogCaps,
363
+ getBundledRegistry,
364
+ } from "@x12i/ai-profiles";
365
+
366
+ // Four supported resolution forms:
367
+ // 1. profile/choice → registry (strict)
368
+ // 2. vendor slug → catalog (strict in resolveBundledCatalogModel; best-effort in ensureConcreteModel)
369
+ // 3. gateway wire → catalog
370
+ // 4. { provider, modelId } → catalog
371
+
372
+ ensureConcreteModel("cheap/default");
373
+ // → { provider: "openrouter", modelId: "deepseek/deepseek-v4-flash", profileChoice: { profile: "cheap", choice: "default" } }
374
+
375
+ ensureConcreteModel("google/gemini-2.5-flash-lite");
376
+ // → { provider: "openrouter", modelId: "google/gemini-2.5-flash-lite", matchConfidence: "exact" }
377
+
378
+ ensureConcreteModel("openrouter/openai/gpt-5.5");
379
+ // → { provider: "openrouter", modelId: "openai/gpt-5.5" }
380
+
381
+ if (isKnownProfileInput("cheap/default")) {
382
+ const resolved = resolveBundledInput("cheap/default", { catalogLane: "text" });
383
+ // resolved.provider is never "cheap"
384
+ }
385
+
386
+ const wire = normalizeGatewayWireId("openrouter/openai/gpt-5.5");
387
+ // → { provider: "openrouter", modelId: "openai/gpt-5.5" }
388
+
389
+ isReasoningModel("deep/default"); // true
390
+ isReasoningModel("cheap/default"); // true (catalog marks gemini-2.5-flash-lite reasoning-capable)
391
+ isReasoningModel("google/gemini-2.5-flash-lite"); // false
392
+
393
+ const caps = lookupBundledCatalogCaps({
394
+ provider: "openrouter",
395
+ modelId: "google/gemini-2.5-flash-lite",
396
+ });
397
+
398
+ const registry = getBundledRegistry();
399
+ const routed = applyModelRouting(
400
+ registry.profiles.cheap.choices.default,
401
+ "openrouter",
402
+ true,
403
+ );
404
+ ```
405
+
406
+ For the same profile-first order with optional remote registry/catalog (`source: "auto"` / `"remote"` / `"bundled"`), use **`resolveInput`**:
407
+
408
+ ```ts
409
+ import { resolveInput } from "@x12i/ai-profiles";
410
+
411
+ await resolveInput("cheap/default", { catalogLane: "text", source: "auto" });
412
+ await resolveInput("google/gemma-3-4b-it", { source: "bundled" });
413
+ ```
414
+
415
+ `isKnownProfileInput` / `isKnownProfileChoice` return **false** for bare profiles (`cheap`), legacy shortcuts (`cheapest`), and concrete slugs (`google/gemini-2.5-flash-lite`).
416
+
417
+ ## Basic usage
418
+
419
+ ```ts
420
+ import {
421
+ listAIProfiles,
422
+ listAIProfileChoices,
423
+ isKnownProfileInput,
424
+ resolveAIProfile,
425
+ resolveCatalogModel,
426
+ resolveInput,
427
+ } from "@x12i/ai-profiles";
428
+
429
+ const profiles = await listAIProfiles();
430
+ const choices = await listAIProfileChoices();
431
+
432
+ // Strict lookup key: profile/choice
433
+ const model = await resolveAIProfile("cheap/default", { catalogLane: "text" });
434
+ // Or unified async: await resolveInput("cheap/default", { catalogLane: "text" });
435
+
436
+ console.log(model.profile); // canonical primary key: cheap
437
+ console.log(model.provider); // "openrouter" by default for remote profiles
438
+ console.log(model.modelId); // "google/gemini-2.5-flash-lite"
439
+ console.log(model.routing); // "openrouter" | "direct"
440
+ console.log(model.pricing); // from models-catalog.json
441
+ console.log(model.modelStatus); // verified | predicted
442
+ console.log(model.requiredCapabilities); // profile intent
443
+ console.log(model.capabilities); // contextWindow, supportsTools, …
444
+ console.log(model.instructionTier);
445
+ console.log(model.backend);
446
+
447
+ // SKU lookup (catalog), not a profile
448
+ const sku = await resolveCatalogModel("google/gemini-2.5-flash-lite", {
449
+ source: "bundled",
450
+ preferOpenRouter: false,
451
+ });
452
+
453
+ console.log(isKnownProfileInput("cheap/default")); // true
454
+ console.log(isKnownProfileInput("cheap")); // false
455
+ ```
456
+
457
+ ## Registry statistics
458
+
459
+ Use **`getAIRegistryStatistics()`** for discovery dashboards, CI summaries, and operator tooling. It loads profiles and the models catalog with the same `source` / `refresh` options as `resolveAIProfile`, then returns structured counts.
460
+
461
+ ```ts
462
+ import {
463
+ formatRegistryStatistics,
464
+ getAIRegistryStatistics,
465
+ } from "@x12i/ai-profiles";
466
+
467
+ const { statistics, warnings } = await getAIRegistryStatistics({
468
+ source: "bundled", // or "auto" | "remote"
469
+ includeCatalog: true,
470
+ includeLinkage: true,
471
+ });
472
+
473
+ console.log(statistics.profiles.total);
474
+ console.log(statistics.profiles.providers);
475
+ console.log(statistics.catalog?.totalModels);
476
+ console.log(statistics.linkage?.faulty);
477
+
478
+ console.log(formatRegistryStatistics(statistics));
479
+ ```
480
+
481
+ CLI (after build): `npm run stats` (text) or `npm run stats:json`.
482
+
483
+ ## Supported resolution inputs
484
+
485
+ Resolution accepts exactly **four** input forms:
486
+
487
+ | Form | Example | Resolver |
488
+ |------|---------|----------|
489
+ | Profile + choice | `cheap/default` | Registry (`resolveAIProfile`, `resolveBundledAIProfile`) |
490
+ | Vendor slug | `google/gemini-2.5-flash-lite` | Catalog (`resolveCatalogModel`, `resolveBundledCatalogModel`) |
491
+ | Gateway wire | `openrouter/openai/gpt-5.5` | Catalog (gateway normalization) |
492
+ | Object | `{ provider: "google", modelId: "gemini-2.5-flash-lite" }` | Catalog |
493
+
494
+ **Not supported:** shortcuts (`cheapest`), bare profiles (`cheap`), aliases (`cost-sensitive`). Use discovery to pick a profile, then resolve an explicit `profile/choice`.
495
+
496
+ **Tags exist to filter.** Short codes on profiles and catalog models (`cyb`, `eco`, `cod`, `oai`, …). Get the tag list, then filter:
497
+
498
+ ```ts
499
+ import {
500
+ listAIProfileTags, // all allowed tags (+ labels)
501
+ listUsedAIProfileTags, // tags present in the loaded registry
502
+ listAIProfiles, // filter profiles by tags
503
+ resolveAIProfileByTags, // pick best matching profile → resolve it
504
+ listAICatalogModels, // filter catalog models by tags
505
+ resolveCatalogModelByTags, // pick best matching model (+ optional profile branch)
506
+ } from "@x12i/ai-profiles";
507
+
508
+ listAIProfileTags(); // glossary for pickers
509
+ await listUsedAIProfileTags({ source: "bundled" }); // what's actually used
510
+
511
+ // Filter: keep profiles that have these tags
512
+ await listAIProfiles({ tags: ["cyb", "eco"], tagMatch: "any" }); // any of
513
+ await listAIProfiles({ tags: ["cyb", "sec"], tagMatch: "all" }); // all of
514
+
515
+ // Filter + resolve in one step
516
+ await resolveAIProfileByTags(["cyb", "eco", "ds"], { catalogLane: "text" });
517
+
518
+ // Catalog models (tags are derived + inherited during registry:finish)
519
+ await listAICatalogModels({
520
+ tags: ["cod", "eco"],
521
+ tagMatch: "all",
522
+ provider: "google",
523
+ status: "active",
524
+ supportsTools: true,
525
+ });
526
+ await resolveCatalogModelByTags(["cod", "eco"], { catalogLane: "text" });
527
+ ```
528
+
529
+ `tagMatch: "any"` (default) = match if any requested tag is present. `"all"` = every requested tag must be present. Results are ranked by **weighted** tag score (domain/task 3, capability 2, tier/vendor 1, `wf` 0.25), then coverage ratio, then fewer tags.
530
+
531
+ **Discovery exclusion:** by default, tag list/resolve pools skip `vendorFamily` and `category: "discovery"` profiles (`catalog`, `claude`, `grok`, …). Pass `includeDiscovery: true`, or include the `vnd` tag, to include them.
532
+
533
+ Input is normalized (trimmed, lowercased) before matching. Composite keys accept **`/` or `\`** as the separator (`cyber\default` → `cyber/default`). **Profile and choice segment names treat `-` and `_` as equivalent** (`cheap/google-floor` → `cheap/google_floor`).
534
+
535
+ ### Examples
536
+
537
+ ```ts
538
+ // Composite key
539
+ await resolveAIProfile("balanced/default", { catalogLane: "text" });
540
+
541
+ // Tag-based pick (partial overlap OK) → explicit profile/choice
542
+ await resolveAIProfileByTags(["cyb", "eco", "ds"], { catalogLane: "text" });
543
+
544
+ // Model SKU → catalog, not a profile
545
+ await resolveCatalogModel("google/gemini-2.5-flash-lite", { source: "bundled" });
546
+
547
+ // String normalizer for invoke-time routing
548
+ ensureConcreteModel("cheap/default");
549
+ ensureConcreteModel("google/gemini-2.5-flash-lite");
550
+ ```
551
+
552
+ `listAIProfiles()` returns profile keys, tags, and choices for pickers. `listAIProfileChoices()` lists every valid `profile/choice` composite key.
553
+
554
+ ## Invoke wire shape (gateway / HTTP)
555
+
556
+ Downstream packages (`ai-tasks`, `ai-skills`, `ai-gateway`, `xynthesis`, `optimixer`) must agree on what is sent on the wire **after** semantic resolution. **Stored graph config** uses `profile/choice` aliases; **gateway / HTTP** uses the invoke tuple below.
557
+
558
+ ### Display slug
559
+
560
+ A **display slug** is a single string with an `openrouter/` prefix for human-readable UI and logs, e.g. `openrouter/deepseek/deepseek-v4-pro`. Studio pickers, plan previews, and Activix run logs may show this form. It is **not** the shape passed to `ai-gateway` catalog lookup or OpenRouter HTTP — normalize before those boundaries.
561
+
562
+ ### Invoke tuple
563
+
564
+ An **invoke tuple** is `{ provider, model, routing }` where `provider` is `"openrouter"` (or a vendor for direct routing) and `model` is the **bare** vendor/model slug without a gateway prefix, e.g. `{ provider: "openrouter", model: "deepseek/deepseek-v4-pro", routing: "openrouter" }`. This is what `ai-gateway` uses for catalog lookup and what OpenRouter HTTP expects.
565
+
566
+ Call **`normalizeInvokeModel`** at every gateway boundary (idempotent). Profile intent still goes through **`resolveAIProfile`** first, or use **`resolveAndNormalizeInvokeModel`** / **`resolveAndNormalizeBundledInvokeModel`** for the combined path.
567
+
568
+ | Export | Sync? | Purpose |
569
+ |--------|-------|---------|
570
+ | `normalizeInvokeModel(input, options?)` | Yes | Display slug or invoke object → canonical invoke tuple; rejects unresolved `profile/choice` |
571
+ | `resolveAndNormalizeInvokeModel(alias, options)` | No (async) | `resolveAIProfile` → `normalizeInvokeModel` |
572
+ | `resolveAndNormalizeBundledInvokeModel(alias, options)` | Yes | Bundled `resolveAIProfile` → `normalizeInvokeModel` (no network) |
573
+
574
+ ```ts
575
+ import {
576
+ normalizeInvokeModel,
577
+ resolveAndNormalizeInvokeModel,
578
+ resolveAndNormalizeBundledInvokeModel,
579
+ } from "@x12i/ai-profiles";
580
+
581
+ // Display slug → invoke tuple (string or { model } object)
582
+ normalizeInvokeModel("openrouter/deepseek/deepseek-v4-pro");
583
+ normalizeInvokeModel({ model: "openrouter/deepseek/deepseek-v4-pro" });
584
+ // → { provider: "openrouter", model: "deepseek/deepseek-v4-pro", routing: "openrouter", displaySlug: "..." }
585
+
586
+ // Already-correct tuple → unchanged (idempotent)
587
+ normalizeInvokeModel({ provider: "openrouter", model: "deepseek/deepseek-v4-pro" });
588
+
589
+ // Unresolved profile/choice at gateway → INVOKE_MODEL_ALIAS_AT_GATEWAY
590
+ normalizeInvokeModel("cheap/default");
591
+ normalizeInvokeModel({ model: "cheap/default" }); // same error
592
+
593
+ // Profile/choice → resolve, then normalize (gateway catalog-lookup tuple)
594
+ await resolveAndNormalizeInvokeModel("cyber/deep_forensics", {
595
+ catalogLane: "text",
596
+ preferOpenRouter: true,
597
+ });
598
+ // → { provider: "openrouter", model: "deepseek/deepseek-v4-pro", routing: "openrouter", ... }
599
+
600
+ // Sync bundled variant (tests, predict paths)
601
+ resolveAndNormalizeBundledInvokeModel("cyber/deep_forensics", {
602
+ catalogLane: "text",
603
+ preferOpenRouter: true,
604
+ });
605
+ ```
606
+
607
+ **Error codes** (on `AIProfilesError.code`):
608
+
609
+ | Code | When |
610
+ |------|------|
611
+ | `INVOKE_MODEL_ALIAS_AT_GATEWAY` | `profile/choice` reached `normalizeInvokeModel` without prior `resolveAIProfile` |
612
+ | `INVOKE_MODEL_SHAPE_INVALID` | Empty model, missing provider, or unparseable composite after normalization |
613
+
614
+ `allowAlias: true` exists for rare internal paths; **gateway and HTTP callers should not use it** — resolve aliases first.
615
+
616
+ ## Sync validation (bundled registry)
617
+
618
+ Use **`isKnownProfileInput(input)`** (or **`isKnownProfileChoice`**) before run/execute or on first paint when the remote registry may not be loaded yet. It reads the **bundled** JSON only (no network, no in-memory cache race).
619
+
620
+ ```ts
621
+ const canRun =
622
+ isKnownProfileInput(aiProfileKey) &&
623
+ isKnownProfileInput(fallbackKey);
624
+ ```
625
+
626
+ Accepts **valid `profile/choice` keys only**. Unknown strings return `false`.
627
+
628
+ After validation, call `resolveAIProfile` (usually `source: "auto"` or `"bundled"`) to get the canonical `resolved.profile` and the concrete model details.
629
+
630
+ ### UI guidance
631
+
632
+ - **Profile picker**: `await listAIProfiles()` → use each row’s `profile` as the value; show `displayName` as the label.
633
+ - **Choice picker**: `await listAIProfileChoices({ profile: "cheap" })` or list choices from the profile summary.
634
+ - **Stored config**: store `profile/choice` composite keys (e.g. `cheap/default`).
635
+
636
+ ## Pick a specific model implementation (choice)
637
+
638
+ ```ts
639
+ const model = await resolveAIProfile("cheap/anthropic_cheap", {
640
+ catalogLane: "text",
641
+ });
642
+ ```
643
+
644
+ ## OpenRouter vs vendor-direct routing
645
+
646
+ Remote profiles (anything that is not `local` / on-device) can be resolved for **OpenRouter** or for a **vendor API directly**. Local CPU profiles are always returned as-is.
647
+
648
+ ### Resolution priority
649
+
650
+ 1. **`options.preferOpenRouter`** when passed to `resolveAIProfile`
651
+ 2. **`PREFER_OPENROUTER`** in `.env` / process env
652
+ 3. **Default: `true`** (OpenRouter)
653
+
654
+ Supported today: **OpenRouter** and **vendor-direct**. Azure and AWS routing are not supported yet.
655
+
656
+ ### OpenRouter (default)
657
+
658
+ ```ts
659
+ const resolved = await resolveAIProfile("cheap/default", { catalogLane: "text" });
660
+ // or explicitly:
661
+ await resolveAIProfile("cheap/default", { catalogLane: "text", preferOpenRouter: true });
662
+
663
+ // resolved.provider === "openrouter"
664
+ // resolved.modelId === "google/gemini-3.1-flash-lite"
665
+ // resolved.routing === "openrouter"
666
+ // resolved.backend === "openrouter"
667
+ ```
668
+
669
+ Registry choices store vendor-native ids (e.g. `gpt-5.4`, `gemini-2.5-flash-lite`). When routing via OpenRouter, this package rewrites them to full slugs: `{vendor}/{model}` (e.g. `openai/gpt-5.4`, `anthropic/claude-sonnet-4.6`). Anthropic version segments are normalized to dotted form (`4.6`, not `4-6`).
670
+
671
+ This applies to any `profile/choice` input that resolves to a remote profile choice.
672
+
673
+ ### Avoid hardcoded OpenRouter slugs (especially dated previews)
674
+
675
+ Do **not** copy OpenRouter slugs into graph JSON or app config (`preActionModel`, `skillModel`, `postActionModel`, env vars, etc.) and do **not** use `canonicalSlug` from the catalog for API calls. OpenRouter retires dated preview ids (e.g. `google/gemini-2.5-flash-lite-preview-06-17`) while stable ids remain (`google/gemini-2.5-flash-lite`).
676
+
677
+ ```ts
678
+ // Good — store profile/choice; resolve at execute time
679
+ preActionModel: "cheap/default";
680
+ skillModel: "balanced/default";
681
+ postActionModel: "cheap/default";
682
+
683
+ const pre = await resolveAIProfile("cheap/default", { catalogLane: "text" });
684
+ // pre.modelId → "google/gemini-2.5-flash-lite" (concrete id only after resolution)
685
+
686
+ // Bad — concrete slug in stored config (stale when catalog moves)
687
+ preActionModel: "google/gemini-2.5-flash-lite-preview-06-17";
688
+ ```
689
+
690
+ Use `assertStableOpenRouterSlug(slug)` before outbound OpenRouter calls when you must accept external slug strings. Run `npm run verify:openrouter:live` in CI to catch catalog drift.
691
+
692
+ ### Vendor-direct
693
+
694
+ ```ts
695
+ const resolved = await resolveAIProfile("cheap/default", {
696
+ catalogLane: "text",
697
+ preferOpenRouter: false,
698
+ });
699
+
700
+ // resolved.provider === "google"
701
+ // resolved.modelId === "gemini-2.5-flash-lite"
702
+ // resolved.routing === "direct"
703
+ // resolved.backend === "custom"
704
+ ```
705
+
706
+ Use this when calling OpenAI, Anthropic, Google, etc. APIs directly instead of through OpenRouter.
707
+
708
+ ### Rich catalog data (pricing, reasoning, modalities)
709
+
710
+ Use the right entry point for your input shape:
711
+
712
+ | Input | Function | Returns |
713
+ |-------|----------|---------|
714
+ | OpenRouter / vendor slug | `resolveCatalogModelDetails(slug)` or sync `lookupBundledCatalogModel(slug)` | `ResolvedCatalogModel` |
715
+ | `profile/choice` | `resolveAIProfile(key, { catalogLane, includeCatalog: true })` | `ResolvedAIProfile` + `catalogModel` |
716
+ | Post-resolve slug check | `requireCatalogModel(slug, { includeDetails: true })` | presence + optional `catalogModel` |
717
+
718
+ ```ts
719
+ // Slug → full catalog enrichment
720
+ const model = await resolveCatalogModelDetails("google/gemini-2.5-flash-lite", {
721
+ source: "bundled",
722
+ });
723
+ model.pricing?.input; // flattened per-1M rates
724
+ model.catalogPricing?.imageInput; // raw OpenRouter pricing slice
725
+ model.contextWindow; // e.g. 1048576
726
+ model.maxCompletionTokens; // e.g. 65536 (catalog maxCompletionTokens)
727
+ model.limits?.maxOutputTokens; // same as maxCompletionTokens
728
+ model.modelSignals.isReasoningModel; // true
729
+ model.modelSignals.maxOutputTokens; // same as maxCompletionTokens
730
+ model.catalogCapabilities?.toolCalling; // true
731
+ model.invocation.openrouter?.modelId; // "google/gemini-2.5-flash-lite"
732
+ model.capabilities?.supportsOpenRouterReasoningParam; // gateway reasoning.effort
733
+ ```
734
+
735
+ ### Invoke cost (Activix / FuncX)
736
+
737
+ ```ts
738
+ import { calculateInvokeCost, buildInvokePricingRecord } from "@x12i/ai-profiles";
739
+
740
+ const cost = await calculateInvokeCost(
741
+ {
742
+ model: "cheap/default",
743
+ tokens: { prompt: 1000, completion: 500 },
744
+ },
745
+ { catalogLane: "text", bundledOnly: true, includeBreakdown: true },
746
+ );
747
+ // cost.costUsd, cost.costStatus: "priced", cost.breakdown
748
+
749
+ // Profile/choice catalog validation
750
+ const required = await requireCatalogModel("cheap/default", {
751
+ catalogLane: "text",
752
+ resolveProfileKeys: true,
753
+ bundledOnly: true,
754
+ });
755
+ // required.found, required.modelId, required.profileChoice
756
+ ```
757
+
758
+ See `.docs/AI-PROFILES-ACTIVIX-COST-CONTRACT.md` for Activix migration wire.
759
+
760
+ **Catalog SOT:** do not use ai-tools' small OpenRouter index for invoke gating — use `requireCatalogModel` / `validateBundledProfileCatalogLinkage` on this package (`npm run validate:linkage`).
761
+
762
+ ```ts
763
+ // Profile → same enrichment on catalogModel
764
+ const resolved = await resolveAIProfile("cheap/default", {
765
+ catalogLane: "text",
766
+ includeCatalog: true,
767
+ includeCatalogEntry: true, // attach full models-catalog.json row
768
+ });
769
+ resolved.catalogModel?.pricing;
770
+ resolved.catalogModel?.catalogEntry;
771
+ ```
772
+
773
+ ### Env fallback
774
+
775
+ Set in `.env` or the process environment:
776
+
777
+ ```env
778
+ PREFER_OPENROUTER=1 # or true, yes, on → OpenRouter
779
+ PREFER_OPENROUTER=0 # or false, no, off → vendor-direct
780
+ ```
781
+
782
+ When `preferOpenRouter` is omitted from `resolveAIProfile`, the env value is used. An explicit option always wins over env.
783
+
784
+ ```ts
785
+ process.env.PREFER_OPENROUTER = "0";
786
+ await resolveAIProfile("cheap/default", { catalogLane: "text" }); // vendor-direct
787
+
788
+ await resolveAIProfile("cheap/default", { catalogLane: "text", preferOpenRouter: true }); // still OpenRouter
789
+ ```
790
+
791
+ Helper exports:
792
+
793
+ ```ts
794
+ import {
795
+ resolvePreferOpenRouter,
796
+ buildOpenRouterModelId,
797
+ buildModelInvocation,
798
+ resolveModelIdentity,
799
+ } from "@x12i/ai-profiles";
800
+
801
+ resolvePreferOpenRouter(); // true by default
802
+ resolvePreferOpenRouter(false); // explicit override
803
+
804
+ buildOpenRouterModelId("openai", "gpt-5.4"); // "openai/gpt-5.4"
805
+
806
+ // Same direct + OpenRouter shape whether input is bare or prefixed:
807
+ buildModelInvocation("anthropic", "claude-3-5-sonnet-20241022");
808
+ buildModelInvocation("anthropic", "anthropic/claude-3-5-sonnet-20241022");
809
+
810
+ // Bare model string → vendor + model (no profile name required):
811
+ resolveModelIdentity("google/gemini-2.5-flash-lite");
812
+ // { provider: "google", modelId: "gemini-2.5-flash-lite", invocation: { … } }
813
+
814
+ resolveModelIdentity("google/gemini-2.5-flash-lite", { asOpenRouter: true });
815
+ // { provider: "openrouter", modelId: "google/gemini-2.5-flash-lite", … }
816
+ ```
817
+
818
+ Tests: `test/resolveModelRouting.test.ts`, `test/modelIdentity.test.ts`, `test/resolveModelIdentity.test.ts`.
819
+
820
+ ## Use bundled only
821
+
822
+ ```ts
823
+ const model = await resolveAIProfile("balanced/default", {
824
+ catalogLane: "text",
825
+ source: "bundled",
826
+ });
827
+ ```
828
+
829
+ ## Force refresh
830
+
831
+ ```ts
832
+ const model = await resolveAIProfile("balanced/default", {
833
+ catalogLane: "text",
834
+ refresh: true,
835
+ });
836
+ ```
837
+
838
+ ## Runtime behavior
839
+
840
+ **Default (`source: "auto"`):**
841
+
842
+ 1. Fetch `models-profiles.json` from the assets URL (see below).
843
+ 2. Validate the response; if valid, use it and cache it in process memory for 24 hours.
844
+ 3. If fetch or validation fails, use the JSON shipped inside this npm package (bundled fallback).
845
+ 4. After TTL, the next call tries fetch again; if that fails but an earlier fetch was cached, reuse the stale cache with a warning.
846
+
847
+ **`source: "bundled"`** — package JSON only, no network.
848
+
849
+ **`source: "remote"`** — fetch every time (still cached after success); errors propagate, no bundled fallback.
850
+
851
+ No database. No disk cache in v1.
852
+
853
+ The `version` field in the JSON files (and `registryVersion` on resolved output) is an optional label for humans or external tooling. This package does not compare versions, enforce semver, or pick assets by version number.
854
+
855
+ ## Remote assets
856
+
857
+ Upload the bundled JSON files **as-is** (no filename version suffix):
858
+
859
+ - `https://open-assets.x12i.com/models-profiles.json`
860
+ - `https://open-assets.x12i.com/models-catalog.json`
861
+
862
+ Older `.v4` / `.v2` URLs are intentionally retired — point every consumer at the unversioned paths above.
863
+
864
+ ## Integration example
865
+
866
+ ```ts
867
+ import { resolveAIProfile, resolveAndNormalizeInvokeModel } from "@x12i/ai-profiles";
868
+
869
+ // Graph JSON stores aliases only (merged job defaults + node overrides per task)
870
+ const slots = {
871
+ preActionModel: node.taskConfiguration.modelConfig?.preActionModel ?? "deep/default",
872
+ skillModel: node.taskConfiguration.modelConfig?.skillModel ?? "balanced/default",
873
+ postActionModel: node.taskConfiguration.modelConfig?.postActionModel ?? "cheap/default",
874
+ };
875
+
876
+ // Resolve each phase independently at execute time
877
+ const pre = await resolveAIProfile(slots.preActionModel, { catalogLane: "text" });
878
+ const main = await resolveAIProfile(slots.skillModel, { catalogLane: "text" });
879
+ const post = await resolveAIProfile(slots.postActionModel, { catalogLane: "text" });
880
+
881
+ // Gateway handoff: resolve + normalize invoke tuple
882
+ const mainInvoke = await resolveAndNormalizeInvokeModel(slots.skillModel, {
883
+ catalogLane: "text",
884
+ preferOpenRouter: true,
885
+ });
886
+ // mainInvoke → { provider: "openrouter", model: "openai/gpt-5.6-terra", routing: "openrouter", ... }
887
+ ```
888
+
889
+ ## Profile matrix (FuncX contract)
890
+
891
+ Default choice per profile (vendor-native ids in registry; OpenRouter slugs when `preferOpenRouter` is true):
892
+
893
+ | Profile | Inference | Instruction tier | Default choice | Example model |
894
+ |---------|-----------|------------------|----------------|---------------|
895
+ | `cheap` | Remote | **`default`** | `default` | `deepseek-v4-flash` |
896
+ | `fast` | Remote | **`default`** | `default` | `gpt-5.6-luna` |
897
+ | `balanced` | Remote | **`default`** | `default` | `gpt-5.6-terra` |
898
+ | `deep` | Remote | **`reasoning`** | `default` | `claude-sonnet-5` |
899
+ | `pro` | Remote | **`default`** | `default` | `gpt-5.6-sol-pro` |
900
+ | `json` | Remote | **`default`** | `default` | `gpt-5.6-luna` (schema output) |
901
+ | `agentic` | Remote | **`default`** | `default` | `claude-sonnet-5` |
902
+ | `research` | Remote | **`reasoning`** | `default` | `claude-sonnet-5` |
903
+ | `cyber` | Remote | **`default`** | `default` | `deepseek-v4-flash` |
904
+ | `content` | Remote | **`default`** | `default` | `claude-fable-5` |
905
+ | `sum` | Remote | **`default`** | `default` | `claude-haiku-4.5` |
906
+ | `vol` | Remote | **`default`** | `default` | `deepseek-v4-flash` |
907
+ | `routing` | Remote | **`default`** | `default` | `gemini-2.5-flash-lite` |
908
+ | `extraction` | Remote | **`default`** | `default` | `gemini-2.5-flash-lite` |
909
+ | `coding` | Remote | **`default`** | `default` | `deepseek-v4-flash` |
910
+ | `local` | CPU (no OpenRouter) | **`cpu`** | `llama_cpp_gguf` | `funcx:llama-cpp:gguf` |
911
+
912
+ Local CPU choices expose FuncX / runtime env keys in `resolved.metadata` (e.g. `LLAMA_CPP_MODEL_PATH`, `OLLAMA_MODEL`, `VLLM_BASE_URL`).
913
+
914
+ ### OpenRouter model ids
915
+
916
+ Remote profile choices in `models-profiles.json` use vendor-native `modelId` values (e.g. `gpt-5.6-sol-pro`, `gemini-2.5-flash-lite`). By default, `resolveAIProfile` returns OpenRouter-ready output:
917
+
918
+ - `provider`: `"openrouter"`
919
+ - `modelId`: full slug such as `openai/gpt-5.6-sol-pro` (with correct OpenRouter prefixes, e.g. `x-ai/…`)
920
+ - `routing`: `"openrouter"`
921
+
922
+ Pass `preferOpenRouter: false` (or `PREFER_OPENROUTER=0`) to get vendor-native `provider` + `modelId` for direct API calls.
923
+
924
+ Every resolved profile includes **`invocation`** with both call shapes:
925
+
926
+ ```ts
927
+ resolved.invocation.direct // { provider: "openai", modelId: "gpt-5.6-sol-pro" }
928
+ resolved.invocation.openrouter // { provider: "openrouter", modelId: "openai/gpt-5.6-sol-pro" } | null
929
+ ```
930
+
931
+ Top-level `provider` / `modelId` / `routing` remain the **active** path selected by `preferOpenRouter`.
932
+
933
+ ### Vendor trimming
934
+
935
+ Restrict resolution to specific vendors (auto-picks within the profile when the default is outside the set). **Leading vendors** (`openai`, `anthropic`, `google`, `deepseek`, `minimax`, `xai`) are **preferred** during auto-pick, not forced — explicit `choice` still honors `together` and other providers.
936
+
937
+ ```ts
938
+ await resolveAIProfile("balanced/default", {
939
+ catalogLane: "text",
940
+ allowedProviders: ["google", "openai"],
941
+ preferLeadingVendors: true, // default
942
+ });
943
+ ```
944
+
945
+ ### Modality filtering (input / output media)
946
+
947
+ Every profile declares **required input and output media** in `requiredCapabilities`:
948
+
949
+ - Most profiles: `inputModalities: ["text"]`, `outputModalities: ["text"]`
950
+ - `vision`: `inputModalities: ["text", "image"]`, `outputModalities: ["text"]`
951
+
952
+ Supported values: `text`, `image`, `audio`, `video`, `file` (aligned with `models-catalog.json`).
953
+
954
+ During resolution, choices whose catalog modalities do not satisfy the contract are **excluded**. A text-only model cannot be picked for `vision`; a vision-capable model can still serve text profiles.
955
+
956
+ ```ts
957
+ const resolved = await resolveAIProfile("vision/default", { catalogLane: "image" });
958
+ // resolved.requiredModalities.input includes "image"
959
+ // resolved.modalities reflects the picked model from catalog
960
+
961
+ await resolveAIProfile("cheap/default", {
962
+ catalogLane: "text",
963
+ inputModalities: ["text", "image"], // override for this call
964
+ outputModalities: ["text"],
965
+ });
966
+ ```
967
+
968
+ Override at resolve time with `inputModalities` / `outputModalities`. Incompatible explicit `choice` values throw `NO_MODALITY_MATCH`.
969
+
970
+ Registry maintenance:
971
+
972
+ ```ts
973
+ import { validateBundledProfileModalityCoverage } from "@x12i/ai-profiles";
974
+
975
+ validateBundledProfileModalityCoverage(); // { ok, profiles[] } with mismatches
976
+ ```
977
+
978
+ `npm run catalog:build` writes `MODALITY_MISMATCH` rows to `reports/fault-report.json`.
979
+
980
+ ### Cost cap filtering
981
+
982
+ Restrict auto-pick to choices whose catalog pricing stays under a USD-per-1M-token ceiling:
983
+
984
+ ```ts
985
+ // Both input and output rates must be <= $0.20 / 1M tokens
986
+ await resolveAIProfile("balanced/default", { catalogLane: "text", costCapPer1M: 0.2 });
987
+
988
+ // Finer control
989
+ await resolveAIProfile("cheap/minimax_cheap", {
990
+ catalogLane: "text",
991
+ costCapPer1M: { maxInput: 0.2, maxOutput: 2 },
992
+ });
993
+ ```
994
+
995
+ When the default choice exceeds the cap, resolution auto-picks the next compatible alternative (respecting fallback order and vendor preferences). Explicit `choice` values over the cap throw `NO_COST_CAP_MATCH`. Local/self-hosted choices are treated as zero cost.
996
+
997
+ ### Keeping models aligned over time
998
+
999
+ Bundled linkage lives in `src/data/models-registry.json`, built from `models-profiles.json` and `src/data/models-catalog.json`.
1000
+
1001
+ Each catalog model has **two explicit call shapes** (never `provider: "openrouter"` with `modelId: "qwen/..."` as the only view):
1002
+
1003
+ - `direct` — vendor-native (`{ provider: "google", modelId: "gemini-3.5-flash" }`)
1004
+ - `openrouter` — transport (`{ provider: "openrouter", modelId: "google/gemini-3.5-flash" }`)
1005
+
1006
+ Legacy open-assets files named `openrouter-models-catalog.json` are normalized into this shape on `catalog:pull`.
1007
+
1008
+ When OpenRouter deprecates or renames a model slug:
1009
+
1010
+ 1. Update `src/data/models-profiles.json` to a current vendor-native id (preferred).
1011
+ 2. Refresh `src/data/models-catalog.json` via `npm run catalog:pull` (fetched from open-assets, normalized locally).
1012
+ 3. Run alignment checks before publishing:
1013
+
1014
+ ```bash
1015
+ npm run registry:finish # merge profile catalog supplement, verified defaults, rebuild linkage
1016
+ npm run catalog:sync # pull catalog, rebuild models-registry.json, verify
1017
+ npm run catalog:pull # fetch open-assets catalog into src/data/
1018
+ npm run catalog:build # rebuild models-registry.json + reports/fault-report.json
1019
+ npm run verify:openrouter # bundled catalog + resolved slug policy (offline-safe)
1020
+ npm run verify:openrouter:live # above + live OpenRouter API id check (needs network; retries 3x)
1021
+ npm run catalog:verify # registry build / fault report from sync-models-registry
1022
+ ```
1023
+
1024
+ With the seed catalog (&lt;50 models), choices not yet listed are marked `catalog-miss` in the registry (warnings in `reports/fault-report.json`, not CI failures). A full catalog promotes true `faulty` rows for slug mismatches.
1025
+
1026
+ Unit tests in `test/openrouterAlignment.test.ts`, `test/modelIdentity.test.ts`, `test/resolveModelIdentity.test.ts`, and `test/resolveModelRouting.test.ts` guard resolution rules offline.
1027
+
1028
+ Vendor-direct-only choices (not routed via OpenRouter) can opt out:
1029
+
1030
+ ```json
1031
+ "metadata": { "openRouter": "vendor-direct" }
1032
+ ```
1033
+
1034
+ ## Tests
1035
+
1036
+ ```bash
1037
+ npm test # build + full suite
1038
+ npm run test:unit # source tests only (skip integration/exports)
1039
+ npm run test:integration # integration + dist export smoke tests
1040
+ npm run pack:check # dry-run npm tarball contents
1041
+ ```
1042
+
1043
+ ## Publishing to npm
1044
+
1045
+ This package is published as a **public** scoped module: `@x12i/ai-profiles` on [npmjs.com](https://www.npmjs.com/).
1046
+
1047
+ ### Prerequisites
1048
+
1049
+ 1. [npm](https://www.npmjs.com/) account with access to the **`@x12i`** organization/scope
1050
+ 2. Authenticated CLI: `npm login` (or set `NPM_TOKEN` — see `.npmrc.example`)
1051
+ 3. Git remote: [github.com/x12i/ai-profiles](https://github.com/x12i/ai-profiles)
1052
+
1053
+ ### Publish locally
1054
+
1055
+ ```bash
1056
+ npm run pack:check # verify tarball includes dist/ + JSON data
1057
+ npm publish --access public
1058
+ ```
1059
+
1060
+ `prepublishOnly` runs the full test suite; `prepack` rebuilds `dist/` before packing.
1061
+
1062
+ ### Publish via GitHub Actions
1063
+
1064
+ Workflow YAML is in [`docs/github-workflows/`](docs/github-workflows/). Copy into `.github/workflows/` and push using a GitHub token with the **`workflow`** scope (see `docs/github-workflows/README.md`).
1065
+
1066
+ 1. Add repository secret **`NPM_TOKEN`** (npm automation token with publish rights for `@x12i`)
1067
+ 2. Create a **GitHub Release** (tag e.g. `v1.0.0`) — triggers `publish-npm.yml`
1068
+ 3. Or run **Publish to npm** workflow manually from the Actions tab
1069
+
1070
+ ### After publish
1071
+
1072
+ Consumers install with:
1073
+
1074
+ ```bash
1075
+ npm install @x12i/ai-profiles@^4.2.0
1076
+ ```
1077
+
1078
+ Peer dependency for downstream repos (graphs-studio, graph-engine, ai-tasks):
1079
+
1080
+ ```json
1081
+ "@x12i/ai-profiles": "^4.1.0"
1082
+ ```
1083
+
1084
+ ## License
1085
+
1086
+ MIT — see [LICENSE](LICENSE).