@eduardo191labs/opencode-free-pi 0.7.26 → 0.7.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -66,53 +66,27 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
66
66
  - Catálogo en vivo de modelos **free-pi** y **free-pi-defense**.
67
67
  - Integración nativa de OpenCode V2 para credenciales OAuth, clave y entorno.
68
68
  - Cuota diaria, créditos premium y límites con mensajes claros.
69
- - **Límites reales de free-pi**: todos los modelos parten de la ventana de
70
- contexto de 200k y el límite de salida de 32k que aplica el CLI del
71
- proveedor, aunque models.dev informe ventanas mayores para el modelo
72
- upstream. El plugin sube la ventana midiendo lo que el gateway acepta de
73
- verdad (hasta 1M) y deja que los modelos con más presupuesto de salida usen
74
- hasta 131k, para que el razonamiento no se corte. Así OpenCode compacta antes
75
- de que el servidor rechace la conversación y aun así aprovecha la capacidad
76
- real de la cuenta.
69
+ - **Límites declarados, no inventados**: el plugin anuncia los límites que
70
+ publica el catálogo de free-pi y deja que OpenCode los use. No sondea la
71
+ ventana en segundo plano ni la sube por su cuenta: una ventana inventada por
72
+ encima de la real hacía que el turno chocara con el gateway y que la
73
+ compactación ni siquiera cupiera.
77
74
  - **Compactación integrada**: los errores `context_too_long` de free-pi se
78
75
  reescriben para que OpenCode los reconozca como desbordamiento de contexto y
79
76
  ejecute `/compact` automáticamente en vez de terminar el turno.
80
- - **Techo por modelo aprendido del gateway**: cuando free-pi rechaza una
81
- petición real por longitud, ese tamaño se guarda en `live-limits.json` como
82
- techo de ese modelo y el catálogo anuncia una ventana un 15 % menor, también
83
- sin reiniciar (`provider.reload`). Así la siguiente compactación empieza antes
84
- de que el gateway rechace también el propio resumen, que es lo que dejaba el
85
- turno detenido con solo el checkpoint en pantalla. Los rechazos causados por
86
- una imagen o un archivo adjunto no cuentan: su base64 no dice nada de la
87
- ventana de texto.
88
- - **Resumen de compactación sin recortes**: el presupuesto de salida de la
89
- petición de compactación ya no se limita a 32k, porque un resumen cortado por
90
- el límite hace fallar la compactación completa. Si aun así el resumen no cabe
91
- en el techo aprendido, se descartan los turnos de usuario más antiguos (sin
92
- romper parejas de herramienta) en lugar de abortar el turno.
93
- - **Ventana reciente en el resumen**: OpenCode sólo conserva el último
94
- intercambio junto al resumen, así que el trabajo hecho justo antes de
95
- compactar desaparecía. El plugin lee la sesión nativa, cita los últimos turnos
96
- (hasta 24k caracteres) en la petición de compactación y exige que el resumen
97
- termine con `## Recent window`, entregándolos también como último mensaje
98
- porque los modelos gratuitos ignoran las reglas del sistema. Esos turnos
99
- viajan una sola vez en la primera petición posterior, por si el resumen los
100
- comprimió de más; caducan a la hora y no se guardan en disco.
101
- - **Poda de resultados antiguos**: las sesiones largas llegan a prompts de
102
- 100k–170k tokens y a ese tamaño los modelos gratuitos pierden el centro de la
103
- conversación y dejan de seguir las reglas, aunque el gateway acepte la
104
- petición. Antes de enviar, el plugin colapsa los resultados de herramientas
105
- antiguos (conserva 600 caracteres de cabecera y 240 del final, con un aviso de
106
- que se podaron), sin tocar el texto de usuario, las decisiones del asistente
107
- ni los mensajes más recientes. El presupuesto es el 40 % de la ventana
108
- anunciada (mínimo 24k), así que el prompt vuelve a la zona donde el modelo
109
- atiende.
77
+ - **Compactación de OpenCode**: quién recorta el historial y cuándo se decide
78
+ lo maneja OpenCode. El plugin no borra mensajes, no recorta resultados de
79
+ herramientas ni reescribe el razonamiento guardado: un historial mutilado hace
80
+ que el modelo olvide lo que ya hizo y repita la misma acción. Solo se aprende,
81
+ sin coste, el techo real de cada modelo cuando el gateway rechaza una petición
82
+ de verdad por longitud, para que la compactación empiece antes del rechazo del
83
+ propio resumen.
110
84
  - **Sin bucles de compactación**: si el servidor rechaza como «demasiado
