@eduardo191labs/opencode-free-pi 0.7.26 → 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 +4 -1
- package/dist/catalog/models.d.ts +1 -1
- package/dist/catalog/models.js +14 -3
- package/dist/constants.d.ts +15 -13
- package/dist/constants.js +15 -13
- 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 +0 -1
- package/package.json +2 -2
- package/src/catalog/live.ts +4 -1
- package/src/catalog/models.ts +20 -3
- package/src/constants.ts +16 -13
- 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 +0 -1
- package/dist/session/diet.d.ts +0 -23
- package/dist/session/diet.js +0 -176
- package/src/session/diet.ts +0 -201
package/src/session/hooks.ts
CHANGED
|
@@ -11,11 +11,8 @@ import {
|
|
|
11
11
|
CONCURRENT_RETRY_BASE_MS,
|
|
12
12
|
CONCURRENT_RETRY_MAX,
|
|
13
13
|
CONCURRENT_RETRY_MAX_DELAY_MS,
|
|
14
|
-
|
|
15
|
-
CONTEXT_DIET_SHARE,
|
|
14
|
+
CONTEXT_WINDOW,
|
|
16
15
|
DEFENSE_PROVIDER_ID,
|
|
17
|
-
MAX_OUTPUT_TOKENS,
|
|
18
|
-
MAX_OUTPUT_TOKENS_CEILING,
|
|
19
16
|
PROVIDER_ID,
|
|
20
17
|
RETRY_BASE_DELAY_MS,
|
|
21
18
|
RETRY_MAX_DELAY_MS,
|
|
@@ -25,11 +22,7 @@ import {
|
|
|
25
22
|
TRANSPORT_RETRY_MAX,
|
|
26
23
|
TRANSPORT_RETRY_MAX_DELAY_MS,
|
|
27
24
|
} from "../constants.js";
|
|
28
|
-
import {
|
|
29
|
-
currentLiveLimits,
|
|
30
|
-
learnedContextWindow,
|
|
31
|
-
noteRejectedPrompt,
|
|
32
|
-
} from "../catalog/live.js";
|
|
25
|
+
import { currentLiveLimits, noteRejectedPrompt } from "../catalog/live.js";
|
|
33
26
|
import type { Deps } from "../deps.js";
|
|
34
27
|
import { closeFreePiSession } from "../api/session.js";
|
|
35
28
|
import {
|
|
@@ -38,21 +31,15 @@ import {
|
|
|
38
31
|
} from "../errors/limit.js";
|
|
39
32
|
import { parseFreePiError } from "../errors/parse.js";
|
|
40
33
|
import { trimMap } from "../utils/async.js";
|
|
41
|
-
import { pruneStaleToolResults } from "./diet.js";
|
|
42
|
-
import { trimMessagesForBudget, estimateMessageTokens } from "./overflow.js";
|
|
43
34
|
import { watchFreePiNotice } from "./notices.js";
|
|
44
35
|
import {
|
|
45
|
-
clearSpuriousOverflows,
|
|
46
36
|
noteSpuriousOverflow,
|
|
47
37
|
overflowingSpuriously,
|
|
38
|
+
profileRequest,
|
|
39
|
+
SPURIOUS_OVERFLOW_SHARE,
|
|
48
40
|
spuriousOverflowResponse,
|
|
49
41
|
} from "./overflow.js";
|
|
50
|
-
import {
|
|
51
|
-
rememberReplayBody,
|
|
52
|
-
replayConcurrentResponse,
|
|
53
|
-
replaySpuriousOverflow,
|
|
54
|
-
type OverflowReplay,
|
|
55
|
-
} from "./replay.js";
|
|
42
|
+
import { rememberReplayBody, storedBody } from "./replay.js";
|
|
56
43
|
import { localTitle } from "./title.js";
|
|
57
44
|
import { rememberFreePiSession } from "./track.js";
|
|
58
45
|
import {
|
|
@@ -65,7 +52,6 @@ import {
|
|
|
65
52
|
import {
|
|
66
53
|
FREE_PI_TOOL_NAMES,
|
|
67
54
|
isFreePiSession,
|
|
68
|
-
recordCompaction,
|
|
69
55
|
recordToolEnd,
|
|
70
56
|
recordToolStart,
|
|
71
57
|
toolHeaders,
|
|
@@ -104,131 +90,6 @@ function rememberPending(deps: Deps, key: string, turn: AdTurn): void {
|
|
|
104
90
|
deps.state.pendingAdTurns.set(key, turn);
|
|
105
91
|
}
|
|
106
92
|
|
|
107
|
-
/**
|
|
108
|
-
* Fits the compaction request inside the ceiling the gateway has already
|
|
109
|
-
* proven. OpenCode aborts the turn ("the compaction request cannot be reduced
|
|
110
|
-
* further") when the summarizer request is rejected too, so the plugin drops
|
|
111
|
-
* the oldest user turns before that can happen.
|
|
112
|
-
*/
|
|
113
|
-
function fitCompactionMessages(
|
|
114
|
-
deps: Deps,
|
|
115
|
-
event: any,
|
|
116
|
-
reserveTokens = 0,
|
|
117
|
-
): void {
|
|
118
|
-
const modelID = typeof event.model?.id === "string" ? event.model.id : "";
|
|
119
|
-
const ceiling = learnedContextWindow(currentLiveLimits(), modelID);
|
|
120
|
-
if (!ceiling) return;
|
|
121
|
-
const messages = event.messages;
|
|
122
|
-
if (!Array.isArray(messages) || messages.length === 0) return;
|
|
123
|
-
const budget = Math.max(
|
|
124
|
-
1_000,
|
|
125
|
-
Math.floor(ceiling * 0.9) - Math.max(0, reserveTokens),
|
|
126
|
-
);
|
|
127
|
-
const trimmed = trimMessagesForBudget(messages, budget);
|
|
128
|
-
if (trimmed.dropped === 0) return;
|
|
129
|
-
event.messages = [...trimmed.messages];
|
|
130
|
-
deps.log.warn(
|
|
131
|
-
"free-pi trimmed the compaction request to fit the learned window",
|
|
132
|
-
{
|
|
133
|
-
sessionID: event.sessionID,
|
|
134
|
-
model: modelID,
|
|
135
|
-
window: ceiling,
|
|
136
|
-
droppedMessages: trimmed.dropped,
|
|
137
|
-
promptTokens: trimmed.tokens,
|
|
138
|
-
},
|
|
139
|
-
);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* Collapses stale tool payloads before a request goes out. Long free-pi
|
|
144
|
-
* sessions reach 100k-170k token prompts, and at that size the free models
|
|
145
|
-
* lose the middle of the conversation even though the gateway accepts the
|
|
146
|
-
* request. User wording, assistant text and the newest messages are never
|
|
147
|
-
* touched; only old `read`/`grep`/`shell` results are shortened, with a note
|
|
148
|
-
* that says they were pruned.
|
|
149
|
-
*/
|
|
150
|
-
function applyContextDiet(deps: Deps, event: any): void {
|
|
151
|
-
const providerID = event.model?.providerID;
|
|
152
|
-
const modelID = event.model?.id;
|
|
153
|
-
if (typeof providerID !== "string" || typeof modelID !== "string") return;
|
|
154
|
-
const context = deps.state.contextLimits.get(`${providerID}/${modelID}`);
|
|
155
|
-
if (!context || context <= CONTEXT_DIET_MIN_TOKENS) return;
|
|
156
|
-
const budget = Math.max(
|
|
157
|
-
CONTEXT_DIET_MIN_TOKENS,
|
|
158
|
-
Math.floor(context * CONTEXT_DIET_SHARE),
|
|
159
|
-
);
|
|
160
|
-
if (budget >= context) return;
|
|
161
|
-
const messages = event.messages;
|
|
162
|
-
if (!Array.isArray(messages) || messages.length === 0) return;
|
|
163
|
-
const result = pruneStaleToolResults(messages, budget, estimateMessageTokens);
|
|
164
|
-
if (result.pruned === 0) return;
|
|
165
|
-
event.messages = [...result.messages];
|
|
166
|
-
deps.log.info(
|
|
167
|
-
"free-pi pruned stale tool results so the prompt stays attended",
|
|
168
|
-
{
|
|
169
|
-
sessionID: event.sessionID,
|
|
170
|
-
model: modelID,
|
|
171
|
-
context,
|
|
172
|
-
budget,
|
|
173
|
-
pruned: result.pruned,
|
|
174
|
-
tokensBefore: result.tokensBefore,
|
|
175
|
-
tokensAfter: result.tokensAfter,
|
|
176
|
-
},
|
|
177
|
-
);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Drops the reasoning OpenCode stores and echoes back inside assistant
|
|
182
|
-
* messages.
|
|
183
|
-
*
|
|
184
|
-
* The provider request carries it as `reasoning_content`, but it is not input:
|
|
185
|
-
* the gateway billed it on some models (a measured glm-5.3-flash request went
|
|
186
|
-
* from 27 to 188 prompt tokens with the same answer) and the token estimate used
|
|
187
|
-
* for diet/compaction assumes it is not sent. Removing it keeps the request
|
|
188
|
-
* identical in behavior and smaller in credits.
|
|
189
|
-
*/
|
|
190
|
-
function stripAssistantReasoning(deps: Deps, event: any): void {
|
|
191
|
-
const messages = event.messages;
|
|
192
|
-
if (!Array.isArray(messages) || messages.length === 0) return;
|
|
193
|
-
let chars = 0;
|
|
194
|
-
let changed = false;
|
|
195
|
-
const next = messages.map((message: any) => {
|
|
196
|
-
if (!message || message.role !== "assistant") return message;
|
|
197
|
-
let copy: any | undefined;
|
|
198
|
-
const ensureCopy = () => {
|
|
199
|
-
if (!copy) copy = { ...message };
|
|
200
|
-
return copy;
|
|
201
|
-
};
|
|
202
|
-
for (const key of ["reasoning_content", "reasoning"] as const) {
|
|
203
|
-
if (!(key in message)) continue;
|
|
204
|
-
const value = message[key];
|
|
205
|
-
if (typeof value === "string") chars += value.length;
|
|
206
|
-
ensureCopy();
|
|
207
|
-
delete copy[key];
|
|
208
|
-
changed = true;
|
|
209
|
-
}
|
|
210
|
-
if (Array.isArray(message.content)) {
|
|
211
|
-
const kept = message.content.filter(
|
|
212
|
-
(part: any) => part?.type !== "reasoning" && part?.type !== "thinking",
|
|
213
|
-
);
|
|
214
|
-
if (kept.length !== message.content.length) {
|
|
215
|
-
ensureCopy();
|
|
216
|
-
copy.content = kept;
|
|
217
|
-
changed = true;
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
return copy ?? message;
|
|
221
|
-
});
|
|
222
|
-
if (!changed) return;
|
|
223
|
-
event.messages = next;
|
|
224
|
-
if (chars > 0) {
|
|
225
|
-
deps.log.info("free-pi dropped stored reasoning from the request", {
|
|
226
|
-
sessionID: event.sessionID,
|
|
227
|
-
chars,
|
|
228
|
-
});
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
|
|
232
93
|
/** Caps output tokens, applies the efficiency rule and derives the ad turn. */
|
|
233
94
|
async function applyGeneration(
|
|
234
95
|
deps: Deps,
|
|
@@ -246,7 +107,7 @@ async function applyGeneration(
|
|
|
246
107
|
return;
|
|
247
108
|
}
|
|
248
109
|
|
|
249
|
-
|
|
110
|
+
// The title agent gets a local answer, so no free-pi request is made.
|
|
250
111
|
|
|
251
112
|
const modelID = event.model?.id;
|
|
252
113
|
// Remember the choice so a `model_requires_credits` failure can hide exactly
|
|
@@ -257,36 +118,14 @@ async function applyGeneration(
|
|
|
257
118
|
`${event.model.providerID}/${modelID}`,
|
|
258
119
|
);
|
|
259
120
|
}
|
|
260
|
-
const limit = deps.state.outputLimits.get(
|
|
261
|
-
`${event.model.providerID}/${modelID}`,
|
|
262
|
-
);
|
|
263
|
-
// The compaction summary is the one response that must never be cut: a
|
|
264
|
-
// summary that reaches the output limit fails the whole compaction and the
|
|
265
|
-
// turn stops with nothing but the checkpoint. Leave OpenCode's own budget
|
|
266
|
-
// for it and only cap the answers the user reads.
|
|
267
|
-
const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING);
|
|
268
|
-
if (event.options && kind !== "compaction") {
|
|
269
|
-
const current = event.options.maxTokens;
|
|
270
|
-
if (current === undefined || current > cap) event.options.maxTokens = cap;
|
|
271
|
-
}
|
|
272
121
|
|
|
122
|
+
// Compaction is OpenCode's own: it decides when to summarize and what to
|
|
123
|
+
// keep, and the plugin does not measure, trim or rewrite the history. The
|
|
124
|
+
// only thing done here is rotating the wire session id for the request that
|
|
125
|
+
// follows, because the compaction request and the next turn overlap and the
|
|
126
|
+
// gateway holds one request slot per wire session.
|
|
273
127
|
if (kind === "compaction") {
|
|
274
|
-
fitCompactionMessages(deps, event);
|
|
275
|
-
// OpenCode sends the messages it is folding into the summary, which is the
|
|
276
|
-
// same set pi reports through `session_before_compact`.
|
|
277
|
-
recordCompaction(
|
|
278
|
-
deps,
|
|
279
|
-
event.sessionID,
|
|
280
|
-
Array.isArray(event.messages) ? event.messages.length : 0,
|
|
281
|
-
);
|
|
282
|
-
// The compaction request and the next turn overlap: the runner starts the
|
|
283
|
-
// next step while the gateway still holds this wire session's request slot,
|
|
284
|
-
// which costs a `429 concurrent` and a full replay every time. Rotating the
|
|
285
|
-
// id for the next request avoids that round trip without changing what the
|
|
286
|
-
// model receives (the whole compacted history goes out every time).
|
|
287
128
|
markWireSessionDirty(deps, event.sessionID);
|
|
288
|
-
} else {
|
|
289
|
-
applyContextDiet(deps, event);
|
|
290
129
|
}
|
|
291
130
|
|
|
292
131
|
const agent = event.agent;
|
|
@@ -342,7 +181,7 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
|
|
|
342
181
|
|
|
343
182
|
Object.assign(
|
|
344
183
|
event.headers,
|
|
345
|
-
toolHeaders(deps, event.sessionID
|
|
184
|
+
toolHeaders(deps, event.sessionID),
|
|
346
185
|
);
|
|
347
186
|
|
|
348
187
|
const pending = deps.state.pendingAdTurns.get(
|
|
@@ -439,6 +278,26 @@ function isTransportFailure(error: any): boolean {
|
|
|
439
278
|
return TRANSPORT_RETRY_PATTERN.test(message);
|
|
440
279
|
}
|
|
441
280
|
|
|
281
|
+
/**
|
|
282
|
+
* A 5xx the gateway itself returned: the request was valid but the server had
|
|
283
|
+
* a bad moment. Measured live: image input on every free model answered 503
|
|
284
|
+
* `image_screen_unavailable` for minutes at a stretch. Retrying is the only
|
|
285
|
+
* useful response, and the wire id rotates because the failed attempt may
|
|
286
|
+
* have left the session slot marked busy.
|
|
287
|
+
*/
|
|
288
|
+
function isServerFailure(error: any): boolean {
|
|
289
|
+
const status =
|
|
290
|
+
error?.response?.status ??
|
|
291
|
+
(typeof error?.status === "number" ? error.status : undefined);
|
|
292
|
+
if (typeof status === "number" && status >= 500 && status <= 599) {
|
|
293
|
+
return true;
|
|
294
|
+
}
|
|
295
|
+
const message = typeof error?.message === "string" ? error.message : "";
|
|
296
|
+
return /server error|temporarily unavailable|try again later|image_screen_unavailable/i.test(
|
|
297
|
+
message,
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
|
|
442
301
|
function isTerminalFailure(error: any): boolean {
|
|
443
302
|
if (
|
|
444
303
|
error?.type === "aborted" ||
|
|
@@ -522,6 +381,33 @@ function applyRetryPolicy(deps: Deps, event: any): void {
|
|
|
522
381
|
});
|
|
523
382
|
return;
|
|
524
383
|
}
|
|
384
|
+
// A 5xx from the gateway (`image_screen_unavailable` was measured live as a
|
|
385
|
+
// 503) is the server having a bad moment, not the request being wrong. The
|
|
386
|
+
// default retry would stop after three attempts even though the outage
|
|
387
|
+
// usually clears in seconds, so treat it like a transport failure: rotate
|
|
388
|
+
// the wire id and keep trying within the transport budget.
|
|
389
|
+
if (isServerFailure(event.error)) {
|
|
390
|
+
if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
|
|
391
|
+
event.decision = { retry: false };
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
markWireSessionDirty(deps, event.sessionID);
|
|
395
|
+
const attempt = Math.max(1, event.attempt - 1);
|
|
396
|
+
event.decision = {
|
|
397
|
+
retry: true,
|
|
398
|
+
delay: Math.min(
|
|
399
|
+
TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1),
|
|
400
|
+
TRANSPORT_RETRY_MAX_DELAY_MS,
|
|
401
|
+
),
|
|
402
|
+
};
|
|
403
|
+
deps.log.warn("free-pi returned a server error; retrying", {
|
|
404
|
+
sessionID: event.sessionID,
|
|
405
|
+
attempt: event.attempt,
|
|
406
|
+
delay: event.decision.delay,
|
|
407
|
+
error: typeof event.error?.message === "string" ? event.error.message : undefined,
|
|
408
|
+
});
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
525
411
|
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
526
412
|
event.decision = { retry: false };
|
|
527
413
|
return;
|
|
@@ -661,6 +547,95 @@ async function hookForProviders(
|
|
|
661
547
|
}
|
|
662
548
|
}
|
|
663
549
|
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Handles every free-pi HTTP response: replays a busy session, rewrites
|
|
553
|
+
* context overflows into something OpenCode compacts on, turns long-lived
|
|
554
|
+
* limits into readable messages and watches for server notices.
|
|
555
|
+
*
|
|
556
|
+
* Split from `registerSessionHooks` because the response path is the plugin's
|
|
557
|
+
* most intricate logic and it was buried mid-function.
|
|
558
|
+
*/
|
|
559
|
+
async function handleProviderResponse(
|
|
560
|
+
ctx: Plugin.Context,
|
|
561
|
+
deps: Deps,
|
|
562
|
+
event: any,
|
|
563
|
+
): Promise<void> {
|
|
564
|
+
const response = event.response;
|
|
565
|
+
// Context overflow has to be handled first: a 429 context ceiling must
|
|
566
|
+
// become a 400 overflow, not a friendly long-lived limit.
|
|
567
|
+
const overflow = await rewriteContextOverflowResponse(response).catch(
|
|
568
|
+
() => undefined,
|
|
569
|
+
);
|
|
570
|
+
if (overflow) {
|
|
571
|
+
const code =
|
|
572
|
+
overflow.headers.get("x-free-pi-original-code") ?? "context_overflow";
|
|
573
|
+
// A gateway failure can report "too long" for a request that fits the
|
|
574
|
+
// model's window; compacting then loops (summarize, retry, rejected
|
|
575
|
+
// again). The plugin never re-sends the request itself: it only
|
|
576
|
+
// classifies the failure.
|
|
577
|
+
const body = await storedBody(deps, event).catch(() => undefined);
|
|
578
|
+
const profile = body ? profileRequest(body) : undefined;
|
|
579
|
+
const tokens = profile?.tokens;
|
|
580
|
+
const limits = currentLiveLimits();
|
|
581
|
+
const window =
|
|
582
|
+
(profile?.model
|
|
583
|
+
? limits?.models[profile.model]?.maxPromptTokens
|
|
584
|
+
: undefined) ??
|
|
585
|
+
limits?.window?.tokens ??
|
|
586
|
+
CONTEXT_WINDOW;
|
|
587
|
+
// A rejection is real when the request is at least as large as the window
|
|
588
|
+
// the gateway has already accepted for this model; anything meaningfully
|
|
589
|
+
// smaller is a provider failure, not an overflow.
|
|
590
|
+
const fitsWindow =
|
|
591
|
+
typeof tokens === "number" &&
|
|
592
|
+
tokens < window * SPURIOUS_OVERFLOW_SHARE;
|
|
593
|
+
if (
|
|
594
|
+
typeof tokens === "number" &&
|
|
595
|
+
!fitsWindow &&
|
|
596
|
+
profile?.model &&
|
|
597
|
+
profile.hasMedia !== true
|
|
598
|
+
) {
|
|
599
|
+
// A rejection of a real prompt is the only free measurement of the
|
|
600
|
+
// gateway's ceiling. Attachments inflate the estimate and say nothing
|
|
601
|
+
// about the text window, so they are not learned from.
|
|
602
|
+
const learned = noteRejectedPrompt(deps, profile.model, tokens);
|
|
603
|
+
// Re-run the provider transform so this session's next compaction
|
|
604
|
+
// already targets the smaller window; no restart needed.
|
|
605
|
+
if (learned) {
|
|
606
|
+
void ctx.provider.reload().catch(() => undefined);
|
|
607
|
+
}
|
|
608
|
+
} else if (fitsWindow) {
|
|
609
|
+
const count = noteSpuriousOverflow(deps, event.sessionID);
|
|
610
|
+
deps.log.info(
|
|
611
|
+
"free-pi rejected a request as too long that fits the model window",
|
|
612
|
+
{ sessionID: event.sessionID, code, tokens, window, rejections: count },
|
|
613
|
+
);
|
|
614
|
+
if (overflowingSpuriously(deps, event.sessionID)) {
|
|
615
|
+
markWireSessionDirty(deps, event.sessionID);
|
|
616
|
+
deps.log.warn(
|
|
617
|
+
"compact loop stopped: free-pi keeps rejecting a request that fits",
|
|
618
|
+
{ sessionID: event.sessionID, code, tokens, window },
|
|
619
|
+
);
|
|
620
|
+
event.response = watchFreePiNotice(
|
|
621
|
+
deps,
|
|
622
|
+
spuriousOverflowResponse(overflow),
|
|
623
|
+
);
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
event.response = watchFreePiNotice(deps, overflow);
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
const rewritten = await rewriteLimitResponse(response).catch(
|
|
631
|
+
() => undefined,
|
|
632
|
+
);
|
|
633
|
+
event.response = watchFreePiNotice(
|
|
634
|
+
deps,
|
|
635
|
+
rewritten ?? response,
|
|
636
|
+
);
|
|
637
|
+
}
|
|
638
|
+
|
|
664
639
|
export async function registerSessionHooks(
|
|
665
640
|
ctx: Plugin.Context,
|
|
666
641
|
deps: Deps,
|
|
@@ -722,88 +697,7 @@ export async function registerSessionHooks(
|
|
|
722
697
|
await hookForProviders(
|
|
723
698
|
ctx,
|
|
724
699
|
"http.response",
|
|
725
|
-
|
|
726
|
-
// Recover a per-session `429 concurrent` before OpenCode sees it: the
|
|
727
|
-
// step's prepared request is reused on retry, so rotating the id in the
|
|
728
|
-
// retry hook is too late for the failed attempt.
|
|
729
|
-
const replayed = await replayConcurrentResponse(deps, event).catch(
|
|
730
|
-
() => undefined,
|
|
731
|
-
);
|
|
732
|
-
const response = replayed ?? event.response;
|
|
733
|
-
// Context overflow has to be handled first: a 429 context ceiling must
|
|
734
|
-
// become a 400 overflow, not a friendly long-lived limit.
|
|
735
|
-
const overflow = await rewriteContextOverflowResponse(response).catch(
|
|
736
|
-
() => undefined,
|
|
737
|
-
);
|
|
738
|
-
if (overflow) {
|
|
739
|
-
const code =
|
|
740
|
-
overflow.headers.get("x-free-pi-original-code") ?? "context_overflow";
|
|
741
|
-
// A gateway failure can report "too long" for a request that fits the
|
|
742
|
-
// window. Compacting then loops, so retry on a fresh wire session
|
|
743
|
-
// first, and stop compacting once the session has seen a few.
|
|
744
|
-
const reviewed = await replaySpuriousOverflow(deps, event).catch(
|
|
745
|
-
() => ({}) as OverflowReplay,
|
|
746
|
-
);
|
|
747
|
-
// A rejection of a real prompt is the only free measurement of the
|
|
748
|
-
// gateway's ceiling. Attachments inflate the estimate and say nothing
|
|
749
|
-
// about the text window, so they are not learned from.
|
|
750
|
-
if (
|
|
751
|
-
reviewed.spurious === false &&
|
|
752
|
-
typeof reviewed.tokens === "number" &&
|
|
753
|
-
reviewed.model &&
|
|
754
|
-
reviewed.hasMedia !== true
|
|
755
|
-
) {
|
|
756
|
-
const learned = noteRejectedPrompt(
|
|
757
|
-
deps,
|
|
758
|
-
reviewed.model,
|
|
759
|
-
reviewed.tokens,
|
|
760
|
-
);
|
|
761
|
-
// Re-run the provider transform so this session's next compaction
|
|
762
|
-
// already targets the smaller window; no restart needed.
|
|
763
|
-
if (learned) {
|
|
764
|
-
void ctx.provider.reload().catch(() => undefined);
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
if (reviewed.response) {
|
|
768
|
-
clearSpuriousOverflows(deps, event.sessionID);
|
|
769
|
-
event.response = watchFreePiNotice(deps, reviewed.response);
|
|
770
|
-
return;
|
|
771
|
-
}
|
|
772
|
-
if (reviewed.spurious) {
|
|
773
|
-
const count = noteSpuriousOverflow(deps, event.sessionID);
|
|
774
|
-
deps.log.info(
|
|
775
|
-
"free-pi rejected a request as too long that fits the model window",
|
|
776
|
-
{
|
|
777
|
-
sessionID: event.sessionID,
|
|
778
|
-
code,
|
|
779
|
-
tokens: reviewed.tokens,
|
|
780
|
-
rejections: count,
|
|
781
|
-
},
|
|
782
|
-
);
|
|
783
|
-
if (overflowingSpuriously(deps, event.sessionID)) {
|
|
784
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
785
|
-
deps.log.warn(
|
|
786
|
-
"compact loop stopped: free-pi keeps rejecting a request that fits",
|
|
787
|
-
{ sessionID: event.sessionID, code, tokens: reviewed.tokens },
|
|
788
|
-
);
|
|
789
|
-
event.response = watchFreePiNotice(
|
|
790
|
-
deps,
|
|
791
|
-
spuriousOverflowResponse(overflow),
|
|
792
|
-
);
|
|
793
|
-
return;
|
|
794
|
-
}
|
|
795
|
-
}
|
|
796
|
-
event.response = watchFreePiNotice(deps, overflow);
|
|
797
|
-
return;
|
|
798
|
-
}
|
|
799
|
-
const rewritten = await rewriteLimitResponse(response).catch(
|
|
800
|
-
() => undefined,
|
|
801
|
-
);
|
|
802
|
-
event.response = watchFreePiNotice(
|
|
803
|
-
deps,
|
|
804
|
-
rewritten ?? response,
|
|
805
|
-
);
|
|
806
|
-
},
|
|
700
|
+
(event: any) => handleProviderResponse(ctx, deps, event),
|
|
807
701
|
registrations,
|
|
808
702
|
);
|
|
809
703
|
await hookForProviders(
|
package/src/session/overflow.ts
CHANGED
|
@@ -16,8 +16,13 @@
|
|
|
16
16
|
|
|
17
17
|
import type { Deps } from "../deps.js";
|
|
18
18
|
|
|
19
|
-
/**
|
|
20
|
-
|
|
19
|
+
/**
|
|
20
|
+
* A request smaller than this share of the model's window cannot be a real
|
|
21
|
+
* overflow: the gateway has accepted prompts up to the window for that model,
|
|
22
|
+
* so a rejection well below it is a provider failure and compacting again
|
|
23
|
+
* cannot help.
|
|
24
|
+
*/
|
|
25
|
+
export const SPURIOUS_OVERFLOW_SHARE = 0.75;
|
|
21
26
|
|
|
22
27
|
/** Spurious rejections closer together than this belong to the same incident. */
|
|
23
28
|
const STORM_WINDOW_MS = 10 * 60_000;
|
|
@@ -101,81 +106,6 @@ export function profileRequest(body: string): RequestProfile {
|
|
|
101
106
|
}
|
|
102
107
|
}
|
|
103
108
|
|
|
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
|
-
/** Part types OpenCode keeps in the session but does not send to free-pi. */
|
|
110
|
-
const UNSENT_PART_TYPES = new Set(["reasoning", "thinking"]);
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* Cheap per-message estimate; the body is serialized once per message.
|
|
114
|
-
*
|
|
115
|
-
* Assistant reasoning is stored in the session but the provider lowering drops
|
|
116
|
-
* it before the request (`FREE_PI_TRACE` shows `reasoningChars: 0`). Counting it
|
|
117
|
-
* made the diet and the compaction trim believe a prompt was 30-50k tokens
|
|
118
|
-
* larger than the wire, so they pruned or dropped turns the model never saw.
|
|
119
|
-
*/
|
|
120
|
-
export function estimateMessageTokens(message: unknown): number {
|
|
121
|
-
try {
|
|
122
|
-
const full = JSON.stringify(message).length;
|
|
123
|
-
const content = (message as { content?: unknown } | null)?.content;
|
|
124
|
-
if (!Array.isArray(content)) return Math.ceil(full / 4);
|
|
125
|
-
let unsent = 0;
|
|
126
|
-
for (const part of content) {
|
|
127
|
-
if (UNSENT_PART_TYPES.has((part as { type?: string } | null)?.type ?? "")) {
|
|
128
|
-
unsent += JSON.stringify(part).length + 1;
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
return Math.ceil(Math.max(0, full - unsent) / 4);
|
|
132
|
-
} catch {
|
|
133
|
-
return 0;
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* Keeps the newest part of a message list inside `budget` tokens, cutting only
|
|
139
|
-
* at user turns so an assistant tool call never loses its results.
|
|
140
|
-
*
|
|
141
|
-
* OpenCode refuses to compact when the summarization request itself is still
|
|
142
|
-
* too large, and then the turn dies with nothing but the checkpoint shown. The
|
|
143
|
-
* gateway's real ceiling is lower than the advertised window, so the plugin
|
|
144
|
-
* trims the oldest turns it can spare before the summarizer is asked to read
|
|
145
|
-
* them.
|
|
146
|
-
*/
|
|
147
|
-
export function trimMessagesForBudget(
|
|
148
|
-
messages: readonly unknown[],
|
|
149
|
-
budget: number,
|
|
150
|
-
): {
|
|
151
|
-
readonly messages: readonly unknown[];
|
|
152
|
-
readonly dropped: number;
|
|
153
|
-
readonly tokens: number;
|
|
154
|
-
} {
|
|
155
|
-
if (messages.length === 0) return { messages, dropped: 0, tokens: 0 };
|
|
156
|
-
const sizes = messages.map(estimateMessageTokens);
|
|
157
|
-
let total = 0;
|
|
158
|
-
for (const size of sizes) total += size;
|
|
159
|
-
if (total <= budget) return { messages, dropped: 0, tokens: total };
|
|
160
|
-
|
|
161
|
-
const cuts: number[] = [];
|
|
162
|
-
for (let index = 1; index < messages.length; index += 1) {
|
|
163
|
-
const role = (messages[index] as { role?: unknown } | undefined)?.role;
|
|
164
|
-
if (role === "user") cuts.push(index);
|
|
165
|
-
}
|
|
166
|
-
for (const cut of cuts) {
|
|
167
|
-
let tail = 0;
|
|
168
|
-
for (let index = cut; index < sizes.length; index += 1) tail += sizes[index]!;
|
|
169
|
-
if (tail <= budget) {
|
|
170
|
-
return { messages: messages.slice(cut), dropped: cut, tokens: tail };
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
const last = cuts.length > 0 ? cuts[cuts.length - 1]! : messages.length - 1;
|
|
174
|
-
let tail = 0;
|
|
175
|
-
for (let index = last; index < sizes.length; index += 1) tail += sizes[index]!;
|
|
176
|
-
return { messages: messages.slice(last), dropped: last, tokens: tail };
|
|
177
|
-
}
|
|
178
|
-
|
|
179
109
|
/**
|
|
180
110
|
* Records a rejection of a request that fits, and returns the number of them
|
|
181
111
|
* seen for the session inside the current window. A run of them means the
|