@eduardo191labs/opencode-free-pi 0.7.31 → 0.7.33

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
@@ -123,9 +123,10 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
123
123
  funciona es pedir el trabajo explícito: con la regla de «escribe cada paso,
124
124
  recalcula por un segundo método y no respondas hasta que coincidan», el mismo
125
125
  modelo subió de ~450 a ~1250 tokens de razonamiento y acertó 5/5 problemas de
126
- lógica frente a 3/5 sin la regla. Por eso la guía de trabajo prioriza la
127
- respuesta lenta y verificada, y el límite de salida se deja amplio para que
128
- esa cadena no se trunque.
126
+ lógica frente a 3/5 sin la regla. Esa instrucción es una recomendación de uso
127
+ para tu mensaje, no un prompt que el plugin inyecte: el plugin no añade
128
+ instrucciones a la sesión. El límite de salida se deja amplio para que la
129
+ cadena de razonamiento no se trunque.
129
130
  - **Capacidades iguales al CLI**: todos los modelos se registran con
130
131
  razonamiento activo, coste cero, la ventana medida y el límite de salida que
131
132
  publica el upstream (32k por defecto, hasta 131k). No se fuerza temperatura ni
@@ -139,18 +140,11 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
139
140
  nombre, `free`, `section`, `note`, `stats_id` y `usage_x`; no hay endpoint de
140
141
  capacidades ni de ventana. El plugin anuncia los límites que el catálogo
141
142
  publica y deja el resto a OpenCode. Lo único que se aprende en vivo, sin
142
- coste, es el techo de un modelo cuando el gateway rechaza una petición real
143
- por longitud; ese dato se guarda en `live-limits.json` para que la siguiente
144
- compactación empiece antes.
145
- Además, cuando una herramienta falla por un motivo que el modelo repite (un
146
- heredoc rechazado por el scanner del shell, un `edit` con cadenas idénticas o
147
- con un `oldString` ambiguo), el error que recibe añade el siguiente paso
148
- concreto en lugar de dejar solo el mensaje técnico.
149
- - **Compactación con instrucciones**: el resumen de compactación recibe además
150
- un bloque que le pide conservar requisitos sin resolver, decisiones y sus
151
- motivos, rutas y símbolos exactos, comandos con su resultado, errores y
152
- trabajo pendiente. Sin eso, los modelos gratuitos producían resúmenes
153
- demasiado escuetos para continuar la tarea.
143
+ enviar peticiones extra, es el techo de un modelo cuando el gateway rechaza
144
+ una petición real por longitud; ese dato se guarda en `live-limits.json` para
145
+ que la siguiente compactación empiece antes. Las instrucciones del resumen y
146
+ las pistas de las herramientas son de OpenCode: el plugin no añade prompts ni
147
+ modifica los mensajes de error.
154
148
  - **Solo modelos utilizables**: al arrancar se consulta `/me` y el selector
155
149
  `/model` incluye únicamente lo que la cuenta puede usar: los modelos
156
150
  `free: true` siempre, los de pago mientras queden créditos de la cuota o
@@ -161,11 +155,11 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
161
155
  - **Timeouts del CLI**: 5 minutos para las cabeceras y para cada trozo de la
162
156
  respuesta, los mismos valores que `httpIdleTimeoutMs` de pi.
163
157
  - Anuncios e impresiones asociados al turno correcto. El contexto del anuncio se
164
- construye solo con el último mensaje real del usuario: se ignoran el
165
- recordatorio del plugin y los mensajes sintéticos que OpenCode inserta en el
166
- mismo turno (resultado de un subagente, salida de un shell en segundo plano,
167
- AGENTS.md, reinicio del servidor o respuesta interrumpida), que antes
168
- rotaban el anuncio a mitad de turno y enviaban ids internos como contexto.
158
+ construye solo con el último mensaje real del usuario: se ignoran los
159
+ mensajes sintéticos que OpenCode inserta en el mismo turno (resultado de un
160
+ subagente, salida de un shell en segundo plano, AGENTS.md, reinicio del
161
+ servidor o respuesta interrumpida), que antes rotaban el anuncio a mitad de
162
+ turno y enviaban ids internos como contexto.
169
163
  - Cada agente y subagente usa su propio `x-session-id`, `x-turn-id` y contexto
170
164
  de anuncios; nunca reutiliza los del agente principal.
171
165
  - **Cierre de sesión**: free-pi limita la cuenta a 4 sesiones simultáneas. El
@@ -429,8 +423,9 @@ plugin solo conserva en:
429
423
  ~/.cache/opencode/free-pi/live-limits.json
