@eduardo191labs/opencode-free-pi 0.6.3 → 0.6.4

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
  | ---------------- | ------------------------------------------------------------------------ |
@@ -21,7 +21,7 @@ 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
25
  /** OpenCode's user-wide config directory, where it loads custom agents. */
26
26
  export declare function openCodeConfigDir(): string;
27
27
  export declare function freePiAgentPath(configDir: string, id: FreePiAgentID): string;
@@ -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.
@@ -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"))
package/dist/plugin.js CHANGED
@@ -118,9 +118,15 @@ async function setup(ctx) {
118
118
  const defenseModels = buildModels(defense, candidates, buildOptions);
119
119
  for (const [id, model] of Object.entries(mainModels)) {
120
120
  state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
121
+ if (model.modalities.input.includes("image")) {
122
+ state.imageModels.add(`${PROVIDER_ID}/${id}`);
123
+ }
121
124
  }
122
125
  for (const [id, model] of Object.entries(defenseModels)) {
123
126
  state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
127
+ if (model.modalities.input.includes("image")) {
128
+ state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
129
+ }
124
130
  }
125
131
  const credential = await deps.activeCredential().catch(() => undefined);
126
132
  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(),
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * `generate_image`, the free-pi text-to-image tool.
3
3
  *
4
- * The models cannot see images, so the tool writes the server's image into
5
- * `images/` inside the project and returns the relative path. Same endpoint,
6
- * limits and error wording as the provider CLI.
4
+ * The tool writes the server's image into `images/` inside the project and
5
+ * returns the relative path, so the result is a file even when the running
6
+ * model accepts images. Same endpoint, limits and error wording as the provider
7
+ * CLI.
7
8
  */
8
9
  import type { Plugin } from "@opencode/plugin";
9
10
  import type { Deps } from "../deps.js";
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * `generate_image`, the free-pi text-to-image tool.
3
3
  *
4
- * The models cannot see images, so the tool writes the server's image into
5
- * `images/` inside the project and returns the relative path. Same endpoint,
6
- * limits and error wording as the provider CLI.
4
+ * The tool writes the server's image into `images/` inside the project and
5
+ * returns the relative path, so the result is a file even when the running
6
+ * model accepts images. Same endpoint, limits and error wording as the provider
7
+ * CLI.
7
8
  */
8
9
  import { randomBytes } from "node:crypto";
9
10
  import { mkdir, open } from "node:fs/promises";
@@ -123,7 +124,7 @@ async function executeGenerateImage(ctx, deps, raw, context) {
123
124
  mediaType: data.media_type,
124
125
  model: data.model,
125
126
  });
