@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/README.md CHANGED
@@ -98,12 +98,34 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
98
98
  - **Pensamiento por defecto**: el plugin pide `reasoning_effort: "medium"`
99
99
  cuando el modelo no trae variante elegida. Dejarlo sin definir hacía que los
100
100
  modelos gratuitos respondieran con prisa, gastando apenas unas decenas de
101
- tokens de razonamiento incluso en tareas que requieren planificar. Si el
102
- catálogo del modelo solo anuncia `low`/`high`, se usa `high`. El selector
103
- sigue ofreciendo `none`, `minimal`, `low`, `medium` y `high`, y la opción
104
- `reasoningEffort: false` del plugin recupera el comportamiento anterior (nivel
105
- del servidor). No se anuncian `thinking_budget` ni `thinking`, porque la ruta
106
- `openai-compatible` de OpenCode los descarta.
101
+ tokens de razonamiento incluso en tareas que requieren planificar. El
102
+ selector ofrece siempre `none`, `minimal`, `low`, `medium` y `high`, igual
103
+ que los niveles del CLI, y añade `max` cuando el catálogo lo declara; los
104
+ modelos de presupuesto usan `high`. La opción `reasoningEffort: false` del
105
+ plugin recupera el nivel del servidor. No se anuncian `thinking_budget` ni
106
+ `thinking`, porque la ruta `openai-compatible` de OpenCode los descarta.
107
+ - **Capacidades iguales al CLI**: todos los modelos se registran con
108
+ razonamiento activo, entrada solo de texto, coste cero y 32k de salida. La
109
+ ventana arranca en los 200k del CLI, pero el plugin la comprueba contra el
110
+ gateway cada 7 días con un modelo gratuito y usa la medida real. No se fuerza
111
+ temperatura ni `top_p`: la petición real no los incluye, así que el gateway
112
+ aplica su propio valor. El prompt se envía con rol `system`, no `developer`.
113
+ - **Límites medidos, no inventados**: `/client-version` solo devuelve id,
114
+ nombre, `free`, `section`, `note`, `stats_id` y `usage_x`; no hay endpoint de
115
+ capacidades ni de ventana. El plugin no se queda en constantes: mide la
116
+ ventana real del gateway, guarda el resultado en `live-limits.json` y anota en
117
+ cada paso los tokens de prompt y de razonamiento que el servidor confirma.
118
+ `liveLimits: false` desactiva la comprobación y deja la ventana compilada.
119
+ - **Reglas de trabajo en el prompt**: cada petición principal de free-pi añade
120
+ un bloque corto al system prompt con lo que los modelos gratuitos suelen
121
+ omitir: leer antes de editar, ejecutar las comprobaciones de verdad, no
122
+ afirmar que algo pasó si no se ejecutó, reutilizar las decisiones y rutas ya
123
+ establecidas en la conversación y no fingir que se compactó el contexto.
124
+ - **Compactación con instrucciones**: el resumen de compactación recibe además
125
+ un bloque que le pide conservar requisitos sin resolver, decisiones y sus
126
+ motivos, rutas y símbolos exactos, comandos con su resultado, errores y
127
+ trabajo pendiente. Sin eso, los modelos gratuitos producían resúmenes
128
+ demasiado escuetos para continuar la tarea.
107
129
  - **Solo modelos utilizables**: al arrancar se consulta `/me` y el selector
108
130
  `/model` incluye únicamente lo que la cuenta puede usar: los modelos
109
131
  `free: true` siempre, los de pago mientras queden créditos de la cuota o
@@ -113,9 +135,6 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
113
135
  free-pi. El CLI nunca los hace y cada ping gastaría créditos y anuncios.
114
136
  - **Timeouts del CLI**: 5 minutos para las cabeceras y para cada trozo de la
115
137
  respuesta, los mismos valores que `httpIdleTimeoutMs` de pi.
116
- - **Avisos de cache miss opcionales**: con `FREE_PI_CACHE_MISS_NOTICES=1` el
117
- plugin registra en el log los turnos que vuelven a facturar más de 20k
118
- tokens de prompt, usando la misma fórmula que `cache-stats` de pi.
119
138
  - Anuncios e impresiones asociados al turno correcto.
120
139
  - Cada agente y subagente usa su propio `x-session-id`, `x-turn-id` y contexto
