@eduardo191labs/opencode-free-pi 0.7.26 → 0.7.29

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 (48) hide show
  1. package/README.md +60 -105
  2. package/dist/catalog/live.js +4 -1
  3. package/dist/catalog/models.d.ts +1 -1
  4. package/dist/catalog/models.js +14 -3
  5. package/dist/constants.d.ts +15 -35
  6. package/dist/constants.js +15 -35
  7. package/dist/index.d.ts +1 -1
  8. package/dist/plugin.js +14 -46
  9. package/dist/session/events.js +5 -12
  10. package/dist/session/hooks.js +83 -348
  11. package/dist/session/overflow.d.ts +7 -28
  12. package/dist/session/overflow.js +7 -73
  13. package/dist/session/replay.d.ts +8 -41
  14. package/dist/session/replay.js +9 -148
  15. package/dist/session/tools.d.ts +2 -7
  16. package/dist/session/tools.js +3 -18
  17. package/dist/session/trace.js +0 -1
  18. package/dist/session/track.d.ts +2 -0
  19. package/dist/session/track.js +5 -0
  20. package/dist/state.d.ts +1 -6
  21. package/dist/state.js +0 -2
  22. package/dist/tools/vision.js +1 -0
  23. package/dist/types.d.ts +0 -1
  24. package/package.json +2 -2
  25. package/src/catalog/live.ts +4 -1
  26. package/src/catalog/models.ts +20 -3
  27. package/src/constants.ts +16 -38
  28. package/src/index.ts +0 -1
  29. package/src/plugin.ts +12 -52
  30. package/src/session/events.ts +5 -12
  31. package/src/session/hooks.ts +109 -431
  32. package/src/session/overflow.ts +7 -77
  33. package/src/session/replay.ts +12 -188
  34. package/src/session/tools.ts +1 -22
  35. package/src/session/trace.ts +0 -1
  36. package/src/session/track.ts +11 -0
  37. package/src/state.ts +0 -8
  38. package/src/tools/vision.ts +2 -0
  39. package/src/types.ts +0 -1
  40. package/dist/session/diet.d.ts +0 -23
  41. package/dist/session/diet.js +0 -176
  42. package/dist/session/title.d.ts +0 -18
  43. package/dist/session/title.js +0 -81
  44. package/dist/session/usage.d.ts +0 -5
  45. package/dist/session/usage.js +0 -32
  46. package/src/session/diet.ts +0 -201
  47. package/src/session/title.ts +0 -90
  48. package/src/session/usage.ts +0 -46
package/README.md CHANGED
@@ -66,57 +66,32 @@ 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 parten de la ventana de
70
- contexto de 200k y el límite de salida de 32k que aplica el CLI del
71
- proveedor, aunque models.dev informe ventanas mayores para el modelo
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.
69
+ - **Límites declarados, no inventados**: el plugin anuncia los límites que
70
+ publica el catálogo de free-pi y deja que OpenCode los use. No sondea la
71
+ ventana en segundo plano ni la sube por su cuenta: una ventana inventada por
72
+ encima de la real hacía que el turno chocara con el gateway y que la
73
+ compactación ni siquiera cupiera.
77
74
  - **Compactación integrada**: los errores `context_too_long` de free-pi se
78
75
  reescriben para que OpenCode los reconozca como desbordamiento de contexto y
79
76
  ejecute `/compact` automáticamente en vez de terminar el turno.
80
- - **Techo por modelo aprendido del gateway**: cuando free-pi rechaza una
81
- petición real por longitud, ese tamaño se guarda en `live-limits.json` como
82
- techo de ese modelo y el catálogo anuncia una ventana un 15 % menor, también
83
- sin reiniciar (`provider.reload`). Así la siguiente compactación empieza antes
84
- de que el gateway rechace también el propio resumen, que es lo que dejaba el
85
- turno detenido con solo el checkpoint en pantalla. Los rechazos causados por
86
- una imagen o un archivo adjunto no cuentan: su base64 no dice nada de la
87
- ventana de texto.
88
- - **Resumen de compactación sin recortes**: el presupuesto de salida de la
89
- petición de compactación ya no se limita a 32k, porque un resumen cortado por
90
- el límite hace fallar la compactación completa. Si aun así el resumen no cabe
91
- en el techo aprendido, se descartan los turnos de usuario más antiguos (sin
92
- romper parejas de herramienta) en lugar de abortar el turno.
93
- - **Ventana reciente en el resumen**: OpenCode sólo conserva el último
94
- intercambio junto al resumen, así que el trabajo hecho justo antes de
95
- compactar desaparecía. El plugin lee la sesión nativa, cita los últimos turnos
96
- (hasta 24k caracteres) en la petición de compactación y exige que el resumen
97
- termine con `## Recent window`, entregándolos también como último mensaje
98
- porque los modelos gratuitos ignoran las reglas del sistema. Esos turnos
99
- viajan una sola vez en la primera petición posterior, por si el resumen los
100
- comprimió de más; caducan a la hora y no se guardan en disco.
101
- - **Poda de resultados antiguos**: las sesiones largas llegan a prompts de
102
- 100k–170k tokens y a ese tamaño los modelos gratuitos pierden el centro de la
103
- conversación y dejan de seguir las reglas, aunque el gateway acepte la
104
- petición. Antes de enviar, el plugin colapsa los resultados de herramientas
105
- antiguos (conserva 600 caracteres de cabecera y 240 del final, con un aviso de
106
- que se podaron), sin tocar el texto de usuario, las decisiones del asistente
107
- ni los mensajes más recientes. El presupuesto es el 40 % de la ventana
108
- anunciada (mínimo 24k), así que el prompt vuelve a la zona donde el modelo
109
- atiende.
77
+ - **Compactación de OpenCode**: quién recorta el historial y cuándo se decide
78
+ lo maneja OpenCode. El plugin no borra mensajes, no recorta resultados de
79
+ herramientas ni reescribe el razonamiento guardado: un historial mutilado hace
80
+ que el modelo olvide lo que ya hizo y repita la misma acción. Solo se aprende,
81
+ sin coste, el techo real de cada modelo cuando el gateway rechaza una petición
82
+ de verdad por longitud, para que la compactación empiece antes del rechazo del
83
+ propio resumen.
110
84
  - **Sin bucles de compactación**: si el servidor rechaza como «demasiado
