@eduardo191labs/opencode-free-pi 0.5.6 → 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 +33 -39
  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 +10 -10
  7. package/dist/catalog/registry.js +5 -15
  8. package/dist/constants.d.ts +7 -15
  9. package/dist/constants.js +7 -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 +1 -11
  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 +19 -12
  27. package/src/catalog/registry.ts +6 -21
  28. package/src/constants.ts +7 -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 +0 -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
@@ -105,10 +105,17 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
105
105
  plugin recupera el nivel del servidor. No se anuncian `thinking_budget` ni
106
106
  `thinking`, porque la ruta `openai-compatible` de OpenCode los descarta.
107
107
  - **Capacidades iguales al CLI**: todos los modelos se registran con
108
- razonamiento activo, entrada solo de texto, coste cero y la misma ventana de
109
- 200k con 32k de salida que usa `pi`. No se fuerza temperatura ni `top_p`: la
110
- petición real no los incluye, así que el gateway aplica su propio valor. El
111
- prompt se envía con rol `system`, no `developer`.
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.
112
119
  - **Reglas de trabajo en el prompt**: cada petición principal de free-pi añade
113
120
  un bloque corto al system prompt con lo que los modelos gratuitos suelen
114
121
  omitir: leer antes de editar, ejecutar las comprobaciones de verdad, no
@@ -128,9 +135,6 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
128
135
  free-pi. El CLI nunca los hace y cada ping gastaría créditos y anuncios.
129
136
  - **Timeouts del CLI**: 5 minutos para las cabeceras y para cada trozo de la
130
137
  respuesta, los mismos valores que `httpIdleTimeoutMs` de pi.
131
- - **Avisos de cache miss opcionales**: con `FREE_PI_CACHE_MISS_NOTICES=1` el
132
- plugin registra en el log los turnos que vuelven a facturar más de 20k
133
- tokens de prompt, usando la misma fórmula que `cache-stats` de pi.
134
138
  - Anuncios e impresiones asociados al turno correcto.
135
139
  - Cada agente y subagente usa su propio `x-session-id`, `x-turn-id` y contexto
136
140
  de anuncios; nunca reutiliza los del agente principal.
@@ -167,7 +171,7 @@ herramienta `look_at_image` con una ruta y una pregunta concreta. El plugin:
167
171
  - Envía la imagen a `/tools/vision` y devuelve la respuesta del modelo de
168
172
  visión como texto.
169
173
  - Serializa las preguntas entre sesiones y procesos de OpenCode mediante un
170
- 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
171
175
  otra sesión o el CLI está consultando una imagen, reintenta automáticamente
172
176
  respetando `Retry-After` en vez de hacer fallar el turno.
173
177
 
@@ -201,15 +205,8 @@ no pueda escribir fuera de `images/`.
201
205
  códigos `daily_cap`, `rolling_cap`, `rate_limited`, `not_found`,
202
206
  `not_configured`, `upstream_error` y los de invitado se traducen al mismo texto
203
207
  que el CLI, para que el agente sepa cuándo no debe reintentar. Igual que
204
- `look_at_image`, cada llamada consume allowance.
205
-
206
- Las tres herramientas que gastan cuota (`web_search`, `docs_lookup` y
207
- `look_at_image`) comparten una caché de respuestas de 30 minutos: si el modelo,
208
- un subagente o un reintento piden exactamente lo mismo, se reutiliza la primera
209
- respuesta y no se vuelve a cobrar. Las llamadas idénticas en paralelo comparten
210
- una sola petición, y los errores nunca se cachean para que el siguiente intento
211
- vea el estado real del servidor. La respuesta cacheada lo indica y no incluye
212
- `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.
213
210
 
214
211
  `free_pi_usage` consulta `/me/stats` y resume el tier, los créditos restantes
215
212
  con su hora de recarga en ET, los créditos premium o de referidos y los tokens
@@ -271,15 +268,13 @@ permisos también siguen siendo los de OpenCode; free-pi no los reemplaza.
271
268
 
272
269
  El plugin replica las cabeceras del plugin V1 de free-pi:
273
270
 
274
- - **Modelo**: `authorization`, `x-session-id`, `x-client-version`,
275
- `x-turn-id` y `x-freepi-cost-exp` (cuando el catálogo asigna un experimento).
276
- 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`.
277
273
  - **Resultados de herramientas**: `x-freepi-tool-meta` (duración, código de
278
274
  salida y truncado de las últimas llamadas), `x-freepi-tool-errors` (IDs de
279
275
  herramientas fallidas) y `x-freepi-compacted` (mensajes plegados por la
280
276
  última compactación, en la petición siguiente).
