@jadelclemens/pi-model-map 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +86 -0
- package/README.md +299 -2
- package/examples/README.md +60 -0
- package/examples/cursor.json +571 -0
- package/package.json +51 -4
- package/src/catalog.ts +29 -0
- package/src/config.ts +84 -0
- package/src/constants.ts +10 -0
- package/src/index.ts +392 -0
- package/src/log.ts +36 -0
- package/src/mapping.ts +439 -0
- package/src/source-check.ts +87 -0
- package/src/warnings.ts +93 -0
package/src/mapping.ts
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
import type { ThinkingLevel } from "@earendil-works/pi-ai";
|
|
2
|
+
|
|
3
|
+
export interface BackendRef {
|
|
4
|
+
provider: string;
|
|
5
|
+
id: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The four backend variants a single effort level can resolve to, depending on the
|
|
10
|
+
* /pi-model-map-thinking and /pi-model-map-fast toggles.
|
|
11
|
+
*
|
|
12
|
+
* These toggles exist only because some providers (e.g. Cursor) bake extended-thinking
|
|
13
|
+
* mode and a "fast" routing tier into the model ID string instead of exposing them as
|
|
14
|
+
* request parameters. pi-model-map does not add or emulate those parameters itself —
|
|
15
|
+
* it only picks which pre-baked backend model ID to send for a given combination.
|
|
16
|
+
*
|
|
17
|
+
* JSON keys use "default" and "thinking-fast" (hyphenated) to match this project's other
|
|
18
|
+
* naming conventions; they're addressed internally as `default` and `thinkingFast`.
|
|
19
|
+
*
|
|
20
|
+
* - `default` — thinking off, fast off.
|
|
21
|
+
* - `thinking` — thinking on, fast off.
|
|
22
|
+
* - `fast` — thinking off, fast on.
|
|
23
|
+
* - `thinking-fast` — thinking on, fast on.
|
|
24
|
+
*
|
|
25
|
+
* At least one key is required, but `default` is not mandatory: some effort levels have no
|
|
26
|
+
* non-thinking backend at all (e.g. a model whose highest effort tiers only exist in
|
|
27
|
+
* extended-thinking form). When the requested combination isn't configured, pi-model-map falls
|
|
28
|
+
* back to whichever configured variant honors the most of what was actually requested (e.g. if
|
|
29
|
+
* only `thinking`/`thinking-fast` exist and `/pi-model-map-fast` alone was requested,
|
|
30
|
+
* `thinking-fast` is used rather than plain `thinking`, since it also honors the fast request);
|
|
31
|
+
* see `resolveVariant()` in this file for the exact scoring.
|
|
32
|
+
*/
|
|
33
|
+
export interface VariantRefs {
|
|
34
|
+
default?: string;
|
|
35
|
+
thinking?: string;
|
|
36
|
+
fast?: string;
|
|
37
|
+
"thinking-fast"?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** One effort level's mapping: either a bare "provider/modelId" (= default only) or full variants. */
|
|
41
|
+
export type LevelMapping = string | VariantRefs;
|
|
42
|
+
|
|
43
|
+
/** Effort level -> LevelMapping. */
|
|
44
|
+
export type EffortMap = Record<string, LevelMapping>;
|
|
45
|
+
|
|
46
|
+
/** Internal variant key (camelCase for JS object/field ergonomics). */
|
|
47
|
+
export type Variant = "default" | "thinking" | "fast" | "thinkingFast";
|
|
48
|
+
|
|
49
|
+
/** Maps internal Variant keys to their JSON representation in VariantRefs. */
|
|
50
|
+
const VARIANT_JSON_KEYS: Record<Variant, keyof VariantRefs> = {
|
|
51
|
+
default: "default",
|
|
52
|
+
thinking: "thinking",
|
|
53
|
+
fast: "fast",
|
|
54
|
+
thinkingFast: "thinking-fast",
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export interface MappingEntry {
|
|
58
|
+
name?: string;
|
|
59
|
+
/**
|
|
60
|
+
* Whether Pi's "off" thinking level (no reasoning param sent at all) is meaningful for this
|
|
61
|
+
* family. Defaults to an automatic check: if this family's "default" map level's `default`
|
|
62
|
+
* variant resolves to the exact same backend reference as one of its own named effort levels
|
|
63
|
+
* (e.g. "default" is simply aliased to "medium" because the provider has no true no-reasoning
|
|
64
|
+
* variant for this family), pi-model-map infers `false` and hides "off" from Pi's /thinking
|
|
65
|
+
* picker entirely (`thinkingLevelMap.off = null`) rather than implying "no deeper thinking"
|
|
66
|
+
* when the backend actually always reasons at some level. Set explicitly to override the
|
|
67
|
+
* automatic check either way.
|
|
68
|
+
*/
|
|
69
|
+
offSupported?: boolean;
|
|
70
|
+
contextWindow?: number;
|
|
71
|
+
maxTokens?: number;
|
|
72
|
+
input?: ("text" | "image")[];
|
|
73
|
+
/** Effort level -> backend reference(s). Required. */
|
|
74
|
+
map: EffortMap;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface ModelMapConfig {
|
|
78
|
+
/** Provider the virtual models are listed under. Defaults to the config filename stem. */
|
|
79
|
+
provider?: string;
|
|
80
|
+
/**
|
|
81
|
+
* Path to a JSON file describing the delegate provider's live model catalog (e.g. a cache file
|
|
82
|
+
* the delegate extension itself maintains). When set, pi-model-map warns at config-load time
|
|
83
|
+
* (and via `/pi-model-map-check-source`) about any backend id referenced in `mappings` that is
|
|
84
|
+
* no longer present in this file -- a sign the provider renamed or retired that model.
|
|
85
|
+
*
|
|
86
|
+
* Resolved relative to this config file's own directory if not absolute; a leading "~" expands
|
|
87
|
+
* to the home directory. There is no built-in assumption about *which* provider or file format
|
|
88
|
+
* this points to -- every provider's catalog cache looks different (this started from Cursor's
|
|
89
|
+
* `~/.pi/agent/cache/pi-cursor-agent/models.json`, but nothing here is Cursor-specific). Use
|
|
90
|
+
* `sourceListPath` / `sourceIdField` to describe the shape of whatever file you point this at.
|
|
91
|
+
*/
|
|
92
|
+
source?: string;
|
|
93
|
+
/**
|
|
94
|
+
* Dot-path to the array of catalog entries within the parsed `source` JSON (e.g. "models" for
|
|
95
|
+
* Cursor's `{ "models": [...] }` cache shape). Omit if the JSON's root value is already that
|
|
96
|
+
* array.
|
|
97
|
+
*/
|
|
98
|
+
sourceListPath?: string;
|
|
99
|
+
/**
|
|
100
|
+
* Field name holding each entry's raw model id, when `source` list entries are objects rather
|
|
101
|
+
* than bare strings. Defaults to "modelId" (Cursor's cache format). Ignored for entries that
|
|
102
|
+
* are already bare strings.
|
|
103
|
+
*/
|
|
104
|
+
sourceIdField?: string;
|
|
105
|
+
/** Canonical model id -> mapping entry (metadata + effort-level map). */
|
|
106
|
+
mappings: Record<string, MappingEntry>;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Every selectable Pi thinking level, excluding "off" (which corresponds to this project's
|
|
111
|
+
* "default" map key, not a ThinkingLevel). Exported so catalog.ts can build a complete
|
|
112
|
+
* `thinkingLevelMap` — Pi treats an *omitted* key differently from an explicit `null` for
|
|
113
|
+
* standard levels (minimal..high default to "supported" when omitted), so every level a
|
|
114
|
+
* family doesn't map must be set to `null` explicitly, not left out. See models.md's
|
|
115
|
+
* "Thinking Level Map" section.
|
|
116
|
+
*/
|
|
117
|
+
export const EFFORT_LEVELS = [
|
|
118
|
+
"minimal",
|
|
119
|
+
"low",
|
|
120
|
+
"medium",
|
|
121
|
+
"high",
|
|
122
|
+
"xhigh",
|
|
123
|
+
"max",
|
|
124
|
+
] as const satisfies readonly ThinkingLevel[];
|
|
125
|
+
|
|
126
|
+
const VARIANT_KEYS: readonly Variant[] = ["default", "thinking", "fast", "thinkingFast"];
|
|
127
|
+
|
|
128
|
+
/** Which of the two independent toggle axes ("thinking", "fast") each Variant corresponds to. */
|
|
129
|
+
const VARIANT_BITS: Record<Variant, { thinking: boolean; fast: boolean }> = {
|
|
130
|
+
default: { thinking: false, fast: false },
|
|
131
|
+
thinking: { thinking: true, fast: false },
|
|
132
|
+
fast: { thinking: false, fast: true },
|
|
133
|
+
thinkingFast: { thinking: true, fast: true },
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Resolve a variant from a level's parsed refs, falling back to whichever *configured* variant
|
|
138
|
+
* best honors the requested thinking/fast toggle state when the exact combination isn't present.
|
|
139
|
+
*
|
|
140
|
+
* Each configured candidate is scored: +1 for each requested toggle it actually satisfies, -1 for
|
|
141
|
+
* each toggle it forces on that wasn't requested. The highest-scoring configured candidate wins.
|
|
142
|
+
* This is deliberately symmetric across both axes -- e.g. if a level only has "thinking" and
|
|
143
|
+
* "thinking-fast" configured (no "default"/"fast" at all, as with some providers' highest effort
|
|
144
|
+
* tiers) and only the "fast" toggle was requested, "thinking-fast" scores higher than "thinking"
|
|
145
|
+
* because it honors the requested fast toggle too, even though both force thinking on regardless.
|
|
146
|
+
* Ties (both toggles' request-satisfaction identical) prefer satisfying "thinking" over "fast",
|
|
147
|
+
* matching this project's other thinking-first conventions; remaining ties fall back to
|
|
148
|
+
* declaration order (default, thinking, fast, thinking-fast) for full determinism.
|
|
149
|
+
*
|
|
150
|
+
* Returns undefined only if the level has no variants at all (should not happen post-parse,
|
|
151
|
+
* since every level requires at least one variant).
|
|
152
|
+
*/
|
|
153
|
+
const resolveVariant = (
|
|
154
|
+
refs: Partial<Record<Variant, BackendRef>> | undefined,
|
|
155
|
+
variant: Variant,
|
|
156
|
+
): BackendRef | undefined => {
|
|
157
|
+
if (!refs) return undefined;
|
|
158
|
+
const requested = VARIANT_BITS[variant];
|
|
159
|
+
|
|
160
|
+
let best: { candidate: Variant; score: number; thinkingMatch: number } | undefined;
|
|
161
|
+
for (const candidate of VARIANT_KEYS) {
|
|
162
|
+
if (!refs[candidate]) continue;
|
|
163
|
+
const bits = VARIANT_BITS[candidate];
|
|
164
|
+
const thinkingMatch = requested.thinking && bits.thinking ? 1 : 0;
|
|
165
|
+
const fastMatch = requested.fast && bits.fast ? 1 : 0;
|
|
166
|
+
const thinkingPenalty = !requested.thinking && bits.thinking ? 1 : 0;
|
|
167
|
+
const fastPenalty = !requested.fast && bits.fast ? 1 : 0;
|
|
168
|
+
const score = thinkingMatch + fastMatch - thinkingPenalty - fastPenalty;
|
|
169
|
+
if (!best || score > best.score || (score === best.score && thinkingMatch > best.thinkingMatch)) {
|
|
170
|
+
best = { candidate, score, thinkingMatch };
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return best ? refs[best.candidate] : undefined;
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
const parseBackendRef = (
|
|
177
|
+
value: string,
|
|
178
|
+
canonicalId: string,
|
|
179
|
+
level: string,
|
|
180
|
+
variant: Variant,
|
|
181
|
+
source: string,
|
|
182
|
+
): BackendRef => {
|
|
183
|
+
const slashIndex = value.indexOf("/");
|
|
184
|
+
if (slashIndex <= 0 || slashIndex === value.length - 1) {
|
|
185
|
+
const jsonKey = VARIANT_JSON_KEYS[variant];
|
|
186
|
+
const path =
|
|
187
|
+
variant === "default"
|
|
188
|
+
? `mappings.${canonicalId}.map.${level}`
|
|
189
|
+
: `mappings.${canonicalId}.map.${level}.${jsonKey}`;
|
|
190
|
+
throw new Error(
|
|
191
|
+
`${source}: ${path} = "${value}" must be "provider/modelId" ` +
|
|
192
|
+
`(e.g. "cursor-agent/claude-opus-4-8-thinking-high").`,
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
provider: value.slice(0, slashIndex),
|
|
197
|
+
id: value.slice(slashIndex + 1),
|
|
198
|
+
};
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
const normalizeLevelMapping = (value: LevelMapping): Partial<Record<Variant, string>> => {
|
|
202
|
+
if (typeof value === "string") {
|
|
203
|
+
return { default: value };
|
|
204
|
+
}
|
|
205
|
+
const out: Partial<Record<Variant, string>> = {};
|
|
206
|
+
for (const key of VARIANT_KEYS) {
|
|
207
|
+
const v = value[VARIANT_JSON_KEYS[key]];
|
|
208
|
+
if (v) out[key] = v;
|
|
209
|
+
}
|
|
210
|
+
return out;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
export class ModelMapper {
|
|
214
|
+
readonly source: string;
|
|
215
|
+
readonly provider: string;
|
|
216
|
+
/** Raw `source`/`sourceListPath`/`sourceIdField` config, or undefined if `source` was omitted. */
|
|
217
|
+
readonly catalogSource?: { path: string; listPath?: string; idField: string };
|
|
218
|
+
private readonly mappings: Record<string, MappingEntry>;
|
|
219
|
+
/** canonicalId -> effort level -> variant -> BackendRef */
|
|
220
|
+
private readonly parsedMap = new Map<string, Map<string, Partial<Record<Variant, BackendRef>>>>();
|
|
221
|
+
private readonly delegateProviders = new Set<string>();
|
|
222
|
+
/** canonicalId -> distinct delegate providers referenced anywhere in that family's own map. */
|
|
223
|
+
private readonly providersByFamily = new Map<string, Set<string>>();
|
|
224
|
+
/** canonicalId -> whether any level provides a "thinking" variant. */
|
|
225
|
+
private readonly hasThinkingVariant = new Set<string>();
|
|
226
|
+
/** canonicalId -> whether any level provides a "fast" variant. */
|
|
227
|
+
private readonly hasFastVariant = new Set<string>();
|
|
228
|
+
/** raw backend id -> human-readable location(s) it's referenced at, e.g. "claude-opus-5.map.high.thinking". */
|
|
229
|
+
private readonly backendIdLocations = new Map<string, string[]>();
|
|
230
|
+
|
|
231
|
+
constructor(config: ModelMapConfig, source: string, providerDefault?: string) {
|
|
232
|
+
this.source = source;
|
|
233
|
+
this.provider = config.provider ?? providerDefault ?? "model-map";
|
|
234
|
+
this.catalogSource = config.source
|
|
235
|
+
? { path: config.source, listPath: config.sourceListPath, idField: config.sourceIdField ?? "modelId" }
|
|
236
|
+
: undefined;
|
|
237
|
+
this.mappings = config.mappings;
|
|
238
|
+
this.buildIndexes();
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private buildIndexes(): void {
|
|
242
|
+
for (const [canonicalId, entry] of Object.entries(this.mappings)) {
|
|
243
|
+
if (!entry.map || typeof entry.map !== "object") {
|
|
244
|
+
throw new Error(`${this.source}: mappings.${canonicalId} is missing required "map"`);
|
|
245
|
+
}
|
|
246
|
+
const levelMap = new Map<string, Partial<Record<Variant, BackendRef>>>();
|
|
247
|
+
const familyProviders = new Set<string>();
|
|
248
|
+
for (const [level, rawValue] of Object.entries(entry.map)) {
|
|
249
|
+
const normalized = normalizeLevelMapping(rawValue);
|
|
250
|
+
if (Object.keys(normalized).length === 0) {
|
|
251
|
+
throw new Error(
|
|
252
|
+
`${this.source}: mappings.${canonicalId}.map.${level} must define at least one of ` +
|
|
253
|
+
`"default", "thinking", "fast", "thinking-fast"`,
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
const refs: Partial<Record<Variant, BackendRef>> = {};
|
|
257
|
+
for (const variant of VARIANT_KEYS) {
|
|
258
|
+
const value = normalized[variant];
|
|
259
|
+
if (!value) continue;
|
|
260
|
+
const ref = parseBackendRef(value, canonicalId, level, variant, this.source);
|
|
261
|
+
refs[variant] = ref;
|
|
262
|
+
this.delegateProviders.add(ref.provider);
|
|
263
|
+
familyProviders.add(ref.provider);
|
|
264
|
+
const jsonKey = VARIANT_JSON_KEYS[variant];
|
|
265
|
+
const location =
|
|
266
|
+
variant === "default"
|
|
267
|
+
? `mappings.${canonicalId}.map.${level}`
|
|
268
|
+
: `mappings.${canonicalId}.map.${level}.${jsonKey}`;
|
|
269
|
+
const locations = this.backendIdLocations.get(ref.id);
|
|
270
|
+
if (locations) {
|
|
271
|
+
locations.push(location);
|
|
272
|
+
} else {
|
|
273
|
+
this.backendIdLocations.set(ref.id, [location]);
|
|
274
|
+
}
|
|
275
|
+
if (variant === "thinking" || variant === "thinkingFast") {
|
|
276
|
+
this.hasThinkingVariant.add(canonicalId);
|
|
277
|
+
}
|
|
278
|
+
if (variant === "fast" || variant === "thinkingFast") {
|
|
279
|
+
this.hasFastVariant.add(canonicalId);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
levelMap.set(level, refs);
|
|
283
|
+
}
|
|
284
|
+
this.parsedMap.set(canonicalId, levelMap);
|
|
285
|
+
this.providersByFamily.set(canonicalId, familyProviders);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
getCanonicalFamilies(): string[] {
|
|
290
|
+
return Object.keys(this.mappings);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** All distinct delegate providers referenced across every mapping/level/variant. */
|
|
294
|
+
getDelegateProviders(): string[] {
|
|
295
|
+
return [...this.delegateProviders];
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Distinct delegate providers referenced within a single canonical family's own map (across
|
|
300
|
+
* all its effort levels and thinking/fast variants). Used to detect a family whose levels or
|
|
301
|
+
* variants are split across more than one real provider — out of scope for pi-model-map
|
|
302
|
+
* (see `warnings.ts`); each mapping is meant to describe one canonical model backed by one
|
|
303
|
+
* delegate provider, with "provider/modelId" syntax used only for explicitness, not fan-out.
|
|
304
|
+
*/
|
|
305
|
+
getFamilyDelegateProviders(canonicalId: string): string[] {
|
|
306
|
+
return [...(this.providersByFamily.get(canonicalId) ?? [])];
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Whether any effort level of this family defines a "thinking" or "thinkingFast" variant. */
|
|
310
|
+
supportsThinkingToggle(canonicalId: string): boolean {
|
|
311
|
+
return this.hasThinkingVariant.has(canonicalId);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Whether any effort level of this family defines a "fast" or "thinkingFast" variant. */
|
|
315
|
+
supportsFastToggle(canonicalId: string): boolean {
|
|
316
|
+
return this.hasFastVariant.has(canonicalId);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Resolve a canonical id + effort level + thinking/fast toggles to a backend reference.
|
|
321
|
+
*
|
|
322
|
+
* Falls back in this order when the requested variant is not configured:
|
|
323
|
+
* thinking-fast -> thinking or fast (whichever axis is still requested) -> default
|
|
324
|
+
* Falls back to the "default" level's resolved ref when the requested level is absent.
|
|
325
|
+
*/
|
|
326
|
+
toBackendRef(
|
|
327
|
+
canonicalId: string,
|
|
328
|
+
reasoning?: ThinkingLevel,
|
|
329
|
+
thinking = false,
|
|
330
|
+
fast = false,
|
|
331
|
+
): BackendRef | undefined {
|
|
332
|
+
const levelMap = this.parsedMap.get(canonicalId);
|
|
333
|
+
if (!levelMap) {
|
|
334
|
+
return undefined;
|
|
335
|
+
}
|
|
336
|
+
const level = reasoning && levelMap.has(reasoning) ? reasoning : "default";
|
|
337
|
+
const refs = levelMap.get(level) ?? levelMap.get("default");
|
|
338
|
+
if (!refs) {
|
|
339
|
+
return undefined;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const variant: Variant = thinking && fast ? "thinkingFast" : thinking ? "thinking" : fast ? "fast" : "default";
|
|
343
|
+
|
|
344
|
+
return resolveVariant(refs, variant);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** The `map` key `toBackendRef` actually resolves to for a given effort level (falls back to "default" the same way `toBackendRef` does). */
|
|
348
|
+
resolvedLevel(canonicalId: string, reasoning?: ThinkingLevel): string {
|
|
349
|
+
const levelMap = this.parsedMap.get(canonicalId);
|
|
350
|
+
if (!levelMap) return "default";
|
|
351
|
+
return reasoning && levelMap.has(reasoning) ? reasoning : "default";
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Whether `canonicalId`'s `level` has no non-thinking variant at all (only "thinking" and/or
|
|
356
|
+
* "thinking-fast" keys) -- meaning `toBackendRef` will always resolve to a thinking backend for
|
|
357
|
+
* this level regardless of the `/pi-model-map-thinking` toggle's actual state, because there's
|
|
358
|
+
* nothing else to fall back to. Used to warn instead of silently overriding the toggle.
|
|
359
|
+
*/
|
|
360
|
+
isThinkingOnlyLevel(canonicalId: string, level: string): boolean {
|
|
361
|
+
const refs = this.parsedMap.get(canonicalId)?.get(level);
|
|
362
|
+
if (!refs) return false;
|
|
363
|
+
return !refs.default && !refs.fast && (!!refs.thinking || !!refs.thinkingFast);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Whether `level` has no entry at all in `canonicalId`'s map -- meaning `toBackendRef` /
|
|
368
|
+
* `resolvedLevel` silently fall through to the "default" map level instead of resolving
|
|
369
|
+
* `level` itself. Used to warn instead of silently substituting a different effort level
|
|
370
|
+
* than the one actually requested (e.g. a caller -- possibly another extension, like a
|
|
371
|
+
* roundrobin wrapper, that doesn't know this family's supported levels -- asking for
|
|
372
|
+
* "minimal" on a family whose map only defines low/medium/high/xhigh/max).
|
|
373
|
+
*
|
|
374
|
+
* Returns false for a family with no map at all (nothing to compare against) and for a level
|
|
375
|
+
* that *is* mapped, obviously. `"default"` itself is never "unmapped" in this sense -- it's
|
|
376
|
+
* this project's own internal fallback key, not a requestable `ThinkingLevel`.
|
|
377
|
+
*/
|
|
378
|
+
isUnmappedLevel(canonicalId: string, level: ThinkingLevel): boolean {
|
|
379
|
+
const levelMap = this.parsedMap.get(canonicalId);
|
|
380
|
+
if (!levelMap) return false;
|
|
381
|
+
return !levelMap.has(level);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
getModelMetadata(canonicalId: string): MappingEntry | undefined {
|
|
385
|
+
return this.mappings[canonicalId];
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** All distinct raw backend ids (not "provider/id", just the id half) referenced in `mappings`. */
|
|
389
|
+
getAllBackendIds(): string[] {
|
|
390
|
+
return [...this.backendIdLocations.keys()];
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** Where a given raw backend id is referenced, e.g. ["mappings.claude-opus-5.map.high.thinking"]. */
|
|
394
|
+
getBackendIdLocations(id: string): string[] {
|
|
395
|
+
return this.backendIdLocations.get(id) ?? [];
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** All distinct backend references available to a canonical family. */
|
|
399
|
+
getFamilyBackendRefs(canonicalId: string): BackendRef[] {
|
|
400
|
+
const refs = new Map<string, BackendRef>();
|
|
401
|
+
for (const level of this.parsedMap.get(canonicalId)?.values() ?? []) {
|
|
402
|
+
for (const ref of Object.values(level)) {
|
|
403
|
+
if (ref) refs.set(`${ref.provider}/${ref.id}`, ref);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return [...refs.values()];
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
getSupportedThinkingLevels(canonicalId: string): ThinkingLevel[] {
|
|
410
|
+
const levelMap = this.parsedMap.get(canonicalId);
|
|
411
|
+
if (!levelMap) {
|
|
412
|
+
return [];
|
|
413
|
+
}
|
|
414
|
+
return EFFORT_LEVELS.filter((level) => levelMap.has(level));
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Whether this family's "default" map level has a backend distinct from all of its own named
|
|
419
|
+
* effort levels -- i.e. whether Pi's "off" thinking level would mean something real for this
|
|
420
|
+
* family, rather than secretly being some other named effort level under a misleading label.
|
|
421
|
+
* Compares only the "default" variant (no thinking/fast toggle) of each level, since that's
|
|
422
|
+
* what Pi's "off" resolves through. Returns true (supported) when there's nothing to compare
|
|
423
|
+
* against, e.g. a family with only a "default" map level and no other effort levels at all.
|
|
424
|
+
*/
|
|
425
|
+
hasDistinctOffLevel(canonicalId: string): boolean {
|
|
426
|
+
const levelMap = this.parsedMap.get(canonicalId);
|
|
427
|
+
if (!levelMap) return true;
|
|
428
|
+
const defaultRef = levelMap.get("default")?.default;
|
|
429
|
+
if (!defaultRef) return true;
|
|
430
|
+
for (const [level, refs] of levelMap) {
|
|
431
|
+
if (level === "default") continue;
|
|
432
|
+
const ref = refs.default;
|
|
433
|
+
if (ref && ref.provider === defaultRef.provider && ref.id === defaultRef.id) {
|
|
434
|
+
return false;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return true;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
import type { ModelMapper } from "./mapping.js";
|
|
6
|
+
|
|
7
|
+
const expandHome = (p: string): string => (p.startsWith("~") ? path.join(os.homedir(), p.slice(1)) : p);
|
|
8
|
+
|
|
9
|
+
const resolveSourcePath = (mapper: ModelMapper): string | undefined => {
|
|
10
|
+
if (!mapper.catalogSource) return undefined;
|
|
11
|
+
const expanded = expandHome(mapper.catalogSource.path);
|
|
12
|
+
return path.isAbsolute(expanded) ? expanded : path.resolve(path.dirname(mapper.source), expanded);
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const getAtPath = (value: unknown, dotPath: string): unknown =>
|
|
16
|
+
dotPath.split(".").reduce<unknown>((acc, key) => {
|
|
17
|
+
if (acc && typeof acc === "object" && key in (acc as Record<string, unknown>)) {
|
|
18
|
+
return (acc as Record<string, unknown>)[key];
|
|
19
|
+
}
|
|
20
|
+
return undefined;
|
|
21
|
+
}, value);
|
|
22
|
+
|
|
23
|
+
export interface SourceCheckResult {
|
|
24
|
+
/** Resolved path that was actually read. */
|
|
25
|
+
resolvedPath: string;
|
|
26
|
+
/** True if the file was read/parsed successfully and every referenced backend id was found. */
|
|
27
|
+
ok: boolean;
|
|
28
|
+
/** Backend ids referenced in `mappings` that are absent from the source catalog. */
|
|
29
|
+
missingIds: string[];
|
|
30
|
+
/** Set instead of checking ids when the source file itself couldn't be read/parsed/shaped as expected. */
|
|
31
|
+
error?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Compares every raw backend id referenced in `mapper`'s `mappings` against the live catalog
|
|
36
|
+
* file named by its `source` config (if any). Returns undefined when `source` was not configured
|
|
37
|
+
* -- this check is opt-in per config file, since there's no universal catalog cache format or
|
|
38
|
+
* location across providers.
|
|
39
|
+
*/
|
|
40
|
+
export const checkAgainstSource = (mapper: ModelMapper): SourceCheckResult | undefined => {
|
|
41
|
+
const catalogSource = mapper.catalogSource;
|
|
42
|
+
if (!catalogSource) return undefined;
|
|
43
|
+
|
|
44
|
+
const resolvedPath = resolveSourcePath(mapper);
|
|
45
|
+
if (!resolvedPath) return undefined;
|
|
46
|
+
|
|
47
|
+
let raw: unknown;
|
|
48
|
+
try {
|
|
49
|
+
raw = JSON.parse(fs.readFileSync(resolvedPath, "utf8"));
|
|
50
|
+
} catch (error) {
|
|
51
|
+
return {
|
|
52
|
+
resolvedPath,
|
|
53
|
+
ok: false,
|
|
54
|
+
missingIds: [],
|
|
55
|
+
error: `could not read/parse: ${error instanceof Error ? error.message : String(error)}`,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const listValue = catalogSource.listPath ? getAtPath(raw, catalogSource.listPath) : raw;
|
|
60
|
+
if (!Array.isArray(listValue)) {
|
|
61
|
+
return {
|
|
62
|
+
resolvedPath,
|
|
63
|
+
ok: false,
|
|
64
|
+
missingIds: [],
|
|
65
|
+
error:
|
|
66
|
+
`expected an array at ${catalogSource.listPath ? `"${catalogSource.listPath}"` : "the JSON root"}, ` +
|
|
67
|
+
`got ${Array.isArray(listValue) ? "array" : typeof listValue}`,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const sourceIds = new Set<string>();
|
|
72
|
+
for (const entry of listValue) {
|
|
73
|
+
if (typeof entry === "string") {
|
|
74
|
+
sourceIds.add(entry);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (entry && typeof entry === "object") {
|
|
78
|
+
const value = (entry as Record<string, unknown>)[catalogSource.idField];
|
|
79
|
+
if (typeof value === "string") {
|
|
80
|
+
sourceIds.add(value);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const missingIds = mapper.getAllBackendIds().filter((id) => !sourceIds.has(id));
|
|
86
|
+
return { resolvedPath, ok: missingIds.length === 0, missingIds };
|
|
87
|
+
};
|
package/src/warnings.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
import { pluginWarn } from "./log.js";
|
|
4
|
+
import type { ModelMapper } from "./mapping.js";
|
|
5
|
+
import { checkAgainstSource } from "./source-check.js";
|
|
6
|
+
|
|
7
|
+
const WARN_PREFIX = "[pi-model-map]";
|
|
8
|
+
|
|
9
|
+
export const validateProviderConfig = (mapper: ModelMapper): void => {
|
|
10
|
+
checkMultiProviderUsage(mapper);
|
|
11
|
+
checkSourceCatalog(mapper);
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Opt-in: only runs when a config file sets "source". Warns if the source catalog file can't be
|
|
16
|
+
* read/parsed as configured, or if any backend id referenced in "mappings" is missing from it --
|
|
17
|
+
* usually meaning the delegate provider renamed or retired that model since the config was written.
|
|
18
|
+
*/
|
|
19
|
+
const checkSourceCatalog = (mapper: ModelMapper): void => {
|
|
20
|
+
const result = checkAgainstSource(mapper);
|
|
21
|
+
if (!result) return;
|
|
22
|
+
|
|
23
|
+
const label = `${mapper.source} (${mapper.provider})`;
|
|
24
|
+
|
|
25
|
+
if (result.error) {
|
|
26
|
+
pluginWarn(
|
|
27
|
+
`${WARN_PREFIX} WARNING: ${label}: "source" is set to "${result.resolvedPath}" but it ${result.error}. ` +
|
|
28
|
+
`Skipping the backend-id freshness check.`,
|
|
29
|
+
);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (result.missingIds.length === 0) return;
|
|
34
|
+
|
|
35
|
+
for (const id of result.missingIds) {
|
|
36
|
+
const locations = mapper.getBackendIdLocations(id).join(", ");
|
|
37
|
+
pluginWarn(
|
|
38
|
+
`${WARN_PREFIX} WARNING: ${label}: backend id "${id}" (referenced at ${locations}) was not found in ` +
|
|
39
|
+
`"${result.resolvedPath}". The provider may have renamed or retired this model -- verify the mapping ` +
|
|
40
|
+
`still resolves to something real.`,
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* pi-model-map expects each config file to delegate to exactly one real backend provider.
|
|
47
|
+
* "provider/modelId" syntax on every map entry exists for explicitness (and to let one file
|
|
48
|
+
* mix effort levels/variants freely), not to fan a single mapping out across multiple
|
|
49
|
+
* distinct backends. Grouping unrelated providers into one virtual model (e.g. a "thinking
|
|
50
|
+
* tier" that round-robins between different providers' models) is out of scope here — that's
|
|
51
|
+
* a different kind of plugin. This only warns; it does not block loading, since a config that
|
|
52
|
+
* intentionally mixes delegates for some other reason will still work mechanically.
|
|
53
|
+
*/
|
|
54
|
+
const checkMultiProviderUsage = (mapper: ModelMapper): void => {
|
|
55
|
+
const label = `${mapper.source} (${mapper.provider})`;
|
|
56
|
+
const allProviders = mapper.getDelegateProviders();
|
|
57
|
+
|
|
58
|
+
for (const canonicalId of mapper.getCanonicalFamilies()) {
|
|
59
|
+
const familyProviders = mapper.getFamilyDelegateProviders(canonicalId);
|
|
60
|
+
if (familyProviders.length > 1) {
|
|
61
|
+
pluginWarn(
|
|
62
|
+
`${WARN_PREFIX} WARNING: ${label}: mappings.${canonicalId} references multiple delegate ` +
|
|
63
|
+
`providers (${familyProviders.join(", ")}) across its own effort levels/variants. ` +
|
|
64
|
+
`pi-model-map maps one canonical model to one backend provider; mixing providers within a ` +
|
|
65
|
+
`single mapping (e.g. to round-robin between a "cursor-agent" model and an "anthropic" model ` +
|
|
66
|
+
`under one canonical id) is out of scope and not supported by this project's resolution logic — ` +
|
|
67
|
+
`whichever provider a given effort level/variant happens to reference is what will be used, ` +
|
|
68
|
+
`with no cross-provider fallback or selection.`,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (allProviders.length > 1) {
|
|
74
|
+
pluginWarn(
|
|
75
|
+
`${WARN_PREFIX} WARNING: ${label}: this config file references ${allProviders.length} distinct ` +
|
|
76
|
+
`delegate providers overall (${allProviders.join(", ")}). Each config file is intended to delegate ` +
|
|
77
|
+
`to a single backend provider; use separate config files (one provider each) if you want to map ` +
|
|
78
|
+
`models from multiple providers. If this is unintentional, check for a typo in a "provider/modelId" ` +
|
|
79
|
+
`reference.`,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
export const warnOnSessionStart = (ctx: ExtensionContext, mapper: ModelMapper): void => {
|
|
85
|
+
for (const delegateProvider of mapper.getDelegateProviders()) {
|
|
86
|
+
if (!ctx.modelRegistry.getProvider(delegateProvider)) {
|
|
87
|
+
pluginWarn(
|
|
88
|
+
`${WARN_PREFIX} delegate provider "${delegateProvider}" is not registered. ` +
|
|
89
|
+
`Install and authenticate it before using ${mapper.provider} models that reference it.`,
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
};
|