111
- largo» una petición que cabe de sobra en la ventana (menos de 60k tokens),
112
- el plugin la reintenta con un `x-session-id` nuevo en vez de compactar. Si
113
- aun así la sigue rechazando, devuelve un error de proveedor que OpenCode no
114
- clasifica como desbordamiento, para no gastar créditos en resúmenes que no
115
- arreglan nada.
116
- - **Títulos locales**: OpenCode pide un título al modelo al crear una sesión.
117
- El plugin lo responde con la primera línea del primer mensaje, sin gastar
118
- créditos, sin pedir un anuncio y sin dejar la sesión atascada en
119
- «New session».
85
+ largo» una petición que cabe en la ventana medida del modelo, el plugin no la
86
+ vuelve a enviar por su cuenta (eso ejecutaba la misma acción dos veces); deja
87
+ que OpenCode compacte una vez y, si el rechazo se repite, devuelve un error de
88
+ proveedor que OpenCode no clasifica como desbordamiento, para no gastar
89
+ créditos en resúmenes que no arreglan nada.
90
+ - **Títulos de OpenCode**: el agente de títulos, su prompt y su modelo son de
91
+ OpenCode. El plugin no intercepta la petición ni reemplaza el resultado
92
+ (`ctx.session.hook("title")` no se registra), y solo evita pedir un anuncio
93
+ para una petición que el usuario nunca ve. El gateway se validó en vivo con
94
+ la petición de título: responde 200 con un título limpio.
120
95
  - **Capacidades según el modelo**: los modelos gratuitos aceptan imágenes de
121
96
  entrada de forma nativa; se comprobó con `curl_cffi` contra el gateway y los
122
97
  cuatro transcriben una captura adjunta. Los alias de pago anuncian lo que
@@ -130,7 +105,7 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
130
105
  - **Subagentes identificados**: las sesiones hijas envían
131
106
  `x-freepi-subagent: 1`, igual que los proveedores que el CLI crea para sus
132
107
  subagentes.
133
- - **Pensamiento por defecto**: el plugin pide `reasoning_effort: "high"`
108
+ - **Pensamiento por defecto**: el plugin pide `reasoning_effort: "max"`
134
109
  cuando el modelo no trae variante elegida. Dejarlo sin definir hacía que los
135
110
  modelos gratuitos respondieran con prisa, gastando apenas unas decenas de
136
111
  tokens de razonamiento incluso en tareas que requieren planificar. El
@@ -140,10 +115,11 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
140
115
  usan `high` por defecto. La opción `reasoningEffort: false` del plugin
141
116
  recupera el nivel del servidor. No se anuncian `thinking_budget` ni
142
117
  `thinking`, porque la ruta `openai-compatible` de OpenCode los descarta.
143
- - **Más razonamiento real**: medido con `curl_cffi` contra el gateway, cambiar
144
- `reasoning_effort` no altera cuánto piensa el modelo (los tokens de
145
- razonamiento varían al azar entre ~60 y ~600 en cada nivel) y los modelos
146
- `flash` se detienen solos en la primera respuesta plausible. Lo que sí
118
+ - **Más razonamiento real**: medido con `curl_cffi` contra el gateway, subir
119
+ `reasoning_effort` sí alarga el razonamiento (medido: `max` produjo más
120
+ tokens de razonamiento que `high` en la misma tarea), pero los modelos
121
+ `flash` se detienen solos en la primera respuesta plausible, así que el nivel
122
+ solo no basta. Lo que sí
147
123
  funciona es pedir el trabajo explícito: con la regla de «escribe cada paso,
148
124
  recalcula por un segundo método y no respondas hasta que coincidan», el mismo
149
125
  modelo subió de ~450 a ~1250 tokens de razonamiento y acertó 5/5 problemas de
@@ -155,25 +131,17 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
155
131
  publica el upstream (32k por defecto, hasta 131k). No se fuerza temperatura ni