126
- return done(`Saved image to ${relative} (${ext}, ${bytes.length} bytes). You cannot see the image; reference this path in your answer or code, and tell the user you could not check how it looks.`, {
127
+ return done(`Saved image to ${relative} (${ext}, ${bytes.length} bytes). To check how it looks, read that file when this model accepts image input, or call look_at_image with its path. If you cannot inspect it, say so instead of describing it.`, {
127
128
  ok: true,
128
129
  path: relative,
129
130
  ...(typeof data.cost_usd === "number" ? { cost_usd: data.cost_usd } : {}),
@@ -134,7 +135,7 @@ export async function registerGenerateImageTool(ctx, deps) {
134
135
  return ctx.tool.transform((editor) => {
135
136
  editor.add({
136
137
  name: "generate_image",
137
- description: "Generate one image from a text prompt and save it as a file under images/ in the project. Returns the file path; you cannot see the image. Use it only when the user asks for an image, mockup, icon or illustration. Each call uses part of the user's daily allowance.",
138
+ description: "Generate one image from a text prompt and save it as a file under images/ in the project. Returns the file path; read it or call look_at_image to check the result. Use it only when the user asks for an image, mockup, icon or illustration. Each call uses part of the user's daily allowance.",
138
139
  input: IMAGE_INPUT,
139
140
  options: { codemode: false },
140
141
  execute: (input, context) => executeGenerateImage(ctx, deps, input, context),
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * `look_at_image`, the free-pi vision tool.
3
3
  *
4
- * free-pi models are text-only, exactly like the provider CLI. To inspect an
5
- * image the model asks this tool a question; the plugin posts the pixels to
6
- * `/tools/vision` and returns the vision model's text answer. Each call counts
7
- * against the user's daily allowance.
4
+ * Image-capable free-pi models see attached images natively, but a file on disk
5
+ * still has to be attached (and its pixels stay in the context). This tool asks
6
+ * the server's vision model one question about the file and returns text only,
7
+ * which also covers text-only models. Each call counts against the user's daily
8
+ * allowance.
8
9
  */
9
10
  import type { Plugin } from "@opencode/plugin";
10
11
  import type { Deps } from "../deps.js";
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * `look_at_image`, the free-pi vision tool.
3
3
  *
4
- * free-pi models are text-only, exactly like the provider CLI. To inspect an
5
- * image the model asks this tool a question; the plugin posts the pixels to
6
- * `/tools/vision` and returns the vision model's text answer. Each call counts
7
- * against the user's daily allowance.
4
+ * Image-capable free-pi models see attached images natively, but a file on disk
5
+ * still has to be attached (and its pixels stay in the context). This tool asks
6
+ * the server's vision model one question about the file and returns text only,
7
+ * which also covers text-only models. Each call counts against the user's daily
8
+ * allowance.
8
9
  */
9
10
  import { resolveToken } from "../auth/token.js";
10
11
  import { isFreePiSession } from "../session/tools.js";
@@ -246,7 +247,7 @@ export async function registerVisionTool(ctx, deps) {
246
247
  return ctx.tool.transform((editor) => {
247
248
  editor.add({
248
249
  name: TOOL_NAME,
249
- description: "Ask a vision model one question about a PNG, JPEG or WebP image inside the project folder (for example a screenshot) and get a text answer. You cannot see images yourself. Each call uses part of the user's daily allowance.",
250
+ description: "Ask a vision model one question about a PNG, JPEG or WebP image inside the project folder (for example a screenshot) and get a text answer. Use it when the running model takes text only, or when you want a targeted answer without attaching the image. Each call uses part of the user's daily allowance.",
250
251
  input: INPUT,
251
252
  options: { codemode: false },
252
253
  execute: (input, context) => executeVision(ctx, deps, input, context),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.6.3",
3
+ "version": "0.6.4",
4
4
  "description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -49,7 +49,8 @@ it.
49
49
  - \`free_pi_usage\` shows today's remaining allowance, credits, token counts and
50
50
  the account tier. Read-only.
51
51
  - \`look_at_image\` asks a vision model about a PNG, JPEG or WebP inside the
52
- project. free-pi models are text-only, so use it instead of reading images.
52
+ project. Use it when the current model takes text only, or when the image is a
53
+ file on disk and you want a targeted answer instead of attaching it.
53
54
  - \`generate_image\` draws one image from a prompt and saves it under \`images/\`.
54
55
  - \`web_search\` searches the web for current information.
55
56
  - \`docs_lookup\` looks up current library and framework documentation.
@@ -329,9 +329,10 @@ const KNOWN_INPUT_MODALITIES = new Set([
329
329
  /**
330
330
  * Native modalities for the chat route. models.dev describes the upstream
331
331
  * model, and the gateway forwards image parts to multimodal upstreams, so an
332
- * image-capable model is advertised as such. Output is always text: free-pi has
333
- * no image results on the chat route, and the plugin registers every model as
334
- * zero-cost text output.
332
+ * image-capable model is advertised as such. free-pi's free models were probed
333
+ * with `curl_cffi` and all of them transcribe an attached screenshot correctly
334
+ * even when models.dev has no entry for the alias, so free models always accept
335
+ * images. Output is always text: free-pi has no image results on the chat route.
335
336
  */
336
337
  function modelModalities(
337
338
  model: CatalogModel,
@@ -341,6 +342,7 @@ function modelModalities(
341
342
  const input = (declared ?? ["text"]).filter((value) =>
342
343
  KNOWN_INPUT_MODALITIES.has(value),
343
344
  );
345
+ if (model.free === true && !input.includes("image")) input.push("image");
344
346
  if (input.length === 0) input.push("text");
345
347
  if (!input.includes("text")) input.unshift("text");
346
348
  return { input, output: ["text"] };
package/src/plugin.ts CHANGED
@@ -150,9 +150,15 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
150
150
 
151
151
  for (const [id, model] of Object.entries(mainModels)) {
152
152
  state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
153
+ if (model.modalities.input.includes("image")) {
154
+ state.imageModels.add(`${PROVIDER_ID}/${id}`);
155
+ }
153
156
  }
154
157
  for (const [id, model] of Object.entries(defenseModels)) {
155
158
  state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
159
+ if (model.modalities.input.includes("image")) {
160
+ state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
161
+ }
156
162
  }
157
163
 
158
164
  const credential = await deps.activeCredential().catch(() => undefined);
@@ -7,7 +7,7 @@ import { tokenFromCredential } from "../auth/credential.js";
7
7
  import type { Deps } from "../deps.js";
8
8
  import { handleFreePiError } from "../errors/handle.js";
9
9
  import { noteStepTokens } from "../catalog/live.js";
10
- import { forgetToolStats } from "./tools.js";
10
+ import { forgetToolStats, isFreePiSession } from "./tools.js";
11
11
  import {
12
12
  beginExecution,
13
13
  cancelAllFinalizeTimers,
@@ -69,21 +69,25 @@ async function handleEvent(
69
69
  return;
70
70
  }
71
71
  case "session.execution.started": {
72
- beginExecution(deps, event.data?.sessionID);
72
+ const sessionID = event.data?.sessionID;
73
+ if (typeof sessionID === "string" && isFreePiSession(deps, sessionID)) {
74
+ beginExecution(deps, sessionID);
75
+ }
73
76
  return;
74
77
  }
75
78
  case "session.execution.failed": {
76
79
  const sessionID = event.data?.sessionID;
77
- // A request that dies mid-stream can leave its slot locked on the server.
78
- // The next turn will use a fresh wire id instead of waiting on a retry.
79
- if (isAbortLike(event.data?.error)) {
80
- markWireSessionDirty(deps, sessionID);
80
+ if (typeof sessionID === "string" && isFreePiSession(deps, sessionID)) {
81
+ // A request that dies mid-stream can leave its slot locked on the
82
+ // server. The next turn will use a fresh wire id instead of waiting on
83
+ // a retry.
84
+ if (isAbortLike(event.data?.error)) {
85
+ markWireSessionDirty(deps, sessionID);
86
+ }
87
+ await handleFreePiError(deps, event.data?.error, {
88
+ allowRaw: true,
89
+ }).catch(() => undefined);
81
90
  }
82
- await handleFreePiError(deps, event.data?.error, {
83
- allowRaw:
84
- typeof sessionID === "string" &&
85
- deps.state.freePiSessions.has(sessionID),
86
- }).catch(() => undefined);
87
91
  endExecution(deps, sessionID);
88
92
  return;
89
93
  }
@@ -92,30 +96,31 @@ async function handleEvent(
92
96
  return;
93
97
  }
94
98
  case "session.execution.interrupted": {
95
- markWireSessionDirty(deps, event.data?.sessionID);
96
- endExecution(deps, event.data?.sessionID);
99
+ const sessionID = event.data?.sessionID;
100
+ if (typeof sessionID === "string" && isFreePiSession(deps, sessionID)) {
101
+ markWireSessionDirty(deps, sessionID);
102
+ }
103
+ endExecution(deps, sessionID);
97
104
  return;
98
105
  }
99
106
  case "session.usage.updated": {
100
- recordUsage(
101
- deps,
102
- event.data?.sessionID,
103
- event.data?.cost,
104
- event.data?.tokens,
105
- );
107
+ const sessionID = event.data?.sessionID;
108
+ if (typeof sessionID !== "string" || !isFreePiSession(deps, sessionID)) {
109
+ return;
110
+ }
111
+ recordUsage(deps, sessionID, event.data?.cost, event.data?.tokens);
106
112
  return;
107
113
  }
108
114
  case "session.step.ended": {
109
- recordUsage(
110
- deps,
111
- event.data?.sessionID,
112
- event.data?.cost,
113
- event.data?.tokens,
114
- );
115
+ const sessionID = event.data?.sessionID;
116
+ if (typeof sessionID !== "string" || !isFreePiSession(deps, sessionID)) {
117
+ return;
118
+ }
119
+ recordUsage(deps, sessionID, event.data?.cost, event.data?.tokens);
115
120
  // Step tokens are per request; usage.updated is cumulative.
116
121
  noteStepTokens(
117
122
  deps,
118
- deps.state.trackedModels.get(event.data?.sessionID)?.modelID ?? "",
123
+ deps.state.trackedModels.get(sessionID)?.modelID ?? "",
119
124
  event.data?.tokens,
120
125
  );
121
126
  return;
@@ -55,6 +55,7 @@ import {
55
55
  wireSessionID,
56
56
  } from "./wire.js";
57
57
  import {
58
+ FREE_PI_TOOL_NAMES,
58
59
  isFreePiSession,
59
60
  recordCompaction,
60
61
  recordToolEnd,
@@ -181,7 +182,6 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
181
182
  const providerID = event.model?.providerID;
182
183
  if (!isFreePiProvider(providerID)) return;
183
184
  rememberFreePiSession(deps, event.sessionID);
184
- rememberTrackedModel(deps, event.sessionID, providerID, event.model?.id ?? "");
185
185
 
186
186
  const agent = event.agent ?? (event.kind === "title" ? "title" : undefined);
187
187
  event.headers ??= {};
@@ -368,6 +368,22 @@ function applyRetryPolicy(deps: Deps, event: any): void {
368
368
  );
369
369
  }
370
370
 
371
+ /**
372
+ * Removes this plugin's tools from a request served by another provider. The
373
+ * tool editor is global, so without this every model would see `look_at_image`,
374
+ * `web_search` and the rest in its prompt even though their execution refuses
375
+ * non-free-pi sessions. The session's own (not another provider's) tool list is
376
+ * what the model receives, so this keeps free-pi's tools to free-pi models.
377
+ */
378
+ function hideFreePiTools(event: any): void {
379
+ if (isFreePiProvider(event.model?.providerID)) return;
380
+ const tools = event.tools;
381
+ if (!tools || typeof tools !== "object") return;
382
+ for (const name of FREE_PI_TOOL_NAMES) {
383
+ if (Object.hasOwn(tools, name)) delete tools[name];
384
+ }
385
+ }
386
+
371
387
  async function registerToolHooks(
372
388
  ctx: Plugin.Context,
373
389
  deps: Deps,
@@ -393,14 +409,22 @@ async function registerToolHooks(
393
409
  }
394
410
 
395
411
  /**
396
- * free-pi only accepts text, like the provider CLI. OpenCode already swaps
397
- * media for this notice when it builds a request for a text-only model, but
398
- * doing it when the tool settles keeps the base64 image out of the session
399
- * (and out of compaction) instead of storing hundreds of KB per read.
412
+ * Models whose upstream accepts images get them natively, so a `read` that
413
+ * returns a picture must keep the file part. Text-only models would turn it
414
+ * into an error, so the image is swapped for a pointer to `look_at_image` when
415
+ * the tool settles: the base64 payload never enters the session (or a later
416
+ * compaction) instead of being stored only to be discarded at request time.
400
417
  */
401
418
  function replaceUnsupportedImages(deps: Deps, event: any): void {
402
419
  if (event.status !== "completed") return;
403
420
  if (!isFreePiSession(deps, event.sessionID)) return;
421
+ const tracked = deps.state.trackedModels.get(event.sessionID);
422
+ if (
423
+ tracked &&
424
+ deps.state.imageModels.has(`${tracked.providerID}/${tracked.modelID}`)
425
+ ) {
426
+ return;
427
+ }
404
428
  const content = event.result?.content;
405
429
  if (!Array.isArray(content)) return;
406
430
  const replaced = content.map((part: any) => {
@@ -411,7 +435,7 @@ function replaceUnsupportedImages(deps: Deps, event: any): void {
411
435
  typeof event.input?.path === "string" ? event.input.path : name;
412
436
  return {
413
437
  type: "text",
414
- 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.`,
438
+ 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.`,
415
439
  };
416
440
  });
417
441
  if (replaced.every((part, index) => part === content[index])) return;
@@ -450,6 +474,35 @@ export async function registerSessionHooks(
450
474
  );
451
475
  await hookForProviders(ctx, "generate", generation("generate"), registrations);
452
476
  await hookForProviders(ctx, "title", generation("title"), registrations);
477
+ // The generation hooks above only run for free-pi providers. These unscoped
478
+ // ones strip the plugin's tools from every other provider's requests.
479
+ for (const name of ["context", "compaction", "generate"] as const) {
480
+ registrations.push(
481
+ await ctx.session.hook(name as any, ((event: any) => {
482
+ hideFreePiTools(event);
483
+ }) as any),
484
+ );
485
+ }
486
+ // Track the model of every request, not only free-pi's: the tool gate and
487
+ // the usage handler must know when a session switches to another provider,
488
+ // otherwise a session that used free-pi once would keep its tools armed.
489
+ registrations.push(
490
+ await ctx.session.hook("model.request" as any, ((event: any) => {
491
+ const providerID = event.model?.providerID;
492
+ if (
493
+ typeof providerID === "string" &&
494
+ typeof event.sessionID === "string" &&
495
+ event.sessionID
496
+ ) {
497
+ rememberTrackedModel(
498
+ deps,
499
+ event.sessionID,
500
+ providerID,
501
+ event.model?.id ?? "",
502
+ );
503
+ }
504
+ }) as any),
505
+ );
453
506
  await hookForProviders(
454
507
  ctx,
455
508
  "model.request",
@@ -24,6 +24,20 @@ const ID_PATTERN = /^[\w.:-]{1,100}$/;
24
24
  const MAX_ENTRY_LENGTH = 150;
25
25
  const MAX_STARTED = 200;
26
26
 
27
+ /**
28
+ * Every tool this plugin adds. They are registered globally because OpenCode's
29
+ * tool editor has no provider filter, so the plugin hides them from requests
30
+ * served by another provider (see `hideFreePiTools`) and refuses to run them
31
+ * outside a free-pi session.
32
+ */
33
+ export const FREE_PI_TOOL_NAMES = [
34
+ "look_at_image",
35
+ "free_pi_usage",
36
+ "web_search",
37
+ "docs_lookup",
38
+ "generate_image",
39
+ ] as const;
40
+
27
41
  type ToolResultLike = {
28
42
  metadata?: Record<string, unknown>;
29
43
  };
@@ -35,13 +49,20 @@ type ToolEnd = {
35
49
  result?: ToolResultLike;
36
50
  };
37
51
 
52
+ /**
53
+ * Whether this session is currently served by free-pi. The last request's
54
+ * model wins over the historical set, so a session that switches to another
55
+ * provider stops seeing free-pi's tools and headers immediately.
56
+ */
38
57
  export function isFreePiSession(deps: Deps, sessionID: string): boolean {
39
- if (deps.state.freePiSessions.has(sessionID)) return true;
40
58
  const tracked = deps.state.trackedModels.get(sessionID);
41
- return (
42
- tracked?.providerID === PROVIDER_ID ||
43
- tracked?.providerID === DEFENSE_PROVIDER_ID
44
- );
59
+ if (tracked) {
60
+ return (
61
+ tracked.providerID === PROVIDER_ID ||
62
+ tracked.providerID === DEFENSE_PROVIDER_ID
63
+ );
64
+ }
65
+ return deps.state.freePiSessions.has(sessionID);
45
66
  }
46
67
 
47
68
  function statsFor(deps: Deps, sessionID: string): ToolStats {
package/src/state.ts CHANGED
@@ -29,6 +29,8 @@ export type RuntimeState = {
29
29
  lastQuotaNotice?: string;
30
30
  catalogModels: Catalog;
31
31
  outputLimits: Map<string, number>;
32
+ /** `provider/model` ids whose upstream accepts image input. */
33
+ imageModels: Set<string>;
32
34
 
33
35
  quotaCache?: QuotaSnapshot;
34
36
  quotaPromise?: Promise<QuotaSnapshot>;
@@ -74,6 +76,7 @@ export function createRuntimeState(): RuntimeState {
74
76
  registryAttemptAt: 0,
75
77
  catalogModels: {},
76
78
  outputLimits: new Map(),
79
+ imageModels: new Set(),
77
80
  lastQuotaRefreshAt: 0,
78
81
  lastErrorLogAt: 0,
79
82
  tokenChecks: new Map(),
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * `generate_image`, the free-pi text-to-image tool.
3
3
  *
4
- * The models cannot see images, so the tool writes the server's image into
5
- * `images/` inside the project and returns the relative path. Same endpoint,
6
- * limits and error wording as the provider CLI.
4
+ * The tool writes the server's image into `images/` inside the project and
5
+ * returns the relative path, so the result is a file even when the running
6
+ * model accepts images. Same endpoint, limits and error wording as the provider
7
+ * CLI.
7
8
  */
8
9
 
9
10
  import { randomBytes } from "node:crypto";
@@ -167,7 +168,7 @@ async function executeGenerateImage(
167
168
  model: data.model,
168
169
  });
169
170
  return done(
170
- `Saved image to ${relative} (${ext}, ${bytes.length} bytes). You cannot see the image; reference this path in your answer or code, and tell the user you could not check how it looks.`,
171
+ `Saved image to ${relative} (${ext}, ${bytes.length} bytes). To check how it looks, read that file when this model accepts image input, or call look_at_image with its path. If you cannot inspect it, say so instead of describing it.`,
171
172
  {
172
173
  ok: true,
173
174
  path: relative,
@@ -185,7 +186,7 @@ export async function registerGenerateImageTool(
185
186
  editor.add({
186
187
  name: "generate_image",
187
188
  description:
188
- "Generate one image from a text prompt and save it as a file under images/ in the project. Returns the file path; you cannot see the image. Use it only when the user asks for an image, mockup, icon or illustration. Each call uses part of the user's daily allowance.",
189
+ "Generate one image from a text prompt and save it as a file under images/ in the project. Returns the file path; read it or call look_at_image to check the result. Use it only when the user asks for an image, mockup, icon or illustration. Each call uses part of the user's daily allowance.",
189
190
  input: IMAGE_INPUT,
190
191
  options: { codemode: false },
191
192
  execute: (input: unknown, context: any) =>
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * `look_at_image`, the free-pi vision tool.
3
3
  *
4
- * free-pi models are text-only, exactly like the provider CLI. To inspect an
5
- * image the model asks this tool a question; the plugin posts the pixels to
6
- * `/tools/vision` and returns the vision model's text answer. Each call counts
7
- * against the user's daily allowance.
4
+ * Image-capable free-pi models see attached images natively, but a file on disk
5
+ * still has to be attached (and its pixels stay in the context). This tool asks
6
+ * the server's vision model one question about the file and returns text only,
7
+ * which also covers text-only models. Each call counts against the user's daily
8
+ * allowance.
8
9
  */
9
10
 
10
11
  import type { Plugin } from "@opencode/plugin";
@@ -314,7 +315,7 @@ export async function registerVisionTool(
314
315
  editor.add({
315
316
  name: TOOL_NAME,
316
317
  description:
317
- "Ask a vision model one question about a PNG, JPEG or WebP image inside the project folder (for example a screenshot) and get a text answer. You cannot see images yourself. Each call uses part of the user's daily allowance.",
318
+ "Ask a vision model one question about a PNG, JPEG or WebP image inside the project folder (for example a screenshot) and get a text answer. Use it when the running model takes text only, or when you want a targeted answer without attaching the image. Each call uses part of the user's daily allowance.",
318
319
  input: INPUT,
319
320
  options: { codemode: false },
320
321
  execute: (