281
- - **Catálogo** (`/client-version`): `authorization` y `x-freepi-cost-exp: 1`,
282
- igual que el CLI, para que el servidor pueda asignar el experimento de coste.
277
+ - **Catálogo** (`/client-version`): `authorization`.
283
278
  - **Anuncios** (`/ads/next`): `authorization`, `x-session-id`,
284
279
  `x-client-version`, `x-turn-id`, `x-ad-trigger`, `x-client-os`,
285
280
  `x-client-arch`, `x-client-timezone`, `x-client-locale` y `x-ad-context`.
@@ -318,10 +313,7 @@ sin fallar ni mostrar reintentos. Además libera el id anterior, y si el replay
318
313
  puede completarse el hook de reintento rota el id para los siguientes pasos. Un
319
314
  turno que se aborta o falla a mitad de stream marca su `x-session-id` como sucio:
320
315
  la siguiente petición arranca directamente con un id nuevo y libera el anterior,
321
- de modo que la sesión continúa sin interrupciones y sin pasar por un reintento. Si
322
- el catálogo asigna el experimento `compact100`, el plugin baja la ventana a 117
323
- 647 tokens para que OpenCode compacte al llegar a 100k, que es el mismo umbral
324
- que consigue `reserveTokens: 100000` en el CLI.
316
+ de modo que la sesión continúa sin interrupciones y sin pasar por un reintento.
325
317
 
326
318
  ## Rutas por plataforma
327
319
 
@@ -344,24 +336,25 @@ Si `XDG_CONFIG_HOME` o `OPENCODE_CONFIG_DIR` están definidos, se respetan.
344
336
  | `FREEPI_DEVICE_LOGIN=1` | Forzar inicio de sesión por dispositivo. |
345
337
  | `FREEPI_CONFIGURE=1` | Registrar el paquete en `opencode.json` al instalar. |
346
338
  | `OPENCODE_CONFIG_DIR` | Directorio de configuración de OpenCode. |
347
- | `FREE_PI_CACHE_DIR` | Directorio de caché del plugin. |
339
+ | `FREE_PI_DATA_DIR` | Directorio de datos del plugin. |
348
340
  | `FREE_PI_LOG_FILE` | Ruta alternativa del archivo de log del plugin. |
349
- | `FREE_PI_CACHE_MISS_NOTICES=1` | Registrar en el log los cache miss de más de 20k tokens. |
350
341
 
351
342
  No hay variables obligatorias.
352
343
 
353
- ## Caché y logs
344
+ ## Datos y logs
354
345
 
355
- 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:
356
349
 
357
350
  ```text
358
- ~/.cache/opencode/free-pi/catalog.json
359
- ~/.cache/opencode/free-pi/models-dev.json
351
+ ~/.cache/opencode/free-pi/live-limits.json
360
352
  ```
361
353
 
