@eduardo191labs/opencode-free-pi 0.6.4 → 0.6.6
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 +45 -3
- package/dist/agents/definitions.d.ts +18 -0
- package/dist/agents/definitions.js +34 -0
- package/dist/catalog/live.d.ts +18 -2
- package/dist/catalog/live.js +43 -2
- package/dist/catalog/models.js +11 -2
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +3 -0
- package/dist/plugin.js +28 -6
- package/dist/session/hooks.js +48 -3
- 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/package.json +1 -1
- package/src/agents/definitions.ts +45 -0
- package/src/catalog/live.ts +65 -2
- package/src/catalog/models.ts +11 -1
- package/src/constants.ts +3 -0
- package/src/plugin.ts +31 -4
- package/src/session/hooks.ts +59 -3
- package/src/session/overflow.ts +98 -4
- package/src/session/replay.ts +14 -6
package/README.md
CHANGED
|
@@ -77,6 +77,19 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
77
77
|
- **Compactación integrada**: los errores `context_too_long` de free-pi se
|
|
78
78
|
reescriben para que OpenCode los reconozca como desbordamiento de contexto y
|
|
79
79
|
ejecute `/compact` automáticamente en vez de terminar el turno.
|
|
80
|
+
- **Techo por modelo aprendido del gateway**: cuando free-pi rechaza una
|
|
81
|
+
petición real por longitud, ese tamaño se guarda en `live-limits.json` como
|
|
82
|
+
techo de ese modelo y el catálogo anuncia una ventana un 15 % menor, también
|
|
83
|
+
sin reiniciar (`provider.reload`). Así la siguiente compactación empieza antes
|
|
84
|
+
de que el gateway rechace también el propio resumen, que es lo que dejaba el
|
|
85
|
+
turno detenido con solo el checkpoint en pantalla. Los rechazos causados por
|
|
86
|
+
una imagen o un archivo adjunto no cuentan: su base64 no dice nada de la
|
|
87
|
+
ventana de texto.
|
|
88
|
+
- **Resumen de compactación sin recortes**: el presupuesto de salida de la
|
|
89
|
+
petición de compactación ya no se limita a 32k, porque un resumen cortado por
|
|
90
|
+
el límite hace fallar la compactación completa. Si aun así el resumen no cabe
|
|
91
|
+
en el techo aprendido, se descartan los turnos de usuario más antiguos (sin
|
|
92
|
+
romper parejas de herramienta) en lugar de abortar el turno.
|
|
80
93
|
- **Sin bucles de compactación**: si el servidor rechaza como «demasiado
|
|
81
94
|
largo» una petición que cabe de sobra en la ventana (menos de 60k tokens),
|
|
82
95
|
el plugin la reintenta con un `x-session-id` nuevo en vez de compactar. Si
|
|
@@ -275,14 +288,34 @@ plano, comparten el allowance diario y envían su informe al agente principal.
|
|
|
275
288
|
Así se conservan las sesiones hijas, los permisos, la profundidad de subagentes
|
|
276
289
|
y el resto del comportamiento nativo.
|
|
277
290
|
|
|
291
|
+
La herramienta `subagent` es la de OpenCode y está disponible para **cualquier
|
|
292
|
+
modelo**, no solo para los agentes `free-pi/*`: también puede lanzarlos un
|
|
293
|
+
modelo de otro proveedor configurado en OpenCode. El plugin garantiza además que
|
|
294
|
+
todos los modelos gratuitos anuncien soporte de tools, de modo que el runner
|
|
295
|
+
nunca oculte `subagent` por una capacidad incorrecta de models.dev.
|
|
296
|
+
|
|
278
297
|
El plugin solo reescribe estos archivos si conservan su marca de gestión; si el
|
|
279
298
|
usuario edita o reemplaza uno, se respeta tal cual.
|
|
280
299
|
|
|
281
300
|
## Skill y contexto
|
|
282
301
|
|
|
283
|
-
El plugin
|
|
284
|
-
|
|
285
|
-
|
|
302
|
+
El plugin instala una skill nativa en:
|
|
303
|
+
|
|
304
|
+
```text
|
|
305
|
+
~/.config/opencode/skills/free-pi/SKILL.md
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
OpenCode la descubre con su propio cargador (ID `free-pi`), la anuncia cuando es
|
|
309
|
+
relevante y el agente la carga con su herramienta `skill`. Contiene la lista de
|
|
310
|
+
herramientas, los subagentes y las reglas de allowance. Si el directorio de
|
|
311
|
+
configuración no se puede escribir, el plugin la registra mediante la API de
|
|
312
|
+
skills como respaldo.
|
|
313
|
+
|
|
314
|
+
Cada petición principal de free-pi recibe además una guía breve que pide
|
|
315
|
+
delegar el trabajo grande en `free-pi/scout`, `free-pi/planner`,
|
|
316
|
+
`free-pi/worker` o `free-pi/reviewer` con `subagent`, cargar skills con `skill`
|
|
317
|
+
y seguir `AGENTS.md` en lugar de inventar convenciones. Esa guía solo se añade a
|
|
318
|
+
las peticiones de `free-pi` y `free-pi-defense`.
|
|
286
319
|
|
|
287
320
|
La memoria, las sesiones y el contexto son los de OpenCode: `AGENTS.md` y los
|
|
288
321
|
archivos de `instructions` se cargan de forma nativa, las sesiones persisten y
|
|
@@ -327,6 +360,15 @@ insiste, devuelve un `400` con un mensaje de error de proveedor. Ese texto no
|
|
|
327
360
|
coincide con el patrón de desbordamiento de OpenCode, así que el runner deja de
|
|
328
361
|
compactar en lugar de entrar en un ciclo de resúmenes que no reducen nada.
|
|
329
362
|
|
|
363
|
+
Cuando el rechazo sí corresponde a una conversación larga, el tamaño medido se
|
|
364
|
+
guarda como `rejectedPromptTokens` del modelo en `live-limits.json`. El
|
|
365
|
+
`provider.transform` reconstruye el catálogo con ese techo (85 % del tamaño
|
|
366
|
+
rechazado, sin bajar de la ventana ya aceptada) y `provider.reload` lo aplica en
|
|
367
|
+
caliente, de modo que la siguiente compactación se dispara antes de que el
|
|
368
|
+
gateway rechace el resumen. Si el resumen aún no cupiera, el hook de
|
|
369
|
+
compactación descarta los turnos de usuario más antiguos en lugar de dejar que
|
|
370
|
+
OpenCode aborte el turno.
|
|
371
|
+
|
|
330
372
|
free-pi cobra en créditos contra una cuota diaria, no en USD por token. Por
|
|
331
373
|
eso los modelos se registran con costo `0`, igual que el CLI del proveedor; el
|
|
332
374
|
consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
|
|
@@ -22,9 +22,16 @@ export declare const FREE_PI_SKILL_ID = "free-pi";
|
|
|
22
22
|
export declare const FREE_PI_SKILL_NAME = "free-pi";
|
|
23
23
|
export declare const FREE_PI_SKILL_DESCRIPTION = "How free-pi works in OpenCode: its tools, the installed native subagents, allowance and limits, and where sessions and memory live.";
|
|
24
24
|
export declare const FREE_PI_SKILL = "# free-pi in OpenCode\n\nfree-pi is a free, ad-supported provider for OpenCode. You sign in with GitHub\nand ads in the session pay for the inference; there is no model API key. The\nfree daily allowance is shared by every free-pi model and every tool that spends\nit.\n\n## Tools\n- `free_pi_usage` shows today's remaining allowance, credits, token counts and\n the account tier. Read-only.\n- `look_at_image` asks a vision model about a PNG, JPEG or WebP inside the\n project. Use it when the current model takes text only, or when the image is a\n file on disk and you want a targeted answer instead of attaching it.\n- `generate_image` draws one image from a prompt and saves it under `images/`.\n- `web_search` searches the web for current information.\n- `docs_lookup` looks up current library and framework documentation.\n\nEvery tool except `free_pi_usage` spends allowance. Usage limits\n(`daily_cap`, `rolling_cap`, concurrency) are terminal: stop and continue\nwithout the tool instead of retrying.\n\n## Subagents\n\nUse OpenCode's native subagent tool with the agents this plugin installs:\n\n| Agent | Use it for |\n| --- | --- |\n| `free-pi/scout` | Read-only recon: locate code and return structured findings. |\n| `free-pi/planner` | Read-only plan for a change, ready for a worker. |\n| `free-pi/worker` | Carry out one full task in its own context window. |\n| `free-pi/reviewer` | Read-only review with file and line references. |\n\nSubagents inherit the free-pi model, share the same daily allowance, and run as\nchild sessions in the background. Keep large exploration in a subagent so it\ndoes not fill your own context. Use OpenCode's agent picker or the `subagent`\ntool; do not try to launch them through shell commands.\n\n## Memory and sessions\n\nOpenCode owns memory and context: `AGENTS.md` and configured instruction files\nare loaded natively, sessions persist and resume, and compaction folds long\nconversations into a summary. Put durable project facts in `AGENTS.md` (or a\nfile listed under `instructions`) instead of repeating them in every prompt.\n\n## Native integrations\n\nMCP servers, skills, commands, references and permissions are configured in\nOpenCode as usual; free-pi does not replace them. Prefer those native features\nover running an external CLI.\n";
|
|
25
|
+
/**
|
|
26
|
+
* The same skill as a native `SKILL.md`. OpenCode discovers it from the global
|
|
27
|
+
* skills directory, so the file, its ID, its permissions and the `skill` tool
|
|
28
|
+
* all belong to OpenCode instead of a runtime registration.
|
|
29
|
+
*/
|
|
30
|
+
export declare const FREE_PI_SKILL_FILE = "---\nname: free-pi\ndescription: How free-pi works in OpenCode: its tools, the installed native subagents, allowance and limits, and where sessions and memory live.\n---\n\n<!-- managed by @eduardo191labs/opencode-free-pi; delete this line to keep your own copy -->\n\n# free-pi in OpenCode\n\nfree-pi is a free, ad-supported provider for OpenCode. You sign in with GitHub\nand ads in the session pay for the inference; there is no model API key. The\nfree daily allowance is shared by every free-pi model and every tool that spends\nit.\n\n## Tools\n- `free_pi_usage` shows today's remaining allowance, credits, token counts and\n the account tier. Read-only.\n- `look_at_image` asks a vision model about a PNG, JPEG or WebP inside the\n project. Use it when the current model takes text only, or when the image is a\n file on disk and you want a targeted answer instead of attaching it.\n- `generate_image` draws one image from a prompt and saves it under `images/`.\n- `web_search` searches the web for current information.\n- `docs_lookup` looks up current library and framework documentation.\n\nEvery tool except `free_pi_usage` spends allowance. Usage limits\n(`daily_cap`, `rolling_cap`, concurrency) are terminal: stop and continue\nwithout the tool instead of retrying.\n\n## Subagents\n\nUse OpenCode's native subagent tool with the agents this plugin installs:\n\n| Agent | Use it for |\n| --- | --- |\n| `free-pi/scout` | Read-only recon: locate code and return structured findings. |\n| `free-pi/planner` | Read-only plan for a change, ready for a worker. |\n| `free-pi/worker` | Carry out one full task in its own context window. |\n| `free-pi/reviewer` | Read-only review with file and line references. |\n\nSubagents inherit the free-pi model, share the same daily allowance, and run as\nchild sessions in the background. Keep large exploration in a subagent so it\ndoes not fill your own context. Use OpenCode's agent picker or the `subagent`\ntool; do not try to launch them through shell commands.\n\n## Memory and sessions\n\nOpenCode owns memory and context: `AGENTS.md` and configured instruction files\nare loaded natively, sessions persist and resume, and compaction folds long\nconversations into a summary. Put durable project facts in `AGENTS.md` (or a\nfile listed under `instructions`) instead of repeating them in every prompt.\n\n## Native integrations\n\nMCP servers, skills, commands, references and permissions are configured in\nOpenCode as usual; free-pi does not replace them. Prefer those native features\nover running an external CLI.\n";
|
|
25
31
|
/** OpenCode's user-wide config directory, where it loads custom agents. */
|
|
26
32
|
export declare function openCodeConfigDir(): string;
|
|
27
33
|
export declare function freePiAgentPath(configDir: string, id: FreePiAgentID): string;
|
|
34
|
+
export declare function freePiSkillPath(configDir: string): string;
|
|
28
35
|
export type AgentInstallResult = {
|
|
29
36
|
readonly installed: FreePiAgentID[];
|
|
30
37
|
readonly skipped: FreePiAgentID[];
|
|
@@ -36,3 +43,14 @@ export type AgentInstallResult = {
|
|
|
36
43
|
* treated as user-owned and left untouched.
|
|
37
44
|
*/
|
|
38
45
|
export declare function installFreePiAgents(configDir?: string): Promise<AgentInstallResult>;
|
|
46
|
+
export type SkillInstallResult = {
|
|
47
|
+
readonly installed: boolean;
|
|
48
|
+
readonly skipped: boolean;
|
|
49
|
+
readonly changed: boolean;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Writes the free-pi skill as `skills/free-pi/SKILL.md`, the layout OpenCode's
|
|
53
|
+
* own skill loader reads. A file without our marker is user-owned and stays
|
|
54
|
+
* untouched, exactly like the agent files.
|
|
55
|
+
*/
|
|
56
|
+
export declare function installFreePiSkill(configDir?: string): Promise<SkillInstallResult>;
|
|
@@ -79,6 +79,19 @@ MCP servers, skills, commands, references and permissions are configured in
|
|
|
79
79
|
OpenCode as usual; free-pi does not replace them. Prefer those native features
|
|
80
80
|
over running an external CLI.
|
|
81
81
|
`;
|
|
82
|
+
/**
|
|
83
|
+
* The same skill as a native `SKILL.md`. OpenCode discovers it from the global
|
|
84
|
+
* skills directory, so the file, its ID, its permissions and the `skill` tool
|
|
85
|
+
* all belong to OpenCode instead of a runtime registration.
|
|
86
|
+
*/
|
|
87
|
+
export const FREE_PI_SKILL_FILE = `---
|
|
88
|
+
name: ${FREE_PI_SKILL_NAME}
|
|
89
|
+
description: ${FREE_PI_SKILL_DESCRIPTION}
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
${MARKER}
|
|
93
|
+
|
|
94
|
+
${FREE_PI_SKILL}`;
|
|
82
95
|
const SCOUT = `---
|
|
83
96
|
description: Read-only recon. Locates code, traces how pieces connect, and returns structured findings the lead can use without re-reading the files.
|
|
84
97
|
mode: all
|
|
@@ -240,6 +253,9 @@ export function openCodeConfigDir() {
|
|
|
240
253
|
export function freePiAgentPath(configDir, id) {
|
|
241
254
|
return join(configDir, "agents", ...id.split("/")) + ".md";
|
|
242
255
|
}
|
|
256
|
+
export function freePiSkillPath(configDir) {
|
|
257
|
+
return join(configDir, "skills", FREE_PI_SKILL_ID, "SKILL.md");
|
|
258
|
+
}
|
|
243
259
|
async function fileState(path, content) {
|
|
244
260
|
try {
|
|
245
261
|
const current = await readFile(path, "utf8");
|
|
@@ -275,3 +291,21 @@ export async function installFreePiAgents(configDir = openCodeConfigDir()) {
|
|
|
275
291
|
}
|
|
276
292
|
return { installed, skipped, changed: installed.length > 0 };
|
|
277
293
|
}
|
|
294
|
+
/**
|
|
295
|
+
* Writes the free-pi skill as `skills/free-pi/SKILL.md`, the layout OpenCode's
|
|
296
|
+
* own skill loader reads. A file without our marker is user-owned and stays
|
|
297
|
+
* untouched, exactly like the agent files.
|
|
298
|
+
*/
|
|
299
|
+
export async function installFreePiSkill(configDir = openCodeConfigDir()) {
|
|
300
|
+
const path = freePiSkillPath(configDir);
|
|
301
|
+
const state = await fileState(path, FREE_PI_SKILL_FILE);
|
|
302
|
+
if (state === "same") {
|
|
303
|
+
return { installed: false, skipped: false, changed: false };
|
|
304
|
+
}
|
|
305
|
+
if (state === "protected") {
|
|
306
|
+
return { installed: false, skipped: true, changed: false };
|
|
307
|
+
}
|
|
308
|
+
await mkdir(dirname(path), { recursive: true });
|
|
309
|
+
await writeFile(path, FREE_PI_SKILL_FILE, "utf8");
|
|
310
|
+
return { installed: true, skipped: false, changed: true };
|
|
311
|
+
}
|
package/dist/catalog/live.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ import type { TokenUsageLike } from "../types.js";
|
|
|
13
13
|
export type ModelObservation = {
|
|
14
14
|
/** Largest prompt the gateway accepted for this model. */
|
|
15
15
|
maxPromptTokens?: number;
|
|
16
|
+
/** Smallest prompt the gateway rejected as too long for this model. */
|
|
17
|
+
rejectedPromptTokens?: number;
|
|
16
18
|
/** Whether a real response carried reasoning tokens. */
|
|
17
19
|
reasoning?: boolean;
|
|
18
20
|
updatedAt: number;
|
|
@@ -38,8 +40,22 @@ export declare function currentLiveLimits(): LiveLimits | undefined;
|
|
|
38
40
|
* model really reasoned for this account.
|
|
39
41
|
*/
|
|
40
42
|
export declare function noteStepTokens(_deps: Deps, modelID: string, tokens: TokenUsageLike | undefined): void;
|
|
41
|
-
/**
|
|
42
|
-
|
|
43
|
+
/**
|
|
44
|
+
* Safe context window for a model whose real ceiling is only known from a
|
|
45
|
+
* rejection. The gateway never publishes it, so the smallest prompt it refused
|
|
46
|
+
* is the only evidence available; the advertised window stays a margin below
|
|
47
|
+
* that, which lets OpenCode compact before the summarizer request is refused
|
|
48
|
+
* too.
|
|
49
|
+
*/
|
|
50
|
+
export declare function learnedContextWindow(limits: LiveLimits | undefined, modelID: string): number | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* Records a request the gateway refused as too long. Real traffic is the only
|
|
53
|
+
* probe that costs nothing, and a rejection is a hard upper bound on the
|
|
54
|
+
* model's window, so it lowers what the catalog advertises for that model from
|
|
55
|
+
* the next build on. Returns the window that now applies, if it changed.
|
|
56
|
+
*/
|
|
57
|
+
export declare function noteRejectedPrompt(deps: Deps, modelID: string, tokens: number): number | undefined;
|
|
58
|
+
/** Whether the persisted window is old enough to verify again. */ export declare function shouldVerifyWindow(limits: LiveLimits | undefined): boolean;
|
|
43
59
|
export type VerifyLimitsOptions = {
|
|
44
60
|
/** A free model to probe with; paid models would spend credits. */
|
|
45
61
|
model?: string;
|
package/dist/catalog/live.js
CHANGED
|
@@ -46,6 +46,10 @@ function sanitize(value) {
|
|
|
46
46
|
if (Number.isFinite(entry.maxPromptTokens) && entry.maxPromptTokens > 0) {
|
|
47
47
|
observation.maxPromptTokens = Math.floor(entry.maxPromptTokens);
|
|
48
48
|
}
|
|
49
|
+
if (Number.isFinite(entry.rejectedPromptTokens) &&
|
|
50
|
+
entry.rejectedPromptTokens > 0) {
|
|
51
|
+
observation.rejectedPromptTokens = Math.floor(entry.rejectedPromptTokens);
|
|
52
|
+
}
|
|
49
53
|
if (typeof entry.reasoning === "boolean") {
|
|
50
54
|
observation.reasoning = entry.reasoning;
|
|
51
55
|
}
|
|
@@ -136,8 +140,45 @@ export function noteStepTokens(_deps, modelID, tokens) {
|
|
|
136
140
|
entry.updatedAt = Date.now();
|
|
137
141
|
scheduleWrite();
|
|
138
142
|
}
|
|
139
|
-
/**
|
|
140
|
-
|
|
143
|
+
/** Keeps the advertised window this far below the smallest rejected prompt. */
|
|
144
|
+
const REJECTION_HEADROOM = 0.85;
|
|
145
|
+
/**
|
|
146
|
+
* Safe context window for a model whose real ceiling is only known from a
|
|
147
|
+
* rejection. The gateway never publishes it, so the smallest prompt it refused
|
|
148
|
+
* is the only evidence available; the advertised window stays a margin below
|
|
149
|
+
* that, which lets OpenCode compact before the summarizer request is refused
|
|
150
|
+
* too.
|
|
151
|
+
*/
|
|
152
|
+
export function learnedContextWindow(limits, modelID) {
|
|
153
|
+
const rejected = limits?.models[modelID]?.rejectedPromptTokens;
|
|
154
|
+
if (!rejected || rejected <= 0)
|
|
155
|
+
return undefined;
|
|
156
|
+
return Math.max(2_048, Math.min(Math.floor(rejected * REJECTION_HEADROOM), MAX_WINDOW));
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Records a request the gateway refused as too long. Real traffic is the only
|
|
160
|
+
* probe that costs nothing, and a rejection is a hard upper bound on the
|
|
161
|
+
* model's window, so it lowers what the catalog advertises for that model from
|
|
162
|
+
* the next build on. Returns the window that now applies, if it changed.
|
|
163
|
+
*/
|
|
164
|
+
export function noteRejectedPrompt(deps, modelID, tokens) {
|
|
165
|
+
if (!modelID || !Number.isFinite(tokens) || tokens <= 0)
|
|
166
|
+
return undefined;
|
|
167
|
+
const rejected = Math.floor(tokens);
|
|
168
|
+
const entry = observation(modelID);
|
|
169
|
+
if (entry.rejectedPromptTokens !== undefined &&
|
|
170
|
+
entry.rejectedPromptTokens <= rejected) {
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
const previous = learnedContextWindow(cached, modelID);
|
|
174
|
+
entry.rejectedPromptTokens = rejected;
|
|
175
|
+
entry.updatedAt = Date.now();
|
|
176
|
+
scheduleWrite();
|
|
177
|
+
const window = learnedContextWindow(cached, modelID);
|
|
178
|
+
deps.log.warn("free-pi rejected a prompt as too long; lowering the advertised window", { model: modelID, rejectedTokens: rejected, previous, window });
|
|
179
|
+
return window;
|
|
180
|
+
}
|
|
181
|
+
/** Whether the persisted window is old enough to verify again. */ export function shouldVerifyWindow(limits) {
|
|
141
182
|
const verifiedAt = limits?.window?.verifiedAt;
|
|
142
183
|
if (!verifiedAt)
|
|
143
184
|
return true;
|
package/dist/catalog/models.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
2
|
import { CONTEXT_WINDOW, DEFAULT_REASONING_EFFORT, DEFAULT_THINKING_LEVELS, MAX_CONTEXT_WINDOW, MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING, REASONING_EFFORTS, } from "../constants.js";
|
|
3
|
+
import { learnedContextWindow } from "./live.js";
|
|
3
4
|
import { positiveNumber } from "../utils/numbers.js";
|
|
4
5
|
import { cleanText } from "../utils/text.js";
|
|
5
6
|
export function usableModels(catalog) {
|
|
@@ -268,7 +269,11 @@ export function buildModels(models, candidates = [], options = {}) {
|
|
|
268
269
|
// never push a session past what the gateway takes.
|
|
269
270
|
const observed = options.live?.models[model.id]?.maxPromptTokens ?? 0;
|
|
270
271
|
const contextCeiling = Math.min(MAX_CONTEXT_WINDOW, Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed));
|
|
271
|
-
|
|
272
|
+
// A prompt the gateway already refused is a hard ceiling: advertise below
|
|
273
|
+
// it so OpenCode compacts before the summarization request itself is
|
|
274
|
+
// rejected, which ends the turn with the checkpoint and no answer.
|
|
275
|
+
const learned = learnedContextWindow(options.live, model.id);
|
|
276
|
+
const limitContext = Math.min(positiveNumber(model.context_window, model.contextWindow, model.limit?.context, capability?.limit?.context) ?? contextCeiling, contextCeiling, learned ?? contextCeiling);
|
|
272
277
|
// Reasoning shares the output budget. When models.dev knows the upstream
|
|
273
278
|
// model emits more than the CLI's 32k, advertise that larger budget (up to a
|
|
274
279
|
// sane ceiling) instead of truncating the chain of thought.
|
|
@@ -298,7 +303,11 @@ export function buildModels(models, candidates = [], options = {}) {
|
|
|
298
303
|
...(defaultEffort ? { settings: { reasoningEffort: defaultEffort } } : {}),
|
|
299
304
|
enabled: model.unavailable !== true,
|
|
300
305
|
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
301
|
-
|
|
306
|
+
// All free models were probed against the gateway and call tools, so a
|
|
307
|
+
// models.dev entry that marks the matched upstream as text-only must not
|
|
308
|
+
// take away their tools. That would also hide OpenCode's native
|
|
309
|
+
// `subagent` tool. A `tool_call` value in free-pi's own catalog still wins.
|
|
310
|
+
tool_call: model.tool_call ?? (model.free === true ? true : capability?.tool_call ?? true),
|
|
302
311
|
attachment: model.attachment ??
|
|
303
312
|
capability?.attachment ??
|
|
304
313
|
modalities.input.includes("image"),
|
package/dist/constants.d.ts
CHANGED
|
@@ -50,7 +50,7 @@ export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low"
|
|
|
50
50
|
* models show: skipping analysis, inventing verification, and ignoring the
|
|
51
51
|
* context the conversation already established.
|
|
52
52
|
*/
|
|
53
|
-
export declare const FREE_PI_GUIDANCE = "# free-pi working rules\n- Answer the user's latest request and keep their constraints; do not switch to a different task.\n- Slow down on multi-step work (arithmetic, counting, logic, dates, units, planning, debugging): write out each step, recompute the result a second way, and only then answer. On those tasks a correct answer after a dozen explicit steps beats a fast guess; do not stop at the first plausible number.\n- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.\n- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.\n- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.\n- Never claim to have compacted, summarized or cleared context unless that actually happened.\n- Continue until the request is finished, then report concisely what changed and what you verified.";
|
|
53
|
+
export declare const FREE_PI_GUIDANCE = "# free-pi working rules\n- Answer the user's latest request and keep their constraints; do not switch to a different task.\n- Slow down on multi-step work (arithmetic, counting, logic, dates, units, planning, debugging): write out each step, recompute the result a second way, and only then answer. On those tasks a correct answer after a dozen explicit steps beats a fast guess; do not stop at the first plausible number.\n- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.\n- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.\n- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.\n- Delegate large or self-contained work with OpenCode's native `subagent` tool: `free-pi/scout` and `free-pi/planner` for read-only recon and planning, `free-pi/worker` for a full task, `free-pi/reviewer` for review. A subagent runs in its own context and reports back; never launch a subagent from inside one.\n- Load a skill with the native `skill` tool when its description matches the task.\n- `AGENTS.md` and the files listed under `instructions` are the project's memory. Follow them; do not restate or replace them.\n- Never claim to have compacted, summarized or cleared context unless that actually happened.\n- Continue until the request is finished, then report concisely what changed and what you verified.";
|
|
54
54
|
export declare const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
|
|
55
55
|
/**
|
|
56
56
|
* Appended to OpenCode's compaction request. Its default summary prompt asks
|
package/dist/constants.js
CHANGED
|
@@ -70,6 +70,9 @@ export const FREE_PI_GUIDANCE = `# free-pi working rules
|
|
|
70
70
|
- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.
|
|
71
71
|
- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.
|
|
72
72
|
- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.
|
|
73
|
+
- Delegate large or self-contained work with OpenCode's native \`subagent\` tool: \`free-pi/scout\` and \`free-pi/planner\` for read-only recon and planning, \`free-pi/worker\` for a full task, \`free-pi/reviewer\` for review. A subagent runs in its own context and reports back; never launch a subagent from inside one.
|
|
74
|
+
- Load a skill with the native \`skill\` tool when its description matches the task.
|
|
75
|
+
- \`AGENTS.md\` and the files listed under \`instructions\` are the project's memory. Follow them; do not restate or replace them.
|
|
73
76
|
- Never claim to have compacted, summarized or cleared context unless that actually happened.
|
|
74
77
|
- Continue until the request is finished, then report concisely what changed and what you verified.`;
|
|
75
78
|
export const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
|
package/dist/plugin.js
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
/** OpenCode V2 plugin entry point for free-pi. */
|
|
2
2
|
import { Plugin } from "@opencode/plugin";
|
|
3
|
-
import {
|
|
4
|
-
import { FREE_PI_SKILL, FREE_PI_SKILL_DESCRIPTION, FREE_PI_SKILL_ID, FREE_PI_SKILL_NAME, installFreePiAgents, openCodeConfigDir, } from "./agents/definitions.js";
|
|
3
|
+
import { FREE_PI_SKILL, FREE_PI_SKILL_DESCRIPTION, FREE_PI_SKILL_ID, FREE_PI_SKILL_NAME, freePiSkillPath, installFreePiAgents, installFreePiSkill, openCodeConfigDir, } from "./agents/definitions.js";
|
|
5
4
|
import { fetchQuota } from "./api/quota.js";
|
|
6
5
|
import { closeFreePiSession } from "./api/session.js";
|
|
7
6
|
import { readCredentialsToken } from "./auth/credentials.js";
|
|
8
7
|
import { tokenFromCredential } from "./auth/credential.js";
|
|
9
8
|
import { fetchCatalog } from "./catalog/catalog.js";
|
|
10
|
-
import { loadLiveLimits, shouldVerifyWindow, verifyGatewayWindow, } from "./catalog/live.js";
|
|
9
|
+
import { currentLiveLimits, loadLiveLimits, shouldVerifyWindow, verifyGatewayWindow, } from "./catalog/live.js";
|
|
11
10
|
import { accountAccess, buildModels, filterAccessibleModels, isReasoningEffort, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
|
|
12
11
|
import { fetchModelsRegistry } from "./catalog/registry.js";
|
|
13
12
|
import { applyProvider } from "./catalog/v2.js";
|
|
@@ -71,6 +70,23 @@ async function setup(ctx) {
|
|
|
71
70
|
catch (error) {
|
|
72
71
|
log.warn("Could not install the free-pi subagents", error);
|
|
73
72
|
}
|
|
73
|
+
// OpenCode's own skill loader reads `skills/free-pi/SKILL.md`. Install the
|
|
74
|
+
// file first so the skill has a real path, supporting files and permissions
|
|
75
|
+
// like any other native skill; the transform below only fills the gap when
|
|
76
|
+
// the config directory is not writable.
|
|
77
|
+
try {
|
|
78
|
+
const skill = await installFreePiSkill();
|
|
79
|
+
if (skill.changed) {
|
|
80
|
+
await ctx.skill.reload();
|
|
81
|
+
log.info("Installed the native free-pi skill");
|
|
82
|
+
}
|
|
83
|
+
if (skill.skipped) {
|
|
84
|
+
log.warn("Left the user-owned free-pi skill file untouched", freePiSkillPath(openCodeConfigDir()));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
log.warn("Could not install the free-pi skill file", error);
|
|
89
|
+
}
|
|
74
90
|
try {
|
|
75
91
|
nativeRegistrations.push(await ctx.skill.transform((editor) => {
|
|
76
92
|
if (editor.get(FREE_PI_SKILL_ID))
|
|
@@ -79,7 +95,7 @@ async function setup(ctx) {
|
|
|
79
95
|
id: FREE_PI_SKILL_ID,
|
|
80
96
|
name: FREE_PI_SKILL_NAME,
|
|
81
97
|
description: FREE_PI_SKILL_DESCRIPTION,
|
|
82
|
-
path:
|
|
98
|
+
path: freePiSkillPath(openCodeConfigDir()),
|
|
83
99
|
content: FREE_PI_SKILL,
|
|
84
100
|
});
|
|
85
101
|
}));
|
|
@@ -133,9 +149,15 @@ async function setup(ctx) {
|
|
|
133
149
|
tokenFromCredential(credential) ?? (await readCredentialsToken());
|
|
134
150
|
await registerIntegration(ctx, deps);
|
|
135
151
|
await ctx.provider.transform((editor) => {
|
|
136
|
-
|
|
152
|
+
// Rebuilt on every transform so a learned context ceiling applies as soon
|
|
153
|
+
// as the response hook records it, without restarting OpenCode.
|
|
154
|
+
const active = currentLiveLimits() ?? live;
|
|
155
|
+
const buildOptionsNow = { ...buildOptions, live: active };
|
|
156
|
+
const mainNow = buildModels(main, candidates, buildOptionsNow);
|
|
157
|
+
const defenseNow = buildModels(defense, candidates, buildOptionsNow);
|
|
158
|
+
applyProvider(editor, PROVIDER_ID, "Free Pi", mainNow, state.providerToken);
|
|
137
159
|
if (includeDefense && defense.length > 0) {
|
|
138
|
-
applyProvider(editor, DEFENSE_PROVIDER_ID, "Free Pi Defense",
|
|
160
|
+
applyProvider(editor, DEFENSE_PROVIDER_ID, "Free Pi Defense", defenseNow, state.providerToken);
|
|
139
161
|
}
|
|
140
162
|
});
|
|
141
163
|
// The gateway does not publish its context ceiling. Verify the compiled
|
package/dist/session/hooks.js
CHANGED
|
@@ -3,10 +3,12 @@ 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 { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, DEFENSE_PROVIDER_ID, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER, MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, } from "../constants.js";
|
|
6
|
+
import { currentLiveLimits, learnedContextWindow, noteRejectedPrompt, } from "../catalog/live.js";
|
|
6
7
|
import { closeFreePiSession } from "../api/session.js";
|
|
7
8
|
import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
|
|
8
9
|
import { parseFreePiError } from "../errors/parse.js";
|
|
9
10
|
import { trimMap } from "../utils/async.js";
|
|
11
|
+
import { trimMessagesForBudget } from "./overflow.js";
|
|
10
12
|
import { watchFreePiNotice } from "./notices.js";
|
|
11
13
|
import { clearSpuriousOverflows, noteSpuriousOverflow, overflowingSpuriously, spuriousOverflowResponse, } from "./overflow.js";
|
|
12
14
|
import { rememberReplayBody, replayConcurrentResponse, replaySpuriousOverflow, } from "./replay.js";
|
|
@@ -27,6 +29,32 @@ function rememberPending(deps, key, turn) {
|
|
|
27
29
|
trimMap(deps.state.pendingAdTurns, PENDING_LIMIT);
|
|
28
30
|
deps.state.pendingAdTurns.set(key, turn);
|
|
29
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Fits the compaction request inside the ceiling the gateway has already
|
|
34
|
+
* proven. OpenCode aborts the turn ("the compaction request cannot be reduced
|
|
35
|
+
* further") when the summarizer request is rejected too, so the plugin drops
|
|
36
|
+
* the oldest user turns before that can happen.
|
|
37
|
+
*/
|
|
38
|
+
function fitCompactionMessages(deps, event) {
|
|
39
|
+
const modelID = typeof event.model?.id === "string" ? event.model.id : "";
|
|
40
|
+
const ceiling = learnedContextWindow(currentLiveLimits(), modelID);
|
|
41
|
+
if (!ceiling)
|
|
42
|
+
return;
|
|
43
|
+
const messages = event.messages;
|
|
44
|
+
if (!Array.isArray(messages) || messages.length === 0)
|
|
45
|
+
return;
|
|
46
|
+
const trimmed = trimMessagesForBudget(messages, Math.floor(ceiling * 0.9));
|
|
47
|
+
if (trimmed.dropped === 0)
|
|
48
|
+
return;
|
|
49
|
+
event.messages = [...trimmed.messages];
|
|
50
|
+
deps.log.warn("free-pi trimmed the compaction request to fit the learned window", {
|
|
51
|
+
sessionID: event.sessionID,
|
|
52
|
+
model: modelID,
|
|
53
|
+
window: ceiling,
|
|
54
|
+
droppedMessages: trimmed.dropped,
|
|
55
|
+
promptTokens: trimmed.tokens,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
30
58
|
/** Adds a system block once, even when OpenCode reuses the same event. */
|
|
31
59
|
function appendSystemGuidance(event, text, marker) {
|
|
32
60
|
const system = Array.isArray(event.system) ? event.system : [];
|
|
@@ -52,15 +80,18 @@ async function applyGeneration(deps, event, kind) {
|
|
|
52
80
|
}
|
|
53
81
|
const modelID = event.model?.id;
|
|
54
82
|
const limit = deps.state.outputLimits.get(`${event.model.providerID}/${modelID}`);
|
|
55
|
-
//
|
|
56
|
-
//
|
|
83
|
+
// The compaction summary is the one response that must never be cut: a
|
|
84
|
+
// summary that reaches the output limit fails the whole compaction and the
|
|
85
|
+
// turn stops with nothing but the checkpoint. Leave OpenCode's own budget
|
|
86
|
+
// for it and only cap the answers the user reads.
|
|
57
87
|
const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING);
|
|
58
|
-
if (event.options) {
|
|
88
|
+
if (event.options && kind !== "compaction") {
|
|
59
89
|
const current = event.options.maxTokens;
|
|
60
90
|
if (current === undefined || current > cap)
|
|
61
91
|
event.options.maxTokens = cap;
|
|
62
92
|
}
|
|
63
93
|
if (kind === "compaction") {
|
|
94
|
+
fitCompactionMessages(deps, event);
|
|
64
95
|
appendSystemGuidance(event, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER);
|
|
65
96
|
// OpenCode sends the messages it is folding into the summary, which is the
|
|
66
97
|
// same set pi reports through `session_before_compact`.
|
|
@@ -363,6 +394,20 @@ export async function registerSessionHooks(ctx, deps) {
|
|
|
363
394
|
// window. Compacting then loops, so retry on a fresh wire session
|
|
364
395
|
// first, and stop compacting once the session has seen a few.
|
|
365
396
|
const reviewed = await replaySpuriousOverflow(deps, event).catch(() => ({}));
|
|
397
|
+
// A rejection of a real prompt is the only free measurement of the
|
|
398
|
+
// gateway's ceiling. Attachments inflate the estimate and say nothing
|
|
399
|
+
// about the text window, so they are not learned from.
|
|
400
|
+
if (reviewed.spurious === false &&
|
|
401
|
+
typeof reviewed.tokens === "number" &&
|
|
402
|
+
reviewed.model &&
|
|
403
|
+
reviewed.hasMedia !== true) {
|
|
404
|
+
const learned = noteRejectedPrompt(deps, reviewed.model, reviewed.tokens);
|
|
405
|
+
// Re-run the provider transform so this session's next compaction
|
|
406
|
+
// already targets the smaller window; no restart needed.
|
|
407
|
+
if (learned) {
|
|
408
|
+
void ctx.provider.reload().catch(() => undefined);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
366
411
|
if (reviewed.response) {
|
|
367
412
|
clearSpuriousOverflows(deps, event.sessionID);
|
|
368
413
|
event.response = watchFreePiNotice(deps, reviewed.response);
|
|
@@ -17,12 +17,43 @@ import type { Deps } from "../deps.js";
|
|
|
17
17
|
/** A request below this many tokens cannot exhaust a 200k window on its own. */
|
|
18
18
|
export declare const SPURIOUS_OVERFLOW_TOKENS = 60000;
|
|
19
19
|
export declare const SPURIOUS_OVERFLOW_MESSAGE: string;
|
|
20
|
+
export type RequestProfile = {
|
|
21
|
+
/** Approximate token count of the whole body. */
|
|
22
|
+
readonly tokens: number;
|
|
23
|
+
/** The upstream model the body asks for, when it can be read. */
|
|
24
|
+
readonly model?: string;
|
|
25
|
+
/** Whether the body carries an inline image or file. */
|
|
26
|
+
readonly hasMedia: boolean;
|
|
27
|
+
};
|
|
20
28
|
/**
|
|
21
29
|
* Approximate token count of a chat-completions body: every string in it,
|
|
22
30
|
* message text and tool output alike, at the usual four characters per token.
|
|
23
31
|
* Inline media counts at its base64 length, which is what the provider bills.
|
|
32
|
+
*
|
|
33
|
+
* The same walk reports the requested model and whether the body carries
|
|
34
|
+
* inline media. A rejection caused by a large attachment says nothing about
|
|
35
|
+
* the model's text window, so callers must not learn a ceiling from it.
|
|
24
36
|
*/
|
|
37
|
+
export declare function profileRequest(body: string): RequestProfile;
|
|
38
|
+
/** Token count of a request body, without the extra facts. */
|
|
25
39
|
export declare function measureRequestTokens(body: string): number;
|
|
40
|
+
/** Cheap per-message estimate; the body is serialized once per message. */
|
|
41
|
+
export declare function estimateMessageTokens(message: unknown): number;
|
|
42
|
+
/**
|
|
43
|
+
* Keeps the newest part of a message list inside `budget` tokens, cutting only
|
|
44
|
+
* at user turns so an assistant tool call never loses its results.
|
|
45
|
+
*
|
|
46
|
+
* OpenCode refuses to compact when the summarization request itself is still
|
|
47
|
+
* too large, and then the turn dies with nothing but the checkpoint shown. The
|
|
48
|
+
* gateway's real ceiling is lower than the advertised window, so the plugin
|
|
49
|
+
* trims the oldest turns it can spare before the summarizer is asked to read
|
|
50
|
+
* them.
|
|
51
|
+
*/
|
|
52
|
+
export declare function trimMessagesForBudget(messages: readonly unknown[], budget: number): {
|
|
53
|
+
readonly messages: readonly unknown[];
|
|
54
|
+
readonly dropped: number;
|
|
55
|
+
readonly tokens: number;
|
|
56
|
+
};
|
|
26
57
|
/**
|
|
27
58
|
* Records a rejection of a request that fits, and returns the number of them
|
|
28
59
|
* seen for the session inside the current window. A run of them means the
|
package/dist/session/overflow.js
CHANGED
|
@@ -22,18 +22,35 @@ const STORM_LIMIT = 2;
|
|
|
22
22
|
const STORM_LIMIT_PER_SESSION = 512;
|
|
23
23
|
export const SPURIOUS_OVERFLOW_MESSAGE = "free-pi rejected this request as too long even though it fits the model's window; " +
|
|
24
24
|
"this is a provider failure, not a context overflow. Retry the message, or start a new session if it persists.";
|
|
25
|
+
/** Part types that carry an inline image or file, which the provider bills in full. */
|
|
26
|
+
const MEDIA_PART_TYPES = new Set([
|
|
27
|
+
"image",
|
|
28
|
+
"image_url",
|
|
29
|
+
"input_image",
|
|
30
|
+
"file",
|
|
31
|
+
"input_file",
|
|
32
|
+
]);
|
|
25
33
|
/**
|
|
26
34
|
* Approximate token count of a chat-completions body: every string in it,
|
|
27
35
|
* message text and tool output alike, at the usual four characters per token.
|
|
28
36
|
* Inline media counts at its base64 length, which is what the provider bills.
|
|
37
|
+
*
|
|
38
|
+
* The same walk reports the requested model and whether the body carries
|
|
39
|
+
* inline media. A rejection caused by a large attachment says nothing about
|
|
40
|
+
* the model's text window, so callers must not learn a ceiling from it.
|
|
29
41
|
*/
|
|
30
|
-
export function
|
|
42
|
+
export function profileRequest(body) {
|
|
31
43
|
try {
|
|
32
44
|
const data = JSON.parse(body);
|
|
33
45
|
let chars = 0;
|
|
46
|
+
let model;
|
|
47
|
+
let hasMedia = false;
|
|
34
48
|
const walk = (value) => {
|
|
35
49
|
if (typeof value === "string") {
|
|
36
50
|
chars += value.length;
|
|
51
|
+
if (value.startsWith("data:image/") || value.startsWith("data:application/")) {
|
|
52
|
+
hasMedia = true;
|
|
53
|
+
}
|
|
37
54
|
return;
|
|
38
55
|
}
|
|
39
56
|
if (Array.isArray(value)) {
|
|
@@ -42,18 +59,79 @@ export function measureRequestTokens(body) {
|
|
|
42
59
|
return;
|
|
43
60
|
}
|
|
44
61
|
if (value && typeof value === "object") {
|
|
45
|
-
|
|
62
|
+
const record = value;
|
|
63
|
+
if (typeof record.type === "string" && MEDIA_PART_TYPES.has(record.type)) {
|
|
64
|
+
hasMedia = true;
|
|
65
|
+
}
|
|
66
|
+
if (model === undefined &&
|
|
67
|
+
typeof record.model === "string" &&
|
|
68
|
+
record.model.length > 0) {
|
|
69
|
+
model = record.model;
|
|
70
|
+
}
|
|
71
|
+
for (const [key, item] of Object.entries(record)) {
|
|
46
72
|
chars += key.length;
|
|
47
73
|
walk(item);
|
|
48
74
|
}
|
|
49
75
|
}
|
|
50
76
|
};
|
|
51
77
|
walk(data);
|
|
52
|
-
return Math.ceil(chars / 4);
|
|
78
|
+
return { tokens: Math.ceil(chars / 4), model, hasMedia };
|
|
53
79
|
}
|
|
54
80
|
catch {
|
|
55
|
-
return Math.ceil(body.length / 4);
|
|
81
|
+
return { tokens: Math.ceil(body.length / 4), hasMedia: false };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** Token count of a request body, without the extra facts. */
|
|
85
|
+
export function measureRequestTokens(body) {
|
|
86
|
+
return profileRequest(body).tokens;
|
|
87
|
+
}
|
|
88
|
+
/** Cheap per-message estimate; the body is serialized once per message. */
|
|
89
|
+
export function estimateMessageTokens(message) {
|
|
90
|
+
try {
|
|
91
|
+
return Math.ceil(JSON.stringify(message).length / 4);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return 0;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Keeps the newest part of a message list inside `budget` tokens, cutting only
|
|
99
|
+
* at user turns so an assistant tool call never loses its results.
|
|
100
|
+
*
|
|
101
|
+
* OpenCode refuses to compact when the summarization request itself is still
|
|
102
|
+
* too large, and then the turn dies with nothing but the checkpoint shown. The
|
|
103
|
+
* gateway's real ceiling is lower than the advertised window, so the plugin
|
|
104
|
+
* trims the oldest turns it can spare before the summarizer is asked to read
|
|
105
|
+
* them.
|
|
106
|
+
*/
|
|
107
|
+
export function trimMessagesForBudget(messages, budget) {
|
|
108
|
+
if (messages.length === 0)
|
|
109
|
+
return { messages, dropped: 0, tokens: 0 };
|
|
110
|
+
const sizes = messages.map(estimateMessageTokens);
|
|
111
|
+
let total = 0;
|
|
112
|
+
for (const size of sizes)
|
|
113
|
+
total += size;
|
|
114
|
+
if (total <= budget)
|
|
115
|
+
return { messages, dropped: 0, tokens: total };
|
|
116
|
+
const cuts = [];
|
|
117
|
+
for (let index = 1; index < messages.length; index += 1) {
|
|
118
|
+
const role = messages[index]?.role;
|
|
119
|
+
if (role === "user")
|
|
120
|
+
cuts.push(index);
|
|
121
|
+
}
|
|
122
|
+
for (const cut of cuts) {
|
|
123
|
+
let tail = 0;
|
|
124
|
+
for (let index = cut; index < sizes.length; index += 1)
|
|
125
|
+
tail += sizes[index];
|
|
126
|
+
if (tail <= budget) {
|
|
127
|
+
return { messages: messages.slice(cut), dropped: cut, tokens: tail };
|
|
128
|
+
}
|
|
56
129
|
}
|
|
130
|
+
const last = cuts.length > 0 ? cuts[cuts.length - 1] : messages.length - 1;
|
|
131
|
+
let tail = 0;
|
|
132
|
+
for (let index = last; index < sizes.length; index += 1)
|
|
133
|
+
tail += sizes[index];
|
|
134
|
+
return { messages: messages.slice(last), dropped: last, tokens: tail };
|
|
57
135
|
}
|
|
58
136
|
/**
|
|
59
137
|
* Records a rejection of a request that fits, and returns the number of them
|
package/dist/session/replay.d.ts
CHANGED
|
@@ -24,6 +24,10 @@ export declare function replayConcurrentResponse(deps: Deps, event: any): Promis
|
|
|
24
24
|
export type OverflowReplay = {
|
|
25
25
|
/** Tokens of the rejected request, when its body was available. */
|
|
26
26
|
readonly tokens?: number;
|
|
27
|
+
/** Upstream model the rejected request asked for. */
|
|
28
|
+
readonly model?: string;
|
|
29
|
+
/** Whether the rejected request carried an inline image or file. */
|
|
30
|
+
readonly hasMedia?: boolean;
|
|
27
31
|
/** Whether the rejected request plainly fits the model window. */
|
|
28
32
|
readonly spurious?: boolean;
|
|
29
33
|
/** A good response from a fresh wire session, when the retry succeeded. */
|
package/dist/session/replay.js
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
import { closeFreePiSession } from "../api/session.js";
|
|
17
17
|
import { overflowCodeOf } from "../errors/limit.js";
|
|
18
18
|
import { sleep, trimMap } from "../utils/async.js";
|
|
19
|
-
import {
|
|
19
|
+
import { profileRequest, SPURIOUS_OVERFLOW_TOKENS, } from "./overflow.js";
|
|
20
20
|
import { rotateWireSessionID, wireSessionID } from "./wire.js";
|
|
21
21
|
const REPLAY_BODY_LIMIT = 24;
|
|
22
22
|
const REPLAY_MAX_ATTEMPTS = 4;
|
|
@@ -152,13 +152,16 @@ export async function replaySpuriousOverflow(deps, event) {
|
|
|
152
152
|
const body = await storedBody(deps, event);
|
|
153
153
|
if (!body)
|
|
154
154
|
return {};
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
155
|
+
const profile = profileRequest(body);
|
|
156
|
+
const tokens = profile.tokens;
|
|
157
|
+
const facts = { model: profile.model, hasMedia: profile.hasMedia };
|
|
158
|
+
if (tokens >= SPURIOUS_OVERFLOW_TOKENS) {
|
|
159
|
+
return { tokens, ...facts, spurious: false };
|
|
160
|
+
}
|
|
158
161
|
let previous = request.headers.get("x-session-id") ?? wireSessionID(deps, event.sessionID);
|
|
159
162
|
for (let attempt = 1; attempt <= OVERFLOW_REPLAY_ATTEMPTS; attempt++) {
|
|
160
163
|
if (request.signal.aborted)
|
|
161
|
-
return { tokens, spurious: true };
|
|
164
|
+
return { tokens, ...facts, spurious: true };
|
|
162
165
|
const next = rotateWireSessionID(deps, event.sessionID);
|
|
163
166
|
if (previous && previous !== next) {
|
|
164
167
|
void closeFreePiSession(deps, previous).catch(() => undefined);
|
|
@@ -178,9 +181,9 @@ export async function replaySpuriousOverflow(deps, event) {
|
|
|
178
181
|
continue;
|
|
179
182
|
if (!(await overflowCodeOf(response))) {
|
|
180
183
|
deps.log.info("free-pi rejected a request that fits as too long; replayed it on a fresh session id", { sessionID: event.sessionID, tokens, to: next, attempt });
|
|
181
|
-
return { tokens, spurious: true, response };
|
|
184
|
+
return { tokens, ...facts, spurious: true, response };
|
|
182
185
|
}
|
|
183
186
|
}
|
|
184
187
|
deps.log.info("free-pi keeps rejecting a request that fits as too long; the provider is failing", { sessionID: event.sessionID, tokens });
|
|
185
|
-
return { tokens, spurious: true };
|
|
188
|
+
return { tokens, ...facts, spurious: true };
|
|
186
189
|
}
|
package/package.json
CHANGED
|
@@ -89,6 +89,20 @@ OpenCode as usual; free-pi does not replace them. Prefer those native features
|
|
|
89
89
|
over running an external CLI.
|
|
90
90
|
`;
|
|
91
91
|
|
|
92
|
+
/**
|
|
93
|
+
* The same skill as a native `SKILL.md`. OpenCode discovers it from the global
|
|
94
|
+
* skills directory, so the file, its ID, its permissions and the `skill` tool
|
|
95
|
+
* all belong to OpenCode instead of a runtime registration.
|
|
96
|
+
*/
|
|
97
|
+
export const FREE_PI_SKILL_FILE = `---
|
|
98
|
+
name: ${FREE_PI_SKILL_NAME}
|
|
99
|
+
description: ${FREE_PI_SKILL_DESCRIPTION}
|
|
100
|
+
---
|
|
101
|
+
|
|
102
|
+
${MARKER}
|
|
103
|
+
|
|
104
|
+
${FREE_PI_SKILL}`;
|
|
105
|
+
|
|
92
106
|
const SCOUT = `---
|
|
93
107
|
description: Read-only recon. Locates code, traces how pieces connect, and returns structured findings the lead can use without re-reading the files.
|
|
94
108
|
mode: all
|
|
@@ -255,6 +269,10 @@ export function freePiAgentPath(configDir: string, id: FreePiAgentID): string {
|
|
|
255
269
|
return join(configDir, "agents", ...id.split("/")) + ".md";
|
|
256
270
|
}
|
|
257
271
|
|
|
272
|
+
export function freePiSkillPath(configDir: string): string {
|
|
273
|
+
return join(configDir, "skills", FREE_PI_SKILL_ID, "SKILL.md");
|
|
274
|
+
}
|
|
275
|
+
|
|
258
276
|
async function fileState(
|
|
259
277
|
path: string,
|
|
260
278
|
content: string,
|
|
@@ -301,3 +319,30 @@ export async function installFreePiAgents(
|
|
|
301
319
|
|
|
302
320
|
return { installed, skipped, changed: installed.length > 0 };
|
|
303
321
|
}
|
|
322
|
+
|
|
323
|
+
export type SkillInstallResult = {
|
|
324
|
+
readonly installed: boolean;
|
|
325
|
+
readonly skipped: boolean;
|
|
326
|
+
readonly changed: boolean;
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Writes the free-pi skill as `skills/free-pi/SKILL.md`, the layout OpenCode's
|
|
331
|
+
* own skill loader reads. A file without our marker is user-owned and stays
|
|
332
|
+
* untouched, exactly like the agent files.
|
|
333
|
+
*/
|
|
334
|
+
export async function installFreePiSkill(
|
|
335
|
+
configDir = openCodeConfigDir(),
|
|
336
|
+
): Promise<SkillInstallResult> {
|
|
337
|
+
const path = freePiSkillPath(configDir);
|
|
338
|
+
const state = await fileState(path, FREE_PI_SKILL_FILE);
|
|
339
|
+
if (state === "same") {
|
|
340
|
+
return { installed: false, skipped: false, changed: false };
|
|
341
|
+
}
|
|
342
|
+
if (state === "protected") {
|
|
343
|
+
return { installed: false, skipped: true, changed: false };
|
|
344
|
+
}
|
|
345
|
+
await mkdir(dirname(path), { recursive: true });
|
|
346
|
+
await writeFile(path, FREE_PI_SKILL_FILE, "utf8");
|
|
347
|
+
return { installed: true, skipped: false, changed: true };
|
|
348
|
+
}
|
package/src/catalog/live.ts
CHANGED
|
@@ -37,6 +37,8 @@ const INITIAL_CHARS_PER_TOKEN = 4;
|
|
|
37
37
|
export type ModelObservation = {
|
|
38
38
|
/** Largest prompt the gateway accepted for this model. */
|
|
39
39
|
maxPromptTokens?: number;
|
|
40
|
+
/** Smallest prompt the gateway rejected as too long for this model. */
|
|
41
|
+
rejectedPromptTokens?: number;
|
|
40
42
|
/** Whether a real response carried reasoning tokens. */
|
|
41
43
|
reasoning?: boolean;
|
|
42
44
|
updatedAt: number;
|
|
@@ -71,6 +73,14 @@ function sanitize(value: unknown): LiveLimits {
|
|
|
71
73
|
if (Number.isFinite(entry.maxPromptTokens) && entry.maxPromptTokens! > 0) {
|
|
72
74
|
observation.maxPromptTokens = Math.floor(entry.maxPromptTokens!);
|
|
73
75
|
}
|
|
76
|
+
if (
|
|
77
|
+
Number.isFinite(entry.rejectedPromptTokens) &&
|
|
78
|
+
entry.rejectedPromptTokens! > 0
|
|
79
|
+
) {
|
|
80
|
+
observation.rejectedPromptTokens = Math.floor(
|
|
81
|
+
entry.rejectedPromptTokens!,
|
|
82
|
+
);
|
|
83
|
+
}
|
|
74
84
|
if (typeof entry.reasoning === "boolean") {
|
|
75
85
|
observation.reasoning = entry.reasoning;
|
|
76
86
|
}
|
|
@@ -166,8 +176,61 @@ export function noteStepTokens(
|
|
|
166
176
|
scheduleWrite();
|
|
167
177
|
}
|
|
168
178
|
|
|
169
|
-
/**
|
|
170
|
-
|
|
179
|
+
/** Keeps the advertised window this far below the smallest rejected prompt. */
|
|
180
|
+
const REJECTION_HEADROOM = 0.85;
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Safe context window for a model whose real ceiling is only known from a
|
|
184
|
+
* rejection. The gateway never publishes it, so the smallest prompt it refused
|
|
185
|
+
* is the only evidence available; the advertised window stays a margin below
|
|
186
|
+
* that, which lets OpenCode compact before the summarizer request is refused
|
|
187
|
+
* too.
|
|
188
|
+
*/
|
|
189
|
+
export function learnedContextWindow(
|
|
190
|
+
limits: LiveLimits | undefined,
|
|
191
|
+
modelID: string,
|
|
192
|
+
): number | undefined {
|
|
193
|
+
const rejected = limits?.models[modelID]?.rejectedPromptTokens;
|
|
194
|
+
if (!rejected || rejected <= 0) return undefined;
|
|
195
|
+
return Math.max(2_048, Math.min(
|
|
196
|
+
Math.floor(rejected * REJECTION_HEADROOM),
|
|
197
|
+
MAX_WINDOW,
|
|
198
|
+
));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Records a request the gateway refused as too long. Real traffic is the only
|
|
203
|
+
* probe that costs nothing, and a rejection is a hard upper bound on the
|
|
204
|
+
* model's window, so it lowers what the catalog advertises for that model from
|
|
205
|
+
* the next build on. Returns the window that now applies, if it changed.
|
|
206
|
+
*/
|
|
207
|
+
export function noteRejectedPrompt(
|
|
208
|
+
deps: Deps,
|
|
209
|
+
modelID: string,
|
|
210
|
+
tokens: number,
|
|
211
|
+
): number | undefined {
|
|
212
|
+
if (!modelID || !Number.isFinite(tokens) || tokens <= 0) return undefined;
|
|
213
|
+
const rejected = Math.floor(tokens);
|
|
214
|
+
const entry = observation(modelID);
|
|
215
|
+
if (
|
|
216
|
+
entry.rejectedPromptTokens !== undefined &&
|
|
217
|
+
entry.rejectedPromptTokens <= rejected
|
|
218
|
+
) {
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
const previous = learnedContextWindow(cached, modelID);
|
|
222
|
+
entry.rejectedPromptTokens = rejected;
|
|
223
|
+
entry.updatedAt = Date.now();
|
|
224
|
+
scheduleWrite();
|
|
225
|
+
const window = learnedContextWindow(cached, modelID);
|
|
226
|
+
deps.log.warn(
|
|
227
|
+
"free-pi rejected a prompt as too long; lowering the advertised window",
|
|
228
|
+
{ model: modelID, rejectedTokens: rejected, previous, window },
|
|
229
|
+
);
|
|
230
|
+
return window;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Whether the persisted window is old enough to verify again. */export function shouldVerifyWindow(limits: LiveLimits | undefined): boolean {
|
|
171
234
|
const verifiedAt = limits?.window?.verifiedAt;
|
|
172
235
|
if (!verifiedAt) return true;
|
|
173
236
|
return Date.now() - verifiedAt > VERIFY_LIMITS_TTL_MS;
|
package/src/catalog/models.ts
CHANGED
|
@@ -20,6 +20,7 @@ import type {
|
|
|
20
20
|
RegistryCandidate,
|
|
21
21
|
} from "../types.js";
|
|
22
22
|
import type { LiveLimits } from "./live.js";
|
|
23
|
+
import { learnedContextWindow } from "./live.js";
|
|
23
24
|
import { positiveNumber } from "../utils/numbers.js";
|
|
24
25
|
import { cleanText } from "../utils/text.js";
|
|
25
26
|
|
|
@@ -376,6 +377,10 @@ export function buildModels(
|
|
|
376
377
|
MAX_CONTEXT_WINDOW,
|
|
377
378
|
Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed),
|
|
378
379
|
);
|
|
380
|
+
// A prompt the gateway already refused is a hard ceiling: advertise below
|
|
381
|
+
// it so OpenCode compacts before the summarization request itself is
|
|
382
|
+
// rejected, which ends the turn with the checkpoint and no answer.
|
|
383
|
+
const learned = learnedContextWindow(options.live, model.id);
|
|
379
384
|
const limitContext = Math.min(
|
|
380
385
|
positiveNumber(
|
|
381
386
|
model.context_window,
|
|
@@ -384,6 +389,7 @@ export function buildModels(
|
|
|
384
389
|
capability?.limit?.context,
|
|
385
390
|
) ?? contextCeiling,
|
|
386
391
|
contextCeiling,
|
|
392
|
+
learned ?? contextCeiling,
|
|
387
393
|
);
|
|
388
394
|
// Reasoning shares the output budget. When models.dev knows the upstream
|
|
389
395
|
// model emits more than the CLI's 32k, advertise that larger budget (up to a
|
|
@@ -424,7 +430,11 @@ export function buildModels(
|
|
|
424
430
|
...(defaultEffort ? { settings: { reasoningEffort: defaultEffort } } : {}),
|
|
425
431
|
enabled: model.unavailable !== true,
|
|
426
432
|
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
427
|
-
|
|
433
|
+
// All free models were probed against the gateway and call tools, so a
|
|
434
|
+
// models.dev entry that marks the matched upstream as text-only must not
|
|
435
|
+
// take away their tools. That would also hide OpenCode's native
|
|
436
|
+
// `subagent` tool. A `tool_call` value in free-pi's own catalog still wins.
|
|
437
|
+
tool_call: model.tool_call ?? (model.free === true ? true : capability?.tool_call ?? true),
|
|
428
438
|
attachment:
|
|
429
439
|
model.attachment ??
|
|
430
440
|
capability?.attachment ??
|
package/src/constants.ts
CHANGED
|
@@ -77,6 +77,9 @@ export const FREE_PI_GUIDANCE = `# free-pi working rules
|
|
|
77
77
|
- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.
|
|
78
78
|
- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.
|
|
79
79
|
- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.
|
|
80
|
+
- Delegate large or self-contained work with OpenCode's native \`subagent\` tool: \`free-pi/scout\` and \`free-pi/planner\` for read-only recon and planning, \`free-pi/worker\` for a full task, \`free-pi/reviewer\` for review. A subagent runs in its own context and reports back; never launch a subagent from inside one.
|
|
81
|
+
- Load a skill with the native \`skill\` tool when its description matches the task.
|
|
82
|
+
- \`AGENTS.md\` and the files listed under \`instructions\` are the project's memory. Follow them; do not restate or replace them.
|
|
80
83
|
- Never claim to have compacted, summarized or cleared context unless that actually happened.
|
|
81
84
|
- Continue until the request is finished, then report concisely what changed and what you verified.`;
|
|
82
85
|
export const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
|
package/src/plugin.ts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
/** OpenCode V2 plugin entry point for free-pi. */
|
|
2
2
|
|
|
3
3
|
import { Plugin } from "@opencode/plugin";
|
|
4
|
-
import { join } from "node:path";
|
|
5
4
|
import {
|
|
6
5
|
FREE_PI_SKILL,
|
|
7
6
|
FREE_PI_SKILL_DESCRIPTION,
|
|
8
7
|
FREE_PI_SKILL_ID,
|
|
9
8
|
FREE_PI_SKILL_NAME,
|
|
9
|
+
freePiSkillPath,
|
|
10
10
|
installFreePiAgents,
|
|
11
|
+
installFreePiSkill,
|
|
11
12
|
openCodeConfigDir,
|
|
12
13
|
} from "./agents/definitions.js";
|
|
13
14
|
import { fetchQuota } from "./api/quota.js";
|
|
@@ -16,6 +17,7 @@ import { readCredentialsToken } from "./auth/credentials.js";
|
|
|
16
17
|
import { tokenFromCredential } from "./auth/credential.js";
|
|
17
18
|
import { fetchCatalog } from "./catalog/catalog.js";
|
|
18
19
|
import {
|
|
20
|
+
currentLiveLimits,
|
|
19
21
|
loadLiveLimits,
|
|
20
22
|
shouldVerifyWindow,
|
|
21
23
|
verifyGatewayWindow,
|
|
@@ -100,6 +102,25 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
100
102
|
} catch (error) {
|
|
101
103
|
log.warn("Could not install the free-pi subagents", error);
|
|
102
104
|
}
|
|
105
|
+
// OpenCode's own skill loader reads `skills/free-pi/SKILL.md`. Install the
|
|
106
|
+
// file first so the skill has a real path, supporting files and permissions
|
|
107
|
+
// like any other native skill; the transform below only fills the gap when
|
|
108
|
+
// the config directory is not writable.
|
|
109
|
+
try {
|
|
110
|
+
const skill = await installFreePiSkill();
|
|
111
|
+
if (skill.changed) {
|
|
112
|
+
await ctx.skill.reload();
|
|
113
|
+
log.info("Installed the native free-pi skill");
|
|
114
|
+
}
|
|
115
|
+
if (skill.skipped) {
|
|
116
|
+
log.warn(
|
|
117
|
+
"Left the user-owned free-pi skill file untouched",
|
|
118
|
+
freePiSkillPath(openCodeConfigDir()),
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
} catch (error) {
|
|
122
|
+
log.warn("Could not install the free-pi skill file", error);
|
|
123
|
+
}
|
|
103
124
|
try {
|
|
104
125
|
nativeRegistrations.push(
|
|
105
126
|
await ctx.skill.transform((editor) => {
|
|
@@ -108,7 +129,7 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
108
129
|
id: FREE_PI_SKILL_ID,
|
|
109
130
|
name: FREE_PI_SKILL_NAME,
|
|
110
131
|
description: FREE_PI_SKILL_DESCRIPTION,
|
|
111
|
-
path:
|
|
132
|
+
path: freePiSkillPath(openCodeConfigDir()),
|
|
112
133
|
content: FREE_PI_SKILL,
|
|
113
134
|
} as any);
|
|
114
135
|
}),
|
|
@@ -168,11 +189,17 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
168
189
|
await registerIntegration(ctx, deps);
|
|
169
190
|
|
|
170
191
|
await ctx.provider.transform((editor) => {
|
|
192
|
+
// Rebuilt on every transform so a learned context ceiling applies as soon
|
|
193
|
+
// as the response hook records it, without restarting OpenCode.
|
|
194
|
+
const active = currentLiveLimits() ?? live;
|
|
195
|
+
const buildOptionsNow = { ...buildOptions, live: active };
|
|
196
|
+
const mainNow = buildModels(main, candidates, buildOptionsNow);
|
|
197
|
+
const defenseNow = buildModels(defense, candidates, buildOptionsNow);
|
|
171
198
|
applyProvider(
|
|
172
199
|
editor,
|
|
173
200
|
PROVIDER_ID,
|
|
174
201
|
"Free Pi",
|
|
175
|
-
|
|
202
|
+
mainNow,
|
|
176
203
|
state.providerToken,
|
|
177
204
|
);
|
|
178
205
|
if (includeDefense && defense.length > 0) {
|
|
@@ -180,7 +207,7 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
180
207
|
editor,
|
|
181
208
|
DEFENSE_PROVIDER_ID,
|
|
182
209
|
"Free Pi Defense",
|
|
183
|
-
|
|
210
|
+
defenseNow,
|
|
184
211
|
state.providerToken,
|
|
185
212
|
);
|
|
186
213
|
}
|
package/src/session/hooks.ts
CHANGED
|
@@ -24,6 +24,11 @@ import {
|
|
|
24
24
|
RETRY_MAX_RETRIES,
|
|
25
25
|
SUBAGENT_HEADER,
|
|
26
26
|
} from "../constants.js";
|
|
27
|
+
import {
|
|
28
|
+
currentLiveLimits,
|
|
29
|
+
learnedContextWindow,
|
|
30
|
+
noteRejectedPrompt,
|
|
31
|
+
} from "../catalog/live.js";
|
|
27
32
|
import type { Deps } from "../deps.js";
|
|
28
33
|
import { closeFreePiSession } from "../api/session.js";
|
|
29
34
|
import {
|
|
@@ -32,6 +37,7 @@ import {
|
|
|
32
37
|
} from "../errors/limit.js";
|
|
33
38
|
import { parseFreePiError } from "../errors/parse.js";
|
|
34
39
|
import { trimMap } from "../utils/async.js";
|
|
40
|
+
import { trimMessagesForBudget } from "./overflow.js";
|
|
35
41
|
import { watchFreePiNotice } from "./notices.js";
|
|
36
42
|
import {
|
|
37
43
|
clearSpuriousOverflows,
|
|
@@ -96,6 +102,33 @@ function rememberPending(deps: Deps, key: string, turn: AdTurn): void {
|
|
|
96
102
|
deps.state.pendingAdTurns.set(key, turn);
|
|
97
103
|
}
|
|
98
104
|
|
|
105
|
+
/**
|
|
106
|
+
* Fits the compaction request inside the ceiling the gateway has already
|
|
107
|
+
* proven. OpenCode aborts the turn ("the compaction request cannot be reduced
|
|
108
|
+
* further") when the summarizer request is rejected too, so the plugin drops
|
|
109
|
+
* the oldest user turns before that can happen.
|
|
110
|
+
*/
|
|
111
|
+
function fitCompactionMessages(deps: Deps, event: any): void {
|
|
112
|
+
const modelID = typeof event.model?.id === "string" ? event.model.id : "";
|
|
113
|
+
const ceiling = learnedContextWindow(currentLiveLimits(), modelID);
|
|
114
|
+
if (!ceiling) return;
|
|
115
|
+
const messages = event.messages;
|
|
116
|
+
if (!Array.isArray(messages) || messages.length === 0) return;
|
|
117
|
+
const trimmed = trimMessagesForBudget(messages, Math.floor(ceiling * 0.9));
|
|
118
|
+
if (trimmed.dropped === 0) return;
|
|
119
|
+
event.messages = [...trimmed.messages];
|
|
120
|
+
deps.log.warn(
|
|
121
|
+
"free-pi trimmed the compaction request to fit the learned window",
|
|
122
|
+
{
|
|
123
|
+
sessionID: event.sessionID,
|
|
124
|
+
model: modelID,
|
|
125
|
+
window: ceiling,
|
|
126
|
+
droppedMessages: trimmed.dropped,
|
|
127
|
+
promptTokens: trimmed.tokens,
|
|
128
|
+
},
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
99
132
|
/** Adds a system block once, even when OpenCode reuses the same event. */
|
|
100
133
|
function appendSystemGuidance(
|
|
101
134
|
event: any,
|
|
@@ -138,15 +171,18 @@ async function applyGeneration(
|
|
|
138
171
|
const limit = deps.state.outputLimits.get(
|
|
139
172
|
`${event.model.providerID}/${modelID}`,
|
|
140
173
|
);
|
|
141
|
-
//
|
|
142
|
-
//
|
|
174
|
+
// The compaction summary is the one response that must never be cut: a
|
|
175
|
+
// summary that reaches the output limit fails the whole compaction and the
|
|
176
|
+
// turn stops with nothing but the checkpoint. Leave OpenCode's own budget
|
|
177
|
+
// for it and only cap the answers the user reads.
|
|
143
178
|
const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING);
|
|
144
|
-
if (event.options) {
|
|
179
|
+
if (event.options && kind !== "compaction") {
|
|
145
180
|
const current = event.options.maxTokens;
|
|
146
181
|
if (current === undefined || current > cap) event.options.maxTokens = cap;
|
|
147
182
|
}
|
|
148
183
|
|
|
149
184
|
if (kind === "compaction") {
|
|
185
|
+
fitCompactionMessages(deps, event);
|
|
150
186
|
appendSystemGuidance(
|
|
151
187
|
event,
|
|
152
188
|
FREE_PI_COMPACTION_GUIDANCE,
|
|
@@ -540,6 +576,26 @@ export async function registerSessionHooks(
|
|
|
540
576
|
const reviewed = await replaySpuriousOverflow(deps, event).catch(
|
|
541
577
|
() => ({}) as OverflowReplay,
|
|
542
578
|
);
|
|
579
|
+
// A rejection of a real prompt is the only free measurement of the
|
|
580
|
+
// gateway's ceiling. Attachments inflate the estimate and say nothing
|
|
581
|
+
// about the text window, so they are not learned from.
|
|
582
|
+
if (
|
|
583
|
+
reviewed.spurious === false &&
|
|
584
|
+
typeof reviewed.tokens === "number" &&
|
|
585
|
+
reviewed.model &&
|
|
586
|
+
reviewed.hasMedia !== true
|
|
587
|
+
) {
|
|
588
|
+
const learned = noteRejectedPrompt(
|
|
589
|
+
deps,
|
|
590
|
+
reviewed.model,
|
|
591
|
+
reviewed.tokens,
|
|
592
|
+
);
|
|
593
|
+
// Re-run the provider transform so this session's next compaction
|
|
594
|
+
// already targets the smaller window; no restart needed.
|
|
595
|
+
if (learned) {
|
|
596
|
+
void ctx.provider.reload().catch(() => undefined);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
543
599
|
if (reviewed.response) {
|
|
544
600
|
clearSpuriousOverflows(deps, event.sessionID);
|
|
545
601
|
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
|
}
|