@eduardo191labs/opencode-free-pi 0.6.0 → 0.6.3
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 +40 -25
- package/dist/catalog/live.d.ts +21 -5
- package/dist/catalog/live.js +116 -32
- package/dist/catalog/models.d.ts +6 -0
- package/dist/catalog/models.js +65 -17
- package/dist/catalog/v2.js +5 -7
- package/dist/constants.d.ts +17 -6
- package/dist/constants.js +17 -4
- package/dist/plugin.js +15 -3
- package/dist/session/hooks.js +4 -2
- package/package.json +1 -1
- package/src/catalog/live.ts +132 -32
- package/src/catalog/models.ts +78 -16
- package/src/catalog/v2.ts +5 -7
- package/src/constants.ts +17 -4
- package/src/plugin.ts +17 -3
- package/src/session/hooks.ts +4 -1
package/README.md
CHANGED
|
@@ -66,11 +66,14 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
66
66
|
- Catálogo en vivo de modelos **free-pi** y **free-pi-defense**.
|
|
67
67
|
- Integración nativa de OpenCode V2 para credenciales OAuth, clave y entorno.
|
|
68
68
|
- Cuota diaria, créditos premium y límites con mensajes claros.
|
|
69
|
-
- **Límites reales de free-pi**: todos los modelos
|
|
69
|
+
- **Límites reales de free-pi**: todos los modelos parten de la ventana de
|
|
70
70
|
contexto de 200k y el límite de salida de 32k que aplica el CLI del
|
|
71
71
|
proveedor, aunque models.dev informe ventanas mayores para el modelo
|
|
72
|
-
upstream.
|
|
73
|
-
|
|
72
|
+
upstream. El plugin sube la ventana midiendo lo que el gateway acepta de
|
|
73
|
+
verdad (hasta 1M) y deja que los modelos con más presupuesto de salida usen
|
|
74
|
+
hasta 131k, para que el razonamiento no se corte. Así OpenCode compacta antes
|
|
75
|
+
de que el servidor rechace la conversación y aun así aprovecha la capacidad
|
|
76
|
+
real de la cuenta.
|
|
74
77
|
- **Compactación integrada**: los errores `context_too_long` de free-pi se
|
|
75
78
|
reescriben para que OpenCode los reconozca como desbordamiento de contexto y
|
|
76
79
|
ejecute `/compact` automáticamente en vez de terminar el turno.
|
|
@@ -84,38 +87,50 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
84
87
|
El plugin lo responde con la primera línea del primer mensaje, sin gastar
|
|
85
88
|
créditos, sin pedir un anuncio y sin dejar la sesión atascada en
|
|
86
89
|
«New session».
|
|
87
|
-
- **
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
tokens de imagen
|
|
92
|
-
aplica el mismo aviso al terminar la herramienta para que
|
|
93
|
-
guardado en la sesión
|
|
94
|
-
|
|
90
|
+
- **Capacidades según el modelo**: los modelos que models.dev identifica como
|
|
91
|
+
multimodales anuncian entrada de imágenes y el gateway las reenvía al modelo
|
|
92
|
+
upstream. Los modelos de solo texto siguen usando `look_at_image`, porque
|
|
93
|
+
incrustar cada imagen leída (cientos de KB) en la conversación desborda la
|
|
94
|
+
ventana y gasta cuota en tokens de imagen; OpenCode sustituye las imágenes por
|
|
95
|
+
un aviso y el plugin aplica el mismo aviso al terminar la herramienta para que
|
|
96
|
+
el base64 no quede guardado en la sesión. La salida es siempre texto: la ruta
|
|
97
|
+
de chat no devuelve imágenes.
|
|
95
98
|
- **Subagentes identificados**: las sesiones hijas envían
|
|
96
99
|
`x-freepi-subagent: 1`, igual que los proveedores que el CLI crea para sus
|
|
97
100
|
subagentes.
|
|
98
|
-
- **Pensamiento por defecto**: el plugin pide `reasoning_effort: "
|
|
101
|
+
- **Pensamiento por defecto**: el plugin pide `reasoning_effort: "high"`
|
|
99
102
|
cuando el modelo no trae variante elegida. Dejarlo sin definir hacía que los
|
|
100
103
|
modelos gratuitos respondieran con prisa, gastando apenas unas decenas de
|
|
101
104
|
tokens de razonamiento incluso en tareas que requieren planificar. El
|
|
102
|
-
selector ofrece siempre
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
105
|
+
selector ofrece siempre los seis niveles que el gateway acepta —`none`,
|
|
106
|
+
`minimal`, `low`, `medium`, `high` y `max`—, para todos los modelos, y el
|
|
107
|
+
mismo conjunto se anuncia en `reasoning_options`; los modelos de presupuesto
|
|
108
|
+
usan `high` por defecto. La opción `reasoningEffort: false` del plugin
|
|
109
|
+
recupera el nivel del servidor. No se anuncian `thinking_budget` ni
|
|
106
110
|
`thinking`, porque la ruta `openai-compatible` de OpenCode los descarta.
|
|
111
|
+
- **Más razonamiento real**: medido con `curl_cffi` contra el gateway, cambiar
|
|
112
|
+
`reasoning_effort` no altera cuánto piensa el modelo (los tokens de
|
|
113
|
+
razonamiento varían al azar entre ~60 y ~600 en cada nivel) y los modelos
|
|
114
|
+
`flash` se detienen solos en la primera respuesta plausible. Lo que sí
|
|
115
|
+
funciona es pedir el trabajo explícito: con la regla de «escribe cada paso,
|
|
116
|
+
recalcula por un segundo método y no respondas hasta que coincidan», el mismo
|
|
117
|
+
modelo subió de ~450 a ~1250 tokens de razonamiento y acertó 5/5 problemas de
|
|
118
|
+
lógica frente a 3/5 sin la regla. Por eso la guía de trabajo prioriza la
|
|
119
|
+
respuesta lenta y verificada, y el límite de salida se deja amplio para que
|
|
120
|
+
esa cadena no se trunque.
|
|
107
121
|
- **Capacidades iguales al CLI**: todos los modelos se registran con
|
|
108
|
-
razonamiento activo,
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
aplica su propio valor. El prompt se envía con rol `system`, no `developer`.
|
|
122
|
+
razonamiento activo, coste cero, la ventana medida y el límite de salida que
|
|
123
|
+
publica el upstream (32k por defecto, hasta 131k). No se fuerza temperatura ni
|
|
124
|
+
`top_p`: la petición real no los incluye, así que el gateway aplica su propio
|
|
125
|
+
valor. El prompt se envía con rol `system`, no `developer`.
|
|
113
126
|
- **Límites medidos, no inventados**: `/client-version` solo devuelve id,
|
|
114
127
|
nombre, `free`, `section`, `note`, `stats_id` y `usage_x`; no hay endpoint de
|
|
115
|
-
capacidades ni de ventana. El plugin no se queda en constantes:
|
|
116
|
-
ventana
|
|
117
|
-
|
|
118
|
-
|
|
128
|
+
capacidades ni de ventana. El plugin no se queda en constantes: confirma la
|
|
129
|
+
ventana compilada y después la agranda mientras el gateway acepte prompts
|
|
130
|
+
mayores, con búsqueda binaria al primer rechazo y un 3 % de margen. Guarda el
|
|
131
|
+
resultado en `live-limits.json` y anota en cada paso los tokens de prompt y de
|
|
132
|
+
razonamiento que el servidor confirma. `liveLimits: false` desactiva la
|
|
133
|
+
comprobación y deja la ventana compilada.
|
|
119
134
|
- **Reglas de trabajo en el prompt**: cada petición principal de free-pi añade
|
|
120
135
|
un bloque corto al system prompt con lo que los modelos gratuitos suelen
|
|
121
136
|
omitir: leer antes de editar, ejecutar las comprobaciones de verdad, no
|
package/dist/catalog/live.d.ts
CHANGED
|
@@ -43,13 +43,29 @@ export declare function shouldVerifyWindow(limits: LiveLimits | undefined): bool
|
|
|
43
43
|
export type VerifyLimitsOptions = {
|
|
44
44
|
/** A free model to probe with; paid models would spend credits. */
|
|
45
45
|
model?: string;
|
|
46
|
-
/** Window to check. Defaults to the compiled one. */
|
|
46
|
+
/** Window to check. Defaults to the measured one, then the compiled one. */
|
|
47
47
|
window?: number;
|
|
48
48
|
};
|
|
49
|
+
/** One gateway answer used to settle the advertised window. */
|
|
50
|
+
export type ProbeSample = {
|
|
51
|
+
chars: number;
|
|
52
|
+
/** Prompt tokens the gateway reported for an accepted probe. */
|
|
53
|
+
tokens?: number;
|
|
54
|
+
tooLong: boolean;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Largest window the accepted probes prove, with headroom. Pure so the probe
|
|
58
|
+
* loop and the persisted value can be tested without a server.
|
|
59
|
+
*/
|
|
60
|
+
export declare function settleWindow(samples: readonly ProbeSample[]): number | undefined;
|
|
49
61
|
/**
|
|
50
|
-
* Checks the compiled window against the gateway
|
|
51
|
-
*
|
|
52
|
-
* the
|
|
53
|
-
*
|
|
62
|
+
* Checks the compiled window against the gateway and then grows past it while
|
|
63
|
+
* the gateway keeps accepting larger prompts. The start value is a floor, not a
|
|
64
|
+
* ceiling: the server has no endpoint for its real limit, and pinning sessions
|
|
65
|
+
* to the CLI's 200k wastes capacity the account can actually use. On rejection
|
|
66
|
+
* it binary-searches between the largest accepted prompt and the rejected one,
|
|
67
|
+
* so the next catalog build advertises the measured window. Returns the verified
|
|
68
|
+
* window, or `undefined` when nothing could be learned (the previous value is
|
|
69
|
+
* kept).
|
|
54
70
|
*/
|
|
55
71
|
export declare function verifyGatewayWindow(deps: Deps, options?: VerifyLimitsOptions): Promise<number | undefined>;
|
package/dist/catalog/live.js
CHANGED
|
@@ -18,6 +18,14 @@ const FILE = "live-limits.json";
|
|
|
18
18
|
const WRITE_DEBOUNCE_MS = 2_000;
|
|
19
19
|
/** Verification stops shrinking here instead of advertising a useless window. */
|
|
20
20
|
const MIN_WINDOW = 32_768;
|
|
21
|
+
/** Hard stop for the upward search; `buildModels` never advertises more. */
|
|
22
|
+
const MAX_WINDOW = 1_000_000;
|
|
23
|
+
/** Keep headroom under the exact ceiling so a fresh turn never hits a 413. */
|
|
24
|
+
const WINDOW_SAFETY = 0.97;
|
|
25
|
+
/** Probe requests per verification, counting the initial confirmation. */
|
|
26
|
+
const MAX_PROBES = 6;
|
|
27
|
+
/** OpenCode budgets four characters per token; correct it after the first probe. */
|
|
28
|
+
const INITIAL_CHARS_PER_TOKEN = 4;
|
|
21
29
|
let cached;
|
|
22
30
|
let loaded = false;
|
|
23
31
|
let writeTimer;
|
|
@@ -185,45 +193,121 @@ async function sendProbe(deps, modelID, chars) {
|
|
|
185
193
|
};
|
|
186
194
|
}
|
|
187
195
|
/**
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
|
|
191
|
-
|
|
196
|
+
* Largest window the accepted probes prove, with headroom. Pure so the probe
|
|
197
|
+
* loop and the persisted value can be tested without a server.
|
|
198
|
+
*/
|
|
199
|
+
export function settleWindow(samples) {
|
|
200
|
+
let best = 0;
|
|
201
|
+
for (const sample of samples) {
|
|
202
|
+
if (sample.tooLong)
|
|
203
|
+
continue;
|
|
204
|
+
if (!Number.isFinite(sample.tokens) || (sample.tokens ?? 0) <= 0)
|
|
205
|
+
continue;
|
|
206
|
+
if (sample.tokens <= best)
|
|
207
|
+
continue;
|
|
208
|
+
best = sample.tokens;
|
|
209
|
+
}
|
|
210
|
+
if (best === 0)
|
|
211
|
+
return undefined;
|
|
212
|
+
return Math.min(MAX_WINDOW, Math.max(MIN_WINDOW, Math.floor((best * WINDOW_SAFETY) / 1_000) * 1_000));
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Stores a measured window and writes it immediately. Called after every
|
|
216
|
+
* accepted probe, so a process that exits mid-verification keeps the smallest
|
|
217
|
+
* proven value instead of losing the whole run.
|
|
218
|
+
*/
|
|
219
|
+
async function commitWindow(deps, tokens, modelID) {
|
|
220
|
+
const limits = (cached ??= emptyLimits());
|
|
221
|
+
if (limits.window && limits.window.tokens >= tokens)
|
|
222
|
+
return limits.window.tokens;
|
|
223
|
+
limits.window = { tokens, verifiedAt: Date.now(), model: modelID };
|
|
224
|
+
loaded = true;
|
|
225
|
+
await persist();
|
|
226
|
+
return tokens;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Checks the compiled window against the gateway and then grows past it while
|
|
230
|
+
* the gateway keeps accepting larger prompts. The start value is a floor, not a
|
|
231
|
+
* ceiling: the server has no endpoint for its real limit, and pinning sessions
|
|
232
|
+
* to the CLI's 200k wastes capacity the account can actually use. On rejection
|
|
233
|
+
* it binary-searches between the largest accepted prompt and the rejected one,
|
|
234
|
+
* so the next catalog build advertises the measured window. Returns the verified
|
|
235
|
+
* window, or `undefined` when nothing could be learned (the previous value is
|
|
236
|
+
* kept).
|
|
192
237
|
*/
|
|
193
238
|
export async function verifyGatewayWindow(deps, options = {}) {
|
|
194
239
|
const modelID = options.model;
|
|
195
240
|
if (!modelID)
|
|
196
241
|
return undefined;
|
|
197
|
-
const
|
|
198
|
-
|
|
199
|
-
// prompt
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
242
|
+
const fallback = options.window ?? cached?.window?.tokens ?? CONTEXT_WINDOW;
|
|
243
|
+
const samples = [];
|
|
244
|
+
// Accepted prompt tokens; also the lower bound of the binary search.
|
|
245
|
+
let accepted = 0;
|
|
246
|
+
let charsPerToken = INITIAL_CHARS_PER_TOKEN;
|
|
247
|
+
let target = Math.max(MIN_WINDOW, Math.min(fallback, MAX_WINDOW));
|
|
248
|
+
let verified;
|
|
249
|
+
const floor = Math.min(fallback, CONTEXT_WINDOW);
|
|
250
|
+
for (let attempt = 0; attempt < MAX_PROBES; attempt += 1) {
|
|
251
|
+
const chars = Math.max(MIN_WINDOW * charsPerToken, Math.floor(target * charsPerToken * 0.99));
|
|
207
252
|
const result = await sendProbe(deps, modelID, chars);
|
|
208
|
-
if (result.status === "failed")
|
|
209
|
-
|
|
210
|
-
|
|
253
|
+
if (result.status === "failed") {
|
|
254
|
+
// A network failure or a rejected body proves nothing; keep what the
|
|
255
|
+
// earlier probes already established.
|
|
256
|
+
if (samples.length === 0)
|
|
257
|
+
return verified;
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
if (result.status === "too_long") {
|
|
261
|
+
samples.push({ chars, tooLong: true });
|
|
262
|
+
if (accepted === 0) {
|
|
263
|
+
// The compiled window itself is too large: step down as before.
|
|
264
|
+
target = Math.floor(target * 0.85);
|
|
265
|
+
if (target < MIN_WINDOW)
|
|
266
|
+
break;
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
const next = Math.floor((accepted + target) / 2);
|
|
270
|
+
if (next <= accepted)
|
|
271
|
+
break;
|
|
272
|
+
target = next;
|
|
211
273
|
continue;
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
await persist();
|
|
219
|
-
deps.log.info("free-pi verified the gateway context window", {
|
|
220
|
-
model: modelID,
|
|
221
|
-
window: verified,
|
|
222
|
-
compiled: window,
|
|
223
|
-
probedChars: chars,
|
|
224
|
-
probedTokens: result.promptTokens,
|
|
274
|
+
}
|
|
275
|
+
const tokens = result.promptTokens;
|
|
276
|
+
samples.push({
|
|
277
|
+
chars,
|
|
278
|
+
tooLong: false,
|
|
279
|
+
...(tokens && tokens > 0 ? { tokens } : {}),
|
|
225
280
|
});
|
|
226
|
-
|
|
281
|
+
if (tokens && tokens > 0) {
|
|
282
|
+
accepted = tokens;
|
|
283
|
+
// Learn the real characters-per-token ratio for this prompt shape; the
|
|
284
|
+
// filler is prose, and four chars/token overshoots badly.
|
|
285
|
+
charsPerToken = chars / tokens;
|
|
286
|
+
}
|
|
287
|
+
else {
|
|
288
|
+
accepted = Math.floor(chars / charsPerToken);
|
|
289
|
+
}
|
|
290
|
+
const settled = settleWindow(samples);
|
|
291
|
+
if (settled) {
|
|
292
|
+
// Never go below the window that already worked for this account.
|
|
293
|
+
verified = await commitWindow(deps, Math.max(settled, floor), modelID);
|
|
294
|
+
}
|
|
295
|
+
if (accepted >= MAX_WINDOW)
|
|
296
|
+
break;
|
|
297
|
+
const next = Math.min(MAX_WINDOW, Math.floor(accepted * 1.2));
|
|
298
|
+
if (next <= accepted)
|
|
299
|
+
break;
|
|
300
|
+
target = next;
|
|
227
301
|
}
|
|
228
|
-
|
|
302
|
+
if (!verified)
|
|
303
|
+
return undefined;
|
|
304
|
+
deps.log.info("free-pi verified the gateway context window", {
|
|
305
|
+
model: modelID,
|
|
306
|
+
window: verified,
|
|
307
|
+
compiled: fallback,
|
|
308
|
+
probes: samples.length,
|
|
309
|
+
acceptedTokens: accepted,
|
|
310
|
+
charsPerToken: Number(charsPerToken.toFixed(2)),
|
|
311
|
+
});
|
|
312
|
+
return verified;
|
|
229
313
|
}
|
package/dist/catalog/models.d.ts
CHANGED
|
@@ -13,6 +13,12 @@ export declare function modelCost(_model: CatalogModel, _capability?: ModelsDevM
|
|
|
13
13
|
export declare function modelRegistryCandidates(registry: ModelRegistry | undefined): RegistryCandidate[];
|
|
14
14
|
export declare function modelCapability(model: CatalogModel, candidates: RegistryCandidate[]): ModelsDevModel | undefined;
|
|
15
15
|
export declare function modelVariants(options: ReasoningOption[] | undefined, _outputLimit: number): VariantMap;
|
|
16
|
+
/**
|
|
17
|
+
* The levels the model actually exposes, so OpenCode's picker and the
|
|
18
|
+
* `reasoning_effort` values the plugin sends come from the same list. The
|
|
19
|
+
* gateway accepts every level for every model, so the CLI set always applies.
|
|
20
|
+
*/
|
|
21
|
+
export declare function effectiveReasoningOptions(options: ReasoningOption[] | undefined, variants: VariantMap): ReasoningOption[];
|
|
16
22
|
export declare function isReasoningEffort(value: unknown): value is string;
|
|
17
23
|
/**
|
|
18
24
|
* The effort sent when no variant is selected. `false` leaves the gateway's
|
package/dist/catalog/models.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
|
-
import { CONTEXT_WINDOW, DEFAULT_REASONING_EFFORT, DEFAULT_THINKING_LEVELS, MAX_OUTPUT_TOKENS, REASONING_EFFORTS, } from "../constants.js";
|
|
2
|
+
import { CONTEXT_WINDOW, DEFAULT_REASONING_EFFORT, DEFAULT_THINKING_LEVELS, MAX_CONTEXT_WINDOW, MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING, REASONING_EFFORTS, } from "../constants.js";
|
|
3
3
|
import { positiveNumber } from "../utils/numbers.js";
|
|
4
4
|
import { cleanText } from "../utils/text.js";
|
|
5
5
|
export function usableModels(catalog) {
|
|
@@ -129,7 +129,8 @@ export function modelVariants(options, _outputLimit) {
|
|
|
129
129
|
// The provider CLI registers every model with `reasoning: true` and an unset
|
|
130
130
|
// `thinkingLevelMap`, so it offers these levels to every model. models.dev
|
|
131
131
|
// lists fewer levels for some upstream models, but the gateway accepts the
|
|
132
|
-
// CLI's set, and hiding levels only makes the picker
|
|
132
|
+
// CLI's set (including `max`), and hiding levels only makes the picker
|
|
133
|
+
// disagree with the CLI.
|
|
133
134
|
const variants = {};
|
|
134
135
|
for (const level of DEFAULT_THINKING_LEVELS) {
|
|
135
136
|
variants[level] = { reasoningEffort: level };
|
|
@@ -147,6 +148,20 @@ export function modelVariants(options, _outputLimit) {
|
|
|
147
148
|
}
|
|
148
149
|
return variants;
|
|
149
150
|
}
|
|
151
|
+
/**
|
|
152
|
+
* The levels the model actually exposes, so OpenCode's picker and the
|
|
153
|
+
* `reasoning_effort` values the plugin sends come from the same list. The
|
|
154
|
+
* gateway accepts every level for every model, so the CLI set always applies.
|
|
155
|
+
*/
|
|
156
|
+
export function effectiveReasoningOptions(options, variants) {
|
|
157
|
+
const values = Object.keys(variants);
|
|
158
|
+
const declared = options?.find((option) => option.type === "effort")?.values;
|
|
159
|
+
for (const value of declared ?? []) {
|
|
160
|
+
if (!values.includes(value))
|
|
161
|
+
values.push(value);
|
|
162
|
+
}
|
|
163
|
+
return values.length > 0 ? [{ type: "effort", values }] : [];
|
|
164
|
+
}
|
|
150
165
|
export function isReasoningEffort(value) {
|
|
151
166
|
return (typeof value === "string" &&
|
|
152
167
|
REASONING_EFFORTS.includes(value));
|
|
@@ -206,6 +221,29 @@ export function filterAccessibleModels(models, access) {
|
|
|
206
221
|
return access.hasAllowance || access.walletCredits > 0;
|
|
207
222
|
});
|
|
208
223
|
}
|
|
224
|
+
const KNOWN_INPUT_MODALITIES = new Set([
|
|
225
|
+
"text",
|
|
226
|
+
"image",
|
|
227
|
+
"audio",
|
|
228
|
+
"video",
|
|
229
|
+
"pdf",
|
|
230
|
+
]);
|
|
231
|
+
/**
|
|
232
|
+
* Native modalities for the chat route. models.dev describes the upstream
|
|
233
|
+
* model, and the gateway forwards image parts to multimodal upstreams, so an
|
|
234
|
+
* image-capable model is advertised as such. Output is always text: free-pi has
|
|
235
|
+
* no image results on the chat route, and the plugin registers every model as
|
|
236
|
+
* zero-cost text output.
|
|
237
|
+
*/
|
|
238
|
+
function modelModalities(model, capability) {
|
|
239
|
+
const declared = model.modalities?.input ?? capability?.modalities?.input;
|
|
240
|
+
const input = (declared ?? ["text"]).filter((value) => KNOWN_INPUT_MODALITIES.has(value));
|
|
241
|
+
if (input.length === 0)
|
|
242
|
+
input.push("text");
|
|
243
|
+
if (!input.includes("text"))
|
|
244
|
+
input.unshift("text");
|
|
245
|
+
return { input, output: ["text"] };
|
|
246
|
+
}
|
|
209
247
|
export function buildModels(models, candidates = [], options = {}) {
|
|
210
248
|
const result = {};
|
|
211
249
|
for (const model of models) {
|
|
@@ -220,17 +258,28 @@ export function buildModels(models, candidates = [], options = {}) {
|
|
|
220
258
|
// free-pi enforces a context window on every model regardless of what
|
|
221
259
|
// models.dev reports for the upstream provider. The provider CLI starts at
|
|
222
260
|
// 200k, but the gateway does not publish its ceiling: `verifyGatewayWindow`
|
|
223
|
-
// measures it
|
|
224
|
-
//
|
|
225
|
-
//
|
|
226
|
-
//
|
|
261
|
+
// measures it (growing past 200k when the gateway accepts more) and the
|
|
262
|
+
// result is used here from the next start. Real steps also prove the gateway
|
|
263
|
+
// accepted at least their prompt size. A published catalog field still wins,
|
|
264
|
+
// but only inside that measured ceiling, so an advertised 1M window can
|
|
265
|
+
// never push a session past what the gateway takes.
|
|
227
266
|
const observed = options.live?.models[model.id]?.maxPromptTokens ?? 0;
|
|
228
|
-
const contextCeiling = Math.min(
|
|
267
|
+
const contextCeiling = Math.min(MAX_CONTEXT_WINDOW, Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed));
|
|
229
268
|
const limitContext = Math.min(positiveNumber(model.context_window, model.contextWindow, model.limit?.context, capability?.limit?.context) ?? contextCeiling, contextCeiling);
|
|
230
|
-
|
|
269
|
+
// Reasoning shares the output budget. When models.dev knows the upstream
|
|
270
|
+
// model emits more than the CLI's 32k, advertise that larger budget (up to a
|
|
271
|
+
// sane ceiling) instead of truncating the chain of thought.
|
|
272
|
+
const limitOutput = Math.min(positiveNumber(model.max_tokens, model.maxTokens, model.max_output_tokens, model.limit?.output, capability?.limit?.output) ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING);
|
|
231
273
|
const defaultEffort = reasoning
|
|
232
274
|
? preferredReasoningEffort(reasoningOptions, options.reasoningEffort)
|
|
233
275
|
: undefined;
|
|
276
|
+
const variants = reasoning
|
|
277
|
+
? modelVariants(reasoningOptions, limitOutput)
|
|
278
|
+
: {};
|
|
279
|
+
const modalities = modelModalities(model, capability);
|
|
280
|
+
const declaredOptions = reasoning
|
|
281
|
+
? effectiveReasoningOptions(reasoningOptions, variants)
|
|
282
|
+
: undefined;
|
|
234
283
|
result[model.id] = {
|
|
235
284
|
id: model.id,
|
|
236
285
|
name: displayName(model),
|
|
@@ -239,22 +288,21 @@ export function buildModels(models, candidates = [], options = {}) {
|
|
|
239
288
|
(model.section === "defense" ? "defense" : ""),
|
|
240
289
|
release_date: model.release_date ?? capability?.release_date,
|
|
241
290
|
reasoning,
|
|
242
|
-
|
|
243
|
-
|
|
291
|
+
...(declaredOptions && declaredOptions.length > 0
|
|
292
|
+
? { reasoning_options: declaredOptions }
|
|
293
|
+
: {}),
|
|
294
|
+
variants,
|
|
244
295
|
...(defaultEffort ? { settings: { reasoningEffort: defaultEffort } } : {}),
|
|
245
296
|
enabled: model.unavailable !== true,
|
|
246
297
|
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
247
298
|
tool_call: model.tool_call ?? capability?.tool_call ?? true,
|
|
248
|
-
attachment: model.attachment ??
|
|
299
|
+
attachment: model.attachment ??
|
|
300
|
+
capability?.attachment ??
|
|
301
|
+
modalities.input.includes("image"),
|
|
249
302
|
interleaved: model.interleaved ?? capability?.interleaved,
|
|
250
303
|
cost: modelCost(model, capability),
|
|
251
304
|
limit: { context: limitContext, output: limitOutput },
|
|
252
|
-
modalities
|
|
253
|
-
input: model.modalities?.input ??
|
|
254
|
-
capability?.modalities?.input ?? ["text"],
|
|
255
|
-
output: model.modalities?.output ??
|
|
256
|
-
capability?.modalities?.output ?? ["text"],
|
|
257
|
-
},
|
|
305
|
+
modalities,
|
|
258
306
|
status: model.unavailable ? "deprecated" : "active",
|
|
259
307
|
};
|
|
260
308
|
}
|
package/dist/catalog/v2.js
CHANGED
|
@@ -13,13 +13,11 @@ export function toV2Models(providerID, models) {
|
|
|
13
13
|
...(model.family ? { family: model.family } : {}),
|
|
14
14
|
capabilities: {
|
|
15
15
|
tools: model.tool_call !== false,
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
|
|
21
|
-
// advertised capability identical to the CLI.
|
|
22
|
-
input: ["text"],
|
|
16
|
+
// models.dev tells us which upstream models accept images. free-pi's
|
|
17
|
+
// gateway forwards image parts, so advertise exactly those modalities.
|
|
18
|
+
// Text-only models keep using the `look_at_image` tool, which keeps
|
|
19
|
+
// screenshots out of the token stream and the daily allowance.
|
|
20
|
+
input: model.modalities?.input ?? ["text"],
|
|
23
21
|
output: ["text"],
|
|
24
22
|
...(model.temperature === undefined
|
|
25
23
|
? {}
|
package/dist/constants.d.ts
CHANGED
|
@@ -13,7 +13,16 @@ export declare const CONSENT_VERSION = "4";
|
|
|
13
13
|
* with what the server actually accepts.
|
|
14
14
|
*/
|
|
15
15
|
export declare const CONTEXT_WINDOW = 200000;
|
|
16
|
+
/** Largest window the plugin will ever advertise after measuring the gateway. */
|
|
17
|
+
export declare const MAX_CONTEXT_WINDOW = 1000000;
|
|
16
18
|
export declare const MAX_OUTPUT_TOKENS = 32768;
|
|
19
|
+
/**
|
|
20
|
+
* Upper bound for a model that publishes a larger output budget. Reasoning
|
|
21
|
+
* tokens share this budget, so a model that can emit more must not be pinned to
|
|
22
|
+
* the CLI's 32k: a long chain of thought would consume it and leave `content`
|
|
23
|
+
* empty.
|
|
24
|
+
*/
|
|
25
|
+
export declare const MAX_OUTPUT_TOKENS_CEILING = 131072;
|
|
17
26
|
/** How long a measured gateway window is trusted before checking again. */
|
|
18
27
|
export declare const VERIFY_LIMITS_TTL_MS: number;
|
|
19
28
|
export declare const AD_CONTEXT_HEADER = "x-ad-context";
|
|
@@ -26,20 +35,22 @@ export declare const SUBAGENT_HEADER = "x-freepi-subagent";
|
|
|
26
35
|
/**
|
|
27
36
|
* The provider CLI starts with thinking off, but leaving `reasoning_effort`
|
|
28
37
|
* unset makes the gateway answer in a hurry: the free models spend only a few
|
|
29
|
-
* dozen reasoning tokens even on tasks that need planning. The
|
|
30
|
-
*
|
|
31
|
-
*
|
|
38
|
+
* dozen reasoning tokens even on tasks that need planning. The gateway accepts
|
|
39
|
+
* every level (measured with curl_cffi) but currently does not let the level
|
|
40
|
+
* change how long the upstream thinks, so the plugin also asks for explicit
|
|
41
|
+
* step-by-step checking in the prompt and defaults to `high`. `none`/`minimal`
|
|
42
|
+
* stay one pick away when speed matters more than care.
|
|
32
43
|
*/
|
|
33
|
-
export declare const DEFAULT_REASONING_EFFORT = "
|
|
44
|
+
export declare const DEFAULT_REASONING_EFFORT = "high";
|
|
34
45
|
export declare const REASONING_EFFORTS: readonly ["none", "minimal", "low", "medium", "high", "max"];
|
|
35
|
-
export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low", "medium", "high"];
|
|
46
|
+
export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low", "medium", "high", "max"];
|
|
36
47
|
/**
|
|
37
48
|
* Injected into every primary free-pi request. OpenCode already supplies the
|
|
38
49
|
* coding instructions; this block covers the failure modes the weaker free
|
|
39
50
|
* models show: skipping analysis, inventing verification, and ignoring the
|
|
40
51
|
* context the conversation already established.
|
|
41
52
|
*/
|
|
42
|
-
export declare const FREE_PI_GUIDANCE = "# free-pi working rules\n- Answer the user's latest request and keep their constraints; do not switch to a different task.\n- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.\n- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.\n- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.\n- Never claim to have compacted, summarized or cleared context unless that actually happened.\n- Continue until the request is finished, then report concisely what changed and what you verified.";
|
|
53
|
+
export declare const FREE_PI_GUIDANCE = "# free-pi working rules\n- Answer the user's latest request and keep their constraints; do not switch to a different task.\n- Slow down on multi-step work (arithmetic, counting, logic, dates, units, planning, debugging): write out each step, recompute the result a second way, and only then answer. On those tasks a correct answer after a dozen explicit steps beats a fast guess; do not stop at the first plausible number.\n- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.\n- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.\n- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.\n- Never claim to have compacted, summarized or cleared context unless that actually happened.\n- Continue until the request is finished, then report concisely what changed and what you verified.";
|
|
43
54
|
export declare const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
|
|
44
55
|
/**
|
|
45
56
|
* Appended to OpenCode's compaction request. Its default summary prompt asks
|
package/dist/constants.js
CHANGED
|
@@ -13,7 +13,16 @@ export const CONSENT_VERSION = "4";
|
|
|
13
13
|
* with what the server actually accepts.
|
|
14
14
|
*/
|
|
15
15
|
export const CONTEXT_WINDOW = 200_000;
|
|
16
|
+
/** Largest window the plugin will ever advertise after measuring the gateway. */
|
|
17
|
+
export const MAX_CONTEXT_WINDOW = 1_000_000;
|
|
16
18
|
export const MAX_OUTPUT_TOKENS = 32_768;
|
|
19
|
+
/**
|
|
20
|
+
* Upper bound for a model that publishes a larger output budget. Reasoning
|
|
21
|
+
* tokens share this budget, so a model that can emit more must not be pinned to
|
|
22
|
+
* the CLI's 32k: a long chain of thought would consume it and leave `content`
|
|
23
|
+
* empty.
|
|
24
|
+
*/
|
|
25
|
+
export const MAX_OUTPUT_TOKENS_CEILING = 131_072;
|
|
17
26
|
/** How long a measured gateway window is trusted before checking again. */
|
|
18
27
|
export const VERIFY_LIMITS_TTL_MS = 7 * 24 * 60 * 60 * 1_000;
|
|
19
28
|
export const AD_CONTEXT_HEADER = "x-ad-context";
|
|
@@ -26,11 +35,13 @@ export const SUBAGENT_HEADER = "x-freepi-subagent";
|
|
|
26
35
|
/**
|
|
27
36
|
* The provider CLI starts with thinking off, but leaving `reasoning_effort`
|
|
28
37
|
* unset makes the gateway answer in a hurry: the free models spend only a few
|
|
29
|
-
* dozen reasoning tokens even on tasks that need planning. The
|
|
30
|
-
*
|
|
31
|
-
*
|
|
38
|
+
* dozen reasoning tokens even on tasks that need planning. The gateway accepts
|
|
39
|
+
* every level (measured with curl_cffi) but currently does not let the level
|
|
40
|
+
* change how long the upstream thinks, so the plugin also asks for explicit
|
|
41
|
+
* step-by-step checking in the prompt and defaults to `high`. `none`/`minimal`
|
|
42
|
+
* stay one pick away when speed matters more than care.
|
|
32
43
|
*/
|
|
33
|
-
export const DEFAULT_REASONING_EFFORT = "
|
|
44
|
+
export const DEFAULT_REASONING_EFFORT = "high";
|
|
34
45
|
export const REASONING_EFFORTS = [
|
|
35
46
|
"none",
|
|
36
47
|
"minimal",
|
|
@@ -45,6 +56,7 @@ export const DEFAULT_THINKING_LEVELS = [
|
|
|
45
56
|
"low",
|
|
46
57
|
"medium",
|
|
47
58
|
"high",
|
|
59
|
+
"max",
|
|
48
60
|
];
|
|
49
61
|
/**
|
|
50
62
|
* Injected into every primary free-pi request. OpenCode already supplies the
|
|
@@ -54,6 +66,7 @@ export const DEFAULT_THINKING_LEVELS = [
|
|
|
54
66
|
*/
|
|
55
67
|
export const FREE_PI_GUIDANCE = `# free-pi working rules
|
|
56
68
|
- Answer the user's latest request and keep their constraints; do not switch to a different task.
|
|
69
|
+
- Slow down on multi-step work (arithmetic, counting, logic, dates, units, planning, debugging): write out each step, recompute the result a second way, and only then answer. On those tasks a correct answer after a dozen explicit steps beats a fast guess; do not stop at the first plausible number.
|
|
57
70
|
- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.
|
|
58
71
|
- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.
|
|
59
72
|
- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.
|
package/dist/plugin.js
CHANGED
|
@@ -134,10 +134,22 @@ async function setup(ctx) {
|
|
|
134
134
|
});
|
|
135
135
|
// The gateway does not publish its context ceiling. Verify the compiled
|
|
136
136
|
// window against it once a week with a free model, in the background, and
|
|
137
|
-
// persist the result for the next catalog build.
|
|
137
|
+
// persist the result for the next catalog build. Prefer the free model with
|
|
138
|
+
// the largest prompt already accepted in real traffic: it has the most
|
|
139
|
+
// evidence behind it, so the growth probes describe the window sessions use.
|
|
138
140
|
if (ctx.options?.liveLimits !== false && shouldVerifyWindow(live)) {
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
+
const free = main.filter((model) => model.free === true && typeof model.id === "string");
|
|
142
|
+
const probe = free
|
|
143
|
+
.map((model) => ({
|
|
144
|
+
id: model.id,
|
|
145
|
+
seen: live?.models[model.id ?? ""]?.maxPromptTokens ?? 0,
|
|
146
|
+
}))
|
|
147
|
+
.sort((a, b) => b.seen - a.seen)[0]?.id ??
|
|
148
|
+
(catalog?.default_model &&
|
|
149
|
+
free.some((model) => model.id === catalog.default_model)
|
|
150
|
+
? catalog.default_model
|
|
151
|
+
: undefined) ??
|
|
152
|
+
free[0]?.id ??
|
|
141
153
|
Object.keys(mainModels)[0];
|
|
142
154
|
if (probe) {
|
|
143
155
|
void verifyGatewayWindow(deps, { model: probe }).catch(() => undefined);
|
package/dist/session/hooks.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { ensureAdImpression } from "../ads/impression.js";
|
|
3
3
|
import { resolveAdTurn } from "../ads/resolve.js";
|
|
4
4
|
import { resolveToken } from "../auth/token.js";
|
|
5
|
-
import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, DEFENSE_PROVIDER_ID, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER, MAX_OUTPUT_TOKENS, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, } from "../constants.js";
|
|
5
|
+
import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, DEFENSE_PROVIDER_ID, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER, MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, } from "../constants.js";
|
|
6
6
|
import { closeFreePiSession } from "../api/session.js";
|
|
7
7
|
import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
|
|
8
8
|
import { parseFreePiError } from "../errors/parse.js";
|
|
@@ -52,7 +52,9 @@ async function applyGeneration(deps, event, kind) {
|
|
|
52
52
|
}
|
|
53
53
|
const modelID = event.model?.id;
|
|
54
54
|
const limit = deps.state.outputLimits.get(`${event.model.providerID}/${modelID}`);
|
|
55
|
-
|
|
55
|
+
// Reasoning shares the output budget; a model that publishes more than the
|
|
56
|
+
// CLI's 32k keeps that larger budget (up to the plugin ceiling).
|
|
57
|
+
const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING);
|
|
56
58
|
if (event.options) {
|
|
57
59
|
const current = event.options.maxTokens;
|
|
58
60
|
if (current === undefined || current > cap)
|
package/package.json
CHANGED
package/src/catalog/live.ts
CHANGED
|
@@ -25,6 +25,14 @@ const FILE = "live-limits.json";
|
|
|
25
25
|
const WRITE_DEBOUNCE_MS = 2_000;
|
|
26
26
|
/** Verification stops shrinking here instead of advertising a useless window. */
|
|
27
27
|
const MIN_WINDOW = 32_768;
|
|
28
|
+
/** Hard stop for the upward search; `buildModels` never advertises more. */
|
|
29
|
+
const MAX_WINDOW = 1_000_000;
|
|
30
|
+
/** Keep headroom under the exact ceiling so a fresh turn never hits a 413. */
|
|
31
|
+
const WINDOW_SAFETY = 0.97;
|
|
32
|
+
/** Probe requests per verification, counting the initial confirmation. */
|
|
33
|
+
const MAX_PROBES = 6;
|
|
34
|
+
/** OpenCode budgets four characters per token; correct it after the first probe. */
|
|
35
|
+
const INITIAL_CHARS_PER_TOKEN = 4;
|
|
28
36
|
|
|
29
37
|
export type ModelObservation = {
|
|
30
38
|
/** Largest prompt the gateway accepted for this model. */
|
|
@@ -228,15 +236,66 @@ async function sendProbe(
|
|
|
228
236
|
export type VerifyLimitsOptions = {
|
|
229
237
|
/** A free model to probe with; paid models would spend credits. */
|
|
230
238
|
model?: string;
|
|
231
|
-
/** Window to check. Defaults to the compiled one. */
|
|
239
|
+
/** Window to check. Defaults to the measured one, then the compiled one. */
|
|
232
240
|
window?: number;
|
|
233
241
|
};
|
|
234
242
|
|
|
243
|
+
/** One gateway answer used to settle the advertised window. */
|
|
244
|
+
export type ProbeSample = {
|
|
245
|
+
chars: number;
|
|
246
|
+
/** Prompt tokens the gateway reported for an accepted probe. */
|
|
247
|
+
tokens?: number;
|
|
248
|
+
tooLong: boolean;
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Largest window the accepted probes prove, with headroom. Pure so the probe
|
|
253
|
+
* loop and the persisted value can be tested without a server.
|
|
254
|
+
*/
|
|
255
|
+
export function settleWindow(
|
|
256
|
+
samples: readonly ProbeSample[],
|
|
257
|
+
): number | undefined {
|
|
258
|
+
let best = 0;
|
|
259
|
+
for (const sample of samples) {
|
|
260
|
+
if (sample.tooLong) continue;
|
|
261
|
+
if (!Number.isFinite(sample.tokens) || (sample.tokens ?? 0) <= 0) continue;
|
|
262
|
+
if (sample.tokens! <= best) continue;
|
|
263
|
+
best = sample.tokens!;
|
|
264
|
+
}
|
|
265
|
+
if (best === 0) return undefined;
|
|
266
|
+
return Math.min(
|
|
267
|
+
MAX_WINDOW,
|
|
268
|
+
Math.max(MIN_WINDOW, Math.floor((best * WINDOW_SAFETY) / 1_000) * 1_000),
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Stores a measured window and writes it immediately. Called after every
|
|
274
|
+
* accepted probe, so a process that exits mid-verification keeps the smallest
|
|
275
|
+
* proven value instead of losing the whole run.
|
|
276
|
+
*/
|
|
277
|
+
async function commitWindow(
|
|
278
|
+
deps: Deps,
|
|
279
|
+
tokens: number,
|
|
280
|
+
modelID: string,
|
|
281
|
+
): Promise<number> {
|
|
282
|
+
const limits = (cached ??= emptyLimits());
|
|
283
|
+
if (limits.window && limits.window.tokens >= tokens) return limits.window.tokens;
|
|
284
|
+
limits.window = { tokens, verifiedAt: Date.now(), model: modelID };
|
|
285
|
+
loaded = true;
|
|
286
|
+
await persist();
|
|
287
|
+
return tokens;
|
|
288
|
+
}
|
|
289
|
+
|
|
235
290
|
/**
|
|
236
|
-
* Checks the compiled window against the gateway
|
|
237
|
-
*
|
|
238
|
-
* the
|
|
239
|
-
*
|
|
291
|
+
* Checks the compiled window against the gateway and then grows past it while
|
|
292
|
+
* the gateway keeps accepting larger prompts. The start value is a floor, not a
|
|
293
|
+
* ceiling: the server has no endpoint for its real limit, and pinning sessions
|
|
294
|
+
* to the CLI's 200k wastes capacity the account can actually use. On rejection
|
|
295
|
+
* it binary-searches between the largest accepted prompt and the rejected one,
|
|
296
|
+
* so the next catalog build advertises the measured window. Returns the verified
|
|
297
|
+
* window, or `undefined` when nothing could be learned (the previous value is
|
|
298
|
+
* kept).
|
|
240
299
|
*/
|
|
241
300
|
export async function verifyGatewayWindow(
|
|
242
301
|
deps: Deps,
|
|
@@ -244,34 +303,75 @@ export async function verifyGatewayWindow(
|
|
|
244
303
|
): Promise<number | undefined> {
|
|
245
304
|
const modelID = options.model;
|
|
246
305
|
if (!modelID) return undefined;
|
|
247
|
-
const
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
//
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
306
|
+
const fallback =
|
|
307
|
+
options.window ?? cached?.window?.tokens ?? CONTEXT_WINDOW;
|
|
308
|
+
const samples: ProbeSample[] = [];
|
|
309
|
+
// Accepted prompt tokens; also the lower bound of the binary search.
|
|
310
|
+
let accepted = 0;
|
|
311
|
+
let charsPerToken = INITIAL_CHARS_PER_TOKEN;
|
|
312
|
+
let target = Math.max(MIN_WINDOW, Math.min(fallback, MAX_WINDOW));
|
|
313
|
+
let verified: number | undefined;
|
|
314
|
+
const floor = Math.min(fallback, CONTEXT_WINDOW);
|
|
315
|
+
|
|
316
|
+
for (let attempt = 0; attempt < MAX_PROBES; attempt += 1) {
|
|
317
|
+
const chars = Math.max(
|
|
318
|
+
MIN_WINDOW * charsPerToken,
|
|
319
|
+
Math.floor(target * charsPerToken * 0.99),
|
|
320
|
+
);
|
|
256
321
|
const result = await sendProbe(deps, modelID, chars);
|
|
257
|
-
if (result.status === "failed")
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
322
|
+
if (result.status === "failed") {
|
|
323
|
+
// A network failure or a rejected body proves nothing; keep what the
|
|
324
|
+
// earlier probes already established.
|
|
325
|
+
if (samples.length === 0) return verified;
|
|
326
|
+
break;
|
|
327
|
+
}
|
|
328
|
+
if (result.status === "too_long") {
|
|
329
|
+
samples.push({ chars, tooLong: true });
|
|
330
|
+
if (accepted === 0) {
|
|
331
|
+
// The compiled window itself is too large: step down as before.
|
|
332
|
+
target = Math.floor(target * 0.85);
|
|
333
|
+
if (target < MIN_WINDOW) break;
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
const next = Math.floor((accepted + target) / 2);
|
|
337
|
+
if (next <= accepted) break;
|
|
338
|
+
target = next;
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const tokens = result.promptTokens;
|
|
343
|
+
samples.push({
|
|
344
|
+
chars,
|
|
345
|
+
tooLong: false,
|
|
346
|
+
...(tokens && tokens > 0 ? { tokens } : {}),
|
|
273
347
|
});
|
|
274
|
-
|
|
348
|
+
if (tokens && tokens > 0) {
|
|
349
|
+
accepted = tokens;
|
|
350
|
+
// Learn the real characters-per-token ratio for this prompt shape; the
|
|
351
|
+
// filler is prose, and four chars/token overshoots badly.
|
|
352
|
+
charsPerToken = chars / tokens;
|
|
353
|
+
} else {
|
|
354
|
+
accepted = Math.floor(chars / charsPerToken);
|
|
355
|
+
}
|
|
356
|
+
const settled = settleWindow(samples);
|
|
357
|
+
if (settled) {
|
|
358
|
+
// Never go below the window that already worked for this account.
|
|
359
|
+
verified = await commitWindow(deps, Math.max(settled, floor), modelID);
|
|
360
|
+
}
|
|
361
|
+
if (accepted >= MAX_WINDOW) break;
|
|
362
|
+
const next = Math.min(MAX_WINDOW, Math.floor(accepted * 1.2));
|
|
363
|
+
if (next <= accepted) break;
|
|
364
|
+
target = next;
|
|
275
365
|
}
|
|
276
|
-
|
|
366
|
+
|
|
367
|
+
if (!verified) return undefined;
|
|
368
|
+
deps.log.info("free-pi verified the gateway context window", {
|
|
369
|
+
model: modelID,
|
|
370
|
+
window: verified,
|
|
371
|
+
compiled: fallback,
|
|
372
|
+
probes: samples.length,
|
|
373
|
+
acceptedTokens: accepted,
|
|
374
|
+
charsPerToken: Number(charsPerToken.toFixed(2)),
|
|
375
|
+
});
|
|
376
|
+
return verified;
|
|
277
377
|
}
|
package/src/catalog/models.ts
CHANGED
|
@@ -4,7 +4,9 @@ import {
|
|
|
4
4
|
CONTEXT_WINDOW,
|
|
5
5
|
DEFAULT_REASONING_EFFORT,
|
|
6
6
|
DEFAULT_THINKING_LEVELS,
|
|
7
|
+
MAX_CONTEXT_WINDOW,
|
|
7
8
|
MAX_OUTPUT_TOKENS,
|
|
9
|
+
MAX_OUTPUT_TOKENS_CEILING,
|
|
8
10
|
REASONING_EFFORTS,
|
|
9
11
|
} from "../constants.js";
|
|
10
12
|
import type {
|
|
@@ -178,7 +180,8 @@ export function modelVariants(
|
|
|
178
180
|
// The provider CLI registers every model with `reasoning: true` and an unset
|
|
179
181
|
// `thinkingLevelMap`, so it offers these levels to every model. models.dev
|
|
180
182
|
// lists fewer levels for some upstream models, but the gateway accepts the
|
|
181
|
-
// CLI's set, and hiding levels only makes the picker
|
|
183
|
+
// CLI's set (including `max`), and hiding levels only makes the picker
|
|
184
|
+
// disagree with the CLI.
|
|
182
185
|
const variants: VariantMap = {};
|
|
183
186
|
for (const level of DEFAULT_THINKING_LEVELS) {
|
|
184
187
|
variants[level] = { reasoningEffort: level };
|
|
@@ -199,6 +202,26 @@ export function modelVariants(
|
|
|
199
202
|
return variants;
|
|
200
203
|
}
|
|
201
204
|
|
|
205
|
+
/**
|
|
206
|
+
* The levels the model actually exposes, so OpenCode's picker and the
|
|
207
|
+
* `reasoning_effort` values the plugin sends come from the same list. The
|
|
208
|
+
* gateway accepts every level for every model, so the CLI set always applies.
|
|
209
|
+
*/
|
|
210
|
+
export function effectiveReasoningOptions(
|
|
211
|
+
options: ReasoningOption[] | undefined,
|
|
212
|
+
variants: VariantMap,
|
|
213
|
+
): ReasoningOption[] {
|
|
214
|
+
const values = Object.keys(variants);
|
|
215
|
+
const declared = options?.find(
|
|
216
|
+
(option): option is Extract<ReasoningOption, { type: "effort" }> =>
|
|
217
|
+
option.type === "effort",
|
|
218
|
+
)?.values;
|
|
219
|
+
for (const value of declared ?? []) {
|
|
220
|
+
if (!values.includes(value)) values.push(value);
|
|
221
|
+
}
|
|
222
|
+
return values.length > 0 ? [{ type: "effort", values }] : [];
|
|
223
|
+
}
|
|
224
|
+
|
|
202
225
|
export function isReasoningEffort(value: unknown): value is string {
|
|
203
226
|
return (
|
|
204
227
|
typeof value === "string" &&
|
|
@@ -295,6 +318,34 @@ export function filterAccessibleModels(
|
|
|
295
318
|
});
|
|
296
319
|
}
|
|
297
320
|
|
|
321
|
+
const KNOWN_INPUT_MODALITIES = new Set([
|
|
322
|
+
"text",
|
|
323
|
+
"image",
|
|
324
|
+
"audio",
|
|
325
|
+
"video",
|
|
326
|
+
"pdf",
|
|
327
|
+
]);
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Native modalities for the chat route. models.dev describes the upstream
|
|
331
|
+
* model, and the gateway forwards image parts to multimodal upstreams, so an
|
|
332
|
+
* image-capable model is advertised as such. Output is always text: free-pi has
|
|
333
|
+
* no image results on the chat route, and the plugin registers every model as
|
|
334
|
+
* zero-cost text output.
|
|
335
|
+
*/
|
|
336
|
+
function modelModalities(
|
|
337
|
+
model: CatalogModel,
|
|
338
|
+
capability: ModelsDevModel | undefined,
|
|
339
|
+
): { input: string[]; output: string[] } {
|
|
340
|
+
const declared = model.modalities?.input ?? capability?.modalities?.input;
|
|
341
|
+
const input = (declared ?? ["text"]).filter((value) =>
|
|
342
|
+
KNOWN_INPUT_MODALITIES.has(value),
|
|
343
|
+
);
|
|
344
|
+
if (input.length === 0) input.push("text");
|
|
345
|
+
if (!input.includes("text")) input.unshift("text");
|
|
346
|
+
return { input, output: ["text"] };
|
|
347
|
+
}
|
|
348
|
+
|
|
298
349
|
export function buildModels(
|
|
299
350
|
models: CatalogModel[],
|
|
300
351
|
candidates: RegistryCandidate[] = [],
|
|
@@ -313,13 +364,14 @@ export function buildModels(
|
|
|
313
364
|
// free-pi enforces a context window on every model regardless of what
|
|
314
365
|
// models.dev reports for the upstream provider. The provider CLI starts at
|
|
315
366
|
// 200k, but the gateway does not publish its ceiling: `verifyGatewayWindow`
|
|
316
|
-
// measures it
|
|
317
|
-
//
|
|
318
|
-
//
|
|
319
|
-
//
|
|
367
|
+
// measures it (growing past 200k when the gateway accepts more) and the
|
|
368
|
+
// result is used here from the next start. Real steps also prove the gateway
|
|
369
|
+
// accepted at least their prompt size. A published catalog field still wins,
|
|
370
|
+
// but only inside that measured ceiling, so an advertised 1M window can
|
|
371
|
+
// never push a session past what the gateway takes.
|
|
320
372
|
const observed = options.live?.models[model.id]?.maxPromptTokens ?? 0;
|
|
321
373
|
const contextCeiling = Math.min(
|
|
322
|
-
|
|
374
|
+
MAX_CONTEXT_WINDOW,
|
|
323
375
|
Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed),
|
|
324
376
|
);
|
|
325
377
|
const limitContext = Math.min(
|
|
@@ -331,6 +383,9 @@ export function buildModels(
|
|
|
331
383
|
) ?? contextCeiling,
|
|
332
384
|
contextCeiling,
|
|
333
385
|
);
|
|
386
|
+
// Reasoning shares the output budget. When models.dev knows the upstream
|
|
387
|
+
// model emits more than the CLI's 32k, advertise that larger budget (up to a
|
|
388
|
+
// sane ceiling) instead of truncating the chain of thought.
|
|
334
389
|
const limitOutput = Math.min(
|
|
335
390
|
positiveNumber(
|
|
336
391
|
model.max_tokens,
|
|
@@ -339,11 +394,18 @@ export function buildModels(
|
|
|
339
394
|
model.limit?.output,
|
|
340
395
|
capability?.limit?.output,
|
|
341
396
|
) ?? MAX_OUTPUT_TOKENS,
|
|
342
|
-
|
|
397
|
+
MAX_OUTPUT_TOKENS_CEILING,
|
|
343
398
|
);
|
|
344
399
|
const defaultEffort = reasoning
|
|
345
400
|
? preferredReasoningEffort(reasoningOptions, options.reasoningEffort)
|
|
346
401
|
: undefined;
|
|
402
|
+
const variants = reasoning
|
|
403
|
+
? modelVariants(reasoningOptions, limitOutput)
|
|
404
|
+
: {};
|
|
405
|
+
const modalities = modelModalities(model, capability);
|
|
406
|
+
const declaredOptions = reasoning
|
|
407
|
+
? effectiveReasoningOptions(reasoningOptions, variants)
|
|
408
|
+
: undefined;
|
|
347
409
|
result[model.id] = {
|
|
348
410
|
id: model.id,
|
|
349
411
|
name: displayName(model),
|
|
@@ -353,22 +415,22 @@ export function buildModels(
|
|
|
353
415
|
(model.section === "defense" ? "defense" : ""),
|
|
354
416
|
release_date: model.release_date ?? capability?.release_date,
|
|
355
417
|
reasoning,
|
|
356
|
-
|
|
357
|
-
|
|
418
|
+
...(declaredOptions && declaredOptions.length > 0
|
|
419
|
+
? { reasoning_options: declaredOptions }
|
|
420
|
+
: {}),
|
|
421
|
+
variants,
|
|
358
422
|
...(defaultEffort ? { settings: { reasoningEffort: defaultEffort } } : {}),
|
|
359
423
|
enabled: model.unavailable !== true,
|
|
360
424
|
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
361
425
|
tool_call: model.tool_call ?? capability?.tool_call ?? true,
|
|
362
|
-
attachment:
|
|
426
|
+
attachment:
|
|
427
|
+
model.attachment ??
|
|
428
|
+
capability?.attachment ??
|
|
429
|
+
modalities.input.includes("image"),
|
|
363
430
|
interleaved: model.interleaved ?? capability?.interleaved,
|
|
364
431
|
cost: modelCost(model, capability),
|
|
365
432
|
limit: { context: limitContext, output: limitOutput },
|
|
366
|
-
modalities
|
|
367
|
-
input: model.modalities?.input ??
|
|
368
|
-
capability?.modalities?.input ?? ["text"],
|
|
369
|
-
output: model.modalities?.output ??
|
|
370
|
-
capability?.modalities?.output ?? ["text"],
|
|
371
|
-
},
|
|
433
|
+
modalities,
|
|
372
434
|
status: model.unavailable ? "deprecated" : "active",
|
|
373
435
|
};
|
|
374
436
|
}
|
package/src/catalog/v2.ts
CHANGED
|
@@ -32,13 +32,11 @@ export function toV2Models(providerID: string, models: ModelMap): any[] {
|
|
|
32
32
|
...(model.family ? { family: model.family } : {}),
|
|
33
33
|
capabilities: {
|
|
34
34
|
tools: model.tool_call !== false,
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
//
|
|
39
|
-
|
|
40
|
-
// advertised capability identical to the CLI.
|
|
41
|
-
input: ["text"],
|
|
35
|
+
// models.dev tells us which upstream models accept images. free-pi's
|
|
36
|
+
// gateway forwards image parts, so advertise exactly those modalities.
|
|
37
|
+
// Text-only models keep using the `look_at_image` tool, which keeps
|
|
38
|
+
// screenshots out of the token stream and the daily allowance.
|
|
39
|
+
input: model.modalities?.input ?? ["text"],
|
|
42
40
|
output: ["text"],
|
|
43
41
|
...(model.temperature === undefined
|
|
44
42
|
? {}
|
package/src/constants.ts
CHANGED
|
@@ -17,7 +17,16 @@ export const CONSENT_VERSION = "4";
|
|
|
17
17
|
* with what the server actually accepts.
|
|
18
18
|
*/
|
|
19
19
|
export const CONTEXT_WINDOW = 200_000;
|
|
20
|
+
/** Largest window the plugin will ever advertise after measuring the gateway. */
|
|
21
|
+
export const MAX_CONTEXT_WINDOW = 1_000_000;
|
|
20
22
|
export const MAX_OUTPUT_TOKENS = 32_768;
|
|
23
|
+
/**
|
|
24
|
+
* Upper bound for a model that publishes a larger output budget. Reasoning
|
|
25
|
+
* tokens share this budget, so a model that can emit more must not be pinned to
|
|
26
|
+
* the CLI's 32k: a long chain of thought would consume it and leave `content`
|
|
27
|
+
* empty.
|
|
28
|
+
*/
|
|
29
|
+
export const MAX_OUTPUT_TOKENS_CEILING = 131_072;
|
|
21
30
|
/** How long a measured gateway window is trusted before checking again. */
|
|
22
31
|
export const VERIFY_LIMITS_TTL_MS = 7 * 24 * 60 * 60 * 1_000;
|
|
23
32
|
|
|
@@ -32,11 +41,13 @@ export const SUBAGENT_HEADER = "x-freepi-subagent";
|
|
|
32
41
|
/**
|
|
33
42
|
* The provider CLI starts with thinking off, but leaving `reasoning_effort`
|
|
34
43
|
* unset makes the gateway answer in a hurry: the free models spend only a few
|
|
35
|
-
* dozen reasoning tokens even on tasks that need planning. The
|
|
36
|
-
*
|
|
37
|
-
*
|
|
44
|
+
* dozen reasoning tokens even on tasks that need planning. The gateway accepts
|
|
45
|
+
* every level (measured with curl_cffi) but currently does not let the level
|
|
46
|
+
* change how long the upstream thinks, so the plugin also asks for explicit
|
|
47
|
+
* step-by-step checking in the prompt and defaults to `high`. `none`/`minimal`
|
|
48
|
+
* stay one pick away when speed matters more than care.
|
|
38
49
|
*/
|
|
39
|
-
export const DEFAULT_REASONING_EFFORT = "
|
|
50
|
+
export const DEFAULT_REASONING_EFFORT = "high";
|
|
40
51
|
export const REASONING_EFFORTS = [
|
|
41
52
|
"none",
|
|
42
53
|
"minimal",
|
|
@@ -51,6 +62,7 @@ export const DEFAULT_THINKING_LEVELS = [
|
|
|
51
62
|
"low",
|
|
52
63
|
"medium",
|
|
53
64
|
"high",
|
|
65
|
+
"max",
|
|
54
66
|
] as const;
|
|
55
67
|
|
|
56
68
|
/**
|
|
@@ -61,6 +73,7 @@ export const DEFAULT_THINKING_LEVELS = [
|
|
|
61
73
|
*/
|
|
62
74
|
export const FREE_PI_GUIDANCE = `# free-pi working rules
|
|
63
75
|
- Answer the user's latest request and keep their constraints; do not switch to a different task.
|
|
76
|
+
- Slow down on multi-step work (arithmetic, counting, logic, dates, units, planning, debugging): write out each step, recompute the result a second way, and only then answer. On those tasks a correct answer after a dozen explicit steps beats a fast guess; do not stop at the first plausible number.
|
|
64
77
|
- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.
|
|
65
78
|
- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.
|
|
66
79
|
- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.
|
package/src/plugin.ts
CHANGED
|
@@ -182,11 +182,25 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
182
182
|
|
|
183
183
|
// The gateway does not publish its context ceiling. Verify the compiled
|
|
184
184
|
// window against it once a week with a free model, in the background, and
|
|
185
|
-
// persist the result for the next catalog build.
|
|
185
|
+
// persist the result for the next catalog build. Prefer the free model with
|
|
186
|
+
// the largest prompt already accepted in real traffic: it has the most
|
|
187
|
+
// evidence behind it, so the growth probes describe the window sessions use.
|
|
186
188
|
if (ctx.options?.liveLimits !== false && shouldVerifyWindow(live)) {
|
|
189
|
+
const free = main.filter(
|
|
190
|
+
(model) => model.free === true && typeof model.id === "string",
|
|
191
|
+
);
|
|
187
192
|
const probe =
|
|
188
|
-
|
|
189
|
-
|
|
193
|
+
free
|
|
194
|
+
.map((model) => ({
|
|
195
|
+
id: model.id,
|
|
196
|
+
seen: live?.models[model.id ?? ""]?.maxPromptTokens ?? 0,
|
|
197
|
+
}))
|
|
198
|
+
.sort((a, b) => b.seen - a.seen)[0]?.id ??
|
|
199
|
+
(catalog?.default_model &&
|
|
200
|
+
free.some((model) => model.id === catalog.default_model)
|
|
201
|
+
? catalog.default_model
|
|
202
|
+
: undefined) ??
|
|
203
|
+
free[0]?.id ??
|
|
190
204
|
Object.keys(mainModels)[0];
|
|
191
205
|
if (probe) {
|
|
192
206
|
void verifyGatewayWindow(deps, { model: probe }).catch(() => undefined);
|
package/src/session/hooks.ts
CHANGED
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
FREE_PI_GUIDANCE,
|
|
18
18
|
FREE_PI_GUIDANCE_MARKER,
|
|
19
19
|
MAX_OUTPUT_TOKENS,
|
|
20
|
+
MAX_OUTPUT_TOKENS_CEILING,
|
|
20
21
|
PROVIDER_ID,
|
|
21
22
|
RETRY_BASE_DELAY_MS,
|
|
22
23
|
RETRY_MAX_DELAY_MS,
|
|
@@ -136,7 +137,9 @@ async function applyGeneration(
|
|
|
136
137
|
const limit = deps.state.outputLimits.get(
|
|
137
138
|
`${event.model.providerID}/${modelID}`,
|
|
138
139
|
);
|
|
139
|
-
|
|
140
|
+
// Reasoning shares the output budget; a model that publishes more than the
|
|
141
|
+
// CLI's 32k keeps that larger budget (up to the plugin ceiling).
|
|
142
|
+
const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING);
|
|
140
143
|
if (event.options) {
|
|
141
144
|
const current = event.options.maxTokens;
|
|
142
145
|
if (current === undefined || current > cap) event.options.maxTokens = cap;
|