362
- En Windows es `%USERPROFILE%\.cache\opencode\free-pi\`. El catálogo se reutiliza
363
- hasta 24 h y el registro hasta 7 días si la red falla; cuando la petición
364
- 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\`.
365
358
 
366
359
  Los mensajes del plugin se escriben en la consola con el prefijo `[free-pi]` y
367
360
  también en:
@@ -431,16 +424,17 @@ src/
431
424
  auth/ OAuth, JWT, credenciales y conexión
432
425
  api/ cuota y reset de sesión
433
426
  ads/ contexto, turnos e impresiones
434
- catalog/ catálogo en vivo y registro models.dev
427
+ catalog/ catálogo en vivo, models.dev y límites medidos
435
428
  errors/ parseo, mensajes y reescritura de límites
436
429
  integration/ integración y métodos de inicio de sesión
437
430
  session/ hooks, eventos, seguimiento y uso
438
- utils/ helpers pequeños (incluye cache.ts)
431
+ utils/ helpers pequeños (directorio de datos y URLs)
439
432
  dist/ build ESM y tipos
440
433
  scripts/postinstall.mjs registro en opencode.json
441
434
  test/smoke.mjs prueba de humo del build
442
- test/registry.mjs caché y tolerancia a fallos de models.dev
443
- 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
444
438
  test/hooks.mjs hooks de sesión, anuncios, cuota y compactación
445
439
  ```
446
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) {
@@ -217,15 +217,15 @@ export function buildModels(models, candidates = [], options = {}) {
217
217
  // explicit answer, otherwise keep reasoning on like the CLI does.
218
218
  const reasoning = model.reasoning ?? true;
219
219
  const reasoningOptions = model.reasoning_options ?? capability?.reasoning_options;
220
- // free-pi enforces a 200k input window and 32k output cap on every model,
221
- // regardless of what models.dev reports for the upstream provider. The
222
- // provider CLI registers exactly these limits, so clamp to them here too:
223
- // an advertised 1M window would let OpenCode grow a session past the
224
- // server's real ceiling and fail with `context_too_long` instead of
225
- // compacting.
226
- const contextCeiling = options.compact100
227
- ? COMPACT100_CONTEXT_WINDOW
228
- : 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));
229
229
  const limitContext = Math.min(positiveNumber(model.context_window, model.contextWindow, model.limit?.context, capability?.limit?.context) ?? contextCeiling, contextCeiling);
230
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);
231
231
  const defaultEffort = reasoning
@@ -1,9 +1,7 @@
1
1
  /** Fetches the models.dev capability registry. */
2
- import { REGISTRY_ATTEMPTS, REGISTRY_DISK_TTL_MS, REGISTRY_RETRY_MS, REGISTRY_TIMEOUT_MS, REGISTRY_TTL_MS, } from "../constants.js";
2
+ import { REGISTRY_ATTEMPTS, REGISTRY_RETRY_MS, REGISTRY_TIMEOUT_MS, REGISTRY_TTL_MS, } from "../constants.js";
3
3
  import { sleep } from "../utils/async.js";
4
- import { readCache, writeCache } from "../utils/cache.js";
5
4
  import { modelsRegistryUrl } from "../utils/urls.js";
6
- const CACHE_FILE = "models-dev.json";
7
5
  function isRegistry(value) {
8
6
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
7
  }
@@ -54,7 +52,6 @@ export function refreshModelsRegistry(deps) {
54
52
  }
55
53
  state.cachedRegistry = registry;
56
54
  state.cachedRegistryAt = Date.now();
57
- void writeCache(CACHE_FILE, registry);
58
55
  return registry;
59
56
  }