121
140
  de anuncios; nunca reutiliza los del agente principal.
@@ -152,7 +171,7 @@ herramienta `look_at_image` con una ruta y una pregunta concreta. El plugin:
152
171
  - Envía la imagen a `/tools/vision` y devuelve la respuesta del modelo de
153
172
  visión como texto.
154
173
  - Serializa las preguntas entre sesiones y procesos de OpenCode mediante un
155
- bloqueo en la caché del plugin. Si el servidor responde `rate_limited` porque
174
+ bloqueo en el directorio de datos del plugin. Si el servidor responde `rate_limited` porque
156
175
  otra sesión o el CLI está consultando una imagen, reintenta automáticamente
157
176
  respetando `Retry-After` en vez de hacer fallar el turno.
158
177
 
@@ -186,15 +205,8 @@ no pueda escribir fuera de `images/`.
186
205
  códigos `daily_cap`, `rolling_cap`, `rate_limited`, `not_found`,
187
206
  `not_configured`, `upstream_error` y los de invitado se traducen al mismo texto
188
207
  que el CLI, para que el agente sepa cuándo no debe reintentar. Igual que
189
- `look_at_image`, cada llamada consume allowance.
190
-
191
- Las tres herramientas que gastan cuota (`web_search`, `docs_lookup` y
192
- `look_at_image`) comparten una caché de respuestas de 30 minutos: si el modelo,
193
- un subagente o un reintento piden exactamente lo mismo, se reutiliza la primera
194
- respuesta y no se vuelve a cobrar. Las llamadas idénticas en paralelo comparten
195
- una sola petición, y los errores nunca se cachean para que el siguiente intento
196
- vea el estado real del servidor. La respuesta cacheada lo indica y no incluye
197
- `cost_usd`.
208
+ `look_at_image`, cada llamada consume allowance y se ejecuta tal cual: el plugin
209
+ no reutiliza respuestas ni oculta llamadas repetidas.
198
210
 
199
211
  `free_pi_usage` consulta `/me/stats` y resume el tier, los créditos restantes
200
212
  con su hora de recarga en ET, los créditos premium o de referidos y los tokens
@@ -256,15 +268,13 @@ permisos también siguen siendo los de OpenCode; free-pi no los reemplaza.
256
268
 
257
269
  El plugin replica las cabeceras del plugin V1 de free-pi:
258
270
 
259
- - **Modelo**: `authorization`, `x-session-id`, `x-client-version`,
260
- `x-turn-id` y `x-freepi-cost-exp` (cuando el catálogo asigna un experimento).
261
- Las sesiones hijas añaden `x-freepi-subagent: 1`.
271
+ - **Modelo**: `authorization`, `x-session-id`, `x-client-version` y
272
+ `x-turn-id`. Las sesiones hijas añaden `x-freepi-subagent: 1`.
262
273
  - **Resultados de herramientas**: `x-freepi-tool-meta` (duración, código de
263
274
  salida y truncado de las últimas llamadas), `x-freepi-tool-errors` (IDs de
264
275
  herramientas fallidas) y `x-freepi-compacted` (mensajes plegados por la
265
276
  última compactación, en la petición siguiente).
266
- - **Catálogo** (`/client-version`): `authorization` y `x-freepi-cost-exp: 1`,
267
- igual que el CLI, para que el servidor pueda asignar el experimento de coste.
277
+ - **Catálogo** (`/client-version`): `authorization`.
268
278
  - **Anuncios** (`/ads/next`): `authorization`, `x-session-id`,
269
279
  `x-client-version`, `x-turn-id`, `x-ad-trigger`, `x-client-os`,
270
280
  `x-client-arch`, `x-client-timezone`, `x-client-locale` y `x-ad-context`.
@@ -303,10 +313,7 @@ sin fallar ni mostrar reintentos. Además libera el id anterior, y si el replay
303
313
  puede completarse el hook de reintento rota el id para los siguientes pasos. Un
304
314
  turno que se aborta o falla a mitad de stream marca su `x-session-id` como sucio:
305
315
  la siguiente petición arranca directamente con un id nuevo y libera el anterior,
