@eduardo191labs/opencode-free-pi 0.6.3 → 0.6.5

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 CHANGED
@@ -87,14 +87,16 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
87
87
  El plugin lo responde con la primera línea del primer mensaje, sin gastar
88
88
  créditos, sin pedir un anuncio y sin dejar la sesión atascada en
89
89
  «New session».
90
- - **Capacidades según el modelo**: los modelos que models.dev identifica como
91
- multimodales anuncian entrada de imágenes y el gateway las reenvía al modelo
92
- upstream. Los modelos de solo texto siguen usando `look_at_image`, porque
93
- incrustar cada imagen leída (cientos de KB) en la conversación desborda la
94
- ventana y gasta cuota en tokens de imagen; OpenCode sustituye las imágenes por
95
- un aviso y el plugin aplica el mismo aviso al terminar la herramienta para que
96
- el base64 no quede guardado en la sesión. La salida es siempre texto: la ruta
97
- de chat no devuelve imágenes.
90
+ - **Capacidades según el modelo**: los modelos gratuitos aceptan imágenes de
91
+ entrada de forma nativa; se comprobó con `curl_cffi` contra el gateway y los
92
+ cuatro transcriben una captura adjunta. Los alias de pago anuncian lo que
93
+ models.dev sabe de su modelo upstream. La salida es siempre texto: la ruta de
94
+ chat no devuelve imágenes. Para una imagen en disco o para un modelo de solo
95
+ texto sigue estando `look_at_image`, que además no deja el base64 en la
96
+ conversación. OpenCode recodifica los adjuntos grandes a 2000 px y cuenta su
97
+ base64 como tokens, así que una imagen de más de ~500 KB puede disparar una
98
+ compactación automática antes del turno; en ese caso conviene `look_at_image`,
99
+ que reescala y envía solo lo necesario.
98
100
  - **Subagentes identificados**: las sesiones hijas envían
99
101
  `x-freepi-subagent: 1`, igual que los proveedores que el CLI crea para sus
100
102
  subagentes.
@@ -163,22 +165,33 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
163
165
  hook de respuesta y entrega el resultado a OpenCode, así que el turno sigue sin
164
166
  mostrar «one request at a time»; el reintento normal también rota el id como
165
167
  respaldo.
166
- - **Catálogo y metadatos resistentes**: el catálogo de free-pi y el registro de
167
- models.dev se guardan en disco; si la red falla al arrancar se usan las copias
168
- locales en vez de quedarse sin modelos o sin límites de contexto. Los avisos
169
- que el servidor manda en el catálogo y en `/me` (`notice`) se registran una
170
- vez en el log del plugin.
168
+ - **Catálogo y metadatos en vivo**: el catálogo de free-pi y el registro de
169
+ models.dev se consultan en cada arranque y solo se guardan en memoria para el
170
+ proceso actual. El único archivo persistente es `live-limits.json`, con la
171
+ ventana y los tokens que el servidor confirmó. Si la red falla, se usa lo que
172
+ ya esté en memoria en vez de inventar límites. Los avisos que el servidor
173
+ manda en el catálogo y en `/me` (`notice`) se registran una vez en el log del
174
+ plugin.
175
+ - **Aislamiento por proveedor**: todo lo que añade el plugin —herramientas,
176
+ cabeceras, anuncios, reglas de prompt, compactación, reintentos, topes de
177
+ tokens y ajustes— se aplica solo a `free-pi` y `free-pi-defense`. Los demás
178
+ proveedores no reciben las herramientas en su lista (el plugin las quita de la
179
+ petición), no ven las cabeceras free-pi y conservan sus propias imágenes y su
180
+ propio uso. Si una sesión cambia de free-pi a otro modelo, pierde las
181
+ herramientas en la siguiente petición y las llamadas directas se rechazan.
171
182
  - Compatible con rutas, credenciales y navegador de cada sistema operativo.
172
183
 
173
184
  ## Lectura de imágenes
174
185
 
175
- Los modelos siguen siendo solo texto, igual que en el CLI. Para mirar una
176
- captura de pantalla o cualquier imagen del proyecto, el modelo llama a la
177
- herramienta `look_at_image` con una ruta y una pregunta concreta. El plugin:
186
+ Los modelos gratuitos de free-pi aceptan imágenes adjuntas de forma nativa: al
187
+ adjuntar una captura en la conversación, el gateway la reenvía al modelo upstream
188
+ y el modelo la ve. En los modelos de solo texto, o cuando la imagen está en disco
189
+ y no conviene cargarla entera, el modelo llama a `look_at_image` con una ruta y
190
+ una pregunta concreta. El plugin:
178
191
 
192
+ - Acepta PNG, JPEG y WebP.
179
193
  - Solo lee archivos dentro de la carpeta del proyecto (incluidos enlaces
180
194
  simbólicos resueltos).
181
- - Acepta PNG, JPEG y WebP.
182
195
  - Lee las dimensiones de la cabecera y envía el archivo intacto mientras no
183
196
  supere los 5 MB, conservando la resolución y la calidad originales. Solo las
184
197
  imágenes mayores se recodifican con Photon, manteniendo el mayor tamaño y la
