@evandu/super-pi 0.1.216 → 0.1.218

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 (40) hide show
  1. package/dist/client/.super-pi-client-sources.json +6 -6
  2. package/dist/client/assets/{CodeMirrorEditor-lexoCaIG.js → CodeMirrorEditor-CyESWKhO.js} +2 -2
  3. package/dist/client/assets/{dist-BnnInFnU.js → dist-1djw1Aua.js} +1 -1
  4. package/dist/client/assets/{dist-3-Tz7V5x.js → dist-B33BwR-8.js} +1 -1
  5. package/dist/client/assets/{dist-Bb5oLu1I.js → dist-BQ5yUYGI.js} +1 -1
  6. package/dist/client/assets/{dist-BK9jBgy4.js → dist-BXMYNRiG.js} +1 -1
  7. package/dist/client/assets/{dist-BpfM-LP8.js → dist-BXq9HMCd.js} +1 -1
  8. package/dist/client/assets/{dist-DNfXS-LN.js → dist-BfAB10-T.js} +1 -1
  9. package/dist/client/assets/{dist-B3rJZwH0.js → dist-BlALlifb.js} +1 -1
  10. package/dist/client/assets/{dist-CYNCQ0fQ.js → dist-BwQiVXeZ.js} +1 -1
  11. package/dist/client/assets/{dist-B8hN96MY.js → dist-C6tiomV0.js} +1 -1
  12. package/dist/client/assets/{dist-BG9UcsbA.js → dist-C7y8W3IU.js} +1 -1
  13. package/dist/client/assets/{dist-B38kVE3N.js → dist-C9qNY2Kp.js} +1 -1
  14. package/dist/client/assets/{dist-otNdihLI.js → dist-CWLwzCNI.js} +1 -1
  15. package/dist/client/assets/{dist-DHLp8Bhu.js → dist-Cgclz1Km.js} +1 -1
  16. package/dist/client/assets/{dist-BPCH5VZO.js → dist-CkjmcyTq.js} +1 -1
  17. package/dist/client/assets/{dist-FKpeRDqz.js → dist-DH6F4kKv.js} +1 -1
  18. package/dist/client/assets/{dist-BmyPZADX.js → dist-DHh4-Br1.js} +1 -1
  19. package/dist/client/assets/{dist-Bhq8WMen.js → dist-DZGY_CNU.js} +1 -1
  20. package/dist/client/assets/{dist-B-mRGWa4.js → dist-DtyV497P.js} +1 -1
  21. package/dist/client/assets/{dist-Bk2EriC1.js → dist-GMozZ-IZ.js} +1 -1
  22. package/dist/client/assets/{dist-B9VATyNG.js → dist-XNj0UVAT.js} +1 -1
  23. package/dist/client/assets/{dist-DgZHuTC8.js → dist-Zl8KoipB.js} +1 -1
  24. package/dist/client/assets/{dist-Da4kKR0w.js → dist-xAE0Sxu_.js} +1 -1
  25. package/dist/client/assets/{index-Dc62tdic.js → index-2k9h0zMt.js} +20 -20
  26. package/dist/client/assets/index-CwfAN5Vw.css +1 -0
  27. package/dist/client/index.html +2 -2
  28. package/dist/server/application/provider-service.js +50 -7
  29. package/dist/server/pi-session.d.ts +26 -5
  30. package/dist/server/pi-session.js +64 -12
  31. package/dist/server/providers.d.ts +22 -1
  32. package/dist/server/providers.js +106 -17
  33. package/dist/server/runtime.js +19 -3
  34. package/dist/server/thinking-level-discovery.d.ts +38 -0
  35. package/dist/server/thinking-level-discovery.js +159 -0
  36. package/dist/server/types.d.ts +25 -0
  37. package/dist/shared/thinking-levels.d.ts +53 -0
  38. package/dist/shared/thinking-levels.js +85 -0
  39. package/package.json +1 -1
  40. package/dist/client/assets/index-DVt_dk47.css +0 -1
@@ -8,8 +8,8 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-Dc62tdic.js"></script>
12
- <link rel="stylesheet" crossorigin href="/assets/index-DVt_dk47.css">
11
+ <script type="module" crossorigin src="/assets/index-2k9h0zMt.js"></script>
12
+ <link rel="stylesheet" crossorigin href="/assets/index-CwfAN5Vw.css">
13
13
  </head>
14
14
  <body>
15
15
  <div id="root"></div>
@@ -2,6 +2,7 @@ import { KNOWN_APIS, publicProviders, validateProvider, fetchRemoteModels } from
2
2
  import { readProviderProxyEnv } from "../provider-proxy.js";
3
3
  import { piAgentDir } from "../providers.js";
4
4
  import { hasStoredCredential } from "../provider-network.js";
