@eduardo191labs/opencode-free-pi 0.5.3 → 0.5.4

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
@@ -74,6 +74,12 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
74
74
  - **Compactación integrada**: los errores `context_too_long` de free-pi se
75
75
  reescriben para que OpenCode los reconozca como desbordamiento de contexto y
76
76
  ejecute `/compact` automáticamente en vez de terminar el turno.
77
+ - **Sin bucles de compactación**: si el servidor rechaza como «demasiado
78
+ largo» una petición que cabe de sobra en la ventana (menos de 60k tokens),
79
+ el plugin la reintenta con un `x-session-id` nuevo en vez de compactar. Si
80
+ aun así la sigue rechazando, devuelve un error de proveedor que OpenCode no
81
+ clasifica como desbordamiento, para no gastar créditos en resúmenes que no
82
+ arreglan nada.
77
83
  - **Títulos locales**: OpenCode pide un título al modelo al crear una sesión.
78
84
  El plugin lo responde con la primera línea del primer mensaje, sin gastar
79
85
  créditos, sin pedir un anuncio y sin dejar la sesión atascada en
@@ -271,6 +277,13 @@ código `context_too_long`, `context_too_long_for_fallback` o `context_ceiling`
271
277
  se reescriben a un `400` con el texto que OpenCode clasifica como
272
278
  desbordamiento de contexto, para que dispare la compactación automática.
273
279
 
280
+ El plugin mide el cuerpo de cada petición rechazada. Cuando el rechazo llega
281
+ con un cuerpo que no puede agotar la ventana, lo trata como un fallo del
282
+ proveedor: repite la petición con un `x-session-id` nuevo y, si el servidor
283
+ insiste, devuelve un `400` con un mensaje de error de proveedor. Ese texto no
284
+ coincide con el patrón de desbordamiento de OpenCode, así que el runner deja de
285
+ compactar en lugar de entrar en un ciclo de resúmenes que no reducen nada.
286
+
274
287
  free-pi cobra en créditos contra una cuota diaria, no en USD por token. Por
275
288
  eso los modelos se registran con costo `0`, igual que el CLI del proveedor; el
276
289
  consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
@@ -2,6 +2,8 @@
2
2
  * Rewrites long-lived free-pi limit responses so the client shows the friendly
3
3
  * message instead of a raw 429. Mirrors the fetch wrapper used by the V1 plugin.
4
4
  */