@@ -192,15 +205,18 @@ herramienta `look_at_image` con una ruta y una pregunta concreta. El plugin:
192
205
 
193
206
  Cada llamada consume parte del allowance diario del usuario, como en el CLI.
194
207
  La herramienta solo se ejecuta en sesiones de free-pi; en otros proveedores
195
- responde que no está disponible. Si el modelo intenta leer una imagen con
196
- `read`, el plugin sustituye el base64 por un aviso que le indica usar
197
- `look_at_image` con la misma ruta.
208
+ responde que no está disponible. Si el modelo activo acepta imágenes, un `read`
209
+ de una imagen conserva el archivo y el modelo la ve; si es de solo texto, el
210
+ plugin sustituye el base64 por un aviso que le indica usar `look_at_image` con la
211
+ misma ruta.
198
212
 
199
213
  ## Herramientas free-pi
200
214
 
201
- El plugin registra las mismas herramientas de servidor que el CLI. Todas
202
- comprueban que la sesión sea de free-pi antes de gastar cuota; en cualquier otro
203
- proveedor responden que no están disponibles.
215
+ El plugin registra las mismas herramientas de servidor que el CLI. OpenCode no
216
+ permite registrar una herramienta solo para un proveedor, así que el plugin las
217
+ quita de la lista de herramientas de cada petición servida por otro proveedor y,
218
+ además, todas comprueban que la sesión sea de free-pi antes de gastar cuota. Los
219
+ demás modelos no las ven ni pueden ejecutarlas.
204
220
 
205
221
  | Herramienta | Qué hace |
206
222
  | ---------------- | ------------------------------------------------------------------------ |
@@ -259,14 +275,34 @@ plano, comparten el allowance diario y envían su informe al agente principal.
259
275
  Así se conservan las sesiones hijas, los permisos, la profundidad de subagentes
260
276
  y el resto del comportamiento nativo.
261
277
 
278
+ La herramienta `subagent` es la de OpenCode y está disponible para **cualquier
279
+ modelo**, no solo para los agentes `free-pi/*`: también puede lanzarlos un
280
+ modelo de otro proveedor configurado en OpenCode. El plugin garantiza además que
281
+ todos los modelos gratuitos anuncien soporte de tools, de modo que el runner
282
+ nunca oculte `subagent` por una capacidad incorrecta de models.dev.
283
+
262
284
  El plugin solo reescribe estos archivos si conservan su marca de gestión; si el
263
285
  usuario edita o reemplaza uno, se respeta tal cual.
264
286
 
265
287
  ## Skill y contexto
266
288
 
267
- El plugin registra una skill `free-pi` mediante la API nativa de skills, con la
268
- lista de herramientas, los subagentes y las reglas de allowance. OpenCode la
269
- anuncia cuando es relevante y el agente la carga con su herramienta `skill`.
289
+ El plugin instala una skill nativa en:
290
+
291
+ ```text
292
+ ~/.config/opencode/skills/free-pi/SKILL.md
293
+ ```
294
+
295
+ OpenCode la descubre con su propio cargador (ID `free-pi`), la anuncia cuando es
296
+ relevante y el agente la carga con su herramienta `skill`. Contiene la lista de
297
+ herramientas, los subagentes y las reglas de allowance. Si el directorio de
298
+ configuración no se puede escribir, el plugin la registra mediante la API de
299
+ skills como respaldo.
300
+
301
+ Cada petición principal de free-pi recibe además una guía breve que pide
302
+ delegar el trabajo grande en `free-pi/scout`, `free-pi/planner`,
303
+ `free-pi/worker` o `free-pi/reviewer` con `subagent`, cargar skills con `skill`
304
+ y seguir `AGENTS.md` en lugar de inventar convenciones. Esa guía solo se añade a
305
+ las peticiones de `free-pi` y `free-pi-defense`.
270
306
 
271
307
  La memoria, las sesiones y el contexto son los de OpenCode: `AGENTS.md` y los
272
308
  archivos de `instructions` se cargan de forma nativa, las sesiones persisten y