60
57
  catch (error) {
@@ -79,18 +76,11 @@ export async function fetchModelsRegistry(deps) {
79
76
  return state.cachedRegistry;
80
77
  }
81
78
  if (!state.cachedRegistry) {
82
- const disk = await readCache(CACHE_FILE, REGISTRY_DISK_TTL_MS);
83
- if (isRegistry(disk)) {
84
- state.cachedRegistry = disk;
85
- state.cachedRegistryAt = Date.now();
86
- // Serve the cached copy immediately and refresh it in the background.
87
- void refreshModelsRegistry(deps);
88
- return disk;
79
+ if (state.registryAttemptAt &&
80
+ Date.now() - state.registryAttemptAt < REGISTRY_RETRY_MS) {
81
+ return state.cachedRegistry;
89
82
  }
90
- }
91
- if (state.registryAttemptAt &&
92
- Date.now() - state.registryAttemptAt < REGISTRY_RETRY_MS) {
93
- return state.cachedRegistry;
83
+ return refreshModelsRegistry(deps);
94
84
  }
95
85
  return refreshModelsRegistry(deps);
96
86
  }
@@ -7,8 +7,15 @@ export declare const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
7
7
  export declare const DEFAULT_BASE_URL = "https://api.freepi.ai";
8
8
  export declare const DEFAULT_CLIENT_VERSION = "0.6.25";
9
9
  export declare const CONSENT_VERSION = "4";
10
+ /**
11
+ * The provider CLI's window. The gateway enforces its own ceiling but does not
12
+ * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
13
+ * with what the server actually accepts.
14
+ */
10
15
  export declare const CONTEXT_WINDOW = 200000;
11
16
  export declare const MAX_OUTPUT_TOKENS = 32768;
17
+ /** How long a measured gateway window is trusted before checking again. */
18
+ export declare const VERIFY_LIMITS_TTL_MS: number;
12
19
  export declare const AD_CONTEXT_HEADER = "x-ad-context";
13
20
  /**
14
21
  * The CLI sends `none` when the ad context is unavailable or private instead of
@@ -16,8 +23,6 @@ export declare const AD_CONTEXT_HEADER = "x-ad-context";
16
23
  */
17
24
  export declare const AD_CONTEXT_OPT_OUT = "none";
18
25
  export declare const SUBAGENT_HEADER = "x-freepi-subagent";
19
- export declare const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
20
- export declare const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
21
26
  /**
22
27
  * The provider CLI starts with thinking off, but leaving `reasoning_effort`
23
28
  * unset makes the gateway answer in a hurry: the free models spend only a few
@@ -58,23 +63,12 @@ export declare const RETRY_MAX_DELAY_MS = 60000;
58
63
  export declare const CONCURRENT_RETRY_MAX = 6;
59
64
  export declare const CONCURRENT_RETRY_BASE_MS = 1000;
60
65
  export declare const CONCURRENT_RETRY_MAX_DELAY_MS = 15000;
61
- /** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
62
- export declare const CACHE_TTL_MS: number;
63
- export declare const CACHE_MISS_NOISE_FLOOR_TOKENS = 1024;
64
- export declare const CACHE_MISS_NOTICE_TOKENS = 20000;
65
66
  /** Tool outcome headers emitted by the free-pi provider CLI. */
66
67
  export declare const TOOL_META_HEADER = "x-freepi-tool-meta";
67
68
  export declare const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
68
69
  export declare const COMPACTED_HEADER = "x-freepi-compacted";
69
70
  export declare const TOOL_META_BUDGET = 1500;
70
71
  export declare const TOOL_ID_LIMIT = 50;
71
- /**
72
- * The `compact100` cost experiment reserves 100k tokens, so pi compacts when
73
- * the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
74
- * 117_647 is the smallest window that keeps that trigger at 100k.
75
- */
76
- export declare const COMPACT100_TRIGGER_TOKENS = 100000;
77
- export declare const COMPACT100_CONTEXT_WINDOW = 117647;
78
72
  export declare const SESSION_TRACK_LIMIT = 200;
79
73
  export declare const AUTH_SKEW_MS = 60000;
80
74
  export declare const AUTH_TIMEOUT_MS: number;
@@ -88,10 +82,8 @@ export declare const AD_TURN_LIMIT = 200;
88
82
  export declare const AD_IMPRESSION_LIMIT = 200;
89
83
  export declare const CREDITS_PER_USD: number;
90
84
  export declare const CATALOG_TTL_MS: number;
91
- export declare const CATALOG_DISK_TTL_MS: number;
92
85
  export declare const CATALOG_TIMEOUT_MS = 8000;
93
86
  export declare const REGISTRY_TTL_MS: number;
94
- export declare const REGISTRY_DISK_TTL_MS: number;
95
87
  export declare const REGISTRY_RETRY_MS = 60000;
96
88
  export declare const REGISTRY_TIMEOUT_MS = 3500;
97
89
  export declare const REGISTRY_ATTEMPTS = 2;