@eduardo191labs/opencode-free-pi 0.5.5 → 0.6.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.
Files changed (47) hide show
  1. package/README.md +50 -41
  2. package/dist/catalog/catalog.js +1 -21
  3. package/dist/catalog/live.d.ts +55 -0
  4. package/dist/catalog/live.js +229 -0
  5. package/dist/catalog/models.d.ts +7 -2
  6. package/dist/catalog/models.js +26 -36
  7. package/dist/catalog/registry.js +5 -15
  8. package/dist/constants.d.ts +22 -15
  9. package/dist/constants.js +32 -15
  10. package/dist/logging.js +2 -2
  11. package/dist/plugin.js +14 -2
  12. package/dist/session/events.js +2 -3
  13. package/dist/session/hooks.js +17 -10
  14. package/dist/state.d.ts +1 -15
  15. package/dist/state.js +0 -3
  16. package/dist/tools/vision-queue.d.ts +1 -1
  17. package/dist/tools/vision-queue.js +5 -5
  18. package/dist/tools/vision.js +24 -35
  19. package/dist/tools/web.js +39 -44
  20. package/dist/types.d.ts +5 -9
  21. package/dist/utils/data-dir.d.ts +3 -0
  22. package/dist/utils/data-dir.js +12 -0
  23. package/package.json +2 -2
  24. package/src/catalog/catalog.ts +0 -25
  25. package/src/catalog/live.ts +277 -0
  26. package/src/catalog/models.ts +34 -38
  27. package/src/catalog/registry.ts +6 -21
  28. package/src/constants.ts +34 -18
  29. package/src/logging.ts +2 -2
  30. package/src/plugin.ts +20 -2
  31. package/src/session/events.ts +6 -3
  32. package/src/session/hooks.ts +34 -17
  33. package/src/state.ts +0 -18
  34. package/src/tools/vision-queue.ts +5 -5
  35. package/src/tools/vision.ts +26 -38
  36. package/src/tools/web.ts +49 -59
  37. package/src/types.ts +5 -8
  38. package/src/utils/data-dir.ts +14 -0
  39. package/dist/session/cache.d.ts +0 -15
  40. package/dist/session/cache.js +0 -57
  41. package/dist/tools/spend-cache.d.ts +0 -15
  42. package/dist/tools/spend-cache.js +0 -64
  43. package/dist/utils/cache.d.ts +0 -7
  44. package/dist/utils/cache.js +0 -45
  45. package/src/session/cache.ts +0 -82
  46. package/src/tools/spend-cache.ts +0 -79
  47. package/src/utils/cache.ts +0 -49
package/dist/types.d.ts CHANGED
@@ -92,9 +92,6 @@ export type Catalog = {
92
92
  default_model?: string;
93
93
  notice?: string;
94
94
  models?: CatalogModel[];
95
- cost_experiment?: {
96
- arm?: string;
97
- };
98
95
  };
99
96
  /** Intermediate, SDK-agnostic model shape used while the catalog is built. */
