@eduardo191labs/opencode-free-pi 0.6.5 → 0.6.7
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 +43 -1
- package/dist/agents/definitions.d.ts +2 -2
- package/dist/agents/definitions.js +7 -1
- package/dist/catalog/live.d.ts +18 -2
- package/dist/catalog/live.js +43 -2
- package/dist/catalog/models.js +6 -1
- package/dist/constants.d.ts +10 -1
- package/dist/constants.js +10 -1
- package/dist/deps.d.ts +4 -1
- package/dist/plugin.js +46 -3
- package/dist/session/hooks.js +84 -4
- package/dist/session/overflow.d.ts +31 -0
- package/dist/session/overflow.js +82 -4
- package/dist/session/replay.d.ts +4 -0
- package/dist/session/replay.js +10 -7
- package/dist/session/tools.d.ts +1 -1
- package/dist/session/tools.js +1 -0
- package/dist/tools/subagent.d.ts +29 -0
- package/dist/tools/subagent.js +197 -0
- package/dist/types.d.ts +11 -0
- package/package.json +1 -1
- package/src/agents/definitions.ts +7 -1
- package/src/catalog/live.ts +65 -2
- package/src/catalog/models.ts +6 -0
- package/src/constants.ts +11 -1
- package/src/deps.ts +8 -1
- package/src/plugin.ts +44 -2
- package/src/session/hooks.ts +102 -3
- package/src/session/overflow.ts +98 -4
- package/src/session/replay.ts +14 -6
- package/src/session/tools.ts +1 -0
- package/src/tools/subagent.ts +271 -0
- package/src/types.ts +18 -0
package/src/plugin.ts
CHANGED
|
@@ -17,6 +17,7 @@ import { readCredentialsToken } from "./auth/credentials.js";
|
|
|
17
17
|
import { tokenFromCredential } from "./auth/credential.js";
|
|
18
18
|
import { fetchCatalog } from "./catalog/catalog.js";
|
|
19
19
|
import {
|
|
20
|
+
currentLiveLimits,
|
|
20
21
|
loadLiveLimits,
|
|
21
22
|
shouldVerifyWindow,
|
|
22
23
|
verifyGatewayWindow,
|
|
@@ -44,6 +45,7 @@ import { cancelAllFinalizeTimers } from "./session/track.js";
|
|
|
44
45
|
import { createRuntimeState } from "./state.js";
|
|
45
46
|
import { registerGenerateImageTool } from "./tools/image-generate.js";
|
|
46
47
|
import { registerUsageTool } from "./tools/usage.js";
|
|
48
|
+
import { registerSubagentTool } from "./tools/subagent.js";
|
|
47
49
|
import { registerVisionTool } from "./tools/vision.js";
|
|
48
50
|
import { registerWebTools } from "./tools/web.js";
|
|
49
51
|
import { settle } from "./utils/async.js";
|
|
@@ -76,6 +78,36 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
76
78
|
return [];
|
|
77
79
|
}
|
|
78
80
|
},
|
|
81
|
+
readSession: async (sessionID) => {
|
|
82
|
+
try {
|
|
83
|
+
const info = await ctx.session.get({ sessionID });
|
|
84
|
+
return {
|
|
85
|
+
id: info.id,
|
|
86
|
+
parentID: info.parentID,
|
|
87
|
+
title: info.title,
|
|
88
|
+
agent: info.agent,
|
|
89
|
+
outcome: info.outcome,
|
|
90
|
+
updated: info.time?.updated,
|
|
91
|
+
};
|
|
92
|
+
} catch {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
listSubagentSessions: async (parentID) => {
|
|
97
|
+
try {
|
|
98
|
+
const result = await ctx.session.list({ parentID, limit: 50 });
|
|
99
|
+
return (result.data ?? []).map((info) => ({
|
|
100
|
+
id: info.id,
|
|
101
|
+
parentID: info.parentID,
|
|
102
|
+
title: info.title,
|
|
103
|
+
agent: info.agent,
|
|
104
|
+
outcome: info.outcome,
|
|
105
|
+
updated: info.time?.updated,
|
|
106
|
+
}));
|
|
107
|
+
} catch {
|
|
108
|
+
return [];
|
|
109
|
+
}
|
|
110
|
+
},
|
|
79
111
|
storage: ctx.storage,
|
|
80
112
|
};
|
|
81
113
|
|
|
@@ -188,11 +220,17 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
188
220
|
await registerIntegration(ctx, deps);
|
|
189
221
|
|
|
190
222
|
await ctx.provider.transform((editor) => {
|
|
223
|
+
// Rebuilt on every transform so a learned context ceiling applies as soon
|
|
224
|
+
// as the response hook records it, without restarting OpenCode.
|
|
225
|
+
const active = currentLiveLimits() ?? live;
|
|
226
|
+
const buildOptionsNow = { ...buildOptions, live: active };
|
|
227
|
+
const mainNow = buildModels(main, candidates, buildOptionsNow);
|
|
228
|
+
const defenseNow = buildModels(defense, candidates, buildOptionsNow);
|
|
191
229
|
applyProvider(
|
|
192
230
|
editor,
|
|
193
231
|
PROVIDER_ID,
|
|
194
232
|
"Free Pi",
|
|
195
|
-
|
|
233
|
+
mainNow,
|
|
196
234
|
state.providerToken,
|
|
197
235
|
);
|
|
198
236
|
if (includeDefense && defense.length > 0) {
|
|
@@ -200,7 +238,7 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
200
238
|
editor,
|
|
201
239
|
DEFENSE_PROVIDER_ID,
|
|
202
240
|
"Free Pi Defense",
|
|
203
|
-
|
|
241
|
+
defenseNow,
|
|
204
242
|
state.providerToken,
|
|
205
243
|
);
|
|
206
244
|
}
|
|
@@ -251,6 +289,10 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
251
289
|
}> = [
|
|
252
290
|
{ name: "look_at_image", register: () => registerVisionTool(ctx, deps) },
|
|
253
291
|
{ name: "free_pi_usage", register: () => registerUsageTool(ctx, deps) },
|
|
292
|
+
{
|
|
293
|
+
name: "free_pi_subagent_read",
|
|
294
|
+
register: () => registerSubagentTool(ctx, deps),
|
|
295
|
+
},
|
|
254
296
|
{ name: "web", register: () => registerWebTools(ctx, deps) },
|
|
255
297
|
{ name: "generate_image", register: () => registerGenerateImageTool(ctx, deps) },
|
|
256
298
|
];
|
package/src/session/hooks.ts
CHANGED
|
@@ -23,7 +23,15 @@ import {
|
|
|
23
23
|
RETRY_MAX_DELAY_MS,
|
|
24
24
|
RETRY_MAX_RETRIES,
|
|
25
25
|
SUBAGENT_HEADER,
|
|
26
|
+
TRANSPORT_RETRY_BASE_MS,
|
|
27
|
+
TRANSPORT_RETRY_MAX,
|
|
28
|
+
TRANSPORT_RETRY_MAX_DELAY_MS,
|
|
26
29
|
} from "../constants.js";
|
|
30
|
+
import {
|
|
31
|
+
currentLiveLimits,
|
|
32
|
+
learnedContextWindow,
|
|
33
|
+
noteRejectedPrompt,
|
|
34
|
+
} from "../catalog/live.js";
|
|
27
35
|
import type { Deps } from "../deps.js";
|
|
28
36
|
import { closeFreePiSession } from "../api/session.js";
|
|
29
37
|
import {
|
|
@@ -32,6 +40,7 @@ import {
|
|
|
32
40
|
} from "../errors/limit.js";
|
|
33
41
|
import { parseFreePiError } from "../errors/parse.js";
|
|
34
42
|
import { trimMap } from "../utils/async.js";
|
|
43
|
+
import { trimMessagesForBudget } from "./overflow.js";
|
|
35
44
|
import { watchFreePiNotice } from "./notices.js";
|
|
36
45
|
import {
|
|
37
46
|
clearSpuriousOverflows,
|
|
@@ -96,6 +105,33 @@ function rememberPending(deps: Deps, key: string, turn: AdTurn): void {
|
|
|
96
105
|
deps.state.pendingAdTurns.set(key, turn);
|
|
97
106
|
}
|
|
98
107
|
|
|
108
|
+
/**
|
|
109
|
+
* Fits the compaction request inside the ceiling the gateway has already
|
|
110
|
+
* proven. OpenCode aborts the turn ("the compaction request cannot be reduced
|
|
111
|
+
* further") when the summarizer request is rejected too, so the plugin drops
|
|
112
|
+
* the oldest user turns before that can happen.
|
|
113
|
+
*/
|
|
114
|
+
function fitCompactionMessages(deps: Deps, event: any): void {
|
|
115
|
+
const modelID = typeof event.model?.id === "string" ? event.model.id : "";
|
|
116
|
+
const ceiling = learnedContextWindow(currentLiveLimits(), modelID);
|
|
117
|
+
if (!ceiling) return;
|
|
118
|
+
const messages = event.messages;
|
|
119
|
+
if (!Array.isArray(messages) || messages.length === 0) return;
|
|
120
|
+
const trimmed = trimMessagesForBudget(messages, Math.floor(ceiling * 0.9));
|
|
121
|
+
if (trimmed.dropped === 0) return;
|
|
122
|
+
event.messages = [...trimmed.messages];
|
|
123
|
+
deps.log.warn(
|
|
124
|
+
"free-pi trimmed the compaction request to fit the learned window",
|
|
125
|
+
{
|
|
126
|
+
sessionID: event.sessionID,
|
|
127
|
+
model: modelID,
|
|
128
|
+
window: ceiling,
|
|
129
|
+
droppedMessages: trimmed.dropped,
|
|
130
|
+
promptTokens: trimmed.tokens,
|
|
131
|
+
},
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
|
|
99
135
|
/** Adds a system block once, even when OpenCode reuses the same event. */
|
|
100
136
|
function appendSystemGuidance(
|
|
101
137
|
event: any,
|
|
@@ -138,15 +174,18 @@ async function applyGeneration(
|
|
|
138
174
|
const limit = deps.state.outputLimits.get(
|
|
139
175
|
`${event.model.providerID}/${modelID}`,
|
|
140
176
|
);
|
|
141
|
-
//
|
|
142
|
-
//
|
|
177
|
+
// The compaction summary is the one response that must never be cut: a
|
|
178
|
+
// summary that reaches the output limit fails the whole compaction and the
|
|
179
|
+
// turn stops with nothing but the checkpoint. Leave OpenCode's own budget
|
|
180
|
+
// for it and only cap the answers the user reads.
|
|
143
181
|
const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING);
|
|
144
|
-
if (event.options) {
|
|
182
|
+
if (event.options && kind !== "compaction") {
|
|
145
183
|
const current = event.options.maxTokens;
|
|
146
184
|
if (current === undefined || current > cap) event.options.maxTokens = cap;
|
|
147
185
|
}
|
|
148
186
|
|
|
149
187
|
if (kind === "compaction") {
|
|
188
|
+
fitCompactionMessages(deps, event);
|
|
150
189
|
appendSystemGuidance(
|
|
151
190
|
event,
|
|
152
191
|
FREE_PI_COMPACTION_GUIDANCE,
|
|
@@ -297,6 +336,22 @@ const TERMINAL_RETRY_CODES = new Set([
|
|
|
297
336
|
const TERMINAL_RETRY_PATTERN =
|
|
298
337
|
/free usage limit|monthly usage limit|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/i;
|
|
299
338
|
|
|
339
|
+
/**
|
|
340
|
+
* A request that never reached the gateway. `provider.transport` covers the
|
|
341
|
+
* typed path, while the pattern catches bare fetch errors. These are worth
|
|
342
|
+
* retrying beyond the usual budget: a brief offline moment or a background
|
|
343
|
+
* service restart is not a provider limit.
|
|
344
|
+
*/
|
|
345
|
+
const TRANSPORT_RETRY_PATTERN =
|
|
346
|
+
/ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|EPIPE|socket hang up|fetch failed|Unable to connect|connection (?:refused|reset)/i;
|
|
347
|
+
|
|
348
|
+
function isTransportFailure(error: any): boolean {
|
|
349
|
+
const type = typeof error?.type === "string" ? error.type : "";
|
|
350
|
+
if (/transport|network|connection/i.test(type)) return true;
|
|
351
|
+
const message = `${error?.message ?? ""}\n${error?.cause?.message ?? ""}`;
|
|
352
|
+
return TRANSPORT_RETRY_PATTERN.test(message);
|
|
353
|
+
}
|
|
354
|
+
|
|
300
355
|
function isTerminalFailure(error: any): boolean {
|
|
301
356
|
if (
|
|
302
357
|
error?.type === "aborted" ||
|
|
@@ -356,6 +411,30 @@ function applyRetryPolicy(deps: Deps, event: any): void {
|
|
|
356
411
|
event.decision = { retry: false };
|
|
357
412
|
return;
|
|
358
413
|
}
|
|
414
|
+
if (isTransportFailure(event.error)) {
|
|
415
|
+
if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
|
|
416
|
+
event.decision = { retry: false };
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
// A connection that dropped mid-turn can leave the gateway's per-session
|
|
420
|
+
// slot marked busy, so the next attempt should not reuse the wire id.
|
|
421
|
+
markWireSessionDirty(deps, event.sessionID);
|
|
422
|
+
const attempt = Math.max(1, event.attempt - 1);
|
|
423
|
+
event.decision = {
|
|
424
|
+
retry: true,
|
|
425
|
+
delay: Math.min(
|
|
426
|
+
TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1),
|
|
427
|
+
TRANSPORT_RETRY_MAX_DELAY_MS,
|
|
428
|
+
),
|
|
429
|
+
};
|
|
430
|
+
deps.log.warn("free-pi could not be reached; retrying", {
|
|
431
|
+
sessionID: event.sessionID,
|
|
432
|
+
attempt: event.attempt,
|
|
433
|
+
delay: event.decision.delay,
|
|
434
|
+
error: typeof event.error?.message === "string" ? event.error.message : undefined,
|
|
435
|
+
});
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
359
438
|
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
360
439
|
event.decision = { retry: false };
|
|
361
440
|
return;
|
|
@@ -540,6 +619,26 @@ export async function registerSessionHooks(
|
|
|
540
619
|
const reviewed = await replaySpuriousOverflow(deps, event).catch(
|
|
541
620
|
() => ({}) as OverflowReplay,
|
|
542
621
|
);
|
|
622
|
+
// A rejection of a real prompt is the only free measurement of the
|
|
623
|
+
// gateway's ceiling. Attachments inflate the estimate and say nothing
|
|
624
|
+
// about the text window, so they are not learned from.
|
|
625
|
+
if (
|
|
626
|
+
reviewed.spurious === false &&
|
|
627
|
+
typeof reviewed.tokens === "number" &&
|
|
628
|
+
reviewed.model &&
|
|
629
|
+
reviewed.hasMedia !== true
|
|
630
|
+
) {
|
|
631
|
+
const learned = noteRejectedPrompt(
|
|
632
|
+
deps,
|
|
633
|
+
reviewed.model,
|
|
634
|
+
reviewed.tokens,
|
|
635
|
+
);
|
|
636
|
+
// Re-run the provider transform so this session's next compaction
|
|
637
|
+
// already targets the smaller window; no restart needed.
|
|
638
|
+
if (learned) {
|
|
639
|
+
void ctx.provider.reload().catch(() => undefined);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
543
642
|
if (reviewed.response) {
|
|
544
643
|
clearSpuriousOverflows(deps, event.sessionID);
|
|
545
644
|
event.response = watchFreePiNotice(deps, reviewed.response);
|
package/src/session/overflow.ts
CHANGED
|
@@ -31,18 +31,45 @@ export const SPURIOUS_OVERFLOW_MESSAGE =
|
|
|
31
31
|
"free-pi rejected this request as too long even though it fits the model's window; " +
|
|
32
32
|
"this is a provider failure, not a context overflow. Retry the message, or start a new session if it persists.";
|
|
33
33
|
|
|
34
|
+
/** Part types that carry an inline image or file, which the provider bills in full. */
|
|
35
|
+
const MEDIA_PART_TYPES = new Set([
|
|
36
|
+
"image",
|
|
37
|
+
"image_url",
|
|
38
|
+
"input_image",
|
|
39
|
+
"file",
|
|
40
|
+
"input_file",
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
export type RequestProfile = {
|
|
44
|
+
/** Approximate token count of the whole body. */
|
|
45
|
+
readonly tokens: number;
|
|
46
|
+
/** The upstream model the body asks for, when it can be read. */
|
|
47
|
+
readonly model?: string;
|
|
48
|
+
/** Whether the body carries an inline image or file. */
|
|
49
|
+
readonly hasMedia: boolean;
|
|
50
|
+
};
|
|
51
|
+
|
|
34
52
|
/**
|
|
35
53
|
* Approximate token count of a chat-completions body: every string in it,
|
|
36
54
|
* message text and tool output alike, at the usual four characters per token.
|
|
37
55
|
* Inline media counts at its base64 length, which is what the provider bills.
|
|
56
|
+
*
|
|
57
|
+
* The same walk reports the requested model and whether the body carries
|
|
58
|
+
* inline media. A rejection caused by a large attachment says nothing about
|
|
59
|
+
* the model's text window, so callers must not learn a ceiling from it.
|
|
38
60
|
*/
|
|
39
|
-
export function
|
|
61
|
+
export function profileRequest(body: string): RequestProfile {
|
|
40
62
|
try {
|
|
41
63
|
const data = JSON.parse(body) as unknown;
|
|
42
64
|
let chars = 0;
|
|
65
|
+
let model: string | undefined;
|
|
66
|
+
let hasMedia = false;
|
|
43
67
|
const walk = (value: unknown): void => {
|
|
44
68
|
if (typeof value === "string") {
|
|
45
69
|
chars += value.length;
|
|
70
|
+
if (value.startsWith("data:image/") || value.startsWith("data:application/")) {
|
|
71
|
+
hasMedia = true;
|
|
72
|
+
}
|
|
46
73
|
return;
|
|
47
74
|
}
|
|
48
75
|
if (Array.isArray(value)) {
|
|
@@ -50,17 +77,84 @@ export function measureRequestTokens(body: string): number {
|
|
|
50
77
|
return;
|
|
51
78
|
}
|
|
52
79
|
if (value && typeof value === "object") {
|
|
53
|
-
|
|
80
|
+
const record = value as Record<string, unknown>;
|
|
81
|
+
if (typeof record.type === "string" && MEDIA_PART_TYPES.has(record.type)) {
|
|
82
|
+
hasMedia = true;
|
|
83
|
+
}
|
|
84
|
+
if (
|
|
85
|
+
model === undefined &&
|
|
86
|
+
typeof record.model === "string" &&
|
|
87
|
+
record.model.length > 0
|
|
88
|
+
) {
|
|
89
|
+
model = record.model;
|
|
90
|
+
}
|
|
91
|
+
for (const [key, item] of Object.entries(record)) {
|
|
54
92
|
chars += key.length;
|
|
55
93
|
walk(item);
|
|
56
94
|
}
|
|
57
95
|
}
|
|
58
96
|
};
|
|
59
97
|
walk(data);
|
|
60
|
-
return Math.ceil(chars / 4);
|
|
98
|
+
return { tokens: Math.ceil(chars / 4), model, hasMedia };
|
|
61
99
|
} catch {
|
|
62
|
-
return Math.ceil(body.length / 4);
|
|
100
|
+
return { tokens: Math.ceil(body.length / 4), hasMedia: false };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Token count of a request body, without the extra facts. */
|
|
105
|
+
export function measureRequestTokens(body: string): number {
|
|
106
|
+
return profileRequest(body).tokens;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Cheap per-message estimate; the body is serialized once per message. */
|
|
110
|
+
export function estimateMessageTokens(message: unknown): number {
|
|
111
|
+
try {
|
|
112
|
+
return Math.ceil(JSON.stringify(message).length / 4);
|
|
113
|
+
} catch {
|
|
114
|
+
return 0;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Keeps the newest part of a message list inside `budget` tokens, cutting only
|
|
120
|
+
* at user turns so an assistant tool call never loses its results.
|
|
121
|
+
*
|
|
122
|
+
* OpenCode refuses to compact when the summarization request itself is still
|
|
123
|
+
* too large, and then the turn dies with nothing but the checkpoint shown. The
|
|
124
|
+
* gateway's real ceiling is lower than the advertised window, so the plugin
|
|
125
|
+
* trims the oldest turns it can spare before the summarizer is asked to read
|
|
126
|
+
* them.
|
|
127
|
+
*/
|
|
128
|
+
export function trimMessagesForBudget(
|
|
129
|
+
messages: readonly unknown[],
|
|
130
|
+
budget: number,
|
|
131
|
+
): {
|
|
132
|
+
readonly messages: readonly unknown[];
|
|
133
|
+
readonly dropped: number;
|
|
134
|
+
readonly tokens: number;
|
|
135
|
+
} {
|
|
136
|
+
if (messages.length === 0) return { messages, dropped: 0, tokens: 0 };
|
|
137
|
+
const sizes = messages.map(estimateMessageTokens);
|
|
138
|
+
let total = 0;
|
|
139
|
+
for (const size of sizes) total += size;
|
|
140
|
+
if (total <= budget) return { messages, dropped: 0, tokens: total };
|
|
141
|
+
|
|
142
|
+
const cuts: number[] = [];
|
|
143
|
+
for (let index = 1; index < messages.length; index += 1) {
|
|
144
|
+
const role = (messages[index] as { role?: unknown } | undefined)?.role;
|
|
145
|
+
if (role === "user") cuts.push(index);
|
|
146
|
+
}
|
|
147
|
+
for (const cut of cuts) {
|
|
148
|
+
let tail = 0;
|
|
149
|
+
for (let index = cut; index < sizes.length; index += 1) tail += sizes[index]!;
|
|
150
|
+
if (tail <= budget) {
|
|
151
|
+
return { messages: messages.slice(cut), dropped: cut, tokens: tail };
|
|
152
|
+
}
|
|
63
153
|
}
|
|
154
|
+
const last = cuts.length > 0 ? cuts[cuts.length - 1]! : messages.length - 1;
|
|
155
|
+
let tail = 0;
|
|
156
|
+
for (let index = last; index < sizes.length; index += 1) tail += sizes[index]!;
|
|
157
|
+
return { messages: messages.slice(last), dropped: last, tokens: tail };
|
|
64
158
|
}
|
|
65
159
|
|
|
66
160
|
/**
|
package/src/session/replay.ts
CHANGED
|
@@ -19,7 +19,7 @@ import type { Deps } from "../deps.js";
|
|
|
19
19
|
import { overflowCodeOf } from "../errors/limit.js";
|
|
20
20
|
import { sleep, trimMap } from "../utils/async.js";
|
|
21
21
|
import {
|
|
22
|
-
|
|
22
|
+
profileRequest,
|
|
23
23
|
SPURIOUS_OVERFLOW_TOKENS,
|
|
24
24
|
} from "./overflow.js";
|
|
25
25
|
import { rotateWireSessionID, wireSessionID } from "./wire.js";
|
|
@@ -159,6 +159,10 @@ export async function replayConcurrentResponse(
|
|
|
159
159
|
export type OverflowReplay = {
|
|
160
160
|
/** Tokens of the rejected request, when its body was available. */
|
|
161
161
|
readonly tokens?: number;
|
|
162
|
+
/** Upstream model the rejected request asked for. */
|
|
163
|
+
readonly model?: string;
|
|
164
|
+
/** Whether the rejected request carried an inline image or file. */
|
|
165
|
+
readonly hasMedia?: boolean;
|
|
162
166
|
/** Whether the rejected request plainly fits the model window. */
|
|
163
167
|
readonly spurious?: boolean;
|
|
164
168
|
/** A good response from a fresh wire session, when the retry succeeded. */
|
|
@@ -187,13 +191,17 @@ export async function replaySpuriousOverflow(
|
|
|
187
191
|
|
|
188
192
|
const body = await storedBody(deps, event);
|
|
189
193
|
if (!body) return {};
|
|
190
|
-
const
|
|
191
|
-
|
|
194
|
+
const profile = profileRequest(body);
|
|
195
|
+
const tokens = profile.tokens;
|
|
196
|
+
const facts = { model: profile.model, hasMedia: profile.hasMedia };
|
|
197
|
+
if (tokens >= SPURIOUS_OVERFLOW_TOKENS) {
|
|
198
|
+
return { tokens, ...facts, spurious: false };
|
|
199
|
+
}
|
|
192
200
|
|
|
193
201
|
let previous =
|
|
194
202
|
request.headers.get("x-session-id") ?? wireSessionID(deps, event.sessionID);
|
|
195
203
|
for (let attempt = 1; attempt <= OVERFLOW_REPLAY_ATTEMPTS; attempt++) {
|
|
196
|
-
if (request.signal.aborted) return { tokens, spurious: true };
|
|
204
|
+
if (request.signal.aborted) return { tokens, ...facts, spurious: true };
|
|
197
205
|
const next = rotateWireSessionID(deps, event.sessionID);
|
|
198
206
|
if (previous && previous !== next) {
|
|
199
207
|
void closeFreePiSession(deps, previous).catch(() => undefined);
|
|
@@ -217,12 +225,12 @@ export async function replaySpuriousOverflow(
|
|
|
217
225
|
"free-pi rejected a request that fits as too long; replayed it on a fresh session id",
|
|
218
226
|
{ sessionID: event.sessionID, tokens, to: next, attempt },
|
|
219
227
|
);
|
|
220
|
-
return { tokens, spurious: true, response };
|
|
228
|
+
return { tokens, ...facts, spurious: true, response };
|
|
221
229
|
}
|
|
222
230
|
}
|
|
223
231
|
deps.log.info(
|
|
224
232
|
"free-pi keeps rejecting a request that fits as too long; the provider is failing",
|
|
225
233
|
{ sessionID: event.sessionID, tokens },
|
|
226
234
|
);
|
|
227
|
-
return { tokens, spurious: true };
|
|
235
|
+
return { tokens, ...facts, spurious: true };
|
|
228
236
|
}
|