156
132
  `top_p`: la petición real no los incluye, así que el gateway aplica su propio
157
133
  valor. El prompt se envía con rol `system`, no `developer`.
158
- - **Sin razonamiento reenviado**: OpenCode guarda el pensamiento del modelo en
159
- los mensajes del asistente y lo devuelve dentro de `reasoning_content`. La
160
- captura con `curl_cffi` mostró que el gateway lo cobra como entrada (mismo
161
- prompt y misma respuesta pasaron de 27 a 188 tokens en `glm-5.3-flash`), así
162
- que el plugin lo quita antes de enviar. No cambia la respuesta: el modelo ya
163
- razonó en su turno y el historial conserva el texto visible.
164
- - **Límites medidos, no inventados**: `/client-version` solo devuelve id,
134
+ - **El razonamiento guardado se conserva**: el historial se envía tal como
135
+ OpenCode lo guarda, incluido el `reasoning_content` de cada turno. Borrarlo
136
+ para ahorrar tokens hacía que un modelo de razonamiento perdiera el motivo de
137
+ sus decisiones y repitiera la misma acción.
138
+ - **Límites declarados por el catálogo**: `/client-version` solo devuelve id,
165
139
  nombre, `free`, `section`, `note`, `stats_id` y `usage_x`; no hay endpoint de
166
- capacidades ni de ventana. El plugin no se queda en constantes: confirma la
167
- ventana compilada y después la agranda mientras el gateway acepte prompts
168
- mayores, con búsqueda binaria al primer rechazo y un 3 % de margen. Guarda el
169
- resultado en `live-limits.json` y anota en cada paso los tokens de prompt y de
170
- razonamiento que el servidor confirma. `liveLimits: false` desactiva la
171
- comprobación y deja la ventana compilada.
172
- - **Reglas de trabajo en el prompt**: cada petición principal de free-pi añade
173
- un bloque corto al system prompt con lo que los modelos gratuitos suelen
174
- omitir: leer antes de editar, ejecutar las comprobaciones de verdad, no
175
- afirmar que algo pasó si no se ejecutó, reutilizar las decisiones y rutas ya
176
- establecidas en la conversación y no fingir que se compactó el contexto.
140
+ capacidades ni de ventana. El plugin anuncia los límites que el catálogo
141
+ publica y deja el resto a OpenCode. Lo único que se aprende en vivo, sin
142
+ coste, es el techo de un modelo cuando el gateway rechaza una petición real
143
+ por longitud; ese dato se guarda en `live-limits.json` para que la siguiente
144
+ compactación empiece antes.
177
145
  Además, cuando una herramienta falla por un motivo que el modelo repite (un
178
146
  heredoc rechazado por el scanner del shell, un `edit` con cadenas idénticas o
179
147
  con un `oldString` ambiguo), el error que recibe añade el siguiente paso
@@ -422,9 +390,9 @@ El plugin replica las cabeceras del plugin V1 de free-pi:
422
390
  - **Modelo**: `authorization`, `x-session-id`, `x-client-version` y
423
391
  `x-turn-id`. Las sesiones hijas añaden `x-freepi-subagent: 1`.
424
392
  - **Resultados de herramientas**: `x-freepi-tool-meta` (duración, código de
425
- salida y truncado de las últimas llamadas), `x-freepi-tool-errors` (IDs de
426
- herramientas fallidas) y `x-freepi-compacted` (mensajes plegados por la
427
- última compactación, en la petición siguiente).
393
+ salida y truncado de las últimas llamadas) y `x-freepi-tool-errors` (IDs de
394
+ herramientas fallidas). El historial y su compactación son de OpenCode: el
395
+ plugin no pliega mensajes ni envía marcadores de compactación.
428
396
  - **Catálogo** (`/client-version`): `authorization`.
429
397
  - **Anuncios** (`/ads/next`): `authorization`, `x-session-id`,
430
398
  `x-client-version`, `x-turn-id`, `x-ad-trigger`, `x-client-os`,
@@ -441,49 +409,36 @@ se reescriben a un `400` con el texto que OpenCode clasifica como
441
409
  desbordamiento de contexto, para que dispare la compactación automática.
442
410
 
443
411
  El plugin mide el cuerpo de cada petición rechazada. Cuando el rechazo llega
444
- con un cuerpo que no puede agotar la ventana, lo trata como un fallo del
445
- proveedor: repite la petición con un `x-session-id` nuevo y, si el servidor
446
- insiste, devuelve un `400` con un mensaje de error de proveedor. Ese texto no
447
- coincide con el patrón de desbordamiento de OpenCode, así que el runner deja de
448
- compactar en lugar de entrar en un ciclo de resúmenes que no reducen nada.
412
+ con un cuerpo que no puede agotar la ventana, lo clasifica como fallo del
413
+ proveedor y devuelve un `400` con un mensaje de error: ese texto no coincide con
414
+ el patrón de desbordamiento de OpenCode, así que el runner deja de compactar en
415
+ lugar de entrar en un ciclo de resúmenes que no reducen nada. El plugin nunca
416
+ reenvía la petición ni recorta el historial.
449
417
 
450
418
  Cuando el rechazo sí corresponde a una conversación larga, el tamaño medido se
