@eduardo191labs/opencode-free-pi 0.6.5 → 0.6.6
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 -0
- package/dist/catalog/live.d.ts +18 -2
- package/dist/catalog/live.js +43 -2
- package/dist/catalog/models.js +6 -1
- package/dist/plugin.js +9 -3
- package/dist/session/hooks.js +48 -3
- package/dist/session/overflow.d.ts +31 -0
- package/dist/session/overflow.js +82 -4
- package/dist/session/replay.d.ts +4 -0
- package/dist/session/replay.js +10 -7
- package/package.json +1 -1
- package/src/catalog/live.ts +65 -2
- package/src/catalog/models.ts +6 -0
- package/src/plugin.ts +9 -2
- package/src/session/hooks.ts +59 -3
- package/src/session/overflow.ts +98 -4
- package/src/session/replay.ts +14 -6
package/README.md
CHANGED
|
@@ -77,6 +77,19 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
77
77
|
- **Compactación integrada**: los errores `context_too_long` de free-pi se
|
|
78
78
|
reescriben para que OpenCode los reconozca como desbordamiento de contexto y
|
|
79
79
|
ejecute `/compact` automáticamente en vez de terminar el turno.
|
|
80
|
+
- **Techo por modelo aprendido del gateway**: cuando free-pi rechaza una
|
|
81
|
+
petición real por longitud, ese tamaño se guarda en `live-limits.json` como
|
|
82
|
+
techo de ese modelo y el catálogo anuncia una ventana un 15 % menor, también
|
|
83
|
+
sin reiniciar (`provider.reload`). Así la siguiente compactación empieza antes
|
|
84
|
+
de que el gateway rechace también el propio resumen, que es lo que dejaba el
|
|
85
|
+
turno detenido con solo el checkpoint en pantalla. Los rechazos causados por
|
|
86
|
+
una imagen o un archivo adjunto no cuentan: su base64 no dice nada de la
|
|
87
|
+
ventana de texto.
|
|
88
|
+
- **Resumen de compactación sin recortes**: el presupuesto de salida de la
|
|
89
|
+
petición de compactación ya no se limita a 32k, porque un resumen cortado por
|
|
90
|
+
el límite hace fallar la compactación completa. Si aun así el resumen no cabe
|
|
91
|
+
en el techo aprendido, se descartan los turnos de usuario más antiguos (sin
|
|
92
|
+
romper parejas de herramienta) en lugar de abortar el turno.
|
|
80
93
|
- **Sin bucles de compactación**: si el servidor rechaza como «demasiado
|
|
81
94
|
largo» una petición que cabe de sobra en la ventana (menos de 60k tokens),
|
|
82
95
|
el plugin la reintenta con un `x-session-id` nuevo en vez de compactar. Si
|
|
@@ -347,6 +360,15 @@ insiste, devuelve un `400` con un mensaje de error de proveedor. Ese texto no
|
|
|
347
360
|
coincide con el patrón de desbordamiento de OpenCode, así que el runner deja de
|
|
348
361
|
compactar en lugar de entrar en un ciclo de resúmenes que no reducen nada.
|
|
349
362
|
|
|
363
|
+
Cuando el rechazo sí corresponde a una conversación larga, el tamaño medido se
|
|
364
|
+
guarda como `rejectedPromptTokens` del modelo en `live-limits.json`. El
|
|
365
|
+
`provider.transform` reconstruye el catálogo con ese techo (85 % del tamaño
|
|
366
|
+
rechazado, sin bajar de la ventana ya aceptada) y `provider.reload` lo aplica en
|
|
367
|
+
caliente, de modo que la siguiente compactación se dispara antes de que el
|
|
368
|
+
gateway rechace el resumen. Si el resumen aún no cupiera, el hook de
|
|
369
|
+
compactación descarta los turnos de usuario más antiguos en lugar de dejar que
|
|
370
|
+
OpenCode aborte el turno.
|
|
371
|
+
|
|
350
372
|
free-pi cobra en créditos contra una cuota diaria, no en USD por token. Por
|
|
351
373
|
eso los modelos se registran con costo `0`, igual que el CLI del proveedor; el
|
|
352
374
|
consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
|
package/dist/catalog/live.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ import type { TokenUsageLike } from "../types.js";
|
|
|
13
13
|
export type ModelObservation = {
|
|
14
14
|
/** Largest prompt the gateway accepted for this model. */
|
|
15
15
|
maxPromptTokens?: number;
|
|
16
|
+
/** Smallest prompt the gateway rejected as too long for this model. */
|
|
17
|
+
rejectedPromptTokens?: number;
|
|
16
18
|
/** Whether a real response carried reasoning tokens. */
|
|
17
19
|
reasoning?: boolean;
|
|
18
20
|
updatedAt: number;
|
|
@@ -38,8 +40,22 @@ export declare function currentLiveLimits(): LiveLimits | undefined;
|
|
|
38
40
|
* model really reasoned for this account.
|
|
39
41
|
*/
|
|
40
42
|
export declare function noteStepTokens(_deps: Deps, modelID: string, tokens: TokenUsageLike | undefined): void;
|
|
41
|
-
/**
|
|
42
|
-
|
|
43
|
+
/**
|
|
44
|
+
* Safe context window for a model whose real ceiling is only known from a
|
|
45
|
+
* rejection. The gateway never publishes it, so the smallest prompt it refused
|
|
46
|
+
* is the only evidence available; the advertised window stays a margin below
|
|
47
|
+
* that, which lets OpenCode compact before the summarizer request is refused
|
|
48
|
+
* too.
|
|
49
|
+
*/
|
|
50
|
+
export declare function learnedContextWindow(limits: LiveLimits | undefined, modelID: string): number | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* Records a request the gateway refused as too long. Real traffic is the only
|
|
53
|
+
* probe that costs nothing, and a rejection is a hard upper bound on the
|
|
54
|
+
* model's window, so it lowers what the catalog advertises for that model from
|
|
55
|
+
* the next build on. Returns the window that now applies, if it changed.
|
|
56
|
+
*/
|
|
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;
|
|
43
59
|
export type VerifyLimitsOptions = {
|
|
44
60
|
/** A free model to probe with; paid models would spend credits. */
|
|
45
61
|
model?: string;
|
package/dist/catalog/live.js
CHANGED
|
@@ -46,6 +46,10 @@ function sanitize(value) {
|
|
|
46
46
|
if (Number.isFinite(entry.maxPromptTokens) && entry.maxPromptTokens > 0) {
|
|
47
47
|
observation.maxPromptTokens = Math.floor(entry.maxPromptTokens);
|
|
48
48
|
}
|
|
49
|
+
if (Number.isFinite(entry.rejectedPromptTokens) &&
|
|
50
|
+
entry.rejectedPromptTokens > 0) {
|
|
51
|
+
observation.rejectedPromptTokens = Math.floor(entry.rejectedPromptTokens);
|
|
52
|
+
}
|
|
49
53
|
if (typeof entry.reasoning === "boolean") {
|
|
50
54
|
observation.reasoning = entry.reasoning;
|
|
51
55
|
}
|
|
@@ -136,8 +140,45 @@ export function noteStepTokens(_deps, modelID, tokens) {
|
|
|
136
140
|
entry.updatedAt = Date.now();
|
|
137
141
|
scheduleWrite();
|
|
138
142
|
}
|
|
139
|
-
/**
|
|
140
|
-
|
|
143
|
+
/** Keeps the advertised window this far below the smallest rejected prompt. */
|
|
144
|
+
const REJECTION_HEADROOM = 0.85;
|
|
145
|
+
/**
|
|
146
|
+
* Safe context window for a model whose real ceiling is only known from a
|
|
147
|
+
* rejection. The gateway never publishes it, so the smallest prompt it refused
|
|
148
|
+
* is the only evidence available; the advertised window stays a margin below
|
|
149
|
+
* that, which lets OpenCode compact before the summarizer request is refused
|
|
150
|
+
* too.
|
|
151
|
+
*/
|
|
152
|
+
export function learnedContextWindow(limits, modelID) {
|
|
153
|
+
const rejected = limits?.models[modelID]?.rejectedPromptTokens;
|
|
154
|
+
if (!rejected || rejected <= 0)
|
|
155
|
+
return undefined;
|
|
156
|
+
return Math.max(2_048, Math.min(Math.floor(rejected * REJECTION_HEADROOM), MAX_WINDOW));
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Records a request the gateway refused as too long. Real traffic is the only
|
|
160
|
+
* probe that costs nothing, and a rejection is a hard upper bound on the
|
|
161
|
+
* model's window, so it lowers what the catalog advertises for that model from
|
|
162
|
+
* the next build on. Returns the window that now applies, if it changed.
|
|
163
|
+
*/
|
|
164
|
+
export function noteRejectedPrompt(deps, modelID, tokens) {
|
|
165
|
+
if (!modelID || !Number.isFinite(tokens) || tokens <= 0)
|
|
166
|
+
return undefined;
|
|
167
|
+
const rejected = Math.floor(tokens);
|
|
168
|
+
const entry = observation(modelID);
|
|
169
|
+
if (entry.rejectedPromptTokens !== undefined &&
|
|
170
|
+
entry.rejectedPromptTokens <= rejected) {
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
const previous = learnedContextWindow(cached, modelID);
|
|
174
|
+
entry.rejectedPromptTokens = rejected;
|
|
175
|
+
entry.updatedAt = Date.now();
|
|
176
|
+
scheduleWrite();
|
|
177
|
+
const window = learnedContextWindow(cached, modelID);
|
|
178
|
+
deps.log.warn("free-pi rejected a prompt as too long; lowering the advertised window", { model: modelID, rejectedTokens: rejected, previous, window });
|
|
179
|
+
return window;
|
|
180
|
+
}
|
|
181
|
+
/** Whether the persisted window is old enough to verify again. */ export function shouldVerifyWindow(limits) {
|
|
141
182
|
const verifiedAt = limits?.window?.verifiedAt;
|
|
142
183
|
if (!verifiedAt)
|
|
143
184
|
return true;
|
package/dist/catalog/models.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
2
|
import { CONTEXT_WINDOW, DEFAULT_REASONING_EFFORT, DEFAULT_THINKING_LEVELS, MAX_CONTEXT_WINDOW, MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING, REASONING_EFFORTS, } from "../constants.js";
|
|
3
|
+
import { learnedContextWindow } from "./live.js";
|
|
3
4
|
import { positiveNumber } from "../utils/numbers.js";
|
|
4
5
|
import { cleanText } from "../utils/text.js";
|
|
5
6
|
export function usableModels(catalog) {
|
|
@@ -268,7 +269,11 @@ export function buildModels(models, candidates = [], options = {}) {
|
|
|
268
269
|
// never push a session past what the gateway takes.
|
|
269
270
|
const observed = options.live?.models[model.id]?.maxPromptTokens ?? 0;
|
|
270
271
|
const contextCeiling = Math.min(MAX_CONTEXT_WINDOW, Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed));
|
|
271
|
-
|
|
272
|
+
// A prompt the gateway already refused is a hard ceiling: advertise below
|
|
273
|
+
// it so OpenCode compacts before the summarization request itself is
|
|
274
|
+
// rejected, which ends the turn with the checkpoint and no answer.
|
|
275
|
+
const learned = learnedContextWindow(options.live, model.id);
|
|
276
|
+
const limitContext = Math.min(positiveNumber(model.context_window, model.contextWindow, model.limit?.context, capability?.limit?.context) ?? contextCeiling, contextCeiling, learned ?? contextCeiling);
|
|
272
277
|
// Reasoning shares the output budget. When models.dev knows the upstream
|
|
273
278
|
// model emits more than the CLI's 32k, advertise that larger budget (up to a
|
|
274
279
|
// sane ceiling) instead of truncating the chain of thought.
|
package/dist/plugin.js
CHANGED
|
@@ -6,7 +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 { loadLiveLimits, shouldVerifyWindow, verifyGatewayWindow, } from "./catalog/live.js";
|
|
9
|
+
import { currentLiveLimits, loadLiveLimits, shouldVerifyWindow, verifyGatewayWindow, } from "./catalog/live.js";
|
|
10
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";
|
|
@@ -149,9 +149,15 @@ async function setup(ctx) {
|
|
|
149
149
|
tokenFromCredential(credential) ?? (await readCredentialsToken());
|
|
150
150
|
await registerIntegration(ctx, deps);
|
|
151
151
|
await ctx.provider.transform((editor) => {
|
|
152
|
-
|
|
152
|
+
// Rebuilt on every transform so a learned context ceiling applies as soon
|
|
153
|
+
// as the response hook records it, without restarting OpenCode.
|
|
154
|
+
const active = currentLiveLimits() ?? live;
|
|
155
|
+
const buildOptionsNow = { ...buildOptions, live: active };
|
|
156
|
+
const mainNow = buildModels(main, candidates, buildOptionsNow);
|
|
157
|
+
const defenseNow = buildModels(defense, candidates, buildOptionsNow);
|
|
158
|
+
applyProvider(editor, PROVIDER_ID, "Free Pi", mainNow, state.providerToken);
|
|
153
159
|
if (includeDefense && defense.length > 0) {
|
|
154
|
-
applyProvider(editor, DEFENSE_PROVIDER_ID, "Free Pi Defense",
|
|
160
|
+
applyProvider(editor, DEFENSE_PROVIDER_ID, "Free Pi Defense", defenseNow, state.providerToken);
|
|
155
161
|
}
|
|
156
162
|
});
|
|
157
163
|
// The gateway does not publish its context ceiling. Verify the compiled
|
package/dist/session/hooks.js
CHANGED
|
@@ -3,10 +3,12 @@ import { ensureAdImpression } from "../ads/impression.js";
|
|
|
3
3
|
import { resolveAdTurn } from "../ads/resolve.js";
|
|
4
4
|
import { resolveToken } from "../auth/token.js";
|
|
5
5
|
import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, DEFENSE_PROVIDER_ID, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER, MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, } from "../constants.js";
|
|
6
|
+
import { currentLiveLimits, learnedContextWindow, noteRejectedPrompt, } from "../catalog/live.js";
|
|
6
7
|
import { closeFreePiSession } from "../api/session.js";
|
|
7
8
|
import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
|
|
8
9
|
import { parseFreePiError } from "../errors/parse.js";
|
|
9
10
|
import { trimMap } from "../utils/async.js";
|
|
11
|
+
import { trimMessagesForBudget } from "./overflow.js";
|
|
10
12
|
import { watchFreePiNotice } from "./notices.js";
|
|
11
13
|
import { clearSpuriousOverflows, noteSpuriousOverflow, overflowingSpuriously, spuriousOverflowResponse, } from "./overflow.js";
|
|
12
14
|
import { rememberReplayBody, replayConcurrentResponse, replaySpuriousOverflow, } from "./replay.js";
|
|
@@ -27,6 +29,32 @@ function rememberPending(deps, key, turn) {
|
|
|
27
29
|
trimMap(deps.state.pendingAdTurns, PENDING_LIMIT);
|
|
28
30
|
deps.state.pendingAdTurns.set(key, turn);
|
|
29
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Fits the compaction request inside the ceiling the gateway has already
|
|
34
|
+
* proven. OpenCode aborts the turn ("the compaction request cannot be reduced
|
|
35
|
+
* further") when the summarizer request is rejected too, so the plugin drops
|
|
36
|
+
* the oldest user turns before that can happen.
|
|
37
|
+
*/
|
|
38
|
+
function fitCompactionMessages(deps, event) {
|
|
39
|
+
const modelID = typeof event.model?.id === "string" ? event.model.id : "";
|
|
40
|
+
const ceiling = learnedContextWindow(currentLiveLimits(), modelID);
|
|
41
|
+
if (!ceiling)
|
|
42
|
+
return;
|
|
43
|
+
const messages = event.messages;
|
|
44
|
+
if (!Array.isArray(messages) || messages.length === 0)
|
|
45
|
+
return;
|
|
46
|
+
const trimmed = trimMessagesForBudget(messages, Math.floor(ceiling * 0.9));
|
|
47
|
+
if (trimmed.dropped === 0)
|
|
48
|
+
return;
|
|
49
|
+
event.messages = [...trimmed.messages];
|
|
50
|
+
deps.log.warn("free-pi trimmed the compaction request to fit the learned window", {
|
|
51
|
+
sessionID: event.sessionID,
|
|
52
|
+
model: modelID,
|
|
53
|
+
window: ceiling,
|
|
54
|
+
droppedMessages: trimmed.dropped,
|
|
55
|
+
promptTokens: trimmed.tokens,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
30
58
|
/** Adds a system block once, even when OpenCode reuses the same event. */
|
|
31
59
|
function appendSystemGuidance(event, text, marker) {
|
|
32
60
|
const system = Array.isArray(event.system) ? event.system : [];
|
|
@@ -52,15 +80,18 @@ async function applyGeneration(deps, event, kind) {
|
|
|
52
80
|
}
|
|
53
81
|
const modelID = event.model?.id;
|
|
54
82
|
const limit = deps.state.outputLimits.get(`${event.model.providerID}/${modelID}`);
|
|
55
|
-
//
|
|
56
|
-
//
|
|
83
|
+
// The compaction summary is the one response that must never be cut: a
|
|
84
|
+
// summary that reaches the output limit fails the whole compaction and the
|
|
85
|
+
// turn stops with nothing but the checkpoint. Leave OpenCode's own budget
|
|
86
|
+
// for it and only cap the answers the user reads.
|
|
57
87
|
const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING);
|
|
58
|
-
if (event.options) {
|
|
88
|
+
if (event.options && kind !== "compaction") {
|
|
59
89
|
const current = event.options.maxTokens;
|
|
60
90
|
if (current === undefined || current > cap)
|
|
61
91
|
event.options.maxTokens = cap;
|
|
62
92
|
}
|
|
63
93
|
if (kind === "compaction") {
|
|
94
|
+
fitCompactionMessages(deps, event);
|
|
64
95
|
appendSystemGuidance(event, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER);
|
|
65
96
|
// OpenCode sends the messages it is folding into the summary, which is the
|
|
66
97
|
// same set pi reports through `session_before_compact`.
|
|
@@ -363,6 +394,20 @@ export async function registerSessionHooks(ctx, deps) {
|
|
|
363
394
|
// window. Compacting then loops, so retry on a fresh wire session
|
|
364
395
|
// first, and stop compacting once the session has seen a few.
|
|
365
396
|
const reviewed = await replaySpuriousOverflow(deps, event).catch(() => ({}));
|
|
397
|
+
// A rejection of a real prompt is the only free measurement of the
|
|
398
|
+
// gateway's ceiling. Attachments inflate the estimate and say nothing
|
|
399
|
+
// about the text window, so they are not learned from.
|
|
400
|
+
if (reviewed.spurious === false &&
|
|
401
|
+
typeof reviewed.tokens === "number" &&
|
|
402
|
+
reviewed.model &&
|
|
403
|
+
reviewed.hasMedia !== true) {
|
|
404
|
+
const learned = noteRejectedPrompt(deps, reviewed.model, reviewed.tokens);
|
|
405
|
+
// Re-run the provider transform so this session's next compaction
|
|
406
|
+
// already targets the smaller window; no restart needed.
|
|
407
|
+
if (learned) {
|
|
408
|
+
void ctx.provider.reload().catch(() => undefined);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
366
411
|
if (reviewed.response) {
|
|
367
412
|
clearSpuriousOverflows(deps, event.sessionID);
|
|
368
413
|
event.response = watchFreePiNotice(deps, reviewed.response);
|
|
@@ -17,12 +17,43 @@ import type { Deps } from "../deps.js";
|
|
|
17
17
|
/** A request below this many tokens cannot exhaust a 200k window on its own. */
|
|
18
18
|
export declare const SPURIOUS_OVERFLOW_TOKENS = 60000;
|
|
19
19
|
export declare const SPURIOUS_OVERFLOW_MESSAGE: string;
|
|
20
|
+
export type RequestProfile = {
|
|
21
|
+
/** Approximate token count of the whole body. */
|
|
22
|
+
readonly tokens: number;
|
|
23
|
+
/** The upstream model the body asks for, when it can be read. */
|
|
24
|
+
readonly model?: string;
|
|
25
|
+
/** Whether the body carries an inline image or file. */
|
|
26
|
+
readonly hasMedia: boolean;
|
|
27
|
+
};
|
|
20
28
|
/**
|
|
21
29
|
* Approximate token count of a chat-completions body: every string in it,
|
|
22
30
|
* message text and tool output alike, at the usual four characters per token.
|
|
23
31
|
* Inline media counts at its base64 length, which is what the provider bills.
|
|
32
|
+
*
|
|
33
|
+
* The same walk reports the requested model and whether the body carries
|
|
34
|
+
* inline media. A rejection caused by a large attachment says nothing about
|
|
35
|
+
* the model's text window, so callers must not learn a ceiling from it.
|
|
24
36
|
*/
|
|
37
|
+
export declare function profileRequest(body: string): RequestProfile;
|
|
38
|
+
/** Token count of a request body, without the extra facts. */
|
|
25
39
|
export declare function measureRequestTokens(body: string): number;
|
|
40
|
+
/** Cheap per-message estimate; the body is serialized once per message. */
|
|
41
|
+
export declare function estimateMessageTokens(message: unknown): number;
|
|
42
|
+
/**
|
|
43
|
+
* Keeps the newest part of a message list inside `budget` tokens, cutting only
|
|
44
|
+
* at user turns so an assistant tool call never loses its results.
|
|
45
|
+
*
|
|
46
|
+
* OpenCode refuses to compact when the summarization request itself is still
|
|
47
|
+
* too large, and then the turn dies with nothing but the checkpoint shown. The
|
|
48
|
+
* gateway's real ceiling is lower than the advertised window, so the plugin
|
|
49
|
+
* trims the oldest turns it can spare before the summarizer is asked to read
|
|
50
|
+
* them.
|
|
51
|
+
*/
|
|
52
|
+
export declare function trimMessagesForBudget(messages: readonly unknown[], budget: number): {
|
|
53
|
+
readonly messages: readonly unknown[];
|
|
54
|
+
readonly dropped: number;
|
|
55
|
+
readonly tokens: number;
|
|
56
|
+
};
|
|
26
57
|
/**
|
|
27
58
|
* Records a rejection of a request that fits, and returns the number of them
|
|
28
59
|
* seen for the session inside the current window. A run of them means the
|
package/dist/session/overflow.js
CHANGED
|
@@ -22,18 +22,35 @@ const STORM_LIMIT = 2;
|
|
|
22
22
|
const STORM_LIMIT_PER_SESSION = 512;
|
|
23
23
|
export const SPURIOUS_OVERFLOW_MESSAGE = "free-pi rejected this request as too long even though it fits the model's window; " +
|
|
24
24
|
"this is a provider failure, not a context overflow. Retry the message, or start a new session if it persists.";
|
|
25
|
+
/** Part types that carry an inline image or file, which the provider bills in full. */
|
|
26
|
+
const MEDIA_PART_TYPES = new Set([
|
|
27
|
+
"image",
|
|
28
|
+
"image_url",
|
|
29
|
+
"input_image",
|
|
30
|
+
"file",
|
|
31
|
+
"input_file",
|
|
32
|
+
]);
|
|
25
33
|
/**
|
|
26
34
|
* Approximate token count of a chat-completions body: every string in it,
|
|
27
35
|
* message text and tool output alike, at the usual four characters per token.
|
|
28
36
|
* Inline media counts at its base64 length, which is what the provider bills.
|
|
37
|
+
*
|
|
38
|
+
* The same walk reports the requested model and whether the body carries
|
|
39
|
+
* inline media. A rejection caused by a large attachment says nothing about
|
|
40
|
+
* the model's text window, so callers must not learn a ceiling from it.
|
|
29
41
|
*/
|
|
30
|
-
export function
|
|
42
|
+
export function profileRequest(body) {
|
|
31
43
|
try {
|
|
32
44
|
const data = JSON.parse(body);
|
|
33
45
|
let chars = 0;
|
|
46
|
+
let model;
|
|
47
|
+
let hasMedia = false;
|
|
34
48
|
const walk = (value) => {
|
|
35
49
|
if (typeof value === "string") {
|
|
36
50
|
chars += value.length;
|
|
51
|
+
if (value.startsWith("data:image/") || value.startsWith("data:application/")) {
|
|
52
|
+
hasMedia = true;
|
|
53
|
+
}
|
|
37
54
|
return;
|
|
38
55
|
}
|
|
39
56
|
if (Array.isArray(value)) {
|
|
@@ -42,18 +59,79 @@ export function measureRequestTokens(body) {
|
|
|
42
59
|
return;
|
|
43
60
|
}
|
|
44
61
|
if (value && typeof value === "object") {
|
|
45
|
-
|
|
62
|
+
const record = value;
|
|
63
|
+
if (typeof record.type === "string" && MEDIA_PART_TYPES.has(record.type)) {
|
|
64
|
+
hasMedia = true;
|
|
65
|
+
}
|
|
66
|
+
if (model === undefined &&
|
|
67
|
+
typeof record.model === "string" &&
|
|
68
|
+
record.model.length > 0) {
|
|
69
|
+
model = record.model;
|
|
70
|
+
}
|
|
71
|
+
for (const [key, item] of Object.entries(record)) {
|
|
46
72
|
chars += key.length;
|
|
47
73
|
walk(item);
|
|
48
74
|
}
|
|
49
75
|
}
|
|
50
76
|
};
|
|
51
77
|
walk(data);
|
|
52
|
-
return Math.ceil(chars / 4);
|
|
78
|
+
return { tokens: Math.ceil(chars / 4), model, hasMedia };
|
|
53
79
|
}
|
|
54
80
|
catch {
|
|
55
|
-
return Math.ceil(body.length / 4);
|
|
81
|
+
return { tokens: Math.ceil(body.length / 4), hasMedia: false };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** Token count of a request body, without the extra facts. */
|
|
85
|
+
export function measureRequestTokens(body) {
|
|
86
|
+
return profileRequest(body).tokens;
|
|
87
|
+
}
|
|
88
|
+
/** Cheap per-message estimate; the body is serialized once per message. */
|
|
89
|
+
export function estimateMessageTokens(message) {
|
|
90
|
+
try {
|
|
91
|
+
return Math.ceil(JSON.stringify(message).length / 4);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return 0;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Keeps the newest part of a message list inside `budget` tokens, cutting only
|
|
99
|
+
* at user turns so an assistant tool call never loses its results.
|
|
100
|
+
*
|
|
101
|
+
* OpenCode refuses to compact when the summarization request itself is still
|
|
102
|
+
* too large, and then the turn dies with nothing but the checkpoint shown. The
|
|
103
|
+
* gateway's real ceiling is lower than the advertised window, so the plugin
|
|
104
|
+
* trims the oldest turns it can spare before the summarizer is asked to read
|
|
105
|
+
* them.
|
|
106
|
+
*/
|
|
107
|
+
export function trimMessagesForBudget(messages, budget) {
|
|
108
|
+
if (messages.length === 0)
|
|
109
|
+
return { messages, dropped: 0, tokens: 0 };
|
|
110
|
+
const sizes = messages.map(estimateMessageTokens);
|
|
111
|
+
let total = 0;
|
|
112
|
+
for (const size of sizes)
|
|
113
|
+
total += size;
|
|
114
|
+
if (total <= budget)
|
|
115
|
+
return { messages, dropped: 0, tokens: total };
|
|
116
|
+
const cuts = [];
|
|
117
|
+
for (let index = 1; index < messages.length; index += 1) {
|
|
118
|
+
const role = messages[index]?.role;
|
|
119
|
+
if (role === "user")
|
|
120
|
+
cuts.push(index);
|
|
121
|
+
}
|
|
122
|
+
for (const cut of cuts) {
|
|
123
|
+
let tail = 0;
|
|
124
|
+
for (let index = cut; index < sizes.length; index += 1)
|
|
125
|
+
tail += sizes[index];
|
|
126
|
+
if (tail <= budget) {
|
|
127
|
+
return { messages: messages.slice(cut), dropped: cut, tokens: tail };
|
|
128
|
+
}
|
|
56
129
|
}
|
|
130
|
+
const last = cuts.length > 0 ? cuts[cuts.length - 1] : messages.length - 1;
|
|
131
|
+
let tail = 0;
|
|
132
|
+
for (let index = last; index < sizes.length; index += 1)
|
|
133
|
+
tail += sizes[index];
|
|
134
|
+
return { messages: messages.slice(last), dropped: last, tokens: tail };
|
|
57
135
|
}
|
|
58
136
|
/**
|
|
59
137
|
* Records a rejection of a request that fits, and returns the number of them
|
package/dist/session/replay.d.ts
CHANGED
|
@@ -24,6 +24,10 @@ export declare function replayConcurrentResponse(deps: Deps, event: any): Promis
|
|
|
24
24
|
export type OverflowReplay = {
|
|
25
25
|
/** Tokens of the rejected request, when its body was available. */
|
|
26
26
|
readonly tokens?: number;
|
|
27
|
+
/** Upstream model the rejected request asked for. */
|
|
28
|
+
readonly model?: string;
|
|
29
|
+
/** Whether the rejected request carried an inline image or file. */
|
|
30
|
+
readonly hasMedia?: boolean;
|
|
27
31
|
/** Whether the rejected request plainly fits the model window. */
|
|
28
32
|
readonly spurious?: boolean;
|
|
29
33
|
/** A good response from a fresh wire session, when the retry succeeded. */
|
package/dist/session/replay.js
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
import { closeFreePiSession } from "../api/session.js";
|
|
17
17
|
import { overflowCodeOf } from "../errors/limit.js";
|
|
18
18
|
import { sleep, trimMap } from "../utils/async.js";
|
|
19
|
-
import {
|
|
19
|
+
import { profileRequest, SPURIOUS_OVERFLOW_TOKENS, } from "./overflow.js";
|
|
20
20
|
import { rotateWireSessionID, wireSessionID } from "./wire.js";
|
|
21
21
|
const REPLAY_BODY_LIMIT = 24;
|
|
22
22
|
const REPLAY_MAX_ATTEMPTS = 4;
|
|
@@ -152,13 +152,16 @@ export async function replaySpuriousOverflow(deps, event) {
|
|
|
152
152
|
const body = await storedBody(deps, event);
|
|
153
153
|
if (!body)
|
|
154
154
|
return {};
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
155
|
+
const profile = profileRequest(body);
|
|
156
|
+
const tokens = profile.tokens;
|
|
157
|
+
const facts = { model: profile.model, hasMedia: profile.hasMedia };
|
|
158
|
+
if (tokens >= SPURIOUS_OVERFLOW_TOKENS) {
|
|
159
|
+
return { tokens, ...facts, spurious: false };
|
|
160
|
+
}
|
|
158
161
|
let previous = request.headers.get("x-session-id") ?? wireSessionID(deps, event.sessionID);
|
|
159
162
|
for (let attempt = 1; attempt <= OVERFLOW_REPLAY_ATTEMPTS; attempt++) {
|
|
160
163
|
if (request.signal.aborted)
|
|
161
|
-
return { tokens, spurious: true };
|
|
164
|
+
return { tokens, ...facts, spurious: true };
|
|
162
165
|
const next = rotateWireSessionID(deps, event.sessionID);
|
|
163
166
|
if (previous && previous !== next) {
|
|
164
167
|
void closeFreePiSession(deps, previous).catch(() => undefined);
|
|
@@ -178,9 +181,9 @@ export async function replaySpuriousOverflow(deps, event) {
|
|
|
178
181
|
continue;
|
|
179
182
|
if (!(await overflowCodeOf(response))) {
|
|
180
183
|
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 };
|
|
184
|
+
return { tokens, ...facts, spurious: true, response };
|
|
182
185
|
}
|
|
183
186
|
}
|
|
184
187
|
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 };
|
|
188
|
+
return { tokens, ...facts, spurious: true };
|
|
186
189
|
}
|
package/package.json
CHANGED
package/src/catalog/live.ts
CHANGED
|
@@ -37,6 +37,8 @@ const INITIAL_CHARS_PER_TOKEN = 4;
|
|
|
37
37
|
export type ModelObservation = {
|
|
38
38
|
/** Largest prompt the gateway accepted for this model. */
|
|
39
39
|
maxPromptTokens?: number;
|
|
40
|
+
/** Smallest prompt the gateway rejected as too long for this model. */
|
|
41
|
+
rejectedPromptTokens?: number;
|
|
40
42
|
/** Whether a real response carried reasoning tokens. */
|
|
41
43
|
reasoning?: boolean;
|
|
42
44
|
updatedAt: number;
|
|
@@ -71,6 +73,14 @@ function sanitize(value: unknown): LiveLimits {
|
|
|
71
73
|
if (Number.isFinite(entry.maxPromptTokens) && entry.maxPromptTokens! > 0) {
|
|
72
74
|
observation.maxPromptTokens = Math.floor(entry.maxPromptTokens!);
|
|
73
75
|
}
|
|
76
|
+
if (
|
|
77
|
+
Number.isFinite(entry.rejectedPromptTokens) &&
|
|
78
|
+
entry.rejectedPromptTokens! > 0
|
|
79
|
+
) {
|
|
80
|
+
observation.rejectedPromptTokens = Math.floor(
|
|
81
|
+
entry.rejectedPromptTokens!,
|
|
82
|
+
);
|
|
83
|
+
}
|
|
74
84
|
if (typeof entry.reasoning === "boolean") {
|
|
75
85
|
observation.reasoning = entry.reasoning;
|
|
76
86
|
}
|
|
@@ -166,8 +176,61 @@ export function noteStepTokens(
|
|
|
166
176
|
scheduleWrite();
|
|
167
177
|
}
|
|
168
178
|
|
|
169
|
-
/**
|
|
170
|
-
|
|
179
|
+
/** Keeps the advertised window this far below the smallest rejected prompt. */
|
|
180
|
+
const REJECTION_HEADROOM = 0.85;
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Safe context window for a model whose real ceiling is only known from a
|
|
184
|
+
* rejection. The gateway never publishes it, so the smallest prompt it refused
|
|
185
|
+
* is the only evidence available; the advertised window stays a margin below
|
|
186
|
+
* that, which lets OpenCode compact before the summarizer request is refused
|
|
187
|
+
* too.
|
|
188
|
+
*/
|
|
189
|
+
export function learnedContextWindow(
|
|
190
|
+
limits: LiveLimits | undefined,
|
|
191
|
+
modelID: string,
|
|
192
|
+
): number | undefined {
|
|
193
|
+
const rejected = limits?.models[modelID]?.rejectedPromptTokens;
|
|
194
|
+
if (!rejected || rejected <= 0) return undefined;
|
|
195
|
+
return Math.max(2_048, Math.min(
|
|
196
|
+
Math.floor(rejected * REJECTION_HEADROOM),
|
|
197
|
+
MAX_WINDOW,
|
|
198
|
+
));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Records a request the gateway refused as too long. Real traffic is the only
|
|
203
|
+
* probe that costs nothing, and a rejection is a hard upper bound on the
|
|
204
|
+
* model's window, so it lowers what the catalog advertises for that model from
|
|
205
|
+
* the next build on. Returns the window that now applies, if it changed.
|
|
206
|
+
*/
|
|
207
|
+
export function noteRejectedPrompt(
|
|
208
|
+
deps: Deps,
|
|
209
|
+
modelID: string,
|
|
210
|
+
tokens: number,
|
|
211
|
+
): number | undefined {
|
|
212
|
+
if (!modelID || !Number.isFinite(tokens) || tokens <= 0) return undefined;
|
|
213
|
+
const rejected = Math.floor(tokens);
|
|
214
|
+
const entry = observation(modelID);
|
|
215
|
+
if (
|
|
216
|
+
entry.rejectedPromptTokens !== undefined &&
|
|
217
|
+
entry.rejectedPromptTokens <= rejected
|
|
218
|
+
) {
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
const previous = learnedContextWindow(cached, modelID);
|
|
222
|
+
entry.rejectedPromptTokens = rejected;
|
|
223
|
+
entry.updatedAt = Date.now();
|
|
224
|
+
scheduleWrite();
|
|
225
|
+
const window = learnedContextWindow(cached, modelID);
|
|
226
|
+
deps.log.warn(
|
|
227
|
+
"free-pi rejected a prompt as too long; lowering the advertised window",
|
|
228
|
+
{ model: modelID, rejectedTokens: rejected, previous, window },
|
|
229
|
+
);
|
|
230
|
+
return window;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Whether the persisted window is old enough to verify again. */export function shouldVerifyWindow(limits: LiveLimits | undefined): boolean {
|
|
171
234
|
const verifiedAt = limits?.window?.verifiedAt;
|
|
172
235
|
if (!verifiedAt) return true;
|
|
173
236
|
return Date.now() - verifiedAt > VERIFY_LIMITS_TTL_MS;
|
package/src/catalog/models.ts
CHANGED
|
@@ -20,6 +20,7 @@ import type {
|
|
|
20
20
|
RegistryCandidate,
|
|
21
21
|
} from "../types.js";
|
|
22
22
|
import type { LiveLimits } from "./live.js";
|
|
23
|
+
import { learnedContextWindow } from "./live.js";
|
|
23
24
|
import { positiveNumber } from "../utils/numbers.js";
|
|
24
25
|
import { cleanText } from "../utils/text.js";
|
|
25
26
|
|
|
@@ -376,6 +377,10 @@ export function buildModels(
|
|
|
376
377
|
MAX_CONTEXT_WINDOW,
|
|
377
378
|
Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed),
|
|
378
379
|
);
|
|
380
|
+
// A prompt the gateway already refused is a hard ceiling: advertise below
|
|
381
|
+
// it so OpenCode compacts before the summarization request itself is
|
|
382
|
+
// rejected, which ends the turn with the checkpoint and no answer.
|
|
383
|
+
const learned = learnedContextWindow(options.live, model.id);
|
|
379
384
|
const limitContext = Math.min(
|
|
380
385
|
positiveNumber(
|
|
381
386
|
model.context_window,
|
|
@@ -384,6 +389,7 @@ export function buildModels(
|
|
|
384
389
|
capability?.limit?.context,
|
|
385
390
|
) ?? contextCeiling,
|
|
386
391
|
contextCeiling,
|
|
392
|
+
learned ?? contextCeiling,
|
|
387
393
|
);
|
|
388
394
|
// Reasoning shares the output budget. When models.dev knows the upstream
|
|
389
395
|
// model emits more than the CLI's 32k, advertise that larger budget (up to a
|
package/src/plugin.ts
CHANGED
|
@@ -17,6 +17,7 @@ import { readCredentialsToken } from "./auth/credentials.js";
|
|
|
17
17
|
import { tokenFromCredential } from "./auth/credential.js";
|
|
18
18
|
import { fetchCatalog } from "./catalog/catalog.js";
|
|
19
19
|
import {
|
|
20
|
+
currentLiveLimits,
|
|
20
21
|
loadLiveLimits,
|
|
21
22
|
shouldVerifyWindow,
|
|
22
23
|
verifyGatewayWindow,
|
|
@@ -188,11 +189,17 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
188
189
|
await registerIntegration(ctx, deps);
|
|
189
190
|
|
|
190
191
|
await ctx.provider.transform((editor) => {
|
|
192
|
+
// Rebuilt on every transform so a learned context ceiling applies as soon
|
|
193
|
+
// as the response hook records it, without restarting OpenCode.
|
|
194
|
+
const active = currentLiveLimits() ?? live;
|
|
195
|
+
const buildOptionsNow = { ...buildOptions, live: active };
|
|
196
|
+
const mainNow = buildModels(main, candidates, buildOptionsNow);
|
|
197
|
+
const defenseNow = buildModels(defense, candidates, buildOptionsNow);
|
|
191
198
|
applyProvider(
|
|
192
199
|
editor,
|
|
193
200
|
PROVIDER_ID,
|
|
194
201
|
"Free Pi",
|
|
195
|
-
|
|
202
|
+
mainNow,
|
|
196
203
|
state.providerToken,
|
|
197
204
|
);
|
|
198
205
|
if (includeDefense && defense.length > 0) {
|
|
@@ -200,7 +207,7 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
200
207
|
editor,
|
|
201
208
|
DEFENSE_PROVIDER_ID,
|
|
202
209
|
"Free Pi Defense",
|
|
203
|
-
|
|
210
|
+
defenseNow,
|
|
204
211
|
state.providerToken,
|
|
205
212
|
);
|
|
206
213
|
}
|
package/src/session/hooks.ts
CHANGED
|
@@ -24,6 +24,11 @@ import {
|
|
|
24
24
|
RETRY_MAX_RETRIES,
|
|
25
25
|
SUBAGENT_HEADER,
|
|
26
26
|
} from "../constants.js";
|
|
27
|
+
import {
|
|
28
|
+
currentLiveLimits,
|
|
29
|
+
learnedContextWindow,
|
|
30
|
+
noteRejectedPrompt,
|
|
31
|
+
} from "../catalog/live.js";
|
|
27
32
|
import type { Deps } from "../deps.js";
|
|
28
33
|
import { closeFreePiSession } from "../api/session.js";
|
|
29
34
|
import {
|
|
@@ -32,6 +37,7 @@ import {
|
|
|
32
37
|
} from "../errors/limit.js";
|
|
33
38
|
import { parseFreePiError } from "../errors/parse.js";
|
|
34
39
|
import { trimMap } from "../utils/async.js";
|
|
40
|
+
import { trimMessagesForBudget } from "./overflow.js";
|
|
35
41
|
import { watchFreePiNotice } from "./notices.js";
|
|
36
42
|
import {
|
|
37
43
|
clearSpuriousOverflows,
|
|
@@ -96,6 +102,33 @@ function rememberPending(deps: Deps, key: string, turn: AdTurn): void {
|
|
|
96
102
|
deps.state.pendingAdTurns.set(key, turn);
|
|
97
103
|
}
|
|
98
104
|
|
|
105
|
+
/**
|
|
106
|
+
* Fits the compaction request inside the ceiling the gateway has already
|
|
107
|
+
* proven. OpenCode aborts the turn ("the compaction request cannot be reduced
|
|
108
|
+
* further") when the summarizer request is rejected too, so the plugin drops
|
|
109
|
+
* the oldest user turns before that can happen.
|
|
110
|
+
*/
|
|
111
|
+
function fitCompactionMessages(deps: Deps, event: any): void {
|
|
112
|
+
const modelID = typeof event.model?.id === "string" ? event.model.id : "";
|
|
113
|
+
const ceiling = learnedContextWindow(currentLiveLimits(), modelID);
|
|
114
|
+
if (!ceiling) return;
|
|
115
|
+
const messages = event.messages;
|
|
116
|
+
if (!Array.isArray(messages) || messages.length === 0) return;
|
|
117
|
+
const trimmed = trimMessagesForBudget(messages, Math.floor(ceiling * 0.9));
|
|
118
|
+
if (trimmed.dropped === 0) return;
|
|
119
|
+
event.messages = [...trimmed.messages];
|
|
120
|
+
deps.log.warn(
|
|
121
|
+
"free-pi trimmed the compaction request to fit the learned window",
|
|
122
|
+
{
|
|
123
|
+
sessionID: event.sessionID,
|
|
124
|
+
model: modelID,
|
|
125
|
+
window: ceiling,
|
|
126
|
+
droppedMessages: trimmed.dropped,
|
|
127
|
+
promptTokens: trimmed.tokens,
|
|
128
|
+
},
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
99
132
|
/** Adds a system block once, even when OpenCode reuses the same event. */
|
|
100
133
|
function appendSystemGuidance(
|
|
101
134
|
event: any,
|
|
@@ -138,15 +171,18 @@ async function applyGeneration(
|
|
|
138
171
|
const limit = deps.state.outputLimits.get(
|
|
139
172
|
`${event.model.providerID}/${modelID}`,
|
|
140
173
|
);
|
|
141
|
-
//
|
|
142
|
-
//
|
|
174
|
+
// The compaction summary is the one response that must never be cut: a
|
|
175
|
+
// summary that reaches the output limit fails the whole compaction and the
|
|
176
|
+
// turn stops with nothing but the checkpoint. Leave OpenCode's own budget
|
|
177
|
+
// for it and only cap the answers the user reads.
|
|
143
178
|
const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING);
|
|
144
|
-
if (event.options) {
|
|
179
|
+
if (event.options && kind !== "compaction") {
|
|
145
180
|
const current = event.options.maxTokens;
|
|
146
181
|
if (current === undefined || current > cap) event.options.maxTokens = cap;
|
|
147
182
|
}
|
|
148
183
|
|
|
149
184
|
if (kind === "compaction") {
|
|
185
|
+
fitCompactionMessages(deps, event);
|
|
150
186
|
appendSystemGuidance(
|
|
151
187
|
event,
|
|
152
188
|
FREE_PI_COMPACTION_GUIDANCE,
|
|
@@ -540,6 +576,26 @@ export async function registerSessionHooks(
|
|
|
540
576
|
const reviewed = await replaySpuriousOverflow(deps, event).catch(
|
|
541
577
|
() => ({}) as OverflowReplay,
|
|
542
578
|
);
|
|
579
|
+
// A rejection of a real prompt is the only free measurement of the
|
|
580
|
+
// gateway's ceiling. Attachments inflate the estimate and say nothing
|
|
581
|
+
// about the text window, so they are not learned from.
|
|
582
|
+
if (
|
|
583
|
+
reviewed.spurious === false &&
|
|
584
|
+
typeof reviewed.tokens === "number" &&
|
|
585
|
+
reviewed.model &&
|
|
586
|
+
reviewed.hasMedia !== true
|
|
587
|
+
) {
|
|
588
|
+
const learned = noteRejectedPrompt(
|
|
589
|
+
deps,
|
|
590
|
+
reviewed.model,
|
|
591
|
+
reviewed.tokens,
|
|
592
|
+
);
|
|
593
|
+
// Re-run the provider transform so this session's next compaction
|
|
594
|
+
// already targets the smaller window; no restart needed.
|
|
595
|
+
if (learned) {
|
|
596
|
+
void ctx.provider.reload().catch(() => undefined);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
543
599
|
if (reviewed.response) {
|
|
544
600
|
clearSpuriousOverflows(deps, event.sessionID);
|
|
545
601
|
event.response = watchFreePiNotice(deps, reviewed.response);
|
package/src/session/overflow.ts
CHANGED
|
@@ -31,18 +31,45 @@ export const SPURIOUS_OVERFLOW_MESSAGE =
|
|
|
31
31
|
"free-pi rejected this request as too long even though it fits the model's window; " +
|
|
32
32
|
"this is a provider failure, not a context overflow. Retry the message, or start a new session if it persists.";
|
|
33
33
|
|
|
34
|
+
/** Part types that carry an inline image or file, which the provider bills in full. */
|
|
35
|
+
const MEDIA_PART_TYPES = new Set([
|
|
36
|
+
"image",
|
|
37
|
+
"image_url",
|
|
38
|
+
"input_image",
|
|
39
|
+
"file",
|
|
40
|
+
"input_file",
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
export type RequestProfile = {
|
|
44
|
+
/** Approximate token count of the whole body. */
|
|
45
|
+
readonly tokens: number;
|
|
46
|
+
/** The upstream model the body asks for, when it can be read. */
|
|
47
|
+
readonly model?: string;
|
|
48
|
+
/** Whether the body carries an inline image or file. */
|
|
49
|
+
readonly hasMedia: boolean;
|
|
50
|
+
};
|
|
51
|
+
|
|
34
52
|
/**
|
|
35
53
|
* Approximate token count of a chat-completions body: every string in it,
|
|
36
54
|
* message text and tool output alike, at the usual four characters per token.
|
|
37
55
|
* Inline media counts at its base64 length, which is what the provider bills.
|
|
56
|
+
*
|
|
57
|
+
* The same walk reports the requested model and whether the body carries
|
|
58
|
+
* inline media. A rejection caused by a large attachment says nothing about
|
|
59
|
+
* the model's text window, so callers must not learn a ceiling from it.
|
|
38
60
|
*/
|
|
39
|
-
export function
|
|
61
|
+
export function profileRequest(body: string): RequestProfile {
|
|
40
62
|
try {
|
|
41
63
|
const data = JSON.parse(body) as unknown;
|
|
42
64
|
let chars = 0;
|
|
65
|
+
let model: string | undefined;
|
|
66
|
+
let hasMedia = false;
|
|
43
67
|
const walk = (value: unknown): void => {
|
|
44
68
|
if (typeof value === "string") {
|
|
45
69
|
chars += value.length;
|
|
70
|
+
if (value.startsWith("data:image/") || value.startsWith("data:application/")) {
|
|
71
|
+
hasMedia = true;
|
|
72
|
+
}
|
|
46
73
|
return;
|
|
47
74
|
}
|
|
48
75
|
if (Array.isArray(value)) {
|
|
@@ -50,17 +77,84 @@ export function measureRequestTokens(body: string): number {
|
|
|
50
77
|
return;
|
|
51
78
|
}
|
|
52
79
|
if (value && typeof value === "object") {
|
|
53
|
-
|
|
80
|
+
const record = value as Record<string, unknown>;
|
|
81
|
+
if (typeof record.type === "string" && MEDIA_PART_TYPES.has(record.type)) {
|
|
82
|
+
hasMedia = true;
|
|
83
|
+
}
|
|
84
|
+
if (
|
|
85
|
+
model === undefined &&
|
|
86
|
+
typeof record.model === "string" &&
|
|
87
|
+
record.model.length > 0
|
|
88
|
+
) {
|
|
89
|
+
model = record.model;
|
|
90
|
+
}
|
|
91
|
+
for (const [key, item] of Object.entries(record)) {
|
|
54
92
|
chars += key.length;
|
|
55
93
|
walk(item);
|
|
56
94
|
}
|
|
57
95
|
}
|
|
58
96
|
};
|
|
59
97
|
walk(data);
|
|
60
|
-
return Math.ceil(chars / 4);
|
|
98
|
+
return { tokens: Math.ceil(chars / 4), model, hasMedia };
|
|
61
99
|
} catch {
|
|
62
|
-
return Math.ceil(body.length / 4);
|
|
100
|
+
return { tokens: Math.ceil(body.length / 4), hasMedia: false };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Token count of a request body, without the extra facts. */
|
|
105
|
+
export function measureRequestTokens(body: string): number {
|
|
106
|
+
return profileRequest(body).tokens;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Cheap per-message estimate; the body is serialized once per message. */
|
|
110
|
+
export function estimateMessageTokens(message: unknown): number {
|
|
111
|
+
try {
|
|
112
|
+
return Math.ceil(JSON.stringify(message).length / 4);
|
|
113
|
+
} catch {
|
|
114
|
+
return 0;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Keeps the newest part of a message list inside `budget` tokens, cutting only
|
|
120
|
+
* at user turns so an assistant tool call never loses its results.
|
|
121
|
+
*
|
|
122
|
+
* OpenCode refuses to compact when the summarization request itself is still
|
|
123
|
+
* too large, and then the turn dies with nothing but the checkpoint shown. The
|
|
124
|
+
* gateway's real ceiling is lower than the advertised window, so the plugin
|
|
125
|
+
* trims the oldest turns it can spare before the summarizer is asked to read
|
|
126
|
+
* them.
|
|
127
|
+
*/
|
|
128
|
+
export function trimMessagesForBudget(
|
|
129
|
+
messages: readonly unknown[],
|
|
130
|
+
budget: number,
|
|
131
|
+
): {
|
|
132
|
+
readonly messages: readonly unknown[];
|
|
133
|
+
readonly dropped: number;
|
|
134
|
+
readonly tokens: number;
|
|
135
|
+
} {
|
|
136
|
+
if (messages.length === 0) return { messages, dropped: 0, tokens: 0 };
|
|
137
|
+
const sizes = messages.map(estimateMessageTokens);
|
|
138
|
+
let total = 0;
|
|
139
|
+
for (const size of sizes) total += size;
|
|
140
|
+
if (total <= budget) return { messages, dropped: 0, tokens: total };
|
|
141
|
+
|
|
142
|
+
const cuts: number[] = [];
|
|
143
|
+
for (let index = 1; index < messages.length; index += 1) {
|
|
144
|
+
const role = (messages[index] as { role?: unknown } | undefined)?.role;
|
|
145
|
+
if (role === "user") cuts.push(index);
|
|
146
|
+
}
|
|
147
|
+
for (const cut of cuts) {
|
|
148
|
+
let tail = 0;
|
|
149
|
+
for (let index = cut; index < sizes.length; index += 1) tail += sizes[index]!;
|
|
150
|
+
if (tail <= budget) {
|
|
151
|
+
return { messages: messages.slice(cut), dropped: cut, tokens: tail };
|
|
152
|
+
}
|
|
63
153
|
}
|
|
154
|
+
const last = cuts.length > 0 ? cuts[cuts.length - 1]! : messages.length - 1;
|
|
155
|
+
let tail = 0;
|
|
156
|
+
for (let index = last; index < sizes.length; index += 1) tail += sizes[index]!;
|
|
157
|
+
return { messages: messages.slice(last), dropped: last, tokens: tail };
|
|
64
158
|
}
|
|
65
159
|
|
|
66
160
|
/**
|
package/src/session/replay.ts
CHANGED
|
@@ -19,7 +19,7 @@ import type { Deps } from "../deps.js";
|
|
|
19
19
|
import { overflowCodeOf } from "../errors/limit.js";
|
|
20
20
|
import { sleep, trimMap } from "../utils/async.js";
|
|
21
21
|
import {
|
|
22
|
-
|
|
22
|
+
profileRequest,
|
|
23
23
|
SPURIOUS_OVERFLOW_TOKENS,
|
|
24
24
|
} from "./overflow.js";
|
|
25
25
|
import { rotateWireSessionID, wireSessionID } from "./wire.js";
|
|
@@ -159,6 +159,10 @@ export async function replayConcurrentResponse(
|
|
|
159
159
|
export type OverflowReplay = {
|
|
160
160
|
/** Tokens of the rejected request, when its body was available. */
|
|
161
161
|
readonly tokens?: number;
|
|
162
|
+
/** Upstream model the rejected request asked for. */
|
|
163
|
+
readonly model?: string;
|
|
164
|
+
/** Whether the rejected request carried an inline image or file. */
|
|
165
|
+
readonly hasMedia?: boolean;
|
|
162
166
|
/** Whether the rejected request plainly fits the model window. */
|
|
163
167
|
readonly spurious?: boolean;
|
|
164
168
|
/** A good response from a fresh wire session, when the retry succeeded. */
|
|
@@ -187,13 +191,17 @@ export async function replaySpuriousOverflow(
|
|
|
187
191
|
|
|
188
192
|
const body = await storedBody(deps, event);
|
|
189
193
|
if (!body) return {};
|
|
190
|
-
const
|
|
191
|
-
|
|
194
|
+
const profile = profileRequest(body);
|
|
195
|
+
const tokens = profile.tokens;
|
|
196
|
+
const facts = { model: profile.model, hasMedia: profile.hasMedia };
|
|
197
|
+
if (tokens >= SPURIOUS_OVERFLOW_TOKENS) {
|
|
198
|
+
return { tokens, ...facts, spurious: false };
|
|
199
|
+
}
|
|
192
200
|
|
|
193
201
|
let previous =
|
|
194
202
|
request.headers.get("x-session-id") ?? wireSessionID(deps, event.sessionID);
|
|
195
203
|
for (let attempt = 1; attempt <= OVERFLOW_REPLAY_ATTEMPTS; attempt++) {
|
|
196
|
-
if (request.signal.aborted) return { tokens, spurious: true };
|
|
204
|
+
if (request.signal.aborted) return { tokens, ...facts, spurious: true };
|
|
197
205
|
const next = rotateWireSessionID(deps, event.sessionID);
|
|
198
206
|
if (previous && previous !== next) {
|
|
199
207
|
void closeFreePiSession(deps, previous).catch(() => undefined);
|
|
@@ -217,12 +225,12 @@ export async function replaySpuriousOverflow(
|
|
|
217
225
|
"free-pi rejected a request that fits as too long; replayed it on a fresh session id",
|
|
218
226
|
{ sessionID: event.sessionID, tokens, to: next, attempt },
|
|
219
227
|
);
|
|
220
|
-
return { tokens, spurious: true, response };
|
|
228
|
+
return { tokens, ...facts, spurious: true, response };
|
|
221
229
|
}
|
|
222
230
|
}
|
|
223
231
|
deps.log.info(
|
|
224
232
|
"free-pi keeps rejecting a request that fits as too long; the provider is failing",
|
|
225
233
|
{ sessionID: event.sessionID, tokens },
|
|
226
234
|
);
|
|
227
|
-
return { tokens, spurious: true };
|
|
235
|
+
return { tokens, ...facts, spurious: true };
|
|
228
236
|
}
|