@eduardo191labs/opencode-free-pi 0.5.6 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +64 -55
  2. package/dist/catalog/catalog.js +1 -21
  3. package/dist/catalog/live.d.ts +71 -0
  4. package/dist/catalog/live.js +301 -0
  5. package/dist/catalog/models.d.ts +13 -2
  6. package/dist/catalog/models.js +69 -21
  7. package/dist/catalog/registry.js +5 -15
  8. package/dist/catalog/v2.js +5 -7
  9. package/dist/constants.d.ts +24 -21
  10. package/dist/constants.js +24 -19
  11. package/dist/logging.js +2 -2
  12. package/dist/plugin.js +26 -2
  13. package/dist/session/events.js +2 -3
  14. package/dist/session/hooks.js +4 -12
  15. package/dist/state.d.ts +1 -15
  16. package/dist/state.js +0 -3
  17. package/dist/tools/vision-queue.d.ts +1 -1
  18. package/dist/tools/vision-queue.js +5 -5
  19. package/dist/tools/vision.js +24 -35
  20. package/dist/tools/web.js +39 -44
  21. package/dist/types.d.ts +5 -9
  22. package/dist/utils/data-dir.d.ts +3 -0
  23. package/dist/utils/data-dir.js +12 -0
  24. package/package.json +2 -2
  25. package/src/catalog/catalog.ts +0 -25
  26. package/src/catalog/live.ts +361 -0
  27. package/src/catalog/models.ts +92 -23
  28. package/src/catalog/registry.ts +6 -21
  29. package/src/catalog/v2.ts +5 -7
  30. package/src/constants.ts +24 -22
  31. package/src/logging.ts +2 -2
  32. package/src/plugin.ts +34 -2
  33. package/src/session/events.ts +6 -3
  34. package/src/session/hooks.ts +4 -18
  35. package/src/state.ts +0 -18
  36. package/src/tools/vision-queue.ts +5 -5
  37. package/src/tools/vision.ts +26 -38
  38. package/src/tools/web.ts +49 -59
  39. package/src/types.ts +5 -8
  40. package/src/utils/data-dir.ts +14 -0
  41. package/dist/session/cache.d.ts +0 -15
  42. package/dist/session/cache.js +0 -57
  43. package/dist/tools/spend-cache.d.ts +0 -15
  44. package/dist/tools/spend-cache.js +0 -64
  45. package/dist/utils/cache.d.ts +0 -7
  46. package/dist/utils/cache.js +0 -45
  47. package/src/session/cache.ts +0 -82
  48. package/src/tools/spend-cache.ts +0 -79
  49. package/src/utils/cache.ts +0 -49