451
419
  guarda como `rejectedPromptTokens` del modelo en `live-limits.json`. El
452
420
  `provider.transform` reconstruye el catálogo con ese techo (85 % del tamaño
453
421
  rechazado, sin bajar de la ventana ya aceptada) y `provider.reload` lo aplica en
454
- caliente, de modo que la siguiente compactación se dispara antes de que el
455
- gateway rechace el resumen. Si el resumen aún no cupiera, el hook de
456
- compactación descarta los turnos de usuario más antiguos en lugar de dejar que
457
- OpenCode aborte el turno.
422
+ caliente, de modo que la siguiente compactación la decide OpenCode con un
423
+ presupuesto más realista.
458
424
 
459
425
  free-pi cobra en créditos contra una cuota diaria, no en USD por token. Por
460
426
  eso los modelos se registran con costo `0`, igual que el CLI del proveedor; el
461
427
  consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
462
428
  cuota y límite.
463
429
 
464
- Los reintentos siguen la política de pi: como máximo 3 reintentos, con espera
465
- `min(2s · 2^(n-1), 60s)`. Los límites terminales (`free_usage_limit`, cupos
466
- diarios u horarios, créditos, cuenta bloqueada) se convierten en un 400 con el
467
- mensaje amigable y no se reintentan, igual que hace el CLI de pi; así OpenCode no
468
- muestra un «Retrying…» que nunca termina. El 429 `concurrent` («one request at a
469
- time») es la excepción: como OpenCode reutiliza la petición ya preparada al
470
- reintentar, el plugin **repite la petición** desde el hook de respuesta con un
471
- `x-session-id` nuevo y devuelve el resultado bueno a OpenCode; el turno continúa
472
- sin fallar ni mostrar reintentos. Además libera el id anterior, y si el replay no
473
- puede completarse el hook de reintento rota el id para los siguientes pasos. Un
474
- turno que se aborta o falla a mitad de stream marca su `x-session-id` como sucio:
475
- la siguiente petición arranca directamente con un id nuevo y libera el anterior,
476
- de modo que la sesión continúa sin interrupciones y sin pasar por un reintento.
477
- Una compactación también deja el id marcado: el resumen y el turno siguiente se
478
- solapan en el gateway y ese solape producía un 429 `concurrent` y un replay en
479
- cada compactación, así que el turno posterior ya sale con un id nuevo.
480
-
481
- Los fallos de transporte (`ECONNREFUSED`, `ECONNRESET`, `ETIMEDOUT`, DNS
482
- temporal, `socket hang up`) no son límites de cuenta: el plugin los reintenta con
483
- espera exponencial hasta cinco veces más (2 s, 4 s, 8 s, 16 s y 30 s) y marca el
484
- `x-session-id` como sucio para que el siguiente intento use una conexión y un
485
- slot nuevos. Así un corte breve de red, del router o del servicio local de
486
- OpenCode no termina el turno en el segundo intento.
430
+ Los reintentos son de OpenCode: el runner decide si un error se reintenta, con
431
+ qué presupuesto y con qué espera. El plugin no fija delays ni límites de
432
+ intentos y tampoco reenvía la petición. Lo único que hace en el hook de
433
+ reintento es preparar el `x-session-id` de free-pi: si OpenCode va a reintentar,
434
+ marca el id como sucio y el siguiente intento sale con uno nuevo, porque el
435
+ gateway mantiene un slot por sesión y un intento fallido puede dejarlo ocupado.
436
+ Al rotar, el plugin libera el id anterior con `/session/reset`. Un turno
437
+ abortado o interrumpido hace lo mismo para el turno siguiente.
438
+
439
+ Los límites de larga duración (`free_usage_limit`, cupos diarios u horarios,
440
+ créditos, cuenta bloqueada) se reescriben a un `400` con el mensaje amigable;
441
+ OpenCode los trata como un fallo normal y no muestra un «Retrying…» infinito.
487
442
 
488
443
  ## Rutas por plataforma
489
444
 
@@ -202,7 +202,10 @@ async function sendProbe(deps, modelID, chars) {
202
202
  "content-type": "application/json",
203
203
  authorization: `Bearer ${token}`,
204
204
  "x-client-version": deps.state.latestClientVersion,
205
- "x-session-id": `free-pi-window-${Date.now().toString(36)}`,
205
+ "x-session-id": `free-pi-window-${Date.now().toString(36)}-${Math
206
+ .random()
207
+ .toString(36)
208
+ .slice(2, 8)}`,
206
209
  "x-ad-context": "none",
207
210
  },