111
- largo» una petición que cabe de sobra en la ventana (menos de 60k tokens),
112
- el plugin la reintenta con un `x-session-id` nuevo en vez de compactar. Si
113
- aun así la sigue rechazando, devuelve un error de proveedor que OpenCode no
114
- clasifica como desbordamiento, para no gastar créditos en resúmenes que no
115
- arreglan nada.
85
+ largo» una petición que cabe en la ventana medida del modelo, el plugin no la
86
+ vuelve a enviar por su cuenta (eso ejecutaba la misma acción dos veces); deja
87
+ que OpenCode compacte una vez y, si el rechazo se repite, devuelve un error de
88
+ proveedor que OpenCode no clasifica como desbordamiento, para no gastar
89
+ créditos en resúmenes que no arreglan nada.
116
90
  - **Títulos locales**: OpenCode pide un título al modelo al crear una sesión.
117
91
  El plugin lo responde con la primera línea del primer mensaje, sin gastar
118
92
  créditos, sin pedir un anuncio y sin dejar la sesión atascada en
@@ -130,7 +104,7 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
130
104
  - **Subagentes identificados**: las sesiones hijas envían
131
105
  `x-freepi-subagent: 1`, igual que los proveedores que el CLI crea para sus
132
106
  subagentes.
133
- - **Pensamiento por defecto**: el plugin pide `reasoning_effort: "high"`
107
+ - **Pensamiento por defecto**: el plugin pide `reasoning_effort: "max"`
134
108
  cuando el modelo no trae variante elegida. Dejarlo sin definir hacía que los
135
109
  modelos gratuitos respondieran con prisa, gastando apenas unas decenas de
136
110
  tokens de razonamiento incluso en tareas que requieren planificar. El
@@ -140,10 +114,11 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
140
114
  usan `high` por defecto. La opción `reasoningEffort: false` del plugin
141
115
  recupera el nivel del servidor. No se anuncian `thinking_budget` ni
142
116
  `thinking`, porque la ruta `openai-compatible` de OpenCode los descarta.
143
- - **Más razonamiento real**: medido con `curl_cffi` contra el gateway, cambiar
144
- `reasoning_effort` no altera cuánto piensa el modelo (los tokens de
145
- razonamiento varían al azar entre ~60 y ~600 en cada nivel) y los modelos
146
- `flash` se detienen solos en la primera respuesta plausible. Lo que sí
117
+ - **Más razonamiento real**: medido con `curl_cffi` contra el gateway, subir
118
+ `reasoning_effort` sí alarga el razonamiento (medido: `max` produjo más
119
+ tokens de razonamiento que `high` en la misma tarea), pero los modelos
120
+ `flash` se detienen solos en la primera respuesta plausible, así que el nivel
121
+ solo no basta. Lo que sí
147
122
  funciona es pedir el trabajo explícito: con la regla de «escribe cada paso,
148
123
  recalcula por un segundo método y no respondas hasta que coincidan», el mismo
149
124
  modelo subió de ~450 a ~1250 tokens de razonamiento y acertó 5/5 problemas de
@@ -155,25 +130,17 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
155
130
  publica el upstream (32k por defecto, hasta 131k). No se fuerza temperatura ni
156
131
  `top_p`: la petición real no los incluye, así que el gateway aplica su propio
157
132
  valor. El prompt se envía con rol `system`, no `developer`.