306
- de modo que la sesión continúa sin interrupciones y sin pasar por un reintento. Si
307
- el catálogo asigna el experimento `compact100`, el plugin baja la ventana a 117
308
- 647 tokens para que OpenCode compacte al llegar a 100k, que es el mismo umbral
309
- que consigue `reserveTokens: 100000` en el CLI.
316
+ de modo que la sesión continúa sin interrupciones y sin pasar por un reintento.
310
317
 
311
318
  ## Rutas por plataforma
312
319
 
@@ -329,24 +336,25 @@ Si `XDG_CONFIG_HOME` o `OPENCODE_CONFIG_DIR` están definidos, se respetan.
329
336
  | `FREEPI_DEVICE_LOGIN=1` | Forzar inicio de sesión por dispositivo. |
330
337
  | `FREEPI_CONFIGURE=1` | Registrar el paquete en `opencode.json` al instalar. |
331
338
  | `OPENCODE_CONFIG_DIR` | Directorio de configuración de OpenCode. |
332
- | `FREE_PI_CACHE_DIR` | Directorio de caché del plugin. |
339
+ | `FREE_PI_DATA_DIR` | Directorio de datos del plugin. |
333
340
  | `FREE_PI_LOG_FILE` | Ruta alternativa del archivo de log del plugin. |
334
- | `FREE_PI_CACHE_MISS_NOTICES=1` | Registrar en el log los cache miss de más de 20k tokens. |
335
341
 
336
342
  No hay variables obligatorias.
337
343
 
338
- ## Caché y logs
344
+ ## Datos y logs
339
345
 
340
- El plugin guarda el catálogo de free-pi y el registro de models.dev en:
346
+ El catálogo y el registro de models.dev se piden en vivo en cada arranque: no
347
+ se guardan copias en disco ni se muestran datos de una ejecución anterior. El
348
+ plugin solo conserva en:
341
349
 
342
350
  ```text
343
- ~/.cache/opencode/free-pi/catalog.json
344
- ~/.cache/opencode/free-pi/models-dev.json
351
+ ~/.cache/opencode/free-pi/live-limits.json
345
352
  ```
346
353
 
347
- En Windows es `%USERPROFILE%\.cache\opencode\free-pi\`. El catálogo se reutiliza
348
- hasta 24 h y el registro hasta 7 días si la red falla; cuando la petición
349
- funciona, las copias se refrescan solas.
354
+ la ventana de contexto que midió contra el gateway y lo que cada paso real
355
+ demostró sobre el modelo. Esa medición se vuelve a comprobar cada 7 días.
356
+
357
+ En Windows es `%USERPROFILE%\.cache\opencode\free-pi\`.
350
358
 
351
359
  Los mensajes del plugin se escriben en la consola con el prefijo `[free-pi]` y
352
360
  también en:
@@ -416,16 +424,17 @@ src/
416
424
  auth/ OAuth, JWT, credenciales y conexión
417
425
  api/ cuota y reset de sesión
418
426
  ads/ contexto, turnos e impresiones
419
- catalog/ catálogo en vivo y registro models.dev
427
+ catalog/ catálogo en vivo, models.dev y límites medidos
420
428
  errors/ parseo, mensajes y reescritura de límites
421
429
  integration/ integración y métodos de inicio de sesión
422
430
  session/ hooks, eventos, seguimiento y uso
423
- utils/ helpers pequeños (incluye cache.ts)
431
+ utils/ helpers pequeños (directorio de datos y URLs)
424
432
  dist/ build ESM y tipos
425
433
  scripts/postinstall.mjs registro en opencode.json
426
434
  test/smoke.mjs prueba de humo del build
427
- test/registry.mjs caché y tolerancia a fallos de models.dev
428
- test/models.mjs capacidades, variantes, límites reales y costos
435
+ test/registry.mjs models.dev en vivo y tolerancia a fallos
436
+ test/models.mjs capacidades, variantes y límites
437
+ test/live.mjs ventana medida y observaciones del gateway
429
438
  test/hooks.mjs hooks de sesión, anuncios, cuota y compactación
430
439
  ```
431
440
 
@@ -1,9 +1,7 @@
1
1
  /** Fetches the live free-pi model catalog. */
2
2
  import { resolveToken } from "../auth/token.js";
3
- import { CATALOG_DISK_TTL_MS, CATALOG_TIMEOUT_MS, CATALOG_TTL_MS, COST_EXPERIMENT_HEADER, } from "../constants.js";
4
- import { readCache, writeCache } from "../utils/cache.js";
3
+ import { CATALOG_TIMEOUT_MS, CATALOG_TTL_MS, } from "../constants.js";
5
4
  import { resolveBaseUrl } from "../utils/urls.js";
