@eduardo191labs/opencode-free-pi 0.7.25 → 0.7.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -66
- package/dist/catalog/live.js +14 -1
- package/dist/catalog/models.d.ts +1 -1
- package/dist/catalog/models.js +24 -3
- package/dist/constants.d.ts +18 -14
- package/dist/constants.js +19 -15
- package/dist/plugin.js +14 -46
- package/dist/session/hooks.js +116 -205
- package/dist/session/overflow.d.ts +7 -28
- package/dist/session/overflow.js +7 -73
- package/dist/session/replay.d.ts +8 -41
- package/dist/session/replay.js +9 -148
- package/dist/session/tools.d.ts +2 -7
- package/dist/session/tools.js +3 -18
- package/dist/session/trace.js +0 -1
- package/dist/state.d.ts +0 -3
- package/dist/state.js +0 -2
- package/dist/tools/vision.js +1 -0
- package/dist/types.d.ts +9 -1
- package/package.json +2 -2
- package/src/catalog/live.ts +14 -1
- package/src/catalog/models.ts +28 -3
- package/src/constants.ts +20 -15
- package/src/plugin.ts +12 -52
- package/src/session/hooks.ts +149 -255
- package/src/session/overflow.ts +7 -77
- package/src/session/replay.ts +12 -188
- package/src/session/tools.ts +1 -22
- package/src/session/trace.ts +0 -1
- package/src/state.ts +0 -5
- package/src/tools/vision.ts +2 -0
- package/src/types.ts +6 -1
- package/dist/session/diet.d.ts +0 -23
- package/dist/session/diet.js +0 -176
- package/src/session/diet.ts +0 -201
package/dist/session/hooks.js
CHANGED
|
@@ -2,21 +2,19 @@
|
|
|
2
2
|
import { ensureAdImpression } from "../ads/impression.js";
|
|
3
3
|
import { resolveAdTurn } from "../ads/resolve.js";
|
|
4
4
|
import { resolveToken } from "../auth/token.js";
|
|
5
|
-
import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS,
|
|
6
|
-
import { currentLiveLimits,
|
|
5
|
+
import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, CONTEXT_WINDOW, DEFENSE_PROVIDER_ID, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, TRANSPORT_RETRY_BASE_MS, TRANSPORT_RETRY_MAX, TRANSPORT_RETRY_MAX_DELAY_MS, } from "../constants.js";
|
|
6
|
+
import { currentLiveLimits, noteRejectedPrompt } from "../catalog/live.js";
|
|
7
7
|
import { closeFreePiSession } from "../api/session.js";
|
|
8
8
|
import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
|
|
9
9
|
import { parseFreePiError } from "../errors/parse.js";
|
|
10
10
|
import { trimMap } from "../utils/async.js";
|
|
11
|
-
import { pruneStaleToolResults } from "./diet.js";
|
|
12
|
-
import { trimMessagesForBudget, estimateMessageTokens } from "./overflow.js";
|
|
13
11
|
import { watchFreePiNotice } from "./notices.js";
|
|
14
|
-
import {
|
|
15
|
-
import { rememberReplayBody,
|
|
12
|
+
import { noteSpuriousOverflow, overflowingSpuriously, profileRequest, SPURIOUS_OVERFLOW_SHARE, spuriousOverflowResponse, } from "./overflow.js";
|
|
13
|
+
import { rememberReplayBody, storedBody } from "./replay.js";
|
|
16
14
|
import { localTitle } from "./title.js";
|
|
17
15
|
import { rememberFreePiSession } from "./track.js";
|
|
18
16
|
import { hydrateWireSessionID, markWireSessionDirty, rotateWireSessionID, takeWireSessionDirty, wireSessionID, } from "./wire.js";
|
|
19
|
-
import { FREE_PI_TOOL_NAMES, isFreePiSession,
|
|
17
|
+
import { FREE_PI_TOOL_NAMES, isFreePiSession, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
|
|
20
18
|
import { rememberTrackedModel } from "./usage.js";
|
|
21
19
|
const PENDING_LIMIT = 400;
|
|
22
20
|
/** Each agent gets its own ad turn, so a subagent never reuses the parent's. */
|
|
@@ -30,124 +28,6 @@ function rememberPending(deps, key, turn) {
|
|
|
30
28
|
trimMap(deps.state.pendingAdTurns, PENDING_LIMIT);
|
|
31
29
|
deps.state.pendingAdTurns.set(key, turn);
|
|
32
30
|
}
|
|
33
|
-
/**
|
|
34
|
-
* Fits the compaction request inside the ceiling the gateway has already
|
|
35
|
-
* proven. OpenCode aborts the turn ("the compaction request cannot be reduced
|
|
36
|
-
* further") when the summarizer request is rejected too, so the plugin drops
|
|
37
|
-
* the oldest user turns before that can happen.
|
|
38
|
-
*/
|
|
39
|
-
function fitCompactionMessages(deps, event, reserveTokens = 0) {
|
|
40
|
-
const modelID = typeof event.model?.id === "string" ? event.model.id : "";
|
|
41
|
-
const ceiling = learnedContextWindow(currentLiveLimits(), modelID);
|
|
42
|
-
if (!ceiling)
|
|
43
|
-
return;
|
|
44
|
-
const messages = event.messages;
|
|
45
|
-
if (!Array.isArray(messages) || messages.length === 0)
|
|
46
|
-
return;
|
|
47
|
-
const budget = Math.max(1_000, Math.floor(ceiling * 0.9) - Math.max(0, reserveTokens));
|
|
48
|
-
const trimmed = trimMessagesForBudget(messages, budget);
|
|
49
|
-
if (trimmed.dropped === 0)
|
|
50
|
-
return;
|
|
51
|
-
event.messages = [...trimmed.messages];
|
|
52
|
-
deps.log.warn("free-pi trimmed the compaction request to fit the learned window", {
|
|
53
|
-
sessionID: event.sessionID,
|
|
54
|
-
model: modelID,
|
|
55
|
-
window: ceiling,
|
|
56
|
-
droppedMessages: trimmed.dropped,
|
|
57
|
-
promptTokens: trimmed.tokens,
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* Collapses stale tool payloads before a request goes out. Long free-pi
|
|
62
|
-
* sessions reach 100k-170k token prompts, and at that size the free models
|
|
63
|
-
* lose the middle of the conversation even though the gateway accepts the
|
|
64
|
-
* request. User wording, assistant text and the newest messages are never
|
|
65
|
-
* touched; only old `read`/`grep`/`shell` results are shortened, with a note
|
|
66
|
-
* that says they were pruned.
|
|
67
|
-
*/
|
|
68
|
-
function applyContextDiet(deps, event) {
|
|
69
|
-
const providerID = event.model?.providerID;
|
|
70
|
-
const modelID = event.model?.id;
|
|
71
|
-
if (typeof providerID !== "string" || typeof modelID !== "string")
|
|
72
|
-
return;
|
|
73
|
-
const context = deps.state.contextLimits.get(`${providerID}/${modelID}`);
|
|
74
|
-
if (!context || context <= CONTEXT_DIET_MIN_TOKENS)
|
|
75
|
-
return;
|
|
76
|
-
const budget = Math.max(CONTEXT_DIET_MIN_TOKENS, Math.floor(context * CONTEXT_DIET_SHARE));
|
|
77
|
-
if (budget >= context)
|
|
78
|
-
return;
|
|
79
|
-
const messages = event.messages;
|
|
80
|
-
if (!Array.isArray(messages) || messages.length === 0)
|
|
81
|
-
return;
|
|
82
|
-
const result = pruneStaleToolResults(messages, budget, estimateMessageTokens);
|
|
83
|
-
if (result.pruned === 0)
|
|
84
|
-
return;
|
|
85
|
-
event.messages = [...result.messages];
|
|
86
|
-
deps.log.info("free-pi pruned stale tool results so the prompt stays attended", {
|
|
87
|
-
sessionID: event.sessionID,
|
|
88
|
-
model: modelID,
|
|
89
|
-
context,
|
|
90
|
-
budget,
|
|
91
|
-
pruned: result.pruned,
|
|
92
|
-
tokensBefore: result.tokensBefore,
|
|
93
|
-
tokensAfter: result.tokensAfter,
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
/**
|
|
97
|
-
* Drops the reasoning OpenCode stores and echoes back inside assistant
|
|
98
|
-
* messages.
|
|
99
|
-
*
|
|
100
|
-
* The provider request carries it as `reasoning_content`, but it is not input:
|
|
101
|
-
* the gateway billed it on some models (a measured glm-5.3-flash request went
|
|
102
|
-
* from 27 to 188 prompt tokens with the same answer) and the token estimate used
|
|
103
|
-
* for diet/compaction assumes it is not sent. Removing it keeps the request
|
|
104
|
-
* identical in behavior and smaller in credits.
|
|
105
|
-
*/
|
|
106
|
-
function stripAssistantReasoning(deps, event) {
|
|
107
|
-
const messages = event.messages;
|
|
108
|
-
if (!Array.isArray(messages) || messages.length === 0)
|
|
109
|
-
return;
|
|
110
|
-
let chars = 0;
|
|
111
|
-
let changed = false;
|
|
112
|
-
const next = messages.map((message) => {
|
|
113
|
-
if (!message || message.role !== "assistant")
|
|
114
|
-
return message;
|
|
115
|
-
let copy;
|
|
116
|
-
const ensureCopy = () => {
|
|
117
|
-
if (!copy)
|
|
118
|
-
copy = { ...message };
|
|
119
|
-
return copy;
|
|
120
|
-
};
|
|
121
|
-
for (const key of ["reasoning_content", "reasoning"]) {
|
|
122
|
-
if (!(key in message))
|
|
123
|
-
continue;
|
|
124
|
-
const value = message[key];
|
|
125
|
-
if (typeof value === "string")
|
|
126
|
-
chars += value.length;
|
|
127
|
-
ensureCopy();
|
|
128
|
-
delete copy[key];
|
|
129
|
-
changed = true;
|
|
130
|
-
}
|
|
131
|
-
if (Array.isArray(message.content)) {
|
|
132
|
-
const kept = message.content.filter((part) => part?.type !== "reasoning" && part?.type !== "thinking");
|
|
133
|
-
if (kept.length !== message.content.length) {
|
|
134
|
-
ensureCopy();
|
|
135
|
-
copy.content = kept;
|
|
136
|
-
changed = true;
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
return copy ?? message;
|
|
140
|
-
});
|
|
141
|
-
if (!changed)
|
|
142
|
-
return;
|
|
143
|
-
event.messages = next;
|
|
144
|
-
if (chars > 0) {
|
|
145
|
-
deps.log.info("free-pi dropped stored reasoning from the request", {
|
|
146
|
-
sessionID: event.sessionID,
|
|
147
|
-
chars,
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
31
|
/** Caps output tokens, applies the efficiency rule and derives the ad turn. */
|
|
152
32
|
async function applyGeneration(deps, event, kind) {
|
|
153
33
|
if (!isFreePiProvider(event.model?.providerID))
|
|
@@ -160,39 +40,21 @@ async function applyGeneration(deps, event, kind) {
|
|
|
160
40
|
event.result = localTitle(event.messages);
|
|
161
41
|
return;
|
|
162
42
|
}
|
|
163
|
-
|
|
43
|
+
// The title agent gets a local answer, so no free-pi request is made.
|
|
164
44
|
const modelID = event.model?.id;
|
|
165
45
|
// Remember the choice so a `model_requires_credits` failure can hide exactly
|
|
166
46
|
// the model that was rejected instead of the whole provider.
|
|
167
47
|
if (typeof event.sessionID === "string" && typeof modelID === "string") {
|
|
168
48
|
deps.state.lastModelBySession.set(event.sessionID, `${event.model.providerID}/${modelID}`);
|
|
169
49
|
}
|
|
170
|
-
|
|
171
|
-
//
|
|
172
|
-
//
|
|
173
|
-
//
|
|
174
|
-
//
|
|
175
|
-
const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING);
|
|
176
|
-
if (event.options && kind !== "compaction") {
|
|
177
|
-
const current = event.options.maxTokens;
|
|
178
|
-
if (current === undefined || current > cap)
|
|
179
|
-
event.options.maxTokens = cap;
|
|
180
|
-
}
|
|
50
|
+
// Compaction is OpenCode's own: it decides when to summarize and what to
|
|
51
|
+
// keep, and the plugin does not measure, trim or rewrite the history. The
|
|
52
|
+
// only thing done here is rotating the wire session id for the request that
|
|
53
|
+
// follows, because the compaction request and the next turn overlap and the
|
|
54
|
+
// gateway holds one request slot per wire session.
|
|
181
55
|
if (kind === "compaction") {
|
|
182
|
-
fitCompactionMessages(deps, event);
|
|
183
|
-
// OpenCode sends the messages it is folding into the summary, which is the
|
|
184
|
-
// same set pi reports through `session_before_compact`.
|
|
185
|
-
recordCompaction(deps, event.sessionID, Array.isArray(event.messages) ? event.messages.length : 0);
|
|
186
|
-
// The compaction request and the next turn overlap: the runner starts the
|
|
187
|
-
// next step while the gateway still holds this wire session's request slot,
|
|
188
|
-
// which costs a `429 concurrent` and a full replay every time. Rotating the
|
|
189
|
-
// id for the next request avoids that round trip without changing what the
|
|
190
|
-
// model receives (the whole compacted history goes out every time).
|
|
191
56
|
markWireSessionDirty(deps, event.sessionID);
|
|
192
57
|
}
|
|
193
|
-
else {
|
|
194
|
-
applyContextDiet(deps, event);
|
|
195
|
-
}
|
|
196
58
|
const agent = event.agent;
|
|
197
59
|
const turn = await resolveAdTurn(deps, {
|
|
198
60
|
sessionID: event.sessionID,
|
|
@@ -241,7 +103,7 @@ async function applyModelRequest(deps, event) {
|
|
|
241
103
|
// an impression the user never sees.
|
|
242
104
|
if (event.kind === "title")
|
|
243
105
|
return;
|
|
244
|
-
Object.assign(event.headers, toolHeaders(deps, event.sessionID
|
|
106
|
+
Object.assign(event.headers, toolHeaders(deps, event.sessionID));
|
|
245
107
|
const pending = deps.state.pendingAdTurns.get(pendingKeyOf(event.sessionID, agent, event.kind));
|
|
246
108
|
const turn = pending ??
|
|
247
109
|
(await resolveAdTurn(deps, {
|
|
@@ -322,6 +184,22 @@ function isTransportFailure(error) {
|
|
|
322
184
|
const message = `${error?.message ?? ""}\n${error?.cause?.message ?? ""}`;
|
|
323
185
|
return TRANSPORT_RETRY_PATTERN.test(message);
|
|
324
186
|
}
|
|
187
|
+
/**
|
|
188
|
+
* A 5xx the gateway itself returned: the request was valid but the server had
|
|
189
|
+
* a bad moment. Measured live: image input on every free model answered 503
|
|
190
|
+
* `image_screen_unavailable` for minutes at a stretch. Retrying is the only
|
|
191
|
+
* useful response, and the wire id rotates because the failed attempt may
|
|
192
|
+
* have left the session slot marked busy.
|
|
193
|
+
*/
|
|
194
|
+
function isServerFailure(error) {
|
|
195
|
+
const status = error?.response?.status ??
|
|
196
|
+
(typeof error?.status === "number" ? error.status : undefined);
|
|
197
|
+
if (typeof status === "number" && status >= 500 && status <= 599) {
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
const message = typeof error?.message === "string" ? error.message : "";
|
|
201
|
+
return /server error|temporarily unavailable|try again later|image_screen_unavailable/i.test(message);
|
|
202
|
+
}
|
|
325
203
|
function isTerminalFailure(error) {
|
|
326
204
|
if (error?.type === "aborted" ||
|
|
327
205
|
/aborted|cancelled|canceled|interrupted|AbortError/i.test(`${error?.message ?? ""}`)) {
|
|
@@ -394,6 +272,30 @@ function applyRetryPolicy(deps, event) {
|
|
|
394
272
|
});
|
|
395
273
|
return;
|
|
396
274
|
}
|
|
275
|
+
// A 5xx from the gateway (`image_screen_unavailable` was measured live as a
|
|
276
|
+
// 503) is the server having a bad moment, not the request being wrong. The
|
|
277
|
+
// default retry would stop after three attempts even though the outage
|
|
278
|
+
// usually clears in seconds, so treat it like a transport failure: rotate
|
|
279
|
+
// the wire id and keep trying within the transport budget.
|
|
280
|
+
if (isServerFailure(event.error)) {
|
|
281
|
+
if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
|
|
282
|
+
event.decision = { retry: false };
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
markWireSessionDirty(deps, event.sessionID);
|
|
286
|
+
const attempt = Math.max(1, event.attempt - 1);
|
|
287
|
+
event.decision = {
|
|
288
|
+
retry: true,
|
|
289
|
+
delay: Math.min(TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1), TRANSPORT_RETRY_MAX_DELAY_MS),
|
|
290
|
+
};
|
|
291
|
+
deps.log.warn("free-pi returned a server error; retrying", {
|
|
292
|
+
sessionID: event.sessionID,
|
|
293
|
+
attempt: event.attempt,
|
|
294
|
+
delay: event.decision.delay,
|
|
295
|
+
error: typeof event.error?.message === "string" ? event.error.message : undefined,
|
|
296
|
+
});
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
397
299
|
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
398
300
|
event.decision = { retry: false };
|
|
399
301
|
return;
|
|
@@ -526,6 +428,69 @@ async function hookForProviders(ctx, name, callback, registrations) {
|
|
|
526
428
|
}));
|
|
527
429
|
}
|
|
528
430
|
}
|
|
431
|
+
/**
|
|
432
|
+
* Handles every free-pi HTTP response: replays a busy session, rewrites
|
|
433
|
+
* context overflows into something OpenCode compacts on, turns long-lived
|
|
434
|
+
* limits into readable messages and watches for server notices.
|
|
435
|
+
*
|
|
436
|
+
* Split from `registerSessionHooks` because the response path is the plugin's
|
|
437
|
+
* most intricate logic and it was buried mid-function.
|
|
438
|
+
*/
|
|
439
|
+
async function handleProviderResponse(ctx, deps, event) {
|
|
440
|
+
const response = event.response;
|
|
441
|
+
// Context overflow has to be handled first: a 429 context ceiling must
|
|
442
|
+
// become a 400 overflow, not a friendly long-lived limit.
|
|
443
|
+
const overflow = await rewriteContextOverflowResponse(response).catch(() => undefined);
|
|
444
|
+
if (overflow) {
|
|
445
|
+
const code = overflow.headers.get("x-free-pi-original-code") ?? "context_overflow";
|
|
446
|
+
// A gateway failure can report "too long" for a request that fits the
|
|
447
|
+
// model's window; compacting then loops (summarize, retry, rejected
|
|
448
|
+
// again). The plugin never re-sends the request itself: it only
|
|
449
|
+
// classifies the failure.
|
|
450
|
+
const body = await storedBody(deps, event).catch(() => undefined);
|
|
451
|
+
const profile = body ? profileRequest(body) : undefined;
|
|
452
|
+
const tokens = profile?.tokens;
|
|
453
|
+
const limits = currentLiveLimits();
|
|
454
|
+
const window = (profile?.model
|
|
455
|
+
? limits?.models[profile.model]?.maxPromptTokens
|
|
456
|
+
: undefined) ??
|
|
457
|
+
limits?.window?.tokens ??
|
|
458
|
+
CONTEXT_WINDOW;
|
|
459
|
+
// A rejection is real when the request is at least as large as the window
|
|
460
|
+
// the gateway has already accepted for this model; anything meaningfully
|
|
461
|
+
// smaller is a provider failure, not an overflow.
|
|
462
|
+
const fitsWindow = typeof tokens === "number" &&
|
|
463
|
+
tokens < window * SPURIOUS_OVERFLOW_SHARE;
|
|
464
|
+
if (typeof tokens === "number" &&
|
|
465
|
+
!fitsWindow &&
|
|
466
|
+
profile?.model &&
|
|
467
|
+
profile.hasMedia !== true) {
|
|
468
|
+
// A rejection of a real prompt is the only free measurement of the
|
|
469
|
+
// gateway's ceiling. Attachments inflate the estimate and say nothing
|
|
470
|
+
// about the text window, so they are not learned from.
|
|
471
|
+
const learned = noteRejectedPrompt(deps, profile.model, tokens);
|
|
472
|
+
// Re-run the provider transform so this session's next compaction
|
|
473
|
+
// already targets the smaller window; no restart needed.
|
|
474
|
+
if (learned) {
|
|
475
|
+
void ctx.provider.reload().catch(() => undefined);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
else if (fitsWindow) {
|
|
479
|
+
const count = noteSpuriousOverflow(deps, event.sessionID);
|
|
480
|
+
deps.log.info("free-pi rejected a request as too long that fits the model window", { sessionID: event.sessionID, code, tokens, window, rejections: count });
|
|
481
|
+
if (overflowingSpuriously(deps, event.sessionID)) {
|
|
482
|
+
markWireSessionDirty(deps, event.sessionID);
|
|
483
|
+
deps.log.warn("compact loop stopped: free-pi keeps rejecting a request that fits", { sessionID: event.sessionID, code, tokens, window });
|
|
484
|
+
event.response = watchFreePiNotice(deps, spuriousOverflowResponse(overflow));
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
event.response = watchFreePiNotice(deps, overflow);
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
const rewritten = await rewriteLimitResponse(response).catch(() => undefined);
|
|
492
|
+
event.response = watchFreePiNotice(deps, rewritten ?? response);
|
|
493
|
+
}
|
|
529
494
|
export async function registerSessionHooks(ctx, deps) {
|
|
530
495
|
const registrations = [];
|
|
531
496
|
const generation = (kind) => (event) => applyGeneration(deps, event, kind);
|
|
@@ -553,61 +518,7 @@ export async function registerSessionHooks(ctx, deps) {
|
|
|
553
518
|
})));
|
|
554
519
|
await hookForProviders(ctx, "model.request", (event) => applyModelRequest(deps, event), registrations);
|
|
555
520
|
await hookForProviders(ctx, "http.request", (event) => rememberReplayBody(deps, event), registrations);
|
|
556
|
-
await hookForProviders(ctx, "http.response",
|
|
557
|
-
// Recover a per-session `429 concurrent` before OpenCode sees it: the
|
|
558
|
-
// step's prepared request is reused on retry, so rotating the id in the
|
|
559
|
-
// retry hook is too late for the failed attempt.
|
|
560
|
-
const replayed = await replayConcurrentResponse(deps, event).catch(() => undefined);
|
|
561
|
-
const response = replayed ?? event.response;
|
|
562
|
-
// Context overflow has to be handled first: a 429 context ceiling must
|
|
563
|
-
// become a 400 overflow, not a friendly long-lived limit.
|
|
564
|
-
const overflow = await rewriteContextOverflowResponse(response).catch(() => undefined);
|
|
565
|
-
if (overflow) {
|
|
566
|
-
const code = overflow.headers.get("x-free-pi-original-code") ?? "context_overflow";
|
|
567
|
-
// A gateway failure can report "too long" for a request that fits the
|
|
568
|
-
// window. Compacting then loops, so retry on a fresh wire session
|
|
569
|
-
// first, and stop compacting once the session has seen a few.
|
|
570
|
-
const reviewed = await replaySpuriousOverflow(deps, event).catch(() => ({}));
|
|
571
|
-
// A rejection of a real prompt is the only free measurement of the
|
|
572
|
-
// gateway's ceiling. Attachments inflate the estimate and say nothing
|
|
573
|
-
// about the text window, so they are not learned from.
|
|
574
|
-
if (reviewed.spurious === false &&
|
|
575
|
-
typeof reviewed.tokens === "number" &&
|
|
576
|
-
reviewed.model &&
|
|
577
|
-
reviewed.hasMedia !== true) {
|
|
578
|
-
const learned = noteRejectedPrompt(deps, reviewed.model, reviewed.tokens);
|
|
579
|
-
// Re-run the provider transform so this session's next compaction
|
|
580
|
-
// already targets the smaller window; no restart needed.
|
|
581
|
-
if (learned) {
|
|
582
|
-
void ctx.provider.reload().catch(() => undefined);
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
if (reviewed.response) {
|
|
586
|
-
clearSpuriousOverflows(deps, event.sessionID);
|
|
587
|
-
event.response = watchFreePiNotice(deps, reviewed.response);
|
|
588
|
-
return;
|
|
589
|
-
}
|
|
590
|
-
if (reviewed.spurious) {
|
|
591
|
-
const count = noteSpuriousOverflow(deps, event.sessionID);
|
|
592
|
-
deps.log.info("free-pi rejected a request as too long that fits the model window", {
|
|
593
|
-
sessionID: event.sessionID,
|
|
594
|
-
code,
|
|
595
|
-
tokens: reviewed.tokens,
|
|
596
|
-
rejections: count,
|
|
597
|
-
});
|
|
598
|
-
if (overflowingSpuriously(deps, event.sessionID)) {
|
|
599
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
600
|
-
deps.log.warn("compact loop stopped: free-pi keeps rejecting a request that fits", { sessionID: event.sessionID, code, tokens: reviewed.tokens });
|
|
601
|
-
event.response = watchFreePiNotice(deps, spuriousOverflowResponse(overflow));
|
|
602
|
-
return;
|
|
603
|
-
}
|
|
604
|
-
}
|
|
605
|
-
event.response = watchFreePiNotice(deps, overflow);
|
|
606
|
-
return;
|
|
607
|
-
}
|
|
608
|
-
const rewritten = await rewriteLimitResponse(response).catch(() => undefined);
|
|
609
|
-
event.response = watchFreePiNotice(deps, rewritten ?? response);
|
|
610
|
-
}, registrations);
|
|
521
|
+
await hookForProviders(ctx, "http.response", (event) => handleProviderResponse(ctx, deps, event), registrations);
|
|
611
522
|
await hookForProviders(ctx, "retry", (event) => applyRetryPolicy(deps, event), registrations);
|
|
612
523
|
await registerToolHooks(ctx, deps, registrations);
|
|
613
524
|
return registrations;
|
|
@@ -14,8 +14,13 @@
|
|
|
14
14
|
* compaction.
|
|
15
15
|
*/
|
|
16
16
|
import type { Deps } from "../deps.js";
|
|
17
|
-
/**
|
|
18
|
-
|
|
17
|
+
/**
|
|
18
|
+
* A request smaller than this share of the model's window cannot be a real
|
|
19
|
+
* overflow: the gateway has accepted prompts up to the window for that model,
|
|
20
|
+
* so a rejection well below it is a provider failure and compacting again
|
|
21
|
+
* cannot help.
|
|
22
|
+
*/
|
|
23
|
+
export declare const SPURIOUS_OVERFLOW_SHARE = 0.75;
|
|
19
24
|
export declare const SPURIOUS_OVERFLOW_MESSAGE: string;
|
|
20
25
|
export type RequestProfile = {
|
|
21
26
|
/** Approximate token count of the whole body. */
|
|
@@ -35,32 +40,6 @@ export type RequestProfile = {
|
|
|
35
40
|
* the model's text window, so callers must not learn a ceiling from it.
|
|
36
41
|
*/
|
|
37
42
|
export declare function profileRequest(body: string): RequestProfile;
|
|
38
|
-
/** Token count of a request body, without the extra facts. */
|
|
39
|
-
export declare function measureRequestTokens(body: string): number;
|
|
40
|
-
/**
|
|
41
|
-
* Cheap per-message estimate; the body is serialized once per message.
|
|
42
|
-
*
|
|
43
|
-
* Assistant reasoning is stored in the session but the provider lowering drops
|
|
44
|
-
* it before the request (`FREE_PI_TRACE` shows `reasoningChars: 0`). Counting it
|
|
45
|
-
* made the diet and the compaction trim believe a prompt was 30-50k tokens
|
|
46
|
-
* larger than the wire, so they pruned or dropped turns the model never saw.
|
|
47
|
-
*/
|
|
48
|
-
export declare function estimateMessageTokens(message: unknown): number;
|
|
49
|
-
/**
|
|
50
|
-
* Keeps the newest part of a message list inside `budget` tokens, cutting only
|
|
51
|
-
* at user turns so an assistant tool call never loses its results.
|
|
52
|
-
*
|
|
53
|
-
* OpenCode refuses to compact when the summarization request itself is still
|
|
54
|
-
* too large, and then the turn dies with nothing but the checkpoint shown. The
|
|
55
|
-
* gateway's real ceiling is lower than the advertised window, so the plugin
|
|
56
|
-
* trims the oldest turns it can spare before the summarizer is asked to read
|
|
57
|
-
* them.
|
|
58
|
-
*/
|
|
59
|
-
export declare function trimMessagesForBudget(messages: readonly unknown[], budget: number): {
|
|
60
|
-
readonly messages: readonly unknown[];
|
|
61
|
-
readonly dropped: number;
|
|
62
|
-
readonly tokens: number;
|
|
63
|
-
};
|
|
64
43
|
/**
|
|
65
44
|
* Records a rejection of a request that fits, and returns the number of them
|
|
66
45
|
* seen for the session inside the current window. A run of them means the
|
package/dist/session/overflow.js
CHANGED
|
@@ -13,8 +13,13 @@
|
|
|
13
13
|
* still fails, surfaces a provider error instead of asking for another
|
|
14
14
|
* compaction.
|
|
15
15
|
*/
|
|
16
|
-
/**
|
|
17
|
-
|
|
16
|
+
/**
|
|
17
|
+
* A request smaller than this share of the model's window cannot be a real
|
|
18
|
+
* overflow: the gateway has accepted prompts up to the window for that model,
|
|
19
|
+
* so a rejection well below it is a provider failure and compacting again
|
|
20
|
+
* cannot help.
|
|
21
|
+
*/
|
|
22
|
+
export const SPURIOUS_OVERFLOW_SHARE = 0.75;
|
|
18
23
|
/** Spurious rejections closer together than this belong to the same incident. */
|
|
19
24
|
const STORM_WINDOW_MS = 10 * 60_000;
|
|
20
25
|
/** Spurious rejections tolerated in a window before the error stops compacting. */
|
|
@@ -81,77 +86,6 @@ export function profileRequest(body) {
|
|
|
81
86
|
return { tokens: Math.ceil(body.length / 4), hasMedia: false };
|
|
82
87
|
}
|
|
83
88
|
}
|
|
84
|
-
/** Token count of a request body, without the extra facts. */
|
|
85
|
-
export function measureRequestTokens(body) {
|
|
86
|
-
return profileRequest(body).tokens;
|
|
87
|
-
}
|
|
88
|
-
/** Part types OpenCode keeps in the session but does not send to free-pi. */
|
|
89
|
-
const UNSENT_PART_TYPES = new Set(["reasoning", "thinking"]);
|
|
90
|
-
/**
|
|
91
|
-
* Cheap per-message estimate; the body is serialized once per message.
|
|
92
|
-
*
|
|
93
|
-
* Assistant reasoning is stored in the session but the provider lowering drops
|
|
94
|
-
* it before the request (`FREE_PI_TRACE` shows `reasoningChars: 0`). Counting it
|
|
95
|
-
* made the diet and the compaction trim believe a prompt was 30-50k tokens
|
|
96
|
-
* larger than the wire, so they pruned or dropped turns the model never saw.
|
|
97
|
-
*/
|
|
98
|
-
export function estimateMessageTokens(message) {
|
|
99
|
-
try {
|
|
100
|
-
const full = JSON.stringify(message).length;
|
|
101
|
-
const content = message?.content;
|
|
102
|
-
if (!Array.isArray(content))
|
|
103
|
-
return Math.ceil(full / 4);
|
|
104
|
-
let unsent = 0;
|
|
105
|
-
for (const part of content) {
|
|
106
|
-
if (UNSENT_PART_TYPES.has(part?.type ?? "")) {
|
|
107
|
-
unsent += JSON.stringify(part).length + 1;
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
return Math.ceil(Math.max(0, full - unsent) / 4);
|
|
111
|
-
}
|
|
112
|
-
catch {
|
|
113
|
-
return 0;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
/**
|
|
117
|
-
* Keeps the newest part of a message list inside `budget` tokens, cutting only
|
|
118
|
-
* at user turns so an assistant tool call never loses its results.
|
|
119
|
-
*
|
|
120
|
-
* OpenCode refuses to compact when the summarization request itself is still
|
|
121
|
-
* too large, and then the turn dies with nothing but the checkpoint shown. The
|
|
122
|
-
* gateway's real ceiling is lower than the advertised window, so the plugin
|
|
123
|
-
* trims the oldest turns it can spare before the summarizer is asked to read
|
|
124
|
-
* them.
|
|
125
|
-
*/
|
|
126
|
-
export function trimMessagesForBudget(messages, budget) {
|
|
127
|
-
if (messages.length === 0)
|
|
128
|
-
return { messages, dropped: 0, tokens: 0 };
|
|
129
|
-
const sizes = messages.map(estimateMessageTokens);
|
|
130
|
-
let total = 0;
|
|
131
|
-
for (const size of sizes)
|
|
132
|
-
total += size;
|
|
133
|
-
if (total <= budget)
|
|
134
|
-
return { messages, dropped: 0, tokens: total };
|
|
135
|
-
const cuts = [];
|
|
136
|
-
for (let index = 1; index < messages.length; index += 1) {
|
|
137
|
-
const role = messages[index]?.role;
|
|
138
|
-
if (role === "user")
|
|
139
|
-
cuts.push(index);
|
|
140
|
-
}
|
|
141
|
-
for (const cut of cuts) {
|
|
142
|
-
let tail = 0;
|
|
143
|
-
for (let index = cut; index < sizes.length; index += 1)
|
|
144
|
-
tail += sizes[index];
|
|
145
|
-
if (tail <= budget) {
|
|
146
|
-
return { messages: messages.slice(cut), dropped: cut, tokens: tail };
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
const last = cuts.length > 0 ? cuts[cuts.length - 1] : messages.length - 1;
|
|
150
|
-
let tail = 0;
|
|
151
|
-
for (let index = last; index < sizes.length; index += 1)
|
|
152
|
-
tail += sizes[index];
|
|
153
|
-
return { messages: messages.slice(last), dropped: last, tokens: tail };
|
|
154
|
-
}
|
|
155
89
|
/**
|
|
156
90
|
* Records a rejection of a request that fits, and returns the number of them
|
|
157
91
|
* seen for the session inside the current window. A run of them means the
|
package/dist/session/replay.d.ts
CHANGED
|
@@ -1,46 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
* `429 concurrent` limit.
|
|
2
|
+
* Keeps the outgoing request body around for diagnostics and overflow sizing.
|
|
4
3
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* also leave a session slot locked after an aborted stream, which resets do not
|
|
10
|
-
* clear.
|
|
11
|
-
*
|
|
12
|
-
* Replaying from `http.response` instead sends the same body with a fresh wire
|
|
13
|
-
* session id and returns the good response to OpenCode, so the turn continues
|
|
14
|
-
* without a visible "Retrying…" or a failed step.
|
|
4
|
+
* The plugin never re-sends a request on its own: doing that ran the same
|
|
5
|
+
* prompt (and its tool calls) twice for one user turn. Retries belong to
|
|
6
|
+
* OpenCode's runner, which only retries after a failed attempt, and the wire
|
|
7
|
+
* session id is rotated in the retry hook so that retry reaches a free slot.
|
|
15
8
|
*/
|
|
16
9
|
import type { Deps } from "../deps.js";
|
|
17
|
-
/** Keeps the body around so
|
|
10
|
+
/** Keeps the body around so an overflow can be sized after fetch consumed it. */
|
|
18
11
|
export declare function rememberReplayBody(deps: Deps, event: any): Promise<void>;
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
* `undefined` to leave the original response untouched.
|
|
22
|
-
*/
|
|
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
|
-
/** 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;
|
|
31
|
-
/** Whether the rejected request plainly fits the model window. */
|
|
32
|
-
readonly spurious?: boolean;
|
|
33
|
-
/** A good response from a fresh wire session, when the retry succeeded. */
|
|
34
|
-
readonly response?: Response;
|
|
35
|
-
};
|
|
36
|
-
/**
|
|
37
|
-
* Retries an overflow rejection whose request plainly fits the model window.
|
|
38
|
-
*
|
|
39
|
-
* free-pi reports `context_ceiling`/`context_too_long` from the upstream
|
|
40
|
-
* model, and a failing gateway can report them for a small prompt. Compacting
|
|
41
|
-
* cannot fix that: the summary is accepted, the next turn is rejected the same
|
|
42
|
-
* way, and the runner compacts again. A fresh wire session is the cheapest
|
|
43
|
-
* recovery, so a small request is replayed on one before the overflow is
|
|
44
|
-
* handed to the runner.
|
|
45
|
-
*/
|
|
46
|
-
export declare function replaySpuriousOverflow(deps: Deps, event: any): Promise<OverflowReplay>;
|
|
12
|
+
/** The request body, either remembered before the send or re-read from it. */
|
|
13
|
+
export declare function storedBody(deps: Deps, event: any): Promise<string | undefined>;
|