5
+ import { thinkingLevelsEndpoint } from "../../shared/thinking-levels.js";
5
6
  /**
6
7
  * THE PROVIDERS A PERSON ADDED, as a service.
7
8
  *
@@ -187,13 +188,42 @@ export class ProviderService {
187
188
  const models = !existing
188
189
  ? requested.models
189
190
  : (() => {
190
- let list = [...existing.models];
191
- for (const inc of requested.models) {
191
+ const endpointChanged = thinkingLevelsEndpoint(existing.baseUrl, existing.api)
192
+ !== thinkingLevelsEndpoint(requested.baseUrl, requested.api);
193
+ const list = existing.models.map((model) => endpointChanged
194
+ ? { ...model, thinkingLevelMap: null }
195
+ : model);
196
+ for (const model of requested.models) {
197
+ const inc = endpointChanged && model.thinkingLevelMap === undefined
198
+ ? { ...model, thinkingLevelMap: null }
199
+ : model;
192
200
  const idx = list.findIndex((m) => m.id === inc.id);
193
- if (idx >= 0)
194
- list[idx] = inc;
195
- else
196
- list.push(inc);
201
+ if (idx < 0) {
202
+ list.push(inc.thinkingLevelMap
203
+ ? { ...inc, reasoning: inc.reasoning === undefined ? true : inc.reasoning }
204
+ : inc);
205
+ continue;
206
+ }
207
+ const saved = list[idx];
208
+ if (inc.thinkingLevelMap === undefined && saved.thinkingLevelMap !== undefined) {
209
+ // NO NEW LEVELS, AND THERE ARE OLD ONES. The saved levels stay, and everything that
210
+ // goes with them stays: the model's own word about thinking - somebody may have
211
+ // turned it off by hand, and that is not this form's to undo - and the compatibility
212
+ // switches somebody set are not reset by an import that knows nothing about them.
213
+ list[idx] = {
214
+ ...inc,
215
+ reasoning: saved.reasoning ?? inc.reasoning,
216
+ thinkingLevelMap: saved.thinkingLevelMap,
217
+ ...(saved.supportsDeveloperRole !== undefined ? { supportsDeveloperRole: saved.supportsDeveloperRole } : {}),
218
+ ...(saved.supportsReasoningEffort !== undefined ? { supportsReasoningEffort: saved.supportsReasoningEffort } : {}),
219
+ };
220
+ continue;
221
+ }
222
+ // A MAP MEANS THE MODEL THINKS - unless somebody already said otherwise, in which case
223
+ // their word wins: the levels are not a licence to overrule it.
224
+ list[idx] = inc.thinkingLevelMap
225
+ ? { ...inc, reasoning: inc.reasoning === undefined ? (saved.reasoning ?? true) : inc.reasoning }
226
+ : inc;
197
227
  }
198
228
  return list;
199
229
  })();
@@ -217,7 +247,20 @@ export class ProviderService {
217
247
  // what it put into Pi's files. Pi's files are put back the way they were, and the failure is
218
248
  // reported rather than swallowed: a registry that disagrees with Pi's files is a state the
219
249
  // next write would trip over.
220
- await this.registry.applyToPi(next, previous).catch(() => undefined);
250
+ //
251
+ // THE OLD STATE, EXACTLY. The write that is being undone put the new thinking levels into
252
+ // Pi's file, and the "keep whatever was there" rule would carry them into the rollback - so
253
+ // a model that had NO levels before would keep the ones the failed write gave it. The
254
+ // levels are therefore said out loud (`null` means "this model has none"), which is the same
255
+ // thing the form says when it means it.
256
+ const restore = previous.map((provider) => ({
257
+ ...provider,
258
+ models: provider.models.map((model) => ({
259
+ ...model,
260
+ thinkingLevelMap: model.thinkingLevelMap ?? null,
261
+ })),
262
+ }));
263
+ await this.registry.applyToPi(next, restore).catch(() => undefined);
221
264
  throw error;
222
265
  }
223
266
  await this.afterChange();
@@ -139,15 +139,22 @@ export declare function warmPiSdk(): Promise<boolean>;
139
139
  export interface SdkCatalog {
140
140
  /** Pi's own model objects, for the caller to reduce with the same helpers the RPC path used. */
141
141
  models: unknown[];
142
- /** The model Pi would use by default, if settings name one. */
142
+ /**
143
+ * THE MODEL PI WOULD RUN, resolved by PI ITSELF.
144
+ *
145
+ * NOT "the pair Pi's settings name". Pi's settings are a WISH, and a wish is not always granted:
146
+ * the pair may be absent (nobody ever chose a default), it may name a model Pi no longer offers,
147
+ * and it may name a model whose provider has no credential. Pi's own resolver checks all three
148
+ * and, when the wish cannot be granted, picks a model it CAN run. This is that model's identity.
149
+ *
150
+ * UNDEFINED MEANS "PI HAS NO MODEL TO RUN", which is an honest answer and not a gap to paper over.
151
+ */
143
152
  defaultModel?: {
144
153
  provider: string;
145
154
  modelId: string;
146
155
  };
