@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.
- package/README.md +60 -105
- package/dist/catalog/live.js +4 -1
- package/dist/catalog/models.d.ts +1 -1
- package/dist/catalog/models.js +14 -3
- package/dist/constants.d.ts +15 -35
- package/dist/constants.js +15 -35
- package/dist/index.d.ts +1 -1
- package/dist/plugin.js +14 -46
- package/dist/session/events.js +5 -12
- package/dist/session/hooks.js +83 -348
- package/dist/session/overflow.d.ts +7 -28
- package/dist/session/overflow.js +7 -73
- package/dist/session/replay.d.ts +8 -41
- package/dist/session/replay.js +9 -148
- package/dist/session/tools.d.ts +2 -7
- package/dist/session/tools.js +3 -18
- package/dist/session/trace.js +0 -1
- package/dist/session/track.d.ts +2 -0
- package/dist/session/track.js +5 -0
- package/dist/state.d.ts +1 -6
- package/dist/state.js +0 -2
- package/dist/tools/vision.js +1 -0
- package/dist/types.d.ts +0 -1
- package/package.json +2 -2
- package/src/catalog/live.ts +4 -1
- package/src/catalog/models.ts +20 -3
- package/src/constants.ts +16 -38
- package/src/index.ts +0 -1
- package/src/plugin.ts +12 -52
- package/src/session/events.ts +5 -12
- package/src/session/hooks.ts +109 -431
- package/src/session/overflow.ts +7 -77
- package/src/session/replay.ts +12 -188
- package/src/session/tools.ts +1 -22
- package/src/session/trace.ts +0 -1
- package/src/session/track.ts +11 -0
- package/src/state.ts +0 -8
- package/src/tools/vision.ts +2 -0
- package/src/types.ts +0 -1
- package/dist/session/diet.d.ts +0 -23
- package/dist/session/diet.js +0 -176
- package/dist/session/title.d.ts +0 -18
- package/dist/session/title.js +0 -81
- package/dist/session/usage.d.ts +0 -5
- package/dist/session/usage.js +0 -32
- package/src/session/diet.ts +0 -201
- package/src/session/title.ts +0 -90
- 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
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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
|
-
- **
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
clasifica como desbordamiento, para no gastar
|
|
115
|
-
arreglan nada.
|
|
116
|
-
- **Títulos
|
|
117
|
-
El plugin
|
|
118
|
-
|
|
119
|
-
|
|
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: "
|
|
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,
|
|
144
|
-
`reasoning_effort`
|
|
145
|
-
|
|
146
|
-
`flash` se detienen solos en la primera respuesta plausible
|
|
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
|
-
- **
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
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
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
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)
|
|
426
|
-
herramientas fallidas) y
|
|
427
|
-
|
|
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
|
|
445
|
-
proveedor
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
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
|
|
455
|
-
|
|
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
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
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
|
|
package/dist/catalog/live.js
CHANGED
|
@@ -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({
|
package/dist/catalog/models.d.ts
CHANGED
|
@@ -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
|
-
* `
|
|
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;
|
package/dist/catalog/models.js
CHANGED
|
@@ -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
|
-
* `
|
|
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.
|
|
183
|
-
//
|
|
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) {
|
package/dist/constants.d.ts
CHANGED
|
@@ -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 `
|
|
51
|
-
*
|
|
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 = "
|
|
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 `
|
|
51
|
-
*
|
|
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 = "
|
|
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,
|
|
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
|
|
186
|
-
//
|
|
187
|
-
const buildMain = () => withoutDenied(PROVIDER_ID, buildModels(currentMain, candidates,
|
|
188
|
-
|
|
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
|
|
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
|
-
//
|
|
229
|
-
//
|
|
230
|
-
//
|
|
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 = (
|
|
257
|
-
|
|
258
|
-
|
|
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
|
});
|