@jadelclemens/pi-model-map 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/catalog.ts ADDED
@@ -0,0 +1,63 @@
1
+ import type { Api, Model, ThinkingLevel, ThinkingLevelMap } from "@earendil-works/pi-ai";
2
+
3
+ import { EFFORT_LEVELS, type ModelMapper } from "./mapping.js";
4
+
5
+ const defaultCost = {
6
+ input: 0,
7
+ output: 0,
8
+ cacheRead: 0,
9
+ cacheWrite: 0,
10
+ };
11
+
12
+ /**
13
+ * Build a complete thinkingLevelMap covering every ThinkingLevel, not just the supported ones.
14
+ *
15
+ * Pi treats an omitted key differently from an explicit `null`: for standard levels
16
+ * (minimal..high), omitting the key means "supported via provider default" rather than
17
+ * "unsupported." Since pi-model-map families often only support a subset of levels (e.g. a
18
+ * family with only low/high/max backends), every unsupported level must be set to `null`
19
+ * explicitly so Pi's /thinking UI and pi.setThinkingLevel() clamping correctly restrict
20
+ * selection to what this family's "map" actually defines. See docs/models.md's
21
+ * "Thinking Level Map" section.
22
+ */
23
+ const buildThinkingLevelMap = (supportedLevels: ThinkingLevel[], offSupported: boolean): ThinkingLevelMap => {
24
+ const supported = new Set<ThinkingLevel>(supportedLevels);
25
+ const map = Object.fromEntries(
26
+ EFFORT_LEVELS.map((level) => [level, supported.has(level) ? level : null]),
27
+ ) as ThinkingLevelMap;
28
+ // "off" (Pi's literal no-reasoning-param state) is left omitted ("supported via provider
29
+ // default") unless this family has no real non-reasoning backend at all, in which case it's
30
+ // set to null so /thinking never implies "no deeper thinking" when that's not actually true.
31
+ // See ModelMapper.hasDistinctOffLevel() / MappingEntry.offSupported.
32
+ if (!offSupported) {
33
+ map.off = null;
34
+ }
35
+ return map;
36
+ };
37
+
38
+ export const buildProviderModels = (
39
+ mapper: ModelMapper,
40
+ api: Api,
41
+ baseUrl: string,
42
+ ): Model<Api>[] => {
43
+ return mapper.getCanonicalFamilies().map((canonicalId) => {
44
+ const metadata = mapper.getModelMetadata(canonicalId);
45
+ const supportedLevels = mapper.getSupportedThinkingLevels(canonicalId);
46
+ const offSupported = metadata?.offSupported ?? mapper.hasDistinctOffLevel(canonicalId);
47
+ const thinkingLevelMap = buildThinkingLevelMap(supportedLevels, offSupported);
48
+
49
+ return {
50
+ id: canonicalId,
51
+ name: metadata?.name ?? canonicalId,
52
+ api,
53
+ provider: mapper.provider,
54
+ baseUrl,
55
+ reasoning: metadata?.reasoning ?? supportedLevels.length > 0,
56
+ input: metadata?.input ?? ["text", "image"],
57
+ cost: metadata?.cost ?? defaultCost,
58
+ contextWindow: metadata?.contextWindow ?? 1_000_000,
59
+ maxTokens: metadata?.maxTokens ?? 128_000,
60
+ thinkingLevelMap,
61
+ } satisfies Model<Api>;
62
+ });
63
+ };
package/src/config.ts ADDED
@@ -0,0 +1,84 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import { CONFIG_DIR_NAME } from "./constants.js";
6
+ import type { ModelMapConfig } from "./mapping.js";
7
+ import { ModelMapper } from "./mapping.js";
8
+ import { validateProviderConfig } from "./warnings.js";
9
+
10
+ const GLOBAL_CONFIG_DIR = path.join(os.homedir(), ".pi", "agent", CONFIG_DIR_NAME);
11
+
12
+ const parseConfigFile = (file: string): ModelMapConfig => {
13
+ const raw = fs.readFileSync(file, "utf8");
14
+ const parsed = JSON.parse(raw) as ModelMapConfig;
15
+ if (!parsed.mappings || typeof parsed.mappings !== "object") {
16
+ throw new Error(`${file}: missing required "mappings" object`);
17
+ }
18
+ return parsed;
19
+ };
20
+
21
+ const providerDefaultFromFilename = (file: string): string | undefined => {
22
+ const base = path.basename(file, path.extname(file));
23
+ return base.length > 0 ? base : undefined;
24
+ };
25
+
26
+ const loadConfigDir = (dir: string): ModelMapper[] => {
27
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
28
+ return [];
29
+ }
30
+
31
+ const files = fs
32
+ .readdirSync(dir)
33
+ .filter((name) => name.endsWith(".json"))
34
+ .sort()
35
+ .map((name) => path.join(dir, name));
36
+
37
+ if (files.length === 0) {
38
+ return [];
39
+ }
40
+
41
+ const mappers = files.map((file) => {
42
+ const config = parseConfigFile(file);
43
+ const mapper = new ModelMapper(config, file, providerDefaultFromFilename(file));
44
+ validateProviderConfig(mapper);
45
+ return mapper;
46
+ });
47
+
48
+ const seen = new Set<string>();
49
+ for (const mapper of mappers) {
50
+ if (seen.has(mapper.provider)) {
51
+ throw new Error(
52
+ `${mapper.source}: duplicate provider "${mapper.provider}" — each config file must use a unique provider id`,
53
+ );
54
+ }
55
+ seen.add(mapper.provider);
56
+ }
57
+
58
+ return mappers;
59
+ };
60
+
61
+ const configDirCandidates = (cwd: string): string[] => [
62
+ path.join(cwd, ".pi", "agent", CONFIG_DIR_NAME),
63
+ path.join(cwd, ".pi", CONFIG_DIR_NAME),
64
+ path.join(cwd, CONFIG_DIR_NAME),
65
+ GLOBAL_CONFIG_DIR,
66
+ ];
67
+
68
+ export const loadModelMappers = (cwd = process.cwd()): ModelMapper[] => {
69
+ for (const dir of configDirCandidates(cwd)) {
70
+ const mappers = loadConfigDir(dir);
71
+ if (mappers.length > 0) {
72
+ return mappers;
73
+ }
74
+ }
75
+
76
+ throw new Error(
77
+ `No model-map config found. Create ${GLOBAL_CONFIG_DIR}/cursor.json (one file per provider mapping) ` +
78
+ `or copy from examples/.`,
79
+ );
80
+ };
81
+
82
+ export const createModelMappers = (cwd = process.cwd()): ModelMapper[] => {
83
+ return loadModelMappers(cwd);
84
+ };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Pi requires an apiKey (or oauth) when extension providers register models, even when
3
+ * streamSimple only delegates to another provider that owns real authentication.
4
+ * This value is never used for API calls.
5
+ */
6
+ export const FAKE_REGISTRATION_API_KEY =
7
+ "PI_MODEL_MAP_FAKE_KEY_NEEDED_FOR_PROVIDER_REGISTRATION";
8
+
9
+ export const CONFIG_DIR_NAME = "model-map";
10
+
11
+ /** Command name prefix for the /pi-model-map-* command family. */
12
+ export const COMMAND_PREFIX = "pi-model-map";
13
+
14
+ /** Plugin log file name, under `~/.pi/agent/model-map/`. */
15
+ export const LOG_FILE_NAME = "pi-model-map.log";
16
+
17
+ /** Log file size cap before truncate-rotation. */
18
+ export const LOG_MAX_BYTES = 2 * 1024 * 1024;
package/src/index.ts ADDED
@@ -0,0 +1,522 @@
1
+ import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
2
+ import type {
3
+ Api,
4
+ AssistantMessageEventStream,
5
+ Model,
6
+ ModelThinkingLevel,
7
+ SimpleStreamOptions,
8
+ ThinkingLevel,
9
+ TranscriptContext,
10
+ } from "@earendil-works/pi-ai";
11
+ import type {
12
+ ExtensionAPI,
13
+ ExtensionCommandContext,
14
+ ExtensionContext,
15
+ } from "@earendil-works/pi-coding-agent";
16
+
17
+ import { buildProviderModels } from "./catalog.js";
18
+ import { createModelMappers } from "./config.js";
19
+ import { COMMAND_PREFIX, FAKE_REGISTRATION_API_KEY } from "./constants.js";
20
+ import { logFilePath, pluginWarn } from "./log.js";
21
+ import type { ModelMapper } from "./mapping.js";
22
+ import { checkAgainstSource } from "./source-check.js";
23
+ import { warnOnSessionStart } from "./warnings.js";
24
+
25
+ type DelegateProvider = {
26
+ streamSimple?: (
27
+ model: Model<Api>,
28
+ context: TranscriptContext,
29
+ options?: SimpleStreamOptions,
30
+ ) => AssistantMessageEventStream;
31
+ };
32
+
33
+ type Registration = {
34
+ mapper: ModelMapper;
35
+ streamMapped: (
36
+ model: Model<Api>,
37
+ context: TranscriptContext,
38
+ options?: SimpleStreamOptions,
39
+ ) => AssistantMessageEventStream;
40
+ };
41
+
42
+ /** Drop credentials Pi resolved for this virtual mapping provider so nested registry streaming can re-resolve the delegate. */
43
+ const withoutVirtualProviderAuth = (options?: SimpleStreamOptions): SimpleStreamOptions | undefined => {
44
+ if (!options) return options;
45
+ const { apiKey: _apiKey, headers: _headers, env: _env, ...rest } = options;
46
+ return rest;
47
+ };
48
+
49
+ /** ModelThinkingLevel's "off" isn't a real ThinkingLevel -- normalize it to undefined for the mapper APIs that expect `ThinkingLevel | undefined`. */
50
+ const asReasoningLevel = (level: ModelThinkingLevel | undefined): ThinkingLevel | undefined =>
51
+ level && level !== "off" ? level : undefined;
52
+
53
+ type ToggleArg = "on" | "off" | "toggle";
54
+
55
+ /**
56
+ * Opt-in routing trace. Off by default (silent, matches every other Pi provider). Enable with
57
+ * PI_MODEL_MAP_DEBUG=1 to print, on every request, exactly which backend provider/model a
58
+ * canonical model + effort level + toggle combination resolved to. Useful for confirming
59
+ * routing without needing to inspect the actual outbound HTTP payload.
60
+ */
61
+ const DEBUG =
62
+ process.env.PI_MODEL_MAP_DEBUG === "1" || process.env.PI_MODEL_MAP_DEBUG === "true";
63
+
64
+ const parseToggleArg = (args: string): ToggleArg => {
65
+ const trimmed = args.trim().toLowerCase();
66
+ if (trimmed === "on" || trimmed === "off") return trimmed;
67
+ if (trimmed === "") return "toggle";
68
+ throw new Error(`Expected "on", "off", or no argument to toggle. Got "${args}".`);
69
+ };
70
+
71
+ export default (pi: ExtensionAPI) => {
72
+ const mappers = createModelMappers();
73
+ let lastCtx: ExtensionContext | null = null;
74
+ let warnedOnSession = false;
75
+ const registrations: Registration[] = [];
76
+
77
+ // Session-wide mapping toggles. These do not add or emulate any real API parameter —
78
+ // they only pick which pre-baked backend model ID a "provider/modelId" map entry
79
+ // resolves to for providers (like Cursor) that bake a "thinking" mode and/or a
80
+ // "fast" routing tier into the model ID string instead of exposing them as
81
+ // request options.
82
+ let thinkingEnabled = false;
83
+ let fastEnabled = false;
84
+
85
+ const assertDelegateAvailable = (
86
+ mapper: ModelMapper,
87
+ delegateProvider: string,
88
+ ownStream: Registration["streamMapped"],
89
+ ): void => {
90
+ const delegate = lastCtx?.modelRegistry.getProvider(
91
+ delegateProvider,
92
+ ) as DelegateProvider | undefined;
93
+
94
+ if (delegate?.streamSimple === ownStream) {
95
+ throw new Error(
96
+ `[pi-model-map] Cannot delegate to "${delegateProvider}" (${mapper.source}) because this mapping ` +
97
+ `replaced that provider namespace (provider="${mapper.provider}"). ` +
98
+ `Use a unique provider name and keep the "provider/modelId" delegate as "${delegateProvider}/...".`,
99
+ );
100
+ }
101
+
102
+ if (!delegate?.streamSimple) {
103
+ throw new Error(
104
+ `[pi-model-map] Delegate provider "${delegateProvider}" is not available for ${mapper.provider} (${mapper.source}). ` +
105
+ `Install and authenticate the delegate connector first.`,
106
+ );
107
+ }
108
+ };
109
+
110
+ /**
111
+ * Warn if `canonicalId` at effort level `reasoning` has no non-thinking backend at all, so
112
+ * `/pi-model-map-thinking off` is silently overridden. Shared by streamMapped (checked on every
113
+ * request) and the model_select / thinking_level_select handlers (checked the moment the
114
+ * selection changes, before any request is ever sent).
115
+ *
116
+ * Tracks only the *most recently checked* (provider, canonicalId, level) combination, not
117
+ * "every combination ever warned about this session" -- so cycling /thinking xhigh -> max ->
118
+ * xhigh warns all three times (each is a real change from the immediately preceding state),
119
+ * while sending multiple turns in a row without changing the model or effort level does not
120
+ * repeat the warning, since nothing changed between those checks.
121
+ */
122
+ let lastCheckedThinkingOnlyKey: string | undefined;
123
+ const checkThinkingOnlyLevel = (
124
+ mapper: ModelMapper,
125
+ canonicalId: string,
126
+ reasoning: ThinkingLevel | undefined,
127
+ ): void => {
128
+ if (thinkingEnabled) return;
129
+ const level = mapper.resolvedLevel(canonicalId, reasoning);
130
+ const key = `${mapper.provider}/${canonicalId}:${level}`;
131
+ if (key === lastCheckedThinkingOnlyKey) return;
132
+ lastCheckedThinkingOnlyKey = key;
133
+ if (!mapper.isThinkingOnlyLevel(canonicalId, level)) return;
134
+ const effortLabel = reasoning ?? "off";
135
+ lastCtx?.ui.notify(
136
+ `${effortLabel} effort for ${canonicalId} is only supported in "thinking" mode. Thinking will be ` +
137
+ `silently enabled regardless of your current pi-model-map "thinking" setting.`,
138
+ "warning",
139
+ );
140
+ };
141
+
142
+ /**
143
+ * Warn if `canonicalId` was asked for an effort level that has no entry at all in its map, so
144
+ * `toBackendRef` silently falls back to the "default" level instead. Shared by streamMapped
145
+ * (checked on every request -- the only place this is guaranteed to see the level that will
146
+ * actually be sent, since a wrapper like pi-provider-manager's roundrobin can pick a different
147
+ * candidate per request without this extension ever seeing a model_select/thinking_level_select
148
+ * for it) and the model_select / thinking_level_select handlers (checked the moment the
149
+ * selection changes, for models selected directly rather than through such a wrapper).
150
+ *
151
+ * Tracked separately from `lastCheckedThinkingOnlyKey` (own dedup key) since the two warn about
152
+ * unrelated conditions and either can be true independently of the other's dedup state.
153
+ */
154
+ let lastCheckedUnmappedLevelKey: string | undefined;
155
+ const checkUnmappedLevel = (
156
+ mapper: ModelMapper,
157
+ canonicalId: string,
158
+ reasoning: ThinkingLevel | undefined,
159
+ ): void => {
160
+ // "off" (reasoning === undefined here) resolves to "default" by design, not by fallback --
161
+ // that's gated separately by offSupported / thinkingLevelMap.off in catalog.ts. Nothing to
162
+ // warn about here unless a real effort level was requested.
163
+ if (!reasoning) return;
164
+ const key = `${mapper.provider}/${canonicalId}:${reasoning}`;
165
+ if (key === lastCheckedUnmappedLevelKey) return;
166
+ lastCheckedUnmappedLevelKey = key;
167
+ if (!mapper.isUnmappedLevel(canonicalId, reasoning)) return;
168
+ lastCtx?.ui.notify(
169
+ `"${reasoning}" effort has no mapping for ${canonicalId} in ${mapper.source}. Falling back to ` +
170
+ `the default effort level for this model.`,
171
+ "warning",
172
+ );
173
+ };
174
+
175
+ for (const mapper of mappers) {
176
+ const streamMapped = (
177
+ model: Model<Api>,
178
+ context: TranscriptContext,
179
+ options?: SimpleStreamOptions,
180
+ ): AssistantMessageEventStream => {
181
+ const ref = mapper.toBackendRef(model.id, options?.reasoning, thinkingEnabled, fastEnabled);
182
+ if (!ref) {
183
+ throw new Error(
184
+ `[pi-model-map] No mapping found for "${model.id}" in ${mapper.source}.`,
185
+ );
186
+ }
187
+ checkThinkingOnlyLevel(mapper, model.id, options?.reasoning);
188
+ checkUnmappedLevel(mapper, model.id, options?.reasoning);
189
+ if (DEBUG) {
190
+ // Leading "\n": Pi's TUI doesn't insert a newline before extension stderr output, so
191
+ // without it this line would print immediately after the user's echoed input on the
192
+ // same terminal line instead of starting cleanly on its own.
193
+ console.error(
194
+ `\n[pi-model-map:debug] ${mapper.provider}/${model.id} ` +
195
+ `(reasoning=${options?.reasoning ?? "default"}, thinking=${thinkingEnabled}, fast=${fastEnabled}) ` +
196
+ `-> ${ref.provider}/${ref.id}`,
197
+ );
198
+ }
199
+ assertDelegateAvailable(mapper, ref.provider, streamMapped);
200
+ const registered = lastCtx?.modelRegistry.find(ref.provider, ref.id);
201
+ const backendModel: Model<Api> = registered
202
+ ? { ...registered, id: ref.id, provider: ref.provider }
203
+ : { ...model, id: ref.id, provider: ref.provider };
204
+
205
+ // Nested dispatch through ModelRegistry.streamSimple resolves the delegate's
206
+ // request-time auth (including headers and baseUrl). Incoming options.apiKey is
207
+ // this mapping provider's placeholder registration key and must not be forwarded.
208
+ const out = createAssistantMessageEventStream();
209
+ void (async () => {
210
+ try {
211
+ const ctx = lastCtx;
212
+ if (!ctx) {
213
+ throw new Error(
214
+ `[pi-model-map] No session context to stream ${ref.provider}/${ref.id} (${mapper.source}).`,
215
+ );
216
+ }
217
+ if (DEBUG && !registered) {
218
+ console.error(
219
+ `\n[pi-model-map:debug] no registry metadata for ${ref.provider}/${ref.id}; ` +
220
+ `delegating with the virtual model's api/baseUrl`,
221
+ );
222
+ }
223
+ const inner = ctx.modelRegistry.streamSimple(
224
+ backendModel,
225
+ context,
226
+ withoutVirtualProviderAuth(options),
227
+ );
228
+ for await (const event of inner) {
229
+ out.push(event);
230
+ }
231
+ } catch (error) {
232
+ const message = error instanceof Error ? error.message : String(error);
233
+ out.push({
234
+ type: "error",
235
+ reason: "error",
236
+ error: {
237
+ role: "assistant",
238
+ content: [],
239
+ api: backendModel.api,
240
+ provider: backendModel.provider,
241
+ model: backendModel.id,
242
+ usage: {
243
+ input: 0,
244
+ output: 0,
245
+ cacheRead: 0,
246
+ cacheWrite: 0,
247
+ totalTokens: 0,
248
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
249
+ },
250
+ stopReason: "error",
251
+ errorMessage: `[pi-model-map] ${message}`,
252
+ timestamp: Date.now(),
253
+ },
254
+ });
255
+ }
256
+ })();
257
+ return out;
258
+ };
259
+
260
+ registrations.push({ mapper, streamMapped });
261
+
262
+ pi.registerProvider(mapper.provider, {
263
+ name: mapper.displayName,
264
+ api: mapper.api,
265
+ apiKey: FAKE_REGISTRATION_API_KEY,
266
+ baseUrl: mapper.baseUrl,
267
+ models: buildProviderModels(mapper, mapper.api, mapper.baseUrl),
268
+ streamSimple: streamMapped,
269
+ });
270
+ }
271
+
272
+ const activeMapperForModel = (ctx: ExtensionContext): ModelMapper | undefined => {
273
+ const modelProvider = ctx.model?.provider;
274
+ return registrations.find((r) => r.mapper.provider === modelProvider)?.mapper;
275
+ };
276
+
277
+ const findRegistration = (provider: string | undefined): Registration | undefined =>
278
+ registrations.find((r) => r.mapper.provider === provider);
279
+
280
+ const missingBackends = (mapper: ModelMapper, canonicalId: string, ctx: ExtensionContext): string[] => {
281
+ return mapper.getFamilyBackendRefs(canonicalId)
282
+ .filter((ref) => !ctx.modelRegistry.find(ref.provider, ref.id))
283
+ .map((ref) => `${ref.provider}/${ref.id}`);
284
+ };
285
+
286
+ /** Registry availability is a session-start diagnostic, not a per-request check. */
287
+ const scanRegistryAvailability = (ctx: ExtensionContext): number => {
288
+ let issues = 0;
289
+ for (const { mapper, streamMapped } of registrations) {
290
+ warnOnSessionStart(ctx, mapper, streamMapped);
291
+ const availableFamilies = mapper.getCanonicalFamilies().filter((id) =>
292
+ mapper.getFamilyBackendRefs(id).some((ref) => ctx.modelRegistry.find(ref.provider, ref.id)),
293
+ );
294
+ for (const id of mapper.getCanonicalFamilies()) {
295
+ const refs = mapper.getFamilyBackendRefs(id);
296
+ const missing = missingBackends(mapper, id, ctx);
297
+ if (!availableFamilies.includes(id)) {
298
+ pluginWarn(
299
+ `Omitting ${mapper.provider}/${id}: none of its mapped backend models are registered.`,
300
+ );
301
+ issues++;
302
+ } else if (missing.length > 0 && missing.length < refs.length) {
303
+ pluginWarn(
304
+ `${mapper.provider}/${id} has unavailable mapped backend(s): ${missing.join(", ")}. ` +
305
+ `Other mapped backend variants are available; selecting an unavailable variant may fail.`,
306
+ );
307
+ issues++;
308
+ }
309
+ }
310
+ const models = buildProviderModels(mapper, mapper.api, mapper.baseUrl)
311
+ .filter((model) => availableFamilies.includes(model.id));
312
+ pi.registerProvider(mapper.provider, {
313
+ name: mapper.displayName,
314
+ api: mapper.api,
315
+ apiKey: FAKE_REGISTRATION_API_KEY,
316
+ baseUrl: mapper.baseUrl,
317
+ models,
318
+ streamSimple: streamMapped,
319
+ });
320
+ }
321
+ return issues;
322
+ };
323
+
324
+ const updateStatus = (ctx: ExtensionContext): void => {
325
+ const parts: string[] = [];
326
+ if (thinkingEnabled) parts.push("thinking");
327
+ if (fastEnabled) parts.push("fast");
328
+ ctx.ui.setStatus("pi-model-map", parts.length > 0 ? parts.join("+") : undefined);
329
+ };
330
+
331
+ const applyThinking = (ctx: ExtensionCommandContext, arg: ToggleArg): void => {
332
+ const next = arg === "toggle" ? !thinkingEnabled : arg === "on";
333
+ const mapper = activeMapperForModel(ctx);
334
+ if (next && mapper && ctx.model && !mapper.supportsThinkingToggle(ctx.model.id)) {
335
+ ctx.ui.notify(
336
+ `No "thinking" variant configured for ${ctx.model.id} in ${mapper.source}. Falling back to the default mapping.`,
337
+ "warning",
338
+ );
339
+ }
340
+ thinkingEnabled = next;
341
+ if (thinkingEnabled) {
342
+ // The thinking-only-level warning only applies while the toggle is off (see
343
+ // checkThinkingOnlyLevel); clear its "last checked" state so that if the toggle is turned
344
+ // back off later while still on the same model/level, that's treated as a fresh change and
345
+ // warns again, rather than being silently deduped against a check from before this toggle.
346
+ lastCheckedThinkingOnlyKey = undefined;
347
+ }
348
+ updateStatus(ctx);
349
+ ctx.ui.notify(`Model-map thinking variant: ${thinkingEnabled ? "on" : "off"}`, "info");
350
+ };
351
+
352
+ const applyFast = (ctx: ExtensionCommandContext, arg: ToggleArg): void => {
353
+ const next = arg === "toggle" ? !fastEnabled : arg === "on";
354
+ const mapper = activeMapperForModel(ctx);
355
+ if (next && mapper && ctx.model && !mapper.supportsFastToggle(ctx.model.id)) {
356
+ ctx.ui.notify(
357
+ `No "fast" variant configured for ${ctx.model.id} in ${mapper.source}. Falling back to the default mapping.`,
358
+ "warning",
359
+ );
360
+ }
361
+ fastEnabled = next;
362
+ updateStatus(ctx);
363
+ ctx.ui.notify(`Model-map fast variant: ${fastEnabled ? "on" : "off"}`, "info");
364
+ };
365
+
366
+ const toggleCompletions = (prefix: string) => {
367
+ const options = ["on", "off"];
368
+ const trimmed = prefix.trim();
369
+ const filtered = trimmed.length > 0 ? options.filter((o) => o.startsWith(trimmed)) : options;
370
+ return filtered.length > 0 ? filtered.map((value) => ({ value, label: value })) : null;
371
+ };
372
+
373
+ pi.registerCommand(`${COMMAND_PREFIX}-thinking`, {
374
+ description:
375
+ 'Toggle use of the mapped "thinking" backend variant (falls back to default if unconfigured)',
376
+ getArgumentCompletions: toggleCompletions,
377
+ handler: async (args, ctx) => {
378
+ try {
379
+ applyThinking(ctx, parseToggleArg(args));
380
+ } catch (error) {
381
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
382
+ }
383
+ },
384
+ });
385
+ pi.registerCommand(`${COMMAND_PREFIX}-thinking-on`, {
386
+ description: 'Enable the mapped "thinking" backend variant',
387
+ handler: async (_args, ctx) => applyThinking(ctx, "on"),
388
+ });
389
+ pi.registerCommand(`${COMMAND_PREFIX}-thinking-off`, {
390
+ description: 'Disable the mapped "thinking" backend variant',
391
+ handler: async (_args, ctx) => applyThinking(ctx, "off"),
392
+ });
393
+
394
+ pi.registerCommand(`${COMMAND_PREFIX}-fast`, {
395
+ description:
396
+ 'Toggle use of the mapped "fast" backend variant (falls back to default if unconfigured)',
397
+ getArgumentCompletions: toggleCompletions,
398
+ handler: async (args, ctx) => {
399
+ try {
400
+ applyFast(ctx, parseToggleArg(args));
401
+ } catch (error) {
402
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
403
+ }
404
+ },
405
+ });
406
+ pi.registerCommand(`${COMMAND_PREFIX}-fast-on`, {
407
+ description: 'Enable the mapped "fast" backend variant',
408
+ handler: async (_args, ctx) => applyFast(ctx, "on"),
409
+ });
410
+ pi.registerCommand(`${COMMAND_PREFIX}-fast-off`, {
411
+ description: 'Disable the mapped "fast" backend variant',
412
+ handler: async (_args, ctx) => applyFast(ctx, "off"),
413
+ });
414
+
415
+ pi.registerCommand(`${COMMAND_PREFIX}-check-source`, {
416
+ description:
417
+ 'Re-check every config file\'s "source" catalog now (without restarting Pi) and report any backend ids that have disappeared',
418
+ handler: async (_args, ctx) => {
419
+ let checked = 0;
420
+ let stale = 0;
421
+ let skipped = 0;
422
+ for (const { mapper } of registrations) {
423
+ const result = checkAgainstSource(mapper);
424
+ if (!result) {
425
+ skipped++;
426
+ continue;
427
+ }
428
+ checked++;
429
+ if (result.error) {
430
+ ctx.ui.notify(
431
+ `${mapper.provider}: could not check "${result.resolvedPath}": ${result.error}`,
432
+ "warning",
433
+ );
434
+ continue;
435
+ }
436
+ if (result.missingIds.length > 0) {
437
+ stale += result.missingIds.length;
438
+ for (const id of result.missingIds) {
439
+ const locations = mapper.getBackendIdLocations(id).join(", ");
440
+ ctx.ui.notify(
441
+ `${mapper.provider}: backend id "${id}" (${locations}) not found in ${result.resolvedPath}`,
442
+ "warning",
443
+ );
444
+ }
445
+ }
446
+ }
447
+ if (checked === 0) {
448
+ ctx.ui.notify(
449
+ `No config file has "source" set -- nothing to check. Add "source" (and optionally ` +
450
+ `"sourceListPath"/"sourceIdField") to a config file to enable this.`,
451
+ "info",
452
+ );
453
+ } else if (stale === 0) {
454
+ ctx.ui.notify(
455
+ `Checked ${checked} config file(s) against their "source" catalogs: every backend id still exists.${skipped > 0 ? ` (${skipped} file(s) skipped -- no "source" set.)` : ""}`,
456
+ "info",
457
+ );
458
+ } else {
459
+ ctx.ui.notify(`Found ${stale} stale backend id(s) across ${checked} checked config file(s). See warnings above.`, "warning");
460
+ }
461
+ },
462
+ });
463
+
464
+ const rememberContext = (_: unknown, ctx: ExtensionContext) => {
465
+ lastCtx = ctx;
466
+ updateStatus(ctx);
467
+ };
468
+
469
+ pi.on("session_start", (_event, ctx) => {
470
+ lastCtx = ctx;
471
+ const issues = scanRegistryAvailability(ctx);
472
+ if (issues > 0) {
473
+ ctx.ui.notify(
474
+ `${issues} mapped family(ies) have backends Pi has not registered. Details: ${logFilePath()}`,
475
+ "warning",
476
+ );
477
+ }
478
+ if (!warnedOnSession) {
479
+ // Also check whatever model/thinking-level is already active as of this session bind --
480
+ // covers a session that already had an affected model+level selected before this check
481
+ // existed, or before an extension reload, rather than only catching it on the next change
482
+ // or the next request.
483
+ if (ctx.model) {
484
+ const registration = findRegistration(ctx.model.provider);
485
+ if (registration) {
486
+ const level = asReasoningLevel(ctx.thinkingLevel);
487
+ checkThinkingOnlyLevel(registration.mapper, ctx.model.id, level);
488
+ checkUnmappedLevel(registration.mapper, ctx.model.id, level);
489
+ }
490
+ }
491
+ warnedOnSession = true;
492
+ }
493
+ updateStatus(ctx);
494
+ });
495
+
496
+ // Keep lastCtx current for nested streaming; do not re-scan the registry on every turn.
497
+ pi.on("before_agent_start", rememberContext);
498
+
499
+ // Proactively catch the same "this effort level is thinking-only" situation the moment the
500
+ // model or thinking level changes, rather than only at request time (streamMapped already
501
+ // covers request time; these two cover selection time).
502
+ pi.on("model_select", (event, ctx) => {
503
+ lastCtx = ctx;
504
+ const registration = findRegistration(event.model.provider);
505
+ if (registration) {
506
+ const level = asReasoningLevel(ctx.thinkingLevel);
507
+ checkThinkingOnlyLevel(registration.mapper, event.model.id, level);
508
+ checkUnmappedLevel(registration.mapper, event.model.id, level);
509
+ }
510
+ });
511
+
512
+ pi.on("thinking_level_select", (event, ctx) => {
513
+ lastCtx = ctx;
514
+ if (!ctx.model) return;
515
+ const registration = findRegistration(ctx.model.provider);
516
+ if (registration) {
517
+ const level = asReasoningLevel(event.level);
518
+ checkThinkingOnlyLevel(registration.mapper, ctx.model.id, level);
519
+ checkUnmappedLevel(registration.mapper, ctx.model.id, level);
520
+ }
521
+ });
522
+ };