@eduardo191labs/opencode-free-pi 0.5.3 → 0.5.5
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 +22 -7
- package/dist/catalog/models.d.ts +14 -0
- package/dist/catalog/models.js +36 -1
- package/dist/constants.d.ts +8 -6
- package/dist/constants.js +15 -5
- package/dist/errors/limit.d.ts +2 -0
- package/dist/errors/limit.js +14 -0
- package/dist/plugin.js +10 -2
- package/dist/session/hooks.js +27 -1
- package/dist/session/overflow.d.ts +40 -0
- package/dist/session/overflow.js +104 -0
- package/dist/session/replay.d.ts +19 -0
- package/dist/session/replay.js +74 -7
- package/dist/state.d.ts +5 -0
- package/dist/state.js +1 -0
- package/dist/types.d.ts +5 -0
- package/package.json +1 -1
- package/src/catalog/models.ts +47 -0
- package/src/constants.ts +15 -5
- package/src/errors/limit.ts +18 -0
- package/src/plugin.ts +10 -1
- package/src/session/hooks.ts +45 -0
- package/src/session/overflow.ts +115 -0
- package/src/session/replay.ts +95 -8
- package/src/state.ts +3 -0
- package/src/types.ts +5 -0
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
|
|
@@ -89,13 +95,15 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
89
95
|
- **Subagentes identificados**: las sesiones hijas envían
|
|
90
96
|
`x-freepi-subagent: 1`, igual que los proveedores que el CLI crea para sus
|
|
91
97
|
subagentes.
|
|
92
|
-
- **Pensamiento
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
`
|
|
98
|
-
|
|
98
|
+
- **Pensamiento por defecto**: el plugin pide `reasoning_effort: "medium"`
|
|
99
|
+
cuando el modelo no trae variante elegida. Dejarlo sin definir hacía que los
|
|
100
|
+
modelos gratuitos respondieran con prisa, gastando apenas unas decenas de
|
|
101
|
+
tokens de razonamiento incluso en tareas que requieren planificar. Si el
|
|
102
|
+
catálogo del modelo solo anuncia `low`/`high`, se usa `high`. El selector
|
|
103
|
+
sigue ofreciendo `none`, `minimal`, `low`, `medium` y `high`, y la opción
|
|
104
|
+
`reasoningEffort: false` del plugin recupera el comportamiento anterior (nivel
|
|
105
|
+
del servidor). No se anuncian `thinking_budget` ni `thinking`, porque la ruta
|
|
106
|
+
`openai-compatible` de OpenCode los descarta.
|
|
99
107
|
- **Solo modelos utilizables**: al arrancar se consulta `/me` y el selector
|
|
100
108
|
`/model` incluye únicamente lo que la cuenta puede usar: los modelos
|
|
101
109
|
`free: true` siempre, los de pago mientras queden créditos de la cuota o
|
|
@@ -271,6 +279,13 @@ código `context_too_long`, `context_too_long_for_fallback` o `context_ceiling`
|
|
|
271
279
|
se reescriben a un `400` con el texto que OpenCode clasifica como
|
|
272
280
|
desbordamiento de contexto, para que dispare la compactación automática.
|
|
273
281
|
|
|
282
|
+
El plugin mide el cuerpo de cada petición rechazada. Cuando el rechazo llega
|
|
283
|
+
con un cuerpo que no puede agotar la ventana, lo trata como un fallo del
|
|
284
|
+
proveedor: repite la petición con un `x-session-id` nuevo y, si el servidor
|
|
285
|
+
insiste, devuelve un `400` con un mensaje de error de proveedor. Ese texto no
|
|
286
|
+
coincide con el patrón de desbordamiento de OpenCode, así que el runner deja de
|
|
287
|
+
compactar en lugar de entrar en un ciclo de resúmenes que no reducen nada.
|
|
288
|
+
|
|
274
289
|
free-pi cobra en créditos contra una cuota diaria, no en USD por token. Por
|
|
275
290
|
eso los modelos se registran con costo `0`, igual que el CLI del proveedor; el
|
|
276
291
|
consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
|
package/dist/catalog/models.d.ts
CHANGED
|
@@ -12,9 +12,23 @@ export declare function modelCost(_model: CatalogModel, _capability?: ModelsDevM
|
|
|
12
12
|
export declare function modelRegistryCandidates(registry: ModelRegistry | undefined): RegistryCandidate[];
|
|
13
13
|
export declare function modelCapability(model: CatalogModel, candidates: RegistryCandidate[]): ModelsDevModel | undefined;
|
|
14
14
|
export declare function modelVariants(options: ReasoningOption[] | undefined, _outputLimit: number): VariantMap;
|
|
15
|
+
export declare function isReasoningEffort(value: unknown): value is string;
|
|
16
|
+
/**
|
|
17
|
+
* The effort sent when no variant is selected. `false` leaves the gateway's
|
|
18
|
+
* own default untouched; otherwise the catalog's supported levels win over
|
|
19
|
+
* `medium`, so a model that only accepts `low`/`high` never gets an effort it
|
|
20
|
+
* would reject.
|
|
21
|
+
*/
|
|
22
|
+
export declare function preferredReasoningEffort(options: ReasoningOption[] | undefined, configured?: string | false): string | undefined;
|
|
15
23
|
export type BuildModelsOptions = {
|
|
16
24
|
/** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
|
|
17
25
|
compact100?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Effort sent when the user has not picked a variant. `false` keeps the
|
|
28
|
+
* gateway default. Defaults to `medium` because an unset effort makes the
|
|
29
|
+
* free models answer before they reason.
|
|
30
|
+
*/
|
|
31
|
+
reasoningEffort?: string | false;
|
|
18
32
|
};
|
|
19
33
|
/**
|
|
20
34
|
* What the signed-in account can actually use, derived from `GET /me`.
|
package/dist/catalog/models.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
|
-
import { COMPACT100_CONTEXT_WINDOW, CONTEXT_WINDOW, DEFAULT_THINKING_LEVELS, MAX_OUTPUT_TOKENS, } from "../constants.js";
|
|
2
|
+
import { COMPACT100_CONTEXT_WINDOW, CONTEXT_WINDOW, DEFAULT_REASONING_EFFORT, DEFAULT_THINKING_LEVELS, MAX_OUTPUT_TOKENS, REASONING_EFFORTS, } from "../constants.js";
|
|
3
3
|
import { positiveNumber } from "../utils/numbers.js";
|
|
4
4
|
import { cleanText } from "../utils/text.js";
|
|
5
5
|
export function usableModels(catalog) {
|
|
@@ -151,6 +151,37 @@ export function modelVariants(options, _outputLimit) {
|
|
|
151
151
|
}
|
|
152
152
|
return variants;
|
|
153
153
|
}
|
|
154
|
+
export function isReasoningEffort(value) {
|
|
155
|
+
return (typeof value === "string" &&
|
|
156
|
+
REASONING_EFFORTS.includes(value));
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* The effort sent when no variant is selected. `false` leaves the gateway's
|
|
160
|
+
* own default untouched; otherwise the catalog's supported levels win over
|
|
161
|
+
* `medium`, so a model that only accepts `low`/`high` never gets an effort it
|
|
162
|
+
* would reject.
|
|
163
|
+
*/
|
|
164
|
+
export function preferredReasoningEffort(options, configured) {
|
|
165
|
+
if (configured === false)
|
|
166
|
+
return undefined;
|
|
167
|
+
if (configured)
|
|
168
|
+
return configured;
|
|
169
|
+
if (!options || options.length === 0)
|
|
170
|
+
return DEFAULT_REASONING_EFFORT;
|
|
171
|
+
const effort = options.find((option) => option.type === "effort");
|
|
172
|
+
if (effort) {
|
|
173
|
+
if (effort.values.includes(DEFAULT_REASONING_EFFORT))
|
|
174
|
+
return DEFAULT_REASONING_EFFORT;
|
|
175
|
+
if (effort.values.includes("high"))
|
|
176
|
+
return "high";
|
|
177
|
+
return effort.values[effort.values.length - 1];
|
|
178
|
+
}
|
|
179
|
+
if (options.some((option) => option.type === "toggle"))
|
|
180
|
+
return "high";
|
|
181
|
+
if (options.some((option) => option.type === "budget_tokens"))
|
|
182
|
+
return "high";
|
|
183
|
+
return DEFAULT_REASONING_EFFORT;
|
|
184
|
+
}
|
|
154
185
|
export function accountAccess(me) {
|
|
155
186
|
if (!me)
|
|
156
187
|
return undefined;
|
|
@@ -207,6 +238,9 @@ export function buildModels(models, candidates = [], options = {}) {
|
|
|
207
238
|
: CONTEXT_WINDOW;
|
|
208
239
|
const limitContext = Math.min(positiveNumber(model.context_window, model.contextWindow, model.limit?.context, capability?.limit?.context) ?? contextCeiling, contextCeiling);
|
|
209
240
|
const limitOutput = Math.min(positiveNumber(model.max_tokens, model.maxTokens, model.max_output_tokens, model.limit?.output, capability?.limit?.output) ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS);
|
|
241
|
+
const defaultEffort = reasoning
|
|
242
|
+
? preferredReasoningEffort(reasoningOptions, options.reasoningEffort)
|
|
243
|
+
: undefined;
|
|
210
244
|
result[model.id] = {
|
|
211
245
|
id: model.id,
|
|
212
246
|
name: displayName(model),
|
|
@@ -217,6 +251,7 @@ export function buildModels(models, candidates = [], options = {}) {
|
|
|
217
251
|
reasoning,
|
|
218
252
|
reasoning_options: reasoningOptions,
|
|
219
253
|
variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
|
|
254
|
+
...(defaultEffort ? { settings: { reasoningEffort: defaultEffort } } : {}),
|
|
220
255
|
enabled: model.unavailable !== true,
|
|
221
256
|
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
222
257
|
tool_call: model.tool_call ?? capability?.tool_call ?? true,
|
package/dist/constants.d.ts
CHANGED
|
@@ -19,13 +19,15 @@ export declare const SUBAGENT_HEADER = "x-freepi-subagent";
|
|
|
19
19
|
export declare const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
20
20
|
export declare const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
|
|
21
21
|
/**
|
|
22
|
-
* The provider CLI
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
22
|
+
* The provider CLI starts with thinking off, but leaving `reasoning_effort`
|
|
23
|
+
* unset makes the gateway answer in a hurry: the free models spend only a few
|
|
24
|
+
* dozen reasoning tokens even on tasks that need planning. The plugin therefore
|
|
25
|
+
* asks for `medium` by default and keeps the CLI's levels as variants, so
|
|
26
|
+
* `none`/`minimal` are still one pick away when speed matters more than care.
|
|
26
27
|
*/
|
|
27
|
-
export declare const DEFAULT_REASONING_EFFORT = "
|
|
28
|
-
export declare const
|
|
28
|
+
export declare const DEFAULT_REASONING_EFFORT = "medium";
|
|
29
|
+
export declare const REASONING_EFFORTS: readonly ["none", "minimal", "low", "medium", "high", "max"];
|
|
30
|
+
export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low", "medium", "high"];
|
|
29
31
|
/** pi-ai's HTTP idle timeout for headers and body chunks. */
|
|
30
32
|
export declare const HEADER_TIMEOUT_MS = 300000;
|
|
31
33
|
export declare const CHUNK_TIMEOUT_MS = 300000;
|
package/dist/constants.js
CHANGED
|
@@ -19,13 +19,23 @@ export const SUBAGENT_HEADER = "x-freepi-subagent";
|
|
|
19
19
|
export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
20
20
|
export const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
|
|
21
21
|
/**
|
|
22
|
-
* The provider CLI
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
22
|
+
* The provider CLI starts with thinking off, but leaving `reasoning_effort`
|
|
23
|
+
* unset makes the gateway answer in a hurry: the free models spend only a few
|
|
24
|
+
* dozen reasoning tokens even on tasks that need planning. The plugin therefore
|
|
25
|
+
* asks for `medium` by default and keeps the CLI's levels as variants, so
|
|
26
|
+
* `none`/`minimal` are still one pick away when speed matters more than care.
|
|
26
27
|
*/
|
|
27
|
-
export const DEFAULT_REASONING_EFFORT = "
|
|
28
|
+
export const DEFAULT_REASONING_EFFORT = "medium";
|
|
29
|
+
export const REASONING_EFFORTS = [
|
|
30
|
+
"none",
|
|
31
|
+
"minimal",
|
|
32
|
+
"low",
|
|
33
|
+
"medium",
|
|
34
|
+
"high",
|
|
35
|
+
"max",
|
|
36
|
+
];
|
|
28
37
|
export const DEFAULT_THINKING_LEVELS = [
|
|
38
|
+
"none",
|
|
29
39
|
"minimal",
|
|
30
40
|
"low",
|
|
31
41
|
"medium",
|
package/dist/errors/limit.d.ts
CHANGED
|
@@ -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
|
package/dist/errors/limit.js
CHANGED
|
@@ -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
|
package/dist/plugin.js
CHANGED
|
@@ -7,7 +7,7 @@ import { closeFreePiSession } from "./api/session.js";
|
|
|
7
7
|
import { readCredentialsToken } from "./auth/credentials.js";
|
|
8
8
|
import { tokenFromCredential } from "./auth/credential.js";
|
|
9
9
|
import { fetchCatalog } from "./catalog/catalog.js";
|
|
10
|
-
import { accountAccess, buildModels, filterAccessibleModels, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
|
|
10
|
+
import { accountAccess, buildModels, filterAccessibleModels, isReasoningEffort, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
|
|
11
11
|
import { fetchModelsRegistry } from "./catalog/registry.js";
|
|
12
12
|
import { applyProvider } from "./catalog/v2.js";
|
|
13
13
|
import { DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "./constants.js";
|
|
@@ -103,7 +103,15 @@ async function setup(ctx) {
|
|
|
103
103
|
const main = filterAccessibleModels(catalogMain, access);
|
|
104
104
|
const defense = filterAccessibleModels(catalogDefense, access);
|
|
105
105
|
const candidates = modelRegistryCandidates(registry);
|
|
106
|
-
const
|
|
106
|
+
const configuredEffort = ctx.options?.reasoningEffort;
|
|
107
|
+
const buildOptions = {
|
|
108
|
+
compact100: state.costExperimentArm === "compact100",
|
|
109
|
+
...(configuredEffort === false
|
|
110
|
+
? { reasoningEffort: false }
|
|
111
|
+
: isReasoningEffort(configuredEffort)
|
|
112
|
+
? { reasoningEffort: configuredEffort }
|
|
113
|
+
: {}),
|
|
114
|
+
};
|
|
107
115
|
const mainModels = buildModels(main, candidates, buildOptions);
|
|
108
116
|
const defenseModels = buildModels(defense, candidates, buildOptions);
|
|
109
117
|
for (const [id, model] of Object.entries(mainModels)) {
|
package/dist/session/hooks.js
CHANGED
|
@@ -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 {
|
|
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
|
+
}
|
package/dist/session/replay.d.ts
CHANGED
|
@@ -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>;
|
package/dist/session/replay.js
CHANGED
|
@@ -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
|
|
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
package/dist/types.d.ts
CHANGED
|
@@ -133,6 +133,11 @@ export type ModelDefinition = {
|
|
|
133
133
|
export type ModelMap = Record<string, ModelDefinition>;
|
|
134
134
|
export type FreePiOptions = {
|
|
135
135
|
includeDefense?: boolean;
|
|
136
|
+
/**
|
|
137
|
+
* Effort used when no variant is picked. Defaults to `medium` so the free
|
|
138
|
+
* models plan before answering. Set `false` to keep the gateway default.
|
|
139
|
+
*/
|
|
140
|
+
reasoningEffort?: string | false;
|
|
136
141
|
};
|
|
137
142
|
export type MeResponse = {
|
|
138
143
|
handle?: string;
|
package/package.json
CHANGED
package/src/catalog/models.ts
CHANGED
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
import {
|
|
4
4
|
COMPACT100_CONTEXT_WINDOW,
|
|
5
5
|
CONTEXT_WINDOW,
|
|
6
|
+
DEFAULT_REASONING_EFFORT,
|
|
6
7
|
DEFAULT_THINKING_LEVELS,
|
|
7
8
|
MAX_OUTPUT_TOKENS,
|
|
9
|
+
REASONING_EFFORTS,
|
|
8
10
|
} from "../constants.js";
|
|
9
11
|
import type {
|
|
10
12
|
Catalog,
|
|
@@ -202,9 +204,50 @@ export function modelVariants(
|
|
|
202
204
|
return variants;
|
|
203
205
|
}
|
|
204
206
|
|
|
207
|
+
export function isReasoningEffort(value: unknown): value is string {
|
|
208
|
+
return (
|
|
209
|
+
typeof value === "string" &&
|
|
210
|
+
(REASONING_EFFORTS as readonly string[]).includes(value)
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* The effort sent when no variant is selected. `false` leaves the gateway's
|
|
216
|
+
* own default untouched; otherwise the catalog's supported levels win over
|
|
217
|
+
* `medium`, so a model that only accepts `low`/`high` never gets an effort it
|
|
218
|
+
* would reject.
|
|
219
|
+
*/
|
|
220
|
+
export function preferredReasoningEffort(
|
|
221
|
+
options: ReasoningOption[] | undefined,
|
|
222
|
+
configured?: string | false,
|
|
223
|
+
): string | undefined {
|
|
224
|
+
if (configured === false) return undefined;
|
|
225
|
+
if (configured) return configured;
|
|
226
|
+
if (!options || options.length === 0) return DEFAULT_REASONING_EFFORT;
|
|
227
|
+
const effort = options.find(
|
|
228
|
+
(option): option is Extract<ReasoningOption, { type: "effort" }> =>
|
|
229
|
+
option.type === "effort",
|
|
230
|
+
);
|
|
231
|
+
if (effort) {
|
|
232
|
+
if (effort.values.includes(DEFAULT_REASONING_EFFORT))
|
|
233
|
+
return DEFAULT_REASONING_EFFORT;
|
|
234
|
+
if (effort.values.includes("high")) return "high";
|
|
235
|
+
return effort.values[effort.values.length - 1];
|
|
236
|
+
}
|
|
237
|
+
if (options.some((option) => option.type === "toggle")) return "high";
|
|
238
|
+
if (options.some((option) => option.type === "budget_tokens")) return "high";
|
|
239
|
+
return DEFAULT_REASONING_EFFORT;
|
|
240
|
+
}
|
|
241
|
+
|
|
205
242
|
export type BuildModelsOptions = {
|
|
206
243
|
/** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
|
|
207
244
|
compact100?: boolean;
|
|
245
|
+
/**
|
|
246
|
+
* Effort sent when the user has not picked a variant. `false` keeps the
|
|
247
|
+
* gateway default. Defaults to `medium` because an unset effort makes the
|
|
248
|
+
* free models answer before they reason.
|
|
249
|
+
*/
|
|
250
|
+
reasoningEffort?: string | false;
|
|
208
251
|
};
|
|
209
252
|
|
|
210
253
|
/**
|
|
@@ -302,6 +345,9 @@ export function buildModels(
|
|
|
302
345
|
) ?? MAX_OUTPUT_TOKENS,
|
|
303
346
|
MAX_OUTPUT_TOKENS,
|
|
304
347
|
);
|
|
348
|
+
const defaultEffort = reasoning
|
|
349
|
+
? preferredReasoningEffort(reasoningOptions, options.reasoningEffort)
|
|
350
|
+
: undefined;
|
|
305
351
|
result[model.id] = {
|
|
306
352
|
id: model.id,
|
|
307
353
|
name: displayName(model),
|
|
@@ -313,6 +359,7 @@ export function buildModels(
|
|
|
313
359
|
reasoning,
|
|
314
360
|
reasoning_options: reasoningOptions,
|
|
315
361
|
variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
|
|
362
|
+
...(defaultEffort ? { settings: { reasoningEffort: defaultEffort } } : {}),
|
|
316
363
|
enabled: model.unavailable !== true,
|
|
317
364
|
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
318
365
|
tool_call: model.tool_call ?? capability?.tool_call ?? true,
|
package/src/constants.ts
CHANGED
|
@@ -26,13 +26,23 @@ export const EFFICIENCY_RULE =
|
|
|
26
26
|
"- When several independent reads or searches are needed, issue them in the same turn.";
|
|
27
27
|
|
|
28
28
|
/**
|
|
29
|
-
* The provider CLI
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
29
|
+
* The provider CLI starts with thinking off, but leaving `reasoning_effort`
|
|
30
|
+
* unset makes the gateway answer in a hurry: the free models spend only a few
|
|
31
|
+
* dozen reasoning tokens even on tasks that need planning. The plugin therefore
|
|
32
|
+
* asks for `medium` by default and keeps the CLI's levels as variants, so
|
|
33
|
+
* `none`/`minimal` are still one pick away when speed matters more than care.
|
|
33
34
|
*/
|
|
34
|
-
export const DEFAULT_REASONING_EFFORT = "
|
|
35
|
+
export const DEFAULT_REASONING_EFFORT = "medium";
|
|
36
|
+
export const REASONING_EFFORTS = [
|
|
37
|
+
"none",
|
|
38
|
+
"minimal",
|
|
39
|
+
"low",
|
|
40
|
+
"medium",
|
|
41
|
+
"high",
|
|
42
|
+
"max",
|
|
43
|
+
] as const;
|
|
35
44
|
export const DEFAULT_THINKING_LEVELS = [
|
|
45
|
+
"none",
|
|
36
46
|
"minimal",
|
|
37
47
|
"low",
|
|
38
48
|
"medium",
|
package/src/errors/limit.ts
CHANGED
|
@@ -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
|
package/src/plugin.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
accountAccess,
|
|
20
20
|
buildModels,
|
|
21
21
|
filterAccessibleModels,
|
|
22
|
+
isReasoningEffort,
|
|
22
23
|
modelRegistryCandidates,
|
|
23
24
|
partitionModels,
|
|
24
25
|
} from "./catalog/models.js";
|
|
@@ -129,7 +130,15 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
129
130
|
const main = filterAccessibleModels(catalogMain, access);
|
|
130
131
|
const defense = filterAccessibleModels(catalogDefense, access);
|
|
131
132
|
const candidates = modelRegistryCandidates(registry);
|
|
132
|
-
const
|
|
133
|
+
const configuredEffort = ctx.options?.reasoningEffort;
|
|
134
|
+
const buildOptions = {
|
|
135
|
+
compact100: state.costExperimentArm === "compact100",
|
|
136
|
+
...(configuredEffort === false
|
|
137
|
+
? { reasoningEffort: false as const }
|
|
138
|
+
: isReasoningEffort(configuredEffort)
|
|
139
|
+
? { reasoningEffort: configuredEffort }
|
|
140
|
+
: {}),
|
|
141
|
+
};
|
|
133
142
|
const mainModels = buildModels(main, candidates, buildOptions);
|
|
134
143
|
const defenseModels = buildModels(defense, candidates, buildOptions);
|
|
135
144
|
|
package/src/session/hooks.ts
CHANGED
|
@@ -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
|
+
}
|
package/src/session/replay.ts
CHANGED
|
@@ -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(),
|
package/src/types.ts
CHANGED
|
@@ -110,6 +110,11 @@ export type ModelMap = Record<string, ModelDefinition>;
|
|
|
110
110
|
|
|
111
111
|
export type FreePiOptions = {
|
|
112
112
|
includeDefense?: boolean;
|
|
113
|
+
/**
|
|
114
|
+
* Effort used when no variant is picked. Defaults to `medium` so the free
|
|
115
|
+
* models plan before answering. Set `false` to keep the gateway default.
|
|
116
|
+
*/
|
|
117
|
+
reasoningEffort?: string | false;
|
|
113
118
|
};
|
|
114
119
|
|
|
115
120
|
export type MeResponse = {
|