@eduardo191labs/opencode-free-pi 0.6.2 → 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 +39 -23
- package/dist/agents/definitions.d.ts +1 -1
- package/dist/agents/definitions.js +2 -1
- package/dist/catalog/live.js +24 -12
- package/dist/catalog/models.js +6 -3
- package/dist/plugin.js +6 -0
- package/dist/session/events.js +31 -15
- package/dist/session/hooks.js +48 -7
- package/dist/session/tools.d.ts +12 -0
- package/dist/session/tools.js +23 -4
- package/dist/state.d.ts +2 -0
- package/dist/state.js +1 -0
- package/dist/tools/image-generate.d.ts +4 -3
- package/dist/tools/image-generate.js +6 -5
- package/dist/tools/vision.d.ts +5 -4
- package/dist/tools/vision.js +6 -5
- package/package.json +1 -1
- package/src/agents/definitions.ts +2 -1
- package/src/catalog/live.ts +28 -12
- package/src/catalog/models.ts +5 -3
- package/src/plugin.ts +6 -0
- package/src/session/events.ts +31 -26
- package/src/session/hooks.ts +59 -6
- package/src/session/tools.ts +26 -5
- package/src/state.ts +3 -0
- package/src/tools/image-generate.ts +6 -5
- package/src/tools/vision.ts +6 -5
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
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
de
|
|
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
|
|
167
|
-
models.dev se
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
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
|
|
176
|
-
captura
|
|
177
|
-
|
|
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
|
|
196
|
-
|
|
197
|
-
`look_at_image` con la
|
|
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.
|
|
202
|
-
|
|
203
|
-
|
|
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.
|
|
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.
|
|
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.
|
package/dist/catalog/live.js
CHANGED
|
@@ -211,6 +211,20 @@ export function settleWindow(samples) {
|
|
|
211
211
|
return undefined;
|
|
212
212
|
return Math.min(MAX_WINDOW, Math.max(MIN_WINDOW, Math.floor((best * WINDOW_SAFETY) / 1_000) * 1_000));
|
|
213
213
|
}
|
|
214
|
+
/**
|
|
215
|
+
* Stores a measured window and writes it immediately. Called after every
|
|
216
|
+
* accepted probe, so a process that exits mid-verification keeps the smallest
|
|
217
|
+
* proven value instead of losing the whole run.
|
|
218
|
+
*/
|
|
219
|
+
async function commitWindow(deps, tokens, modelID) {
|
|
220
|
+
const limits = (cached ??= emptyLimits());
|
|
221
|
+
if (limits.window && limits.window.tokens >= tokens)
|
|
222
|
+
return limits.window.tokens;
|
|
223
|
+
limits.window = { tokens, verifiedAt: Date.now(), model: modelID };
|
|
224
|
+
loaded = true;
|
|
225
|
+
await persist();
|
|
226
|
+
return tokens;
|
|
227
|
+
}
|
|
214
228
|
/**
|
|
215
229
|
* Checks the compiled window against the gateway and then grows past it while
|
|
216
230
|
* the gateway keeps accepting larger prompts. The start value is a floor, not a
|
|
@@ -231,6 +245,8 @@ export async function verifyGatewayWindow(deps, options = {}) {
|
|
|
231
245
|
let accepted = 0;
|
|
232
246
|
let charsPerToken = INITIAL_CHARS_PER_TOKEN;
|
|
233
247
|
let target = Math.max(MIN_WINDOW, Math.min(fallback, MAX_WINDOW));
|
|
248
|
+
let verified;
|
|
249
|
+
const floor = Math.min(fallback, CONTEXT_WINDOW);
|
|
234
250
|
for (let attempt = 0; attempt < MAX_PROBES; attempt += 1) {
|
|
235
251
|
const chars = Math.max(MIN_WINDOW * charsPerToken, Math.floor(target * charsPerToken * 0.99));
|
|
236
252
|
const result = await sendProbe(deps, modelID, chars);
|
|
@@ -238,7 +254,7 @@ export async function verifyGatewayWindow(deps, options = {}) {
|
|
|
238
254
|
// A network failure or a rejected body proves nothing; keep what the
|
|
239
255
|
// earlier probes already established.
|
|
240
256
|
if (samples.length === 0)
|
|
241
|
-
return
|
|
257
|
+
return verified;
|
|
242
258
|
break;
|
|
243
259
|
}
|
|
244
260
|
if (result.status === "too_long") {
|
|
@@ -247,7 +263,7 @@ export async function verifyGatewayWindow(deps, options = {}) {
|
|
|
247
263
|
// The compiled window itself is too large: step down as before.
|
|
248
264
|
target = Math.floor(target * 0.85);
|
|
249
265
|
if (target < MIN_WINDOW)
|
|
250
|
-
|
|
266
|
+
break;
|
|
251
267
|
continue;
|
|
252
268
|
}
|
|
253
269
|
const next = Math.floor((accepted + target) / 2);
|
|
@@ -271,6 +287,11 @@ export async function verifyGatewayWindow(deps, options = {}) {
|
|
|
271
287
|
else {
|
|
272
288
|
accepted = Math.floor(chars / charsPerToken);
|
|
273
289
|
}
|
|
290
|
+
const settled = settleWindow(samples);
|
|
291
|
+
if (settled) {
|
|
292
|
+
// Never go below the window that already worked for this account.
|
|
293
|
+
verified = await commitWindow(deps, Math.max(settled, floor), modelID);
|
|
294
|
+
}
|
|
274
295
|
if (accepted >= MAX_WINDOW)
|
|
275
296
|
break;
|
|
276
297
|
const next = Math.min(MAX_WINDOW, Math.floor(accepted * 1.2));
|
|
@@ -278,17 +299,8 @@ export async function verifyGatewayWindow(deps, options = {}) {
|
|
|
278
299
|
break;
|
|
279
300
|
target = next;
|
|
280
301
|
}
|
|
281
|
-
|
|
282
|
-
if (!settled)
|
|
302
|
+
if (!verified)
|
|
283
303
|
return undefined;
|
|
284
|
-
// Keep the previous floor when growth probes only prove less: the CLI's 200k
|
|
285
|
-
// is already known to work, so a small upstream probe model must not shrink
|
|
286
|
-
// every session's window.
|
|
287
|
-
const verified = Math.max(settled, Math.min(fallback, CONTEXT_WINDOW));
|
|
288
|
-
const limits = (cached ??= emptyLimits());
|
|
289
|
-
limits.window = { tokens: verified, verifiedAt: Date.now(), model: modelID };
|
|
290
|
-
loaded = true;
|
|
291
|
-
await persist();
|
|
292
304
|
deps.log.info("free-pi verified the gateway context window", {
|
|
293
305
|
model: modelID,
|
|
294
306
|
window: verified,
|
package/dist/catalog/models.js
CHANGED
|
@@ -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.
|
|
235
|
-
*
|
|
236
|
-
*
|
|
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 =
|
package/dist/session/events.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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
|
-
|
|
78
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
104
|
+
noteStepTokens(deps, deps.state.trackedModels.get(sessionID)?.modelID ?? "", event.data?.tokens);
|
|
89
105
|
return;
|
|
90
106
|
}
|
|
91
107
|
case "session.deleted": {
|
package/dist/session/hooks.js
CHANGED
|
@@ -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
|
-
*
|
|
266
|
-
*
|
|
267
|
-
*
|
|
268
|
-
*
|
|
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
|
|
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) => {
|
package/dist/session/tools.d.ts
CHANGED
|
@@ -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;
|
package/dist/session/tools.js
CHANGED
|
@@ -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
|
-
|
|
19
|
-
tracked
|
|
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
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `generate_image`, the free-pi text-to-image tool.
|
|
3
3
|
*
|
|
4
|
-
* The
|
|
5
|
-
*
|
|
6
|
-
* limits and error wording as the provider
|
|
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
|
|
5
|
-
*
|
|
6
|
-
* limits and error wording as the provider
|
|
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).
|
|
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;
|
|
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),
|
package/dist/tools/vision.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `look_at_image`, the free-pi vision tool.
|
|
3
3
|
*
|
|
4
|
-
* free-pi models
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* against the user's daily
|
|
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";
|
package/dist/tools/vision.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `look_at_image`, the free-pi vision tool.
|
|
3
3
|
*
|
|
4
|
-
* free-pi models
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* against the user's daily
|
|
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.
|
|
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
|
@@ -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.
|
|
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.
|
package/src/catalog/live.ts
CHANGED
|
@@ -269,6 +269,24 @@ export function settleWindow(
|
|
|
269
269
|
);
|
|
270
270
|
}
|
|
271
271
|
|
|
272
|
+
/**
|
|
273
|
+
* Stores a measured window and writes it immediately. Called after every
|
|
274
|
+
* accepted probe, so a process that exits mid-verification keeps the smallest
|
|
275
|
+
* proven value instead of losing the whole run.
|
|
276
|
+
*/
|
|
277
|
+
async function commitWindow(
|
|
278
|
+
deps: Deps,
|
|
279
|
+
tokens: number,
|
|
280
|
+
modelID: string,
|
|
281
|
+
): Promise<number> {
|
|
282
|
+
const limits = (cached ??= emptyLimits());
|
|
283
|
+
if (limits.window && limits.window.tokens >= tokens) return limits.window.tokens;
|
|
284
|
+
limits.window = { tokens, verifiedAt: Date.now(), model: modelID };
|
|
285
|
+
loaded = true;
|
|
286
|
+
await persist();
|
|
287
|
+
return tokens;
|
|
288
|
+
}
|
|
289
|
+
|
|
272
290
|
/**
|
|
273
291
|
* Checks the compiled window against the gateway and then grows past it while
|
|
274
292
|
* the gateway keeps accepting larger prompts. The start value is a floor, not a
|
|
@@ -292,6 +310,8 @@ export async function verifyGatewayWindow(
|
|
|
292
310
|
let accepted = 0;
|
|
293
311
|
let charsPerToken = INITIAL_CHARS_PER_TOKEN;
|
|
294
312
|
let target = Math.max(MIN_WINDOW, Math.min(fallback, MAX_WINDOW));
|
|
313
|
+
let verified: number | undefined;
|
|
314
|
+
const floor = Math.min(fallback, CONTEXT_WINDOW);
|
|
295
315
|
|
|
296
316
|
for (let attempt = 0; attempt < MAX_PROBES; attempt += 1) {
|
|
297
317
|
const chars = Math.max(
|
|
@@ -302,7 +322,7 @@ export async function verifyGatewayWindow(
|
|
|
302
322
|
if (result.status === "failed") {
|
|
303
323
|
// A network failure or a rejected body proves nothing; keep what the
|
|
304
324
|
// earlier probes already established.
|
|
305
|
-
if (samples.length === 0) return
|
|
325
|
+
if (samples.length === 0) return verified;
|
|
306
326
|
break;
|
|
307
327
|
}
|
|
308
328
|
if (result.status === "too_long") {
|
|
@@ -310,7 +330,7 @@ export async function verifyGatewayWindow(
|
|
|
310
330
|
if (accepted === 0) {
|
|
311
331
|
// The compiled window itself is too large: step down as before.
|
|
312
332
|
target = Math.floor(target * 0.85);
|
|
313
|
-
if (target < MIN_WINDOW)
|
|
333
|
+
if (target < MIN_WINDOW) break;
|
|
314
334
|
continue;
|
|
315
335
|
}
|
|
316
336
|
const next = Math.floor((accepted + target) / 2);
|
|
@@ -333,22 +353,18 @@ export async function verifyGatewayWindow(
|
|
|
333
353
|
} else {
|
|
334
354
|
accepted = Math.floor(chars / charsPerToken);
|
|
335
355
|
}
|
|
356
|
+
const settled = settleWindow(samples);
|
|
357
|
+
if (settled) {
|
|
358
|
+
// Never go below the window that already worked for this account.
|
|
359
|
+
verified = await commitWindow(deps, Math.max(settled, floor), modelID);
|
|
360
|
+
}
|
|
336
361
|
if (accepted >= MAX_WINDOW) break;
|
|
337
362
|
const next = Math.min(MAX_WINDOW, Math.floor(accepted * 1.2));
|
|
338
363
|
if (next <= accepted) break;
|
|
339
364
|
target = next;
|
|
340
365
|
}
|
|
341
366
|
|
|
342
|
-
|
|
343
|
-
if (!settled) return undefined;
|
|
344
|
-
// Keep the previous floor when growth probes only prove less: the CLI's 200k
|
|
345
|
-
// is already known to work, so a small upstream probe model must not shrink
|
|
346
|
-
// every session's window.
|
|
347
|
-
const verified = Math.max(settled, Math.min(fallback, CONTEXT_WINDOW));
|
|
348
|
-
const limits = (cached ??= emptyLimits());
|
|
349
|
-
limits.window = { tokens: verified, verifiedAt: Date.now(), model: modelID };
|
|
350
|
-
loaded = true;
|
|
351
|
-
await persist();
|
|
367
|
+
if (!verified) return undefined;
|
|
352
368
|
deps.log.info("free-pi verified the gateway context window", {
|
|
353
369
|
model: modelID,
|
|
354
370
|
window: verified,
|
package/src/catalog/models.ts
CHANGED
|
@@ -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.
|
|
333
|
-
*
|
|
334
|
-
*
|
|
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);
|
package/src/session/events.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
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
|
-
|
|
96
|
-
|
|
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
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
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
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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(
|
|
123
|
+
deps.state.trackedModels.get(sessionID)?.modelID ?? "",
|
|
119
124
|
event.data?.tokens,
|
|
120
125
|
);
|
|
121
126
|
return;
|
package/src/session/hooks.ts
CHANGED
|
@@ -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
|
-
*
|
|
397
|
-
*
|
|
398
|
-
*
|
|
399
|
-
*
|
|
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
|
|
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",
|
package/src/session/tools.ts
CHANGED
|
@@ -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
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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
|
|
5
|
-
*
|
|
6
|
-
* limits and error wording as the provider
|
|
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).
|
|
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;
|
|
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) =>
|
package/src/tools/vision.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `look_at_image`, the free-pi vision tool.
|
|
3
3
|
*
|
|
4
|
-
* free-pi models
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* against the user's daily
|
|
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.
|
|
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: (
|