@eduardo191labs/opencode-free-pi 0.6.6 → 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 +21 -1
- package/dist/agents/definitions.d.ts +2 -2
- package/dist/agents/definitions.js +7 -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 +37 -0
- package/dist/session/hooks.js +36 -1
- 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/constants.ts +11 -1
- package/src/deps.ts +8 -1
- package/src/plugin.ts +35 -0
- package/src/session/hooks.ts +43 -0
- package/src/session/tools.ts +1 -0
- package/src/tools/subagent.ts +271 -0
- package/src/types.ts +18 -0
package/README.md
CHANGED
|
@@ -238,6 +238,7 @@ demás modelos no las ven ni pueden ejecutarlas.
|
|
|
238
238
|
| `web_search` | Busca en la web y devuelve título, URL, fecha y texto de cada resultado. |
|
|
239
239
|
| `docs_lookup` | Consulta documentación actual de una librería o framework. |
|
|
240
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. |
|
|
241
242
|
|
|
242
243
|
`generate_image` acepta `prompt`, `aspect_ratio` (`1:1`, `16:9`, `9:16`, `4:3`,
|
|
243
244
|
`3:2`) y un `name` opcional para el archivo. Rechaza tipos que no sean PNG,
|
|
@@ -257,6 +258,15 @@ con su hora de recarga en ET, los créditos premium o de referidos y los tokens
|
|
|
257
258
|
de hoy y de por vida. Si el servidor asigna el carril lento, incluye el aviso
|
|
258
259
|
del CLI.
|
|
259
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
|
+
|
|
260
270
|
La compra de créditos y la guía de free-pi ya no se exponen como herramientas:
|
|
261
271
|
se resuelven en el dashboard y la documentación de free-pi, sin gastar cuota ni
|
|
262
272
|
añadir ruido al contexto.
|
|
@@ -292,7 +302,10 @@ La herramienta `subagent` es la de OpenCode y está disponible para **cualquier
|
|
|
292
302
|
modelo**, no solo para los agentes `free-pi/*`: también puede lanzarlos un
|
|
293
303
|
modelo de otro proveedor configurado en OpenCode. El plugin garantiza además que
|
|
294
304
|
todos los modelos gratuitos anuncien soporte de tools, de modo que el runner
|
|
295
|
-
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.
|
|
296
309
|
|
|
297
310
|
El plugin solo reescribe estos archivos si conservan su marca de gestión; si el
|
|
298
311
|
usuario edita o reemplaza uno, se respeta tal cual.
|
|
@@ -388,6 +401,13 @@ turno que se aborta o falla a mitad de stream marca su `x-session-id` como sucio
|
|
|
388
401
|
la siguiente petición arranca directamente con un id nuevo y libera el anterior,
|
|
389
402
|
de modo que la sesión continúa sin interrupciones y sin pasar por un reintento.
|
|
390
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
|
+
|
|
391
411
|
## Rutas por plataforma
|
|
392
412
|
|
|
393
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/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
|
@@ -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
|
|
@@ -198,6 +231,10 @@ async function setup(ctx) {
|
|
|
198
231
|
const tools = [
|
|
199
232
|
{ name: "look_at_image", register: () => registerVisionTool(ctx, deps) },
|
|
200
233
|
{ name: "free_pi_usage", register: () => registerUsageTool(ctx, deps) },
|
|
234
|
+
{
|
|
235
|
+
name: "free_pi_subagent_read",
|
|
236
|
+
register: () => registerSubagentTool(ctx, deps),
|
|
237
|
+
},
|
|
201
238
|
{ name: "web", register: () => registerWebTools(ctx, deps) },
|
|
202
239
|
{ name: "generate_image", register: () => registerGenerateImageTool(ctx, deps) },
|
|
203
240
|
];
|
package/dist/session/hooks.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
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
6
|
import { currentLiveLimits, learnedContextWindow, noteRejectedPrompt, } from "../catalog/live.js";
|
|
7
7
|
import { closeFreePiSession } from "../api/session.js";
|
|
8
8
|
import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
|
|
@@ -215,6 +215,20 @@ const TERMINAL_RETRY_CODES = new Set([
|
|
|
215
215
|
"subagents_unavailable",
|
|
216
216
|
]);
|
|
217
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
|
+
}
|
|
218
232
|
function isTerminalFailure(error) {
|
|
219
233
|
if (error?.type === "aborted" ||
|
|
220
234
|
/aborted|cancelled|canceled|interrupted|AbortError/i.test(`${error?.message ?? ""}`)) {
|
|
@@ -266,6 +280,27 @@ function applyRetryPolicy(deps, event) {
|
|
|
266
280
|
event.decision = { retry: false };
|
|
267
281
|
return;
|
|
268
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
|
+
}
|
|
269
304
|
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
270
305
|
event.decision = { retry: false };
|
|
271
306
|
return;
|
package/dist/session/tools.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ import type { Deps } from "../deps.js";
|
|
|
13
13
|
* served by another provider (see `hideFreePiTools`) and refuses to run them
|
|
14
14
|
* outside a free-pi session.
|
|
15
15
|
*/
|
|
16
|
-
export declare const FREE_PI_TOOL_NAMES: readonly ["look_at_image", "free_pi_usage", "web_search", "docs_lookup", "generate_image"];
|
|
16
|
+
export declare const FREE_PI_TOOL_NAMES: readonly ["look_at_image", "free_pi_usage", "free_pi_subagent_read", "web_search", "docs_lookup", "generate_image"];
|
|
17
17
|
type ToolResultLike = {
|
|
18
18
|
metadata?: Record<string, unknown>;
|
|
19
19
|
};
|
package/dist/session/tools.js
CHANGED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `free_pi_subagent_read`, a transcript reader for child sessions.
|
|
3
|
+
*
|
|
4
|
+
* OpenCode's `subagent` tool reports the child's final output and pings the
|
|
5
|
+
* parent when the child goes idle, but the parent cannot open the child's
|
|
6
|
+
* conversation afterwards. This tool fills that gap: it reads the transcript
|
|
7
|
+
* of a session that is really a child of the calling session, so the parent can
|
|
8
|
+
* see every task the subagent ran (tool calls with input and result) and quote
|
|
9
|
+
* its answer.
|
|
10
|
+
*
|
|
11
|
+
* Read-only. The session is checked against its `parentID`, so a model cannot
|
|
12
|
+
* use it to read unrelated sessions.
|
|
13
|
+
*/
|
|
14
|
+
import type { Plugin } from "@opencode/plugin";
|
|
15
|
+
import type { Deps } from "../deps.js";
|
|
16
|
+
export type Transcript = {
|
|
17
|
+
readonly text: string;
|
|
18
|
+
readonly messages: number;
|
|
19
|
+
readonly truncated: boolean;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Renders a session transcript, keeping the newest turns when it does not fit.
|
|
23
|
+
* The final assistant text is repeated at the end so the parent can quote it
|
|
24
|
+
* even when the middle of the transcript was dropped.
|
|
25
|
+
*/
|
|
26
|
+
export declare function formatTranscript(messages: readonly unknown[], maxChars?: number): Transcript;
|
|
27
|
+
export declare function registerSubagentTool(ctx: Plugin.Context, deps: Deps): Promise<{
|
|
28
|
+
dispose: () => Promise<void>;
|
|
29
|
+
}>;
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `free_pi_subagent_read`, a transcript reader for child sessions.
|
|
3
|
+
*
|
|
4
|
+
* OpenCode's `subagent` tool reports the child's final output and pings the
|
|
5
|
+
* parent when the child goes idle, but the parent cannot open the child's
|
|
6
|
+
* conversation afterwards. This tool fills that gap: it reads the transcript
|
|
7
|
+
* of a session that is really a child of the calling session, so the parent can
|
|
8
|
+
* see every task the subagent ran (tool calls with input and result) and quote
|
|
9
|
+
* its answer.
|
|
10
|
+
*
|
|
11
|
+
* Read-only. The session is checked against its `parentID`, so a model cannot
|
|
12
|
+
* use it to read unrelated sessions.
|
|
13
|
+
*/
|
|
14
|
+
import { done, fail, GATED_TEXT, isGatedSession } from "./api.js";
|
|
15
|
+
const DEFAULT_MAX_CHARS = 60_000;
|
|
16
|
+
const MIN_MAX_CHARS = 2_000;
|
|
17
|
+
const MAX_MAX_CHARS = 200_000;
|
|
18
|
+
const TOOL_RESULT_CHARS = 2_000;
|
|
19
|
+
const TOOL_INPUT_CHARS = 1_500;
|
|
20
|
+
const USER_TEXT_CHARS = 8_000;
|
|
21
|
+
const ASSISTANT_TEXT_CHARS = 16_000;
|
|
22
|
+
const INPUT_SCHEMA = {
|
|
23
|
+
type: "object",
|
|
24
|
+
additionalProperties: false,
|
|
25
|
+
properties: {
|
|
26
|
+
sessionID: {
|
|
27
|
+
type: "string",
|
|
28
|
+
description: "Child session to read, as returned by the `subagent` tool. Omit it to list this session's children.",
|
|
29
|
+
},
|
|
30
|
+
maxChars: {
|
|
31
|
+
type: "integer",
|
|
32
|
+
minimum: MIN_MAX_CHARS,
|
|
33
|
+
maximum: MAX_MAX_CHARS,
|
|
34
|
+
description: `Transcript budget in characters (default ${DEFAULT_MAX_CHARS}). The newest turns are kept.`,
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
function cut(value, limit) {
|
|
39
|
+
const text = value.trim();
|
|
40
|
+
if (text.length <= limit)
|
|
41
|
+
return text;
|
|
42
|
+
return `${text.slice(0, limit)}\n[... ${text.length - limit} characters cut]`;
|
|
43
|
+
}
|
|
44
|
+
function stringify(value) {
|
|
45
|
+
if (typeof value === "string")
|
|
46
|
+
return value;
|
|
47
|
+
try {
|
|
48
|
+
return JSON.stringify(value, null, 2) ?? "";
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return String(value ?? "");
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function textOfContent(content) {
|
|
55
|
+
if (typeof content === "string")
|
|
56
|
+
return content;
|
|
57
|
+
if (!Array.isArray(content))
|
|
58
|
+
return "";
|
|
59
|
+
return content
|
|
60
|
+
.filter((part) => part?.type === "text" && part.synthetic !== true)
|
|
61
|
+
.map((part) => part.text ?? "")
|
|
62
|
+
.join("\n");
|
|
63
|
+
}
|
|
64
|
+
function formatTool(part) {
|
|
65
|
+
const status = part.state?.status ?? "unknown";
|
|
66
|
+
const header = `[tool ${part.name ?? "?"}] ${status}`;
|
|
67
|
+
const input = stringify(part.state?.input ?? {});
|
|
68
|
+
const output = textOfContent(part.state?.content);
|
|
69
|
+
return [
|
|
70
|
+
header,
|
|
71
|
+
`input: ${cut(input, TOOL_INPUT_CHARS)}`,
|
|
72
|
+
...(output.trim() ? [`result: ${cut(output, TOOL_RESULT_CHARS)}`] : []),
|
|
73
|
+
].join("\n");
|
|
74
|
+
}
|
|
75
|
+
function formatMessage(message) {
|
|
76
|
+
const role = message.role ?? message.type;
|
|
77
|
+
if (role === "user") {
|
|
78
|
+
const text = message.text ?? textOfContent(message.content);
|
|
79
|
+
return text.trim() ? `[user]\n${cut(text, USER_TEXT_CHARS)}` : "";
|
|
80
|
+
}
|
|
81
|
+
if (role !== "assistant")
|
|
82
|
+
return "";
|
|
83
|
+
const blocks = [];
|
|
84
|
+
const content = Array.isArray(message.content) ? message.content : [];
|
|
85
|
+
for (const part of content) {
|
|
86
|
+
if (part?.type === "text" && part.synthetic !== true) {
|
|
87
|
+
const text = part.text ?? "";
|
|
88
|
+
if (text.trim())
|
|
89
|
+
blocks.push(cut(text, ASSISTANT_TEXT_CHARS));
|
|
90
|
+
}
|
|
91
|
+
else if (part?.type === "tool") {
|
|
92
|
+
blocks.push(formatTool(part));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (blocks.length === 0)
|
|
96
|
+
return "";
|
|
97
|
+
const finish = message.finish && message.finish !== "stop" ? ` (${message.finish})` : "";
|
|
98
|
+
return `[assistant${message.agent ? ` ${message.agent}` : ""}]${finish}\n${blocks.join("\n\n")}`;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Renders a session transcript, keeping the newest turns when it does not fit.
|
|
102
|
+
* The final assistant text is repeated at the end so the parent can quote it
|
|
103
|
+
* even when the middle of the transcript was dropped.
|
|
104
|
+
*/
|
|
105
|
+
export function formatTranscript(messages, maxChars = DEFAULT_MAX_CHARS) {
|
|
106
|
+
const budget = Math.max(MIN_MAX_CHARS, Math.min(maxChars, MAX_MAX_CHARS));
|
|
107
|
+
const entries = messages
|
|
108
|
+
.map(formatMessage)
|
|
109
|
+
.filter((entry) => entry.length > 0);
|
|
110
|
+
let text = entries.join("\n\n");
|
|
111
|
+
if (text.length <= budget) {
|
|
112
|
+
return { text, messages: entries.length, truncated: false };
|
|
113
|
+
}
|
|
114
|
+
const kept = [];
|
|
115
|
+
let size = 0;
|
|
116
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
117
|
+
const entry = entries[index];
|
|
118
|
+
if (size + entry.length + 2 > budget)
|
|
119
|
+
break;
|
|
120
|
+
kept.unshift(entry);
|
|
121
|
+
size += entry.length + 2;
|
|
122
|
+
}
|
|
123
|
+
const dropped = entries.length - kept.length;
|
|
124
|
+
const notice = `[... ${dropped} older transcript block${dropped === 1 ? "" : "s"} omitted to stay inside ${budget} characters; pass a larger maxChars to see them]`;
|
|
125
|
+
text = [notice, ...kept].join("\n\n");
|
|
126
|
+
return { text, messages: entries.length, truncated: true };
|
|
127
|
+
}
|
|
128
|
+
function listLine(session) {
|
|
129
|
+
const when = session.updated
|
|
130
|
+
? new Date(session.updated).toISOString()
|
|
131
|
+
: "unknown time";
|
|
132
|
+
return `- ${session.id} - ${session.title ?? "(untitled)"} - agent ${session.agent ?? "?"} - ${session.outcome ?? "unknown"} - updated ${when}`;
|
|
133
|
+
}
|
|
134
|
+
async function execute(deps, raw, context) {
|
|
135
|
+
if (!isGatedSession(deps, context.sessionID))
|
|
136
|
+
return fail(GATED_TEXT);
|
|
137
|
+
const input = (raw ?? {});
|
|
138
|
+
const requested = typeof input.sessionID === "string" && input.sessionID.trim()
|
|
139
|
+
? input.sessionID.trim()
|
|
140
|
+
: undefined;
|
|
141
|
+
if (!requested) {
|
|
142
|
+
const children = deps.listSubagentSessions
|
|
143
|
+
? await deps.listSubagentSessions(context.sessionID).catch(() => [])
|
|
144
|
+
: [];
|
|
145
|
+
if (children.length === 0) {
|
|
146
|
+
return done("This session has no child sessions yet. The `subagent` tool returns a sessionID when a child starts.", { ok: true, children: 0 });
|
|
147
|
+
}
|
|
148
|
+
return done(["Child sessions of this session:", ...children.map(listLine)].join("\n"), { ok: true, children: children.length });
|
|
149
|
+
}
|
|
150
|
+
if (!deps.readSession) {
|
|
151
|
+
return fail("Reading subagent sessions is not available in this OpenCode build.");
|
|
152
|
+
}
|
|
153
|
+
const info = await deps.readSession(requested).catch(() => undefined);
|
|
154
|
+
if (!info)
|
|
155
|
+
return fail(`No OpenCode session with id ${requested}.`);
|
|
156
|
+
if (info.parentID !== context.sessionID) {
|
|
157
|
+
return fail(`${requested} is not a subagent of this session, so its transcript cannot be read here.`);
|
|
158
|
+
}
|
|
159
|
+
const messages = await deps.readContext(requested).catch(() => []);
|
|
160
|
+
if (messages.length === 0) {
|
|
161
|
+
return done(`The subagent session ${requested} has no messages yet. It may still be starting.`, { ok: false, sessionID: requested, messages: 0 });
|
|
162
|
+
}
|
|
163
|
+
const budget = typeof input.maxChars === "number" && Number.isFinite(input.maxChars)
|
|
164
|
+
? input.maxChars
|
|
165
|
+
: DEFAULT_MAX_CHARS;
|
|
166
|
+
const transcript = formatTranscript(messages, budget);
|
|
167
|
+
const header = [
|
|
168
|
+
`Subagent session ${requested}${info.title ? ` - ${info.title}` : ""}`,
|
|
169
|
+
`agent: ${info.agent ?? "?"} - outcome: ${info.outcome ?? "running"} - stored messages: ${messages.length}`,
|
|
170
|
+
].join("\n");
|
|
171
|
+
deps.log.info("free_pi_subagent_read answered", {
|
|
172
|
+
sessionID: context.sessionID,
|
|
173
|
+
child: requested,
|
|
174
|
+
messages: transcript.messages,
|
|
175
|
+
truncated: transcript.truncated,
|
|
176
|
+
});
|
|
177
|
+
return done(`${header}\n\n${transcript.text}`, {
|
|
178
|
+
ok: true,
|
|
179
|
+
sessionID: requested,
|
|
180
|
+
parentID: info.parentID,
|
|
181
|
+
agent: info.agent,
|
|
182
|
+
outcome: info.outcome,
|
|
183
|
+
messages: transcript.messages,
|
|
184
|
+
truncated: transcript.truncated,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
export async function registerSubagentTool(ctx, deps) {
|
|
188
|
+
return ctx.tool.transform((editor) => {
|
|
189
|
+
editor.add({
|
|
190
|
+
name: "free_pi_subagent_read",
|
|
191
|
+
description: "Read the transcript of a subagent session started from this session: its prompts, tool calls with inputs and results, and final answer. Pass the child sessionID returned by `subagent`, or omit it to list this session's children. Read-only; only child sessions of the calling session are readable.",
|
|
192
|
+
input: INPUT_SCHEMA,
|
|
193
|
+
options: { codemode: false },
|
|
194
|
+
execute: (input, context) => execute(deps, input, context),
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -290,3 +290,14 @@ export type SessionMessageInfo = {
|
|
|
290
290
|
[key: string]: unknown;
|
|
291
291
|
};
|
|
292
292
|
export type ReadContext = (sessionID: string) => Promise<readonly SessionMessageInfo[]>;
|
|
293
|
+
/** Minimal view of an OpenCode V2 session header. */
|
|
294
|
+
export type SubagentSessionInfo = {
|
|
295
|
+
id: string;
|
|
296
|
+
parentID?: string;
|
|
297
|
+
title?: string;
|
|
298
|
+
agent?: string;
|
|
299
|
+
outcome?: string;
|
|
300
|
+
updated?: number;
|
|
301
|
+
};
|
|
302
|
+
export type ReadSessionInfo = (sessionID: string) => Promise<SubagentSessionInfo | undefined>;
|
|
303
|
+
export type ListSubagentSessions = (parentID: string) => Promise<readonly SubagentSessionInfo[]>;
|
package/package.json
CHANGED
|
@@ -48,6 +48,9 @@ it.
|
|
|
48
48
|
## Tools
|
|
49
49
|
- \`free_pi_usage\` shows today's remaining allowance, credits, token counts and
|
|
50
50
|
the account tier. Read-only.
|
|
51
|
+
- \`free_pi_subagent_read\` reads the transcript of a child session started with
|
|
52
|
+
the \`subagent\` tool: its prompts, every tool call with input and result, and
|
|
53
|
+
its final answer. Read-only; omit \`sessionID\` to list this session's children.
|
|
51
54
|
- \`look_at_image\` asks a vision model about a PNG, JPEG or WebP inside the
|
|
52
55
|
project. Use it when the current model takes text only, or when the image is a
|
|
53
56
|
file on disk and you want a targeted answer instead of attaching it.
|
|
@@ -73,7 +76,10 @@ Use OpenCode's native subagent tool with the agents this plugin installs:
|
|
|
73
76
|
Subagents inherit the free-pi model, share the same daily allowance, and run as
|
|
74
77
|
child sessions in the background. Keep large exploration in a subagent so it
|
|
75
78
|
does not fill your own context. Use OpenCode's agent picker or the \`subagent\`
|
|
76
|
-
tool; do not try to launch them through shell commands.
|
|
79
|
+
tool; do not try to launch them through shell commands. The \`subagent\` tool
|
|
80
|
+
returns the child \`sessionID\` and OpenCode injects the child's report when it
|
|
81
|
+
goes idle; call \`free_pi_subagent_read\` with that id to see what the child ran
|
|
82
|
+
and why its answer says what it says.
|
|
77
83
|
|
|
78
84
|
## Memory and sessions
|
|
79
85
|
|
package/src/constants.ts
CHANGED
|
@@ -77,7 +77,7 @@ 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.
|
|
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. 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).
|
|
81
81
|
- Load a skill with the native \`skill\` tool when its description matches the task.
|
|
82
82
|
- \`AGENTS.md\` and the files listed under \`instructions\` are the project's memory. Follow them; do not restate or replace them.
|
|
83
83
|
- Never claim to have compacted, summarized or cleared context unless that actually happened.
|
|
@@ -105,6 +105,16 @@ export const RETRY_MAX_RETRIES = 3;
|
|
|
105
105
|
export const RETRY_BASE_DELAY_MS = 2_000;
|
|
106
106
|
export const RETRY_MAX_DELAY_MS = 60_000;
|
|
107
107
|
|
|
108
|
+
/**
|
|
109
|
+
* Transport failures (a refused or dropped connection, DNS blips) usually
|
|
110
|
+
* clear on their own. OpenCode stops after its own retries, which can end a
|
|
111
|
+
* turn during a brief local network or service restart, so the plugin gives
|
|
112
|
+
* them a longer budget before giving up.
|
|
113
|
+
*/
|
|
114
|
+
export const TRANSPORT_RETRY_MAX = 5;
|
|
115
|
+
export const TRANSPORT_RETRY_BASE_MS = 2_000;
|
|
116
|
+
export const TRANSPORT_RETRY_MAX_DELAY_MS = 30_000;
|
|
117
|
+
|
|
108
118
|
/**
|
|
109
119
|
* free-pi allows one in-flight request per `x-session-id` and answers a second
|
|
110
120
|
* one with `429 concurrent`. OpenCode does not retry that itself, and a slot
|
package/src/deps.ts
CHANGED
|
@@ -4,13 +4,20 @@ import type { Credential } from "@opencode/schema/credential";
|
|
|
4
4
|
import type { Plugin } from "@opencode/plugin";
|
|
5
5
|
import type { Logger } from "./logging.js";
|
|
6
6
|
import type { RuntimeState } from "./state.js";
|
|
7
|
-
import type {
|
|
7
|
+
import type {
|
|
8
|
+
ListSubagentSessions,
|
|
9
|
+
ReadContext,
|
|
10
|
+
ReadSessionInfo,
|
|
11
|
+
} from "./types.js";
|
|
8
12
|
|
|
9
13
|
export type Deps = {
|
|
10
14
|
readonly state: RuntimeState;
|
|
11
15
|
readonly log: Logger;
|
|
12
16
|
readonly activeCredential: () => Promise<Credential.Value | undefined>;
|
|
13
17
|
readonly readContext: ReadContext;
|
|
18
|
+
/** Session headers, used to prove a session is really this session's child. */
|
|
19
|
+
readonly readSession?: ReadSessionInfo;
|
|
20
|
+
readonly listSubagentSessions?: ListSubagentSessions;
|
|
14
21
|
/** Plugin-scoped durable storage, used to reconnect provider sessions. */
|
|
15
22
|
readonly storage?: Plugin.Context["storage"];
|
|
16
23
|
};
|
package/src/plugin.ts
CHANGED
|
@@ -45,6 +45,7 @@ import { cancelAllFinalizeTimers } from "./session/track.js";
|
|
|
45
45
|
import { createRuntimeState } from "./state.js";
|
|
46
46
|
import { registerGenerateImageTool } from "./tools/image-generate.js";
|
|
47
47
|
import { registerUsageTool } from "./tools/usage.js";
|
|
48
|
+
import { registerSubagentTool } from "./tools/subagent.js";
|
|
48
49
|
import { registerVisionTool } from "./tools/vision.js";
|
|
49
50
|
import { registerWebTools } from "./tools/web.js";
|
|
50
51
|
import { settle } from "./utils/async.js";
|
|
@@ -77,6 +78,36 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
77
78
|
return [];
|
|
78
79
|
}
|
|
79
80
|
},
|
|
81
|
+
readSession: async (sessionID) => {
|
|
82
|
+
try {
|
|
83
|
+
const info = await ctx.session.get({ sessionID });
|
|
84
|
+
return {
|
|
85
|
+
id: info.id,
|
|
86
|
+
parentID: info.parentID,
|
|
87
|
+
title: info.title,
|
|
88
|
+
agent: info.agent,
|
|
89
|
+
outcome: info.outcome,
|
|
90
|
+
updated: info.time?.updated,
|
|
91
|
+
};
|
|
92
|
+
} catch {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
listSubagentSessions: async (parentID) => {
|
|
97
|
+
try {
|
|
98
|
+
const result = await ctx.session.list({ parentID, limit: 50 });
|
|
99
|
+
return (result.data ?? []).map((info) => ({
|
|
100
|
+
id: info.id,
|
|
101
|
+
parentID: info.parentID,
|
|
102
|
+
title: info.title,
|
|
103
|
+
agent: info.agent,
|
|
104
|
+
outcome: info.outcome,
|
|
105
|
+
updated: info.time?.updated,
|
|
106
|
+
}));
|
|
107
|
+
} catch {
|
|
108
|
+
return [];
|
|
109
|
+
}
|
|
110
|
+
},
|
|
80
111
|
storage: ctx.storage,
|
|
81
112
|
};
|
|
82
113
|
|
|
@@ -258,6 +289,10 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
258
289
|
}> = [
|
|
259
290
|
{ name: "look_at_image", register: () => registerVisionTool(ctx, deps) },
|
|
260
291
|
{ name: "free_pi_usage", register: () => registerUsageTool(ctx, deps) },
|
|
292
|
+
{
|
|
293
|
+
name: "free_pi_subagent_read",
|
|
294
|
+
register: () => registerSubagentTool(ctx, deps),
|
|
295
|
+
},
|
|
261
296
|
{ name: "web", register: () => registerWebTools(ctx, deps) },
|
|
262
297
|
{ name: "generate_image", register: () => registerGenerateImageTool(ctx, deps) },
|
|
263
298
|
];
|
package/src/session/hooks.ts
CHANGED
|
@@ -23,6 +23,9 @@ import {
|
|
|
23
23
|
RETRY_MAX_DELAY_MS,
|
|
24
24
|
RETRY_MAX_RETRIES,
|
|
25
25
|
SUBAGENT_HEADER,
|
|
26
|
+
TRANSPORT_RETRY_BASE_MS,
|
|
27
|
+
TRANSPORT_RETRY_MAX,
|
|
28
|
+
TRANSPORT_RETRY_MAX_DELAY_MS,
|
|
26
29
|
} from "../constants.js";
|
|
27
30
|
import {
|
|
28
31
|
currentLiveLimits,
|
|
@@ -333,6 +336,22 @@ const TERMINAL_RETRY_CODES = new Set([
|
|
|
333
336
|
const TERMINAL_RETRY_PATTERN =
|
|
334
337
|
/free usage limit|monthly usage limit|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/i;
|
|
335
338
|
|
|
339
|
+
/**
|
|
340
|
+
* A request that never reached the gateway. `provider.transport` covers the
|
|
341
|
+
* typed path, while the pattern catches bare fetch errors. These are worth
|
|
342
|
+
* retrying beyond the usual budget: a brief offline moment or a background
|
|
343
|
+
* service restart is not a provider limit.
|
|
344
|
+
*/
|
|
345
|
+
const TRANSPORT_RETRY_PATTERN =
|
|
346
|
+
/ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|EPIPE|socket hang up|fetch failed|Unable to connect|connection (?:refused|reset)/i;
|
|
347
|
+
|
|
348
|
+
function isTransportFailure(error: any): boolean {
|
|
349
|
+
const type = typeof error?.type === "string" ? error.type : "";
|
|
350
|
+
if (/transport|network|connection/i.test(type)) return true;
|
|
351
|
+
const message = `${error?.message ?? ""}\n${error?.cause?.message ?? ""}`;
|
|
352
|
+
return TRANSPORT_RETRY_PATTERN.test(message);
|
|
353
|
+
}
|
|
354
|
+
|
|
336
355
|
function isTerminalFailure(error: any): boolean {
|
|
337
356
|
if (
|
|
338
357
|
error?.type === "aborted" ||
|
|
@@ -392,6 +411,30 @@ function applyRetryPolicy(deps: Deps, event: any): void {
|
|
|
392
411
|
event.decision = { retry: false };
|
|
393
412
|
return;
|
|
394
413
|
}
|
|
414
|
+
if (isTransportFailure(event.error)) {
|
|
415
|
+
if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
|
|
416
|
+
event.decision = { retry: false };
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
// A connection that dropped mid-turn can leave the gateway's per-session
|
|
420
|
+
// slot marked busy, so the next attempt should not reuse the wire id.
|
|
421
|
+
markWireSessionDirty(deps, event.sessionID);
|
|
422
|
+
const attempt = Math.max(1, event.attempt - 1);
|
|
423
|
+
event.decision = {
|
|
424
|
+
retry: true,
|
|
425
|
+
delay: Math.min(
|
|
426
|
+
TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1),
|
|
427
|
+
TRANSPORT_RETRY_MAX_DELAY_MS,
|
|
428
|
+
),
|
|
429
|
+
};
|
|
430
|
+
deps.log.warn("free-pi could not be reached; retrying", {
|
|
431
|
+
sessionID: event.sessionID,
|
|
432
|
+
attempt: event.attempt,
|
|
433
|
+
delay: event.decision.delay,
|
|
434
|
+
error: typeof event.error?.message === "string" ? event.error.message : undefined,
|
|
435
|
+
});
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
395
438
|
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
396
439
|
event.decision = { retry: false };
|
|
397
440
|
return;
|
package/src/session/tools.ts
CHANGED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `free_pi_subagent_read`, a transcript reader for child sessions.
|
|
3
|
+
*
|
|
4
|
+
* OpenCode's `subagent` tool reports the child's final output and pings the
|
|
5
|
+
* parent when the child goes idle, but the parent cannot open the child's
|
|
6
|
+
* conversation afterwards. This tool fills that gap: it reads the transcript
|
|
7
|
+
* of a session that is really a child of the calling session, so the parent can
|
|
8
|
+
* see every task the subagent ran (tool calls with input and result) and quote
|
|
9
|
+
* its answer.
|
|
10
|
+
*
|
|
11
|
+
* Read-only. The session is checked against its `parentID`, so a model cannot
|
|
12
|
+
* use it to read unrelated sessions.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { Plugin } from "@opencode/plugin";
|
|
16
|
+
import type { Deps } from "../deps.js";
|
|
17
|
+
import { done, fail, GATED_TEXT, isGatedSession } from "./api.js";
|
|
18
|
+
|
|
19
|
+
const DEFAULT_MAX_CHARS = 60_000;
|
|
20
|
+
const MIN_MAX_CHARS = 2_000;
|
|
21
|
+
const MAX_MAX_CHARS = 200_000;
|
|
22
|
+
const TOOL_RESULT_CHARS = 2_000;
|
|
23
|
+
const TOOL_INPUT_CHARS = 1_500;
|
|
24
|
+
const USER_TEXT_CHARS = 8_000;
|
|
25
|
+
const ASSISTANT_TEXT_CHARS = 16_000;
|
|
26
|
+
|
|
27
|
+
const INPUT_SCHEMA = {
|
|
28
|
+
type: "object",
|
|
29
|
+
additionalProperties: false,
|
|
30
|
+
properties: {
|
|
31
|
+
sessionID: {
|
|
32
|
+
type: "string",
|
|
33
|
+
description:
|
|
34
|
+
"Child session to read, as returned by the `subagent` tool. Omit it to list this session's children.",
|
|
35
|
+
},
|
|
36
|
+
maxChars: {
|
|
37
|
+
type: "integer",
|
|
38
|
+
minimum: MIN_MAX_CHARS,
|
|
39
|
+
maximum: MAX_MAX_CHARS,
|
|
40
|
+
description: `Transcript budget in characters (default ${DEFAULT_MAX_CHARS}). The newest turns are kept.`,
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
} as const;
|
|
44
|
+
|
|
45
|
+
type Part = {
|
|
46
|
+
type?: string;
|
|
47
|
+
text?: string;
|
|
48
|
+
synthetic?: boolean;
|
|
49
|
+
name?: string;
|
|
50
|
+
state?: {
|
|
51
|
+
status?: string;
|
|
52
|
+
input?: unknown;
|
|
53
|
+
content?: unknown;
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
type Message = {
|
|
58
|
+
id?: string;
|
|
59
|
+
type?: string;
|
|
60
|
+
role?: string;
|
|
61
|
+
text?: string;
|
|
62
|
+
agent?: string;
|
|
63
|
+
finish?: string;
|
|
64
|
+
error?: unknown;
|
|
65
|
+
content?: unknown;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
function cut(value: string, limit: number): string {
|
|
69
|
+
const text = value.trim();
|
|
70
|
+
if (text.length <= limit) return text;
|
|
71
|
+
return `${text.slice(0, limit)}\n[... ${text.length - limit} characters cut]`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function stringify(value: unknown): string {
|
|
75
|
+
if (typeof value === "string") return value;
|
|
76
|
+
try {
|
|
77
|
+
return JSON.stringify(value, null, 2) ?? "";
|
|
78
|
+
} catch {
|
|
79
|
+
return String(value ?? "");
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function textOfContent(content: unknown): string {
|
|
84
|
+
if (typeof content === "string") return content;
|
|
85
|
+
if (!Array.isArray(content)) return "";
|
|
86
|
+
return content
|
|
87
|
+
.filter(
|
|
88
|
+
(part: Part) => part?.type === "text" && part.synthetic !== true,
|
|
89
|
+
)
|
|
90
|
+
.map((part: Part) => part.text ?? "")
|
|
91
|
+
.join("\n");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function formatTool(part: Part): string {
|
|
95
|
+
const status = part.state?.status ?? "unknown";
|
|
96
|
+
const header = `[tool ${part.name ?? "?"}] ${status}`;
|
|
97
|
+
const input = stringify(part.state?.input ?? {});
|
|
98
|
+
const output = textOfContent(part.state?.content);
|
|
99
|
+
return [
|
|
100
|
+
header,
|
|
101
|
+
`input: ${cut(input, TOOL_INPUT_CHARS)}`,
|
|
102
|
+
...(output.trim() ? [`result: ${cut(output, TOOL_RESULT_CHARS)}`] : []),
|
|
103
|
+
].join("\n");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function formatMessage(message: Message): string {
|
|
107
|
+
const role = message.role ?? message.type;
|
|
108
|
+
if (role === "user") {
|
|
109
|
+
const text = message.text ?? textOfContent(message.content);
|
|
110
|
+
return text.trim() ? `[user]\n${cut(text, USER_TEXT_CHARS)}` : "";
|
|
111
|
+
}
|
|
112
|
+
if (role !== "assistant") return "";
|
|
113
|
+
|
|
114
|
+
const blocks: string[] = [];
|
|
115
|
+
const content = Array.isArray(message.content) ? message.content : [];
|
|
116
|
+
for (const part of content as Part[]) {
|
|
117
|
+
if (part?.type === "text" && part.synthetic !== true) {
|
|
118
|
+
const text = part.text ?? "";
|
|
119
|
+
if (text.trim()) blocks.push(cut(text, ASSISTANT_TEXT_CHARS));
|
|
120
|
+
} else if (part?.type === "tool") {
|
|
121
|
+
blocks.push(formatTool(part));
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (blocks.length === 0) return "";
|
|
125
|
+
const finish =
|
|
126
|
+
message.finish && message.finish !== "stop" ? ` (${message.finish})` : "";
|
|
127
|
+
return `[assistant${message.agent ? ` ${message.agent}` : ""}]${finish}\n${blocks.join("\n\n")}`;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export type Transcript = {
|
|
131
|
+
readonly text: string;
|
|
132
|
+
readonly messages: number;
|
|
133
|
+
readonly truncated: boolean;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Renders a session transcript, keeping the newest turns when it does not fit.
|
|
138
|
+
* The final assistant text is repeated at the end so the parent can quote it
|
|
139
|
+
* even when the middle of the transcript was dropped.
|
|
140
|
+
*/
|
|
141
|
+
export function formatTranscript(
|
|
142
|
+
messages: readonly unknown[],
|
|
143
|
+
maxChars = DEFAULT_MAX_CHARS,
|
|
144
|
+
): Transcript {
|
|
145
|
+
const budget = Math.max(MIN_MAX_CHARS, Math.min(maxChars, MAX_MAX_CHARS));
|
|
146
|
+
const entries = (messages as Message[])
|
|
147
|
+
.map(formatMessage)
|
|
148
|
+
.filter((entry) => entry.length > 0);
|
|
149
|
+
|
|
150
|
+
let text = entries.join("\n\n");
|
|
151
|
+
if (text.length <= budget) {
|
|
152
|
+
return { text, messages: entries.length, truncated: false };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const kept: string[] = [];
|
|
156
|
+
let size = 0;
|
|
157
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
158
|
+
const entry = entries[index]!;
|
|
159
|
+
if (size + entry.length + 2 > budget) break;
|
|
160
|
+
kept.unshift(entry);
|
|
161
|
+
size += entry.length + 2;
|
|
162
|
+
}
|
|
163
|
+
const dropped = entries.length - kept.length;
|
|
164
|
+
const notice = `[... ${dropped} older transcript block${dropped === 1 ? "" : "s"} omitted to stay inside ${budget} characters; pass a larger maxChars to see them]`;
|
|
165
|
+
text = [notice, ...kept].join("\n\n");
|
|
166
|
+
return { text, messages: entries.length, truncated: true };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function listLine(session: {
|
|
170
|
+
id: string;
|
|
171
|
+
title?: string;
|
|
172
|
+
agent?: string;
|
|
173
|
+
outcome?: string;
|
|
174
|
+
updated?: number;
|
|
175
|
+
}): string {
|
|
176
|
+
const when = session.updated
|
|
177
|
+
? new Date(session.updated).toISOString()
|
|
178
|
+
: "unknown time";
|
|
179
|
+
return `- ${session.id} - ${session.title ?? "(untitled)"} - agent ${session.agent ?? "?"} - ${session.outcome ?? "unknown"} - updated ${when}`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function execute(
|
|
183
|
+
deps: Deps,
|
|
184
|
+
raw: unknown,
|
|
185
|
+
context: { readonly sessionID: string; readonly signal: AbortSignal },
|
|
186
|
+
) {
|
|
187
|
+
if (!isGatedSession(deps, context.sessionID)) return fail(GATED_TEXT);
|
|
188
|
+
const input = (raw ?? {}) as { sessionID?: unknown; maxChars?: unknown };
|
|
189
|
+
const requested =
|
|
190
|
+
typeof input.sessionID === "string" && input.sessionID.trim()
|
|
191
|
+
? input.sessionID.trim()
|
|
192
|
+
: undefined;
|
|
193
|
+
|
|
194
|
+
if (!requested) {
|
|
195
|
+
const children = deps.listSubagentSessions
|
|
196
|
+
? await deps.listSubagentSessions(context.sessionID).catch(() => [])
|
|
197
|
+
: [];
|
|
198
|
+
if (children.length === 0) {
|
|
199
|
+
return done(
|
|
200
|
+
"This session has no child sessions yet. The `subagent` tool returns a sessionID when a child starts.",
|
|
201
|
+
{ ok: true, children: 0 },
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
return done(
|
|
205
|
+
["Child sessions of this session:", ...children.map(listLine)].join("\n"),
|
|
206
|
+
{ ok: true, children: children.length },
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (!deps.readSession) {
|
|
211
|
+
return fail("Reading subagent sessions is not available in this OpenCode build.");
|
|
212
|
+
}
|
|
213
|
+
const info = await deps.readSession(requested).catch(() => undefined);
|
|
214
|
+
if (!info) return fail(`No OpenCode session with id ${requested}.`);
|
|
215
|
+
if (info.parentID !== context.sessionID) {
|
|
216
|
+
return fail(
|
|
217
|
+
`${requested} is not a subagent of this session, so its transcript cannot be read here.`,
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const messages = await deps.readContext(requested).catch(() => []);
|
|
222
|
+
if (messages.length === 0) {
|
|
223
|
+
return done(
|
|
224
|
+
`The subagent session ${requested} has no messages yet. It may still be starting.`,
|
|
225
|
+
{ ok: false, sessionID: requested, messages: 0 },
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const budget =
|
|
230
|
+
typeof input.maxChars === "number" && Number.isFinite(input.maxChars)
|
|
231
|
+
? input.maxChars
|
|
232
|
+
: DEFAULT_MAX_CHARS;
|
|
233
|
+
const transcript = formatTranscript(messages, budget);
|
|
234
|
+
const header = [
|
|
235
|
+
`Subagent session ${requested}${info.title ? ` - ${info.title}` : ""}`,
|
|
236
|
+
`agent: ${info.agent ?? "?"} - outcome: ${info.outcome ?? "running"} - stored messages: ${messages.length}`,
|
|
237
|
+
].join("\n");
|
|
238
|
+
|
|
239
|
+
deps.log.info("free_pi_subagent_read answered", {
|
|
240
|
+
sessionID: context.sessionID,
|
|
241
|
+
child: requested,
|
|
242
|
+
messages: transcript.messages,
|
|
243
|
+
truncated: transcript.truncated,
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
return done(`${header}\n\n${transcript.text}`, {
|
|
247
|
+
ok: true,
|
|
248
|
+
sessionID: requested,
|
|
249
|
+
parentID: info.parentID,
|
|
250
|
+
agent: info.agent,
|
|
251
|
+
outcome: info.outcome,
|
|
252
|
+
messages: transcript.messages,
|
|
253
|
+
truncated: transcript.truncated,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export async function registerSubagentTool(
|
|
258
|
+
ctx: Plugin.Context,
|
|
259
|
+
deps: Deps,
|
|
260
|
+
): Promise<{ dispose: () => Promise<void> }> {
|
|
261
|
+
return ctx.tool.transform((editor) => {
|
|
262
|
+
editor.add({
|
|
263
|
+
name: "free_pi_subagent_read",
|
|
264
|
+
description:
|
|
265
|
+
"Read the transcript of a subagent session started from this session: its prompts, tool calls with inputs and results, and final answer. Pass the child sessionID returned by `subagent`, or omit it to list this session's children. Read-only; only child sessions of the calling session are readable.",
|
|
266
|
+
input: INPUT_SCHEMA,
|
|
267
|
+
options: { codemode: false },
|
|
268
|
+
execute: (input: unknown, context: any) => execute(deps, input, context),
|
|
269
|
+
} as any);
|
|
270
|
+
});
|
|
271
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -280,3 +280,21 @@ export type SessionMessageInfo =
|
|
|
280
280
|
export type ReadContext = (
|
|
281
281
|
sessionID: string,
|
|
282
282
|
) => Promise<readonly SessionMessageInfo[]>;
|
|
283
|
+
|
|
284
|
+
/** Minimal view of an OpenCode V2 session header. */
|
|
285
|
+
export type SubagentSessionInfo = {
|
|
286
|
+
id: string;
|
|
287
|
+
parentID?: string;
|
|
288
|
+
title?: string;
|
|
289
|
+
agent?: string;
|
|
290
|
+
outcome?: string;
|
|
291
|
+
updated?: number;
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
export type ReadSessionInfo = (
|
|
295
|
+
sessionID: string,
|
|
296
|
+
) => Promise<SubagentSessionInfo | undefined>;
|
|
297
|
+
|
|
298
|
+
export type ListSubagentSessions = (
|
|
299
|
+
parentID: string,
|
|
300
|
+
) => Promise<readonly SubagentSessionInfo[]>;
|