100
97
  export type ModelDefinition = {
@@ -138,6 +135,11 @@ export type FreePiOptions = {
138
135
  * models plan before answering. Set `false` to keep the gateway default.
139
136
  */
140
137
  reasoningEffort?: string | false;
138
+ /**
139
+ * Verify the gateway's real context window once a week and reuse the measured
140
+ * value. Defaults to true; set `false` to stay on the compiled window.
141
+ */
142
+ liveLimits?: boolean;
141
143
  };
142
144
  export type MeResponse = {
143
145
  handle?: string;
@@ -247,12 +249,6 @@ export type TrackedModel = {
247
249
  providerID: string;
248
250
  modelID: string;
249
251
  };
250
- export type CacheMissState = {
251
- promptTokens: number;
252
- at: number;
253
- modelKey: string;
254
- reportedCache: boolean;
255
- };
256
252
  export type ToolStats = {
257
253
  meta: string[];
258
254
  metaBytes: number;
@@ -0,0 +1,3 @@
1
+ /** Per-user directory for the files the plugin keeps between runs. */
2
+ export declare function dataDir(): string;
3
+ export declare function dataPath(name: string): string;
@@ -0,0 +1,12 @@
1
+ /** Per-user directory for the files the plugin keeps between runs. */
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ export function dataDir() {
5
+ const configured = process.env.FREE_PI_DATA_DIR?.trim();
6
+ if (configured)
7
+ return configured;
8
+ return join(homedir(), ".cache", "opencode", "free-pi");
9
+ }
10
+ export function dataPath(name) {
11
+ return join(dataDir(), name);
12
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.5.5",
3
+ "version": "0.6.0",
4
4
  "description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,7 +24,7 @@
24
24
  "scripts": {
25
25
  "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json",
26
26
  "typecheck": "tsc -p tsconfig.json --noEmit",
27
- "test": "npm run build && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/spend.mjs && node test/tools.mjs",
27
+ "test": "npm run build && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/live.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/tools.mjs",
28
28
  "prepublishOnly": "npm run build",
29
29
  "postinstall": "node scripts/postinstall.mjs"
30
30
  },
@@ -2,18 +2,13 @@
2
2
 
3
3
  import { resolveToken } from "../auth/token.js";
4
4
  import {
5
- CATALOG_DISK_TTL_MS,
6
5
  CATALOG_TIMEOUT_MS,
7
6
  CATALOG_TTL_MS,
8
- COST_EXPERIMENT_HEADER,
9
7
  } from "../constants.js";
10
8
  import type { Deps } from "../deps.js";
11
9
  import type { Catalog } from "../types.js";
12
- import { readCache, writeCache } from "../utils/cache.js";
13
10
  import { resolveBaseUrl } from "../utils/urls.js";
14
11
 
15
- const CACHE_FILE = "catalog.json";
16
-
17
12
  function isCatalog(value: unknown): value is Catalog {
18
13
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
19
14
  }
@@ -30,11 +25,6 @@ function applyCatalog(deps: Deps, catalog: Catalog): Catalog {
30
25
  if (typeof catalog.latest === "string" && catalog.latest.length > 0) {
31
26
  state.latestClientVersion = catalog.latest;
32
27
  }
33
- const arm = catalog.cost_experiment?.arm;
34
- state.costExperimentArm =
35
- typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
36
- ? arm
37
- : undefined;
38
28
  if (
39
29
  typeof catalog.notice === "string" &&
40
30
  catalog.notice &&
@@ -54,12 +44,9 @@ export function refreshCatalog(deps: Deps): Promise<Catalog | undefined> {
54
44
  if (state.catalogPromise) return state.catalogPromise;
55
45
  const pending = (async () => {
56
46
  try {
57
- // The CLI asks for the catalog with its JWT and the cost-experiment
58
- // header; without both the server may omit `cost_experiment`.
59
47
  const token = await resolveToken(deps).catch(() => undefined);
60
48
  const headers: Record<string, string> = {
61
49
  accept: "application/json",
62
- [COST_EXPERIMENT_HEADER]: "1",
63
50
  };
64
51
  if (token) headers.authorization = `Bearer ${token}`;
65
52
  const response = await fetch(`${resolveBaseUrl()}/client-version`, {
@@ -72,7 +59,6 @@ export function refreshCatalog(deps: Deps): Promise<Catalog | undefined> {
72
59
  throw new Error("free-pi returned an unexpected catalog payload");
73
60
  }
74
61
  applyCatalog(deps, catalog);
75
- void writeCache(CACHE_FILE, catalog);
76
62
  return catalog;
77
63
  } catch (error) {
78
64
  const cached = state.cachedCatalog;
@@ -97,16 +83,5 @@ export async function fetchCatalog(deps: Deps): Promise<Catalog | undefined> {
97
83
  if (state.cachedCatalog && Date.now() - state.cachedCatalogAt < CATALOG_TTL_MS) {
98
84
  return state.cachedCatalog;
99
85
  }
100
-
101
- if (!state.cachedCatalog) {
102
- const disk = await readCache<Catalog>(CACHE_FILE, CATALOG_DISK_TTL_MS);
103
- if (isCatalog(disk)) {
104
- applyCatalog(deps, disk);
105
- // Serve the cached copy immediately and refresh it in the background.
106
- void refreshCatalog(deps);
107
- return disk;
108
- }
109
- }
110
-
111
86
  return refreshCatalog(deps);
112
87
  }
@@ -0,0 +1,277 @@
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
+
29
+ export type ModelObservation = {
30
+ /** Largest prompt the gateway accepted for this model. */
31
+ maxPromptTokens?: number;
32
+ /** Whether a real response carried reasoning tokens. */
33
+ reasoning?: boolean;
34
+ updatedAt: number;
35
+ };
36
+
37
+ export type LiveLimits = {
38
+ version: 1;
39
+ /** Window verified against the gateway, used for the next catalog build. */
40
+ window?: { tokens: number; verifiedAt: number; model?: string };
41
+ /** What real traffic showed for each model. */
42
+ models: Record<string, ModelObservation>;
43
+ };
44
+
45
+ let cached: LiveLimits | undefined;
46
+ let loaded = false;
47
+ let writeTimer: ReturnType<typeof setTimeout> | undefined;
48
+
49
+ function emptyLimits(): LiveLimits {
50
+ return { version: 1, models: {} };
51
+ }
52
+
53
+ function sanitize(value: unknown): LiveLimits {
54
+ if (!value || typeof value !== "object") return emptyLimits();
55
+ const limits = value as Partial<LiveLimits>;
56
+ const models: Record<string, ModelObservation> = {};
57
+ for (const [id, entry] of Object.entries(limits.models ?? {})) {
58
+ if (!entry || typeof entry !== "object") continue;
59
+ const observation: ModelObservation = {
60
+ updatedAt:
61
+ typeof entry.updatedAt === "number" ? entry.updatedAt : Date.now(),
62
+ };
63
+ if (Number.isFinite(entry.maxPromptTokens) && entry.maxPromptTokens! > 0) {
64
+ observation.maxPromptTokens = Math.floor(entry.maxPromptTokens!);
65
+ }
66
+ if (typeof entry.reasoning === "boolean") {
67
+ observation.reasoning = entry.reasoning;
68
+ }
69
+ models[id] = observation;
70
+ }
71
+ const window = limits.window;
72
+ return {
73
+ version: 1,
74
+ models,
75
+ ...(window &&
76
+ Number.isFinite(window.tokens) &&
77
+ window.tokens > 0 &&
78
+ Number.isFinite(window.verifiedAt)
79
+ ? {
80
+ window: {
81
+ tokens: Math.floor(window.tokens),
82
+ verifiedAt: window.verifiedAt,
83
+ ...(typeof window.model === "string" ? { model: window.model } : {}),
84
+ },
85
+ }
86
+ : {}),
87
+ };
88
+ }
89
+
90
+ /** Reads the persisted measurements once per process. Never throws. */
91
+ export async function loadLiveLimits(): Promise<LiveLimits> {
92
+ if (loaded && cached) return cached;
93
+ try {
94
+ cached = sanitize(JSON.parse(await readFile(dataPath(FILE), "utf8")));
95
+ } catch {
96
+ cached = emptyLimits();
97
+ }
98
+ loaded = true;
99
+ return cached;
100
+ }
101
+
102
+ /** The measurements loaded for this process. */
103
+ export function currentLiveLimits(): LiveLimits | undefined {
104
+ return cached;
105
+ }
106
+
107
+ async function persist(): Promise<void> {
108
+ if (!cached) return;
109
+ try {
110
+ const file = dataPath(FILE);
111
+ await mkdir(dirname(file), { recursive: true });
112
+ await writeFile(file, JSON.stringify(cached), "utf8");
113
+ } catch {
114
+ // Measurements are an optimization; failing to persist changes nothing.
115
+ }
116
+ }
117
+
118
+ function scheduleWrite(): void {
119
+ if (writeTimer) return;
120
+ writeTimer = setTimeout(() => {
121
+ writeTimer = undefined;
122
+ void persist();
123
+ }, WRITE_DEBOUNCE_MS);
124
+ writeTimer.unref?.();
125
+ }
126
+
127
+ function observation(modelID: string): ModelObservation {
128
+ const limits = (cached ??= emptyLimits());
129
+ limits.models[modelID] ??= { updatedAt: Date.now() };
130
+ return limits.models[modelID]!;
131
+ }
132
+
133
+ /**
134
+ * Folds a real step's usage into the model's record: the prompt size proves the
135
+ * gateway accepted at least that much context, and reasoning tokens prove the
136
+ * model really reasoned for this account.
137
+ */
138
+ export function noteStepTokens(
139
+ _deps: Deps,
140
+ modelID: string,
141
+ tokens: TokenUsageLike | undefined,
142
+ ): void {
143
+ if (!modelID || !tokens) return;
144
+ const prompt =
145
+ (tokens.input ?? 0) + (tokens.cache?.read ?? 0) + (tokens.cache?.write ?? 0);
146
+ const entry = observation(modelID);
147
+ let changed = false;
148
+ if (prompt > 0 && prompt >= (entry.maxPromptTokens ?? 0)) {
149
+ entry.maxPromptTokens = Math.floor(prompt);
150
+ changed = true;
151
+ }
152
+ if ((tokens.reasoning ?? 0) > 0 && entry.reasoning !== true) {
153
+ entry.reasoning = true;
154
+ changed = true;
155
+ }
156
+ if (!changed) return;
157
+ entry.updatedAt = Date.now();
158
+ scheduleWrite();
159
+ }
160
+
161
+ /** Whether the persisted window is old enough to verify again. */
162
+ export function shouldVerifyWindow(limits: LiveLimits | undefined): boolean {
163
+ const verifiedAt = limits?.window?.verifiedAt;
164
+ if (!verifiedAt) return true;
165
+ return Date.now() - verifiedAt > VERIFY_LIMITS_TTL_MS;
166
+ }
167
+
168
+ function filler(chars: number): string {
169
+ const unit =
170
+ "the quick brown fox jumps over the lazy dog while maintainers review the patch and debate naming ";
171
+ return unit.repeat(Math.ceil(chars / unit.length)).slice(0, chars);
172
+ }
173
+
174
+ type ProbeResult =
175
+ | { status: "ok"; promptTokens?: number }
176
+ | { status: "too_long" }
177
+ | { status: "failed" };
178
+
179
+ async function sendProbe(
180
+ deps: Deps,
181
+ modelID: string,
182
+ chars: number,
183
+ ): Promise<ProbeResult> {
184
+ const token = await resolveToken(deps).catch(() => undefined);
185
+ if (!token) return { status: "failed" };
186
+ const content = `${filler(chars)}\n\nIgnore the filler and reply with OK.`;
187
+ let response: Response;
188
+ try {
189
+ response = await fetch(`${completionsBaseUrl()}/chat/completions`, {
190
+ method: "POST",
191
+ headers: {
192
+ accept: "application/json",
193
+ "content-type": "application/json",
194
+ authorization: `Bearer ${token}`,
195
+ "x-client-version": deps.state.latestClientVersion,
196
+ "x-session-id": `free-pi-window-${Date.now().toString(36)}`,
197
+ "x-ad-context": "none",
198
+ },
199
+ body: JSON.stringify({
200
+ model: modelID,
201
+ messages: [{ role: "user", content }],
202
+ stream: false,
203
+ max_tokens: 256,
204
+ }),
205
+ signal: AbortSignal.timeout(180_000),
206
+ });
207
+ } catch {
208
+ return { status: "failed" };
209
+ }
210
+ if (response.status === 413 || response.status === 400) {
211
+ const body = await response.text().catch(() => "");
212
+ if (/context_too_long|too long|context_ceiling/i.test(body)) {
213
+ return { status: "too_long" };
214
+ }
215
+ return { status: "failed" };
216
+ }
217
+ if (!response.ok) return { status: "failed" };
218
+ const payload = (await response.json().catch(() => undefined)) as
219
+ | { usage?: { prompt_tokens?: number } }
220
+ | undefined;
221
+ const promptTokens = payload?.usage?.prompt_tokens;
222
+ return {
223
+ status: "ok",
224
+ ...(typeof promptTokens === "number" ? { promptTokens } : {}),
225
+ };
226
+ }
227
+
228
+ export type VerifyLimitsOptions = {
229
+ /** A free model to probe with; paid models would spend credits. */
230
+ model?: string;
231
+ /** Window to check. Defaults to the compiled one. */
232
+ window?: number;
233
+ };
234
+
235
+ /**
236
+ * Checks the compiled window against the gateway by sending the largest prompt
237
+ * that window allows. On rejection it steps down until the gateway accepts, so
238
+ * the next catalog build advertises what the server really takes. Returns the
239
+ * verified window, or `undefined` when nothing could be learned.
240
+ */
241
+ export async function verifyGatewayWindow(
242
+ deps: Deps,
243
+ options: VerifyLimitsOptions = {},
244
+ ): Promise<number | undefined> {
245
+ const modelID = options.model;
246
+ if (!modelID) return undefined;
247
+ const window = options.window ?? CONTEXT_WINDOW;
248
+ // OpenCode budgets a token as ~4 characters. The gateway rejects by its own
249
+ // prompt size, so aim just under what the window allows in characters; the
250
+ // reported prompt_tokens are logged for comparison but do not decide the
251
+ // result.
252
+ const targetChars = Math.max(MIN_WINDOW * 4, Math.floor(window * 4 * 0.99));
253
+ for (const factor of [1, 0.85, 0.7, 0.55]) {
254
+ const chars = Math.floor(targetChars * factor);
255
+ if (chars < MIN_WINDOW) break;
256
+ const result = await sendProbe(deps, modelID, chars);
257
+ if (result.status === "failed") return undefined;
258
+ if (result.status === "too_long") continue;
259
+ // Passing the full target confirms the compiled window. After a rejection,
260
+ // only the reduced target is proven, so advertise that instead.
261
+ const verified =
262
+ factor === 1 ? window : Math.max(MIN_WINDOW, Math.floor(window * factor));
263
+ const limits = (cached ??= emptyLimits());
264
+ limits.window = { tokens: verified, verifiedAt: Date.now(), model: modelID };
265
+ loaded = true;
266
+ await persist();
267
+ deps.log.info("free-pi verified the gateway context window", {
268
+ model: modelID,
269
+ window: verified,
270
+ compiled: window,
271
+ probedChars: chars,
272
+ probedTokens: result.promptTokens,
273
+ });
274
+ return verified;
275
+ }
276
+ return undefined;
277
+ }
@@ -1,7 +1,6 @@
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,
@@ -18,6 +17,7 @@ import type {
18
17
  ReasoningOption,
19
18
  RegistryCandidate,
20
19
  } from "../types.js";
20
+ import type { LiveLimits } from "./live.js";
21
21
  import { positiveNumber } from "../utils/numbers.js";
22
22
  import { cleanText } from "../utils/text.js";
23
23
 
@@ -175,15 +175,15 @@ export function modelVariants(
175
175
  options: ReasoningOption[] | undefined,
176
176
  _outputLimit: number,
177
177
  ): VariantMap {
178
+ // The provider CLI registers every model with `reasoning: true` and an unset
179
+ // `thinkingLevelMap`, so it offers these levels to every model. models.dev
180
+ // 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.
178
182
  const variants: VariantMap = {};
179
- // The provider CLI offers these levels to every reasoning model because its
180
- // `thinkingLevelMap` is unset; `xhigh` and `max` stay opt-in.
181
- if (!options || options.length === 0) {
182
- for (const level of DEFAULT_THINKING_LEVELS) {
183
- variants[level] = { reasoningEffort: level };
184
- }
185
- return variants;
183
+ for (const level of DEFAULT_THINKING_LEVELS) {
184
+ variants[level] = { reasoningEffort: level };
186
185
  }
186
+ if (!options || options.length === 0) return variants;
187
187
  const effort = options.find(
188
188
  (option): option is Extract<ReasoningOption, { type: "effort" }> =>
189
189
  option.type === "effort",
@@ -192,11 +192,6 @@ export function modelVariants(
192
192
  for (const value of effort.values) {
193
193
  variants[value] = { reasoningEffort: value };
194
194
  }
195
- return variants;
196
- }
197
- if (options.some((option) => option.type === "toggle")) {
198
- variants.none = { reasoningEffort: "none" };
199
- variants.high = { reasoningEffort: "high" };
200
195
  }
201
196
  if (options.some((option) => option.type === "budget_tokens")) {
202
197
  budgetVariants(variants);
@@ -223,31 +218,26 @@ export function preferredReasoningEffort(
223
218
  ): string | undefined {
224
219
  if (configured === false) return undefined;
225
220
  if (configured) return configured;
226
- if (!options || options.length === 0) return DEFAULT_REASONING_EFFORT;
227
- const effort = options.find(
228
- (option): option is Extract<ReasoningOption, { type: "effort" }> =>
229
- option.type === "effort",
230
- );
231
- if (effort) {
232
- if (effort.values.includes(DEFAULT_REASONING_EFFORT))
233
- return DEFAULT_REASONING_EFFORT;
234
- if (effort.values.includes("high")) return "high";
235
- return effort.values[effort.values.length - 1];
236
- }
237
- if (options.some((option) => option.type === "toggle")) return "high";
238
- if (options.some((option) => option.type === "budget_tokens")) return "high";
221
+ // The provider CLI's levels are the source of truth: models.dev often lists
222
+ // only a subset, but the gateway accepts the CLI set. `medium` is the sane
223
+ // middle ground between the CLI's off default and burning tokens on `high`.
224
+ if (options?.some((option) => option.type === "budget_tokens")) return "high";
239
225
  return DEFAULT_REASONING_EFFORT;
240
226
  }
241
227
 
242
228
  export type BuildModelsOptions = {
243
- /** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
244
- compact100?: boolean;
245
229
  /**
246
230
  * Effort sent when the user has not picked a variant. `false` keeps the
247
231
  * gateway default. Defaults to `medium` because an unset effort makes the
248
232
  * free models answer before they reason.
249
233
  */
250
234
  reasoningEffort?: string | false;
235
+ /**
236
+ * Limits and capabilities observed from the live gateway. The verified
237
+ * window replaces the compiled one, and per-model observations prove what the
238
+ * server really accepted for this account.
239
+ */
240
+ live?: LiveLimits;
251
241
  };
252
242
 
253
243
  /**
@@ -314,18 +304,24 @@ export function buildModels(
314
304
  for (const model of models) {
315
305
  if (!model.id) continue;
316
306
  const capability = modelCapability(model, candidates);
317
- const reasoning = model.reasoning ?? capability?.reasoning ?? true;
307
+ // The provider CLI registers every model as `reasoning: true`; models.dev
308
+ // sometimes omits or disagrees for the upstream alias. Trust the catalog's
309
+ // explicit answer, otherwise keep reasoning on like the CLI does.
310
+ const reasoning = model.reasoning ?? true;
318
311
  const reasoningOptions =
319
312
  model.reasoning_options ?? capability?.reasoning_options;
320
- // free-pi enforces a 200k input window and 32k output cap on every model,
321
- // regardless of what models.dev reports for the upstream provider. The
322
- // provider CLI registers exactly these limits, so clamp to them here too:
323
- // an advertised 1M window would let OpenCode grow a session past the
324
- // server's real ceiling and fail with `context_too_long` instead of
325
- // compacting.
326
- const contextCeiling = options.compact100
327
- ? COMPACT100_CONTEXT_WINDOW
328
- : CONTEXT_WINDOW;
313
+ // free-pi enforces a context window on every model regardless of what
314
+ // models.dev reports for the upstream provider. The provider CLI starts at
315
+ // 200k, but the gateway does not publish its ceiling: `verifyGatewayWindow`
316
+ // measures it and the result is used here from the next start. Real steps
317
+ // also prove the gateway accepted at least their prompt size. A published
318
+ // catalog field still wins, but only inside that measured ceiling, so an
319
+ // advertised 1M window can never push a session past what the gateway takes.
320
+ const observed = options.live?.models[model.id]?.maxPromptTokens ?? 0;
321
+ const contextCeiling = Math.min(
322
+ 1_000_000,
323
+ Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed),
324
+ );
329
325
  const limitContext = Math.min(
330
326
  positiveNumber(
331
327
  model.context_window,
@@ -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);