@eduardo191labs/opencode-free-pi 0.3.2 → 0.3.3
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 +19 -3
- package/dist/catalog/models.d.ts +1 -1
- package/dist/catalog/models.js +15 -26
- package/dist/errors/limit.d.ts +7 -0
- package/dist/errors/limit.js +67 -0
- package/dist/session/hooks.js +8 -1
- package/package.json +1 -1
- package/src/catalog/models.ts +22 -32
- package/src/errors/limit.ts +73 -0
- package/src/session/hooks.ts +13 -1
package/README.md
CHANGED
|
@@ -66,6 +66,14 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
66
66
|
- Catálogo en vivo de modelos **free-pi** y **free-pi-defense**.
|
|
67
67
|
- Integración nativa de OpenCode V2 para credenciales OAuth, clave y entorno.
|
|
68
68
|
- Cuota diaria, créditos premium y límites con mensajes claros.
|
|
69
|
+
- **Límites reales de free-pi**: todos los modelos anuncian la ventana de
|
|
70
|
+
contexto de 200k y el límite de salida de 32k que aplica el CLI del
|
|
71
|
+
proveedor, aunque models.dev informe ventanas mayores para el modelo
|
|
72
|
+
upstream. Así OpenCode compacta antes de que el servidor rechace la
|
|
73
|
+
conversación.
|
|
74
|
+
- **Compactación integrada**: los errores `context_too_long` de free-pi se
|
|
75
|
+
reescriben para que OpenCode los reconozca como desbordamiento de contexto y
|
|
76
|
+
ejecute `/compact` automáticamente en vez de terminar el turno.
|
|
69
77
|
- Anuncios e impresiones asociados al turno correcto.
|
|
70
78
|
- Cada agente y subagente usa su propio `x-session-id`, `x-turn-id` y contexto
|
|
71
79
|
de anuncios; nunca reutiliza los del agente principal.
|
|
@@ -96,7 +104,15 @@ El plugin replica las cabeceras del plugin V1 de free-pi:
|
|
|
96
104
|
`x-client-version` y, cuando aplica, `x-session-id`.
|
|
97
105
|
|
|
98
106
|
Las respuestas `429` de límites largos se reescriben a un `400` con el mensaje
|
|
99
|
-
amigable, igual que en el plugin V1.
|
|
107
|
+
amigable, igual que en el plugin V1. Las respuestas `413` (o `429`/`400`) con
|
|
108
|
+
código `context_too_long`, `context_too_long_for_fallback` o `context_ceiling`
|
|
109
|
+
se reescriben a un `400` con el texto que OpenCode clasifica como
|
|
110
|
+
desbordamiento de contexto, para que dispare la compactación automática.
|
|
111
|
+
|
|
112
|
+
free-pi cobra en créditos contra una cuota diaria, no en USD por token. Por
|
|
113
|
+
eso los modelos se registran con costo `0`, igual que el CLI del proveedor; el
|
|
114
|
+
consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
|
|
115
|
+
cuota y límite.
|
|
100
116
|
|
|
101
117
|
## Rutas por plataforma
|
|
102
118
|
|
|
@@ -214,8 +230,8 @@ dist/ build ESM y tipos
|
|
|
214
230
|
scripts/postinstall.mjs registro en opencode.json
|
|
215
231
|
test/smoke.mjs prueba de humo del build
|
|
216
232
|
test/registry.mjs caché y tolerancia a fallos de models.dev
|
|
217
|
-
test/models.mjs capacidades, variantes, límites y costos
|
|
218
|
-
test/hooks.mjs hooks de sesión, anuncios y
|
|
233
|
+
test/models.mjs capacidades, variantes, límites reales y costos
|
|
234
|
+
test/hooks.mjs hooks de sesión, anuncios, cuota y compactación
|
|
219
235
|
```
|
|
220
236
|
|
|
221
237
|
## Desinstalar
|
package/dist/catalog/models.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export declare function partitionModels(catalog: Catalog | undefined): {
|
|
|
8
8
|
defense: CatalogModel[];
|
|
9
9
|
};
|
|
10
10
|
export declare function displayName(model: CatalogModel): string;
|
|
11
|
-
export declare function modelCost(
|
|
11
|
+
export declare function modelCost(_model: CatalogModel, _capability?: ModelsDevModel): ModelDefinition["cost"];
|
|
12
12
|
export declare function modelRegistryCandidates(registry: ModelRegistry | undefined): RegistryCandidate[];
|
|
13
13
|
export declare function modelCapability(model: CatalogModel, candidates: RegistryCandidate[]): ModelsDevModel | undefined;
|
|
14
14
|
export declare function modelVariants(options: ReasoningOption[] | undefined, outputLimit: number): VariantMap;
|
package/dist/catalog/models.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
2
|
import { CONTEXT_WINDOW, MAX_OUTPUT_TOKENS, } from "../constants.js";
|
|
3
|
-
import {
|
|
3
|
+
import { positiveNumber } from "../utils/numbers.js";
|
|
4
4
|
import { cleanText } from "../utils/text.js";
|
|
5
5
|
export function usableModels(catalog) {
|
|
6
6
|
return (catalog?.models ?? []).filter((model) => typeof model.id === "string" && model.id.length > 0);
|
|
@@ -35,29 +35,12 @@ export function displayName(model) {
|
|
|
35
35
|
}
|
|
36
36
|
return tags.length > 0 ? `${base} (${tags.join(" · ")})` : base;
|
|
37
37
|
}
|
|
38
|
-
export function modelCost(
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
0;
|
|
45
|
-
const output = creditsToUsd(model.output_credits_per_mtok) ||
|
|
46
|
-
positiveNumber(capability?.cost?.output) ||
|
|
47
|
-
0;
|
|
48
|
-
if (input > 0 || output > 0) {
|
|
49
|
-
return {
|
|
50
|
-
input,
|
|
51
|
-
output,
|
|
52
|
-
cache_read: creditsToUsd(model.cache_read_credits_per_mtok) ||
|
|
53
|
-
positiveNumber(capability?.cost?.cache_read) ||
|
|
54
|
-
input,
|
|
55
|
-
cache_write: creditsToUsd(model.cache_write_credits_per_mtok) ||
|
|
56
|
-
positiveNumber(capability?.cost?.cache_write) ||
|
|
57
|
-
input,
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
return zero;
|
|
38
|
+
export function modelCost(_model, _capability) {
|
|
39
|
+
// free-pi bills in credits against a daily allowance; it does not charge
|
|
40
|
+
// per-token USD. The provider CLI registers every model with zero cost and
|
|
41
|
+
// shows the real usage through /usage, so publishing reseller prices here
|
|
42
|
+
// would only invent a cost the account never pays.
|
|
43
|
+
return { input: 0, output: 0, cache_read: 0, cache_write: 0 };
|
|
61
44
|
}
|
|
62
45
|
export function modelRegistryCandidates(registry) {
|
|
63
46
|
const candidates = [];
|
|
@@ -175,8 +158,14 @@ export function buildModels(models, candidates = []) {
|
|
|
175
158
|
const capability = modelCapability(model, candidates);
|
|
176
159
|
const reasoning = model.reasoning ?? capability?.reasoning ?? true;
|
|
177
160
|
const reasoningOptions = model.reasoning_options ?? capability?.reasoning_options;
|
|
178
|
-
|
|
179
|
-
|
|
161
|
+
// free-pi enforces a 200k input window and 32k output cap on every model,
|
|
162
|
+
// regardless of what models.dev reports for the upstream provider. The
|
|
163
|
+
// provider CLI registers exactly these limits, so clamp to them here too:
|
|
164
|
+
// an advertised 1M window would let OpenCode grow a session past the
|
|
165
|
+
// server's real ceiling and fail with `context_too_long` instead of
|
|
166
|
+
// compacting.
|
|
167
|
+
const limitContext = Math.min(positiveNumber(model.context_window, model.contextWindow, model.limit?.context, capability?.limit?.context) ?? CONTEXT_WINDOW, CONTEXT_WINDOW);
|
|
168
|
+
const limitOutput = Math.min(positiveNumber(model.max_tokens, model.maxTokens, model.max_output_tokens, model.limit?.output, capability?.limit?.output) ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS);
|
|
180
169
|
result[model.id] = {
|
|
181
170
|
id: model.id,
|
|
182
171
|
name: displayName(model),
|
package/dist/errors/limit.d.ts
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
* Rewrites long-lived free-pi limit responses so the client shows the friendly
|
|
3
3
|
* message instead of a raw 429. Mirrors the fetch wrapper used by the V1 plugin.
|
|
4
4
|
*/
|
|
5
|
+
/**
|
|
6
|
+
* Returns a replacement response when `response` is a free-pi context overflow.
|
|
7
|
+
* The replacement is a 400 with a message OpenCode recognizes as context
|
|
8
|
+
* overflow, so the session runner compacts and retries instead of surfacing
|
|
9
|
+
* the fatal "conversation is too long" error.
|
|
10
|
+
*/
|
|
11
|
+
export declare function rewriteContextOverflowResponse(response: Response): Promise<Response | undefined>;
|
|
5
12
|
/**
|
|
6
13
|
* Returns a replacement response when `response` is a 429 that represents a
|
|
7
14
|
* long-lived limit. The replacement is a 400 with the same body but a friendly
|
package/dist/errors/limit.js
CHANGED
|
@@ -18,6 +18,19 @@ const LONG_LIMIT_CODES = new Set([
|
|
|
18
18
|
"account_ceiling",
|
|
19
19
|
"region_unavailable",
|
|
20
20
|
]);
|
|
21
|
+
const CONTEXT_OVERFLOW_CODES = new Set([
|
|
22
|
+
"context_too_long",
|
|
23
|
+
"context_too_long_for_fallback",
|
|
24
|
+
"context_ceiling",
|
|
25
|
+
]);
|
|
26
|
+
/**
|
|
27
|
+
* OpenCode classifies HTTP 413 as `payload-too-large` before it looks at the
|
|
28
|
+
* message, so free-pi's `context_too_long` 413 never reaches the compaction
|
|
29
|
+
* recovery path. Rewriting it to a 400 whose message matches OpenCode's
|
|
30
|
+
* `prompt is too long` overflow pattern lets the runner compact and retry the
|
|
31
|
+
* turn instead of failing it with the raw server message.
|
|
32
|
+
*/
|
|
33
|
+
const CONTEXT_OVERFLOW_MESSAGE = "prompt is too long for this model's context window; run /compact or start a new session";
|
|
21
34
|
function retryAfterSeconds(response) {
|
|
22
35
|
const retryAfter = response.headers.get("retry-after");
|
|
23
36
|
if (retryAfter) {
|
|
@@ -81,6 +94,60 @@ function friendlyBody(body, info) {
|
|
|
81
94
|
return body;
|
|
82
95
|
}
|
|
83
96
|
}
|
|
97
|
+
function contextOverflowCode(body) {
|
|
98
|
+
try {
|
|
99
|
+
const data = JSON.parse(body);
|
|
100
|
+
const raw = data?.code ?? data?.error?.code ?? data?.limit;
|
|
101
|
+
if (typeof raw === "string" && CONTEXT_OVERFLOW_CODES.has(raw))
|
|
102
|
+
return raw;
|
|
103
|
+
}
|
|
104
|
+
catch { }
|
|
105
|
+
return undefined;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Returns a replacement response when `response` is a free-pi context overflow.
|
|
109
|
+
* The replacement is a 400 with a message OpenCode recognizes as context
|
|
110
|
+
* overflow, so the session runner compacts and retries instead of surfacing
|
|
111
|
+
* the fatal "conversation is too long" error.
|
|
112
|
+
*/
|
|
113
|
+
export async function rewriteContextOverflowResponse(response) {
|
|
114
|
+
if (response.status !== 413 &&
|
|
115
|
+
response.status !== 429 &&
|
|
116
|
+
response.status !== 400)
|
|
117
|
+
return undefined;
|
|
118
|
+
const body = await response
|
|
119
|
+
.clone()
|
|
120
|
+
.text()
|
|
121
|
+
.catch(() => "");
|
|
122
|
+
if (!body)
|
|
123
|
+
return undefined;
|
|
124
|
+
const code = contextOverflowCode(body);
|
|
125
|
+
if (!code)
|
|
126
|
+
return undefined;
|
|
127
|
+
const headers = new Headers(response.headers);
|
|
128
|
+
headers.delete("retry-after");
|
|
129
|
+
headers.delete("retry-after-ms");
|
|
130
|
+
headers.set("x-free-pi-original-status", String(response.status));
|
|
131
|
+
headers.set("x-free-pi-original-code", code);
|
|
132
|
+
let data;
|
|
133
|
+
try {
|
|
134
|
+
data = JSON.parse(body);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
data = {};
|
|
138
|
+
}
|
|
139
|
+
if (data && typeof data === "object") {
|
|
140
|
+
data.message = CONTEXT_OVERFLOW_MESSAGE;
|
|
141
|
+
if (data.error && typeof data.error === "object") {
|
|
142
|
+
data.error.message = CONTEXT_OVERFLOW_MESSAGE;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return new Response(JSON.stringify(data), {
|
|
146
|
+
status: 400,
|
|
147
|
+
statusText: "Bad Request",
|
|
148
|
+
headers,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
84
151
|
/**
|
|
85
152
|
* Returns a replacement response when `response` is a 429 that represents a
|
|
86
153
|
* long-lived limit. The replacement is a 400 with the same body but a friendly
|
package/dist/session/hooks.js
CHANGED
|
@@ -3,7 +3,7 @@ import { ensureAdImpression } from "../ads/impression.js";
|
|
|
3
3
|
import { resolveAdTurn } from "../ads/resolve.js";
|
|
4
4
|
import { resolveToken } from "../auth/token.js";
|
|
5
5
|
import { COST_EXPERIMENT_HEADER, DEFENSE_PROVIDER_ID, EFFICIENCY_RULE, MAX_OUTPUT_TOKENS, PROVIDER_ID, } from "../constants.js";
|
|
6
|
-
import { rewriteLimitResponse } from "../errors/limit.js";
|
|
6
|
+
import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
|
|
7
7
|
import { trimMap } from "../utils/async.js";
|
|
8
8
|
import { rememberFreePiSession } from "./track.js";
|
|
9
9
|
import { rememberTrackedModel } from "./usage.js";
|
|
@@ -110,6 +110,13 @@ export async function registerSessionHooks(ctx, deps) {
|
|
|
110
110
|
await hookForProviders(ctx, "title", generation("title"), registrations);
|
|
111
111
|
await hookForProviders(ctx, "model.request", (event) => applyModelRequest(deps, event), registrations);
|
|
112
112
|
await hookForProviders(ctx, "http.response", async (event) => {
|
|
113
|
+
// Context overflow has to be handled first: a 429 context ceiling must
|
|
114
|
+
// become a 400 overflow, not a friendly long-lived limit.
|
|
115
|
+
const overflow = await rewriteContextOverflowResponse(event.response).catch(() => undefined);
|
|
116
|
+
if (overflow) {
|
|
117
|
+
event.response = overflow;
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
113
120
|
const rewritten = await rewriteLimitResponse(event.response).catch(() => undefined);
|
|
114
121
|
if (rewritten)
|
|
115
122
|
event.response = rewritten;
|
package/package.json
CHANGED
package/src/catalog/models.ts
CHANGED
|
@@ -13,7 +13,7 @@ import type {
|
|
|
13
13
|
ReasoningOption,
|
|
14
14
|
RegistryCandidate,
|
|
15
15
|
} from "../types.js";
|
|
16
|
-
import {
|
|
16
|
+
import { positiveNumber } from "../utils/numbers.js";
|
|
17
17
|
import { cleanText } from "../utils/text.js";
|
|
18
18
|
|
|
19
19
|
export type VariantMap = Record<string, Record<string, unknown>>;
|
|
@@ -63,34 +63,14 @@ export function displayName(model: CatalogModel): string {
|
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
export function modelCost(
|
|
66
|
-
|
|
67
|
-
|
|
66
|
+
_model: CatalogModel,
|
|
67
|
+
_capability?: ModelsDevModel,
|
|
68
68
|
): ModelDefinition["cost"] {
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
0;
|
|
75
|
-
const output =
|
|
76
|
-
creditsToUsd(model.output_credits_per_mtok) ||
|
|
77
|
-
positiveNumber(capability?.cost?.output) ||
|
|
78
|
-
0;
|
|
79
|
-
if (input > 0 || output > 0) {
|
|
80
|
-
return {
|
|
81
|
-
input,
|
|
82
|
-
output,
|
|
83
|
-
cache_read:
|
|
84
|
-
creditsToUsd(model.cache_read_credits_per_mtok) ||
|
|
85
|
-
positiveNumber(capability?.cost?.cache_read) ||
|
|
86
|
-
input,
|
|
87
|
-
cache_write:
|
|
88
|
-
creditsToUsd(model.cache_write_credits_per_mtok) ||
|
|
89
|
-
positiveNumber(capability?.cost?.cache_write) ||
|
|
90
|
-
input,
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
return zero;
|
|
69
|
+
// free-pi bills in credits against a daily allowance; it does not charge
|
|
70
|
+
// per-token USD. The provider CLI registers every model with zero cost and
|
|
71
|
+
// shows the real usage through /usage, so publishing reseller prices here
|
|
72
|
+
// would only invent a cost the account never pays.
|
|
73
|
+
return { input: 0, output: 0, cache_read: 0, cache_write: 0 };
|
|
94
74
|
}
|
|
95
75
|
|
|
96
76
|
export function modelRegistryCandidates(
|
|
@@ -244,21 +224,31 @@ export function buildModels(
|
|
|
244
224
|
const reasoning = model.reasoning ?? capability?.reasoning ?? true;
|
|
245
225
|
const reasoningOptions =
|
|
246
226
|
model.reasoning_options ?? capability?.reasoning_options;
|
|
247
|
-
|
|
227
|
+
// free-pi enforces a 200k input window and 32k output cap on every model,
|
|
228
|
+
// regardless of what models.dev reports for the upstream provider. The
|
|
229
|
+
// provider CLI registers exactly these limits, so clamp to them here too:
|
|
230
|
+
// an advertised 1M window would let OpenCode grow a session past the
|
|
231
|
+
// server's real ceiling and fail with `context_too_long` instead of
|
|
232
|
+
// compacting.
|
|
233
|
+
const limitContext = Math.min(
|
|
248
234
|
positiveNumber(
|
|
249
235
|
model.context_window,
|
|
250
236
|
model.contextWindow,
|
|
251
237
|
model.limit?.context,
|
|
252
238
|
capability?.limit?.context,
|
|
253
|
-
) ?? CONTEXT_WINDOW
|
|
254
|
-
|
|
239
|
+
) ?? CONTEXT_WINDOW,
|
|
240
|
+
CONTEXT_WINDOW,
|
|
241
|
+
);
|
|
242
|
+
const limitOutput = Math.min(
|
|
255
243
|
positiveNumber(
|
|
256
244
|
model.max_tokens,
|
|
257
245
|
model.maxTokens,
|
|
258
246
|
model.max_output_tokens,
|
|
259
247
|
model.limit?.output,
|
|
260
248
|
capability?.limit?.output,
|
|
261
|
-
) ?? MAX_OUTPUT_TOKENS
|
|
249
|
+
) ?? MAX_OUTPUT_TOKENS,
|
|
250
|
+
MAX_OUTPUT_TOKENS,
|
|
251
|
+
);
|
|
262
252
|
result[model.id] = {
|
|
263
253
|
id: model.id,
|
|
264
254
|
name: displayName(model),
|
package/src/errors/limit.ts
CHANGED
|
@@ -22,6 +22,22 @@ const LONG_LIMIT_CODES = new Set([
|
|
|
22
22
|
"region_unavailable",
|
|
23
23
|
]);
|
|
24
24
|
|
|
25
|
+
const CONTEXT_OVERFLOW_CODES = new Set([
|
|
26
|
+
"context_too_long",
|
|
27
|
+
"context_too_long_for_fallback",
|
|
28
|
+
"context_ceiling",
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* OpenCode classifies HTTP 413 as `payload-too-large` before it looks at the
|
|
33
|
+
* message, so free-pi's `context_too_long` 413 never reaches the compaction
|
|
34
|
+
* recovery path. Rewriting it to a 400 whose message matches OpenCode's
|
|
35
|
+
* `prompt is too long` overflow pattern lets the runner compact and retry the
|
|
36
|
+
* turn instead of failing it with the raw server message.
|
|
37
|
+
*/
|
|
38
|
+
const CONTEXT_OVERFLOW_MESSAGE =
|
|
39
|
+
"prompt is too long for this model's context window; run /compact or start a new session";
|
|
40
|
+
|
|
25
41
|
type LimitInfo = {
|
|
26
42
|
code?: string;
|
|
27
43
|
retryAfterSeconds?: number;
|
|
@@ -85,6 +101,63 @@ function friendlyBody(body: string, info: LimitInfo): string {
|
|
|
85
101
|
}
|
|
86
102
|
}
|
|
87
103
|
|
|
104
|
+
function contextOverflowCode(body: string): string | undefined {
|
|
105
|
+
try {
|
|
106
|
+
const data = JSON.parse(body);
|
|
107
|
+
const raw = data?.code ?? data?.error?.code ?? data?.limit;
|
|
108
|
+
if (typeof raw === "string" && CONTEXT_OVERFLOW_CODES.has(raw)) return raw;
|
|
109
|
+
} catch {}
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Returns a replacement response when `response` is a free-pi context overflow.
|
|
115
|
+
* The replacement is a 400 with a message OpenCode recognizes as context
|
|
116
|
+
* overflow, so the session runner compacts and retries instead of surfacing
|
|
117
|
+
* the fatal "conversation is too long" error.
|
|
118
|
+
*/
|
|
119
|
+
export async function rewriteContextOverflowResponse(
|
|
120
|
+
response: Response,
|
|
121
|
+
): Promise<Response | undefined> {
|
|
122
|
+
if (
|
|
123
|
+
response.status !== 413 &&
|
|
124
|
+
response.status !== 429 &&
|
|
125
|
+
response.status !== 400
|
|
126
|
+
)
|
|
127
|
+
return undefined;
|
|
128
|
+
const body = await response
|
|
129
|
+
.clone()
|
|
130
|
+
.text()
|
|
131
|
+
.catch(() => "");
|
|
132
|
+
if (!body) return undefined;
|
|
133
|
+
const code = contextOverflowCode(body);
|
|
134
|
+
if (!code) return undefined;
|
|
135
|
+
|
|
136
|
+
const headers = new Headers(response.headers);
|
|
137
|
+
headers.delete("retry-after");
|
|
138
|
+
headers.delete("retry-after-ms");
|
|
139
|
+
headers.set("x-free-pi-original-status", String(response.status));
|
|
140
|
+
headers.set("x-free-pi-original-code", code);
|
|
141
|
+
|
|
142
|
+
let data: any;
|
|
143
|
+
try {
|
|
144
|
+
data = JSON.parse(body);
|
|
145
|
+
} catch {
|
|
146
|
+
data = {};
|
|
147
|
+
}
|
|
148
|
+
if (data && typeof data === "object") {
|
|
149
|
+
data.message = CONTEXT_OVERFLOW_MESSAGE;
|
|
150
|
+
if (data.error && typeof data.error === "object") {
|
|
151
|
+
data.error.message = CONTEXT_OVERFLOW_MESSAGE;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return new Response(JSON.stringify(data), {
|
|
155
|
+
status: 400,
|
|
156
|
+
statusText: "Bad Request",
|
|
157
|
+
headers,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
88
161
|
/**
|
|
89
162
|
* Returns a replacement response when `response` is a 429 that represents a
|
|
90
163
|
* long-lived limit. The replacement is a 400 with the same body but a friendly
|
package/src/session/hooks.ts
CHANGED
|
@@ -13,7 +13,10 @@ import {
|
|
|
13
13
|
PROVIDER_ID,
|
|
14
14
|
} from "../constants.js";
|
|
15
15
|
import type { Deps } from "../deps.js";
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
rewriteContextOverflowResponse,
|
|
18
|
+
rewriteLimitResponse,
|
|
19
|
+
} from "../errors/limit.js";
|
|
17
20
|
import { trimMap } from "../utils/async.js";
|
|
18
21
|
import { rememberFreePiSession } from "./track.js";
|
|
19
22
|
import { rememberTrackedModel } from "./usage.js";
|
|
@@ -184,6 +187,15 @@ export async function registerSessionHooks(
|
|
|
184
187
|
ctx,
|
|
185
188
|
"http.response",
|
|
186
189
|
async (event: any) => {
|
|
190
|
+
// Context overflow has to be handled first: a 429 context ceiling must
|
|
191
|
+
// become a 400 overflow, not a friendly long-lived limit.
|
|
192
|
+
const overflow = await rewriteContextOverflowResponse(
|
|
193
|
+
event.response,
|
|
194
|
+
).catch(() => undefined);
|
|
195
|
+
if (overflow) {
|
|
196
|
+
event.response = overflow;
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
187
199
|
const rewritten = await rewriteLimitResponse(event.response).catch(
|
|
188
200
|
() => undefined,
|
|
189
201
|
);
|