@eduardo191labs/opencode-free-pi 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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 anuncian la ventana de
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. Así OpenCode compacta antes de que el servidor rechace la
73
- conversación.
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
- - **Solo texto, como el CLI**: los modelos no anuncian entrada de imágenes.
88
- El CLI las trata fuera de la conversación (su herramienta `look_at_image`),
89
- y enviarlas como partes `image_url` incrusta cada imagen leída (cientos de
90
- KB) en la petición, desborda la ventana de 200k y gasta la cuota diaria en
91
- tokens de imagen. OpenCode sustituye las imágenes por un aviso, y el plugin
92
- aplica el mismo aviso al terminar la herramienta para que el base64 no quede
93
- guardado en la sesión; después el modelo puede usar `look_at_image` para
94
- consultar la imagen sin meterla en el contexto.
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: "medium"`
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 `none`, `minimal`, `low`, `medium` y `high`, igual
103
- que los niveles del CLI, y añade `max` cuando el catálogo lo declara; los
104
- modelos de presupuesto usan `high`. La opción `reasoningEffort: false` del
105
- plugin recupera el nivel del servidor. No se anuncian `thinking_budget` ni
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, entrada solo de texto, coste cero y 32k de salida. La
109
- ventana arranca en los 200k del CLI, pero el plugin la comprueba contra el
110
- gateway cada 7 días con un modelo gratuito y usa la medida real. No se fuerza
111
- temperatura ni `top_p`: la petición real no los incluye, así que el gateway
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: mide la
116
- ventana real del gateway, guarda el resultado en `live-limits.json` y anota en
117
- cada paso los tokens de prompt y de razonamiento que el servidor confirma.
118
- `liveLimits: false` desactiva la comprobación y deja la ventana compilada.
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
@@ -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 by sending the largest prompt
51
- * that window allows. On rejection it steps down until the gateway accepts, so
52
- * the next catalog build advertises what the server really takes. Returns the
53
- * verified window, or `undefined` when nothing could be learned.
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>;
@@ -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,109 @@ async function sendProbe(deps, modelID, chars) {
185
193
  };
186
194
  }
187
195
  /**
188
- * Checks the compiled window against the gateway by sending the largest prompt
189
- * that window allows. On rejection it steps down until the gateway accepts, so
190
- * the next catalog build advertises what the server really takes. Returns the
191
- * verified window, or `undefined` when nothing could be learned.
196
+ * Largest window the accepted probes prove, with headroom. Pure so the probe
197
+ * loop and the persisted value can be tested without a server.
198
+ */
199
+ export function settleWindow(samples) {
200
+ let best = 0;
201
+ for (const sample of samples) {
202
+ if (sample.tooLong)
203
+ continue;
204
+ if (!Number.isFinite(sample.tokens) || (sample.tokens ?? 0) <= 0)
205
+ continue;
206
+ if (sample.tokens <= best)
207
+ continue;
208
+ best = sample.tokens;
209
+ }
210
+ if (best === 0)
211
+ return undefined;
212
+ return Math.min(MAX_WINDOW, Math.max(MIN_WINDOW, Math.floor((best * WINDOW_SAFETY) / 1_000) * 1_000));
213
+ }
214
+ /**
215
+ * Checks the compiled window against the gateway and then grows past it while
216
+ * the gateway keeps accepting larger prompts. The start value is a floor, not a
217
+ * ceiling: the server has no endpoint for its real limit, and pinning sessions
218
+ * to the CLI's 200k wastes capacity the account can actually use. On rejection
219
+ * it binary-searches between the largest accepted prompt and the rejected one,
220
+ * so the next catalog build advertises the measured window. Returns the verified
221
+ * window, or `undefined` when nothing could be learned (the previous value is
222
+ * kept).
192
223
  */
193
224
  export async function verifyGatewayWindow(deps, options = {}) {
194
225
  const modelID = options.model;
195
226
  if (!modelID)
196
227
  return undefined;
197
- const window = options.window ?? CONTEXT_WINDOW;
198
- // OpenCode budgets a token as ~4 characters. The gateway rejects by its own
199
- // prompt size, so aim just under what the window allows in characters; the
200
- // reported prompt_tokens are logged for comparison but do not decide the
201
- // result.
202
- const targetChars = Math.max(MIN_WINDOW * 4, Math.floor(window * 4 * 0.99));
203
- for (const factor of [1, 0.85, 0.7, 0.55]) {
204
- const chars = Math.floor(targetChars * factor);
205
- if (chars < MIN_WINDOW)
206
- break;
228
+ const fallback = options.window ?? cached?.window?.tokens ?? CONTEXT_WINDOW;
229
+ const samples = [];
230
+ // Accepted prompt tokens; also the lower bound of the binary search.
231
+ let accepted = 0;
232
+ let charsPerToken = INITIAL_CHARS_PER_TOKEN;
233
+ let target = Math.max(MIN_WINDOW, Math.min(fallback, MAX_WINDOW));
234
+ for (let attempt = 0; attempt < MAX_PROBES; attempt += 1) {
235
+ const chars = Math.max(MIN_WINDOW * charsPerToken, Math.floor(target * charsPerToken * 0.99));
207
236
  const result = await sendProbe(deps, modelID, chars);
208
- if (result.status === "failed")
209
- return undefined;
210
- if (result.status === "too_long")
237
+ if (result.status === "failed") {
238
+ // A network failure or a rejected body proves nothing; keep what the
239
+ // earlier probes already established.
240
+ if (samples.length === 0)
241
+ return undefined;
242
+ break;
243
+ }
244
+ if (result.status === "too_long") {
245
+ samples.push({ chars, tooLong: true });
246
+ if (accepted === 0) {
247
+ // The compiled window itself is too large: step down as before.
248
+ target = Math.floor(target * 0.85);
249
+ if (target < MIN_WINDOW)
250
+ return undefined;
251
+ continue;
252
+ }
253
+ const next = Math.floor((accepted + target) / 2);
254
+ if (next <= accepted)
255
+ break;
256
+ target = next;
211
257
  continue;
212
- // Passing the full target confirms the compiled window. After a rejection,
213
- // only the reduced target is proven, so advertise that instead.
214
- const verified = factor === 1 ? window : Math.max(MIN_WINDOW, Math.floor(window * factor));
215
- const limits = (cached ??= emptyLimits());
216
- limits.window = { tokens: verified, verifiedAt: Date.now(), model: modelID };
217
- loaded = true;
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,
258
+ }
259
+ const tokens = result.promptTokens;
260
+ samples.push({
261
+ chars,
262
+ tooLong: false,
263
+ ...(tokens && tokens > 0 ? { tokens } : {}),
225
264
  });
226
- return verified;
265
+ if (tokens && tokens > 0) {
266
+ accepted = tokens;
267
+ // Learn the real characters-per-token ratio for this prompt shape; the
268
+ // filler is prose, and four chars/token overshoots badly.
269
+ charsPerToken = chars / tokens;
270
+ }
271
+ else {
272
+ accepted = Math.floor(chars / charsPerToken);
273
+ }
274
+ if (accepted >= MAX_WINDOW)
275
+ break;
276
+ const next = Math.min(MAX_WINDOW, Math.floor(accepted * 1.2));
277
+ if (next <= accepted)
278
+ break;
279
+ target = next;
227
280
  }
228
- return undefined;
281
+ const settled = settleWindow(samples);
282
+ if (!settled)
283
+ return undefined;
284
+ // Keep the previous floor when growth probes only prove less: the CLI's 200k
285
+ // is already known to work, so a small upstream probe model must not shrink
286
+ // every session's window.
287
+ const verified = Math.max(settled, Math.min(fallback, CONTEXT_WINDOW));
288
+ const limits = (cached ??= emptyLimits());
289
+ limits.window = { tokens: verified, verifiedAt: Date.now(), model: modelID };
290
+ loaded = true;
291
+ await persist();
292
+ deps.log.info("free-pi verified the gateway context window", {
293
+ model: modelID,
294
+ window: verified,
295
+ compiled: fallback,
296
+ probes: samples.length,
297
+ acceptedTokens: accepted,
298
+ charsPerToken: Number(charsPerToken.toFixed(2)),
299
+ });
300
+ return verified;
229
301
  }
@@ -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
@@ -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 disagree with the CLI.
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 and the result is used here from the next start. Real steps
224
- // also prove the gateway accepted at least their prompt size. A published
225
- // catalog field still wins, but only inside that measured ceiling, so an
226
- // advertised 1M window can never push a session past what the gateway takes.
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(1_000_000, Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed));
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
- 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);
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
- reasoning_options: reasoningOptions,
243
- variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
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 ?? capability?.attachment ?? false,
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
  }
@@ -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
- // The provider CLI registers every free-pi model as text-only and
17
- // handles images out of band with its vision and image tools. Sending
18
- // native image parts instead makes OpenCode inline every read image
19
- // (hundreds of KB each) into the request, which overflows the 200k
20
- // window and burns the daily allowance on image tokens, so keep the
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
  ? {}
@@ -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 plugin therefore
30
- * asks for `medium` by default and keeps the CLI's levels as variants, so
31
- * `none`/`minimal` are still one pick away when speed matters more than care.
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 = "medium";
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 plugin therefore
30
- * asks for `medium` by default and keeps the CLI's levels as variants, so
31
- * `none`/`minimal` are still one pick away when speed matters more than care.
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 = "medium";
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 probe = main.find((model) => model.free === true)?.id ??
140
- catalog?.default_model ??
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);
@@ -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
- const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS);
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -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,48 @@ 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
+
235
272
  /**
236
- * Checks the compiled window against the gateway by sending the largest prompt
237
- * that window allows. On rejection it steps down until the gateway accepts, so
238
- * the next catalog build advertises what the server really takes. Returns the
239
- * verified window, or `undefined` when nothing could be learned.
273
+ * Checks the compiled window against the gateway and then grows past it while
274
+ * the gateway keeps accepting larger prompts. The start value is a floor, not a
275
+ * ceiling: the server has no endpoint for its real limit, and pinning sessions
276
+ * to the CLI's 200k wastes capacity the account can actually use. On rejection
277
+ * it binary-searches between the largest accepted prompt and the rejected one,
278
+ * so the next catalog build advertises the measured window. Returns the verified
279
+ * window, or `undefined` when nothing could be learned (the previous value is
280
+ * kept).
240
281
  */
241
282
  export async function verifyGatewayWindow(
242
283
  deps: Deps,
@@ -244,34 +285,77 @@ export async function verifyGatewayWindow(
244
285
  ): Promise<number | undefined> {
245
286
  const modelID = options.model;
246
287
  if (!modelID) return undefined;
247
- const window = options.window ?? CONTEXT_WINDOW;
248
- // OpenCode budgets a token as ~4 characters. The gateway rejects by its own
249
- // prompt size, so aim just under what the window allows in characters; the
250
- // reported prompt_tokens are logged for comparison but do not decide the
251
- // result.
252
- const targetChars = Math.max(MIN_WINDOW * 4, Math.floor(window * 4 * 0.99));
253
- for (const factor of [1, 0.85, 0.7, 0.55]) {
254
- const chars = Math.floor(targetChars * factor);
255
- if (chars < MIN_WINDOW) break;
288
+ const fallback =
289
+ options.window ?? cached?.window?.tokens ?? CONTEXT_WINDOW;
290
+ const samples: ProbeSample[] = [];
291
+ // Accepted prompt tokens; also the lower bound of the binary search.
292
+ let accepted = 0;
293
+ let charsPerToken = INITIAL_CHARS_PER_TOKEN;
294
+ let target = Math.max(MIN_WINDOW, Math.min(fallback, MAX_WINDOW));
295
+
296
+ for (let attempt = 0; attempt < MAX_PROBES; attempt += 1) {
297
+ const chars = Math.max(
298
+ MIN_WINDOW * charsPerToken,
299
+ Math.floor(target * charsPerToken * 0.99),
300
+ );
256
301
  const result = await sendProbe(deps, modelID, chars);
257
- if (result.status === "failed") return undefined;
258
- if (result.status === "too_long") continue;
259
- // Passing the full target confirms the compiled window. After a rejection,
260
- // only the reduced target is proven, so advertise that instead.
261
- const verified =
262
- factor === 1 ? window : Math.max(MIN_WINDOW, Math.floor(window * factor));
263
- const limits = (cached ??= emptyLimits());
264
- limits.window = { tokens: verified, verifiedAt: Date.now(), model: modelID };
265
- loaded = true;
266
- await persist();
267
- deps.log.info("free-pi verified the gateway context window", {
268
- model: modelID,
269
- window: verified,
270
- compiled: window,
271
- probedChars: chars,
272
- probedTokens: result.promptTokens,
302
+ if (result.status === "failed") {
303
+ // A network failure or a rejected body proves nothing; keep what the
304
+ // earlier probes already established.
305
+ if (samples.length === 0) return undefined;
306
+ break;
307
+ }
308
+ if (result.status === "too_long") {
309
+ samples.push({ chars, tooLong: true });
310
+ if (accepted === 0) {
311
+ // The compiled window itself is too large: step down as before.
312
+ target = Math.floor(target * 0.85);
313
+ if (target < MIN_WINDOW) return undefined;
314
+ continue;
315
+ }
316
+ const next = Math.floor((accepted + target) / 2);
317
+ if (next <= accepted) break;
318
+ target = next;
319
+ continue;
320
+ }
321
+
322
+ const tokens = result.promptTokens;
323
+ samples.push({
324
+ chars,
325
+ tooLong: false,
326
+ ...(tokens && tokens > 0 ? { tokens } : {}),
273
327
  });
274
- return verified;
328
+ if (tokens && tokens > 0) {
329
+ accepted = tokens;
330
+ // Learn the real characters-per-token ratio for this prompt shape; the
331
+ // filler is prose, and four chars/token overshoots badly.
332
+ charsPerToken = chars / tokens;
333
+ } else {
334
+ accepted = Math.floor(chars / charsPerToken);
335
+ }
336
+ if (accepted >= MAX_WINDOW) break;
337
+ const next = Math.min(MAX_WINDOW, Math.floor(accepted * 1.2));
338
+ if (next <= accepted) break;
339
+ target = next;
275
340
  }
276
- return undefined;
341
+
342
+ const settled = settleWindow(samples);
343
+ if (!settled) return undefined;
344
+ // Keep the previous floor when growth probes only prove less: the CLI's 200k
345
+ // is already known to work, so a small upstream probe model must not shrink
346
+ // every session's window.
347
+ const verified = Math.max(settled, Math.min(fallback, CONTEXT_WINDOW));
348
+ const limits = (cached ??= emptyLimits());
349
+ limits.window = { tokens: verified, verifiedAt: Date.now(), model: modelID };
350
+ loaded = true;
351
+ await persist();
352
+ deps.log.info("free-pi verified the gateway context window", {
353
+ model: modelID,
354
+ window: verified,
355
+ compiled: fallback,
356
+ probes: samples.length,
357
+ acceptedTokens: accepted,
358
+ charsPerToken: Number(charsPerToken.toFixed(2)),
359
+ });
360
+ return verified;
277
361
  }
@@ -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 disagree with the CLI.
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 and the result is used here from the next start. Real steps
317
- // also prove the gateway accepted at least their prompt size. A published
318
- // catalog field still wins, but only inside that measured ceiling, so an
319
- // advertised 1M window can never push a session past what the gateway takes.
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
- 1_000_000,
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
- MAX_OUTPUT_TOKENS,
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
- reasoning_options: reasoningOptions,
357
- variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
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: model.attachment ?? capability?.attachment ?? false,
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
- // The provider CLI registers every free-pi model as text-only and
36
- // handles images out of band with its vision and image tools. Sending
37
- // native image parts instead makes OpenCode inline every read image
38
- // (hundreds of KB each) into the request, which overflows the 200k
39
- // window and burns the daily allowance on image tokens, so keep the
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 plugin therefore
36
- * asks for `medium` by default and keeps the CLI's levels as variants, so
37
- * `none`/`minimal` are still one pick away when speed matters more than care.
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 = "medium";
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
- main.find((model) => model.free === true)?.id ??
189
- catalog?.default_model ??
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);
@@ -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
- const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS);
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;