147
- /** The thinking level Pi would use by default, if settings name one. */
148
- defaultThinkingLevel?: string;
149
156
  /**
150
- * The levels a model supports, read from a session running that model.
157
+ * The levels a model supports, AND the level in force for it, read from a session running that model.
151
158
  *
152
159
  * Separate from the models because it is the expensive half: it needs a session, so a caller that
153
160
  * only wants the list does not pay for it.
@@ -155,11 +162,15 @@ export interface SdkCatalog {
155
162
  * UNDEFINED MEANS "THIS RUNTIME DOES NOT KNOW THAT MODEL", and it is not the same answer as "that
156
163
  * model has no levels but off". A caller that gets undefined asks whoever does know the model; a
157
164
  * caller that got a list would be showing another model's levels.
165
+ *
166
+ * THE LEVEL IN FORCE COMES FROM THE SAME SESSION, because that is where Pi decides it: the
167
+ * per-model override, else the global default, CLAMPED to what this model actually offers.
168
+ * Reporting the unclamped preference would put a level on screen that the model does not have.
158
169
  */
159
170
  thinkingLevelsFor(model: {
160
171
  provider: string;
161
172
  modelId: string;
162
- }): Promise<string[] | undefined>;
173
+ }): Promise<ModelThinking | undefined>;
163
174
  /**
164
175
  * WHAT PI SAYS IS WRONG WITH ITS OWN MODEL CONFIGURATION, verbatim.
165
176
  *
@@ -170,6 +181,16 @@ export interface SdkCatalog {
170
181
  */
171
182
  configError(): string | undefined;
172
183
  }
184
+ /**
185
+ * What a session says about one model's thinking: the levels it offers, and the one in force.
186
+ *
187
+ * The level is Pi's own answer, already clamped to the model. A level that is not in `levels` is a
188
+ * level the model does not have, and putting it on screen would be a claim the model cannot back.
189
+ */
190
+ export type ModelThinking = {
191
+ levels: string[];
192
+ level?: string;
193
+ };
173
194
  /**
174
195
  * Builds a zero-process catalog reader.
175
196
  *
@@ -99,18 +99,17 @@ export async function createSdkCatalog(cwd) {
99
99
  const settingsManager = sdk.SettingsManager.create(cwd, agentDir);
100
100
  const models = (await modelRuntime.getAvailable?.()) ?? modelRuntime.getModels?.() ?? [];
101
101
  const levelsByModel = new Map();
102
+ // THE DEFAULT MODEL IS PI'S TO DECIDE, SO PI IS ASKED. Not read out of the settings and not guessed:
103
+ // the settings say what the person WANTS, and Pi decides what will actually run.
104
+ const resolved = await resolveDefaultModel(sdk, { cwd, agentDir, modelRuntime, settingsManager });
105
+ // The default's own levels come from the session that resolved it, so the level list is not paid
106
+ // for twice: the next question about that model is a cache hit.
107
+ if (resolved)
108
+ levelsByModel.set(`${resolved.model.provider}/${resolved.model.modelId}`, resolved.thinking);
102
109
  return {
103
110
  models,
104
111
  configError: () => modelRuntime.getError?.(),
105
- ...(settingsManager.getDefaultProvider?.() && settingsManager.getDefaultModel?.()
106
- ? {
107
- defaultModel: {
108
- provider: settingsManager.getDefaultProvider(),
109
- modelId: settingsManager.getDefaultModel(),
110
- },
111
- }
112
- : {}),
113
- ...(settingsManager.getDefaultThinkingLevel?.() ? { defaultThinkingLevel: settingsManager.getDefaultThinkingLevel() } : {}),
112
+ ...(resolved ? { defaultModel: resolved.model } : {}),
114
113
  thinkingLevelsFor: async (model) => {
115
114
  const key = `${model.provider}/${model.modelId}`;
116
115
  const cached = levelsByModel.get(key);
@@ -136,9 +135,9 @@ export async function createSdkCatalog(cwd) {
136
135
  model: whole,
137
136
  });
138
137
  try {
139
- const levels = sessionLevels(session);
140
- levelsByModel.set(key, levels);
141
- return levels;
138
+ const value = sessionThinking(session);
139
+ levelsByModel.set(key, value);
140
+ return value;
142
141
  }
143
142
  finally {
144
143
  session.dispose?.();
@@ -146,11 +145,64 @@ export async function createSdkCatalog(cwd) {
146
145
  },
147
146
  };
148
147
  }
148
+ /**
149
+ * THE MODEL PI WOULD RUN, AND WHAT IT CAN THINK - asked of Pi.
150
+ *
151
+ * THE SESSION IS BUILT WITH NO MODEL ON PURPOSE. That is the one way to make Pi do its own default
152
+ * resolution instead of Super Pi guessing at it: Pi's resolver prefers the settings' default, but
153
+ * only when that model still exists AND its provider has a credential, and otherwise it picks a
154
+ * model it can actually run - a preference Super Pi cannot read, because the table of "the default
155
+ * model per provider" is Pi's own and is not exported.
156
+ *
157
+ * The session that comes back is RUNNING ON the model Pi picked, so its levels and its thinking
158
+ * level are that model's - read from the same place Pi reads them from.
159
+ *
160
+ * NO INFERENCE IS SENT. A session that has not been prompted does not talk to the provider; it only
161
+ * resolves its configuration. And a session with NO MODEL reports every thinking level there is,
162
+ * which is Pi's way of saying "I have no model to level" - so a session without a model is not an
163
+ * answer at all, and the honest one is "Pi has no model to run".
164
+ */
165
+ async function resolveDefaultModel(sdk, options) {
166
+ let session;
167
+ try {
168
+ const created = await sdk.createAgentSession({
169
+ cwd: options.cwd,
170
+ agentDir: options.agentDir,
171
+ modelRuntime: options.modelRuntime,
172
+ settingsManager: options.settingsManager,
173
+ sessionManager: sdk.SessionManager.inMemory(options.cwd, { id: "catalog-default" }),
174
+ // NO MODEL: THAT IS THE POINT. Pi resolves the one it would run.
175
+ });
176
+ session = created.session;
177
+ const model = session.model;
178
+ if (typeof model?.provider !== "string" || !model.provider || typeof model.id !== "string" || !model.id)
179
+ return undefined;
180
+ return { model: { provider: model.provider, modelId: model.id }, thinking: sessionThinking(session) };
181
+ }
182
+ catch (error) {
183
+ console.warn(`Pi's SDK could not resolve the default model: ${error instanceof Error ? error.message : String(error)}. The catalog will report no default model rather than a wrong one.`);
184
+ return undefined;
185
+ }
186
+ finally {
187
+ session?.dispose?.();
188
+ }
189
+ }
149
190
  /** Reads the thinking levels off a session, tolerating a session that does not implement the call. */