158
- - **Sin razonamiento reenviado**: OpenCode guarda el pensamiento del modelo en
159
- los mensajes del asistente y lo devuelve dentro de `reasoning_content`. La
160
- captura con `curl_cffi` mostró que el gateway lo cobra como entrada (mismo
161
- prompt y misma respuesta pasaron de 27 a 188 tokens en `glm-5.3-flash`), así
162
- que el plugin lo quita antes de enviar. No cambia la respuesta: el modelo ya
163
- razonó en su turno y el historial conserva el texto visible.
164
- - **Límites medidos, no inventados**: `/client-version` solo devuelve id,
133
+ - **El razonamiento guardado se conserva**: el historial se envía tal como
134
+ OpenCode lo guarda, incluido el `reasoning_content` de cada turno. Borrarlo
135
+ para ahorrar tokens hacía que un modelo de razonamiento perdiera el motivo de
136
+ sus decisiones y repitiera la misma acción.
137
+ - **Límites declarados por el catálogo**: `/client-version` solo devuelve id,
165
138
  nombre, `free`, `section`, `note`, `stats_id` y `usage_x`; no hay endpoint de
166
- capacidades ni de ventana. El plugin no se queda en constantes: confirma la
167
- ventana compilada y después la agranda mientras el gateway acepte prompts
168
- mayores, con búsqueda binaria al primer rechazo y un 3 % de margen. Guarda el
169
- resultado en `live-limits.json` y anota en cada paso los tokens de prompt y de
170
- razonamiento que el servidor confirma. `liveLimits: false` desactiva la
171
- comprobación y deja la ventana compilada.
172
- - **Reglas de trabajo en el prompt**: cada petición principal de free-pi añade
173
- un bloque corto al system prompt con lo que los modelos gratuitos suelen
174
- omitir: leer antes de editar, ejecutar las comprobaciones de verdad, no
175
- afirmar que algo pasó si no se ejecutó, reutilizar las decisiones y rutas ya
176
- establecidas en la conversación y no fingir que se compactó el contexto.
139
+ capacidades ni de ventana. El plugin anuncia los límites que el catálogo
140
+ publica y deja el resto a OpenCode. Lo único que se aprende en vivo, sin
141
+ coste, es el techo de un modelo cuando el gateway rechaza una petición real
142
+ por longitud; ese dato se guarda en `live-limits.json` para que la siguiente
143
+ compactación empiece antes.
177
144
  Además, cuando una herramienta falla por un motivo que el modelo repite (un
178
145
  heredoc rechazado por el scanner del shell, un `edit` con cadenas idénticas o
179
146
  con un `oldString` ambiguo), el error que recibe añade el siguiente paso
@@ -202,7 +202,10 @@ async function sendProbe(deps, modelID, chars) {
202
202
  "content-type": "application/json",
203
203
  authorization: `Bearer ${token}`,
204
204
  "x-client-version": deps.state.latestClientVersion,
205
- "x-session-id": `free-pi-window-${Date.now().toString(36)}`,
205
+ "x-session-id": `free-pi-window-${Date.now().toString(36)}-${Math
206
+ .random()
207
+ .toString(36)
208
+ .slice(2, 8)}`,
206
209
  "x-ad-context": "none",
207
210
  },