430
424
  ```
431
425
 
432
- la ventana de contexto que midió contra el gateway y lo que cada paso real
433
- demostró sobre el modelo. Esa medición se vuelve a comprobar cada 7 días.
426
+ la ventana de contexto que los pasos reales demostraron y el techo que un
427
+ rechazo del gateway confirmó para cada modelo. No se envían peticiones de
428
+ sondeo: el archivo solo se actualiza con tráfico que ya ocurrió.
434
429
 
435
430
  En Windows es `%USERPROFILE%\.cache\opencode\free-pi\`.
436
431
 
@@ -3,10 +3,10 @@
3
3
  *
4
4
  * free-pi's HTTP API never publishes per-model limits: `/client-version` only
5
5
  * carries id/name/free/section/note/stats_id, `/me` carries the quota, and chat
6
- * responses carry usage but no window. The gateway does enforce a real ceiling,
7
- * so the plugin verifies the advertised window against the gateway itself and
8
- * remembers what it learned. The measured value replaces the compiled default
9
- * on the next start; a probe failure leaves the previous value untouched.
6
+ * responses carry usage but no window. The plugin therefore learns only from
7
+ * traffic that already happened: a step proves the gateway accepted its prompt,
8
+ * and a real "too long" rejection proves the model's hard ceiling. Nothing is
9
+ * probed, so learning never spends allowance; the values survive a restart.
10
10
  */
11
11
  import type { Deps } from "../deps.js";
12
12
  import type { TokenUsageLike } from "../types.js";
@@ -21,7 +21,7 @@ export type ModelObservation = {
21
21
  };
22
22
  export type LiveLimits = {
23
23
  version: 1;
24
- /** Window verified against the gateway, used for the next catalog build. */
24
+ /** Largest window real traffic proved, used for the next catalog build. */
25
25
  window?: {
26
26
  tokens: number;
27
27
  verifiedAt: number;
@@ -55,33 +55,3 @@ export declare function learnedContextWindow(limits: LiveLimits | undefined, mod
55
55
  * the next build on. Returns the window that now applies, if it changed.
56
56
  */
57
57
  export declare function noteRejectedPrompt(deps: Deps, modelID: string, tokens: number): number | undefined;
58
- /** Whether the persisted window is old enough to verify again. */ export declare function shouldVerifyWindow(limits: LiveLimits | undefined): boolean;
59
- export type VerifyLimitsOptions = {
60
- /** A free model to probe with; paid models would spend credits. */
61
- model?: string;
62
- /** Window to check. Defaults to the measured one, then the compiled one. */
63
- window?: number;
64
- };
65
- /** One gateway answer used to settle the advertised window. */
66
- export type ProbeSample = {
67
- chars: number;
68
- /** Prompt tokens the gateway reported for an accepted probe. */
69
- tokens?: number;
70
- tooLong: boolean;
71
- };
72
- /**
73
- * Largest window the accepted probes prove, with headroom. Pure so the probe
74
- * loop and the persisted value can be tested without a server.
75
- */
76
- export declare function settleWindow(samples: readonly ProbeSample[]): number | undefined;
77
- /**
78
- * Checks the compiled window against the gateway and then grows past it while
79
- * the gateway keeps accepting larger prompts. The start value is a floor, not a
80
- * ceiling: the server has no endpoint for its real limit, and pinning sessions
81
- * to the CLI's 200k wastes capacity the account can actually use. On rejection
82
- * it binary-searches between the largest accepted prompt and the rejected one,
83
- * so the next catalog build advertises the measured window. Returns the verified
84
- * window, or `undefined` when nothing could be learned (the previous value is
85
- * kept).
86
- */
87
- export declare function verifyGatewayWindow(deps: Deps, options?: VerifyLimitsOptions): Promise<number | undefined>;
@@ -3,29 +3,18 @@
3
3
  *
4
4
  * free-pi's HTTP API never publishes per-model limits: `/client-version` only
5
5
  * carries id/name/free/section/note/stats_id, `/me` carries the quota, and chat
6
- * responses carry usage but no window. The gateway does enforce a real ceiling,
7
- * so the plugin verifies the advertised window against the gateway itself and
8
- * remembers what it learned. The measured value replaces the compiled default
9
- * on the next start; a probe failure leaves the previous value untouched.
6
+ * responses carry usage but no window. The plugin therefore learns only from
7
+ * traffic that already happened: a step proves the gateway accepted its prompt,
8
+ * and a real "too long" rejection proves the model's hard ceiling. Nothing is
9
+ * probed, so learning never spends allowance; the values survive a restart.
10
10
  */
11
11
  import { mkdir, readFile, writeFile } from "node:fs/promises";
12
12
  import { dirname } from "node:path";
13
- import { resolveToken } from "../auth/token.js";
14
- import { CONTEXT_WINDOW, VERIFY_LIMITS_TTL_MS, } from "../constants.js";
15
13
  import { dataPath } from "../utils/data-dir.js";
16
- import { completionsBaseUrl } from "../utils/urls.js";
17
14
  const FILE = "live-limits.json";
18
15
  const WRITE_DEBOUNCE_MS = 2_000;
19
- /** Verification stops shrinking here instead of advertising a useless window. */
20
- const MIN_WINDOW = 32_768;
21
- /** Hard stop for the upward search; `buildModels` never advertises more. */
16
+ /** `buildModels` never advertises a window larger than this. */
22
17
  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;
29
18
  let cached;
30
19
  let loaded = false;
31
20
  let writeTimer;
@@ -178,190 +167,3 @@ export function noteRejectedPrompt(deps, modelID, tokens) {
178
167
  deps.log.warn("free-pi rejected a prompt as too long; lowering the advertised window", { model: modelID, rejectedTokens: rejected, previous, window });
179
168
  return window;
180
169
  }
181
- /** Whether the persisted window is old enough to verify again. */ export function shouldVerifyWindow(limits) {
182
- const verifiedAt = limits?.window?.verifiedAt;
183
- if (!verifiedAt)
184
- return true;
185
- return Date.now() - verifiedAt > VERIFY_LIMITS_TTL_MS;
186
- }
187
- function filler(chars) {
188
- const unit = "the quick brown fox jumps over the lazy dog while maintainers review the patch and debate naming ";
189
- return unit.repeat(Math.ceil(chars / unit.length)).slice(0, chars);
190
- }
191
- async function sendProbe(deps, modelID, chars) {
192
- const token = await resolveToken(deps).catch(() => undefined);
193
- if (!token)
194
- return { status: "failed" };
195
- const content = `${filler(chars)}\n\nIgnore the filler and reply with OK.`;
196
- let response;
197
- try {
198
- response = await fetch(`${completionsBaseUrl()}/chat/completions`, {
199
- method: "POST",
200
- headers: {
201
- accept: "application/json",
202
- "content-type": "application/json",
203
- authorization: `Bearer ${token}`,
204
- "x-client-version": deps.state.latestClientVersion,
205
- "x-session-id": `free-pi-window-${Date.now().toString(36)}-${Math
206
- .random()
207
- .toString(36)
208
- .slice(2, 8)}`,
209
- "x-ad-context": "none",
210
- },
211
- body: JSON.stringify({
212
- model: modelID,
213
- messages: [{ role: "user", content }],
214
- stream: false,
215
- max_tokens: 256,
216
- }),
217
- signal: AbortSignal.timeout(180_000),
218
- });
219
- }
220
- catch {
221
- return { status: "failed" };
222
- }
223
- if (response.status === 413 || response.status === 400) {
224
- const body = await response.text().catch(() => "");
225
- if (/context_too_long|too long|context_ceiling/i.test(body)) {
226
- return { status: "too_long" };
227
- }
228
- return { status: "failed" };
229
- }
230
- if (!response.ok)
231
- return { status: "failed" };
232
- const payload = (await response.json().catch(() => undefined));
233
- const promptTokens = payload?.usage?.prompt_tokens;
234
- return {
235
- status: "ok",
236
- ...(typeof promptTokens === "number" ? { promptTokens } : {}),
237
- };
238
- }
239
- /**
240
- * Largest window the accepted probes prove, with headroom. Pure so the probe
241
- * loop and the persisted value can be tested without a server.
242
- */
243
- export function settleWindow(samples) {
244
- let best = 0;
245
- for (const sample of samples) {
246
- if (sample.tooLong)
247
- continue;
248
- if (!Number.isFinite(sample.tokens) || (sample.tokens ?? 0) <= 0)
249
- continue;
250
- if (sample.tokens <= best)
251
- continue;
252
- best = sample.tokens;
253
- }
254
- if (best === 0)
255
- return undefined;
256
- return Math.min(MAX_WINDOW, Math.max(MIN_WINDOW, Math.floor((best * WINDOW_SAFETY) / 1_000) * 1_000));
257
- }
258
- /**
259
- * Stores a measured window and writes it immediately. Called after every
260
- * accepted probe, so a process that exits mid-verification keeps the smallest
261
- * proven value instead of losing the whole run.
262
- */
263
- async function commitWindow(tokens, modelID) {
264
- const limits = (cached ??= emptyLimits());
265
- // The measured ceiling belongs to the model probed, not to every model: the
266
- // gateway's limit is per model, and a global window taken from one model
267
- // would advertise capacity another one rejects. The per-model value is what
268
- // `buildModels` reads for that model; the global window stays as the
269
- // fallback for models never probed.
270
- const entry = observation(modelID);
271
- if ((entry.maxPromptTokens ?? 0) < tokens) {
272
- entry.maxPromptTokens = tokens;
273
- entry.updatedAt = Date.now();
274
- }
275
- if (limits.window && limits.window.tokens >= tokens)
276
- return limits.window.tokens;
277
- limits.window = { tokens, verifiedAt: Date.now(), model: modelID };
278
- loaded = true;
279
- await persist();
280
- return tokens;
281
- }
282
- /**
283
- * Checks the compiled window against the gateway and then grows past it while
284
- * the gateway keeps accepting larger prompts. The start value is a floor, not a
285
- * ceiling: the server has no endpoint for its real limit, and pinning sessions
286
- * to the CLI's 200k wastes capacity the account can actually use. On rejection
287
- * it binary-searches between the largest accepted prompt and the rejected one,
288
- * so the next catalog build advertises the measured window. Returns the verified
289
- * window, or `undefined` when nothing could be learned (the previous value is
290
- * kept).
291
- */
292
- export async function verifyGatewayWindow(deps, options = {}) {
293
- const modelID = options.model;
294
- if (!modelID)
295
- return undefined;
296
- const fallback = options.window ?? cached?.window?.tokens ?? CONTEXT_WINDOW;
297
- const samples = [];
298
- // Accepted prompt tokens; also the lower bound of the binary search.
299
- let accepted = 0;
300
- let charsPerToken = INITIAL_CHARS_PER_TOKEN;
301
- let target = Math.max(MIN_WINDOW, Math.min(fallback, MAX_WINDOW));
302
- let verified;
303
- const floor = Math.min(fallback, CONTEXT_WINDOW);
304
- for (let attempt = 0; attempt < MAX_PROBES; attempt += 1) {
305
- const chars = Math.max(MIN_WINDOW * charsPerToken, Math.floor(target * charsPerToken * 0.99));
306
- const result = await sendProbe(deps, modelID, chars);
307
- if (result.status === "failed") {
308
- // A network failure or a rejected body proves nothing; keep what the
309
- // earlier probes already established.
310
- if (samples.length === 0)
311
- return verified;
312
- break;
313
- }
314
- if (result.status === "too_long") {
315
- samples.push({ chars, tooLong: true });
316
- if (accepted === 0) {
317
- // The compiled window itself is too large: step down as before.
318
- target = Math.floor(target * 0.85);
319
- if (target < MIN_WINDOW)
320
- break;
321
- continue;
322
- }
323
- const next = Math.floor((accepted + target) / 2);
324
- if (next <= accepted)
325
- break;
326
- target = next;
327
- continue;
328
- }
329
- const tokens = result.promptTokens;
330
- samples.push({
331
- chars,
332
- tooLong: false,
333
- ...(tokens && tokens > 0 ? { tokens } : {}),
334
- });
335
- if (tokens && tokens > 0) {
336
- accepted = tokens;
337
- // Learn the real characters-per-token ratio for this prompt shape; the
338
- // filler is prose, and four chars/token overshoots badly.
339
- charsPerToken = chars / tokens;
340
- }
341
- else {
342
- accepted = Math.floor(chars / charsPerToken);
343
- }
344
- const settled = settleWindow(samples);
345
- if (settled) {
346
- // Never go below the window that already worked for this account.
347
- verified = await commitWindow(Math.max(settled, floor), modelID);
348
- }
349
- if (accepted >= MAX_WINDOW)
350
- break;
351
- const next = Math.min(MAX_WINDOW, Math.floor(accepted * 1.2));
352
- if (next <= accepted)
353
- break;
354
- target = next;
355
- }
356
- if (!verified)
357
- return undefined;
358
- deps.log.info("free-pi verified the gateway context window", {
359
- model: modelID,
360
- window: verified,
361
- compiled: fallback,
362
- probes: samples.length,
363
- acceptedTokens: accepted,
364
- charsPerToken: Number(charsPerToken.toFixed(2)),
365
- });
366
- return verified;
367
- }
@@ -15,11 +15,11 @@ export declare const CONSENT_VERSION = "4";
15
15
  export declare const DEFAULT_FREE_MODEL_ID = "glm-5.3-flash";
16
16
  /**
17
17
  * The provider CLI's window. The gateway enforces its own ceiling but does not
18
- * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
19
- * with what the server actually accepts.
18
+ * publish it, so this is the starting point; a real rejection lowers the
19
+ * advertised value for that model.
20
20
  */
21
21
  export declare const CONTEXT_WINDOW = 200000;
22
- /** Largest window the plugin will ever advertise after measuring the gateway. */
22
+ /** Largest window the plugin will ever advertise. */
23
23
  export declare const MAX_CONTEXT_WINDOW = 1000000;
24
24
  export declare const MAX_OUTPUT_TOKENS = 32768;
25
25
  /**
@@ -29,8 +29,6 @@ export declare const MAX_OUTPUT_TOKENS = 32768;
29
29
  * empty.
30
30
  */
31
31
  export declare const MAX_OUTPUT_TOKENS_CEILING = 131072;
32
- /** How long a measured gateway window is trusted before checking again. */
33
- export declare const VERIFY_LIMITS_TTL_MS: number;
34
32
  export declare const AD_CONTEXT_HEADER = "x-ad-context";
35
33
  /**
36
34
  * The CLI sends `none` when the ad context is unavailable or private instead of
@@ -74,7 +72,6 @@ export declare const AD_REQUEST_TIMEOUT_MS = 5000;
74
72
  export declare const AD_IMPRESSION_TIMEOUT_MS = 3000;
75
73
  export declare const AD_TURN_LIMIT = 200;
76
74
  export declare const AD_IMPRESSION_LIMIT = 200;
77
- export declare const CREDITS_PER_USD: number;
78
75
  export declare const CATALOG_TTL_MS: number;
79
76
  export declare const CATALOG_TIMEOUT_MS = 8000;
80
77
  export declare const CATALOG_ATTEMPTS = 2;
package/dist/constants.js CHANGED
@@ -15,11 +15,11 @@ export const CONSENT_VERSION = "4";
15
15
  export const DEFAULT_FREE_MODEL_ID = "glm-5.3-flash";
16
16
  /**
17
17
  * The provider CLI's window. The gateway enforces its own ceiling but does not
18
- * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
19
- * with what the server actually accepts.
18
+ * publish it, so this is the starting point; a real rejection lowers the
19
+ * advertised value for that model.
20
20
  */
21
21
  export const CONTEXT_WINDOW = 200_000;
22
- /** Largest window the plugin will ever advertise after measuring the gateway. */
22
+ /** Largest window the plugin will ever advertise. */
23
23
  export const MAX_CONTEXT_WINDOW = 1_000_000;
24
24
  export const MAX_OUTPUT_TOKENS = 32_768;
25
25
  /**
@@ -29,8 +29,6 @@ export const MAX_OUTPUT_TOKENS = 32_768;
29
29
  * empty.
30
30
  */
31
31
  export const MAX_OUTPUT_TOKENS_CEILING = 131_072;
32
- /** How long a measured gateway window is trusted before checking again. */
33
- export const VERIFY_LIMITS_TTL_MS = 7 * 24 * 60 * 60 * 1_000;
34
32
  export const AD_CONTEXT_HEADER = "x-ad-context";
35
33
  /**
36
34
  * The CLI sends `none` when the ad context is unavailable or private instead of
@@ -88,7 +86,6 @@ export const AD_REQUEST_TIMEOUT_MS = 5_000;
88
86
  export const AD_IMPRESSION_TIMEOUT_MS = 3_000;
89
87
  export const AD_TURN_LIMIT = 200;
90
88
  export const AD_IMPRESSION_LIMIT = 200;
91
- export const CREDITS_PER_USD = 40_000 / 3;
92
89
  export const CATALOG_TTL_MS = 10 * 60_000;
93
90
  export const CATALOG_TIMEOUT_MS = 8_000;
94
91
  export const CATALOG_ATTEMPTS = 2;
package/dist/plugin.js CHANGED
@@ -5,6 +5,7 @@ import { closeFreePiSession } from "./api/session.js";
5
5
  import { readCredentialsToken } from "./auth/credentials.js";
6
6
  import { tokenFromCredential } from "./auth/credential.js";
7
7
  import { fetchCatalog } from "./catalog/catalog.js";
8
+ import { currentLiveLimits, loadLiveLimits } from "./catalog/live.js";
8
9
  import { accountAccess, buildModels, filterAccessibleModels, isReasoningEffort, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
9
10
  import { fetchModelsRegistry } from "./catalog/registry.js";
10
11
  import { applyProvider } from "./catalog/v2.js";
@@ -89,6 +90,10 @@ async function setup(ctx) {
89
90
  let currentMain = filterAccessibleModels(catalogMain, access);
90
91
  let currentDefense = filterAccessibleModels(catalogDefense, access);
91
92
  const candidates = modelRegistryCandidates(registry);
93
+ // Measurements learned from real traffic and real gateway rejections survive
94
+ // a restart. Loading them is cheap and does not probe the gateway; it only
95
+ // keeps the advertised window honest.
96
+ const live = await loadLiveLimits();
92
97
  const configuredEffort = ctx.options?.reasoningEffort;
93
98
  const buildOptions = {
94
99
  ...(configuredEffort === false
@@ -110,23 +115,30 @@ async function setup(ctx) {
110
115
  }
111
116
  return kept;
112
117
  };
113
- // Rebuilt on every call so a recovered catalog or a refreshed quota applies
114
- // without restarting OpenCode.
115
- const buildMain = () => withoutDenied(PROVIDER_ID, buildModels(currentMain, candidates, buildOptions));
116
- const buildDefense = () => withoutDenied(DEFENSE_PROVIDER_ID, buildModels(currentDefense, candidates, buildOptions));
118
+ // Rebuilt on every call so a recovered catalog, a refreshed quota or a window
119
+ // just learned from a real rejection applies without restarting OpenCode.
120
+ const buildWithLive = (models) => buildModels(models, candidates, {
121
+ ...buildOptions,
122
+ live: currentLiveLimits() ?? live,
123
+ });
124
+ const buildMain = () => withoutDenied(PROVIDER_ID, buildWithLive(currentMain));
125
+ const buildDefense = () => withoutDenied(DEFENSE_PROVIDER_ID, buildWithLive(currentDefense));
117
126
  function indexModelState() {
118
- const mainNow = buildMain();
119
- const defenseNow = buildDefense();
120
- for (const [id, model] of Object.entries(mainNow)) {
127
+ // Rebuilt, not appended: a model that disappears or stops accepting images
128
+ // must stop being treated as image-capable, or a later `read` keeps sending
129
+ // an attachment the current catalog no longer supports.
130
+ const images = new Set();
131
+ for (const [id, model] of Object.entries(buildMain())) {
121
132
  if (model.modalities.input.includes("image")) {
122
- state.imageModels.add(`${PROVIDER_ID}/${id}`);
133
+ images.add(`${PROVIDER_ID}/${id}`);
123
134
  }
124
135
  }
125
- for (const [id, model] of Object.entries(defenseNow)) {
136
+ for (const [id, model] of Object.entries(buildDefense())) {
126
137
  if (model.modalities.input.includes("image")) {
127
- state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
138
+ images.add(`${DEFENSE_PROVIDER_ID}/${id}`);
128
139
  }
129
140
  }
141
+ state.imageModels = images;
130
142
  }
131
143
  indexModelState();
132
144
  const credential = await deps.activeCredential().catch(() => undefined);
@@ -25,7 +25,7 @@ function rememberPending(deps, key, turn) {
25
25
  trimMap(deps.state.pendingAdTurns, PENDING_LIMIT);
26
26
  deps.state.pendingAdTurns.set(key, turn);
27
27
  }
28
- /** Caps output tokens, applies the efficiency rule and derives the ad turn. */
28
+ /** Tracks the free-pi session and derives its ad turn for this request. */
29
29
  async function applyGeneration(deps, event, kind) {
30
30
  if (!isFreePiProvider(event.model?.providerID))
31
31
  return;
@@ -161,55 +161,9 @@ async function registerToolHooks(ctx, deps, registrations) {
161
161
  status: event.status,
162
162
  ...(event.status === "completed" ? { result: event.result } : {}),
163
163
  });
164
- nudgeFailedTool(deps, event);
165
164
  replaceUnsupportedImages(deps, event);
166
165
  }));
167
166
  }
168
- /**
169
- * Adds the concrete next step to a tool failure the free models repeat.
170
- *
171
- * The scan of a week of sessions shows the same failures over and over: the
172
- * portable shell scanner rejects a heredoc or a nested-quote one-liner (72
173
- * times), `edit` gets identical strings (12) or an ambiguous `oldString` (8).
174
- * The model reads the bare error and often repeats the call. The hint is short
175
- * and only goes to free-pi sessions; other providers keep their own messages.
176
- */
177
- function nudgeFailedTool(deps, event) {
178
- if (event.status !== "error")
179
- return;
180
- if (!isFreePiSession(deps, event.sessionID))
181
- return;
182
- const error = event.error;
183
- if (!error || typeof error !== "object")
184
- return;
185
- const message = typeof error.message === "string" ? error.message : "";
186
- if (!message)
187
- return;
188
- let hint = "";
189
- if (message.includes("Portable shell scanner cannot analyze command")) {
190
- hint =
191
- " Write the script to a file with the write tool and run that file; on Windows use PowerShell cmdlets instead of cmd syntax.";
192
- }
193
- else if (/No changes to apply: oldString and newString are identical/i.test(message)) {
194
- hint =
195
- " Change the replacement text: oldString and newString must differ. Re-read the line you want to change first.";
196
- }
197
- else if (/Found \d+ matches? for oldString/i.test(message)) {
198
- hint =
199
- " Include enough surrounding lines so oldString matches exactly once, or set replaceAll when every occurrence must change.";
200
- }
201
- else if (/has not been read yet|read it before/i.test(message)) {
202
- hint = " Read the file with the read tool in this turn before editing it.";
203
- }
204
- if (!hint)
205
- return;
206
- try {
207
- error.message = `${message}${hint}`;
208
- }
209
- catch {
210
- // A frozen error still reaches the model unchanged; the hint is best effort.
211
- }
212
- }
213
167
  /**
214
168
  * Models whose upstream accepts images get them natively, so a `read` that
215
169
  * returns a picture must keep the file part. Text-only models would turn it
@@ -4,10 +4,19 @@ export function sleep(ms) {
4
4
  }
5
5
  /** Resolves with `fallback` if `promise` does not settle within `ms`. */
6
6
  export function settle(promise, fallback, ms = 6_000) {
7
- return Promise.race([
8
- promise,
9
- new Promise((resolve) => setTimeout(() => resolve(fallback), ms)),
10
- ]);
7
+ return new Promise((resolve, reject) => {
8
+ const timer = setTimeout(() => resolve(fallback), ms);
9
+ // The loser of the race must not keep the event loop alive for the whole
10
+ // budget after the real request already answered.
11
+ timer.unref?.();
12
+ promise.then((value) => {
13
+ clearTimeout(timer);
14
+ resolve(value);
15
+ }, (error) => {
16
+ clearTimeout(timer);
17
+ reject(error);
18
+ });
19
+ });
11
20
  }
12
21
  /** Adds an LRU-ish cap to a `Map` keyed by insertion order. */
13
22
  export function trimMap(map, limit) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.7.31",
3
+ "version": "0.7.33",
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",
@@ -3,36 +3,22 @@
3
3
  *
4
4
  * free-pi's HTTP API never publishes per-model limits: `/client-version` only
5
5
  * carries id/name/free/section/note/stats_id, `/me` carries the quota, and chat
6
- * responses carry usage but no window. The gateway does enforce a real ceiling,
7
- * so the plugin verifies the advertised window against the gateway itself and
8
- * remembers what it learned. The measured value replaces the compiled default
9
- * on the next start; a probe failure leaves the previous value untouched.
6
+ * responses carry usage but no window. The plugin therefore learns only from
7
+ * traffic that already happened: a step proves the gateway accepted its prompt,
8
+ * and a real "too long" rejection proves the model's hard ceiling. Nothing is
9
+ * probed, so learning never spends allowance; the values survive a restart.
10
10
  */
11
11
 
12
12
  import { mkdir, readFile, writeFile } from "node:fs/promises";
13
13
  import { dirname } from "node:path";
14
- import { resolveToken } from "../auth/token.js";
15
- import {
16
- CONTEXT_WINDOW,
17
- VERIFY_LIMITS_TTL_MS,
18
- } from "../constants.js";
19
14
  import type { Deps } from "../deps.js";
20
15
  import type { TokenUsageLike } from "../types.js";
21
16
  import { dataPath } from "../utils/data-dir.js";
22
- import { completionsBaseUrl } from "../utils/urls.js";
23
17
 
24
18
  const FILE = "live-limits.json";
25
19
  const WRITE_DEBOUNCE_MS = 2_000;
26
- /** Verification stops shrinking here instead of advertising a useless window. */
27
- const MIN_WINDOW = 32_768;
28
- /** Hard stop for the upward search; `buildModels` never advertises more. */
20
+ /** `buildModels` never advertises a window larger than this. */
29
21
  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;
36
22
 
37
23
  export type ModelObservation = {
38
24
  /** Largest prompt the gateway accepted for this model. */
@@ -46,7 +32,7 @@ export type ModelObservation = {
46
32
 
47
33
  export type LiveLimits = {
48
34
  version: 1;
49
- /** Window verified against the gateway, used for the next catalog build. */
35
+ /** Largest window real traffic proved, used for the next catalog build. */
50
36
  window?: { tokens: number; verifiedAt: number; model?: string };
51
37
  /** What real traffic showed for each model. */
52
38
  models: Record<string, ModelObservation>;
@@ -192,10 +178,10 @@ export function learnedContextWindow(
192
178
  ): number | undefined {
193
179
  const rejected = limits?.models[modelID]?.rejectedPromptTokens;
194
180
  if (!rejected || rejected <= 0) return undefined;
195
- return Math.max(2_048, Math.min(
196
- Math.floor(rejected * REJECTION_HEADROOM),
197
- MAX_WINDOW,
198
- ));
181
+ return Math.max(
182
+ 2_048,
183
+ Math.min(Math.floor(rejected * REJECTION_HEADROOM), MAX_WINDOW),
184
+ );
199
185
  }
200
186
 
201
187
  /**
@@ -229,224 +215,3 @@ export function noteRejectedPrompt(
229
215
  );
230
216
  return window;
231
217
  }
232
-
233
- /** Whether the persisted window is old enough to verify again. */export function shouldVerifyWindow(limits: LiveLimits | undefined): boolean {
234
- const verifiedAt = limits?.window?.verifiedAt;
235
- if (!verifiedAt) return true;
236
- return Date.now() - verifiedAt > VERIFY_LIMITS_TTL_MS;
237
- }
238
-
239
- function filler(chars: number): string {
240
- const unit =
241
- "the quick brown fox jumps over the lazy dog while maintainers review the patch and debate naming ";
242
- return unit.repeat(Math.ceil(chars / unit.length)).slice(0, chars);
243
- }
244
-
245
- type ProbeResult =
246
- | { status: "ok"; promptTokens?: number }
247
- | { status: "too_long" }
248
- | { status: "failed" };
249
-
250
- async function sendProbe(
251
- deps: Deps,
252
- modelID: string,
253
- chars: number,
254
- ): Promise<ProbeResult> {
255
- const token = await resolveToken(deps).catch(() => undefined);
256
- if (!token) return { status: "failed" };
257
- const content = `${filler(chars)}\n\nIgnore the filler and reply with OK.`;
258
- let response: Response;
259
- try {
260
- response = await fetch(`${completionsBaseUrl()}/chat/completions`, {
261
- method: "POST",
262
- headers: {
263
- accept: "application/json",
264
- "content-type": "application/json",
265
- authorization: `Bearer ${token}`,
266
- "x-client-version": deps.state.latestClientVersion,
267
- "x-session-id": `free-pi-window-${Date.now().toString(36)}-${Math
268
- .random()
269
- .toString(36)
270
- .slice(2, 8)}`,
271
- "x-ad-context": "none",
272
- },
273
- body: JSON.stringify({
274
- model: modelID,
275
- messages: [{ role: "user", content }],
276
- stream: false,
277
- max_tokens: 256,
278
- }),
279
- signal: AbortSignal.timeout(180_000),
280
- });
281
- } catch {
282
- return { status: "failed" };
283
- }
284
- if (response.status === 413 || response.status === 400) {
285
- const body = await response.text().catch(() => "");
286
- if (/context_too_long|too long|context_ceiling/i.test(body)) {
287
- return { status: "too_long" };
288
- }
289
- return { status: "failed" };
290
- }
291
- if (!response.ok) return { status: "failed" };
292
- const payload = (await response.json().catch(() => undefined)) as
293
- | { usage?: { prompt_tokens?: number } }
294
- | undefined;
295
- const promptTokens = payload?.usage?.prompt_tokens;
296
- return {
297
- status: "ok",
298
- ...(typeof promptTokens === "number" ? { promptTokens } : {}),
299
- };
300
- }
301
-
302
- export type VerifyLimitsOptions = {
303
- /** A free model to probe with; paid models would spend credits. */
304
- model?: string;
305
- /** Window to check. Defaults to the measured one, then the compiled one. */
306
- window?: number;
307
- };
308
-
309
- /** One gateway answer used to settle the advertised window. */
310
- export type ProbeSample = {
311
- chars: number;
312
- /** Prompt tokens the gateway reported for an accepted probe. */
313
- tokens?: number;
314
- tooLong: boolean;
315
- };
316
-
317
- /**
318
- * Largest window the accepted probes prove, with headroom. Pure so the probe
319
- * loop and the persisted value can be tested without a server.
320
- */
321
- export function settleWindow(
322
- samples: readonly ProbeSample[],
323
- ): number | undefined {
324
- let best = 0;
325
- for (const sample of samples) {
326
- if (sample.tooLong) continue;
327
- if (!Number.isFinite(sample.tokens) || (sample.tokens ?? 0) <= 0) continue;
328
- if (sample.tokens! <= best) continue;
329
- best = sample.tokens!;
330
- }
331
- if (best === 0) return undefined;
332
- return Math.min(
333
- MAX_WINDOW,
334
- Math.max(MIN_WINDOW, Math.floor((best * WINDOW_SAFETY) / 1_000) * 1_000),
335
- );
336
- }
337
-
338
- /**
339
- * Stores a measured window and writes it immediately. Called after every
340
- * accepted probe, so a process that exits mid-verification keeps the smallest
341
- * proven value instead of losing the whole run.
342
- */
343
- async function commitWindow(
344
- tokens: number,
345
- modelID: string,
346
- ): Promise<number> {
347
- const limits = (cached ??= emptyLimits());
348
- // The measured ceiling belongs to the model probed, not to every model: the
349
- // gateway's limit is per model, and a global window taken from one model
350
- // would advertise capacity another one rejects. The per-model value is what
351
- // `buildModels` reads for that model; the global window stays as the
352
- // fallback for models never probed.
353
- const entry = observation(modelID);
354
- if ((entry.maxPromptTokens ?? 0) < tokens) {
355
- entry.maxPromptTokens = tokens;
356
- entry.updatedAt = Date.now();
357
- }
358
- if (limits.window && limits.window.tokens >= tokens) return limits.window.tokens;
359
- limits.window = { tokens, verifiedAt: Date.now(), model: modelID };
360
- loaded = true;
361
- await persist();
362
- return tokens;
363
- }
364
-
365
- /**
366
- * Checks the compiled window against the gateway and then grows past it while
367
- * the gateway keeps accepting larger prompts. The start value is a floor, not a
368
- * ceiling: the server has no endpoint for its real limit, and pinning sessions
369
- * to the CLI's 200k wastes capacity the account can actually use. On rejection
370
- * it binary-searches between the largest accepted prompt and the rejected one,
371
- * so the next catalog build advertises the measured window. Returns the verified
372
- * window, or `undefined` when nothing could be learned (the previous value is
373
- * kept).
374
- */
375
- export async function verifyGatewayWindow(
376
- deps: Deps,
377
- options: VerifyLimitsOptions = {},
378
- ): Promise<number | undefined> {
379
- const modelID = options.model;
380
- if (!modelID) return undefined;
381
- const fallback =
382
- options.window ?? cached?.window?.tokens ?? CONTEXT_WINDOW;
383
- const samples: ProbeSample[] = [];
384
- // Accepted prompt tokens; also the lower bound of the binary search.
385
- let accepted = 0;
386
- let charsPerToken = INITIAL_CHARS_PER_TOKEN;
387
- let target = Math.max(MIN_WINDOW, Math.min(fallback, MAX_WINDOW));
388
- let verified: number | undefined;
389
- const floor = Math.min(fallback, CONTEXT_WINDOW);
390
-
391
- for (let attempt = 0; attempt < MAX_PROBES; attempt += 1) {
392
- const chars = Math.max(
393
- MIN_WINDOW * charsPerToken,
394
- Math.floor(target * charsPerToken * 0.99),
395
- );
396
- const result = await sendProbe(deps, modelID, chars);
397
- if (result.status === "failed") {
398
- // A network failure or a rejected body proves nothing; keep what the
399
- // earlier probes already established.
400
- if (samples.length === 0) return verified;
401
- break;
402
- }
403
- if (result.status === "too_long") {
404
- samples.push({ chars, tooLong: true });
405
- if (accepted === 0) {
406
- // The compiled window itself is too large: step down as before.
407
- target = Math.floor(target * 0.85);
408
- if (target < MIN_WINDOW) break;
409
- continue;
410
- }
411
- const next = Math.floor((accepted + target) / 2);
412
- if (next <= accepted) break;
413
- target = next;
414
- continue;
415
- }
416
-
417
- const tokens = result.promptTokens;
418
- samples.push({
419
- chars,
420
- tooLong: false,
421
- ...(tokens && tokens > 0 ? { tokens } : {}),
422
- });
423
- if (tokens && tokens > 0) {
424
- accepted = tokens;
425
- // Learn the real characters-per-token ratio for this prompt shape; the
426
- // filler is prose, and four chars/token overshoots badly.
427
- charsPerToken = chars / tokens;
428
- } else {
429
- accepted = Math.floor(chars / charsPerToken);
430
- }
431
- const settled = settleWindow(samples);
432
- if (settled) {
433
- // Never go below the window that already worked for this account.
434
- verified = await commitWindow(Math.max(settled, floor), modelID);
435
- }
436
- if (accepted >= MAX_WINDOW) break;
437
- const next = Math.min(MAX_WINDOW, Math.floor(accepted * 1.2));
438
- if (next <= accepted) break;
439
- target = next;
440
- }
441
-
442
- if (!verified) return undefined;
443
- deps.log.info("free-pi verified the gateway context window", {
444
- model: modelID,
445
- window: verified,
446
- compiled: fallback,
447
- probes: samples.length,
448
- acceptedTokens: accepted,
449
- charsPerToken: Number(charsPerToken.toFixed(2)),
450
- });
451
- return verified;
452
- }
package/src/constants.ts CHANGED
@@ -19,11 +19,11 @@ export const DEFAULT_FREE_MODEL_ID = "glm-5.3-flash";
19
19
 
20
20
  /**
21
21
  * The provider CLI's window. The gateway enforces its own ceiling but does not
22
- * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
23
- * with what the server actually accepts.
22
+ * publish it, so this is the starting point; a real rejection lowers the
23
+ * advertised value for that model.
24
24
  */
25
25
  export const CONTEXT_WINDOW = 200_000;
26
- /** Largest window the plugin will ever advertise after measuring the gateway. */
26
+ /** Largest window the plugin will ever advertise. */
27
27
  export const MAX_CONTEXT_WINDOW = 1_000_000;
28
28
  export const MAX_OUTPUT_TOKENS = 32_768;
29
29
  /**
@@ -33,9 +33,6 @@ export const MAX_OUTPUT_TOKENS = 32_768;
33
33
  * empty.
34
34
  */
35
35
  export const MAX_OUTPUT_TOKENS_CEILING = 131_072;
36
- /** How long a measured gateway window is trusted before checking again. */
37
- export const VERIFY_LIMITS_TTL_MS = 7 * 24 * 60 * 60 * 1_000;
38
-
39
36
  export const AD_CONTEXT_HEADER = "x-ad-context";
40
37
  /**
41
38
  * The CLI sends `none` when the ad context is unavailable or private instead of
@@ -100,8 +97,6 @@ export const AD_IMPRESSION_TIMEOUT_MS = 3_000;
100
97
  export const AD_TURN_LIMIT = 200;
101
98
  export const AD_IMPRESSION_LIMIT = 200;
102
99
 
103
- export const CREDITS_PER_USD = 40_000 / 3;
104
-
105
100
  export const CATALOG_TTL_MS = 10 * 60_000;
106
101
  export const CATALOG_TIMEOUT_MS = 8_000;
107
102
  export const CATALOG_ATTEMPTS = 2;
package/src/plugin.ts CHANGED
@@ -6,6 +6,7 @@ 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 } from "./catalog/live.js";
9
10
  import {
10
11
  accountAccess,
11
12
  buildModels,
@@ -111,6 +112,10 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
111
112
  let currentMain = filterAccessibleModels(catalogMain, access);
112
113
  let currentDefense = filterAccessibleModels(catalogDefense, access);
113
114
  const candidates = modelRegistryCandidates(registry);
115
+ // Measurements learned from real traffic and real gateway rejections survive
116
+ // a restart. Loading them is cheap and does not probe the gateway; it only
117
+ // keeps the advertised window honest.
118
+ const live = await loadLiveLimits();
114
119
  const configuredEffort = ctx.options?.reasoningEffort;
115
120
  const buildOptions = {
116
121
  ...(configuredEffort === false
@@ -132,32 +137,34 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
132
137
  return kept;
133
138
  };
134
139
 
135
- // Rebuilt on every call so a recovered catalog or a refreshed quota applies
136
- // without restarting OpenCode.
140
+ // Rebuilt on every call so a recovered catalog, a refreshed quota or a window
141
+ // just learned from a real rejection applies without restarting OpenCode.
142
+ const buildWithLive = (models: typeof currentMain) =>
143
+ buildModels(models, candidates, {
144
+ ...buildOptions,
145
+ live: currentLiveLimits() ?? live,
146
+ });
137
147
  const buildMain = () =>
138
- withoutDenied(
139
- PROVIDER_ID,
140
- buildModels(currentMain, candidates, buildOptions),
141
- );
148
+ withoutDenied(PROVIDER_ID, buildWithLive(currentMain));
142
149
  const buildDefense = () =>
143
- withoutDenied(
144
- DEFENSE_PROVIDER_ID,
145
- buildModels(currentDefense, candidates, buildOptions),
146
- );
150
+ withoutDenied(DEFENSE_PROVIDER_ID, buildWithLive(currentDefense));
147
151
 
148
152
  function indexModelState(): void {
149
- const mainNow = buildMain();
150
- const defenseNow = buildDefense();
151
- for (const [id, model] of Object.entries(mainNow)) {
153
+ // Rebuilt, not appended: a model that disappears or stops accepting images
154
+ // must stop being treated as image-capable, or a later `read` keeps sending
155
+ // an attachment the current catalog no longer supports.
156
+ const images = new Set<string>();
157
+ for (const [id, model] of Object.entries(buildMain())) {
152
158
  if (model.modalities.input.includes("image")) {
153
- state.imageModels.add(`${PROVIDER_ID}/${id}`);
159
+ images.add(`${PROVIDER_ID}/${id}`);
154
160
  }
155
161
  }
156
- for (const [id, model] of Object.entries(defenseNow)) {
162
+ for (const [id, model] of Object.entries(buildDefense())) {
157
163
  if (model.modalities.input.includes("image")) {
158
- state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
164
+ images.add(`${DEFENSE_PROVIDER_ID}/${id}`);
159
165
  }
160
166
  }
167
+ state.imageModels = images;
161
168
  }
162
169
  indexModelState();
163
170
 
@@ -77,7 +77,7 @@ function rememberPending(deps: Deps, key: string, turn: AdTurn): void {
77
77
  deps.state.pendingAdTurns.set(key, turn);
78
78
  }
79
79
 
80
- /** Caps output tokens, applies the efficiency rule and derives the ad turn. */
80
+ /** Tracks the free-pi session and derives its ad turn for this request. */
81
81
  async function applyGeneration(
82
82
  deps: Deps,
83
83
  event: any,
@@ -239,49 +239,11 @@ async function registerToolHooks(
239
239
  status: event.status,
240
240
  ...(event.status === "completed" ? { result: event.result } : {}),
241
241
  });
242
- nudgeFailedTool(deps, event);
243
242
  replaceUnsupportedImages(deps, event);
244
243
  }),
245
244
  );
246
245
  }
247
246
 
248
- /**
249
- * Adds the concrete next step to a tool failure the free models repeat.
250
- *
251
- * The scan of a week of sessions shows the same failures over and over: the
252
- * portable shell scanner rejects a heredoc or a nested-quote one-liner (72
253
- * times), `edit` gets identical strings (12) or an ambiguous `oldString` (8).
254
- * The model reads the bare error and often repeats the call. The hint is short
255
- * and only goes to free-pi sessions; other providers keep their own messages.
256
- */
257
- function nudgeFailedTool(deps: Deps, event: any): void {
258
- if (event.status !== "error") return;
259
- if (!isFreePiSession(deps, event.sessionID)) return;
260
- const error = event.error;
261
- if (!error || typeof error !== "object") return;
262
- const message = typeof error.message === "string" ? error.message : "";
263
- if (!message) return;
264
- let hint = "";
265
- if (message.includes("Portable shell scanner cannot analyze command")) {
266
- hint =
267
- " Write the script to a file with the write tool and run that file; on Windows use PowerShell cmdlets instead of cmd syntax.";
268
- } else if (/No changes to apply: oldString and newString are identical/i.test(message)) {
269
- hint =
270
- " Change the replacement text: oldString and newString must differ. Re-read the line you want to change first.";
271
- } else if (/Found \d+ matches? for oldString/i.test(message)) {
272
- hint =
273
- " Include enough surrounding lines so oldString matches exactly once, or set replaceAll when every occurrence must change.";
274
- } else if (/has not been read yet|read it before/i.test(message)) {
275
- hint = " Read the file with the read tool in this turn before editing it.";
276
- }
277
- if (!hint) return;
278
- try {
279
- error.message = `${message}${hint}`;
280
- } catch {
281
- // A frozen error still reaches the model unchanged; the hint is best effort.
282
- }
283
- }
284
-
285
247
  /**
286
248
  * Models whose upstream accepts images get them natively, so a `read` that
287
249
  * returns a picture must keep the file part. Text-only models would turn it
@@ -10,10 +10,22 @@ export function settle<T>(
10
10
  fallback: T,
11
11
  ms = 6_000,
12
12
  ): Promise<T> {
13
- return Promise.race([
14
- promise,
15
- new Promise<T>((resolve) => setTimeout(() => resolve(fallback), ms)),
16
- ]);
13
+ return new Promise<T>((resolve, reject) => {
14
+ const timer = setTimeout(() => resolve(fallback), ms);
15
+ // The loser of the race must not keep the event loop alive for the whole
16
+ // budget after the real request already answered.
17
+ (timer as { unref?: () => void }).unref?.();
18
+ promise.then(
19
+ (value) => {
20
+ clearTimeout(timer);
21
+ resolve(value);
22
+ },
23
+ (error) => {
24
+ clearTimeout(timer);
25
+ reject(error);
26
+ },
27
+ );
28
+ });
17
29
  }
18
30
 
19
31
  /** Adds an LRU-ish cap to a `Map` keyed by insertion order. */