208
211
  body: JSON.stringify({
@@ -23,7 +23,7 @@ export declare function isReasoningEffort(value: unknown): value is string;
23
23
  /**
24
24
  * The effort sent when no variant is selected. `false` leaves the gateway's
25
25
  * own default untouched; otherwise the catalog's supported levels win over
26
- * `medium`, so a model that only accepts `low`/`high` never gets an effort it
26
+ * `high`, so a model that only accepts `low`/`high` never gets an effort it
27
27
  * would reject.
28
28
  */
29
29
  export declare function preferredReasoningEffort(options: ReasoningOption[] | undefined, configured?: string | false): string | undefined;
@@ -170,7 +170,7 @@ export function isReasoningEffort(value) {
170
170
  /**
171
171
  * The effort sent when no variant is selected. `false` leaves the gateway's
172
172
  * own default untouched; otherwise the catalog's supported levels win over
173
- * `medium`, so a model that only accepts `low`/`high` never gets an effort it
173
+ * `high`, so a model that only accepts `low`/`high` never gets an effort it
174
174
  * would reject.
175
175
  */
176
176
  export function preferredReasoningEffort(options, configured) {
@@ -179,10 +179,21 @@ export function preferredReasoningEffort(options, configured) {
179
179
  if (configured)
180
180
  return configured;
181
181
  // The provider CLI's levels are the source of truth: models.dev often lists
182
- // only a subset, but the gateway accepts the CLI set. `medium` is the sane
183
- // middle ground between the CLI's off default and burning tokens on `high`.
182
+ // only a subset, but the gateway accepts the CLI set. A catalog that lists
183
+ // explicit effort options gets the highest one it lists (a budget-style
184
+ // catalog maps to `high`, the closest explicit level to a token budget);
185
+ // everything else gets the plugin default (`max`), which thinks longest.
184
186
  if (options?.some((option) => option.type === "budget_tokens"))
185
187
  return "high";
188
+ const listed = options
189
+ ?.flatMap((option) => option.type === "effort" && Array.isArray(option.values) ? option.values : [])
190
+ .filter((value) => REASONING_EFFORTS.includes(value));
191
+ if (listed && listed.length > 0) {
192
+ return listed.reduce((best, value) => REASONING_EFFORTS.indexOf(value) >
193
+ REASONING_EFFORTS.indexOf(best)
194
+ ? value
195
+ : best, listed[0]);
196
+ }
186
197
  return DEFAULT_REASONING_EFFORT;
187
198
  }
188
199
  export function accountAccess(me) {
@@ -7,6 +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.28";
9
9
  export declare const CONSENT_VERSION = "4";
10
+ /**
11
+ * The model a fresh session gets when the user has not chosen one. The
12
+ * catalog's own `default_model` points at the fastest cheap model, which is
13
+ * right for the phone app but wrong for coding work: an unset effort makes the
14
+ * free models answer before they think. `glm-5.3-flash` reasons longest of the
15
+ * free models, so it is the better default here; the catalog default stays the
16
+ * fallback when this id ever disappears.
17
+ */
18
+ export declare const DEFAULT_FREE_MODEL_ID = "glm-5.3-flash";
10
19
  /**
11
20
  * The provider CLI's window. The gateway enforces its own ceiling but does not
12
21
  * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
@@ -16,15 +25,6 @@ export declare const CONTEXT_WINDOW = 200000;
16
25
  /** Largest window the plugin will ever advertise after measuring the gateway. */
17
26
  export declare const MAX_CONTEXT_WINDOW = 1000000;
18
27
  export declare const MAX_OUTPUT_TOKENS = 32768;
19
- /**
20
- * Share of the advertised window a primary request may occupy before stale
21
- * tool results are collapsed. Long free-pi sessions reach 100k-170k prompts
22
- * and the free models then lose the middle of the conversation even though the
23
- * gateway still accepts them.
24
- */
25
- export declare const CONTEXT_DIET_SHARE = 0.4;
26
- /** Below this window the diet is pointless: the request is small anyway. */
27
- export declare const CONTEXT_DIET_MIN_TOKENS = 24000;
28
28
  /**
29
29
  * Upper bound for a model that publishes a larger output budget. Reasoning
30
30
  * tokens share this budget, so a model that can emit more must not be pinned to
@@ -47,40 +47,21 @@ export declare const SUBAGENT_HEADER = "x-freepi-subagent";
47
47
  * dozen reasoning tokens even on tasks that need planning. The gateway accepts
48
48
  * every level (measured with curl_cffi) but currently does not let the level
49
49
  * change how long the upstream thinks, so the plugin also asks for explicit
50
- * step-by-step checking in the prompt and defaults to `high`. `none`/`minimal`
51
- * stay one pick away when speed matters more than care.
50
+ * step-by-step checking in the prompt and defaults to `max`. The gateway
51
+ * accepts every level (measured with curl_cffi) and the reasoning_tokens in
52
+ * the usage response vary with the level, so `max` is the level that thinks
53
+ * longest. `none`/`minimal` stay one pick away when speed matters more than
54
+ * care.
52
55
  */
53
- export declare const DEFAULT_REASONING_EFFORT = "high";
56
+ export declare const DEFAULT_REASONING_EFFORT = "max";
54
57
  export declare const REASONING_EFFORTS: readonly ["none", "minimal", "low", "medium", "high", "max"];
55
58
  export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low", "medium", "high", "max"];
56
59
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
57
60
  export declare const HEADER_TIMEOUT_MS = 300000;
58
61
  export declare const CHUNK_TIMEOUT_MS = 300000;
59
- /** pi's retry policy: 3 retries, 2s base, 60s cap. */
60
- export declare const RETRY_MAX_RETRIES = 3;
61
- export declare const RETRY_BASE_DELAY_MS = 2000;
62
- export declare const RETRY_MAX_DELAY_MS = 60000;
63
- /**
64
- * Transport failures (a refused or dropped connection, DNS blips) usually
65
- * clear on their own. OpenCode stops after its own retries, which can end a
66
- * turn during a brief local network or service restart, so the plugin gives
67
- * them a longer budget before giving up.
68
- */
69
- export declare const TRANSPORT_RETRY_MAX = 5;
70
- export declare const TRANSPORT_RETRY_BASE_MS = 2000;
71
- export declare const TRANSPORT_RETRY_MAX_DELAY_MS = 30000;
72
- /**
73
- * free-pi allows one in-flight request per `x-session-id` and answers a second
74
- * one with `429 concurrent`. OpenCode does not retry that itself, and a slot
75
- * can leak server-side, so the plugin rotates the wire session id and retries.
76
- */
77
- export declare const CONCURRENT_RETRY_MAX = 6;
78
- export declare const CONCURRENT_RETRY_BASE_MS = 1000;
79
- export declare const CONCURRENT_RETRY_MAX_DELAY_MS = 15000;
80
62
  /** Tool outcome headers emitted by the free-pi provider CLI. */
81
63
  export declare const TOOL_META_HEADER = "x-freepi-tool-meta";
82
64
  export declare const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
83
- export declare const COMPACTED_HEADER = "x-freepi-compacted";
84
65
  export declare const TOOL_META_BUDGET = 1500;
85
66
  export declare const TOOL_ID_LIMIT = 50;
86
67
  export declare const SESSION_TRACK_LIMIT = 200;
@@ -127,7 +108,6 @@ export declare const REGISTRY_ATTEMPTS = 2;
127
108
  export declare const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
128
109
  export declare const QUOTA_TTL_MS = 30000;
129
110
  export declare const QUOTA_HTTP_TIMEOUT_MS = 5000;
130
- export declare const QUOTA_REFRESH_DEBOUNCE_MS = 1000;
131
111
  export declare const SESSION_RESET_COOLDOWN_MS = 15000;
132
112
  /**
133
113
  * Releasing a server slot is a tiny POST, but a VPN or a proxy adds a round
package/dist/constants.js CHANGED
@@ -7,6 +7,15 @@ export const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
7
7
  export const DEFAULT_BASE_URL = "https://api.freepi.ai";
8
8
  export const DEFAULT_CLIENT_VERSION = "0.6.28";
9
9
  export const CONSENT_VERSION = "4";
10
+ /**
11
+ * The model a fresh session gets when the user has not chosen one. The
12
+ * catalog's own `default_model` points at the fastest cheap model, which is
13
+ * right for the phone app but wrong for coding work: an unset effort makes the
14
+ * free models answer before they think. `glm-5.3-flash` reasons longest of the
15
+ * free models, so it is the better default here; the catalog default stays the
16
+ * fallback when this id ever disappears.
17
+ */
18
+ export const DEFAULT_FREE_MODEL_ID = "glm-5.3-flash";
10
19
  /**
11
20
  * The provider CLI's window. The gateway enforces its own ceiling but does not
12
21
  * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
@@ -16,15 +25,6 @@ export const CONTEXT_WINDOW = 200_000;
16
25
  /** Largest window the plugin will ever advertise after measuring the gateway. */
17
26
  export const MAX_CONTEXT_WINDOW = 1_000_000;
18
27
  export const MAX_OUTPUT_TOKENS = 32_768;
19
- /**
20
- * Share of the advertised window a primary request may occupy before stale
21
- * tool results are collapsed. Long free-pi sessions reach 100k-170k prompts
22
- * and the free models then lose the middle of the conversation even though the
23
- * gateway still accepts them.
24
- */
25
- export const CONTEXT_DIET_SHARE = 0.4;
26
- /** Below this window the diet is pointless: the request is small anyway. */
27
- export const CONTEXT_DIET_MIN_TOKENS = 24_000;
28
28
  /**
29
29
  * Upper bound for a model that publishes a larger output budget. Reasoning
30
30
  * tokens share this budget, so a model that can emit more must not be pinned to
@@ -47,10 +47,13 @@ export const SUBAGENT_HEADER = "x-freepi-subagent";
47
47
  * dozen reasoning tokens even on tasks that need planning. The gateway accepts
48
48
  * every level (measured with curl_cffi) but currently does not let the level
49
49
  * change how long the upstream thinks, so the plugin also asks for explicit
50
- * step-by-step checking in the prompt and defaults to `high`. `none`/`minimal`
51
- * stay one pick away when speed matters more than care.
50
+ * step-by-step checking in the prompt and defaults to `max`. The gateway
51
+ * accepts every level (measured with curl_cffi) and the reasoning_tokens in
52
+ * the usage response vary with the level, so `max` is the level that thinks
53
+ * longest. `none`/`minimal` stay one pick away when speed matters more than
54
+ * care.
52
55
  */
53
- export const DEFAULT_REASONING_EFFORT = "high";
56
+ export const DEFAULT_REASONING_EFFORT = "max";
54
57
  export const REASONING_EFFORTS = [
55
58
  "none",
56
59
  "minimal",
@@ -70,31 +73,9 @@ export const DEFAULT_THINKING_LEVELS = [
70
73
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
71
74
  export const HEADER_TIMEOUT_MS = 300_000;
72
75
  export const CHUNK_TIMEOUT_MS = 300_000;
73
- /** pi's retry policy: 3 retries, 2s base, 60s cap. */
74
- export const RETRY_MAX_RETRIES = 3;
75
- export const RETRY_BASE_DELAY_MS = 2_000;
76
- export const RETRY_MAX_DELAY_MS = 60_000;
77
- /**
78
- * Transport failures (a refused or dropped connection, DNS blips) usually
79
- * clear on their own. OpenCode stops after its own retries, which can end a
80
- * turn during a brief local network or service restart, so the plugin gives
81
- * them a longer budget before giving up.
82
- */
83
- export const TRANSPORT_RETRY_MAX = 5;
84
- export const TRANSPORT_RETRY_BASE_MS = 2_000;
85
- export const TRANSPORT_RETRY_MAX_DELAY_MS = 30_000;
86
- /**
87
- * free-pi allows one in-flight request per `x-session-id` and answers a second
88
- * one with `429 concurrent`. OpenCode does not retry that itself, and a slot
89
- * can leak server-side, so the plugin rotates the wire session id and retries.
90
- */
91
- export const CONCURRENT_RETRY_MAX = 6;
92
- export const CONCURRENT_RETRY_BASE_MS = 1_000;
93
- export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
94
76
  /** Tool outcome headers emitted by the free-pi provider CLI. */
95
77
  export const TOOL_META_HEADER = "x-freepi-tool-meta";
96
78
  export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
97
- export const COMPACTED_HEADER = "x-freepi-compacted";
98
79
  export const TOOL_META_BUDGET = 1_500;
99
80
  export const TOOL_ID_LIMIT = 50;
100
81
  export const SESSION_TRACK_LIMIT = 200;
@@ -143,7 +124,6 @@ export const REGISTRY_ATTEMPTS = 2;
143
124
  export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
144
125
  export const QUOTA_TTL_MS = 30_000;
145
126
  export const QUOTA_HTTP_TIMEOUT_MS = 5_000;
146
- export const QUOTA_REFRESH_DEBOUNCE_MS = 1_000;
147
127
  export const SESSION_RESET_COOLDOWN_MS = 15_000;
148
128
  /**
149
129
  * Releasing a server slot is a tiny POST, but a VPN or a proxy adds a round
package/dist/index.d.ts CHANGED
@@ -4,6 +4,6 @@
4
4
  * Ad-supported free-pi provider plugin for OpenCode V2.
5
5
  */
6
6
  export { FreePiPlugin, default } from "./plugin.js";
7
- export type { Catalog, CatalogModel, FreePiError, FreePiOptions, MeResponse, MeStatsResponse, ModelDefinition, ModelsDevModel, ModelsDevProvider, ModelRegistry, QuotaSnapshot, RequestUsage, } from "./types.js";
7
+ export type { Catalog, CatalogModel, FreePiError, FreePiOptions, MeResponse, MeStatsResponse, ModelDefinition, ModelsDevModel, ModelsDevProvider, ModelRegistry, QuotaSnapshot, } from "./types.js";
8
8
  export { createLogger } from "./logging.js";
9
9
  export type { Logger, LogLevel } from "./logging.js";
package/dist/plugin.js CHANGED
@@ -6,11 +6,10 @@ import { closeFreePiSession } from "./api/session.js";
6
6
  import { readCredentialsToken } from "./auth/credentials.js";
7
7
  import { tokenFromCredential } from "./auth/credential.js";
8
8
  import { fetchCatalog } from "./catalog/catalog.js";
9
- import { currentLiveLimits, loadLiveLimits, shouldVerifyWindow, verifyGatewayWindow, } from "./catalog/live.js";
10
9
  import { accountAccess, buildModels, filterAccessibleModels, isReasoningEffort, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
11
10
  import { fetchModelsRegistry } from "./catalog/registry.js";
12
11
  import { applyProvider } from "./catalog/v2.js";
13
- import { CATALOG_RECOVERY_DELAYS_MS, CATALOG_RECOVERY_INTERVAL_MS, CATALOG_RECOVERY_LOG_EVERY, DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "./constants.js";
12
+ import { CATALOG_RECOVERY_DELAYS_MS, CATALOG_RECOVERY_INTERVAL_MS, CATALOG_RECOVERY_LOG_EVERY, DEFAULT_FREE_MODEL_ID, DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "./constants.js";
14
13
  import { registerIntegration } from "./integration/setup.js";
15
14
  import { createLogger } from "./logging.js";
16
15
  import { applyDirectNetwork } from "./network/direct.js";
@@ -159,10 +158,8 @@ async function setup(ctx) {
159
158
  let currentMain = filterAccessibleModels(catalogMain, access);
160
159
  let currentDefense = filterAccessibleModels(catalogDefense, access);
161
160
  const candidates = modelRegistryCandidates(registry);
162
- const live = await loadLiveLimits();
163
161
  const configuredEffort = ctx.options?.reasoningEffort;
164
162
  const buildOptions = {
165
- live,
166
163
  ...(configuredEffort === false
167
164
  ? { reasoningEffort: false }
168
165
  : isReasoningEffort(configuredEffort)
@@ -182,29 +179,19 @@ async function setup(ctx) {
182
179
  }
183
180
  return kept;
184
181
  };
185
- // Rebuilt on every call so a learned context ceiling or a recovered catalog
186
- // applies without restarting OpenCode.
187
- const buildMain = () => withoutDenied(PROVIDER_ID, buildModels(currentMain, candidates, {
188
- ...buildOptions,
189
- live: currentLiveLimits() ?? live,
190
- }));
191
- const buildDefense = () => withoutDenied(DEFENSE_PROVIDER_ID, buildModels(currentDefense, candidates, {
192
- ...buildOptions,
193
- live: currentLiveLimits() ?? live,
194
- }));
182
+ // Rebuilt on every call so a recovered catalog or a refreshed quota applies
183
+ // without restarting OpenCode.
184
+ const buildMain = () => withoutDenied(PROVIDER_ID, buildModels(currentMain, candidates, buildOptions));
185
+ const buildDefense = () => withoutDenied(DEFENSE_PROVIDER_ID, buildModels(currentDefense, candidates, buildOptions));
195
186
  function indexModelState() {
196
187
  const mainNow = buildMain();
197
188
  const defenseNow = buildDefense();
198
189
  for (const [id, model] of Object.entries(mainNow)) {
199
- state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
200
- state.contextLimits.set(`${PROVIDER_ID}/${id}`, model.limit.context);
201
190
  if (model.modalities.input.includes("image")) {
202
191
  state.imageModels.add(`${PROVIDER_ID}/${id}`);
203
192
  }
204
193
  }
205
194
  for (const [id, model] of Object.entries(defenseNow)) {
206
- state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
207
- state.contextLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.context);
208
195
  if (model.modalities.input.includes("image")) {
209
196
  state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
210
197
  }
@@ -217,7 +204,7 @@ async function setup(ctx) {
217
204
  await registerIntegration(ctx, deps);
218
205
  await ctx.provider.transform((editor) => {
219
206
  // Re-index on every transform: a learned context/output ceiling changes the
220
- // built model, and the diet and maxTokens cap read these maps. Refreshing
207
+ // built model, and the maxTokens cap reads these maps. Refreshing
221
208
  // only at setup would keep budgeting against the old window after a reload.
222
209
  indexModelState();
223
210
  applyProvider(editor, PROVIDER_ID, "Free Pi", buildMain(), state.providerToken);
@@ -225,37 +212,18 @@ async function setup(ctx) {
225
212
  applyProvider(editor, DEFENSE_PROVIDER_ID, "Free Pi Defense", buildDefense(), state.providerToken);
226
213
  }
227
214
  });
228
- // The gateway does not publish its context ceiling. Verify the compiled
229
- // window against it once a week with a free model, in the background, and
230
- // persist the result for the next catalog build. Prefer the free model with
231
- // the largest prompt already accepted in real traffic: it has the most
232
- // evidence behind it, so the growth probes describe the window sessions use.
233
- if (ctx.options?.liveLimits !== false && shouldVerifyWindow(live)) {
234
- const free = currentMain.filter((model) => model.free === true && typeof model.id === "string");
235
- const probe = free
236
- .map((model) => ({
237
- id: model.id,
238
- seen: live?.models[model.id ?? ""]?.maxPromptTokens ?? 0,
239
- }))
240
- .sort((a, b) => b.seen - a.seen)[0]?.id ??
241
- (currentCatalog?.default_model &&
242
- free.some((model) => model.id === currentCatalog?.default_model)
243
- ? currentCatalog.default_model
244
- : undefined) ??
245
- free[0]?.id ??
246
- Object.keys(buildMain())[0];
247
- if (probe) {
248
- void verifyGatewayWindow(deps, { model: probe }).catch(() => undefined);
249
- }
250
- }
251
- // V1 selected the catalog default when the user had no model configured.
215
+ // A fresh session gets the model that reasons longest of the free ones, not
216
+ // the catalog's phone-app default (`particle`, the fastest cheap model). The
217
+ // catalog default stays the fallback for the day this id disappears.
252
218
  await ctx.model.transform((editor) => {
253
219
  if (editor.default.get())
254
220
  return;
255
221
  const models = buildMain();
256
- const preferred = (currentCatalog?.default_model && models[currentCatalog.default_model]
257
- ? currentCatalog.default_model
258
- : undefined) ?? Object.keys(models)[0];
222
+ const preferred = (models[DEFAULT_FREE_MODEL_ID] ? DEFAULT_FREE_MODEL_ID : undefined) ??
223
+ (currentCatalog?.default_model && models[currentCatalog.default_model]
224
+ ? currentCatalog.default_model
225
+ : undefined) ??
226
+ Object.keys(models)[0];
259
227
  if (preferred)
260
228
  editor.default.set(PROVIDER_ID, preferred);
261
229
  });