@eduardo191labs/opencode-free-pi 0.7.27 → 0.7.30
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 +48 -108
- package/dist/constants.d.ts +0 -22
- package/dist/constants.js +0 -22
- package/dist/deps.d.ts +1 -4
- package/dist/index.d.ts +1 -1
- package/dist/legacy.d.ts +17 -0
- package/dist/legacy.js +58 -0
- package/dist/plugin.js +7 -84
- package/dist/session/events.js +5 -12
- package/dist/session/hooks.js +9 -185
- package/dist/session/tools.d.ts +1 -1
- package/dist/session/tools.js +0 -1
- package/dist/session/track.d.ts +2 -0
- package/dist/session/track.js +5 -0
- package/dist/state.d.ts +1 -3
- package/dist/types.d.ts +0 -11
- package/package.json +2 -2
- package/src/constants.ts +0 -25
- package/src/deps.ts +1 -8
- package/src/index.ts +0 -1
- package/src/legacy.ts +62 -0
- package/src/plugin.ts +8 -97
- package/src/session/events.ts +5 -12
- package/src/session/hooks.ts +8 -224
- package/src/session/tools.ts +0 -1
- package/src/session/track.ts +11 -0
- package/src/state.ts +0 -3
- package/src/types.ts +0 -18
- package/dist/agents/definitions.d.ts +0 -56
- package/dist/agents/definitions.js +0 -317
- package/dist/session/title.d.ts +0 -18
- package/dist/session/title.js +0 -81
- package/dist/session/usage.d.ts +0 -5
- package/dist/session/usage.js +0 -32
- package/dist/tools/subagent.d.ts +0 -29
- package/dist/tools/subagent.js +0 -197
- package/src/agents/definitions.ts +0 -354
- package/src/session/title.ts +0 -90
- package/src/session/usage.ts +0 -46
- package/src/tools/subagent.ts +0 -271
package/README.md
CHANGED
|
@@ -87,10 +87,11 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
87
87
|
que OpenCode compacte una vez y, si el rechazo se repite, devuelve un error de
|
|
88
88
|
proveedor que OpenCode no clasifica como desbordamiento, para no gastar
|
|
89
89
|
créditos en resúmenes que no arreglan nada.
|
|
90
|
-
- **Títulos
|
|
91
|
-
El plugin
|
|
92
|
-
|
|
93
|
-
|
|
90
|
+
- **Títulos de OpenCode**: el agente de títulos, su prompt y su modelo son de
|
|
91
|
+
OpenCode. El plugin no intercepta la petición ni reemplaza el resultado
|
|
92
|
+
(`ctx.session.hook("title")` no se registra), y solo evita pedir un anuncio
|
|
93
|
+
para una petición que el usuario nunca ve. El gateway se validó en vivo con
|
|
94
|
+
la petición de título: responde 200 con un título limpio.
|
|
94
95
|
- **Capacidades según el modelo**: los modelos gratuitos aceptan imágenes de
|
|
95
96
|
entrada de forma nativa; se comprobó con `curl_cffi` contra el gateway y los
|
|
96
97
|
cuatro transcriben una captura adjunta. Los alias de pago anuncian lo que
|
|
@@ -279,7 +280,6 @@ demás modelos no las ven ni pueden ejecutarlas.
|
|
|
279
280
|
| `web_search` | Busca en la web y devuelve título, URL, fecha y texto de cada resultado. |
|
|
280
281
|
| `docs_lookup` | Consulta documentación actual de una librería o framework. |
|
|
281
282
|
| `free_pi_usage` | Muestra cuota restante, créditos, tokens y tier de la cuenta. |
|
|
282
|
-
| `free_pi_subagent_read` | Lee la transcripción de una sesión hija: prompts, herramientas y respuesta. |
|
|
283
283
|
|
|
284
284
|
`generate_image` acepta `prompt`, `aspect_ratio` (`1:1`, `16:9`, `9:16`, `4:3`,
|
|
285
285
|
`3:2`) y un `name` opcional para el archivo. Rechaza tipos que no sean PNG,
|
|
@@ -299,83 +299,36 @@ con su hora de recarga en ET, los créditos premium o de referidos y los tokens
|
|
|
299
299
|
de hoy y de por vida. Si el servidor asigna el carril lento, incluye el aviso
|
|
300
300
|
del CLI.
|
|
301
301
|
|
|
302
|
-
`free_pi_subagent_read` recibe el `sessionID` que devuelve la herramienta
|
|
303
|
-
`subagent` y devuelve la conversación de esa sesión hija: el prompt recibido,
|
|
304
|
-
cada llamada a herramienta con su entrada y su resultado, y el texto final del
|
|
305
|
-
subagente. Antes de leer comprueba con `session.get` que `parentID` sea la sesión
|
|
306
|
-
que llama, así que no puede abrir sesiones ajenas. Sin `sessionID` lista las
|
|
307
|
-
sesiones hijas de la sesión actual con su agente y su resultado. El transcript se
|
|
308
|
-
mantiene dentro de un presupuesto de caracteres (`maxChars`, 60k por defecto) y,
|
|
309
|
-
si no cabe, conserva los turnos más recientes y lo indica.
|
|
310
|
-
|
|
311
302
|
La compra de créditos y la guía de free-pi ya no se exponen como herramientas:
|
|
312
303
|
se resuelven en el dashboard y la documentación de free-pi, sin gastar cuota ni
|
|
313
304
|
añadir ruido al contexto.
|
|
314
305
|
|
|
315
|
-
## Agentes y
|
|
316
|
-
|
|
317
|
-
El CLI incluye cuatro personalidades de agente. El plugin las instala como
|
|
318
|
-
agentes Markdown nativos de OpenCode en el directorio global de configuración:
|
|
319
|
-
|
|
320
|
-
```text
|
|
321
|
-
~/.config/opencode/agents/free-pi/
|
|
322
|
-
├── scout.md → free-pi/scout
|
|
323
|
-
├── planner.md → free-pi/planner
|
|
324
|
-
├── worker.md → free-pi/worker
|
|
325
|
-
└── reviewer.md → free-pi/reviewer
|
|
326
|
-
```
|
|
327
|
-
|
|
328
|
-
| Agente | Uso |
|
|
329
|
-
| ----------------- | ---------------------------------------------------------------- |
|
|
330
|
-
| `free-pi/scout` | Reconocimiento de solo lectura; devuelve hallazgos estructurados. |
|
|
331
|
-
| `free-pi/planner` | Plan de implementación de solo lectura, listo para un worker. |
|
|
332
|
-
| `free-pi/worker` | Ejecuta una tarea completa en su propia ventana de contexto. |
|
|
333
|
-
| `free-pi/reviewer`| Revisión de solo lectura con archivo y línea. |
|
|
306
|
+
## Agentes y skills
|
|
334
307
|
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
y el resto del comportamiento nativo.
|
|
308
|
+
Los agentes, sus prompts y las skills son de OpenCode. El plugin no define
|
|
309
|
+
personalidades, no escribe archivos en el directorio de configuración, no
|
|
310
|
+
registra skills y no inyecta instrucciones propias en la sesión. Se usan los
|
|
311
|
+
agentes nativos (`build`, `plan`, `general`, `explore`), los agentes y skills que
|
|
312
|
+
el usuario configure en OpenCode, y la herramienta `subagent` tal cual.
|
|
341
313
|
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
nunca oculte `subagent` por una capacidad incorrecta de models.dev. Cuando el
|
|
347
|
-
hijo termina, OpenCode inyecta su informe en la sesión padre; para ver lo que
|
|
348
|
-
realmente ejecutó, el padre llama a `free_pi_subagent_read` con el `sessionID`
|
|
349
|
-
del hijo.
|
|
350
|
-
|
|
351
|
-
El plugin solo reescribe estos archivos si conservan su marca de gestión; si el
|
|
352
|
-
usuario edita o reemplaza uno, se respeta tal cual.
|
|
353
|
-
|
|
354
|
-
## Skill y contexto
|
|
355
|
-
|
|
356
|
-
El plugin instala una skill nativa en:
|
|
357
|
-
|
|
358
|
-
```text
|
|
359
|
-
~/.config/opencode/skills/free-pi/SKILL.md
|
|
360
|
-
```
|
|
314
|
+
Las versiones anteriores del plugin dejaban cuatro agentes Markdown y una skill
|
|
315
|
+
en `~/.config/opencode`. Al arrancar, esta versión elimina solo esos archivos si
|
|
316
|
+
conservan su marca de gestión; cualquier archivo que el usuario haya editado o
|
|
317
|
+
reemplazado se respeta y sigue siendo de OpenCode.
|
|
361
318
|
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
319
|
+
La herramienta `subagent` está disponible para **cualquier** modelo, no solo
|
|
320
|
+
para los free-pi. El plugin garantiza además que todos los modelos gratuitos
|
|
321
|
+
anuncien soporte de tools, de modo que el runner nunca oculte `subagent` por una
|
|
322
|
+
capacidad incorrecta de models.dev. Cuando el hijo termina, OpenCode inyecta su
|
|
323
|
+
informe en la sesión padre y lo repite tras cada ronda posterior.
|
|
367
324
|
|
|
368
|
-
|
|
369
|
-
delegar el trabajo grande en `free-pi/scout`, `free-pi/planner`,
|
|
370
|
-
`free-pi/worker` o `free-pi/reviewer` con `subagent`, cargar skills con `skill`
|
|
371
|
-
y seguir `AGENTS.md` en lugar de inventar convenciones. Esa guía solo se añade a
|
|
372
|
-
las peticiones de `free-pi` y `free-pi-defense`.
|
|
325
|
+
## Contexto y memoria
|
|
373
326
|
|
|
374
|
-
La memoria, las sesiones
|
|
375
|
-
archivos de `instructions` se cargan de forma nativa, las
|
|
376
|
-
se reanudan, y la compactación pliega conversaciones largas
|
|
377
|
-
plugin no crea archivos de memoria propios
|
|
378
|
-
|
|
327
|
+
La memoria, las sesiones, el contexto y la compactación son los de OpenCode:
|
|
328
|
+
`AGENTS.md` y los archivos de `instructions` se cargan de forma nativa, las
|
|
329
|
+
sesiones persisten y se reanudan, y la compactación pliega conversaciones largas
|
|
330
|
+
en un resumen. El plugin no crea archivos de memoria propios, no duplica el
|
|
331
|
+
almacén de sesiones y no añade prompts de sistema propios.
|
|
379
332
|
|
|
380
333
|
Las herramientas `todo` y `ask_user` del CLI no se duplican: OpenCode ya tiene
|
|
381
334
|
un gestor de todos nativo y su propia herramienta de preguntas al usuario, con
|
|
@@ -389,9 +342,9 @@ El plugin replica las cabeceras del plugin V1 de free-pi:
|
|
|
389
342
|
- **Modelo**: `authorization`, `x-session-id`, `x-client-version` y
|
|
390
343
|
`x-turn-id`. Las sesiones hijas añaden `x-freepi-subagent: 1`.
|
|
391
344
|
- **Resultados de herramientas**: `x-freepi-tool-meta` (duración, código de
|
|
392
|
-
salida y truncado de las últimas llamadas)
|
|
393
|
-
herramientas fallidas) y
|
|
394
|
-
|
|
345
|
+
salida y truncado de las últimas llamadas) y `x-freepi-tool-errors` (IDs de
|
|
346
|
+
herramientas fallidas). El historial y su compactación son de OpenCode: el
|
|
347
|
+
plugin no pliega mensajes ni envía marcadores de compactación.
|
|
395
348
|
- **Catálogo** (`/client-version`): `authorization`.
|
|
396
349
|
- **Anuncios** (`/ads/next`): `authorization`, `x-session-id`,
|
|
397
350
|
`x-client-version`, `x-turn-id`, `x-ad-trigger`, `x-client-os`,
|
|
@@ -408,49 +361,36 @@ se reescriben a un `400` con el texto que OpenCode clasifica como
|
|
|
408
361
|
desbordamiento de contexto, para que dispare la compactación automática.
|
|
409
362
|
|
|
410
363
|
El plugin mide el cuerpo de cada petición rechazada. Cuando el rechazo llega
|
|
411
|
-
con un cuerpo que no puede agotar la ventana, lo
|
|
412
|
-
proveedor
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
364
|
+
con un cuerpo que no puede agotar la ventana, lo clasifica como fallo del
|
|
365
|
+
proveedor y devuelve un `400` con un mensaje de error: ese texto no coincide con
|
|
366
|
+
el patrón de desbordamiento de OpenCode, así que el runner deja de compactar en
|
|
367
|
+
lugar de entrar en un ciclo de resúmenes que no reducen nada. El plugin nunca
|
|
368
|
+
reenvía la petición ni recorta el historial.
|
|
416
369
|
|
|
417
370
|
Cuando el rechazo sí corresponde a una conversación larga, el tamaño medido se
|
|
418
371
|
guarda como `rejectedPromptTokens` del modelo en `live-limits.json`. El
|
|
419
372
|
`provider.transform` reconstruye el catálogo con ese techo (85 % del tamaño
|
|
420
373
|
rechazado, sin bajar de la ventana ya aceptada) y `provider.reload` lo aplica en
|
|
421
|
-
caliente, de modo que la siguiente compactación
|
|
422
|
-
|
|
423
|
-
compactación descarta los turnos de usuario más antiguos en lugar de dejar que
|
|
424
|
-
OpenCode aborte el turno.
|
|
374
|
+
caliente, de modo que la siguiente compactación la decide OpenCode con un
|
|
375
|
+
presupuesto más realista.
|
|
425
376
|
|
|
426
377
|
free-pi cobra en créditos contra una cuota diaria, no en USD por token. Por
|
|
427
378
|
eso los modelos se registran con costo `0`, igual que el CLI del proveedor; el
|
|
428
379
|
consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
|
|
429
380
|
cuota y límite.
|
|
430
381
|
|
|
431
|
-
Los reintentos
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
de modo que la sesión continúa sin interrupciones y sin pasar por un reintento.
|
|
444
|
-
Una compactación también deja el id marcado: el resumen y el turno siguiente se
|
|
445
|
-
solapan en el gateway y ese solape producía un 429 `concurrent` y un replay en
|
|
446
|
-
cada compactación, así que el turno posterior ya sale con un id nuevo.
|
|
447
|
-
|
|
448
|
-
Los fallos de transporte (`ECONNREFUSED`, `ECONNRESET`, `ETIMEDOUT`, DNS
|
|
449
|
-
temporal, `socket hang up`) no son límites de cuenta: el plugin los reintenta con
|
|
450
|
-
espera exponencial hasta cinco veces más (2 s, 4 s, 8 s, 16 s y 30 s) y marca el
|
|
451
|
-
`x-session-id` como sucio para que el siguiente intento use una conexión y un
|
|
452
|
-
slot nuevos. Así un corte breve de red, del router o del servicio local de
|
|
453
|
-
OpenCode no termina el turno en el segundo intento.
|
|
382
|
+
Los reintentos son de OpenCode: el runner decide si un error se reintenta, con
|
|
383
|
+
qué presupuesto y con qué espera. El plugin no fija delays ni límites de
|
|
384
|
+
intentos y tampoco reenvía la petición. Lo único que hace en el hook de
|
|
385
|
+
reintento es preparar el `x-session-id` de free-pi: si OpenCode va a reintentar,
|
|
386
|
+
marca el id como sucio y el siguiente intento sale con uno nuevo, porque el
|
|
387
|
+
gateway mantiene un slot por sesión y un intento fallido puede dejarlo ocupado.
|
|
388
|
+
Al rotar, el plugin libera el id anterior con `/session/reset`. Un turno
|
|
389
|
+
abortado o interrumpido hace lo mismo para el turno siguiente.
|
|
390
|
+
|
|
391
|
+
Los límites de larga duración (`free_usage_limit`, cupos diarios u horarios,
|
|
392
|
+
créditos, cuenta bloqueada) se reescriben a un `400` con el mensaje amigable;
|
|
393
|
+
OpenCode los trata como un fallo normal y no muestra un «Retrying…» infinito.
|
|
454
394
|
|
|
455
395
|
## Rutas por plataforma
|
|
456
396
|
|
package/dist/constants.d.ts
CHANGED
|
@@ -59,27 +59,6 @@ export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low"
|
|
|
59
59
|
/** pi-ai's HTTP idle timeout for headers and body chunks. */
|
|
60
60
|
export declare const HEADER_TIMEOUT_MS = 300000;
|
|
61
61
|
export declare const CHUNK_TIMEOUT_MS = 300000;
|
|
62
|
-
/** pi's retry policy: 3 retries, 2s base, 60s cap. */
|
|
63
|
-
export declare const RETRY_MAX_RETRIES = 3;
|
|
64
|
-
export declare const RETRY_BASE_DELAY_MS = 2000;
|
|
65
|
-
export declare const RETRY_MAX_DELAY_MS = 60000;
|
|
66
|
-
/**
|
|
67
|
-
* Transport failures (a refused or dropped connection, DNS blips) usually
|
|
68
|
-
* clear on their own. OpenCode stops after its own retries, which can end a
|
|
69
|
-
* turn during a brief local network or service restart, so the plugin gives
|
|
70
|
-
* them a longer budget before giving up.
|
|
71
|
-
*/
|
|
72
|
-
export declare const TRANSPORT_RETRY_MAX = 5;
|
|
73
|
-
export declare const TRANSPORT_RETRY_BASE_MS = 2000;
|
|
74
|
-
export declare const TRANSPORT_RETRY_MAX_DELAY_MS = 30000;
|
|
75
|
-
/**
|
|
76
|
-
* free-pi allows one in-flight request per `x-session-id` and answers a second
|
|
77
|
-
* one with `429 concurrent`. OpenCode does not retry that itself, and a slot
|
|
78
|
-
* can leak server-side, so the plugin rotates the wire session id and retries.
|
|
79
|
-
*/
|
|
80
|
-
export declare const CONCURRENT_RETRY_MAX = 6;
|
|
81
|
-
export declare const CONCURRENT_RETRY_BASE_MS = 1000;
|
|
82
|
-
export declare const CONCURRENT_RETRY_MAX_DELAY_MS = 15000;
|
|
83
62
|
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
84
63
|
export declare const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
85
64
|
export declare const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
@@ -129,7 +108,6 @@ export declare const REGISTRY_ATTEMPTS = 2;
|
|
|
129
108
|
export declare const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
|
|
130
109
|
export declare const QUOTA_TTL_MS = 30000;
|
|
131
110
|
export declare const QUOTA_HTTP_TIMEOUT_MS = 5000;
|
|
132
|
-
export declare const QUOTA_REFRESH_DEBOUNCE_MS = 1000;
|
|
133
111
|
export declare const SESSION_RESET_COOLDOWN_MS = 15000;
|
|
134
112
|
/**
|
|
135
113
|
* Releasing a server slot is a tiny POST, but a VPN or a proxy adds a round
|
package/dist/constants.js
CHANGED
|
@@ -73,27 +73,6 @@ export const DEFAULT_THINKING_LEVELS = [
|
|
|
73
73
|
/** pi-ai's HTTP idle timeout for headers and body chunks. */
|
|
74
74
|
export const HEADER_TIMEOUT_MS = 300_000;
|
|
75
75
|
export const CHUNK_TIMEOUT_MS = 300_000;
|
|
76
|
-
/** pi's retry policy: 3 retries, 2s base, 60s cap. */
|
|
77
|
-
export const RETRY_MAX_RETRIES = 3;
|
|
78
|
-
export const RETRY_BASE_DELAY_MS = 2_000;
|
|
79
|
-
export const RETRY_MAX_DELAY_MS = 60_000;
|
|
80
|
-
/**
|
|
81
|
-
* Transport failures (a refused or dropped connection, DNS blips) usually
|
|
82
|
-
* clear on their own. OpenCode stops after its own retries, which can end a
|
|
83
|
-
* turn during a brief local network or service restart, so the plugin gives
|
|
84
|
-
* them a longer budget before giving up.
|
|
85
|
-
*/
|
|
86
|
-
export const TRANSPORT_RETRY_MAX = 5;
|
|
87
|
-
export const TRANSPORT_RETRY_BASE_MS = 2_000;
|
|
88
|
-
export const TRANSPORT_RETRY_MAX_DELAY_MS = 30_000;
|
|
89
|
-
/**
|
|
90
|
-
* free-pi allows one in-flight request per `x-session-id` and answers a second
|
|
91
|
-
* one with `429 concurrent`. OpenCode does not retry that itself, and a slot
|
|
92
|
-
* can leak server-side, so the plugin rotates the wire session id and retries.
|
|
93
|
-
*/
|
|
94
|
-
export const CONCURRENT_RETRY_MAX = 6;
|
|
95
|
-
export const CONCURRENT_RETRY_BASE_MS = 1_000;
|
|
96
|
-
export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
|
|
97
76
|
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
98
77
|
export const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
99
78
|
export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
@@ -145,7 +124,6 @@ export const REGISTRY_ATTEMPTS = 2;
|
|
|
145
124
|
export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
|
|
146
125
|
export const QUOTA_TTL_MS = 30_000;
|
|
147
126
|
export const QUOTA_HTTP_TIMEOUT_MS = 5_000;
|
|
148
|
-
export const QUOTA_REFRESH_DEBOUNCE_MS = 1_000;
|
|
149
127
|
export const SESSION_RESET_COOLDOWN_MS = 15_000;
|
|
150
128
|
/**
|
|
151
129
|
* Releasing a server slot is a tiny POST, but a VPN or a proxy adds a round
|
package/dist/deps.d.ts
CHANGED
|
@@ -3,15 +3,12 @@ import type { Credential } from "@opencode/schema/credential";
|
|
|
3
3
|
import type { Plugin } from "@opencode/plugin";
|
|
4
4
|
import type { Logger } from "./logging.js";
|
|
5
5
|
import type { RuntimeState } from "./state.js";
|
|
6
|
-
import type {
|
|
6
|
+
import type { ReadContext } from "./types.js";
|
|
7
7
|
export type Deps = {
|
|
8
8
|
readonly state: RuntimeState;
|
|
9
9
|
readonly log: Logger;
|
|
10
10
|
readonly activeCredential: () => Promise<Credential.Value | undefined>;
|
|
11
11
|
readonly readContext: ReadContext;
|
|
12
|
-
/** Session headers, used to prove a session is really this session's child. */
|
|
13
|
-
readonly readSession?: ReadSessionInfo;
|
|
14
|
-
readonly listSubagentSessions?: ListSubagentSessions;
|
|
15
12
|
/** Plugin-scoped durable storage, used to reconnect provider sessions. */
|
|
16
13
|
readonly storage?: Plugin.Context["storage"];
|
|
17
14
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,6 @@
|
|
|
4
4
|
* Ad-supported free-pi provider plugin for OpenCode V2.
|
|
5
5
|
*/
|
|
6
6
|
export { FreePiPlugin, default } from "./plugin.js";
|
|
7
|
-
export type { Catalog, CatalogModel, FreePiError, FreePiOptions, MeResponse, MeStatsResponse, ModelDefinition, ModelsDevModel, ModelsDevProvider, ModelRegistry, QuotaSnapshot,
|
|
7
|
+
export type { Catalog, CatalogModel, FreePiError, FreePiOptions, MeResponse, MeStatsResponse, ModelDefinition, ModelsDevModel, ModelsDevProvider, ModelRegistry, QuotaSnapshot, } from "./types.js";
|
|
8
8
|
export { createLogger } from "./logging.js";
|
|
9
9
|
export type { Logger, LogLevel } from "./logging.js";
|
package/dist/legacy.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-time cleanup for files older plugin versions wrote into OpenCode's config
|
|
3
|
+
* directory.
|
|
4
|
+
*
|
|
5
|
+
* Agents, skills and their prompts belong to OpenCode. Earlier releases seeded
|
|
6
|
+
* a free-pi skill and four Markdown agents next to the user's own files, which
|
|
7
|
+
* kept those prompts active after the plugin stopped owning them. This removes
|
|
8
|
+
* only files that still carry the old management marker; anything the user
|
|
9
|
+
* edited or replaced is left untouched.
|
|
10
|
+
*/
|
|
11
|
+
/** OpenCode's user-wide config directory. */
|
|
12
|
+
export declare function openCodeConfigDir(): string;
|
|
13
|
+
/**
|
|
14
|
+
* Deletes the plugin-managed agent and skill files from previous versions and
|
|
15
|
+
* returns their paths. User-owned files are never touched.
|
|
16
|
+
*/
|
|
17
|
+
export declare function removeLegacyFreePiFiles(configDir?: string): Promise<string[]>;
|
package/dist/legacy.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-time cleanup for files older plugin versions wrote into OpenCode's config
|
|
3
|
+
* directory.
|
|
4
|
+
*
|
|
5
|
+
* Agents, skills and their prompts belong to OpenCode. Earlier releases seeded
|
|
6
|
+
* a free-pi skill and four Markdown agents next to the user's own files, which
|
|
7
|
+
* kept those prompts active after the plugin stopped owning them. This removes
|
|
8
|
+
* only files that still carry the old management marker; anything the user
|
|
9
|
+
* edited or replaced is left untouched.
|
|
10
|
+
*/
|
|
11
|
+
import { readFile, rm, rmdir } from "node:fs/promises";
|
|
12
|
+
import { homedir } from "node:os";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
const MARKER = "<!-- managed by @eduardo191labs/opencode-free-pi; delete this line to keep your own copy -->";
|
|
15
|
+
const LEGACY_FILES = [
|
|
16
|
+
["agents", "free-pi", "scout.md"],
|
|
17
|
+
["agents", "free-pi", "planner.md"],
|
|
18
|
+
["agents", "free-pi", "worker.md"],
|
|
19
|
+
["agents", "free-pi", "reviewer.md"],
|
|
20
|
+
["skills", "free-pi", "SKILL.md"],
|
|
21
|
+
];
|
|
22
|
+
/** OpenCode's user-wide config directory. */
|
|
23
|
+
export function openCodeConfigDir() {
|
|
24
|
+
const explicit = process.env.OPENCODE_CONFIG_DIR?.trim();
|
|
25
|
+
if (explicit)
|
|
26
|
+
return explicit;
|
|
27
|
+
const xdg = process.env.XDG_CONFIG_HOME?.trim();
|
|
28
|
+
if (xdg)
|
|
29
|
+
return join(xdg, "opencode");
|
|
30
|
+
return join(homedir(), ".config", "opencode");
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Deletes the plugin-managed agent and skill files from previous versions and
|
|
34
|
+
* returns their paths. User-owned files are never touched.
|
|
35
|
+
*/
|
|
36
|
+
export async function removeLegacyFreePiFiles(configDir = openCodeConfigDir()) {
|
|
37
|
+
const removed = [];
|
|
38
|
+
for (const parts of LEGACY_FILES) {
|
|
39
|
+
const path = join(configDir, ...parts);
|
|
40
|
+
try {
|
|
41
|
+
const current = await readFile(path, "utf8");
|
|
42
|
+
if (!current.slice(0, 1024).includes(MARKER))
|
|
43
|
+
continue;
|
|
44
|
+
await rm(path, { force: true });
|
|
45
|
+
removed.push(path);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
// Missing or unreadable: nothing to clean up.
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (removed.length > 0) {
|
|
52
|
+
// Drop the now-empty plugin folders without touching user-owned entries.
|
|
53
|
+
for (const parts of [["agents", "free-pi"], ["skills", "free-pi"]]) {
|
|
54
|
+
await rmdir(join(configDir, ...parts)).catch(() => undefined);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return removed;
|
|
58
|
+
}
|
package/dist/plugin.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
/** OpenCode V2 plugin entry point for free-pi. */
|
|
2
2
|
import { Plugin } from "@opencode/plugin";
|
|
3
|
-
import { FREE_PI_SKILL, FREE_PI_SKILL_DESCRIPTION, FREE_PI_SKILL_ID, FREE_PI_SKILL_NAME, freePiSkillPath, installFreePiAgents, installFreePiSkill, openCodeConfigDir, } from "./agents/definitions.js";
|
|
4
3
|
import { fetchQuota } from "./api/quota.js";
|
|
5
4
|
import { closeFreePiSession } from "./api/session.js";
|
|
6
5
|
import { readCredentialsToken } from "./auth/credentials.js";
|
|
@@ -12,6 +11,7 @@ import { applyProvider } from "./catalog/v2.js";
|
|
|
12
11
|
import { CATALOG_RECOVERY_DELAYS_MS, CATALOG_RECOVERY_INTERVAL_MS, CATALOG_RECOVERY_LOG_EVERY, DEFAULT_FREE_MODEL_ID, DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "./constants.js";
|
|
13
12
|
import { registerIntegration } from "./integration/setup.js";
|
|
14
13
|
import { createLogger } from "./logging.js";
|
|
14
|
+
import { removeLegacyFreePiFiles } from "./legacy.js";
|
|
15
15
|
import { applyDirectNetwork } from "./network/direct.js";
|
|
16
16
|
import { subscribeEvents } from "./session/events.js";
|
|
17
17
|
import { registerSessionHooks } from "./session/hooks.js";
|
|
@@ -19,7 +19,6 @@ import { cancelAllFinalizeTimers } from "./session/track.js";
|
|
|
19
19
|
import { createRuntimeState } from "./state.js";
|
|
20
20
|
import { registerGenerateImageTool } from "./tools/image-generate.js";
|
|
21
21
|
import { registerUsageTool } from "./tools/usage.js";
|
|
22
|
-
import { registerSubagentTool } from "./tools/subagent.js";
|
|
23
22
|
import { registerVisionTool } from "./tools/vision.js";
|
|
24
23
|
import { registerWebTools } from "./tools/web.js";
|
|
25
24
|
import { settle } from "./utils/async.js";
|
|
@@ -56,89 +55,18 @@ async function setup(ctx) {
|
|
|
56
55
|
return [];
|
|
57
56
|
}
|
|
58
57
|
},
|
|
59
|
-
readSession: async (sessionID) => {
|
|
60
|
-
try {
|
|
61
|
-
const info = await ctx.session.get({ sessionID });
|
|
62
|
-
return {
|
|
63
|
-
id: info.id,
|
|
64
|
-
parentID: info.parentID,
|
|
65
|
-
title: info.title,
|
|
66
|
-
agent: info.agent,
|
|
67
|
-
outcome: info.outcome,
|
|
68
|
-
updated: info.time?.updated,
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
catch {
|
|
72
|
-
return undefined;
|
|
73
|
-
}
|
|
74
|
-
},
|
|
75
|
-
listSubagentSessions: async (parentID) => {
|
|
76
|
-
try {
|
|
77
|
-
const result = await ctx.session.list({ parentID, limit: 50 });
|
|
78
|
-
return (result.data ?? []).map((info) => ({
|
|
79
|
-
id: info.id,
|
|
80
|
-
parentID: info.parentID,
|
|
81
|
-
title: info.title,
|
|
82
|
-
agent: info.agent,
|
|
83
|
-
outcome: info.outcome,
|
|
84
|
-
updated: info.time?.updated,
|
|
85
|
-
}));
|
|
86
|
-
}
|
|
87
|
-
catch {
|
|
88
|
-
return [];
|
|
89
|
-
}
|
|
90
|
-
},
|
|
91
58
|
storage: ctx.storage,
|
|
92
59
|
};
|
|
93
|
-
//
|
|
94
|
-
//
|
|
95
|
-
// so the picker, the subagent tool, permissions and reloads stay native.
|
|
96
|
-
const nativeRegistrations = [];
|
|
97
|
-
try {
|
|
98
|
-
const agents = await installFreePiAgents();
|
|
99
|
-
if (agents.changed) {
|
|
100
|
-
await ctx.agent.reload();
|
|
101
|
-
log.info(`Installed ${agents.installed.length} native free-pi subagent(s)`, agents.installed);
|
|
102
|
-
}
|
|
103
|
-
if (agents.skipped.length > 0) {
|
|
104
|
-
log.warn("Left user-owned free-pi agent files untouched", agents.skipped);
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
catch (error) {
|
|
108
|
-
log.warn("Could not install the free-pi subagents", error);
|
|
109
|
-
}
|
|
110
|
-
// OpenCode's own skill loader reads `skills/free-pi/SKILL.md`. Install the
|
|
111
|
-
// file first so the skill has a real path, supporting files and permissions
|
|
112
|
-
// like any other native skill; the transform below only fills the gap when
|
|
113
|
-
// the config directory is not writable.
|
|
60
|
+
// Agents, skills and their prompts are OpenCode's. Remove the files earlier
|
|
61
|
+
// releases seeded so their prompts stop applying; user-owned files stay.
|
|
114
62
|
try {
|
|
115
|
-
const
|
|
116
|
-
if (
|
|
117
|
-
|
|
118
|
-
log.info("Installed the native free-pi skill");
|
|
119
|
-
}
|
|
120
|
-
if (skill.skipped) {
|
|
121
|
-
log.warn("Left the user-owned free-pi skill file untouched", freePiSkillPath(openCodeConfigDir()));
|
|
63
|
+
const removed = await removeLegacyFreePiFiles();
|
|
64
|
+
if (removed.length > 0) {
|
|
65
|
+
log.info(`Removed ${removed.length} legacy free-pi agent/skill file(s); OpenCode now owns them`, removed);
|
|
122
66
|
}
|
|
123
67
|
}
|
|
124
68
|
catch (error) {
|
|
125
|
-
log.warn("Could not
|
|
126
|
-
}
|
|
127
|
-
try {
|
|
128
|
-
nativeRegistrations.push(await ctx.skill.transform((editor) => {
|
|
129
|
-
if (editor.get(FREE_PI_SKILL_ID))
|
|
130
|
-
return;
|
|
131
|
-
editor.add({
|
|
132
|
-
id: FREE_PI_SKILL_ID,
|
|
133
|
-
name: FREE_PI_SKILL_NAME,
|
|
134
|
-
description: FREE_PI_SKILL_DESCRIPTION,
|
|
135
|
-
path: freePiSkillPath(openCodeConfigDir()),
|
|
136
|
-
content: FREE_PI_SKILL,
|
|
137
|
-
});
|
|
138
|
-
}));
|
|
139
|
-
}
|
|
140
|
-
catch (error) {
|
|
141
|
-
log.warn("Could not register the free-pi skill", error);
|
|
69
|
+
log.warn("Could not remove the legacy free-pi agent/skill files", error);
|
|
142
70
|
}
|
|
143
71
|
const [catalogResult, registryResult, quotaResult] = await Promise.all([
|
|
144
72
|
settle(fetchCatalog(deps), undefined),
|
|
@@ -228,14 +156,9 @@ async function setup(ctx) {
|
|
|
228
156
|
editor.default.set(PROVIDER_ID, preferred);
|
|
229
157
|
});
|
|
230
158
|
const registrations = await registerSessionHooks(ctx, deps);
|
|
231
|
-
registrations.push(...nativeRegistrations);
|
|
232
159
|
const tools = [
|
|
233
160
|
{ name: "look_at_image", register: () => registerVisionTool(ctx, deps) },
|
|
234
161
|
{ name: "free_pi_usage", register: () => registerUsageTool(ctx, deps) },
|
|
235
|
-
{
|
|
236
|
-
name: "free_pi_subagent_read",
|
|
237
|
-
register: () => registerSubagentTool(ctx, deps),
|
|
238
|
-
},
|
|
239
162
|
{ name: "web", register: () => registerWebTools(ctx, deps) },
|
|
240
163
|
{ name: "generate_image", register: () => registerGenerateImageTool(ctx, deps) },
|
|
241
164
|
];
|
package/dist/session/events.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/** Subscribes to core events that affect free-pi state. */
|
|
2
|
+
import { fetchQuota } from "../api/quota.js";
|
|
2
3
|
import { closeFreePiSession } from "../api/session.js";
|
|
3
4
|
import { readCredentialsToken } from "../auth/credentials.js";
|
|
4
5
|
import { tokenFromCredential } from "../auth/credential.js";
|
|
@@ -10,7 +11,6 @@ import { forgetToolStats, isFreePiSession } from "./tools.js";
|
|
|
10
11
|
import { trimSet } from "../utils/async.js";
|
|
11
12
|
import { beginExecution, cancelAllFinalizeTimers, endExecution, finalizeFreePiSession, forgetFreePiSession, } from "./track.js";
|
|
12
13
|
import { markWireSessionDirty, } from "./wire.js";
|
|
13
|
-
import { recordUsage } from "./usage.js";
|
|
14
14
|
function isAbortLike(error) {
|
|
15
15
|
if (!error)
|
|
16
16
|
return false;
|
|
@@ -26,7 +26,6 @@ const EVENT_TYPES = [
|
|
|
26
26
|
"session.execution.succeeded",
|
|
27
27
|
"session.execution.failed",
|
|
28
28
|
"session.execution.interrupted",
|
|
29
|
-
"session.usage.updated",
|
|
30
29
|
"session.step.ended",
|
|
31
30
|
"session.deleted",
|
|
32
31
|
"location.shutdown",
|
|
@@ -103,6 +102,9 @@ async function handleEvent(ctx, deps, event) {
|
|
|
103
102
|
}
|
|
104
103
|
case "session.execution.succeeded": {
|
|
105
104
|
endExecution(deps, event.data?.sessionID);
|
|
105
|
+
// Usage and cost are OpenCode's; the free-pi account quota is not, so a
|
|
106
|
+
// finished turn is the moment to refresh the picker's access filter.
|
|
107
|
+
void fetchQuota(deps).catch(() => undefined);
|
|
106
108
|
return;
|
|
107
109
|
}
|
|
108
110
|
case "session.execution.interrupted": {
|
|
@@ -113,21 +115,12 @@ async function handleEvent(ctx, deps, event) {
|
|
|
113
115
|
endExecution(deps, sessionID);
|
|
114
116
|
return;
|
|
115
117
|
}
|
|
116
|
-
case "session.usage.updated": {
|
|
117
|
-
const sessionID = event.data?.sessionID;
|
|
118
|
-
if (typeof sessionID !== "string" || !isFreePiSession(deps, sessionID)) {
|
|
119
|
-
return;
|
|
120
|
-
}
|
|
121
|
-
recordUsage(deps, sessionID, event.data?.cost, event.data?.tokens);
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
118
|
case "session.step.ended": {
|
|
125
119
|
const sessionID = event.data?.sessionID;
|
|
126
120
|
if (typeof sessionID !== "string" || !isFreePiSession(deps, sessionID)) {
|
|
127
121
|
return;
|
|
128
122
|
}
|
|
129
|
-
|
|
130
|
-
// Step tokens are per request; usage.updated is cumulative.
|
|
123
|
+
// Step tokens are per request; OpenCode owns cumulative usage.
|
|
131
124
|
noteStepTokens(deps, deps.state.trackedModels.get(sessionID)?.modelID ?? "", event.data?.tokens);
|
|
132
125
|
return;
|
|
133
126
|
}
|