6
- const CACHE_FILE = "catalog.json";
7
5
  function isCatalog(value) {
8
6
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
7
  }
@@ -18,11 +16,6 @@ function applyCatalog(deps, catalog) {
18
16
  if (typeof catalog.latest === "string" && catalog.latest.length > 0) {
19
17
  state.latestClientVersion = catalog.latest;
20
18
  }
21
- const arm = catalog.cost_experiment?.arm;
22
- state.costExperimentArm =
23
- typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
24
- ? arm
25
- : undefined;
26
19
  if (typeof catalog.notice === "string" &&
27
20
  catalog.notice &&
28
21
  catalog.notice !== state.lastCatalogNotice) {
@@ -40,12 +33,9 @@ export function refreshCatalog(deps) {
40
33
  return state.catalogPromise;
41
34
  const pending = (async () => {
42
35
  try {
43
- // The CLI asks for the catalog with its JWT and the cost-experiment
44
- // header; without both the server may omit `cost_experiment`.
45
36
  const token = await resolveToken(deps).catch(() => undefined);
46
37
  const headers = {
47
38
  accept: "application/json",
48
- [COST_EXPERIMENT_HEADER]: "1",
49
39
  };
50
40
  if (token)
51
41
  headers.authorization = `Bearer ${token}`;
@@ -60,7 +50,6 @@ export function refreshCatalog(deps) {
60
50
  throw new Error("free-pi returned an unexpected catalog payload");
61
51
  }
62
52
  applyCatalog(deps, catalog);
63
- void writeCache(CACHE_FILE, catalog);
64
53
  return catalog;
65
54
  }
66
55
  catch (error) {
@@ -83,14 +72,5 @@ export async function fetchCatalog(deps) {
83
72
  if (state.cachedCatalog && Date.now() - state.cachedCatalogAt < CATALOG_TTL_MS) {
84
73
  return state.cachedCatalog;
85
74
  }
86
- if (!state.cachedCatalog) {
87
- const disk = await readCache(CACHE_FILE, CATALOG_DISK_TTL_MS);
88
- if (isCatalog(disk)) {
89
- applyCatalog(deps, disk);
90
- // Serve the cached copy immediately and refresh it in the background.
91
- void refreshCatalog(deps);
92
- return disk;
93
- }
94
- }
95
75
  return refreshCatalog(deps);
96
76
  }
@@ -0,0 +1,55 @@
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
+ import type { Deps } from "../deps.js";
12
+ import type { TokenUsageLike } from "../types.js";
13
+ export type ModelObservation = {
14
+ /** Largest prompt the gateway accepted for this model. */
15
+ maxPromptTokens?: number;
16
+ /** Whether a real response carried reasoning tokens. */
17
+ reasoning?: boolean;
18
+ updatedAt: number;
19
+ };
20
+ export type LiveLimits = {
21
+ version: 1;
22
+ /** Window verified against the gateway, used for the next catalog build. */
23
+ window?: {
24
+ tokens: number;
25
+ verifiedAt: number;
26
+ model?: string;
27
+ };
28
+ /** What real traffic showed for each model. */
29
+ models: Record<string, ModelObservation>;
30
+ };
31
+ /** Reads the persisted measurements once per process. Never throws. */
32
+ export declare function loadLiveLimits(): Promise<LiveLimits>;
33
+ /** The measurements loaded for this process. */
34
+ export declare function currentLiveLimits(): LiveLimits | undefined;
35
+ /**
36
+ * Folds a real step's usage into the model's record: the prompt size proves the
37
+ * gateway accepted at least that much context, and reasoning tokens prove the
38
+ * model really reasoned for this account.
39
+ */
40
+ export declare function noteStepTokens(_deps: Deps, modelID: string, tokens: TokenUsageLike | undefined): void;
41
+ /** Whether the persisted window is old enough to verify again. */
42
+ export declare function shouldVerifyWindow(limits: LiveLimits | undefined): boolean;
43
+ export type VerifyLimitsOptions = {
44
+ /** A free model to probe with; paid models would spend credits. */
45
+ model?: string;
46
+ /** Window to check. Defaults to the compiled one. */
47
+ window?: number;
48
+ };
49
+ /**
50
+ * Checks the compiled window against the gateway by sending the largest prompt
51
+ * that window allows. On rejection it steps down until the gateway accepts, so
52
+ * the next catalog build advertises what the server really takes. Returns the
53
+ * verified window, or `undefined` when nothing could be learned.
54
+ */
55
+ export declare function verifyGatewayWindow(deps: Deps, options?: VerifyLimitsOptions): Promise<number | undefined>;
@@ -0,0 +1,229 @@
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
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
12
+ import { dirname } from "node:path";
13
+ import { resolveToken } from "../auth/token.js";
14
+ import { CONTEXT_WINDOW, VERIFY_LIMITS_TTL_MS, } from "../constants.js";
15
+ import { dataPath } from "../utils/data-dir.js";
16
+ import { completionsBaseUrl } from "../utils/urls.js";
17
+ const FILE = "live-limits.json";
18
+ const WRITE_DEBOUNCE_MS = 2_000;
19
+ /** Verification stops shrinking here instead of advertising a useless window. */
20
+ const MIN_WINDOW = 32_768;
21
+ let cached;
22
+ let loaded = false;
23
+ let writeTimer;
24
+ function emptyLimits() {
25
+ return { version: 1, models: {} };
26
+ }
27
+ function sanitize(value) {
28
+ if (!value || typeof value !== "object")
29
+ return emptyLimits();
30
+ const limits = value;
31
+ const models = {};
32
+ for (const [id, entry] of Object.entries(limits.models ?? {})) {
33
+ if (!entry || typeof entry !== "object")
34
+ continue;
35
+ const observation = {
36
+ updatedAt: typeof entry.updatedAt === "number" ? entry.updatedAt : Date.now(),
37
+ };
38
+ if (Number.isFinite(entry.maxPromptTokens) && entry.maxPromptTokens > 0) {
39
+ observation.maxPromptTokens = Math.floor(entry.maxPromptTokens);
40
+ }
41
+ if (typeof entry.reasoning === "boolean") {
42
+ observation.reasoning = entry.reasoning;
43
+ }
44
+ models[id] = observation;
45
+ }
46
+ const window = limits.window;
47
+ return {
48
+ version: 1,
49
+ models,
50
+ ...(window &&
51
+ Number.isFinite(window.tokens) &&
52
+ window.tokens > 0 &&
53
+ Number.isFinite(window.verifiedAt)
54
+ ? {
55
+ window: {
56
+ tokens: Math.floor(window.tokens),
57
+ verifiedAt: window.verifiedAt,
58
+ ...(typeof window.model === "string" ? { model: window.model } : {}),
59
+ },
60
+ }
61
+ : {}),
62
+ };
63
+ }
64
+ /** Reads the persisted measurements once per process. Never throws. */
65
+ export async function loadLiveLimits() {
66
+ if (loaded && cached)
67
+ return cached;
68
+ try {
69
+ cached = sanitize(JSON.parse(await readFile(dataPath(FILE), "utf8")));
70
+ }
71
+ catch {
72
+ cached = emptyLimits();
73
+ }
74
+ loaded = true;
75
+ return cached;
76
+ }
77
+ /** The measurements loaded for this process. */
78
+ export function currentLiveLimits() {
79
+ return cached;
80
+ }
81
+ async function persist() {
82
+ if (!cached)
83
+ return;
84
+ try {
85
+ const file = dataPath(FILE);
86
+ await mkdir(dirname(file), { recursive: true });
87
+ await writeFile(file, JSON.stringify(cached), "utf8");
88
+ }
89
+ catch {
90
+ // Measurements are an optimization; failing to persist changes nothing.
91
+ }
92
+ }
93
+ function scheduleWrite() {
94
+ if (writeTimer)
95
+ return;
96
+ writeTimer = setTimeout(() => {
97
+ writeTimer = undefined;
98
+ void persist();
99
+ }, WRITE_DEBOUNCE_MS);
100
+ writeTimer.unref?.();
101
+ }
102
+ function observation(modelID) {
103
+ const limits = (cached ??= emptyLimits());
104
+ limits.models[modelID] ??= { updatedAt: Date.now() };
105
+ return limits.models[modelID];
106
+ }
107
+ /**
108
+ * Folds a real step's usage into the model's record: the prompt size proves the
109
+ * gateway accepted at least that much context, and reasoning tokens prove the
110
+ * model really reasoned for this account.
111
+ */
112
+ export function noteStepTokens(_deps, modelID, tokens) {
113
+ if (!modelID || !tokens)
114
+ return;
115
+ const prompt = (tokens.input ?? 0) + (tokens.cache?.read ?? 0) + (tokens.cache?.write ?? 0);
116
+ const entry = observation(modelID);
117
+ let changed = false;
118
+ if (prompt > 0 && prompt >= (entry.maxPromptTokens ?? 0)) {
119
+ entry.maxPromptTokens = Math.floor(prompt);
120
+ changed = true;
121
+ }
122
+ if ((tokens.reasoning ?? 0) > 0 && entry.reasoning !== true) {
123
+ entry.reasoning = true;
124
+ changed = true;
125
+ }
126
+ if (!changed)
127
+ return;
128
+ entry.updatedAt = Date.now();
129
+ scheduleWrite();
130
+ }
131
+ /** Whether the persisted window is old enough to verify again. */
132
+ export function shouldVerifyWindow(limits) {
133
+ const verifiedAt = limits?.window?.verifiedAt;
134
+ if (!verifiedAt)
135
+ return true;
136
+ return Date.now() - verifiedAt > VERIFY_LIMITS_TTL_MS;
137
+ }
138
+ function filler(chars) {
139
+ const unit = "the quick brown fox jumps over the lazy dog while maintainers review the patch and debate naming ";
140
+ return unit.repeat(Math.ceil(chars / unit.length)).slice(0, chars);
141
+ }
142
+ async function sendProbe(deps, modelID, chars) {
143
+ const token = await resolveToken(deps).catch(() => undefined);
144
+ if (!token)
145
+ return { status: "failed" };
146
+ const content = `${filler(chars)}\n\nIgnore the filler and reply with OK.`;
147
+ let response;
148
+ try {
149
+ response = await fetch(`${completionsBaseUrl()}/chat/completions`, {
150
+ method: "POST",
151
+ headers: {
152
+ accept: "application/json",
153
+ "content-type": "application/json",
154
+ authorization: `Bearer ${token}`,
155
+ "x-client-version": deps.state.latestClientVersion,
156
+ "x-session-id": `free-pi-window-${Date.now().toString(36)}`,
157
+ "x-ad-context": "none",
158
+ },
159
+ body: JSON.stringify({
160
+ model: modelID,
161
+ messages: [{ role: "user", content }],
162
+ stream: false,
163
+ max_tokens: 256,
164
+ }),
165
+ signal: AbortSignal.timeout(180_000),
166
+ });
167
+ }
168
+ catch {
169
+ return { status: "failed" };
170
+ }
171
+ if (response.status === 413 || response.status === 400) {
172
+ const body = await response.text().catch(() => "");
173
+ if (/context_too_long|too long|context_ceiling/i.test(body)) {
174
+ return { status: "too_long" };
175
+ }
176
+ return { status: "failed" };
177
+ }
178
+ if (!response.ok)
179
+ return { status: "failed" };
180
+ const payload = (await response.json().catch(() => undefined));
181
+ const promptTokens = payload?.usage?.prompt_tokens;
182
+ return {
183
+ status: "ok",
184
+ ...(typeof promptTokens === "number" ? { promptTokens } : {}),
185
+ };
186
+ }
187
+ /**
188
+ * Checks the compiled window against the gateway by sending the largest prompt
189
+ * that window allows. On rejection it steps down until the gateway accepts, so
190
+ * the next catalog build advertises what the server really takes. Returns the
191
+ * verified window, or `undefined` when nothing could be learned.
192
+ */
193
+ export async function verifyGatewayWindow(deps, options = {}) {
194
+ const modelID = options.model;
195
+ if (!modelID)
196
+ return undefined;
197
+ const window = options.window ?? CONTEXT_WINDOW;
198
+ // OpenCode budgets a token as ~4 characters. The gateway rejects by its own
199
+ // prompt size, so aim just under what the window allows in characters; the
200
+ // reported prompt_tokens are logged for comparison but do not decide the
201
+ // result.
202
+ const targetChars = Math.max(MIN_WINDOW * 4, Math.floor(window * 4 * 0.99));
203
+ for (const factor of [1, 0.85, 0.7, 0.55]) {
204
+ const chars = Math.floor(targetChars * factor);
205
+ if (chars < MIN_WINDOW)
206
+ break;
207
+ const result = await sendProbe(deps, modelID, chars);
208
+ if (result.status === "failed")
209
+ return undefined;
210
+ if (result.status === "too_long")
211
+ continue;
212
+ // Passing the full target confirms the compiled window. After a rejection,
213
+ // only the reduced target is proven, so advertise that instead.
214
+ const verified = factor === 1 ? window : Math.max(MIN_WINDOW, Math.floor(window * factor));
215
+ const limits = (cached ??= emptyLimits());
216
+ limits.window = { tokens: verified, verifiedAt: Date.now(), model: modelID };
217
+ loaded = true;
218
+ await persist();
219
+ deps.log.info("free-pi verified the gateway context window", {
220
+ model: modelID,
221
+ window: verified,
222
+ compiled: window,
223
+ probedChars: chars,
224
+ probedTokens: result.promptTokens,
225
+ });
226
+ return verified;
227
+ }
228
+ return undefined;
229
+ }
@@ -1,5 +1,6 @@
1
1
  /** Turns the free-pi catalog and models.dev registry into model definitions. */
2
2
  import type { Catalog, CatalogModel, MeResponse, ModelDefinition, ModelRegistry, ModelsDevModel, ReasoningOption, RegistryCandidate } from "../types.js";
3
+ import type { LiveLimits } from "./live.js";
3
4
  export type VariantMap = Record<string, Record<string, unknown>>;
4
5
  export type ModelMap = Record<string, ModelDefinition>;
5
6
  export declare function usableModels(catalog: Catalog | undefined): CatalogModel[];
@@ -21,14 +22,18 @@ export declare function isReasoningEffort(value: unknown): value is string;
21
22
  */
22
23
  export declare function preferredReasoningEffort(options: ReasoningOption[] | undefined, configured?: string | false): string | undefined;
23
24
  export type BuildModelsOptions = {
24
- /** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
25
- compact100?: boolean;
26
25
  /**
27
26
  * Effort sent when the user has not picked a variant. `false` keeps the
28
27
  * gateway default. Defaults to `medium` because an unset effort makes the
29
28
  * free models answer before they reason.
30
29
  */
31
30
  reasoningEffort?: string | false;
31
+ /**
32
+ * Limits and capabilities observed from the live gateway. The verified
33
+ * window replaces the compiled one, and per-model observations prove what the
34
+ * server really accepted for this account.
35
+ */
36
+ live?: LiveLimits;
32
37
  };
33
38
  /**
34
39
  * What the signed-in account can actually use, derived from `GET /me`.
@@ -1,5 +1,5 @@
1
1
  /** Turns the free-pi catalog and models.dev registry into model definitions. */
2
- import { COMPACT100_CONTEXT_WINDOW, CONTEXT_WINDOW, DEFAULT_REASONING_EFFORT, DEFAULT_THINKING_LEVELS, MAX_OUTPUT_TOKENS, REASONING_EFFORTS, } from "../constants.js";
2
+ import { CONTEXT_WINDOW, DEFAULT_REASONING_EFFORT, DEFAULT_THINKING_LEVELS, MAX_OUTPUT_TOKENS, REASONING_EFFORTS, } from "../constants.js";
3
3
  import { positiveNumber } from "../utils/numbers.js";
4
4
  import { cleanText } from "../utils/text.js";
5
5
  export function usableModels(catalog) {
@@ -126,25 +126,21 @@ function budgetVariants(variants) {
126
126
  variants.max = { reasoningEffort: "max" };
127
127
  }
128
128
  export function modelVariants(options, _outputLimit) {
129
+ // The provider CLI registers every model with `reasoning: true` and an unset
130
+ // `thinkingLevelMap`, so it offers these levels to every model. models.dev
131
+ // lists fewer levels for some upstream models, but the gateway accepts the
132
+ // CLI's set, and hiding levels only makes the picker disagree with the CLI.
129
133
  const variants = {};
130
- // The provider CLI offers these levels to every reasoning model because its
131
- // `thinkingLevelMap` is unset; `xhigh` and `max` stay opt-in.
132
- if (!options || options.length === 0) {
133
- for (const level of DEFAULT_THINKING_LEVELS) {
134
- variants[level] = { reasoningEffort: level };
135
- }
136
- return variants;
134
+ for (const level of DEFAULT_THINKING_LEVELS) {
135
+ variants[level] = { reasoningEffort: level };
137
136
  }
137
+ if (!options || options.length === 0)
138
+ return variants;
138
139
  const effort = options.find((option) => option.type === "effort");
139
140
  if (effort) {
140
141
  for (const value of effort.values) {
141
142
  variants[value] = { reasoningEffort: value };
142
143
  }
143
- return variants;
144
- }
145
- if (options.some((option) => option.type === "toggle")) {
146
- variants.none = { reasoningEffort: "none" };
147
- variants.high = { reasoningEffort: "high" };
148
144
  }
149
145
  if (options.some((option) => option.type === "budget_tokens")) {
150
146
  budgetVariants(variants);
@@ -166,19 +162,10 @@ export function preferredReasoningEffort(options, configured) {
166
162
  return undefined;
167
163
  if (configured)
168
164
  return configured;
169
- if (!options || options.length === 0)
170
- return DEFAULT_REASONING_EFFORT;
171
- const effort = options.find((option) => option.type === "effort");
172
- if (effort) {
173
- if (effort.values.includes(DEFAULT_REASONING_EFFORT))
174
- return DEFAULT_REASONING_EFFORT;
175
- if (effort.values.includes("high"))
176
- return "high";
177
- return effort.values[effort.values.length - 1];
178
- }
179
- if (options.some((option) => option.type === "toggle"))
180
- return "high";
181
- if (options.some((option) => option.type === "budget_tokens"))
165
+ // The provider CLI's levels are the source of truth: models.dev often lists
166
+ // only a subset, but the gateway accepts the CLI set. `medium` is the sane
167
+ // middle ground between the CLI's off default and burning tokens on `high`.
168
+ if (options?.some((option) => option.type === "budget_tokens"))
182
169
  return "high";
183
170
  return DEFAULT_REASONING_EFFORT;
184
171
  }
@@ -225,17 +212,20 @@ export function buildModels(models, candidates = [], options = {}) {
225
212
  if (!model.id)
226
213
  continue;
227
214
  const capability = modelCapability(model, candidates);
228
- const reasoning = model.reasoning ?? capability?.reasoning ?? true;
215
+ // The provider CLI registers every model as `reasoning: true`; models.dev
216
+ // sometimes omits or disagrees for the upstream alias. Trust the catalog's
217
+ // explicit answer, otherwise keep reasoning on like the CLI does.
218
+ const reasoning = model.reasoning ?? true;
229
219
  const reasoningOptions = model.reasoning_options ?? capability?.reasoning_options;
230
- // free-pi enforces a 200k input window and 32k output cap on every model,
231
- // regardless of what models.dev reports for the upstream provider. The
232
- // provider CLI registers exactly these limits, so clamp to them here too:
233
- // an advertised 1M window would let OpenCode grow a session past the
234
- // server's real ceiling and fail with `context_too_long` instead of
235
- // compacting.
236
- const contextCeiling = options.compact100
237
- ? COMPACT100_CONTEXT_WINDOW
238
- : CONTEXT_WINDOW;
220
+ // free-pi enforces a context window on every model regardless of what
221
+ // models.dev reports for the upstream provider. The provider CLI starts at
222
+ // 200k, but the gateway does not publish its ceiling: `verifyGatewayWindow`
223
+ // measures it and the result is used here from the next start. Real steps
224
+ // also prove the gateway accepted at least their prompt size. A published
225
+ // catalog field still wins, but only inside that measured ceiling, so an
226
+ // advertised 1M window can never push a session past what the gateway takes.
227
+ const observed = options.live?.models[model.id]?.maxPromptTokens ?? 0;
228
+ const contextCeiling = Math.min(1_000_000, Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed));
239
229
  const limitContext = Math.min(positiveNumber(model.context_window, model.contextWindow, model.limit?.context, capability?.limit?.context) ?? contextCeiling, contextCeiling);
240
230
  const limitOutput = Math.min(positiveNumber(model.max_tokens, model.maxTokens, model.max_output_tokens, model.limit?.output, capability?.limit?.output) ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS);
241
231
  const defaultEffort = reasoning