@eduardo191labs/opencode-free-pi 0.6.5 → 0.6.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -1
- package/dist/agents/definitions.d.ts +2 -2
- package/dist/agents/definitions.js +7 -1
- package/dist/catalog/live.d.ts +18 -2
- package/dist/catalog/live.js +43 -2
- package/dist/catalog/models.js +6 -1
- package/dist/constants.d.ts +10 -1
- package/dist/constants.js +10 -1
- package/dist/deps.d.ts +4 -1
- package/dist/plugin.js +46 -3
- package/dist/session/hooks.js +84 -4
- package/dist/session/overflow.d.ts +31 -0
- package/dist/session/overflow.js +82 -4
- package/dist/session/replay.d.ts +4 -0
- package/dist/session/replay.js +10 -7
- package/dist/session/tools.d.ts +1 -1
- package/dist/session/tools.js +1 -0
- package/dist/tools/subagent.d.ts +29 -0
- package/dist/tools/subagent.js +197 -0
- package/dist/types.d.ts +11 -0
- package/package.json +1 -1
- package/src/agents/definitions.ts +7 -1
- package/src/catalog/live.ts +65 -2
- package/src/catalog/models.ts +6 -0
- package/src/constants.ts +11 -1
- package/src/deps.ts +8 -1
- package/src/plugin.ts +44 -2
- package/src/session/hooks.ts +102 -3
- package/src/session/overflow.ts +98 -4
- package/src/session/replay.ts +14 -6
- package/src/session/tools.ts +1 -0
- package/src/tools/subagent.ts +271 -0
- package/src/types.ts +18 -0
package/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
|
|
@@ -225,6 +238,7 @@ demás modelos no las ven ni pueden ejecutarlas.
|
|
|
225
238
|
| `web_search` | Busca en la web y devuelve título, URL, fecha y texto de cada resultado. |
|
|
226
239
|
| `docs_lookup` | Consulta documentación actual de una librería o framework. |
|
|
227
240
|
| `free_pi_usage` | Muestra cuota restante, créditos, tokens y tier de la cuenta. |
|
|
241
|
+
| `free_pi_subagent_read` | Lee la transcripción de una sesión hija: prompts, herramientas y respuesta. |
|
|
228
242
|
|
|
229
243
|
`generate_image` acepta `prompt`, `aspect_ratio` (`1:1`, `16:9`, `9:16`, `4:3`,
|
|
230
244
|
`3:2`) y un `name` opcional para el archivo. Rechaza tipos que no sean PNG,
|
|
@@ -244,6 +258,15 @@ con su hora de recarga en ET, los créditos premium o de referidos y los tokens
|
|
|
244
258
|
de hoy y de por vida. Si el servidor asigna el carril lento, incluye el aviso
|
|
245
259
|
del CLI.
|
|
246
260
|
|
|
261
|
+
`free_pi_subagent_read` recibe el `sessionID` que devuelve la herramienta
|
|
262
|
+
`subagent` y devuelve la conversación de esa sesión hija: el prompt recibido,
|
|
263
|
+
cada llamada a herramienta con su entrada y su resultado, y el texto final del
|
|
264
|
+
subagente. Antes de leer comprueba con `session.get` que `parentID` sea la sesión
|
|
265
|
+
que llama, así que no puede abrir sesiones ajenas. Sin `sessionID` lista las
|
|
266
|
+
sesiones hijas de la sesión actual con su agente y su resultado. El transcript se
|
|
267
|
+
mantiene dentro de un presupuesto de caracteres (`maxChars`, 60k por defecto) y,
|
|
268
|
+
si no cabe, conserva los turnos más recientes y lo indica.
|
|
269
|
+
|
|
247
270
|
La compra de créditos y la guía de free-pi ya no se exponen como herramientas:
|
|
248
271
|
se resuelven en el dashboard y la documentación de free-pi, sin gastar cuota ni
|
|
249
272
|
añadir ruido al contexto.
|
|
@@ -279,7 +302,10 @@ La herramienta `subagent` es la de OpenCode y está disponible para **cualquier
|
|
|
279
302
|
modelo**, no solo para los agentes `free-pi/*`: también puede lanzarlos un
|
|
280
303
|
modelo de otro proveedor configurado en OpenCode. El plugin garantiza además que
|
|
281
304
|
todos los modelos gratuitos anuncien soporte de tools, de modo que el runner
|
|
282
|
-
nunca oculte `subagent` por una capacidad incorrecta de models.dev.
|
|
305
|
+
nunca oculte `subagent` por una capacidad incorrecta de models.dev. Cuando el
|
|
306
|
+
hijo termina, OpenCode inyecta su informe en la sesión padre; para ver lo que
|
|
307
|
+
realmente ejecutó, el padre llama a `free_pi_subagent_read` con el `sessionID`
|
|
308
|
+
del hijo.
|
|
283
309
|
|
|
284
310
|
El plugin solo reescribe estos archivos si conservan su marca de gestión; si el
|
|
285
311
|
usuario edita o reemplaza uno, se respeta tal cual.
|
|
@@ -347,6 +373,15 @@ insiste, devuelve un `400` con un mensaje de error de proveedor. Ese texto no
|
|
|
347
373
|
coincide con el patrón de desbordamiento de OpenCode, así que el runner deja de
|
|
348
374
|
compactar en lugar de entrar en un ciclo de resúmenes que no reducen nada.
|
|
349
375
|
|
|
376
|
+
Cuando el rechazo sí corresponde a una conversación larga, el tamaño medido se
|
|
377
|
+
guarda como `rejectedPromptTokens` del modelo en `live-limits.json`. El
|
|
378
|
+
`provider.transform` reconstruye el catálogo con ese techo (85 % del tamaño
|
|
379
|
+
rechazado, sin bajar de la ventana ya aceptada) y `provider.reload` lo aplica en
|
|
380
|
+
caliente, de modo que la siguiente compactación se dispara antes de que el
|
|
381
|
+
gateway rechace el resumen. Si el resumen aún no cupiera, el hook de
|
|
382
|
+
compactación descarta los turnos de usuario más antiguos en lugar de dejar que
|
|
383
|
+
OpenCode aborte el turno.
|
|
384
|
+
|
|
350
385
|
free-pi cobra en créditos contra una cuota diaria, no en USD por token. Por
|
|
351
386
|
eso los modelos se registran con costo `0`, igual que el CLI del proveedor; el
|
|
352
387
|
consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
|
|
@@ -366,6 +401,13 @@ turno que se aborta o falla a mitad de stream marca su `x-session-id` como sucio
|
|
|
366
401
|
la siguiente petición arranca directamente con un id nuevo y libera el anterior,
|
|
367
402
|
de modo que la sesión continúa sin interrupciones y sin pasar por un reintento.
|
|
368
403
|
|
|
404
|
+
Los fallos de transporte (`ECONNREFUSED`, `ECONNRESET`, `ETIMEDOUT`, DNS
|
|
405
|
+
temporal, `socket hang up`) no son límites de cuenta: el plugin los reintenta con
|
|
406
|
+
espera exponencial hasta cinco veces más (2 s, 4 s, 8 s, 16 s y 30 s) y marca el
|
|
407
|
+
`x-session-id` como sucio para que el siguiente intento use una conexión y un
|
|
408
|
+
slot nuevos. Así un corte breve de red, del router o del servicio local de
|
|
409
|
+
OpenCode no termina el turno en el segundo intento.
|
|
410
|
+
|
|
369
411
|
## Rutas por plataforma
|
|
370
412
|
|
|
371
413
|
| Elemento | Windows | Linux / macOS / Termux |
|
|
@@ -21,13 +21,13 @@ export type FreePiAgentID = (typeof FREE_PI_AGENT_IDS)[number];
|
|
|
21
21
|
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
|
-
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";
|
|
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- `free_pi_subagent_read` reads the transcript of a child session started with\n the `subagent` tool: its prompts, every tool call with input and result, and\n its final answer. Read-only; omit `sessionID` to list this session's children.\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. The `subagent` tool\nreturns the child `sessionID` and OpenCode injects the child's report when it\ngoes idle; call `free_pi_subagent_read` with that id to see what the child ran\nand why its answer says what it says.\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
25
|
/**
|
|
26
26
|
* The same skill as a native `SKILL.md`. OpenCode discovers it from the global
|
|
27
27
|
* skills directory, so the file, its ID, its permissions and the `skill` tool
|
|
28
28
|
* all belong to OpenCode instead of a runtime registration.
|
|
29
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";
|
|
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- `free_pi_subagent_read` reads the transcript of a child session started with\n the `subagent` tool: its prompts, every tool call with input and result, and\n its final answer. Read-only; omit `sessionID` to list this session's children.\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. The `subagent` tool\nreturns the child `sessionID` and OpenCode injects the child's report when it\ngoes idle; call `free_pi_subagent_read` with that id to see what the child ran\nand why its answer says what it says.\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";
|
|
31
31
|
/** OpenCode's user-wide config directory, where it loads custom agents. */
|
|
32
32
|
export declare function openCodeConfigDir(): string;
|
|
33
33
|
export declare function freePiAgentPath(configDir: string, id: FreePiAgentID): string;
|
|
@@ -39,6 +39,9 @@ it.
|
|
|
39
39
|
## Tools
|
|
40
40
|
- \`free_pi_usage\` shows today's remaining allowance, credits, token counts and
|
|
41
41
|
the account tier. Read-only.
|
|
42
|
+
- \`free_pi_subagent_read\` reads the transcript of a child session started with
|
|
43
|
+
the \`subagent\` tool: its prompts, every tool call with input and result, and
|
|
44
|
+
its final answer. Read-only; omit \`sessionID\` to list this session's children.
|
|
42
45
|
- \`look_at_image\` asks a vision model about a PNG, JPEG or WebP inside the
|
|
43
46
|
project. Use it when the current model takes text only, or when the image is a
|
|
44
47
|
file on disk and you want a targeted answer instead of attaching it.
|
|
@@ -64,7 +67,10 @@ Use OpenCode's native subagent tool with the agents this plugin installs:
|
|
|
64
67
|
Subagents inherit the free-pi model, share the same daily allowance, and run as
|
|
65
68
|
child sessions in the background. Keep large exploration in a subagent so it
|
|
66
69
|
does not fill your own context. Use OpenCode's agent picker or the \`subagent\`
|
|
67
|
-
tool; do not try to launch them through shell commands.
|
|
70
|
+
tool; do not try to launch them through shell commands. The \`subagent\` tool
|
|
71
|
+
returns the child \`sessionID\` and OpenCode injects the child's report when it
|
|
72
|
+
goes idle; call \`free_pi_subagent_read\` with that id to see what the child ran
|
|
73
|
+
and why its answer says what it says.
|
|
68
74
|
|
|
69
75
|
## Memory and sessions
|
|
70
76
|
|
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.
|
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- 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.";
|
|
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. The `subagent` tool returns a child `sessionID` and OpenCode injects the child's report when it goes idle; to inspect what that child actually did, call `free_pi_subagent_read` with its `sessionID` (omit it to list this session's children).\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
|
|
@@ -66,6 +66,15 @@ export declare const CHUNK_TIMEOUT_MS = 300000;
|
|
|
66
66
|
export declare const RETRY_MAX_RETRIES = 3;
|
|
67
67
|
export declare const RETRY_BASE_DELAY_MS = 2000;
|
|
68
68
|
export declare const RETRY_MAX_DELAY_MS = 60000;
|
|
69
|
+
/**
|
|
70
|
+
* Transport failures (a refused or dropped connection, DNS blips) usually
|
|
71
|
+
* clear on their own. OpenCode stops after its own retries, which can end a
|
|
72
|
+
* turn during a brief local network or service restart, so the plugin gives
|
|
73
|
+
* them a longer budget before giving up.
|
|
74
|
+
*/
|
|
75
|
+
export declare const TRANSPORT_RETRY_MAX = 5;
|
|
76
|
+
export declare const TRANSPORT_RETRY_BASE_MS = 2000;
|
|
77
|
+
export declare const TRANSPORT_RETRY_MAX_DELAY_MS = 30000;
|
|
69
78
|
/**
|
|
70
79
|
* free-pi allows one in-flight request per `x-session-id` and answers a second
|
|
71
80
|
* one with `429 concurrent`. OpenCode does not retry that itself, and a slot
|
package/dist/constants.js
CHANGED
|
@@ -70,7 +70,7 @@ 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.
|
|
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. The \`subagent\` tool returns a child \`sessionID\` and OpenCode injects the child's report when it goes idle; to inspect what that child actually did, call \`free_pi_subagent_read\` with its \`sessionID\` (omit it to list this session's children).
|
|
74
74
|
- Load a skill with the native \`skill\` tool when its description matches the task.
|
|
75
75
|
- \`AGENTS.md\` and the files listed under \`instructions\` are the project's memory. Follow them; do not restate or replace them.
|
|
76
76
|
- Never claim to have compacted, summarized or cleared context unless that actually happened.
|
|
@@ -94,6 +94,15 @@ export const CHUNK_TIMEOUT_MS = 300_000;
|
|
|
94
94
|
export const RETRY_MAX_RETRIES = 3;
|
|
95
95
|
export const RETRY_BASE_DELAY_MS = 2_000;
|
|
96
96
|
export const RETRY_MAX_DELAY_MS = 60_000;
|
|
97
|
+
/**
|
|
98
|
+
* Transport failures (a refused or dropped connection, DNS blips) usually
|
|
99
|
+
* clear on their own. OpenCode stops after its own retries, which can end a
|
|
100
|
+
* turn during a brief local network or service restart, so the plugin gives
|
|
101
|
+
* them a longer budget before giving up.
|
|
102
|
+
*/
|
|
103
|
+
export const TRANSPORT_RETRY_MAX = 5;
|
|
104
|
+
export const TRANSPORT_RETRY_BASE_MS = 2_000;
|
|
105
|
+
export const TRANSPORT_RETRY_MAX_DELAY_MS = 30_000;
|
|
97
106
|
/**
|
|
98
107
|
* free-pi allows one in-flight request per `x-session-id` and answers a second
|
|
99
108
|
* one with `429 concurrent`. OpenCode does not retry that itself, and a slot
|
package/dist/deps.d.ts
CHANGED
|
@@ -3,12 +3,15 @@ import type { Credential } from "@opencode/schema/credential";
|
|
|
3
3
|
import type { Plugin } from "@opencode/plugin";
|
|
4
4
|
import type { Logger } from "./logging.js";
|
|
5
5
|
import type { RuntimeState } from "./state.js";
|
|
6
|
-
import type { ReadContext } from "./types.js";
|
|
6
|
+
import type { ListSubagentSessions, ReadContext, ReadSessionInfo } from "./types.js";
|
|
7
7
|
export type Deps = {
|
|
8
8
|
readonly state: RuntimeState;
|
|
9
9
|
readonly log: Logger;
|
|
10
10
|
readonly activeCredential: () => Promise<Credential.Value | undefined>;
|
|
11
11
|
readonly readContext: ReadContext;
|
|
12
|
+
/** Session headers, used to prove a session is really this session's child. */
|
|
13
|
+
readonly readSession?: ReadSessionInfo;
|
|
14
|
+
readonly listSubagentSessions?: ListSubagentSessions;
|
|
12
15
|
/** Plugin-scoped durable storage, used to reconnect provider sessions. */
|
|
13
16
|
readonly storage?: Plugin.Context["storage"];
|
|
14
17
|
};
|
package/dist/plugin.js
CHANGED
|
@@ -6,7 +6,7 @@ import { closeFreePiSession } from "./api/session.js";
|
|
|
6
6
|
import { readCredentialsToken } from "./auth/credentials.js";
|
|
7
7
|
import { tokenFromCredential } from "./auth/credential.js";
|
|
8
8
|
import { fetchCatalog } from "./catalog/catalog.js";
|
|
9
|
-
import { loadLiveLimits, shouldVerifyWindow, verifyGatewayWindow, } from "./catalog/live.js";
|
|
9
|
+
import { currentLiveLimits, loadLiveLimits, shouldVerifyWindow, verifyGatewayWindow, } from "./catalog/live.js";
|
|
10
10
|
import { accountAccess, buildModels, filterAccessibleModels, isReasoningEffort, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
|
|
11
11
|
import { fetchModelsRegistry } from "./catalog/registry.js";
|
|
12
12
|
import { applyProvider } from "./catalog/v2.js";
|
|
@@ -19,6 +19,7 @@ import { cancelAllFinalizeTimers } from "./session/track.js";
|
|
|
19
19
|
import { createRuntimeState } from "./state.js";
|
|
20
20
|
import { registerGenerateImageTool } from "./tools/image-generate.js";
|
|
21
21
|
import { registerUsageTool } from "./tools/usage.js";
|
|
22
|
+
import { registerSubagentTool } from "./tools/subagent.js";
|
|
22
23
|
import { registerVisionTool } from "./tools/vision.js";
|
|
23
24
|
import { registerWebTools } from "./tools/web.js";
|
|
24
25
|
import { settle } from "./utils/async.js";
|
|
@@ -51,6 +52,38 @@ async function setup(ctx) {
|
|
|
51
52
|
return [];
|
|
52
53
|
}
|
|
53
54
|
},
|
|
55
|
+
readSession: async (sessionID) => {
|
|
56
|
+
try {
|
|
57
|
+
const info = await ctx.session.get({ sessionID });
|
|
58
|
+
return {
|
|
59
|
+
id: info.id,
|
|
60
|
+
parentID: info.parentID,
|
|
61
|
+
title: info.title,
|
|
62
|
+
agent: info.agent,
|
|
63
|
+
outcome: info.outcome,
|
|
64
|
+
updated: info.time?.updated,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
listSubagentSessions: async (parentID) => {
|
|
72
|
+
try {
|
|
73
|
+
const result = await ctx.session.list({ parentID, limit: 50 });
|
|
74
|
+
return (result.data ?? []).map((info) => ({
|
|
75
|
+
id: info.id,
|
|
76
|
+
parentID: info.parentID,
|
|
77
|
+
title: info.title,
|
|
78
|
+
agent: info.agent,
|
|
79
|
+
outcome: info.outcome,
|
|
80
|
+
updated: info.time?.updated,
|
|
81
|
+
}));
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return [];
|
|
85
|
+
}
|
|
86
|
+
},
|
|
54
87
|
storage: ctx.storage,
|
|
55
88
|
};
|
|
56
89
|
// OpenCode owns agents and skills. The plugin only installs the CLI's
|
|
@@ -149,9 +182,15 @@ async function setup(ctx) {
|
|
|
149
182
|
tokenFromCredential(credential) ?? (await readCredentialsToken());
|
|
150
183
|
await registerIntegration(ctx, deps);
|
|
151
184
|
await ctx.provider.transform((editor) => {
|
|
152
|
-
|
|
185
|
+
// Rebuilt on every transform so a learned context ceiling applies as soon
|
|
186
|
+
// as the response hook records it, without restarting OpenCode.
|
|
187
|
+
const active = currentLiveLimits() ?? live;
|
|
188
|
+
const buildOptionsNow = { ...buildOptions, live: active };
|
|
189
|
+
const mainNow = buildModels(main, candidates, buildOptionsNow);
|
|
190
|
+
const defenseNow = buildModels(defense, candidates, buildOptionsNow);
|
|
191
|
+
applyProvider(editor, PROVIDER_ID, "Free Pi", mainNow, state.providerToken);
|
|
153
192
|
if (includeDefense && defense.length > 0) {
|
|
154
|
-
applyProvider(editor, DEFENSE_PROVIDER_ID, "Free Pi Defense",
|
|
193
|
+
applyProvider(editor, DEFENSE_PROVIDER_ID, "Free Pi Defense", defenseNow, state.providerToken);
|
|
155
194
|
}
|
|
156
195
|
});
|
|
157
196
|
// The gateway does not publish its context ceiling. Verify the compiled
|
|
@@ -192,6 +231,10 @@ async function setup(ctx) {
|
|
|
192
231
|
const tools = [
|
|
193
232
|
{ name: "look_at_image", register: () => registerVisionTool(ctx, deps) },
|
|
194
233
|
{ name: "free_pi_usage", register: () => registerUsageTool(ctx, deps) },
|
|
234
|
+
{
|
|
235
|
+
name: "free_pi_subagent_read",
|
|
236
|
+
register: () => registerSubagentTool(ctx, deps),
|
|
237
|
+
},
|
|
195
238
|
{ name: "web", register: () => registerWebTools(ctx, deps) },
|
|
196
239
|
{ name: "generate_image", register: () => registerGenerateImageTool(ctx, deps) },
|
|
197
240
|
];
|
package/dist/session/hooks.js
CHANGED
|
@@ -2,11 +2,13 @@
|
|
|
2
2
|
import { ensureAdImpression } from "../ads/impression.js";
|
|
3
3
|
import { resolveAdTurn } from "../ads/resolve.js";
|
|
4
4
|
import { resolveToken } from "../auth/token.js";
|
|
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";
|
|
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, TRANSPORT_RETRY_BASE_MS, TRANSPORT_RETRY_MAX, TRANSPORT_RETRY_MAX_DELAY_MS, } 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`.
|
|
@@ -184,6 +215,20 @@ const TERMINAL_RETRY_CODES = new Set([
|
|
|
184
215
|
"subagents_unavailable",
|
|
185
216
|
]);
|
|
186
217
|
const TERMINAL_RETRY_PATTERN = /free usage limit|monthly usage limit|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/i;
|
|
218
|
+
/**
|
|
219
|
+
* A request that never reached the gateway. `provider.transport` covers the
|
|
220
|
+
* typed path, while the pattern catches bare fetch errors. These are worth
|
|
221
|
+
* retrying beyond the usual budget: a brief offline moment or a background
|
|
222
|
+
* service restart is not a provider limit.
|
|
223
|
+
*/
|
|
224
|
+
const TRANSPORT_RETRY_PATTERN = /ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|EPIPE|socket hang up|fetch failed|Unable to connect|connection (?:refused|reset)/i;
|
|
225
|
+
function isTransportFailure(error) {
|
|
226
|
+
const type = typeof error?.type === "string" ? error.type : "";
|
|
227
|
+
if (/transport|network|connection/i.test(type))
|
|
228
|
+
return true;
|
|
229
|
+
const message = `${error?.message ?? ""}\n${error?.cause?.message ?? ""}`;
|
|
230
|
+
return TRANSPORT_RETRY_PATTERN.test(message);
|
|
231
|
+
}
|
|
187
232
|
function isTerminalFailure(error) {
|
|
188
233
|
if (error?.type === "aborted" ||
|
|
189
234
|
/aborted|cancelled|canceled|interrupted|AbortError/i.test(`${error?.message ?? ""}`)) {
|
|
@@ -235,6 +280,27 @@ function applyRetryPolicy(deps, event) {
|
|
|
235
280
|
event.decision = { retry: false };
|
|
236
281
|
return;
|
|
237
282
|
}
|
|
283
|
+
if (isTransportFailure(event.error)) {
|
|
284
|
+
if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
|
|
285
|
+
event.decision = { retry: false };
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
// A connection that dropped mid-turn can leave the gateway's per-session
|
|
289
|
+
// slot marked busy, so the next attempt should not reuse the wire id.
|
|
290
|
+
markWireSessionDirty(deps, event.sessionID);
|
|
291
|
+
const attempt = Math.max(1, event.attempt - 1);
|
|
292
|
+
event.decision = {
|
|
293
|
+
retry: true,
|
|
294
|
+
delay: Math.min(TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1), TRANSPORT_RETRY_MAX_DELAY_MS),
|
|
295
|
+
};
|
|
296
|
+
deps.log.warn("free-pi could not be reached; retrying", {
|
|
297
|
+
sessionID: event.sessionID,
|
|
298
|
+
attempt: event.attempt,
|
|
299
|
+
delay: event.decision.delay,
|
|
300
|
+
error: typeof event.error?.message === "string" ? event.error.message : undefined,
|
|
301
|
+
});
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
238
304
|
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
239
305
|
event.decision = { retry: false };
|
|
240
306
|
return;
|
|
@@ -363,6 +429,20 @@ export async function registerSessionHooks(ctx, deps) {
|
|
|
363
429
|
// window. Compacting then loops, so retry on a fresh wire session
|
|
364
430
|
// first, and stop compacting once the session has seen a few.
|
|
365
431
|
const reviewed = await replaySpuriousOverflow(deps, event).catch(() => ({}));
|
|
432
|
+
// A rejection of a real prompt is the only free measurement of the
|
|
433
|
+
// gateway's ceiling. Attachments inflate the estimate and say nothing
|
|
434
|
+
// about the text window, so they are not learned from.
|
|
435
|
+
if (reviewed.spurious === false &&
|
|
436
|
+
typeof reviewed.tokens === "number" &&
|
|
437
|
+
reviewed.model &&
|
|
438
|
+
reviewed.hasMedia !== true) {
|
|
439
|
+
const learned = noteRejectedPrompt(deps, reviewed.model, reviewed.tokens);
|
|
440
|
+
// Re-run the provider transform so this session's next compaction
|
|
441
|
+
// already targets the smaller window; no restart needed.
|
|
442
|
+
if (learned) {
|
|
443
|
+
void ctx.provider.reload().catch(() => undefined);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
366
446
|
if (reviewed.response) {
|
|
367
447
|
clearSpuriousOverflows(deps, event.sessionID);
|
|
368
448
|
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
|