5
+ /** The free-pi overflow code carried by a response, when it is one. */
6
+ export declare function overflowCodeOf(response: Response): Promise<string | undefined>;
5
7
  /**
6
8
  * Returns a replacement response when `response` is a free-pi context overflow.
7
9
  * The replacement is a 400 with a message OpenCode recognizes as context
@@ -105,6 +105,20 @@ function contextOverflowCode(body) {
105
105
  catch { }
106
106
  return undefined;
107
107
  }
108
+ /** The free-pi overflow code carried by a response, when it is one. */
109
+ export async function overflowCodeOf(response) {
110
+ if (response.status !== 413 &&
111
+ response.status !== 429 &&
112
+ response.status !== 400)
113
+ return undefined;
114
+ const body = await response
115
+ .clone()
116
+ .text()
117
+ .catch(() => "");
118
+ if (!body)
119
+ return undefined;
120
+ return contextOverflowCode(body);
121
+ }
108
122
  /**
109
123
  * Returns a replacement response when `response` is a free-pi context overflow.
110
124
  * The replacement is a 400 with a message OpenCode recognizes as context
@@ -8,7 +8,8 @@ import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors
8
8
  import { parseFreePiError } from "../errors/parse.js";
9
9
  import { trimMap } from "../utils/async.js";
10
10
  import { watchFreePiNotice } from "./notices.js";
11
- import { rememberReplayBody, replayConcurrentResponse, } from "./replay.js";
11
+ import { clearSpuriousOverflows, noteSpuriousOverflow, overflowingSpuriously, spuriousOverflowResponse, } from "./overflow.js";
12
+ import { rememberReplayBody, replayConcurrentResponse, replaySpuriousOverflow, } from "./replay.js";
12
13
  import { localTitle } from "./title.js";
13
14
  import { rememberFreePiSession } from "./track.js";
14
15
  import { hydrateWireSessionID, markWireSessionDirty, rotateWireSessionID, takeWireSessionDirty, wireSessionID, } from "./wire.js";
@@ -307,6 +308,31 @@ export async function registerSessionHooks(ctx, deps) {
307
308
  // become a 400 overflow, not a friendly long-lived limit.
308
309
  const overflow = await rewriteContextOverflowResponse(response).catch(() => undefined);
309
310
  if (overflow) {
311
+ const code = overflow.headers.get("x-free-pi-original-code") ?? "context_overflow";
312
+ // A gateway failure can report "too long" for a request that fits the
313
+ // window. Compacting then loops, so retry on a fresh wire session
314
+ // first, and stop compacting once the session has seen a few.
315
+ const reviewed = await replaySpuriousOverflow(deps, event).catch(() => ({}));
316
+ if (reviewed.response) {
317
+ clearSpuriousOverflows(deps, event.sessionID);
318
+ event.response = watchFreePiNotice(deps, reviewed.response);
319
+ return;
320
+ }
321
+ if (reviewed.spurious) {
322
+ const count = noteSpuriousOverflow(deps, event.sessionID);
323
+ deps.log.info("free-pi rejected a request as too long that fits the model window", {
324
+ sessionID: event.sessionID,
325
+ code,
326
+ tokens: reviewed.tokens,
327
+ rejections: count,
328
+ });
329
+ if (overflowingSpuriously(deps, event.sessionID)) {
330
+ markWireSessionDirty(deps, event.sessionID);
331
+ deps.log.warn("compact loop stopped: free-pi keeps rejecting a request that fits", { sessionID: event.sessionID, code, tokens: reviewed.tokens });
332
+ event.response = watchFreePiNotice(deps, spuriousOverflowResponse(overflow));
333
+ return;
334
+ }
335
+ }
310
336
  event.response = watchFreePiNotice(deps, overflow);
311
337
  return;
312
338
  }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Guards against a provider that reports a context overflow for a request that
3
+ * plainly fits the model's window.
4
+ *
5
+ * free-pi returns `context_ceiling`/`context_too_long` when the upstream model
6
+ * rejects a prompt as too long. The client turns that into OpenCode's
7
+ * "prompt is too long" overflow, which is correct for a real overflow: the
8
+ * runner compacts and retries. When the gateway is failing it can report the
9
+ * same code for a small prompt, and then every compaction is followed by the
10
+ * next rejection: an endless compact/retry storm that spends real credits on
11
+ * summaries. A request far below the advertised window cannot be a window
12
+ * overflow, so the plugin retries it on a fresh wire session and, if that
13
+ * still fails, surfaces a provider error instead of asking for another
14
+ * compaction.
15
+ */
16
+ import type { Deps } from "../deps.js";
17
+ /** A request below this many tokens cannot exhaust a 200k window on its own. */
18
+ export declare const SPURIOUS_OVERFLOW_TOKENS = 60000;
19
+ export declare const SPURIOUS_OVERFLOW_MESSAGE: string;
20
+ /**
21
+ * Approximate token count of a chat-completions body: every string in it,
22
+ * message text and tool output alike, at the usual four characters per token.
23
+ * Inline media counts at its base64 length, which is what the provider bills.
24
+ */
25
+ export declare function measureRequestTokens(body: string): number;
26
+ /**
27
+ * Records a rejection of a request that fits, and returns the number of them
28
+ * seen for the session inside the current window. A run of them means the
29
+ * provider is failing, so compacting again cannot help.
30
+ */
31
+ export declare function noteSpuriousOverflow(deps: Deps, sessionID: string): number;
32
+ export declare function clearSpuriousOverflows(deps: Deps, sessionID: string): void;
33
+ /** Whether the session has had enough spurious rejections to stop compacting. */
34
+ export declare function overflowingSpuriously(deps: Deps, sessionID: string): boolean;
35
+ /**
36
+ * Turns an overflow response into a provider error OpenCode will not classify
37
+ * as a context overflow. The session still shows a failure, but the runner
38
+ * stops compacting and retrying a conversation that already fits.
39
+ */
40
+ export declare function spuriousOverflowResponse(original: Response): Response;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Guards against a provider that reports a context overflow for a request that
3
+ * plainly fits the model's window.
4
+ *
5
+ * free-pi returns `context_ceiling`/`context_too_long` when the upstream model
6
+ * rejects a prompt as too long. The client turns that into OpenCode's
7
+ * "prompt is too long" overflow, which is correct for a real overflow: the
8
+ * runner compacts and retries. When the gateway is failing it can report the
9
+ * same code for a small prompt, and then every compaction is followed by the
10
+ * next rejection: an endless compact/retry storm that spends real credits on
11
+ * summaries. A request far below the advertised window cannot be a window
12
+ * overflow, so the plugin retries it on a fresh wire session and, if that
13
+ * still fails, surfaces a provider error instead of asking for another
14
+ * compaction.
15
+ */
16
+ /** A request below this many tokens cannot exhaust a 200k window on its own. */
17
+ export const SPURIOUS_OVERFLOW_TOKENS = 60_000;
18
+ /** Spurious rejections closer together than this belong to the same incident. */
19
+ const STORM_WINDOW_MS = 10 * 60_000;
20
+ /** Spurious rejections tolerated in a window before the error stops compacting. */
21
+ const STORM_LIMIT = 2;
22
+ const STORM_LIMIT_PER_SESSION = 512;
23
+ export const SPURIOUS_OVERFLOW_MESSAGE = "free-pi rejected this request as too long even though it fits the model's window; " +
24
+ "this is a provider failure, not a context overflow. Retry the message, or start a new session if it persists.";
25
+ /**
26
+ * Approximate token count of a chat-completions body: every string in it,
27
+ * message text and tool output alike, at the usual four characters per token.
28
+ * Inline media counts at its base64 length, which is what the provider bills.
29
+ */
30
+ export function measureRequestTokens(body) {
31
+ try {
32
+ const data = JSON.parse(body);
33
+ let chars = 0;
34
+ const walk = (value) => {
35
+ if (typeof value === "string") {
36
+ chars += value.length;
37
+ return;
38
+ }
39
+ if (Array.isArray(value)) {
40
+ for (const item of value)
41
+ walk(item);
42
+ return;
43
+ }
44
+ if (value && typeof value === "object") {
45
+ for (const [key, item] of Object.entries(value)) {
46
+ chars += key.length;
47
+ walk(item);
48
+ }
49
+ }
50
+ };
51
+ walk(data);
52
+ return Math.ceil(chars / 4);
53
+ }
54
+ catch {
55
+ return Math.ceil(body.length / 4);
56
+ }
57
+ }
58
+ /**
59
+ * Records a rejection of a request that fits, and returns the number of them
60
+ * seen for the session inside the current window. A run of them means the
61
+ * provider is failing, so compacting again cannot help.
62
+ */
63
+ export function noteSpuriousOverflow(deps, sessionID) {
64
+ if (!sessionID)
65
+ return 0;
66
+ const now = Date.now();
67
+ const previous = deps.state.spuriousOverflows.get(sessionID);
68
+ const count = previous && now - previous.at <= STORM_WINDOW_MS ? previous.count + 1 : 1;
69
+ deps.state.spuriousOverflows.set(sessionID, { at: now, count });
70
+ if (deps.state.spuriousOverflows.size > STORM_LIMIT_PER_SESSION) {
71
+ const oldest = deps.state.spuriousOverflows.keys().next().value;
72
+ if (oldest !== undefined)
73
+ deps.state.spuriousOverflows.delete(oldest);
74
+ }
75
+ return count;
76
+ }
77
+ export function clearSpuriousOverflows(deps, sessionID) {
78
+ deps.state.spuriousOverflows.delete(sessionID);
79
+ }
80
+ /** Whether the session has had enough spurious rejections to stop compacting. */
81
+ export function overflowingSpuriously(deps, sessionID) {
82
+ const entry = deps.state.spuriousOverflows.get(sessionID);
83
+ if (!entry)
84
+ return false;
85
+ if (Date.now() - entry.at > STORM_WINDOW_MS)
86
+ return false;
87
+ return entry.count > STORM_LIMIT;
88
+ }
89
+ /**
90
+ * Turns an overflow response into a provider error OpenCode will not classify
91
+ * as a context overflow. The session still shows a failure, but the runner
92
+ * stops compacting and retrying a conversation that already fits.
93
+ */
94
+ export function spuriousOverflowResponse(original) {
95
+ const headers = new Headers(original.headers);
96
+ headers.delete("retry-after");
97
+ headers.delete("retry-after-ms");
98
+ headers.set("x-free-pi-spurious-overflow", "1");
99
+ headers.set("content-type", "application/json");
100
+ return new Response(JSON.stringify({
101
+ error: { type: "provider_error", message: SPURIOUS_OVERFLOW_MESSAGE },
102
+ message: SPURIOUS_OVERFLOW_MESSAGE,
103
+ }), { status: 400, statusText: "Bad Request", headers });
104
+ }
@@ -21,3 +21,22 @@ export declare function rememberReplayBody(deps: Deps, event: any): Promise<void
21
21
  * `undefined` to leave the original response untouched.