@@ -21,10 +21,17 @@ 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. free-pi models are text-only, so use it instead of reading images.\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- `look_at_image` asks a vision model about a PNG, JPEG or WebP inside the\n project. Use it when the current model takes text only, or when the image is a\n file on disk and you want a targeted answer instead of attaching it.\n- `generate_image` draws one image from a prompt and saves it under `images/`.\n- `web_search` searches the web for current information.\n- `docs_lookup` looks up current library and framework documentation.\n\nEvery tool except `free_pi_usage` spends allowance. Usage limits\n(`daily_cap`, `rolling_cap`, concurrency) are terminal: stop and continue\nwithout the tool instead of retrying.\n\n## Subagents\n\nUse OpenCode's native subagent tool with the agents this plugin installs:\n\n| Agent | Use it for |\n| --- | --- |\n| `free-pi/scout` | Read-only recon: locate code and return structured findings. |\n| `free-pi/planner` | Read-only plan for a change, ready for a worker. |\n| `free-pi/worker` | Carry out one full task in its own context window. |\n| `free-pi/reviewer` | Read-only review with file and line references. |\n\nSubagents inherit the free-pi model, share the same daily allowance, and run as\nchild sessions in the background. Keep large exploration in a subagent so it\ndoes not fill your own context. Use OpenCode's agent picker or the `subagent`\ntool; do not try to launch them through shell commands.\n\n## Memory and sessions\n\nOpenCode owns memory and context: `AGENTS.md` and configured instruction files\nare loaded natively, sessions persist and resume, and compaction folds long\nconversations into a summary. Put durable project facts in `AGENTS.md` (or a\nfile listed under `instructions`) instead of repeating them in every prompt.\n\n## Native integrations\n\nMCP servers, skills, commands, references and permissions are configured in\nOpenCode as usual; free-pi does not replace them. Prefer those native features\nover running an external CLI.\n";
25
+ /**
26
+ * The same skill as a native `SKILL.md`. OpenCode discovers it from the global
27
+ * skills directory, so the file, its ID, its permissions and the `skill` tool
28
+ * all belong to OpenCode instead of a runtime registration.
29
+ */
30
+ export declare const FREE_PI_SKILL_FILE = "---\nname: free-pi\ndescription: How free-pi works in OpenCode: its tools, the installed native subagents, allowance and limits, and where sessions and memory live.\n---\n\n<!-- managed by @eduardo191labs/opencode-free-pi; delete this line to keep your own copy -->\n\n# free-pi in OpenCode\n\nfree-pi is a free, ad-supported provider for OpenCode. You sign in with GitHub\nand ads in the session pay for the inference; there is no model API key. The\nfree daily allowance is shared by every free-pi model and every tool that spends\nit.\n\n## Tools\n- `free_pi_usage` shows today's remaining allowance, credits, token counts and\n the account tier. Read-only.\n- `look_at_image` asks a vision model about a PNG, JPEG or WebP inside the\n project. Use it when the current model takes text only, or when the image is a\n file on disk and you want a targeted answer instead of attaching it.\n- `generate_image` draws one image from a prompt and saves it under `images/`.\n- `web_search` searches the web for current information.\n- `docs_lookup` looks up current library and framework documentation.\n\nEvery tool except `free_pi_usage` spends allowance. Usage limits\n(`daily_cap`, `rolling_cap`, concurrency) are terminal: stop and continue\nwithout the tool instead of retrying.\n\n## Subagents\n\nUse OpenCode's native subagent tool with the agents this plugin installs:\n\n| Agent | Use it for |\n| --- | --- |\n| `free-pi/scout` | Read-only recon: locate code and return structured findings. |\n| `free-pi/planner` | Read-only plan for a change, ready for a worker. |\n| `free-pi/worker` | Carry out one full task in its own context window. |\n| `free-pi/reviewer` | Read-only review with file and line references. |\n\nSubagents inherit the free-pi model, share the same daily allowance, and run as\nchild sessions in the background. Keep large exploration in a subagent so it\ndoes not fill your own context. Use OpenCode's agent picker or the `subagent`\ntool; do not try to launch them through shell commands.\n\n## Memory and sessions\n\nOpenCode owns memory and context: `AGENTS.md` and configured instruction files\nare loaded natively, sessions persist and resume, and compaction folds long\nconversations into a summary. Put durable project facts in `AGENTS.md` (or a\nfile listed under `instructions`) instead of repeating them in every prompt.\n\n## Native integrations\n\nMCP servers, skills, commands, references and permissions are configured in\nOpenCode as usual; free-pi does not replace them. Prefer those native features\nover running an external CLI.\n";
25
31
  /** OpenCode's user-wide config directory, where it loads custom agents. */
26
32
  export declare function openCodeConfigDir(): string;
27
33
  export declare function freePiAgentPath(configDir: string, id: FreePiAgentID): string;