@@ -0,0 +1,361 @@
1
+ /**
2
+ * Live limits and capabilities.
3
+ *
4
+ * free-pi's HTTP API never publishes per-model limits: `/client-version` only
5
+ * carries id/name/free/section/note/stats_id, `/me` carries the quota, and chat
6
+ * responses carry usage but no window. The gateway does enforce a real ceiling,
7
+ * so the plugin verifies the advertised window against the gateway itself and
8
+ * remembers what it learned. The measured value replaces the compiled default
9
+ * on the next start; a probe failure leaves the previous value untouched.
10
+ */
11
+
12
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
13
+ import { dirname } from "node:path";
14
+ import { resolveToken } from "../auth/token.js";
15
+ import {
16
+ CONTEXT_WINDOW,
17
+ VERIFY_LIMITS_TTL_MS,
18
+ } from "../constants.js";
19
+ import type { Deps } from "../deps.js";
20
+ import type { TokenUsageLike } from "../types.js";
21
+ import { dataPath } from "../utils/data-dir.js";
22
+ import { completionsBaseUrl } from "../utils/urls.js";
23
+
24
+ const FILE = "live-limits.json";
25
+ const WRITE_DEBOUNCE_MS = 2_000;
26
+ /** Verification stops shrinking here instead of advertising a useless window. */
27
+ const MIN_WINDOW = 32_768;
28
+ /** Hard stop for the upward search; `buildModels` never advertises more. */
29
+ const MAX_WINDOW = 1_000_000;
30
+ /** Keep headroom under the exact ceiling so a fresh turn never hits a 413. */
31
+ const WINDOW_SAFETY = 0.97;
32
+ /** Probe requests per verification, counting the initial confirmation. */
33
+ const MAX_PROBES = 6;
34
+ /** OpenCode budgets four characters per token; correct it after the first probe. */
35
+ const INITIAL_CHARS_PER_TOKEN = 4;
36
+
37
+ export type ModelObservation = {
38
+ /** Largest prompt the gateway accepted for this model. */
39
+ maxPromptTokens?: number;
40
+ /** Whether a real response carried reasoning tokens. */
41
+ reasoning?: boolean;
42
+ updatedAt: number;
43
+ };
44
+
45
+ export type LiveLimits = {
46
+ version: 1;
47
+ /** Window verified against the gateway, used for the next catalog build. */
48
+ window?: { tokens: number; verifiedAt: number; model?: string };
49
+ /** What real traffic showed for each model. */
50
+ models: Record<string, ModelObservation>;
51
+ };
52
+
53
+ let cached: LiveLimits | undefined;
54
+ let loaded = false;
55
+ let writeTimer: ReturnType<typeof setTimeout> | undefined;
56
+
57
+ function emptyLimits(): LiveLimits {
58
+ return { version: 1, models: {} };
59
+ }
60
+
61
+ function sanitize(value: unknown): LiveLimits {
62
+ if (!value || typeof value !== "object") return emptyLimits();
63
+ const limits = value as Partial<LiveLimits>;
64
+ const models: Record<string, ModelObservation> = {};
65
+ for (const [id, entry] of Object.entries(limits.models ?? {})) {
66
+ if (!entry || typeof entry !== "object") continue;
67
+ const observation: ModelObservation = {
68
+ updatedAt:
69
+ typeof entry.updatedAt === "number" ? entry.updatedAt : Date.now(),
70
+ };
71
+ if (Number.isFinite(entry.maxPromptTokens) && entry.maxPromptTokens! > 0) {
72
+ observation.maxPromptTokens = Math.floor(entry.maxPromptTokens!);
73
+ }
74
+ if (typeof entry.reasoning === "boolean") {
75
+ observation.reasoning = entry.reasoning;
76
+ }
77
+ models[id] = observation;
78
+ }
79
+ const window = limits.window;
80
+ return {
81
+ version: 1,
82
+ models,
83
+ ...(window &&
84
+ Number.isFinite(window.tokens) &&
85
+ window.tokens > 0 &&
86
+ Number.isFinite(window.verifiedAt)
87
+ ? {
88
+ window: {
89
+ tokens: Math.floor(window.tokens),
90
+ verifiedAt: window.verifiedAt,
91
+ ...(typeof window.model === "string" ? { model: window.model } : {}),
92
+ },
93
+ }
94
+ : {}),
95
+ };
96
+ }
97
+
98
+ /** Reads the persisted measurements once per process. Never throws. */
99
+ export async function loadLiveLimits(): Promise<LiveLimits> {
100
+ if (loaded && cached) return cached;
101
+ try {
102
+ cached = sanitize(JSON.parse(await readFile(dataPath(FILE), "utf8")));
103
+ } catch {
104
+ cached = emptyLimits();
105
+ }
106
+ loaded = true;
107
+ return cached;
108
+ }
109
+
110
+ /** The measurements loaded for this process. */
111
+ export function currentLiveLimits(): LiveLimits | undefined {
112
+ return cached;
113
+ }
114
+
115
+ async function persist(): Promise<void> {
116
+ if (!cached) return;
117
+ try {
118
+ const file = dataPath(FILE);
119
+ await mkdir(dirname(file), { recursive: true });
120
+ await writeFile(file, JSON.stringify(cached), "utf8");
121
+ } catch {
122
+ // Measurements are an optimization; failing to persist changes nothing.
123
+ }
124
+ }
125
+
126
+ function scheduleWrite(): void {
127
+ if (writeTimer) return;
128
+ writeTimer = setTimeout(() => {
129
+ writeTimer = undefined;
130
+ void persist();
131
+ }, WRITE_DEBOUNCE_MS);
132
+ writeTimer.unref?.();
133
+ }
134
+
135
+ function observation(modelID: string): ModelObservation {
136
+ const limits = (cached ??= emptyLimits());
137
+ limits.models[modelID] ??= { updatedAt: Date.now() };
138
+ return limits.models[modelID]!;
139
+ }
140
+
141
+ /**
142
+ * Folds a real step's usage into the model's record: the prompt size proves the
143
+ * gateway accepted at least that much context, and reasoning tokens prove the
144
+ * model really reasoned for this account.
145
+ */
146
+ export function noteStepTokens(
147
+ _deps: Deps,
148
+ modelID: string,
149
+ tokens: TokenUsageLike | undefined,
150
+ ): void {
151
+ if (!modelID || !tokens) return;
152
+ const prompt =
153
+ (tokens.input ?? 0) + (tokens.cache?.read ?? 0) + (tokens.cache?.write ?? 0);
154
+ const entry = observation(modelID);
155
+ let changed = false;
156
+ if (prompt > 0 && prompt >= (entry.maxPromptTokens ?? 0)) {
157
+ entry.maxPromptTokens = Math.floor(prompt);
158
+ changed = true;
159
+ }
160
+ if ((tokens.reasoning ?? 0) > 0 && entry.reasoning !== true) {
161
+ entry.reasoning = true;
162
+ changed = true;
163
+ }
164
+ if (!changed) return;
165
+ entry.updatedAt = Date.now();
166
+ scheduleWrite();
167
+ }
168
+
169
+ /** Whether the persisted window is old enough to verify again. */
170
+ export function shouldVerifyWindow(limits: LiveLimits | undefined): boolean {
171
+ const verifiedAt = limits?.window?.verifiedAt;
172
+ if (!verifiedAt) return true;
173
+ return Date.now() - verifiedAt > VERIFY_LIMITS_TTL_MS;
174
+ }
175
+
176
+ function filler(chars: number): string {
177
+ const unit =
178
+ "the quick brown fox jumps over the lazy dog while maintainers review the patch and debate naming ";
179
+ return unit.repeat(Math.ceil(chars / unit.length)).slice(0, chars);
180
+ }
181
+
182
+ type ProbeResult =
183
+ | { status: "ok"; promptTokens?: number }
184
+ | { status: "too_long" }
185
+ | { status: "failed" };
186
+
187
+ async function sendProbe(
188
+ deps: Deps,
189
+ modelID: string,
190
+ chars: number,
191
+ ): Promise<ProbeResult> {
192
+ const token = await resolveToken(deps).catch(() => undefined);
193
+ if (!token) return { status: "failed" };
194
+ const content = `${filler(chars)}\n\nIgnore the filler and reply with OK.`;
195
+ let response: Response;
196
+ try {
197
+ response = await fetch(`${completionsBaseUrl()}/chat/completions`, {
198
+ method: "POST",
199
+ headers: {
200
+ accept: "application/json",
201
+ "content-type": "application/json",
202
+ authorization: `Bearer ${token}`,
203
+ "x-client-version": deps.state.latestClientVersion,
204
+ "x-session-id": `free-pi-window-${Date.now().toString(36)}`,
205
+ "x-ad-context": "none",
206
+ },
207
+ body: JSON.stringify({
208
+ model: modelID,
209
+ messages: [{ role: "user", content }],
210
+ stream: false,
211
+ max_tokens: 256,
212
+ }),
213
+ signal: AbortSignal.timeout(180_000),
214
+ });
215
+ } catch {
216
+ return { status: "failed" };
217
+ }
218
+ if (response.status === 413 || response.status === 400) {
219
+ const body = await response.text().catch(() => "");
220
+ if (/context_too_long|too long|context_ceiling/i.test(body)) {
221
+ return { status: "too_long" };
222
+ }
223
+ return { status: "failed" };
224
+ }
225
+ if (!response.ok) return { status: "failed" };
226
+ const payload = (await response.json().catch(() => undefined)) as
227
+ | { usage?: { prompt_tokens?: number } }
228
+ | undefined;
229
+ const promptTokens = payload?.usage?.prompt_tokens;
230
+ return {
231
+ status: "ok",
232
+ ...(typeof promptTokens === "number" ? { promptTokens } : {}),
233
+ };
234
+ }
235
+
236
+ export type VerifyLimitsOptions = {
237
+ /** A free model to probe with; paid models would spend credits. */
238
+ model?: string;
239
+ /** Window to check. Defaults to the measured one, then the compiled one. */
240
+ window?: number;
241
+ };
242
+
243
+ /** One gateway answer used to settle the advertised window. */
244
+ export type ProbeSample = {
245
+ chars: number;
246
+ /** Prompt tokens the gateway reported for an accepted probe. */
247
+ tokens?: number;
248
+ tooLong: boolean;
249
+ };
250
+
251
+ /**
252
+ * Largest window the accepted probes prove, with headroom. Pure so the probe
253
+ * loop and the persisted value can be tested without a server.
254
+ */
255
+ export function settleWindow(
256
+ samples: readonly ProbeSample[],
257
+ ): number | undefined {
258
+ let best = 0;
259
+ for (const sample of samples) {
260
+ if (sample.tooLong) continue;
261
+ if (!Number.isFinite(sample.tokens) || (sample.tokens ?? 0) <= 0) continue;
262
+ if (sample.tokens! <= best) continue;
263
+ best = sample.tokens!;
264
+ }
265
+ if (best === 0) return undefined;
266
+ return Math.min(
267
+ MAX_WINDOW,
268
+ Math.max(MIN_WINDOW, Math.floor((best * WINDOW_SAFETY) / 1_000) * 1_000),
269
+ );
270
+ }
271
+
272
+ /**
273
+ * Checks the compiled window against the gateway and then grows past it while
274
+ * the gateway keeps accepting larger prompts. The start value is a floor, not a
275
+ * ceiling: the server has no endpoint for its real limit, and pinning sessions
276
+ * to the CLI's 200k wastes capacity the account can actually use. On rejection
277
+ * it binary-searches between the largest accepted prompt and the rejected one,
278
+ * so the next catalog build advertises the measured window. Returns the verified
279
+ * window, or `undefined` when nothing could be learned (the previous value is
280
+ * kept).
281
+ */
282
+ export async function verifyGatewayWindow(
283
+ deps: Deps,
284
+ options: VerifyLimitsOptions = {},
285
+ ): Promise<number | undefined> {
286
+ const modelID = options.model;
287
+ if (!modelID) return undefined;
288
+ const fallback =
289
+ options.window ?? cached?.window?.tokens ?? CONTEXT_WINDOW;
290
+ const samples: ProbeSample[] = [];
291
+ // Accepted prompt tokens; also the lower bound of the binary search.
292
+ let accepted = 0;
293
+ let charsPerToken = INITIAL_CHARS_PER_TOKEN;
294
+ let target = Math.max(MIN_WINDOW, Math.min(fallback, MAX_WINDOW));
295
+
296
+ for (let attempt = 0; attempt < MAX_PROBES; attempt += 1) {
297
+ const chars = Math.max(
298
+ MIN_WINDOW * charsPerToken,
299
+ Math.floor(target * charsPerToken * 0.99),
300
+ );
301
+ const result = await sendProbe(deps, modelID, chars);
302
+ if (result.status === "failed") {
303
+ // A network failure or a rejected body proves nothing; keep what the
304
+ // earlier probes already established.
305
+ if (samples.length === 0) return undefined;
306
+ break;
307
+ }
308
+ if (result.status === "too_long") {
309
+ samples.push({ chars, tooLong: true });
310
+ if (accepted === 0) {
311
+ // The compiled window itself is too large: step down as before.
312
+ target = Math.floor(target * 0.85);
313
+ if (target < MIN_WINDOW) return undefined;
314
+ continue;
315
+ }
316
+ const next = Math.floor((accepted + target) / 2);
317
+ if (next <= accepted) break;
318
+ target = next;
319
+ continue;
320
+ }
321
+
322
+ const tokens = result.promptTokens;
323
+ samples.push({
324
+ chars,
325
+ tooLong: false,
326
+ ...(tokens && tokens > 0 ? { tokens } : {}),
327
+ });
328
+ if (tokens && tokens > 0) {
329
+ accepted = tokens;
330
+ // Learn the real characters-per-token ratio for this prompt shape; the
331
+ // filler is prose, and four chars/token overshoots badly.
332
+ charsPerToken = chars / tokens;
333
+ } else {
334
+ accepted = Math.floor(chars / charsPerToken);
335
+ }
336
+ if (accepted >= MAX_WINDOW) break;
337
+ const next = Math.min(MAX_WINDOW, Math.floor(accepted * 1.2));
338
+ if (next <= accepted) break;
339
+ target = next;
340
+ }
341
+
342
+ const settled = settleWindow(samples);
343
+ if (!settled) return undefined;
344
+ // Keep the previous floor when growth probes only prove less: the CLI's 200k
345
+ // is already known to work, so a small upstream probe model must not shrink
346
+ // every session's window.
347
+ const verified = Math.max(settled, Math.min(fallback, CONTEXT_WINDOW));
348
+ const limits = (cached ??= emptyLimits());
349
+ limits.window = { tokens: verified, verifiedAt: Date.now(), model: modelID };
350
+ loaded = true;
351
+ await persist();
352
+ deps.log.info("free-pi verified the gateway context window", {
353
+ model: modelID,
354
+ window: verified,
355
+ compiled: fallback,
356
+ probes: samples.length,
357
+ acceptedTokens: accepted,
358
+ charsPerToken: Number(charsPerToken.toFixed(2)),
359
+ });
360
+ return verified;
361
+ }
@@ -1,11 +1,12 @@
1
1
  /** Turns the free-pi catalog and models.dev registry into model definitions. */