22
22
  */
23
23
  export declare function replayConcurrentResponse(deps: Deps, event: any): Promise<Response | undefined>;
24
+ export type OverflowReplay = {
25
+ /** Tokens of the rejected request, when its body was available. */
26
+ readonly tokens?: number;
27
+ /** Whether the rejected request plainly fits the model window. */
28
+ readonly spurious?: boolean;
29
+ /** A good response from a fresh wire session, when the retry succeeded. */
30
+ readonly response?: Response;
31
+ };
32
+ /**
33
+ * Retries an overflow rejection whose request plainly fits the model window.
34
+ *
35
+ * free-pi reports `context_ceiling`/`context_too_long` from the upstream
36
+ * model, and a failing gateway can report them for a small prompt. Compacting
37
+ * cannot fix that: the summary is accepted, the next turn is rejected the same
38
+ * way, and the runner compacts again. A fresh wire session is the cheapest
39
+ * recovery, so a small request is replayed on one before the overflow is
40
+ * handed to the runner.
41
+ */
42
+ export declare function replaySpuriousOverflow(deps: Deps, event: any): Promise<OverflowReplay>;
@@ -14,12 +14,16 @@
14
14
  * without a visible "Retrying…" or a failed step.
15
15
  */
16
16
  import { closeFreePiSession } from "../api/session.js";