150
191
  function sessionLevels(session) {
151
192
  const levels = session.getAvailableThinkingLevels?.();
152
193
  return Array.isArray(levels) ? levels.filter((level) => typeof level === "string") : [];
153
194
  }
195
+ /**
196
+ * The levels a session's model offers, AND the level in force on it.
197
+ *
198
+ * The level is read off the session because that is where Pi clamped it: the per-model override,
199
+ * else the global default, brought down to a level this model actually has.
200
+ */
201
+ function sessionThinking(session) {
202
+ const levels = sessionLevels(session);
203
+ const level = session.thinkingLevel;
204
+ return { levels, ...(typeof level === "string" && level ? { level } : {}) };
205
+ }
154
206
  /**
155
207
  * The transcript file a conversation's session writes to, found WITHOUT starting a Pi process.
156
208
  *
@@ -1,5 +1,6 @@
1
1
  import type { DiscoveredModel, PublicProvider } from "./types.js";
2
2
  import type { SharedProviderProxySettings } from "../shared/provider-network.js";
3
+ import { type ThinkingLevelMap } from "../shared/thinking-levels.js";
3
4
  /**
4
5
  * THE PROVIDERS A PERSON ADDED, and the two files that make Pi know about them.
5
6
  *
@@ -54,6 +55,18 @@ export type ProviderModelDefinition = {
54
55
  */
55
56
  supportsDeveloperRole?: boolean;
56
57
  supportsReasoningEffort?: boolean;
58
+ /**
59
+ * The thinking levels this model really offers, and what each one is sent as.
60
+ *
61
+ * THREE STATES, and the difference between them is the whole point:
62
+ * - ABSENT: nobody said anything about the levels. Whatever was saved for this model stays -
63
+ * a hand-written map in Pi's own file is not this form's to delete.
64
+ * - `null`: this model has NO map. The levels that were saved described an endpoint this model
65
+ * is no longer served by, so they go rather than travel to the new address.
66
+ * - A map: these are the levels, and every one of Pi's seven is named - `null` for the ones the
67
+ * model does not have, because Pi enables the ordinary ones when the map is silent.
68
+ */
69
+ thinkingLevelMap?: ThinkingLevelMap | null;
57
70
  };
58
71
  /** One provider, as the settings window collects it. */
