@eduardo191labs/opencode-free-pi 0.5.6 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -55
- package/dist/catalog/catalog.js +1 -21
- package/dist/catalog/live.d.ts +71 -0
- package/dist/catalog/live.js +301 -0
- package/dist/catalog/models.d.ts +13 -2
- package/dist/catalog/models.js +69 -21
- package/dist/catalog/registry.js +5 -15
- package/dist/catalog/v2.js +5 -7
- package/dist/constants.d.ts +24 -21
- package/dist/constants.js +24 -19
- package/dist/logging.js +2 -2
- package/dist/plugin.js +26 -2
- package/dist/session/events.js +2 -3
- package/dist/session/hooks.js +4 -12
- package/dist/state.d.ts +1 -15
- package/dist/state.js +0 -3
- package/dist/tools/vision-queue.d.ts +1 -1
- package/dist/tools/vision-queue.js +5 -5
- package/dist/tools/vision.js +24 -35
- package/dist/tools/web.js +39 -44
- package/dist/types.d.ts +5 -9
- package/dist/utils/data-dir.d.ts +3 -0
- package/dist/utils/data-dir.js +12 -0
- package/package.json +2 -2
- package/src/catalog/catalog.ts +0 -25
- package/src/catalog/live.ts +361 -0
- package/src/catalog/models.ts +92 -23
- package/src/catalog/registry.ts +6 -21
- package/src/catalog/v2.ts +5 -7
- package/src/constants.ts +24 -22
- package/src/logging.ts +2 -2
- package/src/plugin.ts +34 -2
- package/src/session/events.ts +6 -3
- package/src/session/hooks.ts +4 -18
- package/src/state.ts +0 -18
- package/src/tools/vision-queue.ts +5 -5
- package/src/tools/vision.ts +26 -38
- package/src/tools/web.ts +49 -59
- package/src/types.ts +5 -8
- package/src/utils/data-dir.ts +14 -0
- package/dist/session/cache.d.ts +0 -15
- package/dist/session/cache.js +0 -57
- package/dist/tools/spend-cache.d.ts +0 -15
- package/dist/tools/spend-cache.js +0 -64
- package/dist/utils/cache.d.ts +0 -7
- package/dist/utils/cache.js +0 -45
- package/src/session/cache.ts +0 -82
- package/src/tools/spend-cache.ts +0 -79
- package/src/utils/cache.ts +0 -49
package/README.md
CHANGED
|
@@ -66,11 +66,14 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
66
66
|
- Catálogo en vivo de modelos **free-pi** y **free-pi-defense**.
|
|
67
67
|
- Integración nativa de OpenCode V2 para credenciales OAuth, clave y entorno.
|
|
68
68
|
- Cuota diaria, créditos premium y límites con mensajes claros.
|
|
69
|
-
- **Límites reales de free-pi**: todos los modelos
|
|
69
|
+
- **Límites reales de free-pi**: todos los modelos parten de la ventana de
|
|
70
70
|
contexto de 200k y el límite de salida de 32k que aplica el CLI del
|
|
71
71
|
proveedor, aunque models.dev informe ventanas mayores para el modelo
|
|
72
|
-
upstream.
|
|
73
|
-
|
|
72
|
+
upstream. El plugin sube la ventana midiendo lo que el gateway acepta de
|
|
73
|
+
verdad (hasta 1M) y deja que los modelos con más presupuesto de salida usen
|
|
74
|
+
hasta 131k, para que el razonamiento no se corte. Así OpenCode compacta antes
|
|
75
|
+
de que el servidor rechace la conversación y aun así aprovecha la capacidad
|
|
76
|
+
real de la cuenta.
|
|
74
77
|
- **Compactación integrada**: los errores `context_too_long` de free-pi se
|
|
75
78
|
reescriben para que OpenCode los reconozca como desbordamiento de contexto y
|
|
76
79
|
ejecute `/compact` automáticamente en vez de terminar el turno.
|
|
@@ -84,31 +87,50 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
84
87
|
El plugin lo responde con la primera línea del primer mensaje, sin gastar
|
|
85
88
|
créditos, sin pedir un anuncio y sin dejar la sesión atascada en
|
|
86
89
|
«New session».
|
|
87
|
-
- **
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
tokens de imagen
|
|
92
|
-
aplica el mismo aviso al terminar la herramienta para que
|
|
93
|
-
guardado en la sesión
|
|
94
|
-
|
|
90
|
+
- **Capacidades según el modelo**: los modelos que models.dev identifica como
|
|
91
|
+
multimodales anuncian entrada de imágenes y el gateway las reenvía al modelo
|
|
92
|
+
upstream. Los modelos de solo texto siguen usando `look_at_image`, porque
|
|
93
|
+
incrustar cada imagen leída (cientos de KB) en la conversación desborda la
|
|
94
|
+
ventana y gasta cuota en tokens de imagen; OpenCode sustituye las imágenes por
|
|
95
|
+
un aviso y el plugin aplica el mismo aviso al terminar la herramienta para que
|
|
96
|
+
el base64 no quede guardado en la sesión. La salida es siempre texto: la ruta
|
|
97
|
+
de chat no devuelve imágenes.
|
|
95
98
|
- **Subagentes identificados**: las sesiones hijas envían
|
|
96
99
|
`x-freepi-subagent: 1`, igual que los proveedores que el CLI crea para sus
|
|
97
100
|
subagentes.
|
|
98
|
-
- **Pensamiento por defecto**: el plugin pide `reasoning_effort: "
|
|
101
|
+
- **Pensamiento por defecto**: el plugin pide `reasoning_effort: "high"`
|
|
99
102
|
cuando el modelo no trae variante elegida. Dejarlo sin definir hacía que los
|
|
100
103
|
modelos gratuitos respondieran con prisa, gastando apenas unas decenas de
|
|
101
104
|
tokens de razonamiento incluso en tareas que requieren planificar. El
|
|
102
|
-
selector ofrece siempre
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
105
|
+
selector ofrece siempre los seis niveles que el gateway acepta —`none`,
|
|
106
|
+
`minimal`, `low`, `medium`, `high` y `max`—, para todos los modelos, y el
|
|
107
|
+
mismo conjunto se anuncia en `reasoning_options`; los modelos de presupuesto
|
|
108
|
+
usan `high` por defecto. La opción `reasoningEffort: false` del plugin
|
|
109
|
+
recupera el nivel del servidor. No se anuncian `thinking_budget` ni
|
|
106
110
|
`thinking`, porque la ruta `openai-compatible` de OpenCode los descarta.
|
|
111
|
+
- **Más razonamiento real**: medido con `curl_cffi` contra el gateway, cambiar
|
|
112
|
+
`reasoning_effort` no altera cuánto piensa el modelo (los tokens de
|
|
113
|
+
razonamiento varían al azar entre ~60 y ~600 en cada nivel) y los modelos
|
|
114
|
+
`flash` se detienen solos en la primera respuesta plausible. Lo que sí
|
|
115
|
+
funciona es pedir el trabajo explícito: con la regla de «escribe cada paso,
|
|
116
|
+
recalcula por un segundo método y no respondas hasta que coincidan», el mismo
|
|
117
|
+
modelo subió de ~450 a ~1250 tokens de razonamiento y acertó 5/5 problemas de
|
|
118
|
+
lógica frente a 3/5 sin la regla. Por eso la guía de trabajo prioriza la
|
|
119
|
+
respuesta lenta y verificada, y el límite de salida se deja amplio para que
|
|
120
|
+
esa cadena no se trunque.
|
|
107
121
|
- **Capacidades iguales al CLI**: todos los modelos se registran con
|
|
108
|
-
razonamiento activo,
|
|
109
|
-
|
|
110
|
-
petición real no los incluye, así que el gateway aplica su propio
|
|
111
|
-
prompt se envía con rol `system`, no `developer`.
|
|
122
|
+
razonamiento activo, coste cero, la ventana medida y el límite de salida que
|
|
123
|
+
publica el upstream (32k por defecto, hasta 131k). No se fuerza temperatura ni
|
|
124
|
+
`top_p`: la petición real no los incluye, así que el gateway aplica su propio
|
|
125
|
+
valor. El prompt se envía con rol `system`, no `developer`.
|
|
126
|
+
- **Límites medidos, no inventados**: `/client-version` solo devuelve id,
|
|
127
|
+
nombre, `free`, `section`, `note`, `stats_id` y `usage_x`; no hay endpoint de
|
|
128
|
+
capacidades ni de ventana. El plugin no se queda en constantes: confirma la
|
|
129
|
+
ventana compilada y después la agranda mientras el gateway acepte prompts
|
|
130
|
+
mayores, con búsqueda binaria al primer rechazo y un 3 % de margen. Guarda el
|
|
131
|
+
resultado en `live-limits.json` y anota en cada paso los tokens de prompt y de
|
|
132
|
+
razonamiento que el servidor confirma. `liveLimits: false` desactiva la
|
|
133
|
+
comprobación y deja la ventana compilada.
|
|
112
134
|
- **Reglas de trabajo en el prompt**: cada petición principal de free-pi añade
|
|
113
135
|
un bloque corto al system prompt con lo que los modelos gratuitos suelen
|
|
114
136
|
omitir: leer antes de editar, ejecutar las comprobaciones de verdad, no
|
|
@@ -128,9 +150,6 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
128
150
|
free-pi. El CLI nunca los hace y cada ping gastaría créditos y anuncios.
|
|
129
151
|
- **Timeouts del CLI**: 5 minutos para las cabeceras y para cada trozo de la
|
|
130
152
|
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
153
|
- Anuncios e impresiones asociados al turno correcto.
|
|
135
154
|
- Cada agente y subagente usa su propio `x-session-id`, `x-turn-id` y contexto
|
|
136
155
|
de anuncios; nunca reutiliza los del agente principal.
|
|
@@ -167,7 +186,7 @@ herramienta `look_at_image` con una ruta y una pregunta concreta. El plugin:
|
|
|
167
186
|
- Envía la imagen a `/tools/vision` y devuelve la respuesta del modelo de
|
|
168
187
|
visión como texto.
|
|
169
188
|
- Serializa las preguntas entre sesiones y procesos de OpenCode mediante un
|
|
170
|
-
bloqueo en
|
|
189
|
+
bloqueo en el directorio de datos del plugin. Si el servidor responde `rate_limited` porque
|
|
171
190
|
otra sesión o el CLI está consultando una imagen, reintenta automáticamente
|
|
172
191
|
respetando `Retry-After` en vez de hacer fallar el turno.
|
|
173
192
|
|
|
@@ -201,15 +220,8 @@ no pueda escribir fuera de `images/`.
|
|
|
201
220
|
códigos `daily_cap`, `rolling_cap`, `rate_limited`, `not_found`,
|
|
202
221
|
`not_configured`, `upstream_error` y los de invitado se traducen al mismo texto
|
|
203
222
|
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`.
|
|
223
|
+
`look_at_image`, cada llamada consume allowance y se ejecuta tal cual: el plugin
|
|
224
|
+
no reutiliza respuestas ni oculta llamadas repetidas.
|
|
213
225
|
|
|
214
226
|
`free_pi_usage` consulta `/me/stats` y resume el tier, los créditos restantes
|
|
215
227
|
con su hora de recarga en ET, los créditos premium o de referidos y los tokens
|
|
@@ -271,15 +283,13 @@ permisos también siguen siendo los de OpenCode; free-pi no los reemplaza.
|
|
|
271
283
|
|
|
272
284
|
El plugin replica las cabeceras del plugin V1 de free-pi:
|
|
273
285
|
|
|
274
|
-
- **Modelo**: `authorization`, `x-session-id`, `x-client-version
|
|
275
|
-
`x-turn-id
|
|
276
|
-
Las sesiones hijas añaden `x-freepi-subagent: 1`.
|
|
286
|
+
- **Modelo**: `authorization`, `x-session-id`, `x-client-version` y
|
|
287
|
+
`x-turn-id`. Las sesiones hijas añaden `x-freepi-subagent: 1`.
|
|
277
288
|
- **Resultados de herramientas**: `x-freepi-tool-meta` (duración, código de
|
|
278
289
|
salida y truncado de las últimas llamadas), `x-freepi-tool-errors` (IDs de
|
|
279
290
|
herramientas fallidas) y `x-freepi-compacted` (mensajes plegados por la
|
|
280
291
|
última compactación, en la petición siguiente).
|
|
281
|
-
- **Catálogo** (`/client-version`): `authorization
|
|
282
|
-
igual que el CLI, para que el servidor pueda asignar el experimento de coste.
|
|
292
|
+
- **Catálogo** (`/client-version`): `authorization`.
|
|
283
293
|
- **Anuncios** (`/ads/next`): `authorization`, `x-session-id`,
|
|
284
294
|
`x-client-version`, `x-turn-id`, `x-ad-trigger`, `x-client-os`,
|
|
285
295
|
`x-client-arch`, `x-client-timezone`, `x-client-locale` y `x-ad-context`.
|
|
@@ -318,10 +328,7 @@ sin fallar ni mostrar reintentos. Además libera el id anterior, y si el replay
|
|
|
318
328
|
puede completarse el hook de reintento rota el id para los siguientes pasos. Un
|
|
319
329
|
turno que se aborta o falla a mitad de stream marca su `x-session-id` como sucio:
|
|
320
330
|
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.
|
|
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.
|
|
331
|
+
de modo que la sesión continúa sin interrupciones y sin pasar por un reintento.
|
|
325
332
|
|
|
326
333
|
## Rutas por plataforma
|
|
327
334
|
|
|
@@ -344,24 +351,25 @@ Si `XDG_CONFIG_HOME` o `OPENCODE_CONFIG_DIR` están definidos, se respetan.
|
|
|
344
351
|
| `FREEPI_DEVICE_LOGIN=1` | Forzar inicio de sesión por dispositivo. |
|
|
345
352
|
| `FREEPI_CONFIGURE=1` | Registrar el paquete en `opencode.json` al instalar. |
|
|
346
353
|
| `OPENCODE_CONFIG_DIR` | Directorio de configuración de OpenCode. |
|
|
347
|
-
| `
|
|
354
|
+
| `FREE_PI_DATA_DIR` | Directorio de datos del plugin. |
|
|
348
355
|
| `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
356
|
|
|
351
357
|
No hay variables obligatorias.
|
|
352
358
|
|
|
353
|
-
##
|
|
359
|
+
## Datos y logs
|
|
354
360
|
|
|
355
|
-
El
|
|
361
|
+
El catálogo y el registro de models.dev se piden en vivo en cada arranque: no
|
|
362
|
+
se guardan copias en disco ni se muestran datos de una ejecución anterior. El
|
|
363
|
+
plugin solo conserva en:
|
|
356
364
|
|
|
357
365
|
```text
|
|
358
|
-
~/.cache/opencode/free-pi/
|
|
359
|
-
~/.cache/opencode/free-pi/models-dev.json
|
|
366
|
+
~/.cache/opencode/free-pi/live-limits.json
|
|
360
367
|
```
|
|
361
368
|
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
369
|
+
la ventana de contexto que midió contra el gateway y lo que cada paso real
|
|
370
|
+
demostró sobre el modelo. Esa medición se vuelve a comprobar cada 7 días.
|
|
371
|
+
|
|
372
|
+
En Windows es `%USERPROFILE%\.cache\opencode\free-pi\`.
|
|
365
373
|
|
|
366
374
|
Los mensajes del plugin se escriben en la consola con el prefijo `[free-pi]` y
|
|
367
375
|
también en:
|
|
@@ -431,16 +439,17 @@ src/
|
|
|
431
439
|
auth/ OAuth, JWT, credenciales y conexión
|
|
432
440
|
api/ cuota y reset de sesión
|
|
433
441
|
ads/ contexto, turnos e impresiones
|
|
434
|
-
catalog/ catálogo en vivo y
|
|
442
|
+
catalog/ catálogo en vivo, models.dev y límites medidos
|
|
435
443
|
errors/ parseo, mensajes y reescritura de límites
|
|
436
444
|
integration/ integración y métodos de inicio de sesión
|
|
437
445
|
session/ hooks, eventos, seguimiento y uso
|
|
438
|
-
utils/ helpers pequeños (
|
|
446
|
+
utils/ helpers pequeños (directorio de datos y URLs)
|
|
439
447
|
dist/ build ESM y tipos
|
|
440
448
|
scripts/postinstall.mjs registro en opencode.json
|
|
441
449
|
test/smoke.mjs prueba de humo del build
|
|
442
|
-
test/registry.mjs
|
|
443
|
-
test/models.mjs capacidades, variantes
|
|
450
|
+
test/registry.mjs models.dev en vivo y tolerancia a fallos
|
|
451
|
+
test/models.mjs capacidades, variantes y límites
|
|
452
|
+
test/live.mjs ventana medida y observaciones del gateway
|
|
444
453
|
test/hooks.mjs hooks de sesión, anuncios, cuota y compactación
|
|
445
454
|
```
|
|
446
455
|
|
package/dist/catalog/catalog.js
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
/** Fetches the live free-pi model catalog. */
|
|
2
2
|
import { resolveToken } from "../auth/token.js";
|
|
3
|
-
import {
|
|
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,71 @@
|
|
|
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 measured one, then the compiled one. */
|
|
47
|
+
window?: number;
|
|
48
|
+
};
|
|
49
|
+
/** One gateway answer used to settle the advertised window. */
|
|
50
|
+
export type ProbeSample = {
|
|
51
|
+
chars: number;
|
|
52
|
+
/** Prompt tokens the gateway reported for an accepted probe. */
|
|
53
|
+
tokens?: number;
|
|
54
|
+
tooLong: boolean;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Largest window the accepted probes prove, with headroom. Pure so the probe
|
|
58
|
+
* loop and the persisted value can be tested without a server.
|
|
59
|
+
*/
|
|
60
|
+
export declare function settleWindow(samples: readonly ProbeSample[]): number | undefined;
|
|
61
|
+
/**
|
|
62
|
+
* Checks the compiled window against the gateway and then grows past it while
|
|
63
|
+
* the gateway keeps accepting larger prompts. The start value is a floor, not a
|
|
64
|
+
* ceiling: the server has no endpoint for its real limit, and pinning sessions
|
|
65
|
+
* to the CLI's 200k wastes capacity the account can actually use. On rejection
|
|
66
|
+
* it binary-searches between the largest accepted prompt and the rejected one,
|
|
67
|
+
* so the next catalog build advertises the measured window. Returns the verified
|
|
68
|
+
* window, or `undefined` when nothing could be learned (the previous value is
|
|
69
|
+
* kept).
|
|
70
|
+
*/
|
|
71
|
+
export declare function verifyGatewayWindow(deps: Deps, options?: VerifyLimitsOptions): Promise<number | undefined>;
|
|
@@ -0,0 +1,301 @@
|
|
|
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
|
+
/** Hard stop for the upward search; `buildModels` never advertises more. */
|
|
22
|
+
const MAX_WINDOW = 1_000_000;
|
|
23
|
+
/** Keep headroom under the exact ceiling so a fresh turn never hits a 413. */
|
|
24
|
+
const WINDOW_SAFETY = 0.97;
|
|
25
|
+
/** Probe requests per verification, counting the initial confirmation. */
|
|
26
|
+
const MAX_PROBES = 6;
|
|
27
|
+
/** OpenCode budgets four characters per token; correct it after the first probe. */
|
|
28
|
+
const INITIAL_CHARS_PER_TOKEN = 4;
|
|
29
|
+
let cached;
|
|
30
|
+
let loaded = false;
|
|
31
|
+
let writeTimer;
|
|
32
|
+
function emptyLimits() {
|
|
33
|
+
return { version: 1, models: {} };
|
|
34
|
+
}
|
|
35
|
+
function sanitize(value) {
|
|
36
|
+
if (!value || typeof value !== "object")
|
|
37
|
+
return emptyLimits();
|
|
38
|
+
const limits = value;
|
|
39
|
+
const models = {};
|
|
40
|
+
for (const [id, entry] of Object.entries(limits.models ?? {})) {
|
|
41
|
+
if (!entry || typeof entry !== "object")
|
|
42
|
+
continue;
|
|
43
|
+
const observation = {
|
|
44
|
+
updatedAt: typeof entry.updatedAt === "number" ? entry.updatedAt : Date.now(),
|
|
45
|
+
};
|
|
46
|
+
if (Number.isFinite(entry.maxPromptTokens) && entry.maxPromptTokens > 0) {
|
|
47
|
+
observation.maxPromptTokens = Math.floor(entry.maxPromptTokens);
|
|
48
|
+
}
|
|
49
|
+
if (typeof entry.reasoning === "boolean") {
|
|
50
|
+
observation.reasoning = entry.reasoning;
|
|
51
|
+
}
|
|
52
|
+
models[id] = observation;
|
|
53
|
+
}
|
|
54
|
+
const window = limits.window;
|
|
55
|
+
return {
|
|
56
|
+
version: 1,
|
|
57
|
+
models,
|
|
58
|
+
...(window &&
|
|
59
|
+
Number.isFinite(window.tokens) &&
|
|
60
|
+
window.tokens > 0 &&
|
|
61
|
+
Number.isFinite(window.verifiedAt)
|
|
62
|
+
? {
|
|
63
|
+
window: {
|
|
64
|
+
tokens: Math.floor(window.tokens),
|
|
65
|
+
verifiedAt: window.verifiedAt,
|
|
66
|
+
...(typeof window.model === "string" ? { model: window.model } : {}),
|
|
67
|
+
},
|
|
68
|
+
}
|
|
69
|
+
: {}),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** Reads the persisted measurements once per process. Never throws. */
|
|
73
|
+
export async function loadLiveLimits() {
|
|
74
|
+
if (loaded && cached)
|
|
75
|
+
return cached;
|
|
76
|
+
try {
|
|
77
|
+
cached = sanitize(JSON.parse(await readFile(dataPath(FILE), "utf8")));
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
cached = emptyLimits();
|
|
81
|
+
}
|
|
82
|
+
loaded = true;
|
|
83
|
+
return cached;
|
|
84
|
+
}
|
|
85
|
+
/** The measurements loaded for this process. */
|
|
86
|
+
export function currentLiveLimits() {
|
|
87
|
+
return cached;
|
|
88
|
+
}
|
|
89
|
+
async function persist() {
|
|
90
|
+
if (!cached)
|
|
91
|
+
return;
|
|
92
|
+
try {
|
|
93
|
+
const file = dataPath(FILE);
|
|
94
|
+
await mkdir(dirname(file), { recursive: true });
|
|
95
|
+
await writeFile(file, JSON.stringify(cached), "utf8");
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
// Measurements are an optimization; failing to persist changes nothing.
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function scheduleWrite() {
|
|
102
|
+
if (writeTimer)
|
|
103
|
+
return;
|
|
104
|
+
writeTimer = setTimeout(() => {
|
|
105
|
+
writeTimer = undefined;
|
|
106
|
+
void persist();
|
|
107
|
+
}, WRITE_DEBOUNCE_MS);
|
|
108
|
+
writeTimer.unref?.();
|
|
109
|
+
}
|
|
110
|
+
function observation(modelID) {
|
|
111
|
+
const limits = (cached ??= emptyLimits());
|
|
112
|
+
limits.models[modelID] ??= { updatedAt: Date.now() };
|
|
113
|
+
return limits.models[modelID];
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Folds a real step's usage into the model's record: the prompt size proves the
|
|
117
|
+
* gateway accepted at least that much context, and reasoning tokens prove the
|
|
118
|
+
* model really reasoned for this account.
|
|
119
|
+
*/
|
|
120
|
+
export function noteStepTokens(_deps, modelID, tokens) {
|
|
121
|
+
if (!modelID || !tokens)
|
|
122
|
+
return;
|
|
123
|
+
const prompt = (tokens.input ?? 0) + (tokens.cache?.read ?? 0) + (tokens.cache?.write ?? 0);
|
|
124
|
+
const entry = observation(modelID);
|
|
125
|
+
let changed = false;
|
|
126
|
+
if (prompt > 0 && prompt >= (entry.maxPromptTokens ?? 0)) {
|
|
127
|
+
entry.maxPromptTokens = Math.floor(prompt);
|
|
128
|
+
changed = true;
|
|
129
|
+
}
|
|
130
|
+
if ((tokens.reasoning ?? 0) > 0 && entry.reasoning !== true) {
|
|
131
|
+
entry.reasoning = true;
|
|
132
|
+
changed = true;
|
|
133
|
+
}
|
|
134
|
+
if (!changed)
|
|
135
|
+
return;
|
|
136
|
+
entry.updatedAt = Date.now();
|
|
137
|
+
scheduleWrite();
|
|
138
|
+
}
|
|
139
|
+
/** Whether the persisted window is old enough to verify again. */
|
|
140
|
+
export function shouldVerifyWindow(limits) {
|
|
141
|
+
const verifiedAt = limits?.window?.verifiedAt;
|
|
142
|
+
if (!verifiedAt)
|
|
143
|
+
return true;
|
|
144
|
+
return Date.now() - verifiedAt > VERIFY_LIMITS_TTL_MS;
|
|
145
|
+
}
|
|
146
|
+
function filler(chars) {
|
|
147
|
+
const unit = "the quick brown fox jumps over the lazy dog while maintainers review the patch and debate naming ";
|
|
148
|
+
return unit.repeat(Math.ceil(chars / unit.length)).slice(0, chars);
|
|
149
|
+
}
|
|
150
|
+
async function sendProbe(deps, modelID, chars) {
|
|
151
|
+
const token = await resolveToken(deps).catch(() => undefined);
|
|
152
|
+
if (!token)
|
|
153
|
+
return { status: "failed" };
|
|
154
|
+
const content = `${filler(chars)}\n\nIgnore the filler and reply with OK.`;
|
|
155
|
+
let response;
|
|
156
|
+
try {
|
|
157
|
+
response = await fetch(`${completionsBaseUrl()}/chat/completions`, {
|
|
158
|
+
method: "POST",
|
|
159
|
+
headers: {
|
|
160
|
+
accept: "application/json",
|
|
161
|
+
"content-type": "application/json",
|
|
162
|
+
authorization: `Bearer ${token}`,
|
|
163
|
+
"x-client-version": deps.state.latestClientVersion,
|
|
164
|
+
"x-session-id": `free-pi-window-${Date.now().toString(36)}`,
|
|
165
|
+
"x-ad-context": "none",
|
|
166
|
+
},
|
|
167
|
+
body: JSON.stringify({
|
|
168
|
+
model: modelID,
|
|
169
|
+
messages: [{ role: "user", content }],
|
|
170
|
+
stream: false,
|
|
171
|
+
max_tokens: 256,
|
|
172
|
+
}),
|
|
173
|
+
signal: AbortSignal.timeout(180_000),
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return { status: "failed" };
|
|
178
|
+
}
|
|
179
|
+
if (response.status === 413 || response.status === 400) {
|
|
180
|
+
const body = await response.text().catch(() => "");
|
|
181
|
+
if (/context_too_long|too long|context_ceiling/i.test(body)) {
|
|
182
|
+
return { status: "too_long" };
|
|
183
|
+
}
|
|
184
|
+
return { status: "failed" };
|
|
185
|
+
}
|
|
186
|
+
if (!response.ok)
|
|
187
|
+
return { status: "failed" };
|
|
188
|
+
const payload = (await response.json().catch(() => undefined));
|
|
189
|
+
const promptTokens = payload?.usage?.prompt_tokens;
|
|
190
|
+
return {
|
|
191
|
+
status: "ok",
|
|
192
|
+
...(typeof promptTokens === "number" ? { promptTokens } : {}),
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Largest window the accepted probes prove, with headroom. Pure so the probe
|
|
197
|
+
* loop and the persisted value can be tested without a server.
|
|
198
|
+
*/
|
|
199
|
+
export function settleWindow(samples) {
|
|
200
|
+
let best = 0;
|
|
201
|
+
for (const sample of samples) {
|
|
202
|
+
if (sample.tooLong)
|
|
203
|
+
continue;
|
|
204
|
+
if (!Number.isFinite(sample.tokens) || (sample.tokens ?? 0) <= 0)
|
|
205
|
+
continue;
|
|
206
|
+
if (sample.tokens <= best)
|
|
207
|
+
continue;
|
|
208
|
+
best = sample.tokens;
|
|
209
|
+
}
|
|
210
|
+
if (best === 0)
|
|
211
|
+
return undefined;
|
|
212
|
+
return Math.min(MAX_WINDOW, Math.max(MIN_WINDOW, Math.floor((best * WINDOW_SAFETY) / 1_000) * 1_000));
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Checks the compiled window against the gateway and then grows past it while
|
|
216
|
+
* the gateway keeps accepting larger prompts. The start value is a floor, not a
|
|
217
|
+
* ceiling: the server has no endpoint for its real limit, and pinning sessions
|
|
218
|
+
* to the CLI's 200k wastes capacity the account can actually use. On rejection
|
|
219
|
+
* it binary-searches between the largest accepted prompt and the rejected one,
|
|
220
|
+
* so the next catalog build advertises the measured window. Returns the verified
|
|
221
|
+
* window, or `undefined` when nothing could be learned (the previous value is
|
|
222
|
+
* kept).
|
|
223
|
+
*/
|
|
224
|
+
export async function verifyGatewayWindow(deps, options = {}) {
|
|
225
|
+
const modelID = options.model;
|
|
226
|
+
if (!modelID)
|
|
227
|
+
return undefined;
|
|
228
|
+
const fallback = options.window ?? cached?.window?.tokens ?? CONTEXT_WINDOW;
|
|
229
|
+
const samples = [];
|
|
230
|
+
// Accepted prompt tokens; also the lower bound of the binary search.
|
|
231
|
+
let accepted = 0;
|
|
232
|
+
let charsPerToken = INITIAL_CHARS_PER_TOKEN;
|
|
233
|
+
let target = Math.max(MIN_WINDOW, Math.min(fallback, MAX_WINDOW));
|
|
234
|
+
for (let attempt = 0; attempt < MAX_PROBES; attempt += 1) {
|
|
235
|
+
const chars = Math.max(MIN_WINDOW * charsPerToken, Math.floor(target * charsPerToken * 0.99));
|
|
236
|
+
const result = await sendProbe(deps, modelID, chars);
|
|
237
|
+
if (result.status === "failed") {
|
|
238
|
+
// A network failure or a rejected body proves nothing; keep what the
|
|
239
|
+
// earlier probes already established.
|
|
240
|
+
if (samples.length === 0)
|
|
241
|
+
return undefined;
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
if (result.status === "too_long") {
|
|
245
|
+
samples.push({ chars, tooLong: true });
|
|
246
|
+
if (accepted === 0) {
|
|
247
|
+
// The compiled window itself is too large: step down as before.
|
|
248
|
+
target = Math.floor(target * 0.85);
|
|
249
|
+
if (target < MIN_WINDOW)
|
|
250
|
+
return undefined;
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
const next = Math.floor((accepted + target) / 2);
|
|
254
|
+
if (next <= accepted)
|
|
255
|
+
break;
|
|
256
|
+
target = next;
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
const tokens = result.promptTokens;
|
|
260
|
+
samples.push({
|
|
261
|
+
chars,
|
|
262
|
+
tooLong: false,
|
|
263
|
+
...(tokens && tokens > 0 ? { tokens } : {}),
|
|
264
|
+
});
|
|
265
|
+
if (tokens && tokens > 0) {
|
|
266
|
+
accepted = tokens;
|
|
267
|
+
// Learn the real characters-per-token ratio for this prompt shape; the
|
|
268
|
+
// filler is prose, and four chars/token overshoots badly.
|
|
269
|
+
charsPerToken = chars / tokens;
|
|
270
|
+
}
|
|
271
|
+
else {
|
|
272
|
+
accepted = Math.floor(chars / charsPerToken);
|
|
273
|
+
}
|
|
274
|
+
if (accepted >= MAX_WINDOW)
|
|
275
|
+
break;
|
|
276
|
+
const next = Math.min(MAX_WINDOW, Math.floor(accepted * 1.2));
|
|
277
|
+
if (next <= accepted)
|
|
278
|
+
break;
|
|
279
|
+
target = next;
|
|
280
|
+
}
|
|
281
|
+
const settled = settleWindow(samples);
|
|
282
|
+
if (!settled)
|
|
283
|
+
return undefined;
|
|
284
|
+
// Keep the previous floor when growth probes only prove less: the CLI's 200k
|
|
285
|
+
// is already known to work, so a small upstream probe model must not shrink
|
|
286
|
+
// every session's window.
|
|
287
|
+
const verified = Math.max(settled, Math.min(fallback, CONTEXT_WINDOW));
|
|
288
|
+
const limits = (cached ??= emptyLimits());
|
|
289
|
+
limits.window = { tokens: verified, verifiedAt: Date.now(), model: modelID };
|
|
290
|
+
loaded = true;
|
|
291
|
+
await persist();
|
|
292
|
+
deps.log.info("free-pi verified the gateway context window", {
|
|
293
|
+
model: modelID,
|
|
294
|
+
window: verified,
|
|
295
|
+
compiled: fallback,
|
|
296
|
+
probes: samples.length,
|
|
297
|
+
acceptedTokens: accepted,
|
|
298
|
+
charsPerToken: Number(charsPerToken.toFixed(2)),
|
|
299
|
+
});
|
|
300
|
+
return verified;
|
|
301
|
+
}
|