17
+ import { overflowCodeOf } from "../errors/limit.js";
17
18
  import { sleep, trimMap } from "../utils/async.js";
19
+ import { measureRequestTokens, SPURIOUS_OVERFLOW_TOKENS, } from "./overflow.js";
18
20
  import { rotateWireSessionID, wireSessionID } from "./wire.js";
19
21
  const REPLAY_BODY_LIMIT = 24;
20
22
  const REPLAY_MAX_ATTEMPTS = 4;
21
23
  const REPLAY_BASE_DELAY_MS = 400;
22
24
  const REPLAY_MAX_DELAY_MS = 3_000;
25
+ /** A rejected request that fits is retried only this many times on fresh ids. */
26
+ const OVERFLOW_REPLAY_ATTEMPTS = 2;
23
27
  function requestKey(sessionID, request) {
24
28
  const turn = request.headers.get("x-turn-id") ?? "";
25
29
  return `${sessionID}\u0000${turn}\u0000${request.url}`;
@@ -54,6 +58,21 @@ async function isConcurrent(response) {
54
58
  .catch(() => "");
55
59
  return /"concurrent"/i.test(body) || /one request at a time/i.test(body);
56
60
  }
61
+ /** The request body, either remembered before the send or re-read from it. */
62
+ async function storedBody(deps, event) {
63
+ const request = event?.request;
64
+ if (!(request instanceof Request) || !event.sessionID)
65
+ return;
66
+ const remembered = deps.state.replayBodies.get(requestKey(event.sessionID, request));
67
+ if (remembered !== undefined)
68
+ return remembered;
69
+ if (!isJson(request))
70
+ return;
71
+ return request
72
+ .clone()
73
+ .text()
74
+ .catch(() => undefined);
75
+ }
57
76
  function concurrentDelay(attempt) {
58
77
  return Math.min(REPLAY_BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1), REPLAY_MAX_DELAY_MS);
59
78
  }