34
+ export declare function freePiSkillPath(configDir: string): string;
28
35
  export type AgentInstallResult = {
29
36
  readonly installed: FreePiAgentID[];
30
37
  readonly skipped: FreePiAgentID[];
@@ -36,3 +43,14 @@ export type AgentInstallResult = {
36
43
  * treated as user-owned and left untouched.
37
44
  */
38
45
  export declare function installFreePiAgents(configDir?: string): Promise<AgentInstallResult>;
46
+ export type SkillInstallResult = {
47
+ readonly installed: boolean;
48
+ readonly skipped: boolean;
49
+ readonly changed: boolean;
50
+ };
51
+ /**
52
+ * Writes the free-pi skill as `skills/free-pi/SKILL.md`, the layout OpenCode's
53
+ * own skill loader reads. A file without our marker is user-owned and stays
54
+ * untouched, exactly like the agent files.
55
+ */
56
+ export declare function installFreePiSkill(configDir?: string): Promise<SkillInstallResult>;
@@ -40,7 +40,8 @@ it.
40
40
  - \`free_pi_usage\` shows today's remaining allowance, credits, token counts and
41
41
  the account tier. Read-only.
42
42
  - \`look_at_image\` asks a vision model about a PNG, JPEG or WebP inside the
43
- project. free-pi models are text-only, so use it instead of reading images.
43
+ project. Use it when the current model takes text only, or when the image is a
44
+ file on disk and you want a targeted answer instead of attaching it.
44
45
  - \`generate_image\` draws one image from a prompt and saves it under \`images/\`.
45
46
  - \`web_search\` searches the web for current information.
46
47
  - \`docs_lookup\` looks up current library and framework documentation.
@@ -78,6 +79,19 @@ MCP servers, skills, commands, references and permissions are configured in
78
79
  OpenCode as usual; free-pi does not replace them. Prefer those native features
79
80
  over running an external CLI.
80
81
  `;
82
+ /**
83
+ * The same skill as a native `SKILL.md`. OpenCode discovers it from the global
84
+ * skills directory, so the file, its ID, its permissions and the `skill` tool
85
+ * all belong to OpenCode instead of a runtime registration.
86
+ */
87
+ export const FREE_PI_SKILL_FILE = `---
88
+ name: ${FREE_PI_SKILL_NAME}
89
+ description: ${FREE_PI_SKILL_DESCRIPTION}
90
+ ---
91
+
92
+ ${MARKER}
93
+
94
+ ${FREE_PI_SKILL}`;
81
95
  const SCOUT = `---
82
96
  description: Read-only recon. Locates code, traces how pieces connect, and returns structured findings the lead can use without re-reading the files.
83
97
  mode: all
@@ -239,6 +253,9 @@ export function openCodeConfigDir() {
239
253
  export function freePiAgentPath(configDir, id) {
240
254
  return join(configDir, "agents", ...id.split("/")) + ".md";
241
255
  }
256
+ export function freePiSkillPath(configDir) {
257
+ return join(configDir, "skills", FREE_PI_SKILL_ID, "SKILL.md");
258
+ }
242
259
  async function fileState(path, content) {
243
260
  try {
244
261
  const current = await readFile(path, "utf8");
@@ -274,3 +291,21 @@ export async function installFreePiAgents(configDir = openCodeConfigDir()) {
274
291
  }
275
292
  return { installed, skipped, changed: installed.length > 0 };
276
293
  }
294
+ /**
295
+ * Writes the free-pi skill as `skills/free-pi/SKILL.md`, the layout OpenCode's
296
+ * own skill loader reads. A file without our marker is user-owned and stays
297
+ * untouched, exactly like the agent files.
298
+ */
299
+ export async function installFreePiSkill(configDir = openCodeConfigDir()) {
300
+ const path = freePiSkillPath(configDir);
301
+ const state = await fileState(path, FREE_PI_SKILL_FILE);
302
+ if (state === "same") {
303
+ return { installed: false, skipped: false, changed: false };
304
+ }
305
+ if (state === "protected") {
306
+ return { installed: false, skipped: true, changed: false };
307
+ }
308
+ await mkdir(dirname(path), { recursive: true });
309
+ await writeFile(path, FREE_PI_SKILL_FILE, "utf8");
310
+ return { installed: true, skipped: false, changed: true };
311
+ }
@@ -231,13 +231,16 @@ const KNOWN_INPUT_MODALITIES = new Set([
231
231
  /**
232
232
  * Native modalities for the chat route. models.dev describes the upstream
233
233
  * model, and the gateway forwards image parts to multimodal upstreams, so an
234
- * image-capable model is advertised as such. Output is always text: free-pi has
235
- * no image results on the chat route, and the plugin registers every model as
236
- * zero-cost text output.
234
+ * image-capable model is advertised as such. free-pi's free models were probed
235
+ * with `curl_cffi` and all of them transcribe an attached screenshot correctly
236
+ * even when models.dev has no entry for the alias, so free models always accept
237
+ * images. Output is always text: free-pi has no image results on the chat route.
237
238
  */
238
239
  function modelModalities(model, capability) {
239
240
  const declared = model.modalities?.input ?? capability?.modalities?.input;
240
241
  const input = (declared ?? ["text"]).filter((value) => KNOWN_INPUT_MODALITIES.has(value));
242
+ if (model.free === true && !input.includes("image"))
243
+ input.push("image");
241
244
  if (input.length === 0)
242
245
  input.push("text");
243
246
  if (!input.includes("text"))
@@ -295,7 +298,11 @@ export function buildModels(models, candidates = [], options = {}) {
295
298
  ...(defaultEffort ? { settings: { reasoningEffort: defaultEffort } } : {}),
296
299
  enabled: model.unavailable !== true,
297
300
  temperature: model.temperature ?? capability?.temperature ?? true,
298
- tool_call: model.tool_call ?? capability?.tool_call ?? true,
301
+ // All free models were probed against the gateway and call tools, so a
302
+ // models.dev entry that marks the matched upstream as text-only must not
303
+ // take away their tools. That would also hide OpenCode's native
304
+ // `subagent` tool. A `tool_call` value in free-pi's own catalog still wins.
305
+ tool_call: model.tool_call ?? (model.free === true ? true : capability?.tool_call ?? true),
299
306
  attachment: model.attachment ??
300
307
  capability?.attachment ??
301
308
  modalities.input.includes("image"),
@@ -50,7 +50,7 @@ export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low"
50
50
  * models show: skipping analysis, inventing verification, and ignoring the
51
51
  * context the conversation already established.
52
52
  */
53
- export declare const FREE_PI_GUIDANCE = "# free-pi working rules\n- Answer the user's latest request and keep their constraints; do not switch to a different task.\n- Slow down on multi-step work (arithmetic, counting, logic, dates, units, planning, debugging): write out each step, recompute the result a second way, and only then answer. On those tasks a correct answer after a dozen explicit steps beats a fast guess; do not stop at the first plausible number.\n- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.\n- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.\n- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.\n- Never claim to have compacted, summarized or cleared context unless that actually happened.\n- Continue until the request is finished, then report concisely what changed and what you verified.";
53
+ export declare const FREE_PI_GUIDANCE = "# free-pi working rules\n- Answer the user's latest request and keep their constraints; do not switch to a different task.\n- Slow down on multi-step work (arithmetic, counting, logic, dates, units, planning, debugging): write out each step, recompute the result a second way, and only then answer. On those tasks a correct answer after a dozen explicit steps beats a fast guess; do not stop at the first plausible number.\n- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.\n- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.\n- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.\n- Delegate large or self-contained work with OpenCode's native `subagent` tool: `free-pi/scout` and `free-pi/planner` for read-only recon and planning, `free-pi/worker` for a full task, `free-pi/reviewer` for review. A subagent runs in its own context and reports back; never launch a subagent from inside one.\n- Load a skill with the native `skill` tool when its description matches the task.\n- `AGENTS.md` and the files listed under `instructions` are the project's memory. Follow them; do not restate or replace them.\n- Never claim to have compacted, summarized or cleared context unless that actually happened.\n- Continue until the request is finished, then report concisely what changed and what you verified.";
54
54
  export declare const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
55
55
  /**
56
56
  * Appended to OpenCode's compaction request. Its default summary prompt asks
package/dist/constants.js CHANGED
@@ -70,6 +70,9 @@ export const FREE_PI_GUIDANCE = `# free-pi working rules
70
70
  - Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.
71
71
  - Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.
72
72
  - Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.
73
+ - Delegate large or self-contained work with OpenCode's native \`subagent\` tool: \`free-pi/scout\` and \`free-pi/planner\` for read-only recon and planning, \`free-pi/worker\` for a full task, \`free-pi/reviewer\` for review. A subagent runs in its own context and reports back; never launch a subagent from inside one.
74
+ - Load a skill with the native \`skill\` tool when its description matches the task.
75
+ - \`AGENTS.md\` and the files listed under \`instructions\` are the project's memory. Follow them; do not restate or replace them.
73
76
  - Never claim to have compacted, summarized or cleared context unless that actually happened.
74
77
  - Continue until the request is finished, then report concisely what changed and what you verified.`;
75
78
  export const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
package/dist/plugin.js CHANGED
@@ -1,7 +1,6 @@
1
1
  /** OpenCode V2 plugin entry point for free-pi. */
2
2
  import { Plugin } from "@opencode/plugin";
3
- import { join } from "node:path";
4
- import { FREE_PI_SKILL, FREE_PI_SKILL_DESCRIPTION, FREE_PI_SKILL_ID, FREE_PI_SKILL_NAME, installFreePiAgents, openCodeConfigDir, } from "./agents/definitions.js";
3
+ import { FREE_PI_SKILL, FREE_PI_SKILL_DESCRIPTION, FREE_PI_SKILL_ID, FREE_PI_SKILL_NAME, freePiSkillPath, installFreePiAgents, installFreePiSkill, openCodeConfigDir, } from "./agents/definitions.js";
5
4
  import { fetchQuota } from "./api/quota.js";
6
5
  import { closeFreePiSession } from "./api/session.js";
7
6
  import { readCredentialsToken } from "./auth/credentials.js";
@@ -71,6 +70,23 @@ async function setup(ctx) {
71
70
  catch (error) {
72
71
  log.warn("Could not install the free-pi subagents", error);
73
72
  }
73
+ // OpenCode's own skill loader reads `skills/free-pi/SKILL.md`. Install the
74
+ // file first so the skill has a real path, supporting files and permissions
75
+ // like any other native skill; the transform below only fills the gap when
76
+ // the config directory is not writable.
77
+ try {
78
+ const skill = await installFreePiSkill();
79
+ if (skill.changed) {
80
+ await ctx.skill.reload();
81
+ log.info("Installed the native free-pi skill");
82
+ }
83
+ if (skill.skipped) {
84
+ log.warn("Left the user-owned free-pi skill file untouched", freePiSkillPath(openCodeConfigDir()));
85
+ }
86
+ }
87
+ catch (error) {
88
+ log.warn("Could not install the free-pi skill file", error);
89
+ }
74
90
  try {
75
91
  nativeRegistrations.push(await ctx.skill.transform((editor) => {
76
92
  if (editor.get(FREE_PI_SKILL_ID))
@@ -79,7 +95,7 @@ async function setup(ctx) {
79
95
  id: FREE_PI_SKILL_ID,
80
96
  name: FREE_PI_SKILL_NAME,
81
97
  description: FREE_PI_SKILL_DESCRIPTION,
82
- path: join(openCodeConfigDir(), "skills", "free-pi", "SKILL.md"),
98
+ path: freePiSkillPath(openCodeConfigDir()),
83
99
  content: FREE_PI_SKILL,
84
100
  });
85
101
  }));
@@ -118,9 +134,15 @@ async function setup(ctx) {
118
134
  const defenseModels = buildModels(defense, candidates, buildOptions);
119
135
  for (const [id, model] of Object.entries(mainModels)) {
120
136
  state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
137
+ if (model.modalities.input.includes("image")) {
138
+ state.imageModels.add(`${PROVIDER_ID}/${id}`);
139
+ }
121
140
  }
122
141
  for (const [id, model] of Object.entries(defenseModels)) {
123
142
  state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
143
+ if (model.modalities.input.includes("image")) {
144
+ state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
145
+ }
124
146
  }
125
147
  const credential = await deps.activeCredential().catch(() => undefined);
126
148
  state.providerToken =
@@ -4,7 +4,7 @@ import { readCredentialsToken } from "../auth/credentials.js";
4
4
  import { tokenFromCredential } from "../auth/credential.js";
5
5
  import { handleFreePiError } from "../errors/handle.js";
6
6
  import { noteStepTokens } from "../catalog/live.js";
7
- import { forgetToolStats } from "./tools.js";
7
+ import { forgetToolStats, isFreePiSession } from "./tools.js";
8
8
  import { beginExecution, cancelAllFinalizeTimers, endExecution, finalizeFreePiSession, forgetFreePiSession, } from "./track.js";
9
9
  import { markWireSessionDirty, } from "./wire.js";
10
10
  import { recordUsage } from "./usage.js";
@@ -52,20 +52,25 @@ async function handleEvent(ctx, deps, event) {
52
52
  return;
53
53
  }
54
54
  case "session.execution.started": {
55
- beginExecution(deps, event.data?.sessionID);
55
+ const sessionID = event.data?.sessionID;
56
+ if (typeof sessionID === "string" && isFreePiSession(deps, sessionID)) {
57
+ beginExecution(deps, sessionID);
58
+ }
56
59
  return;
57
60
  }
58
61
  case "session.execution.failed": {
59
62
  const sessionID = event.data?.sessionID;
60
- // A request that dies mid-stream can leave its slot locked on the server.
61
- // The next turn will use a fresh wire id instead of waiting on a retry.
62
- if (isAbortLike(event.data?.error)) {
63
- markWireSessionDirty(deps, sessionID);
63
+ if (typeof sessionID === "string" && isFreePiSession(deps, sessionID)) {
64
+ // A request that dies mid-stream can leave its slot locked on the
65
+ // server. The next turn will use a fresh wire id instead of waiting on
66
+ // a retry.
67
+ if (isAbortLike(event.data?.error)) {
68
+ markWireSessionDirty(deps, sessionID);
69
+ }
70
+ await handleFreePiError(deps, event.data?.error, {
71
+ allowRaw: true,
72
+ }).catch(() => undefined);
64
73
  }
65
- await handleFreePiError(deps, event.data?.error, {
66
- allowRaw: typeof sessionID === "string" &&
67
- deps.state.freePiSessions.has(sessionID),
68
- }).catch(() => undefined);
69
74
  endExecution(deps, sessionID);
70
75
  return;
71
76
  }
@@ -74,18 +79,29 @@ async function handleEvent(ctx, deps, event) {
74
79
  return;
75
80
  }
76
81
  case "session.execution.interrupted": {
77
- markWireSessionDirty(deps, event.data?.sessionID);
78
- endExecution(deps, event.data?.sessionID);
82
+ const sessionID = event.data?.sessionID;
83
+ if (typeof sessionID === "string" && isFreePiSession(deps, sessionID)) {
84
+ markWireSessionDirty(deps, sessionID);
85
+ }
86
+ endExecution(deps, sessionID);
79
87
  return;
80
88
  }
81
89
  case "session.usage.updated": {
82
- recordUsage(deps, event.data?.sessionID, event.data?.cost, event.data?.tokens);
90
+ const sessionID = event.data?.sessionID;
91
+ if (typeof sessionID !== "string" || !isFreePiSession(deps, sessionID)) {
92
+ return;
93
+ }
94
+ recordUsage(deps, sessionID, event.data?.cost, event.data?.tokens);
83
95
  return;
84
96
  }
85
97
  case "session.step.ended": {
86
- recordUsage(deps, event.data?.sessionID, event.data?.cost, event.data?.tokens);
98
+ const sessionID = event.data?.sessionID;
99
+ if (typeof sessionID !== "string" || !isFreePiSession(deps, sessionID)) {
100
+ return;
101
+ }
102
+ recordUsage(deps, sessionID, event.data?.cost, event.data?.tokens);
87
103
  // Step tokens are per request; usage.updated is cumulative.
88
- noteStepTokens(deps, deps.state.trackedModels.get(event.data?.sessionID)?.modelID ?? "", event.data?.tokens);
104
+ noteStepTokens(deps, deps.state.trackedModels.get(sessionID)?.modelID ?? "", event.data?.tokens);
89
105
  return;
90
106
  }
91
107
  case "session.deleted": {
@@ -13,7 +13,7 @@ import { rememberReplayBody, replayConcurrentResponse, replaySpuriousOverflow, }
13
13
  import { localTitle } from "./title.js";
14
14
  import { rememberFreePiSession } from "./track.js";
15
15
  import { hydrateWireSessionID, markWireSessionDirty, rotateWireSessionID, takeWireSessionDirty, wireSessionID, } from "./wire.js";
16
- import { isFreePiSession, recordCompaction, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
16
+ import { FREE_PI_TOOL_NAMES, isFreePiSession, recordCompaction, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
17
17
  import { rememberTrackedModel } from "./usage.js";
18
18
  const PENDING_LIMIT = 400;
19
19
  /** Each agent gets its own ad turn, so a subagent never reuses the parent's. */
@@ -88,7 +88,6 @@ async function applyModelRequest(deps, event) {
88
88
  if (!isFreePiProvider(providerID))
89
89
  return;
90
90
  rememberFreePiSession(deps, event.sessionID);
91
- rememberTrackedModel(deps, event.sessionID, providerID, event.model?.id ?? "");
92
91
  const agent = event.agent ?? (event.kind === "title" ? "title" : undefined);
93
92
  event.headers ??= {};
94
93
  // Reconnect to the provider session saved for this OpenCode session. A
@@ -245,6 +244,24 @@ function applyRetryPolicy(deps, event) {
245
244
  const attempt = Math.max(1, event.attempt - 1);
246
245
  event.decision.delay = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), RETRY_MAX_DELAY_MS);
247
246
  }
247
+ /**
248
+ * Removes this plugin's tools from a request served by another provider. The
249
+ * tool editor is global, so without this every model would see `look_at_image`,
250
+ * `web_search` and the rest in its prompt even though their execution refuses
251
+ * non-free-pi sessions. The session's own (not another provider's) tool list is
252
+ * what the model receives, so this keeps free-pi's tools to free-pi models.
253
+ */
254
+ function hideFreePiTools(event) {
255
+ if (isFreePiProvider(event.model?.providerID))
256
+ return;
257
+ const tools = event.tools;
258
+ if (!tools || typeof tools !== "object")
259
+ return;
260
+ for (const name of FREE_PI_TOOL_NAMES) {
261
+ if (Object.hasOwn(tools, name))
262
+ delete tools[name];
263
+ }
264
+ }
248
265
  async function registerToolHooks(ctx, deps, registrations) {
249
266
  if (!ctx.tool?.hook)
250
267
  return;
@@ -262,16 +279,22 @@ async function registerToolHooks(ctx, deps, registrations) {
262
279
  }));
263
280
  }
264
281
  /**
265
- * free-pi only accepts text, like the provider CLI. OpenCode already swaps
266
- * media for this notice when it builds a request for a text-only model, but
267
- * doing it when the tool settles keeps the base64 image out of the session
268
- * (and out of compaction) instead of storing hundreds of KB per read.
282
+ * Models whose upstream accepts images get them natively, so a `read` that
283
+ * returns a picture must keep the file part. Text-only models would turn it
284
+ * into an error, so the image is swapped for a pointer to `look_at_image` when
285
+ * the tool settles: the base64 payload never enters the session (or a later
286
+ * compaction) instead of being stored only to be discarded at request time.
269
287
  */
270
288
  function replaceUnsupportedImages(deps, event) {
271
289
  if (event.status !== "completed")
272
290
  return;
273
291
  if (!isFreePiSession(deps, event.sessionID))
274
292
  return;
293
+ const tracked = deps.state.trackedModels.get(event.sessionID);
294
+ if (tracked &&
295
+ deps.state.imageModels.has(`${tracked.providerID}/${tracked.modelID}`)) {
296
+ return;
297
+ }
275
298
  const content = event.result?.content;
276
299
  if (!Array.isArray(content))
277
300
  return;
@@ -284,7 +307,7 @@ function replaceUnsupportedImages(deps, event) {
284
307
  const requested = typeof event.input?.path === "string" ? event.input.path : name;
285
308
  return {
286
309
  type: "text",
287
- text: `ERROR: Cannot read "${name}" (free-pi models take text only). If you need its content, call look_at_image with path "${requested}" and a specific question.`,
310
+ text: `ERROR: Cannot read "${name}" (this free-pi model takes text only). If you need its content, call look_at_image with path "${requested}" and a specific question, or switch to a model that accepts image input.`,
288
311
  };
289
312
  });
290
313
  if (replaced.every((part, index) => part === content[index]))
@@ -305,6 +328,24 @@ export async function registerSessionHooks(ctx, deps) {
305
328
  await hookForProviders(ctx, "compaction", generation("compaction"), registrations);
306
329
  await hookForProviders(ctx, "generate", generation("generate"), registrations);
307
330
  await hookForProviders(ctx, "title", generation("title"), registrations);
331
+ // The generation hooks above only run for free-pi providers. These unscoped
332
+ // ones strip the plugin's tools from every other provider's requests.
333
+ for (const name of ["context", "compaction", "generate"]) {
334
+ registrations.push(await ctx.session.hook(name, ((event) => {
335
+ hideFreePiTools(event);
336
+ })));
337
+ }
338
+ // Track the model of every request, not only free-pi's: the tool gate and
339
+ // the usage handler must know when a session switches to another provider,
340
+ // otherwise a session that used free-pi once would keep its tools armed.
341
+ registrations.push(await ctx.session.hook("model.request", ((event) => {
342
+ const providerID = event.model?.providerID;
343
+ if (typeof providerID === "string" &&
344
+ typeof event.sessionID === "string" &&
345
+ event.sessionID) {
346
+ rememberTrackedModel(deps, event.sessionID, providerID, event.model?.id ?? "");
347
+ }
348
+ })));
308
349
  await hookForProviders(ctx, "model.request", (event) => applyModelRequest(deps, event), registrations);
309
350
  await hookForProviders(ctx, "http.request", (event) => rememberReplayBody(deps, event), registrations);
310
351
  await hookForProviders(ctx, "http.response", async (event) => {
@@ -7,6 +7,13 @@
7
7
  * - `x-freepi-compacted: v1:<dropped messages>` on the request after compaction
8
8
  */
9
9
  import type { Deps } from "../deps.js";
10
+ /**
11
+ * Every tool this plugin adds. They are registered globally because OpenCode's
12
+ * tool editor has no provider filter, so the plugin hides them from requests
13
+ * served by another provider (see `hideFreePiTools`) and refuses to run them
14
+ * outside a free-pi session.
15
+ */
16
+ export declare const FREE_PI_TOOL_NAMES: readonly ["look_at_image", "free_pi_usage", "web_search", "docs_lookup", "generate_image"];
10
17
  type ToolResultLike = {
11
18
  metadata?: Record<string, unknown>;
12
19
  };
@@ -16,6 +23,11 @@ type ToolEnd = {
16
23
  status: "completed" | "error";
17
24
  result?: ToolResultLike;
18
25
  };
26
+ /**
27
+ * Whether this session is currently served by free-pi. The last request's
28
+ * model wins over the historical set, so a session that switches to another
29
+ * provider stops seeing free-pi's tools and headers immediately.
30
+ */
19
31
  export declare function isFreePiSession(deps: Deps, sessionID: string): boolean;
20
32
  export declare function recordToolStart(deps: Deps, sessionID: string, id: string): void;
21
33
  export declare function recordToolEnd(deps: Deps, sessionID: string, end: ToolEnd): void;
@@ -11,12 +11,31 @@ import { trimMap } from "../utils/async.js";
11
11
  const ID_PATTERN = /^[\w.:-]{1,100}$/;
12
12
  const MAX_ENTRY_LENGTH = 150;
13
13
  const MAX_STARTED = 200;
14
+ /**
15
+ * Every tool this plugin adds. They are registered globally because OpenCode's
16
+ * tool editor has no provider filter, so the plugin hides them from requests
17
+ * served by another provider (see `hideFreePiTools`) and refuses to run them
18
+ * outside a free-pi session.
19
+ */
20
+ export const FREE_PI_TOOL_NAMES = [
21
+ "look_at_image",
22
+ "free_pi_usage",
23
+ "web_search",
24
+ "docs_lookup",
25
+ "generate_image",
26
+ ];
27
+ /**
28
+ * Whether this session is currently served by free-pi. The last request's
29
+ * model wins over the historical set, so a session that switches to another
30
+ * provider stops seeing free-pi's tools and headers immediately.
31
+ */
14
32
  export function isFreePiSession(deps, sessionID) {
15
- if (deps.state.freePiSessions.has(sessionID))
16
- return true;
17
33
  const tracked = deps.state.trackedModels.get(sessionID);
18
- return (tracked?.providerID === PROVIDER_ID ||
19
- tracked?.providerID === DEFENSE_PROVIDER_ID);
34
+ if (tracked) {
35
+ return (tracked.providerID === PROVIDER_ID ||
36
+ tracked.providerID === DEFENSE_PROVIDER_ID);
37
+ }
38
+ return deps.state.freePiSessions.has(sessionID);
20
39
  }
21
40
  function statsFor(deps, sessionID) {
22
41
  let stats = deps.state.toolStats.get(sessionID);
package/dist/state.d.ts CHANGED
@@ -14,6 +14,8 @@ export type RuntimeState = {
14
14
  lastQuotaNotice?: string;
15
15
  catalogModels: Catalog;
16
16
  outputLimits: Map<string, number>;
17
+ /** `provider/model` ids whose upstream accepts image input. */
18
+ imageModels: Set<string>;
17
19
  quotaCache?: QuotaSnapshot;
18
20
  quotaPromise?: Promise<QuotaSnapshot>;
19
21
  lastQuotaRefreshAt: number;
package/dist/state.js CHANGED
@@ -8,6 +8,7 @@ export function createRuntimeState() {
8
8
  registryAttemptAt: 0,
9
9
  catalogModels: {},
10
10
  outputLimits: new Map(),
11
+ imageModels: new Set(),
11
12
  lastQuotaRefreshAt: 0,
12
13
  lastErrorLogAt: 0,
13
14
  tokenChecks: new Map(),