@eduardo191labs/opencode-free-pi 0.7.26 → 0.7.29
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 +60 -105
- 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 -35
- package/dist/constants.js +15 -35
- package/dist/index.d.ts +1 -1
- package/dist/plugin.js +14 -46
- package/dist/session/events.js +5 -12
- package/dist/session/hooks.js +83 -348
- 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/session/track.d.ts +2 -0
- package/dist/session/track.js +5 -0
- package/dist/state.d.ts +1 -6
- 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 -38
- package/src/index.ts +0 -1
- package/src/plugin.ts +12 -52
- package/src/session/events.ts +5 -12
- package/src/session/hooks.ts +109 -431
- 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/session/track.ts +11 -0
- package/src/state.ts +0 -8
- 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/dist/session/title.d.ts +0 -18
- package/dist/session/title.js +0 -81
- package/dist/session/usage.d.ts +0 -5
- package/dist/session/usage.js +0 -32
- package/src/session/diet.ts +0 -201
- package/src/session/title.ts +0 -90
- package/src/session/usage.ts +0 -46
package/src/session/hooks.ts
CHANGED
|
@@ -8,28 +8,12 @@ import { resolveToken } from "../auth/token.js";
|
|
|
8
8
|
import {
|
|
9
9
|
AD_CONTEXT_HEADER,
|
|
10
10
|
AD_CONTEXT_OPT_OUT,
|
|
11
|
-
|
|
12
|
-
CONCURRENT_RETRY_MAX,
|
|
13
|
-
CONCURRENT_RETRY_MAX_DELAY_MS,
|
|
14
|
-
CONTEXT_DIET_MIN_TOKENS,
|
|
15
|
-
CONTEXT_DIET_SHARE,
|
|
11
|
+
CONTEXT_WINDOW,
|
|
16
12
|
DEFENSE_PROVIDER_ID,
|
|
17
|
-
MAX_OUTPUT_TOKENS,
|
|
18
|
-
MAX_OUTPUT_TOKENS_CEILING,
|
|
19
13
|
PROVIDER_ID,
|
|
20
|
-
RETRY_BASE_DELAY_MS,
|
|
21
|
-
RETRY_MAX_DELAY_MS,
|
|
22
|
-
RETRY_MAX_RETRIES,
|
|
23
14
|
SUBAGENT_HEADER,
|
|
24
|
-
TRANSPORT_RETRY_BASE_MS,
|
|
25
|
-
TRANSPORT_RETRY_MAX,
|
|
26
|
-
TRANSPORT_RETRY_MAX_DELAY_MS,
|
|
27
15
|
} from "../constants.js";
|
|
28
|
-
import {
|
|
29
|
-
currentLiveLimits,
|
|
30
|
-
learnedContextWindow,
|
|
31
|
-
noteRejectedPrompt,
|
|
32
|
-
} from "../catalog/live.js";
|
|
16
|
+
import { currentLiveLimits, noteRejectedPrompt } from "../catalog/live.js";
|
|
33
17
|
import type { Deps } from "../deps.js";
|
|
34
18
|
import { closeFreePiSession } from "../api/session.js";
|
|
35
19
|
import {
|
|
@@ -38,23 +22,16 @@ import {
|
|
|
38
22
|
} from "../errors/limit.js";
|
|
39
23
|
import { parseFreePiError } from "../errors/parse.js";
|
|
40
24
|
import { trimMap } from "../utils/async.js";
|
|
41
|
-
import { pruneStaleToolResults } from "./diet.js";
|
|
42
|
-
import { trimMessagesForBudget, estimateMessageTokens } from "./overflow.js";
|
|
43
25
|
import { watchFreePiNotice } from "./notices.js";
|
|
44
26
|
import {
|
|
45
|
-
clearSpuriousOverflows,
|
|
46
27
|
noteSpuriousOverflow,
|
|
47
28
|
overflowingSpuriously,
|
|
29
|
+
profileRequest,
|
|
30
|
+
SPURIOUS_OVERFLOW_SHARE,
|
|
48
31
|
spuriousOverflowResponse,
|
|
49
32
|
} from "./overflow.js";
|
|
50
|
-
import {
|
|
51
|
-
|
|
52
|
-
replayConcurrentResponse,
|
|
53
|
-
replaySpuriousOverflow,
|
|
54
|
-
type OverflowReplay,
|
|
55
|
-
} from "./replay.js";
|
|
56
|
-
import { localTitle } from "./title.js";
|
|
57
|
-
import { rememberFreePiSession } from "./track.js";
|
|
33
|
+
import { rememberReplayBody, storedBody } from "./replay.js";
|
|
34
|
+
import { rememberFreePiSession, rememberTrackedModel } from "./track.js";
|
|
58
35
|
import {
|
|
59
36
|
hydrateWireSessionID,
|
|
60
37
|
markWireSessionDirty,
|
|
@@ -65,19 +42,16 @@ import {
|
|
|
65
42
|
import {
|
|
66
43
|
FREE_PI_TOOL_NAMES,
|
|
67
44
|
isFreePiSession,
|
|
68
|
-
recordCompaction,
|
|
69
45
|
recordToolEnd,
|
|
70
46
|
recordToolStart,
|
|
71
47
|
toolHeaders,
|
|
72
48
|
} from "./tools.js";
|
|
73
|
-
import { rememberTrackedModel } from "./usage.js";
|
|
74
49
|
|
|
75
50
|
type Registration = { dispose: () => Promise<void> };
|
|
76
51
|
type SessionHookName =
|
|
77
52
|
| "context"
|
|
78
53
|
| "compaction"
|
|
79
54
|
| "generate"
|
|
80
|
-
| "title"
|
|
81
55
|
| "model.request"
|
|
82
56
|
| "http.request"
|
|
83
57
|
| "http.response"
|
|
@@ -104,131 +78,6 @@ function rememberPending(deps: Deps, key: string, turn: AdTurn): void {
|
|
|
104
78
|
deps.state.pendingAdTurns.set(key, turn);
|
|
105
79
|
}
|
|
106
80
|
|
|
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
81
|
/** Caps output tokens, applies the efficiency rule and derives the ad turn. */
|
|
233
82
|
async function applyGeneration(
|
|
234
83
|
deps: Deps,
|
|
@@ -238,16 +87,6 @@ async function applyGeneration(
|
|
|
238
87
|
if (!isFreePiProvider(event.model?.providerID)) return;
|
|
239
88
|
rememberFreePiSession(deps, event.sessionID);
|
|
240
89
|
|
|
241
|
-
// V1 disabled the title agent. OpenCode still asks for a title, so answer
|
|
242
|
-
// from the first user message: no free-pi request, no ad impression, and the
|
|
243
|
-
// session leaves the "New session" state immediately.
|
|
244
|
-
if (kind === "title") {
|
|
245
|
-
event.result = localTitle(event.messages);
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
stripAssistantReasoning(deps, event);
|
|
250
|
-
|
|
251
90
|
const modelID = event.model?.id;
|
|
252
91
|
// Remember the choice so a `model_requires_credits` failure can hide exactly
|
|
253
92
|
// the model that was rejected instead of the whole provider.
|
|
@@ -257,36 +96,14 @@ async function applyGeneration(
|
|
|
257
96
|
`${event.model.providerID}/${modelID}`,
|
|
258
97
|
);
|
|
259
98
|
}
|
|
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
99
|
|
|
100
|
+
// Compaction is OpenCode's own: it decides when to summarize and what to
|
|
101
|
+
// keep, and the plugin does not measure, trim or rewrite the history. The
|
|
102
|
+
// only thing done here is rotating the wire session id for the request that
|
|
103
|
+
// follows, because the compaction request and the next turn overlap and the
|
|
104
|
+
// gateway holds one request slot per wire session.
|
|
273
105
|
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
106
|
markWireSessionDirty(deps, event.sessionID);
|
|
288
|
-
} else {
|
|
289
|
-
applyContextDiet(deps, event);
|
|
290
107
|
}
|
|
291
108
|
|
|
292
109
|
const agent = event.agent;
|
|
@@ -342,7 +159,7 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
|
|
|
342
159
|
|
|
343
160
|
Object.assign(
|
|
344
161
|
event.headers,
|
|
345
|
-
toolHeaders(deps, event.sessionID
|
|
162
|
+
toolHeaders(deps, event.sessionID),
|
|
346
163
|
);
|
|
347
164
|
|
|
348
165
|
const pending = deps.state.pendingAdTurns.get(
|
|
@@ -376,162 +193,16 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
|
|
|
376
193
|
}
|
|
377
194
|
}
|
|
378
195
|
|
|
379
|
-
/** `concurrent` is free-pi's per-session 429 ("one request at a time"). */
|
|
380
|
-
function isConcurrentFailure(error: any): boolean {
|
|
381
|
-
if (!error) return false;
|
|
382
|
-
const body =
|
|
383
|
-
typeof error.response?.body === "string" ? error.response.body : "";
|
|
384
|
-
const message = typeof error.message === "string" ? error.message : "";
|
|
385
|
-
return (
|
|
386
|
-
/one request at a time/i.test(message) ||
|
|
387
|
-
/one request at a time/i.test(body) ||
|
|
388
|
-
/"concurrent"/.test(body)
|
|
389
|
-
);
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
/**
|
|
393
|
-
* Limits and account blocks do not recover by retrying. pi's own retry helper
|
|
394
|
-
* treats them as terminal (`NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN`), but
|
|
395
|
-
* OpenCode retries every 429 by default, which surfaces as an endless
|
|
396
|
-
* "Retrying…". The response rewrite turns most of these into a 400; this guard
|
|
397
|
-
* covers the rest and keeps the CLI's behavior.
|
|
398
|
-
*/
|
|
399
|
-
const TERMINAL_RETRY_CODES = new Set([
|
|
400
|
-
"daily_cap",
|
|
401
|
-
"hourly_ceiling",
|
|
402
|
-
"rolling_cap",
|
|
403
|
-
"global_cap",
|
|
404
|
-
"account_ceiling",
|
|
405
|
-
"free_usage_limit",
|
|
406
|
-
"premium_allowance",
|
|
407
|
-
"guest_allowance",
|
|
408
|
-
"model_requires_credits",
|
|
409
|
-
"insufficient_credits",
|
|
410
|
-
"ads_required",
|
|
411
|
-
"account_review",
|
|
412
|
-
"region_unavailable",
|
|
413
|
-
"unauthorized",
|
|
414
|
-
"expired_token",
|
|
415
|
-
"guest_login_required",
|
|
416
|
-
"consent_required",
|
|
417
|
-
"upgrade_required",
|
|
418
|
-
"reward_required",
|
|
419
|
-
"content_filter",
|
|
420
|
-
"subagents_unavailable",
|
|
421
|
-
]);
|
|
422
|
-
|
|
423
|
-
const TERMINAL_RETRY_PATTERN =
|
|
424
|
-
/free usage limit|monthly usage limit|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/i;
|
|
425
|
-
|
|
426
|
-
/**
|
|
427
|
-
* A request that never reached the gateway. `provider.transport` covers the
|
|
428
|
-
* typed path, while the pattern catches bare fetch errors. These are worth
|
|
429
|
-
* retrying beyond the usual budget: a brief offline moment or a background
|
|
430
|
-
* service restart is not a provider limit.
|
|
431
|
-
*/
|
|
432
|
-
const TRANSPORT_RETRY_PATTERN =
|
|
433
|
-
/ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|EPIPE|socket hang up|fetch failed|Unable to connect|connection (?:refused|reset)/i;
|
|
434
|
-
|
|
435
|
-
function isTransportFailure(error: any): boolean {
|
|
436
|
-
const type = typeof error?.type === "string" ? error.type : "";
|
|
437
|
-
if (/transport|network|connection/i.test(type)) return true;
|
|
438
|
-
const message = `${error?.message ?? ""}\n${error?.cause?.message ?? ""}`;
|
|
439
|
-
return TRANSPORT_RETRY_PATTERN.test(message);
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
function isTerminalFailure(error: any): boolean {
|
|
443
|
-
if (
|
|
444
|
-
error?.type === "aborted" ||
|
|
445
|
-
/aborted|cancelled|canceled|interrupted|AbortError/i.test(
|
|
446
|
-
`${error?.message ?? ""}`,
|
|
447
|
-
)
|
|
448
|
-
) {
|
|
449
|
-
return true;
|
|
450
|
-
}
|
|
451
|
-
const parsed = parseFreePiError(error, true);
|
|
452
|
-
if (parsed?.code && TERMINAL_RETRY_CODES.has(parsed.code)) return true;
|
|
453
|
-
const body =
|
|
454
|
-
typeof error?.response?.body === "string" ? error.response.body : "";
|
|
455
|
-
const message = typeof error?.message === "string" ? error.message : "";
|
|
456
|
-
return TERMINAL_RETRY_PATTERN.test(`${message}\n${body}`);
|
|
457
|
-
}
|
|
458
|
-
|
|
459
196
|
/**
|
|
460
|
-
*
|
|
461
|
-
*
|
|
462
|
-
*
|
|
463
|
-
*
|
|
464
|
-
*
|
|
465
|
-
* and the server can leave a per-session lock behind that resets do not clear.
|
|
466
|
-
* Rotating the wire session id and retrying turns that into a normal retry.
|
|
197
|
+
* Retries belong to OpenCode's session runner: it decides whether an error is
|
|
198
|
+
* retryable, how many times, and the delay. The one thing the runner cannot
|
|
199
|
+
* know is that free-pi holds a per-session request slot and that a failed
|
|
200
|
+
* attempt can leave it marked busy, so the next attempt must use a fresh wire
|
|
201
|
+
* id. This hook only arms that rotation and never touches `decision`.
|
|
467
202
|
*/
|
|
468
203
|
function applyRetryPolicy(deps: Deps, event: any): void {
|
|
469
|
-
if (
|
|
470
|
-
|
|
471
|
-
event.decision = { retry: false };
|
|
472
|
-
return;
|
|
473
|
-
}
|
|
474
|
-
const previous = wireSessionID(deps, event.sessionID);
|
|
475
|
-
const next = rotateWireSessionID(deps, event.sessionID);
|
|
476
|
-
// Releasing the old id cleans up an orphaned slot; a leaked live lock
|
|
477
|
-
// ignores reset, which is exactly why the next request uses a fresh id.
|
|
478
|
-
void closeFreePiSession(deps, previous).catch(() => undefined);
|
|
479
|
-
deps.log.info("free-pi session busy; retrying with a fresh session id", {
|
|
480
|
-
sessionID: event.sessionID,
|
|
481
|
-
from: previous,
|
|
482
|
-
to: next,
|
|
483
|
-
attempt: event.attempt,
|
|
484
|
-
});
|
|
485
|
-
event.decision = {
|
|
486
|
-
retry: true,
|
|
487
|
-
delay: Math.min(
|
|
488
|
-
CONCURRENT_RETRY_BASE_MS * 2 ** (event.attempt - 1),
|
|
489
|
-
CONCURRENT_RETRY_MAX_DELAY_MS,
|
|
490
|
-
),
|
|
491
|
-
};
|
|
492
|
-
return;
|
|
493
|
-
}
|
|
494
|
-
if (isTerminalFailure(event.error)) {
|
|
495
|
-
// Remember the broken stream too, so the next turn rotates its wire id
|
|
496
|
-
// instead of running into the stale per-session lock.
|
|
497
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
498
|
-
event.decision = { retry: false };
|
|
499
|
-
return;
|
|
500
|
-
}
|
|
501
|
-
if (isTransportFailure(event.error)) {
|
|
502
|
-
if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
|
|
503
|
-
event.decision = { retry: false };
|
|
504
|
-
return;
|
|
505
|
-
}
|
|
506
|
-
// A connection that dropped mid-turn can leave the gateway's per-session
|
|
507
|
-
// slot marked busy, so the next attempt should not reuse the wire id.
|
|
508
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
509
|
-
const attempt = Math.max(1, event.attempt - 1);
|
|
510
|
-
event.decision = {
|
|
511
|
-
retry: true,
|
|
512
|
-
delay: Math.min(
|
|
513
|
-
TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1),
|
|
514
|
-
TRANSPORT_RETRY_MAX_DELAY_MS,
|
|
515
|
-
),
|
|
516
|
-
};
|
|
517
|
-
deps.log.warn("free-pi could not be reached; retrying", {
|
|
518
|
-
sessionID: event.sessionID,
|
|
519
|
-
attempt: event.attempt,
|
|
520
|
-
delay: event.decision.delay,
|
|
521
|
-
error: typeof event.error?.message === "string" ? event.error.message : undefined,
|
|
522
|
-
});
|
|
523
|
-
return;
|
|
524
|
-
}
|
|
525
|
-
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
526
|
-
event.decision = { retry: false };
|
|
527
|
-
return;
|
|
528
|
-
}
|
|
529
|
-
if (!event.decision?.retry) return;
|
|
530
|
-
const attempt = Math.max(1, event.attempt - 1);
|
|
531
|
-
event.decision.delay = Math.min(
|
|
532
|
-
RETRY_BASE_DELAY_MS * 2 ** (attempt - 1),
|
|
533
|
-
RETRY_MAX_DELAY_MS,
|
|
534
|
-
);
|
|
204
|
+
if (event.decision?.retry !== true) return;
|
|
205
|
+
markWireSessionDirty(deps, event.sessionID);
|
|
535
206
|
}
|
|
536
207
|
|
|
537
208
|
/**
|
|
@@ -661,6 +332,95 @@ async function hookForProviders(
|
|
|
661
332
|
}
|
|
662
333
|
}
|
|
663
334
|
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Handles every free-pi HTTP response: replays a busy session, rewrites
|
|
338
|
+
* context overflows into something OpenCode compacts on, turns long-lived
|
|
339
|
+
* limits into readable messages and watches for server notices.
|
|
340
|
+
*
|
|
341
|
+
* Split from `registerSessionHooks` because the response path is the plugin's
|
|
342
|
+
* most intricate logic and it was buried mid-function.
|
|
343
|
+
*/
|
|
344
|
+
async function handleProviderResponse(
|
|
345
|
+
ctx: Plugin.Context,
|
|
346
|
+
deps: Deps,
|
|
347
|
+
event: any,
|
|
348
|
+
): Promise<void> {
|
|
349
|
+
const response = event.response;
|
|
350
|
+
// Context overflow has to be handled first: a 429 context ceiling must
|
|
351
|
+
// become a 400 overflow, not a friendly long-lived limit.
|
|
352
|
+
const overflow = await rewriteContextOverflowResponse(response).catch(
|
|
353
|
+
() => undefined,
|
|
354
|
+
);
|
|
355
|
+
if (overflow) {
|
|
356
|
+
const code =
|
|
357
|
+
overflow.headers.get("x-free-pi-original-code") ?? "context_overflow";
|
|
358
|
+
// A gateway failure can report "too long" for a request that fits the
|
|
359
|
+
// model's window; compacting then loops (summarize, retry, rejected
|
|
360
|
+
// again). The plugin never re-sends the request itself: it only
|
|
361
|
+
// classifies the failure.
|
|
362
|
+
const body = await storedBody(deps, event).catch(() => undefined);
|
|
363
|
+
const profile = body ? profileRequest(body) : undefined;
|
|
364
|
+
const tokens = profile?.tokens;
|
|
365
|
+
const limits = currentLiveLimits();
|
|
366
|
+
const window =
|
|
367
|
+
(profile?.model
|
|
368
|
+
? limits?.models[profile.model]?.maxPromptTokens
|
|
369
|
+
: undefined) ??
|
|
370
|
+
limits?.window?.tokens ??
|
|
371
|
+
CONTEXT_WINDOW;
|
|
372
|
+
// A rejection is real when the request is at least as large as the window
|
|
373
|
+
// the gateway has already accepted for this model; anything meaningfully
|
|
374
|
+
// smaller is a provider failure, not an overflow.
|
|
375
|
+
const fitsWindow =
|
|
376
|
+
typeof tokens === "number" &&
|
|
377
|
+
tokens < window * SPURIOUS_OVERFLOW_SHARE;
|
|
378
|
+
if (
|
|
379
|
+
typeof tokens === "number" &&
|
|
380
|
+
!fitsWindow &&
|
|
381
|
+
profile?.model &&
|
|
382
|
+
profile.hasMedia !== true
|
|
383
|
+
) {
|
|
384
|
+
// A rejection of a real prompt is the only free measurement of the
|
|
385
|
+
// gateway's ceiling. Attachments inflate the estimate and say nothing
|
|
386
|
+
// about the text window, so they are not learned from.
|
|
387
|
+
const learned = noteRejectedPrompt(deps, profile.model, tokens);
|
|
388
|
+
// Re-run the provider transform so this session's next compaction
|
|
389
|
+
// already targets the smaller window; no restart needed.
|
|
390
|
+
if (learned) {
|
|
391
|
+
void ctx.provider.reload().catch(() => undefined);
|
|
392
|
+
}
|
|
393
|
+
} else if (fitsWindow) {
|
|
394
|
+
const count = noteSpuriousOverflow(deps, event.sessionID);
|
|
395
|
+
deps.log.info(
|
|
396
|
+
"free-pi rejected a request as too long that fits the model window",
|
|
397
|
+
{ sessionID: event.sessionID, code, tokens, window, rejections: count },
|
|
398
|
+
);
|
|
399
|
+
if (overflowingSpuriously(deps, event.sessionID)) {
|
|
400
|
+
markWireSessionDirty(deps, event.sessionID);
|
|
401
|
+
deps.log.warn(
|
|
402
|
+
"compact loop stopped: free-pi keeps rejecting a request that fits",
|
|
403
|
+
{ sessionID: event.sessionID, code, tokens, window },
|
|
404
|
+
);
|
|
405
|
+
event.response = watchFreePiNotice(
|
|
406
|
+
deps,
|
|
407
|
+
spuriousOverflowResponse(overflow),
|
|
408
|
+
);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
event.response = watchFreePiNotice(deps, overflow);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
const rewritten = await rewriteLimitResponse(response).catch(
|
|
416
|
+
() => undefined,
|
|
417
|
+
);
|
|
418
|
+
event.response = watchFreePiNotice(
|
|
419
|
+
deps,
|
|
420
|
+
rewritten ?? response,
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
|
|
664
424
|
export async function registerSessionHooks(
|
|
665
425
|
ctx: Plugin.Context,
|
|
666
426
|
deps: Deps,
|
|
@@ -677,7 +437,6 @@ export async function registerSessionHooks(
|
|
|
677
437
|
registrations,
|
|
678
438
|
);
|
|
679
439
|
await hookForProviders(ctx, "generate", generation("generate"), registrations);
|
|
680
|
-
await hookForProviders(ctx, "title", generation("title"), registrations);
|
|
681
440
|
// The generation hooks above only run for free-pi providers. These unscoped
|
|
682
441
|
// ones strip the plugin's tools from every other provider's requests.
|
|
683
442
|
for (const name of ["context", "compaction", "generate"] as const) {
|
|
@@ -722,88 +481,7 @@ export async function registerSessionHooks(
|
|
|
722
481
|
await hookForProviders(
|
|
723
482
|
ctx,
|
|
724
483
|
"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
|
-
},
|
|
484
|
+
(event: any) => handleProviderResponse(ctx, deps, event),
|
|
807
485
|
registrations,
|
|
808
486
|
);
|
|
809
487
|
await hookForProviders(
|