@@ -70,13 +89,7 @@ export async function replayConcurrentResponse(deps, event) {
70
89
  return;
71
90
  if (!(await isConcurrent(original)))
72
91
  return;
73
- const body = deps.state.replayBodies.get(requestKey(event.sessionID, request)) ??
74
- (isJson(request)
75
- ? await request
76
- .clone()
77
- .text()
78
- .catch(() => undefined)
79
- : undefined);
92
+ const body = await storedBody(deps, event);
80
93
  if (!body) {
81
94
  deps.log.warn("free-pi session busy but the request body was not available to replay", { sessionID: event.sessionID });
82
95
  return;
@@ -117,3 +130,57 @@ export async function replayConcurrentResponse(deps, event) {
117
130
  }
118
131
  return undefined;
119
132
  }
133
+ /**
134
+ * Retries an overflow rejection whose request plainly fits the model window.
135
+ *
136
+ * free-pi reports `context_ceiling`/`context_too_long` from the upstream
137
+ * model, and a failing gateway can report them for a small prompt. Compacting
138
+ * cannot fix that: the summary is accepted, the next turn is rejected the same
139
+ * way, and the runner compacts again. A fresh wire session is the cheapest
140
+ * recovery, so a small request is replayed on one before the overflow is
141
+ * handed to the runner.
142
+ */
143
+ export async function replaySpuriousOverflow(deps, event) {
144
+ const original = event?.response;
145
+ const request = event?.request;
146
+ if (!(original instanceof Response) || !(request instanceof Request))
147
+ return {};
148
+ if (request.signal.aborted)
149
+ return {};
150
+ if (!(await overflowCodeOf(original)))
151
+ return {};
152
+ const body = await storedBody(deps, event);
153
+ if (!body)
154
+ return {};
155
+ const tokens = measureRequestTokens(body);
156
+ if (tokens >= SPURIOUS_OVERFLOW_TOKENS)
157
+ return { tokens, spurious: false };
158
+ let previous = request.headers.get("x-session-id") ?? wireSessionID(deps, event.sessionID);
159
+ for (let attempt = 1; attempt <= OVERFLOW_REPLAY_ATTEMPTS; attempt++) {
160
+ if (request.signal.aborted)
161
+ return { tokens, spurious: true };
162
+ const next = rotateWireSessionID(deps, event.sessionID);
163
+ if (previous && previous !== next) {
164
+ void closeFreePiSession(deps, previous).catch(() => undefined);
165
+ }
166
+ previous = next;
167
+ const headers = new Headers(request.headers);
168
+ headers.set("x-session-id", next);
169
+ headers.delete("content-length");
170
+ headers.delete("host");
171
+ const response = await fetch(request.url, {
172
+ method: request.method,
173
+ headers,
174
+ body,
175
+ signal: request.signal,
176
+ }).catch(() => undefined);
177
+ if (!response)
178
+ continue;
179
+ if (!(await overflowCodeOf(response))) {
180
+ deps.log.info("free-pi rejected a request that fits as too long; replayed it on a fresh session id", { sessionID: event.sessionID, tokens, to: next, attempt });
181
+ return { tokens, spurious: true, response };
182
+ }
183
+ }
184
+ deps.log.info("free-pi keeps rejecting a request that fits as too long; the provider is failing", { sessionID: event.sessionID, tokens });
185
+ return { tokens, spurious: true };
186
+ }
package/dist/state.d.ts CHANGED
@@ -36,6 +36,11 @@ export type RuntimeState = {
36
36
  wireSessions: Map<string, string>;
37
37
  wireHydrated: Set<string>;
38
38
  replayBodies: Map<string, string>;
39
+ /** Rejections of requests that fit the model window, per session. */
40
+ spuriousOverflows: Map<string, {
41
+ at: number;
42
+ count: number;
43
+ }>;
39
44
  dirtySessions: Set<string>;
40
45
  finalizedSessions: Set<string>;
41
46
  activeExecutions: Set<string>;
package/dist/state.js CHANGED
@@ -17,6 +17,7 @@ export function createRuntimeState() {
17
17
  wireSessions: new Map(),
18
18
  wireHydrated: new Set(),
19
19
  replayBodies: new Map(),
20
+ spuriousOverflows: new Map(),
20
21
  dirtySessions: new Set(),
21
22
  finalizedSessions: new Set(),
22
23
  activeExecutions: new Set(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.5.3",
3
+ "version": "0.5.4",
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",
@@ -111,6 +111,24 @@ function contextOverflowCode(body: string): string | undefined {
111
111
  return undefined;
112
112
  }
113
113
 
114
+ /** The free-pi overflow code carried by a response, when it is one. */
115
+ export async function overflowCodeOf(
116
+ response: Response,
117
+ ): Promise<string | undefined> {
118
+ if (
119
+ response.status !== 413 &&
120
+ response.status !== 429 &&
121
+ response.status !== 400
122
+ )
123
+ return undefined;
124
+ const body = await response
125
+ .clone()
126
+ .text()
127
+ .catch(() => "");
128
+ if (!body) return undefined;
129
+ return contextOverflowCode(body);
130
+ }
131
+
114
132
  /**
115
133
  * Returns a replacement response when `response` is a free-pi context overflow.
116
134
  * The replacement is a 400 with a message OpenCode recognizes as context
@@ -30,9 +30,17 @@ import {
30
30
  import { parseFreePiError } from "../errors/parse.js";
31
31
  import { trimMap } from "../utils/async.js";
32
32
  import { watchFreePiNotice } from "./notices.js";
33
+ import {
34
+ clearSpuriousOverflows,
35
+ noteSpuriousOverflow,
36
+ overflowingSpuriously,
37
+ spuriousOverflowResponse,
38
+ } from "./overflow.js";
33
39
  import {
34
40
  rememberReplayBody,
35
41
  replayConcurrentResponse,
42
+ replaySpuriousOverflow,
43
+ type OverflowReplay,
36
44
  } from "./replay.js";
37
45
  import { localTitle } from "./title.js";
38
46
  import { rememberFreePiSession } from "./track.js";
@@ -451,6 +459,43 @@ export async function registerSessionHooks(
451
459
  () => undefined,
452
460
  );
453
461
  if (overflow) {
462
+ const code =
463
+ overflow.headers.get("x-free-pi-original-code") ?? "context_overflow";
464
+ // A gateway failure can report "too long" for a request that fits the
465
+ // window. Compacting then loops, so retry on a fresh wire session
466
+ // first, and stop compacting once the session has seen a few.
467
+ const reviewed = await replaySpuriousOverflow(deps, event).catch(
468
+ () => ({}) as OverflowReplay,
469
+ );
470
+ if (reviewed.response) {
471
+ clearSpuriousOverflows(deps, event.sessionID);
472
+ event.response = watchFreePiNotice(deps, reviewed.response);
473
+ return;
474
+ }
475
+ if (reviewed.spurious) {
476
+ const count = noteSpuriousOverflow(deps, event.sessionID);
477
+ deps.log.info(
478
+ "free-pi rejected a request as too long that fits the model window",
479
+ {
480
+ sessionID: event.sessionID,
481
+ code,
482
+ tokens: reviewed.tokens,
483
+ rejections: count,
484
+ },
485
+ );
486
+ if (overflowingSpuriously(deps, event.sessionID)) {
487
+ markWireSessionDirty(deps, event.sessionID);
488
+ deps.log.warn(
489
+ "compact loop stopped: free-pi keeps rejecting a request that fits",
490
+ { sessionID: event.sessionID, code, tokens: reviewed.tokens },
491
+ );
492
+ event.response = watchFreePiNotice(
493
+ deps,
494
+ spuriousOverflowResponse(overflow),
495
+ );
496
+ return;
497
+ }
498
+ }
454
499
  event.response = watchFreePiNotice(deps, overflow);
455
500
  return;
456
501
  }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Guards against a provider that reports a context overflow for a request that
3
+ * plainly fits the model's window.
4
+ *
5
+ * free-pi returns `context_ceiling`/`context_too_long` when the upstream model
6
+ * rejects a prompt as too long. The client turns that into OpenCode's
7
+ * "prompt is too long" overflow, which is correct for a real overflow: the
8
+ * runner compacts and retries. When the gateway is failing it can report the
9
+ * same code for a small prompt, and then every compaction is followed by the
10
+ * next rejection: an endless compact/retry storm that spends real credits on
11
+ * summaries. A request far below the advertised window cannot be a window
12
+ * overflow, so the plugin retries it on a fresh wire session and, if that
13
+ * still fails, surfaces a provider error instead of asking for another
14
+ * compaction.
15
+ */
16
+
17
+ import type { Deps } from "../deps.js";
18
+
19
+ /** A request below this many tokens cannot exhaust a 200k window on its own. */
20
+ export const SPURIOUS_OVERFLOW_TOKENS = 60_000;
21
+
22
+ /** Spurious rejections closer together than this belong to the same incident. */
23
+ const STORM_WINDOW_MS = 10 * 60_000;
24
+
25
+ /** Spurious rejections tolerated in a window before the error stops compacting. */
26
+ const STORM_LIMIT = 2;
27
+
28
+ const STORM_LIMIT_PER_SESSION = 512;
29
+
30
+ export const SPURIOUS_OVERFLOW_MESSAGE =
31
+ "free-pi rejected this request as too long even though it fits the model's window; " +
32
+ "this is a provider failure, not a context overflow. Retry the message, or start a new session if it persists.";
33
+
34
+ /**
35
+ * Approximate token count of a chat-completions body: every string in it,
36
+ * message text and tool output alike, at the usual four characters per token.
37
+ * Inline media counts at its base64 length, which is what the provider bills.
38
+ */
39
+ export function measureRequestTokens(body: string): number {
40
+ try {
41
+ const data = JSON.parse(body) as unknown;
42
+ let chars = 0;
43
+ const walk = (value: unknown): void => {
44
+ if (typeof value === "string") {
45
+ chars += value.length;
46
+ return;
47
+ }
48
+ if (Array.isArray(value)) {
49
+ for (const item of value) walk(item);
50
+ return;
51
+ }
52
+ if (value && typeof value === "object") {
53
+ for (const [key, item] of Object.entries(value)) {
54
+ chars += key.length;
55
+ walk(item);
56
+ }
57
+ }
58
+ };
59
+ walk(data);
60
+ return Math.ceil(chars / 4);
61
+ } catch {
62
+ return Math.ceil(body.length / 4);
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Records a rejection of a request that fits, and returns the number of them
68
+ * seen for the session inside the current window. A run of them means the
69
+ * provider is failing, so compacting again cannot help.
70
+ */
71
+ export function noteSpuriousOverflow(deps: Deps, sessionID: string): number {
72
+ if (!sessionID) return 0;
73
+ const now = Date.now();
74
+ const previous = deps.state.spuriousOverflows.get(sessionID);
75
+ const count =
76
+ previous && now - previous.at <= STORM_WINDOW_MS ? previous.count + 1 : 1;
77
+ deps.state.spuriousOverflows.set(sessionID, { at: now, count });
78
+ if (deps.state.spuriousOverflows.size > STORM_LIMIT_PER_SESSION) {
79
+ const oldest = deps.state.spuriousOverflows.keys().next().value;
80
+ if (oldest !== undefined) deps.state.spuriousOverflows.delete(oldest);
81
+ }
82
+ return count;
83
+ }
84
+
85
+ export function clearSpuriousOverflows(deps: Deps, sessionID: string): void {
86
+ deps.state.spuriousOverflows.delete(sessionID);
87
+ }
88
+
89
+ /** Whether the session has had enough spurious rejections to stop compacting. */
90
+ export function overflowingSpuriously(deps: Deps, sessionID: string): boolean {
91
+ const entry = deps.state.spuriousOverflows.get(sessionID);
92
+ if (!entry) return false;
93
+ if (Date.now() - entry.at > STORM_WINDOW_MS) return false;
94
+ return entry.count > STORM_LIMIT;
95
+ }
96
+
97
+ /**
98
+ * Turns an overflow response into a provider error OpenCode will not classify
99
+ * as a context overflow. The session still shows a failure, but the runner
100
+ * stops compacting and retrying a conversation that already fits.
101
+ */
102
+ export function spuriousOverflowResponse(original: Response): Response {
103
+ const headers = new Headers(original.headers);
104
+ headers.delete("retry-after");
105
+ headers.delete("retry-after-ms");
106
+ headers.set("x-free-pi-spurious-overflow", "1");
107
+ headers.set("content-type", "application/json");
108
+ return new Response(
109
+ JSON.stringify({
110
+ error: { type: "provider_error", message: SPURIOUS_OVERFLOW_MESSAGE },
111
+ message: SPURIOUS_OVERFLOW_MESSAGE,
112
+ }),
113
+ { status: 400, statusText: "Bad Request", headers },
114
+ );
115
+ }
@@ -16,7 +16,12 @@
16
16
 
17
17
  import { closeFreePiSession } from "../api/session.js";
18
18
  import type { Deps } from "../deps.js";
19
+ import { overflowCodeOf } from "../errors/limit.js";
19
20
  import { sleep, trimMap } from "../utils/async.js";
21
+ import {
22
+ measureRequestTokens,
23
+ SPURIOUS_OVERFLOW_TOKENS,
24
+ } from "./overflow.js";
20
25
  import { rotateWireSessionID, wireSessionID } from "./wire.js";
21
26
 
22
27
  const REPLAY_BODY_LIMIT = 24;
@@ -24,6 +29,9 @@ const REPLAY_MAX_ATTEMPTS = 4;
24
29
  const REPLAY_BASE_DELAY_MS = 400;
25
30
  const REPLAY_MAX_DELAY_MS = 3_000;
26
31
 
32
+ /** A rejected request that fits is retried only this many times on fresh ids. */
33
+ const OVERFLOW_REPLAY_ATTEMPTS = 2;
34
+
27
35
  function requestKey(sessionID: string, request: Request): string {
28
36
  const turn = request.headers.get("x-turn-id") ?? "";
29
37
  return `${sessionID}\u0000${turn}\u0000${request.url}`;
@@ -62,6 +70,21 @@ async function isConcurrent(response: Response): Promise<boolean> {
62
70
  return /"concurrent"/i.test(body) || /one request at a time/i.test(body);
63
71
  }
64
72
 
73
+ /** The request body, either remembered before the send or re-read from it. */
74
+ async function storedBody(deps: Deps, event: any): Promise<string | undefined> {
75
+ const request = event?.request;
76
+ if (!(request instanceof Request) || !event.sessionID) return;
77
+ const remembered = deps.state.replayBodies.get(
78
+ requestKey(event.sessionID, request),
79
+ );
80
+ if (remembered !== undefined) return remembered;
81
+ if (!isJson(request)) return;
82
+ return request
83
+ .clone()
84
+ .text()
85
+ .catch(() => undefined);
86
+ }
87
+
65
88
  function concurrentDelay(attempt: number): number {
66
89
  return Math.min(
67
90
  REPLAY_BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1),
@@ -83,14 +106,7 @@ export async function replayConcurrentResponse(
83
106
  if (request.signal.aborted) return;
84
107
  if (!(await isConcurrent(original))) return;
85
108
 
86
- const body =
87
- deps.state.replayBodies.get(requestKey(event.sessionID, request)) ??
88
- (isJson(request)
89
- ? await request
90
- .clone()
91
- .text()
92
- .catch(() => undefined)
93
- : undefined);
109
+ const body = await storedBody(deps, event);
94
110
  if (!body) {
95
111
  deps.log.warn(
96
112
  "free-pi session busy but the request body was not available to replay",
@@ -139,3 +155,74 @@ export async function replayConcurrentResponse(
139
155
  }
140
156
  return undefined;
141
157
  }
158
+
159
+ export type OverflowReplay = {
160
+ /** Tokens of the rejected request, when its body was available. */
161
+ readonly tokens?: number;
162
+ /** Whether the rejected request plainly fits the model window. */
163
+ readonly spurious?: boolean;
164
+ /** A good response from a fresh wire session, when the retry succeeded. */
165
+ readonly response?: Response;
166
+ };
167
+
168
+ /**
169
+ * Retries an overflow rejection whose request plainly fits the model window.
170
+ *
171
+ * free-pi reports `context_ceiling`/`context_too_long` from the upstream
172
+ * model, and a failing gateway can report them for a small prompt. Compacting
173
+ * cannot fix that: the summary is accepted, the next turn is rejected the same
174
+ * way, and the runner compacts again. A fresh wire session is the cheapest
175
+ * recovery, so a small request is replayed on one before the overflow is
176
+ * handed to the runner.
177
+ */
178
+ export async function replaySpuriousOverflow(
179
+ deps: Deps,
180
+ event: any,
181
+ ): Promise<OverflowReplay> {
182
+ const original = event?.response;
183
+ const request = event?.request;
184
+ if (!(original instanceof Response) || !(request instanceof Request)) return {};
185
+ if (request.signal.aborted) return {};
186
+ if (!(await overflowCodeOf(original))) return {};
187
+
188
+ const body = await storedBody(deps, event);
189
+ if (!body) return {};
190
+ const tokens = measureRequestTokens(body);
191
+ if (tokens >= SPURIOUS_OVERFLOW_TOKENS) return { tokens, spurious: false };
192
+
193
+ let previous =
194
+ request.headers.get("x-session-id") ?? wireSessionID(deps, event.sessionID);
195
+ for (let attempt = 1; attempt <= OVERFLOW_REPLAY_ATTEMPTS; attempt++) {
196
+ if (request.signal.aborted) return { tokens, spurious: true };
197
+ const next = rotateWireSessionID(deps, event.sessionID);
198
+ if (previous && previous !== next) {
199
+ void closeFreePiSession(deps, previous).catch(() => undefined);
200
+ }
201
+ previous = next;
202
+
203
+ const headers = new Headers(request.headers);
204
+ headers.set("x-session-id", next);
205
+ headers.delete("content-length");
206
+ headers.delete("host");
207
+
208
+ const response = await fetch(request.url, {
209
+ method: request.method,
210
+ headers,
211
+ body,
212
+ signal: request.signal,
213
+ }).catch(() => undefined);
214
+ if (!response) continue;
215
+ if (!(await overflowCodeOf(response))) {
216
+ deps.log.info(
217
+ "free-pi rejected a request that fits as too long; replayed it on a fresh session id",
218
+ { sessionID: event.sessionID, tokens, to: next, attempt },
219
+ );
220
+ return { tokens, spurious: true, response };
221
+ }
222
+ }
223
+ deps.log.info(
224
+ "free-pi keeps rejecting a request that fits as too long; the provider is failing",
225
+ { sessionID: event.sessionID, tokens },
226
+ );
227
+ return { tokens, spurious: true };
228
+ }
package/src/state.ts CHANGED
@@ -53,6 +53,8 @@ export type RuntimeState = {
53
53
  wireSessions: Map<string, string>;
54
54
  wireHydrated: Set<string>;
55
55
  replayBodies: Map<string, string>;
56
+ /** Rejections of requests that fit the model window, per session. */
57
+ spuriousOverflows: Map<string, { at: number; count: number }>;
56
58
  dirtySessions: Set<string>;
57
59
  finalizedSessions: Set<string>;
58
60
  activeExecutions: Set<string>;
@@ -96,6 +98,7 @@ export function createRuntimeState(): RuntimeState {
96
98
  wireSessions: new Map(),
97
99
  wireHydrated: new Set(),
98
100
  replayBodies: new Map(),
101
+ spuriousOverflows: new Map(),
99
102
  dirtySessions: new Set(),
100
103
  finalizedSessions: new Set(),
101
104
  activeExecutions: new Set(),