@eduardo191labs/opencode-free-pi 0.7.25 → 0.7.27
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 +33 -66
- package/dist/catalog/live.js +14 -1
- package/dist/catalog/models.d.ts +1 -1
- package/dist/catalog/models.js +24 -3
- package/dist/constants.d.ts +18 -14
- package/dist/constants.js +19 -15
- package/dist/plugin.js +14 -46
- package/dist/session/hooks.js +116 -205
- 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/state.d.ts +0 -3
- package/dist/state.js +0 -2
- package/dist/tools/vision.js +1 -0
- package/dist/types.d.ts +9 -1
- package/package.json +2 -2
- package/src/catalog/live.ts +14 -1
- package/src/catalog/models.ts +28 -3
- package/src/constants.ts +20 -15
- package/src/plugin.ts +12 -52
- package/src/session/hooks.ts +149 -255
- 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/state.ts +0 -5
- package/src/tools/vision.ts +2 -0
- package/src/types.ts +6 -1
- package/dist/session/diet.d.ts +0 -23
- package/dist/session/diet.js +0 -176
- package/src/session/diet.ts +0 -201
package/README.md
CHANGED
|
@@ -66,53 +66,27 @@ 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.
|
|
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.
|
|
116
90
|
- **Títulos locales**: OpenCode pide un título al modelo al crear una sesión.
|
|
117
91
|
El plugin lo responde con la primera línea del primer mensaje, sin gastar
|
|
118
92
|
créditos, sin pedir un anuncio y sin dejar la sesión atascada en
|
|
@@ -130,7 +104,7 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
130
104
|
- **Subagentes identificados**: las sesiones hijas envían
|
|
131
105
|
`x-freepi-subagent: 1`, igual que los proveedores que el CLI crea para sus
|
|
132
106
|
subagentes.
|
|
133
|
-
- **Pensamiento por defecto**: el plugin pide `reasoning_effort: "
|
|
107
|
+
- **Pensamiento por defecto**: el plugin pide `reasoning_effort: "max"`
|
|
134
108
|
cuando el modelo no trae variante elegida. Dejarlo sin definir hacía que los
|
|
135
109
|
modelos gratuitos respondieran con prisa, gastando apenas unas decenas de
|
|
136
110
|
tokens de razonamiento incluso en tareas que requieren planificar. El
|
|
@@ -140,10 +114,11 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
140
114
|
usan `high` por defecto. La opción `reasoningEffort: false` del plugin
|
|
141
115
|
recupera el nivel del servidor. No se anuncian `thinking_budget` ni
|
|
142
116
|
`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
|
|
117
|
+
- **Más razonamiento real**: medido con `curl_cffi` contra el gateway, subir
|
|
118
|
+
`reasoning_effort` sí alarga el razonamiento (medido: `max` produjo más
|
|
119
|
+
tokens de razonamiento que `high` en la misma tarea), pero los modelos
|
|
120
|
+
`flash` se detienen solos en la primera respuesta plausible, así que el nivel
|
|
121
|
+
solo no basta. Lo que sí
|
|
147
122
|
funciona es pedir el trabajo explícito: con la regla de «escribe cada paso,
|
|
148
123
|
recalcula por un segundo método y no respondas hasta que coincidan», el mismo
|
|
149
124
|
modelo subió de ~450 a ~1250 tokens de razonamiento y acertó 5/5 problemas de
|
|
@@ -155,25 +130,17 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
155
130
|
publica el upstream (32k por defecto, hasta 131k). No se fuerza temperatura ni
|
|
156
131
|
`top_p`: la petición real no los incluye, así que el gateway aplica su propio
|
|
157
132
|
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,
|
|
133
|
+
- **El razonamiento guardado se conserva**: el historial se envía tal como
|
|
134
|
+
OpenCode lo guarda, incluido el `reasoning_content` de cada turno. Borrarlo
|
|
135
|
+
para ahorrar tokens hacía que un modelo de razonamiento perdiera el motivo de
|
|
136
|
+
sus decisiones y repitiera la misma acción.
|
|
137
|
+
- **Límites declarados por el catálogo**: `/client-version` solo devuelve id,
|
|
165
138
|
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.
|
|
139
|
+
capacidades ni de ventana. El plugin anuncia los límites que el catálogo
|
|
140
|
+
publica y deja el resto a OpenCode. Lo único que se aprende en vivo, sin
|
|
141
|
+
coste, es el techo de un modelo cuando el gateway rechaza una petición real
|
|
142
|
+
por longitud; ese dato se guarda en `live-limits.json` para que la siguiente
|
|
143
|
+
compactación empiece antes.
|
|
177
144
|
Además, cuando una herramienta falla por un motivo que el modelo repite (un
|
|
178
145
|
heredoc rechazado por el scanner del shell, un `edit` con cadenas idénticas o
|
|
179
146
|
con un `oldString` ambiguo), el error que recibe añade el siguiente paso
|
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({
|
|
@@ -259,6 +262,16 @@ export function settleWindow(samples) {
|
|
|
259
262
|
*/
|
|
260
263
|
async function commitWindow(deps, tokens, modelID) {
|
|
261
264
|
const limits = (cached ??= emptyLimits());
|
|
265
|
+
// The measured ceiling belongs to the model probed, not to every model: the
|
|
266
|
+
// gateway's limit is per model, and a global window taken from one model
|
|
267
|
+
// would advertise capacity another one rejects. The per-model value is what
|
|
268
|
+
// `buildModels` reads for that model; the global window stays as the
|
|
269
|
+
// fallback for models never probed.
|
|
270
|
+
const entry = observation(modelID);
|
|
271
|
+
if ((entry.maxPromptTokens ?? 0) < tokens) {
|
|
272
|
+
entry.maxPromptTokens = tokens;
|
|
273
|
+
entry.updatedAt = Date.now();
|
|
274
|
+
}
|
|
262
275
|
if (limits.window && limits.window.tokens >= tokens)
|
|
263
276
|
return limits.window.tokens;
|
|
264
277
|
limits.window = { tokens, verifiedAt: Date.now(), model: modelID };
|
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) {
|
|
@@ -203,6 +214,16 @@ export function accountAccess(me) {
|
|
|
203
214
|
};
|
|
204
215
|
}
|
|
205
216
|
function isPremiumModel(model) {
|
|
217
|
+
// The catalog's `access` field is the authoritative lane. `premium_only`
|
|
218
|
+
// means exactly what the name says; before the field existed the only clues
|
|
219
|
+
// were `tier`, the note and the "at capacity" label, and a curl_cffi probe
|
|
220
|
+
// showed those missed 18 of the 19 premium-only models (no tier, empty note,
|
|
221
|
+
// plain "~Nx usage" names). Keep the old heuristics for catalogs that still
|
|
222
|
+
// omit `access`.
|
|
223
|
+
if (model.access === "premium_only")
|
|
224
|
+
return true;
|
|
225
|
+
if (model.access === "free" || model.access === "free_unlimited")
|
|
226
|
+
return false;
|
|
206
227
|
if (model.tier === "premium")
|
|
207
228
|
return true;
|
|
208
229
|
if (/premium\s+credits/i.test(model.note ?? ""))
|
package/dist/constants.d.ts
CHANGED
|
@@ -5,8 +5,17 @@ export declare const INTEGRATION_ID = "free-pi";
|
|
|
5
5
|
export declare const PROVIDER_NAME = "Free Pi";
|
|
6
6
|
export declare const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
|
|
7
7
|
export declare const DEFAULT_BASE_URL = "https://api.freepi.ai";
|
|
8
|
-
export declare const DEFAULT_CLIENT_VERSION = "0.6.
|
|
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,10 +47,13 @@ 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. */
|
|
@@ -80,13 +83,14 @@ export declare const CONCURRENT_RETRY_MAX_DELAY_MS = 15000;
|
|
|
80
83
|
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
81
84
|
export declare const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
82
85
|
export declare const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
83
|
-
export declare const COMPACTED_HEADER = "x-freepi-compacted";
|
|
84
86
|
export declare const TOOL_META_BUDGET = 1500;
|
|
85
87
|
export declare const TOOL_ID_LIMIT = 50;
|
|
86
88
|
export declare const SESSION_TRACK_LIMIT = 200;
|
|
87
89
|
export declare const AUTH_SKEW_MS = 60000;
|
|
88
90
|
export declare const AUTH_TIMEOUT_MS: number;
|
|
89
91
|
export declare const AUTH_NETWORK_FAILURES = 6;
|
|
92
|
+
/** Fallback token lifetime when the JWT carries no `exp`. Measured free-pi
|
|
93
|
+
* tokens live 90 days; this fallback only applies when the header is missing. */
|
|
90
94
|
export declare const DEFAULT_TOKEN_LIFETIME_MS: number;
|
|
91
95
|
export declare const REFRESH_PREFIX = "free-pi:v1:";
|
|
92
96
|
export declare const AD_CONTEXT_MAX_CHARS = 1000;
|
package/dist/constants.js
CHANGED
|
@@ -5,8 +5,17 @@ export const INTEGRATION_ID = PROVIDER_ID;
|
|
|
5
5
|
export const PROVIDER_NAME = "Free Pi";
|
|
6
6
|
export const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
|
|
7
7
|
export const DEFAULT_BASE_URL = "https://api.freepi.ai";
|
|
8
|
-
export const DEFAULT_CLIENT_VERSION = "0.6.
|
|
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",
|
|
@@ -94,14 +97,15 @@ export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
|
|
|
94
97
|
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
95
98
|
export const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
96
99
|
export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
97
|
-
export const COMPACTED_HEADER = "x-freepi-compacted";
|
|
98
100
|
export const TOOL_META_BUDGET = 1_500;
|
|
99
101
|
export const TOOL_ID_LIMIT = 50;
|
|
100
102
|
export const SESSION_TRACK_LIMIT = 200;
|
|
101
103
|
export const AUTH_SKEW_MS = 60_000;
|
|
102
104
|
export const AUTH_TIMEOUT_MS = 15 * 60_000;
|
|
103
105
|
export const AUTH_NETWORK_FAILURES = 6;
|
|
104
|
-
|
|
106
|
+
/** Fallback token lifetime when the JWT carries no `exp`. Measured free-pi
|
|
107
|
+
* tokens live 90 days; this fallback only applies when the header is missing. */
|
|
108
|
+
export const DEFAULT_TOKEN_LIFETIME_MS = 90 * 24 * 60 * 60_000;
|
|
105
109
|
export const REFRESH_PREFIX = "free-pi:v1:";
|
|
106
110
|
export const AD_CONTEXT_MAX_CHARS = 1_000;
|
|
107
111
|
export const AD_REQUEST_TIMEOUT_MS = 5_000;
|
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
|
});
|