59
72
  export type ProviderDefinition = {
@@ -308,5 +321,13 @@ export declare function fetchRemoteModels(input: {
308
321
  *
309
322
  * `fetchRemoteModels` is the transport; this is the reading. Keeping them apart means the reading can
310
323
  * be pinned exactly, and a slow machine can never turn a parsing question into a timeout.
324
+ *
325
+ * THE CONTEXT IS THE ENDPOINT THAT ANSWERED, and it matters for exactly one thing: the thinking
326
+ * levels. A level is only true of the endpoint that published it, so the rules that depend on the
327
+ * address need it - and the rules that do not (a model that declares its own levels) work without
328
+ * it, which is why the context is optional.
311
329
  */
312
- export declare function parseRemoteModels(payload: unknown): DiscoveredModel[];
330
+ export declare function parseRemoteModels(payload: unknown, context?: {
331
+ baseUrl?: string;
332
+ api?: string;
333
+ }): DiscoveredModel[];
@@ -6,6 +6,8 @@ import { SUPER_PI_DEFAULT_MAX_TOKENS, SUPER_PI_GUESSED_MAX_TOKENS as GUESSED_MAX
6
6
  import { providerProxyFetch, readSharedProviderProxy } from "./provider-proxy.js";
7
7
  import { hasStoredCredential, publicProviderNetwork, updateProviderNetwork, ProviderNetworkInputError } from "./provider-network.js";
8
8
  import { supportsProviderProxy } from "../shared/provider-network.js";
9
+ import { isThinkingLevel, readThinkingLevelMap } from "../shared/thinking-levels.js";
10
+ import { discoverThinkingLevels } from "./thinking-level-discovery.js";
9
11
  const unsupportedProxy = (provider) => !supportsProviderProxy(provider);
10
12
  /**
11
13
  * The API adapters Pi ships, as the ids a provider may name.
@@ -220,6 +222,20 @@ function toPiProvider(provider, existing) {
220
222
  ...(model.supportsDeveloperRole === undefined ? {} : { supportsDeveloperRole: model.supportsDeveloperRole }),
221
223
  ...(model.supportsReasoningEffort === undefined ? {} : { supportsReasoningEffort: model.supportsReasoningEffort }),
222
224
  };
225
+ // THE THINKING MAP, IN THREE STATES. A map is written when there is one; `null` REMOVES the one
226
+ // that was there (the levels described an endpoint this model is no longer served by); and
227
+ // ABSENT leaves the saved map alone - a map somebody wrote by hand in Pi's own file is not this
228
+ // form's to delete, and an import that knows nothing about the levels must not throw them away.
229
+ const thinkingLevelMap = model.thinkingLevelMap === null
230
+ ? undefined
231
+ : (model.thinkingLevelMap ?? priorModel.thinkingLevelMap);
232
+ // A MAP MEANS THE MODEL THINKS - UNLESS SOMEBODY SAID OTHERWISE. Pi offers only `off` for a
233
+ // model that does not reason, so levels without `reasoning` would be levels that do nothing;
234
+ // but a model somebody turned off BY HAND stays off, because the map is not a licence to
235
+ // overrule the word that is already there.
236
+ const reasoning = thinkingLevelMap && model.reasoning === undefined
237
+ ? true
238
+ : (model.reasoning ?? false);
223
239
  return {
224
240
  ...priorModel,
225
241
  id: model.id,
@@ -227,11 +243,14 @@ function toPiProvider(provider, existing) {
227
243
  // invalidates the WHOLE models.json - which takes every custom provider out of every picker
228
244
  // with nothing but "must not have fewer than 1 characters" to explain it.
229
245
  name: model.name || model.id,
230
- reasoning: model.reasoning ?? false,
246
+ reasoning,
231
247
  input: model.imageInput ? ["text", "image"] : ["text"],
232
248
  contextWindow: model.contextWindow ?? DEFAULT_CONTEXT_WINDOW,
233
249
  maxTokens: model.maxTokens ?? DEFAULT_MAX_TOKENS,
234
250
  ...(Object.keys(compat).length ? { compat } : { compat: undefined }),
251
+ ...(thinkingLevelMap === undefined
252
+ ? (model.thinkingLevelMap === null ? { thinkingLevelMap: undefined } : {})
253
+ : { thinkingLevelMap }),
235
254
  };
236
255
  });
237
256
  return {
@@ -369,18 +388,27 @@ export class ProviderRegistry {
369
388
  const api = typeof rec.api === "string" ? rec.api : (backup?.api ?? "openai-completions");
370
389
  const name = typeof rec.name === "string" ? rec.name : (backup?.name ?? pId);
371
390
  const rawModels = Array.isArray(rec.models) ? rec.models : (backup?.models ?? []);
372
- const models = rawModels.map((m) => ({
373
- id: typeof m?.id === "string" ? m.id : String(m),
374
- name: typeof m?.name === "string" ? m.name : m?.id,
375
- reasoning: Boolean(m?.reasoning),
376
- imageInput: Array.isArray(m?.input) ? m.input.includes("image") : false,
377
- contextWindow: typeof m?.contextWindow === "number" ? m.contextWindow : undefined,
378
- maxTokens: typeof m?.maxTokens === "number" ? m.maxTokens : undefined,
379
- // THE TWO COMPATIBILITY SWITCHES ARE READ BACK, or the form would show its own defaults for
380
- // a setting the file explicitly turned off, and saving the form would silently turn it on.
381
- ...(typeof m?.compat?.supportsDeveloperRole === "boolean" ? { supportsDeveloperRole: m.compat.supportsDeveloperRole } : {}),
382
- ...(typeof m?.compat?.supportsReasoningEffort === "boolean" ? { supportsReasoningEffort: m.compat.supportsReasoningEffort } : {}),
383
- }));
391
+ const models = rawModels.map((m) => {
392
+ // THE THINKING MAP IS READ BACK, or the panel would show a model with no levels while Pi is
393
+ // offering exactly the ones the file says. What is in Pi's own file IS what the model has.
394
+ const thinkingLevelMap = readThinkingLevelMap(m?.thinkingLevelMap);
395
+ return {
396
+ id: typeof m?.id === "string" ? m.id : String(m),
397
+ name: typeof m?.name === "string" ? m.name : m?.id,
398
+ // THE MODEL'S OWN WORD ABOUT THINKING, kept as it was written. A model whose entry says
399
+ // nothing about it stays silent - so the layers below can tell "somebody turned the
400
+ // thinking off" from "nobody ever said" - and the panel fills the gap with false.
401
+ reasoning: typeof m?.reasoning === "boolean" ? m.reasoning : undefined,
402
+ imageInput: Array.isArray(m?.input) ? m.input.includes("image") : false,
403
+ contextWindow: typeof m?.contextWindow === "number" ? m.contextWindow : undefined,
404
+ maxTokens: typeof m?.maxTokens === "number" ? m.maxTokens : undefined,
405
+ // THE TWO COMPATIBILITY SWITCHES ARE READ BACK, or the form would show its own defaults for
406
+ // a setting the file explicitly turned off, and saving the form would silently turn it on.
407
+ ...(typeof m?.compat?.supportsDeveloperRole === "boolean" ? { supportsDeveloperRole: m.compat.supportsDeveloperRole } : {}),
408
+ ...(typeof m?.compat?.supportsReasoningEffort === "boolean" ? { supportsReasoningEffort: m.compat.supportsReasoningEffort } : {}),
409
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
410
+ };
411
+ });
384
412
  const apiKey = backup?.apiKey;
385
413
  providers.push({
386
414
  id: pId,
@@ -694,9 +722,37 @@ export function publicProviders(providers) {
694
722
  imageInput: model.imageInput ?? false,
695
723
  contextWindow: model.contextWindow ?? DEFAULT_CONTEXT_WINDOW,
696
724
  maxTokens: model.maxTokens ?? DEFAULT_MAX_TOKENS,
725
+ // THE LEVELS TRAVEL TO THE BROWSER, because the panel shows them and the form sends them back.
726
+ // A model with no map simply has none - the browser must not invent one.
727
+ ...(model.thinkingLevelMap ? { thinkingLevelMap: { ...model.thinkingLevelMap } } : {}),
697
728
  })),
698
729
  }));
699
730
  }
731
+ /**
732
+ * Checks the thinking map a form carried, and returns it in the shape the registry stores.
733
+ *
734
+ * THREE ANSWERS. `undefined` means the form said nothing about the levels, so whatever is saved
735
+ * stays. `null` means the form said "this model has no map", and the saved one goes. A map means
736
+ * "these are the levels", and every one of Pi's seven has to be named - a level that is not a level
737
+ * Pi knows, or a value that is neither a string nor `null`, is refused rather than written into
738
+ * Pi's file, where one bad field takes every provider out of every picker.
739
+ */
740
+ function checkedThinkingLevelMap(raw) {
741
+ if (raw === undefined)
742
+ return undefined;
743
+ if (raw === null)
744
+ return null;
745
+ if (typeof raw !== "object" || Array.isArray(raw))
746
+ throw new Error("思考档位必须是一个对象");
747
+ for (const [key, value] of Object.entries(raw)) {
748
+ if (!isThinkingLevel(key))
749
+ throw new Error(`思考档位「${key}」不是 Pi 的档位`);
750
+ if (value !== null && (typeof value !== "string" || !value.trim())) {
751
+ throw new Error(`思考档位「${key}」的值必须是非空字符串或 null`);
752
+ }
753
+ }
754
+ return readThinkingLevelMap(raw) ?? {};
755
+ }
700
756
  /**
701
757
  * Checks what the form collected and returns it in the shape the registry stores.
702
758
  *
@@ -746,15 +802,23 @@ export function validateProvider(input) {
746
802
  const maxTokens = typeof model.maxTokens === "number" ? Math.round(model.maxTokens) : undefined;
747
803
  if (maxTokens !== undefined && (!Number.isFinite(maxTokens) || maxTokens <= 0))
748
804
  throw new Error("最大输出 token 必须是一个正数");
805
+ // THE THINKING MAP IS CHECKED RATHER THAN TRUSTED, because it goes straight into Pi's file. A
806
+ // key Pi does not know, or a value that is neither a string nor `null`, is refused here - the
807
+ // same way an empty `baseUrl` is refused, because Pi rejects the WHOLE file over one bad field.
808
+ const thinkingLevelMap = checkedThinkingLevelMap(model.thinkingLevelMap);
749
809
  return {
750
810
  id: modelId,
751
811
  ...(modelName ? { name: modelName } : {}),
752
- ...(model.reasoning === true ? { reasoning: true } : {}),
812
+ // BOTH WORDS ARE KEPT. A form that says the model does not think says it, and a form that
813
+ // says nothing says nothing - and the difference is the difference between "this model has
814
+ // its thinking switched off" and "nobody ever said".
815
+ ...(typeof model.reasoning === "boolean" ? { reasoning: model.reasoning } : {}),
753
816
  ...(model.imageInput === true ? { imageInput: true } : {}),
754
817
  ...(contextWindow === undefined ? {} : { contextWindow }),
755
818
  ...(maxTokens === undefined ? {} : { maxTokens }),
756
819
  ...(model.supportsDeveloperRole === false ? { supportsDeveloperRole: false } : {}),
757
820
  ...(model.supportsReasoningEffort === false ? { supportsReasoningEffort: false } : {}),
821
+ ...(thinkingLevelMap === undefined ? {} : { thinkingLevelMap }),
758
822
  };
759
823
  });
760
824
  return {
@@ -805,6 +869,11 @@ export async function fetchRemoteModels(input) {
805
869
  let lastError = "";
806
870
  let lastCause;
807
871
  let payload = null;
872
+ // THE URL THAT ANSWERED. A fetch follows redirects, so the endpoint that replied can be a
873
+ // different one from the address in the form - and it is the one that published whatever is
874
+ // being read. Deciding "is this the official endpoint?" from the address that was ASKED would
875
+ // call a redirect's destination the official one.
876
+ let answeredUrl = cleanBase;
808
877
  for (const candidate of candidates) {
809
878
  try {
810
879
  const response = await (providerProxyFetch(input.proxyEnv) ?? fetch)(candidate, {
@@ -816,6 +885,7 @@ export async function fetchRemoteModels(input) {
816
885
  continue;
817
886
  }
818
887
  payload = await response.json();
888
+ answeredUrl = response.url || candidate;
819
889
  if (payload)
820
890
  break;
821
891
  }
@@ -835,7 +905,7 @@ export async function fetchRemoteModels(input) {
835
905
  : undefined;
836
906
  throw new Error(`无法从远程服务获取模型列表 (${lastError || "请求超时或无法连接"}${cause ? `:${cause}` : ""})`);
837
907
  }
838
- return parseRemoteModels(payload);
908
+ return parseRemoteModels(payload, { baseUrl: answeredUrl, api: input.api });
839
909
  }
840
910
  /**
841
911
  * THE ANSWER, READ.
@@ -848,8 +918,13 @@ export async function fetchRemoteModels(input) {
848
918
  *
849
919
  * `fetchRemoteModels` is the transport; this is the reading. Keeping them apart means the reading can
850
920
  * be pinned exactly, and a slow machine can never turn a parsing question into a timeout.
921
+ *
922
+ * THE CONTEXT IS THE ENDPOINT THAT ANSWERED, and it matters for exactly one thing: the thinking
923
+ * levels. A level is only true of the endpoint that published it, so the rules that depend on the
924
+ * address need it - and the rules that do not (a model that declares its own levels) work without
925
+ * it, which is why the context is optional.
851
926
  */
852
- export function parseRemoteModels(payload) {
927
+ export function parseRemoteModels(payload, context) {
853
928
  const rawList = Array.isArray(payload)
854
929
  ? payload
855
930
  : Array.isArray(payload.data)
@@ -871,7 +946,20 @@ export function parseRemoteModels(payload) {
871
946
  continue;
872
947
  seen.add(id);
873
948
  const lower = id.toLowerCase();
874
- const reasoning = /r1|reason|o1|o3|thinking|qwq|deepseek-r1/i.test(lower);
949
+ // THE THINKING LEVELS ARE READ FIRST, because they are part of the answer about the model.
950
+ const thinkingLevelMap = discoverThinkingLevels(rec, { baseUrl: context?.baseUrl ?? "", api: context?.api });
951
+ // THE PROVIDER'S OWN WORD WINS. A payload that says `reasoning: false` says the model does
952
+ // not think, and neither the model's NAME nor the levels it published may overrule that: a
953
+ // level that is switched off is a level that does nothing, and switching it on behind the
954
+ // provider's back would be writing a fact the provider did not give.
955
+ //
956
+ // When the payload says nothing about it, a published map is a fact about the model - Pi
957
+ // offers ONLY `off` for a model that does not reason, so levels on a "not a reasoning model"
958
+ // would be levels Pi never shows - and the NAME is still a reason for the models nobody
959
+ // described.
960
+ const reasoning = typeof rec.reasoning === "boolean"
961
+ ? rec.reasoning
962
+ : (Boolean(thinkingLevelMap) || /r1|reason|o1|o3|thinking|qwq|deepseek-r1/i.test(lower));
875
963
  const imageInput = /vision|vl|4o|gemini|claude-3|flash|pixtral/i.test(lower);
876
964
  // THE CATALOGUE IS ASKED BEFORE THE DEFAULT IS GUESSED. A model the provider did not describe
877
965
  // used to fall straight to the placeholder 128000/16384, and that stamp was later read back as
@@ -894,6 +982,7 @@ export function parseRemoteModels(payload) {
894
982
  imageInput,
895
983
  contextWindow,
896
984
  maxTokens,
985
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
897
986
  });
898
987
  }
899
988
  return discovered.sort((a, b) => a.id.localeCompare(b.id));
@@ -2865,8 +2865,22 @@ export class PiRpcRuntime {
2865
2865
  const pick = (model) => (model ? { provider: model.provider, modelId: model.modelId, label: model.label } : undefined);
2866
2866
  // Unknown levels do not invalidate the SDK model list or imply an external Pi.
2867
2867
  // Keep the catalog usable without spawning a process or borrowing another model's levels.
2868
+ //
2869
+ // THE MODEL IN FORCE IS PI'S ANSWER. With no selection the conversation runs on the model Pi
2870
+ // resolved for itself - not on the pair Pi's settings happen to name, which may be missing,
2871
+ // stale, or unauthenticated. Asking for THAT model's levels is what puts a real list on screen
2872
+ // instead of an empty one.
2868
2873
  const forModel = selection ?? reader.defaultModel;
2869
- const levelNames = (forModel ? await reader.thinkingLevelsFor(forModel) : undefined) ?? [];
2874
+ const thinking = forModel ? await reader.thinkingLevelsFor(forModel) : undefined;
2875
+ const levelNames = thinking?.levels ?? [];
2876
+ // THE DEFAULT MODEL, TAKEN FROM THE LIST RATHER THAN REBUILT. The list carries Pi's own fields
2877
+ // - the window, the output limit, whether the model reasons - and a pair rebuilt from a
2878
+ // provider and an id would carry none of them.
2879
+ const wanted = reader.defaultModel;
2880
+ const defaultOption = wanted
2881
+ ? models.find((model) => model.provider === wanted.provider && model.modelId === wanted.modelId)
2882
+ ?? describeModel({ provider: wanted.provider, id: wanted.modelId, name: wanted.modelId })
2883
+ : undefined;
2870
2884
  const value = {
2871
2885
  source: "pi",
2872
2886
  models,
@@ -2876,8 +2890,10 @@ export class PiRpcRuntime {
2876
2890
  // hardest kind of missing: Pi rejects a whole models.json over one bad field, so EVERY
2877
2891
  // custom provider disappears at once and the only explanation is somewhere else entirely.
2878
2892
  ...(reader.configError?.() ? { configError: reader.configError() } : {}),
2879
- defaultModel: pick(reader.defaultModel ? describeModel({ provider: reader.defaultModel.provider, id: reader.defaultModel.modelId, name: reader.defaultModel.modelId }) : undefined),
2880
- defaultThinkingLevel: reader.defaultThinkingLevel ?? levelNames[0],
2893
+ defaultModel: pick(defaultOption),
2894
+ // THE LEVEL IN FORCE, AS PI RESOLVED IT FOR THIS MODEL. It is already clamped to the level
2895
+ // list above, so the button on screen always names a level the model actually has.
2896
+ defaultThinkingLevel: thinking?.level ?? levelNames[0],
2881
2897
  fetchedAt: new Date().toISOString(),
2882
2898
  };
2883
2899
  return value;
@@ -0,0 +1,38 @@
1
+ import { type ThinkingLevelMap } from "../shared/thinking-levels.js";
2
+ /**
3
+ * WHICH THINKING LEVELS A MODEL REALLY OFFERS, and who is allowed to say.
4
+ *
5
+ * THE PROBLEM THIS SOLVES. A model that only does `low`/`medium`/`high` looks exactly like one that
6
+ * does everything, because Pi ENABLES the ordinary levels when nobody says otherwise. So the picker
7
+ * offers a level the provider does not have, the request carries a `reasoning_effort` the provider
8
+ * refuses, and the turn fails on a setting nobody chose.
9
+ *
10
+ * THE RULE THIS FILE ENFORCES. A level may only be written into a model when somebody SAID it, in
11
+ * a form that names the level. Three things do NOT count as saying it, and all three are refused
12
+ * here:
13
+ *
14
+ * 1. A model whose NAME looks like a reasoning model (`o3`, `deepseek-r1`, `thinking`).
15
+ * 2. A provider that only says it supports the PARAMETER (`supports_reasoning_effort: true`,
16
+ * `supported_parameters: ["reasoning_effort"]`). That says a field exists, not which values
17
+ * the model accepts.
18
+ * 3. `reasoning: true`, which says the model thinks, not how hard it can think.
19
+ *
20
+ * AND THE RULE ABOUT COPIES. A level belongs to ONE endpoint's answer about ONE model. A proxy that
21
+ * serves a model with the same name as somebody else's model does NOT get that model's levels, and
22
+ * an answer about one API is never carried over to another. That is why the only endpoint-specific
23
+ * rule below matches the OFFICIAL host exactly.
24
+ */
25
+ /** What the endpoint that answered is, so a rule can be about it and not about the model alone. */
26
+ export type ThinkingLevelContext = {
27
+ /** The endpoint, exactly as the person typed it. */
28
+ baseUrl: string;
29
+ /** The API that endpoint is spoken with. */
30
+ api?: string;
31
+ };
32
+ /**
33
+ * THE LEVELS A MODEL OFFERS, or `undefined` when nobody said.
34
+ *
35
+ * `undefined` is not "no levels" - it is "nobody said", and the caller keeps whatever behaviour it
36
+ * had. A model that nobody described keeps Pi's own defaults, exactly as before.
37
+ */
38
+ export declare function discoverThinkingLevels(entry: Record<string, unknown>, context: ThinkingLevelContext): ThinkingLevelMap | undefined;