2
2
 
3
3
  import {
4
- COMPACT100_CONTEXT_WINDOW,
5
4
  CONTEXT_WINDOW,
6
5
  DEFAULT_REASONING_EFFORT,
7
6
  DEFAULT_THINKING_LEVELS,
7
+ MAX_CONTEXT_WINDOW,
8
8
  MAX_OUTPUT_TOKENS,
9
+ MAX_OUTPUT_TOKENS_CEILING,
9
10
  REASONING_EFFORTS,
10
11
  } from "../constants.js";
11
12
  import type {
@@ -18,6 +19,7 @@ import type {
18
19
  ReasoningOption,
19
20
  RegistryCandidate,
20
21
  } from "../types.js";
22
+ import type { LiveLimits } from "./live.js";
21
23
  import { positiveNumber } from "../utils/numbers.js";
22
24
  import { cleanText } from "../utils/text.js";
23
25
 
@@ -178,7 +180,8 @@ export function modelVariants(
178
180
  // The provider CLI registers every model with `reasoning: true` and an unset
179
181
  // `thinkingLevelMap`, so it offers these levels to every model. models.dev
180
182
  // lists fewer levels for some upstream models, but the gateway accepts the
181
- // CLI's set, and hiding levels only makes the picker disagree with the CLI.
183
+ // CLI's set (including `max`), and hiding levels only makes the picker
184
+ // disagree with the CLI.
182
185
  const variants: VariantMap = {};
183
186
  for (const level of DEFAULT_THINKING_LEVELS) {
184
187
  variants[level] = { reasoningEffort: level };
@@ -199,6 +202,26 @@ export function modelVariants(
199
202
  return variants;
200
203
  }
201
204
 
205
+ /**
206
+ * The levels the model actually exposes, so OpenCode's picker and the
207
+ * `reasoning_effort` values the plugin sends come from the same list. The
208
+ * gateway accepts every level for every model, so the CLI set always applies.
209
+ */
210
+ export function effectiveReasoningOptions(
211
+ options: ReasoningOption[] | undefined,
212
+ variants: VariantMap,
213
+ ): ReasoningOption[] {
214
+ const values = Object.keys(variants);
215
+ const declared = options?.find(
216
+ (option): option is Extract<ReasoningOption, { type: "effort" }> =>
217
+ option.type === "effort",
218
+ )?.values;
219
+ for (const value of declared ?? []) {
220
+ if (!values.includes(value)) values.push(value);
221
+ }
222
+ return values.length > 0 ? [{ type: "effort", values }] : [];
223
+ }
224
+
202
225
  export function isReasoningEffort(value: unknown): value is string {
203
226
  return (
204
227
  typeof value === "string" &&
@@ -226,14 +249,18 @@ export function preferredReasoningEffort(
226
249
  }
227
250
 
228
251
  export type BuildModelsOptions = {
229
- /** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
230
- compact100?: boolean;
231
252
  /**
232
253
  * Effort sent when the user has not picked a variant. `false` keeps the
233
254
  * gateway default. Defaults to `medium` because an unset effort makes the
234
255
  * free models answer before they reason.
235
256
  */
236
257
  reasoningEffort?: string | false;
258
+ /**
259
+ * Limits and capabilities observed from the live gateway. The verified
260
+ * window replaces the compiled one, and per-model observations prove what the
261
+ * server really accepted for this account.
262
+ */
263
+ live?: LiveLimits;
237
264
  };
238
265
 
239
266
  /**
@@ -291,6 +318,34 @@ export function filterAccessibleModels(
291
318
  });
292
319
  }
293
320
 
321
+ const KNOWN_INPUT_MODALITIES = new Set([
322
+ "text",
323
+ "image",
324
+ "audio",
325
+ "video",
326
+ "pdf",
327
+ ]);
328
+
329
+ /**
330
+ * Native modalities for the chat route. models.dev describes the upstream
331
+ * model, and the gateway forwards image parts to multimodal upstreams, so an
332
+ * image-capable model is advertised as such. Output is always text: free-pi has
333
+ * no image results on the chat route, and the plugin registers every model as
334
+ * zero-cost text output.
335
+ */
336
+ function modelModalities(
337
+ model: CatalogModel,
338
+ capability: ModelsDevModel | undefined,
339
+ ): { input: string[]; output: string[] } {
340
+ const declared = model.modalities?.input ?? capability?.modalities?.input;
341
+ const input = (declared ?? ["text"]).filter((value) =>
342
+ KNOWN_INPUT_MODALITIES.has(value),
343
+ );
344
+ if (input.length === 0) input.push("text");
345
+ if (!input.includes("text")) input.unshift("text");
346
+ return { input, output: ["text"] };
347
+ }
348
+
294
349
  export function buildModels(
295
350
  models: CatalogModel[],
296
351
  candidates: RegistryCandidate[] = [],
@@ -306,15 +361,19 @@ export function buildModels(
306
361
  const reasoning = model.reasoning ?? true;
307
362
  const reasoningOptions =
308
363
  model.reasoning_options ?? capability?.reasoning_options;
309
- // free-pi enforces a 200k input window and 32k output cap on every model,
310
- // regardless of what models.dev reports for the upstream provider. The
311
- // provider CLI registers exactly these limits, so clamp to them here too:
312
- // an advertised 1M window would let OpenCode grow a session past the
313
- // server's real ceiling and fail with `context_too_long` instead of
314
- // compacting.
315
- const contextCeiling = options.compact100
316
- ? COMPACT100_CONTEXT_WINDOW
317
- : CONTEXT_WINDOW;
364
+ // free-pi enforces a context window on every model regardless of what
365
+ // models.dev reports for the upstream provider. The provider CLI starts at
366
+ // 200k, but the gateway does not publish its ceiling: `verifyGatewayWindow`
367
+ // measures it (growing past 200k when the gateway accepts more) and the
368
+ // result is used here from the next start. Real steps also prove the gateway
369
+ // accepted at least their prompt size. A published catalog field still wins,
370
+ // but only inside that measured ceiling, so an advertised 1M window can
371
+ // never push a session past what the gateway takes.
372
+ const observed = options.live?.models[model.id]?.maxPromptTokens ?? 0;
373
+ const contextCeiling = Math.min(
374
+ MAX_CONTEXT_WINDOW,
375
+ Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed),
376
+ );
318
377
  const limitContext = Math.min(
319
378
  positiveNumber(
320
379
  model.context_window,
@@ -324,6 +383,9 @@ export function buildModels(
324
383
  ) ?? contextCeiling,
325
384
  contextCeiling,
326
385
  );
386
+ // Reasoning shares the output budget. When models.dev knows the upstream
387
+ // model emits more than the CLI's 32k, advertise that larger budget (up to a
388
+ // sane ceiling) instead of truncating the chain of thought.
327
389
  const limitOutput = Math.min(
328
390
  positiveNumber(
329
391
  model.max_tokens,
@@ -332,11 +394,18 @@ export function buildModels(
332
394
  model.limit?.output,
333
395
  capability?.limit?.output,
334
396
  ) ?? MAX_OUTPUT_TOKENS,
335
- MAX_OUTPUT_TOKENS,
397
+ MAX_OUTPUT_TOKENS_CEILING,
336
398
  );
337
399
  const defaultEffort = reasoning
338
400
  ? preferredReasoningEffort(reasoningOptions, options.reasoningEffort)
339
401
  : undefined;
402
+ const variants = reasoning
403
+ ? modelVariants(reasoningOptions, limitOutput)
404
+ : {};
405
+ const modalities = modelModalities(model, capability);
406
+ const declaredOptions = reasoning
407
+ ? effectiveReasoningOptions(reasoningOptions, variants)
408
+ : undefined;
340
409
  result[model.id] = {
341
410
  id: model.id,
342
411
  name: displayName(model),
@@ -346,22 +415,22 @@ export function buildModels(
346
415
  (model.section === "defense" ? "defense" : ""),
347
416
  release_date: model.release_date ?? capability?.release_date,
348
417
  reasoning,
349
- reasoning_options: reasoningOptions,
350
- variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
418
+ ...(declaredOptions && declaredOptions.length > 0
419
+ ? { reasoning_options: declaredOptions }
420
+ : {}),
421
+ variants,
351
422
  ...(defaultEffort ? { settings: { reasoningEffort: defaultEffort } } : {}),
352
423
  enabled: model.unavailable !== true,
353
424
  temperature: model.temperature ?? capability?.temperature ?? true,
354
425
  tool_call: model.tool_call ?? capability?.tool_call ?? true,
355
- attachment: model.attachment ?? capability?.attachment ?? false,
426
+ attachment:
427
+ model.attachment ??
428
+ capability?.attachment ??
429
+ modalities.input.includes("image"),
356
430
  interleaved: model.interleaved ?? capability?.interleaved,
357
431
  cost: modelCost(model, capability),
358
432
  limit: { context: limitContext, output: limitOutput },
359
- modalities: {
360
- input: model.modalities?.input ??
361
- capability?.modalities?.input ?? ["text"],
362
- output: model.modalities?.output ??
363
- capability?.modalities?.output ?? ["text"],
364
- },
433
+ modalities,
365
434
  status: model.unavailable ? "deprecated" : "active",
366
435
  };
367
436
  }
@@ -2,7 +2,6 @@
2
2
 
3
3
  import {
4
4
  REGISTRY_ATTEMPTS,
5
- REGISTRY_DISK_TTL_MS,
6
5
  REGISTRY_RETRY_MS,
7
6
  REGISTRY_TIMEOUT_MS,
8
7
  REGISTRY_TTL_MS,
@@ -10,11 +9,8 @@ import {
10
9
  import type { Deps } from "../deps.js";
11
10
  import type { ModelRegistry } from "../types.js";
12
11
  import { sleep } from "../utils/async.js";
13
- import { readCache, writeCache } from "../utils/cache.js";
14
12
  import { modelsRegistryUrl } from "../utils/urls.js";
15
13
 
16
- const CACHE_FILE = "models-dev.json";
17
-
18
14
  function isRegistry(value: unknown): value is ModelRegistry {
19
15
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
20
16
  }
@@ -66,7 +62,6 @@ export function refreshModelsRegistry(
66
62
  }
67
63
  state.cachedRegistry = registry;
68
64
  state.cachedRegistryAt = Date.now();
69
- void writeCache(CACHE_FILE, registry);
70
65
  return registry;
71
66
  } catch (error) {
72
67
  const cached = state.cachedRegistry;
@@ -98,24 +93,14 @@ export async function fetchModelsRegistry(
98
93
  }
99
94
 
100
95
  if (!state.cachedRegistry) {
101
- const disk = await readCache<ModelRegistry>(
102
- CACHE_FILE,
103
- REGISTRY_DISK_TTL_MS,
104
- );
105
- if (isRegistry(disk)) {
106
- state.cachedRegistry = disk;
107
- state.cachedRegistryAt = Date.now();
108
- // Serve the cached copy immediately and refresh it in the background.
109
- void refreshModelsRegistry(deps);
110
- return disk;
96
+ if (
97
+ state.registryAttemptAt &&
98
+ Date.now() - state.registryAttemptAt < REGISTRY_RETRY_MS
99
+ ) {
100
+ return state.cachedRegistry;
111
101
  }
112
- }
113
102
 
114
- if (
115
- state.registryAttemptAt &&
116
- Date.now() - state.registryAttemptAt < REGISTRY_RETRY_MS
117
- ) {
118
- return state.cachedRegistry;
103
+ return refreshModelsRegistry(deps);
119
104
  }
120
105
 
121
106
  return refreshModelsRegistry(deps);
package/src/catalog/v2.ts CHANGED
@@ -32,13 +32,11 @@ export function toV2Models(providerID: string, models: ModelMap): any[] {
32
32
  ...(model.family ? { family: model.family } : {}),
33
33
  capabilities: {
34
34
  tools: model.tool_call !== false,
35
- // The provider CLI registers every free-pi model as text-only and
36
- // handles images out of band with its vision and image tools. Sending
37
- // native image parts instead makes OpenCode inline every read image
38
- // (hundreds of KB each) into the request, which overflows the 200k
39
- // window and burns the daily allowance on image tokens, so keep the
40
- // advertised capability identical to the CLI.
41
- input: ["text"],
35
+ // models.dev tells us which upstream models accept images. free-pi's
36
+ // gateway forwards image parts, so advertise exactly those modalities.
37
+ // Text-only models keep using the `look_at_image` tool, which keeps
38
+ // screenshots out of the token stream and the daily allowance.
39
+ input: model.modalities?.input ?? ["text"],
42
40
  output: ["text"],
43
41
  ...(model.temperature === undefined
44
42
  ? {}