208
211
  body: JSON.stringify({
@@ -23,7 +23,7 @@ export declare function isReasoningEffort(value: unknown): value is string;
23
23
  /**
24
24
  * The effort sent when no variant is selected. `false` leaves the gateway's
25
25
  * own default untouched; otherwise the catalog's supported levels win over
26
- * `medium`, so a model that only accepts `low`/`high` never gets an effort it
26
+ * `high`, so a model that only accepts `low`/`high` never gets an effort it
27
27
  * would reject.
28
28
  */
29
29
  export declare function preferredReasoningEffort(options: ReasoningOption[] | undefined, configured?: string | false): string | undefined;
@@ -170,7 +170,7 @@ export function isReasoningEffort(value) {
170
170
  /**
171
171
  * The effort sent when no variant is selected. `false` leaves the gateway's
172
172
  * own default untouched; otherwise the catalog's supported levels win over
173
- * `medium`, so a model that only accepts `low`/`high` never gets an effort it
173
+ * `high`, so a model that only accepts `low`/`high` never gets an effort it
174
174
  * would reject.
175
175
  */
176
176
  export function preferredReasoningEffort(options, configured) {
@@ -179,10 +179,21 @@ export function preferredReasoningEffort(options, configured) {
179
179
  if (configured)
180
180
  return configured;
181
181
  // The provider CLI's levels are the source of truth: models.dev often lists
182
- // only a subset, but the gateway accepts the CLI set. `medium` is the sane
183
- // middle ground between the CLI's off default and burning tokens on `high`.
182
+ // only a subset, but the gateway accepts the CLI set. A catalog that lists
183
+ // explicit effort options gets the highest one it lists (a budget-style
184
+ // catalog maps to `high`, the closest explicit level to a token budget);
185
+ // everything else gets the plugin default (`max`), which thinks longest.
184
186
  if (options?.some((option) => option.type === "budget_tokens"))
185
187
  return "high";
188
+ const listed = options
189
+ ?.flatMap((option) => option.type === "effort" && Array.isArray(option.values) ? option.values : [])
190
+ .filter((value) => REASONING_EFFORTS.includes(value));
191
+ if (listed && listed.length > 0) {
192
+ return listed.reduce((best, value) => REASONING_EFFORTS.indexOf(value) >
193
+ REASONING_EFFORTS.indexOf(best)
194
+ ? value
195
+ : best, listed[0]);
196
+ }
186
197
  return DEFAULT_REASONING_EFFORT;
187
198
  }
188
199
  export function accountAccess(me) {
@@ -7,6 +7,15 @@ export declare const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
7
7
  export declare const DEFAULT_BASE_URL = "https://api.freepi.ai";
8
8
  export declare const DEFAULT_CLIENT_VERSION = "0.6.28";
9
9
  export declare const CONSENT_VERSION = "4";
10
+ /**
11
+ * The model a fresh session gets when the user has not chosen one. The
12
+ * catalog's own `default_model` points at the fastest cheap model, which is
13
+ * right for the phone app but wrong for coding work: an unset effort makes the
14
+ * free models answer before they think. `glm-5.3-flash` reasons longest of the
15
+ * free models, so it is the better default here; the catalog default stays the
16
+ * fallback when this id ever disappears.
17
+ */
18
+ export declare const DEFAULT_FREE_MODEL_ID = "glm-5.3-flash";
10
19
  /**
11
20
  * The provider CLI's window. The gateway enforces its own ceiling but does not
12
21
  * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
@@ -16,15 +25,6 @@ export declare const CONTEXT_WINDOW = 200000;
16
25
  /** Largest window the plugin will ever advertise after measuring the gateway. */
17
26
  export declare const MAX_CONTEXT_WINDOW = 1000000;
18
27
  export declare const MAX_OUTPUT_TOKENS = 32768;
19
- /**
20
- * Share of the advertised window a primary request may occupy before stale
21
- * tool results are collapsed. Long free-pi sessions reach 100k-170k prompts
22
- * and the free models then lose the middle of the conversation even though the
23
- * gateway still accepts them.
24
- */
25
- export declare const CONTEXT_DIET_SHARE = 0.4;
26
- /** Below this window the diet is pointless: the request is small anyway. */
27
- export declare const CONTEXT_DIET_MIN_TOKENS = 24000;
28
28
  /**
29
29
  * Upper bound for a model that publishes a larger output budget. Reasoning
30
30
  * tokens share this budget, so a model that can emit more must not be pinned to
@@ -47,10 +47,13 @@ export declare const SUBAGENT_HEADER = "x-freepi-subagent";
47
47
  * dozen reasoning tokens even on tasks that need planning. The gateway accepts
48
48
  * every level (measured with curl_cffi) but currently does not let the level
49
49
  * change how long the upstream thinks, so the plugin also asks for explicit
50
- * step-by-step checking in the prompt and defaults to `high`. `none`/`minimal`
51
- * stay one pick away when speed matters more than care.
50
+ * step-by-step checking in the prompt and defaults to `max`. The gateway
51
+ * accepts every level (measured with curl_cffi) and the reasoning_tokens in
52
+ * the usage response vary with the level, so `max` is the level that thinks
53
+ * longest. `none`/`minimal` stay one pick away when speed matters more than
54
+ * care.
52
55
  */
53
- export declare const DEFAULT_REASONING_EFFORT = "high";
56
+ export declare const DEFAULT_REASONING_EFFORT = "max";
54
57
  export declare const REASONING_EFFORTS: readonly ["none", "minimal", "low", "medium", "high", "max"];
55
58
  export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low", "medium", "high", "max"];
56
59
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
@@ -80,7 +83,6 @@ export declare const CONCURRENT_RETRY_MAX_DELAY_MS = 15000;
80
83
  /** Tool outcome headers emitted by the free-pi provider CLI. */
81
84
  export declare const TOOL_META_HEADER = "x-freepi-tool-meta";
82
85
  export declare const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
83
- export declare const COMPACTED_HEADER = "x-freepi-compacted";
84
86
  export declare const TOOL_META_BUDGET = 1500;
85
87
  export declare const TOOL_ID_LIMIT = 50;
86
88
  export declare const SESSION_TRACK_LIMIT = 200;
package/dist/constants.js CHANGED
@@ -7,6 +7,15 @@ export const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
7
7
  export const DEFAULT_BASE_URL = "https://api.freepi.ai";
8
8
  export const DEFAULT_CLIENT_VERSION = "0.6.28";
9
9
  export const CONSENT_VERSION = "4";
10
+ /**
11
+ * The model a fresh session gets when the user has not chosen one. The
12
+ * catalog's own `default_model` points at the fastest cheap model, which is
13
+ * right for the phone app but wrong for coding work: an unset effort makes the
14
+ * free models answer before they think. `glm-5.3-flash` reasons longest of the
15
+ * free models, so it is the better default here; the catalog default stays the
16
+ * fallback when this id ever disappears.
17
+ */
18
+ export const DEFAULT_FREE_MODEL_ID = "glm-5.3-flash";
10
19
  /**
11
20
  * The provider CLI's window. The gateway enforces its own ceiling but does not
12
21
  * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
@@ -16,15 +25,6 @@ export const CONTEXT_WINDOW = 200_000;
16
25
  /** Largest window the plugin will ever advertise after measuring the gateway. */
17
26
  export const MAX_CONTEXT_WINDOW = 1_000_000;
18
27
  export const MAX_OUTPUT_TOKENS = 32_768;
19
- /**
20
- * Share of the advertised window a primary request may occupy before stale
21
- * tool results are collapsed. Long free-pi sessions reach 100k-170k prompts
22
- * and the free models then lose the middle of the conversation even though the
23
- * gateway still accepts them.
24
- */
25
- export const CONTEXT_DIET_SHARE = 0.4;
26
- /** Below this window the diet is pointless: the request is small anyway. */
27
- export const CONTEXT_DIET_MIN_TOKENS = 24_000;
28
28
  /**
29
29
  * Upper bound for a model that publishes a larger output budget. Reasoning
30
30
  * tokens share this budget, so a model that can emit more must not be pinned to
@@ -47,10 +47,13 @@ export const SUBAGENT_HEADER = "x-freepi-subagent";
47
47
  * dozen reasoning tokens even on tasks that need planning. The gateway accepts
48
48
  * every level (measured with curl_cffi) but currently does not let the level
49
49
  * change how long the upstream thinks, so the plugin also asks for explicit
50
- * step-by-step checking in the prompt and defaults to `high`. `none`/`minimal`
51
- * stay one pick away when speed matters more than care.
50
+ * step-by-step checking in the prompt and defaults to `max`. The gateway
51
+ * accepts every level (measured with curl_cffi) and the reasoning_tokens in
52
+ * the usage response vary with the level, so `max` is the level that thinks
53
+ * longest. `none`/`minimal` stay one pick away when speed matters more than
54
+ * care.
52
55
  */
53
- export const DEFAULT_REASONING_EFFORT = "high";
56
+ export const DEFAULT_REASONING_EFFORT = "max";
54
57
  export const REASONING_EFFORTS = [
55
58
  "none",
56
59
  "minimal",
@@ -94,7 +97,6 @@ export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
94
97
  /** Tool outcome headers emitted by the free-pi provider CLI. */
95
98
  export const TOOL_META_HEADER = "x-freepi-tool-meta";
96
99
  export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
97
- export const COMPACTED_HEADER = "x-freepi-compacted";
98
100
  export const TOOL_META_BUDGET = 1_500;
99
101
  export const TOOL_ID_LIMIT = 50;
100
102
  export const SESSION_TRACK_LIMIT = 200;
package/dist/plugin.js CHANGED
@@ -6,11 +6,10 @@ import { closeFreePiSession } from "./api/session.js";
6
6
  import { readCredentialsToken } from "./auth/credentials.js";
7
7
  import { tokenFromCredential } from "./auth/credential.js";
8
8
  import { fetchCatalog } from "./catalog/catalog.js";
9
- import { currentLiveLimits, loadLiveLimits, shouldVerifyWindow, verifyGatewayWindow, } from "./catalog/live.js";
10
9
  import { accountAccess, buildModels, filterAccessibleModels, isReasoningEffort, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
11
10
  import { fetchModelsRegistry } from "./catalog/registry.js";
12
11
  import { applyProvider } from "./catalog/v2.js";
13
- import { CATALOG_RECOVERY_DELAYS_MS, CATALOG_RECOVERY_INTERVAL_MS, CATALOG_RECOVERY_LOG_EVERY, DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "./constants.js";
12
+ import { CATALOG_RECOVERY_DELAYS_MS, CATALOG_RECOVERY_INTERVAL_MS, CATALOG_RECOVERY_LOG_EVERY, DEFAULT_FREE_MODEL_ID, DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "./constants.js";
14
13
  import { registerIntegration } from "./integration/setup.js";
15
14
  import { createLogger } from "./logging.js";
16
15
  import { applyDirectNetwork } from "./network/direct.js";
@@ -159,10 +158,8 @@ async function setup(ctx) {
159
158
  let currentMain = filterAccessibleModels(catalogMain, access);
160
159
  let currentDefense = filterAccessibleModels(catalogDefense, access);
161
160
  const candidates = modelRegistryCandidates(registry);
162
- const live = await loadLiveLimits();
163
161
  const configuredEffort = ctx.options?.reasoningEffort;
164
162
  const buildOptions = {
165
- live,
166
163
  ...(configuredEffort === false
167
164
  ? { reasoningEffort: false }
168
165
  : isReasoningEffort(configuredEffort)
@@ -182,29 +179,19 @@ async function setup(ctx) {
182
179
  }
183
180
  return kept;
184
181
  };
185
- // Rebuilt on every call so a learned context ceiling or a recovered catalog
186
- // applies without restarting OpenCode.
187
- const buildMain = () => withoutDenied(PROVIDER_ID, buildModels(currentMain, candidates, {
188
- ...buildOptions,
189
- live: currentLiveLimits() ?? live,
190
- }));
191
- const buildDefense = () => withoutDenied(DEFENSE_PROVIDER_ID, buildModels(currentDefense, candidates, {
192
- ...buildOptions,
193
- live: currentLiveLimits() ?? live,
194
- }));
182
+ // Rebuilt on every call so a recovered catalog or a refreshed quota applies
183
+ // without restarting OpenCode.
184
+ const buildMain = () => withoutDenied(PROVIDER_ID, buildModels(currentMain, candidates, buildOptions));
185
+ const buildDefense = () => withoutDenied(DEFENSE_PROVIDER_ID, buildModels(currentDefense, candidates, buildOptions));
195
186
  function indexModelState() {
196
187
  const mainNow = buildMain();
197
188
  const defenseNow = buildDefense();
198
189
  for (const [id, model] of Object.entries(mainNow)) {
199
- state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
200
- state.contextLimits.set(`${PROVIDER_ID}/${id}`, model.limit.context);
201
190
  if (model.modalities.input.includes("image")) {
202
191
  state.imageModels.add(`${PROVIDER_ID}/${id}`);
203
192
  }
204
193
  }
205
194
  for (const [id, model] of Object.entries(defenseNow)) {
206
- state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
207
- state.contextLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.context);
208
195
  if (model.modalities.input.includes("image")) {
209
196
  state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
210
197
  }
@@ -217,7 +204,7 @@ async function setup(ctx) {
217
204
  await registerIntegration(ctx, deps);
218
205
  await ctx.provider.transform((editor) => {
219
206
  // Re-index on every transform: a learned context/output ceiling changes the
220
- // built model, and the diet and maxTokens cap read these maps. Refreshing
207
+ // built model, and the maxTokens cap reads these maps. Refreshing
221
208
  // only at setup would keep budgeting against the old window after a reload.
222
209
  indexModelState();
223
210
  applyProvider(editor, PROVIDER_ID, "Free Pi", buildMain(), state.providerToken);
@@ -225,37 +212,18 @@ async function setup(ctx) {
225
212
  applyProvider(editor, DEFENSE_PROVIDER_ID, "Free Pi Defense", buildDefense(), state.providerToken);
226
213
  }
227
214
  });
228
- // The gateway does not publish its context ceiling. Verify the compiled
229
- // window against it once a week with a free model, in the background, and
230
- // persist the result for the next catalog build. Prefer the free model with
231
- // the largest prompt already accepted in real traffic: it has the most
232
- // evidence behind it, so the growth probes describe the window sessions use.
233
- if (ctx.options?.liveLimits !== false && shouldVerifyWindow(live)) {
234
- const free = currentMain.filter((model) => model.free === true && typeof model.id === "string");
235
- const probe = free
236
- .map((model) => ({
237
- id: model.id,
238
- seen: live?.models[model.id ?? ""]?.maxPromptTokens ?? 0,
239
- }))
240
- .sort((a, b) => b.seen - a.seen)[0]?.id ??
241
- (currentCatalog?.default_model &&
242
- free.some((model) => model.id === currentCatalog?.default_model)
243
- ? currentCatalog.default_model
244
- : undefined) ??
245
- free[0]?.id ??
246
- Object.keys(buildMain())[0];
247
- if (probe) {
248
- void verifyGatewayWindow(deps, { model: probe }).catch(() => undefined);
249
- }
250
- }
251
- // V1 selected the catalog default when the user had no model configured.
215
+ // A fresh session gets the model that reasons longest of the free ones, not
216
+ // the catalog's phone-app default (`particle`, the fastest cheap model). The
217
+ // catalog default stays the fallback for the day this id disappears.
252
218
  await ctx.model.transform((editor) => {
253
219
  if (editor.default.get())
254
220
  return;
255
221
  const models = buildMain();
256
- const preferred = (currentCatalog?.default_model && models[currentCatalog.default_model]
257
- ? currentCatalog.default_model
258
- : undefined) ?? Object.keys(models)[0];
222
+ const preferred = (models[DEFAULT_FREE_MODEL_ID] ? DEFAULT_FREE_MODEL_ID : undefined) ??
223
+ (currentCatalog?.default_model && models[currentCatalog.default_model]
224
+ ? currentCatalog.default_model
225
+ : undefined) ??
226
+ Object.keys(models)[0];
259
227
  if (preferred)
260
228
  editor.default.set(PROVIDER_ID, preferred);
261
229
  });