@eduardo191labs/opencode-free-pi 0.2.7 → 0.3.1
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 +151 -157
- package/dist/ads/context.d.ts +18 -0
- package/dist/ads/context.js +125 -0
- package/dist/ads/impression.d.ts +7 -0
- package/dist/ads/impression.js +85 -0
- package/dist/ads/resolve.d.ts +11 -0
- package/dist/ads/resolve.js +35 -0
- package/dist/ads/turns.d.ts +6 -0
- package/dist/ads/turns.js +14 -0
- package/dist/api/quota.d.ts +8 -0
- package/dist/api/quota.js +90 -0
- package/dist/api/session.d.ts +9 -0
- package/dist/api/session.js +69 -0
- package/dist/auth/authorize.d.ts +14 -0
- package/dist/auth/authorize.js +60 -0
- package/dist/auth/connect.d.ts +7 -0
- package/dist/auth/connect.js +117 -0
- package/dist/auth/credential.d.ts +5 -0
- package/dist/auth/credential.js +34 -0
- package/dist/auth/credentials.d.ts +7 -0
- package/dist/auth/credentials.js +56 -0
- package/dist/auth/jwt.d.ts +7 -0
- package/dist/auth/jwt.js +60 -0
- package/dist/auth/token.d.ts +14 -0
- package/dist/auth/token.js +28 -0
- package/dist/catalog/catalog.d.ts +6 -0
- package/dist/catalog/catalog.js +80 -0
- package/dist/catalog/models.d.ts +15 -0
- package/dist/catalog/models.js +206 -0
- package/dist/catalog/registry.d.ts +9 -0
- package/dist/catalog/registry.js +96 -0
- package/dist/catalog/v2.d.ts +18 -0
- package/dist/catalog/v2.js +93 -0
- package/dist/constants.d.ts +46 -0
- package/dist/constants.js +46 -0
- package/dist/deps.d.ts +11 -0
- package/dist/deps.js +2 -0
- package/dist/errors/handle.d.ts +5 -0
- package/dist/errors/handle.js +64 -0
- package/dist/errors/invalid.d.ts +3 -0
- package/dist/errors/invalid.js +8 -0
- package/dist/errors/limit.d.ts +10 -0
- package/dist/errors/limit.js +110 -0
- package/dist/errors/messages.d.ts +6 -0
- package/dist/errors/messages.js +119 -0
- package/dist/errors/parse.d.ts +4 -0
- package/dist/errors/parse.js +153 -0
- package/dist/index.d.ts +9 -9
- package/dist/index.js +7 -3376
- package/dist/integration/setup.d.ts +4 -0
- package/dist/integration/setup.js +49 -0
- package/dist/logging.d.ts +9 -0
- package/dist/logging.js +62 -0
- package/dist/plugin.d.ts +4 -0
- package/dist/plugin.js +109 -0
- package/dist/session/events.d.ts +4 -0
- package/dist/session/events.js +96 -0
- package/dist/session/hooks.d.ts +8 -0
- package/dist/session/hooks.js +114 -0
- package/dist/session/track.d.ts +21 -0
- package/dist/session/track.js +107 -0
- package/dist/session/usage.d.ts +5 -0
- package/dist/session/usage.js +32 -0
- package/dist/state.d.ts +43 -0
- package/dist/state.js +26 -0
- package/dist/types.d.ts +272 -0
- package/dist/types.js +2 -0
- package/dist/utils/async.d.ts +8 -0
- package/dist/utils/async.js +29 -0
- package/dist/utils/browser.d.ts +3 -0
- package/dist/utils/browser.js +55 -0
- package/dist/utils/cache.d.ts +7 -0
- package/dist/utils/cache.js +45 -0
- package/dist/utils/device.d.ts +6 -0
- package/dist/utils/device.js +29 -0
- package/dist/utils/http.d.ts +4 -0
- package/dist/utils/http.js +42 -0
- package/dist/utils/json.d.ts +2 -0
- package/dist/utils/json.js +9 -0
- package/dist/utils/numbers.d.ts +6 -0
- package/dist/utils/numbers.js +49 -0
- package/dist/utils/text.d.ts +2 -0
- package/dist/utils/text.js +6 -0
- package/dist/utils/urls.d.ts +6 -0
- package/dist/utils/urls.js +41 -0
- package/install.ps1 +82 -46
- package/install.sh +98 -40
- package/package.json +5 -4
- package/scripts/postinstall.mjs +68 -34
- package/src/ads/context.ts +156 -0
- package/src/ads/impression.ts +111 -0
- package/src/ads/resolve.ts +62 -0
- package/src/ads/turns.ts +24 -0
- package/src/api/quota.ts +110 -0
- package/src/api/session.ts +76 -0
- package/src/auth/authorize.ts +104 -0
- package/src/auth/connect.ts +144 -0
- package/src/auth/credential.ts +39 -0
- package/src/auth/credentials.ts +60 -0
- package/src/auth/jwt.ts +75 -0
- package/src/auth/token.ts +52 -0
- package/src/catalog/catalog.ts +94 -0
- package/src/catalog/models.ts +291 -0
- package/src/catalog/registry.ts +122 -0
- package/src/catalog/v2.ts +124 -0
- package/src/constants.ts +61 -0
- package/src/deps.ts +13 -0
- package/src/errors/handle.ts +79 -0
- package/src/errors/invalid.ts +15 -0
- package/src/errors/limit.ts +114 -0
- package/src/errors/messages.ts +151 -0
- package/src/errors/parse.ts +156 -0
- package/src/index.ts +23 -4042
- package/src/integration/setup.ts +59 -0
- package/src/logging.ts +70 -0
- package/src/plugin.ts +143 -0
- package/src/session/events.ts +117 -0
- package/src/session/hooks.ts +192 -0
- package/src/session/track.ts +124 -0
- package/src/session/usage.ts +46 -0
- package/src/state.ts +82 -0
- package/src/types.ts +259 -0
- package/src/utils/async.ts +35 -0
- package/src/utils/browser.ts +61 -0
- package/src/utils/cache.ts +49 -0
- package/src/utils/device.ts +25 -0
- package/src/utils/http.ts +56 -0
- package/src/utils/json.ts +9 -0
- package/src/utils/numbers.ts +52 -0
- package/src/utils/text.ts +7 -0
- package/src/utils/urls.ts +47 -0
package/README.md
CHANGED
|
@@ -1,156 +1,111 @@
|
|
|
1
1
|
# @eduardo191labs/opencode-free-pi
|
|
2
2
|
|
|
3
|
-
Proveedor **free-pi** para [OpenCode](https://opencode.ai)
|
|
4
|
-
financiados con anuncios, sin claves de API. Funciona en
|
|
5
|
-
y Termux**.
|
|
3
|
+
Proveedor **free-pi** para [OpenCode](https://opencode.ai) 2.3.2 o superior:
|
|
4
|
+
modelos gratuitos financiados con anuncios, sin claves de API. Funciona en
|
|
5
|
+
**Windows, Linux, macOS y Termux**.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
```bash
|
|
10
|
-
npm i -g @eduardo191labs/opencode-free-pi
|
|
11
|
-
opencode plugin --global @eduardo191labs/opencode-free-pi
|
|
12
|
-
```
|
|
13
|
-
|
|
14
|
-
El primer comando instala el paquete y sus dependencias. El segundo instala
|
|
15
|
-
las dependencias dentro de la configuración de OpenCode, escribe la entrada
|
|
16
|
-
`plugin` y es la forma recomendada, porque npm 12 bloquea los scripts de
|
|
17
|
-
instalación por defecto. En versiones nuevas de OpenCode el subcomando es
|
|
18
|
-
`opencode plugin add`.
|
|
19
|
-
|
|
20
|
-
El `postinstall` del paquete copia el plugin a
|
|
21
|
-
`~/.config/opencode/plugins/opencode-free-pi.ts` (en Windows,
|
|
22
|
-
`%USERPROFILE%\.config\opencode\plugins\opencode-free-pi.ts`) para que
|
|
23
|
-
OpenCode lo descubra automáticamente. Si tu npm bloquea scripts, ejecuta
|
|
24
|
-
también `opencode plugin --global @eduardo191labs/opencode-free-pi` (o
|
|
25
|
-
`opencode plugin add ...` en versiones nuevas).
|
|
7
|
+
El paquete usa el SDK de plugins de OpenCode V2 (`@opencode/plugin`) y exporta
|
|
8
|
+
el plugin en el formato `Plugin.define({ id, setup })`.
|
|
26
9
|
|
|
27
|
-
|
|
28
|
-
`FREEPI_CONFIGURE=1 npm install`.
|
|
10
|
+
## Requisitos
|
|
29
11
|
|
|
30
|
-
|
|
12
|
+
- OpenCode **2.3.2+**
|
|
13
|
+
- Node.js **20+**
|
|
14
|
+
- Una cuenta de free-pi (GitHub) o un JWT de free-pi
|
|
31
15
|
|
|
32
|
-
|
|
33
|
-
`exports`. Este paquete exporta las dos formas: el `server` de OpenCode 1.x y
|
|
34
|
-
el `setup` de OpenCode 2, así que el mismo paquete funciona en ambos.
|
|
16
|
+
## Instalación desde npm
|
|
35
17
|
|
|
36
18
|
```bash
|
|
19
|
+
npm i -g @eduardo191labs/opencode-free-pi
|
|
37
20
|
opencode plugin add @eduardo191labs/opencode-free-pi@latest
|
|
38
21
|
opencode plugin list
|
|
39
22
|
```
|
|
40
23
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
el
|
|
24
|
+
`opencode plugin add` instala el paquete dentro de la configuración de OpenCode
|
|
25
|
+
y lo añade a la lista `plugins`. Es la forma recomendada. En versiones antiguas
|
|
26
|
+
del CLI el subcomando equivalente es `opencode plugin --global ...`.
|
|
44
27
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
`id` ni `version`. Elimínala y deja solo una:
|
|
28
|
+
La lista debe mostrar `free-pi` como `active`. Si aparece `failed`, ejecuta
|
|
29
|
+
`opencode --print-logs` y revisa el `cause=` del log.
|
|
48
30
|
|
|
49
|
-
|
|
50
|
-
opencode plugin remove @eduardo191labs/opencode-free-pi@0.2.3
|
|
51
|
-
opencode plugin list
|
|
52
|
-
```
|
|
31
|
+
### Registro manual
|
|
53
32
|
|
|
54
|
-
|
|
55
|
-
`~/.config/opencode/plugins/opencode-free-pi.ts`. Ese archivo local no tiene
|
|
56
|
-
versión de paquete y puede quedar desactualizado; en OpenCode 2 bórralo para
|
|
57
|
-
que no compita con el paquete:
|
|
33
|
+
Añade el paquete a la lista `plugins` de tu `opencode.json`:
|
|
58
34
|
|
|
59
|
-
```
|
|
60
|
-
|
|
35
|
+
```json
|
|
36
|
+
{
|
|
37
|
+
"plugins": ["@eduardo191labs/opencode-free-pi"]
|
|
38
|
+
}
|
|
61
39
|
```
|
|
62
40
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
41
|
+
El `postinstall` del paquete hace esto automáticamente cuando la instalación es
|
|
42
|
+
global (`npm i -g`) o cuando defines `FREEPI_CONFIGURE=1`. No copia archivos a
|
|
43
|
+
`~/.config/opencode/plugins/`: el paquete debe seguir resolviéndose desde
|
|
44
|
+
`node_modules` porque importa `@opencode/plugin` en tiempo de ejecución.
|
|
66
45
|
|
|
67
|
-
|
|
68
|
-
también registra la integración `free-pi`, así que el inicio de sesión
|
|
69
|
-
interactivo funciona en OpenCode 2:
|
|
46
|
+
## Iniciar sesión
|
|
70
47
|
|
|
71
48
|
```bash
|
|
72
49
|
opencode auth login free-pi
|
|
73
50
|
```
|
|
74
51
|
|
|
75
|
-
|
|
76
|
-
`FREEPI_JWT` o de `~/.free-pi/agent/credentials.json`.
|
|
52
|
+
Métodos disponibles:
|
|
77
53
|
|
|
78
|
-
|
|
54
|
+
1. **GitHub OAuth**: abre el navegador y confirma el código. Si el navegador no
|
|
55
|
+
está disponible, usa el flujo de dispositivo de GitHub.
|
|
56
|
+
2. **Pegar un JWT**: útil si ya tienes un token de free-pi.
|
|
57
|
+
3. **Variable de entorno**: define `FREEPI_JWT`.
|
|
79
58
|
|
|
80
|
-
|
|
81
|
-
|
|
59
|
+
El plugin también lee `~/.free-pi/agent/credentials.json`, el archivo que crea
|
|
60
|
+
`free-pi-cli`, como respaldo.
|
|
82
61
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
```powershell
|
|
86
|
-
curl.exe -fsSL "https://raw.githubusercontent.com/eduardo191-star/opencode-free-pi/main/install.ps1" | powershell -NoProfile -ExecutionPolicy Bypass -Command -
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
Si tu terminal no acepta la tubería, descarga y ejecuta el `.ps1`:
|
|
90
|
-
|
|
91
|
-
```powershell
|
|
92
|
-
curl.exe -fsSL -o "$env:TEMP\install-free-pi.ps1" "https://raw.githubusercontent.com/eduardo191-star/opencode-free-pi/main/install.ps1"; powershell -NoProfile -ExecutionPolicy Bypass -File "$env:TEMP\install-free-pi.ps1"
|
|
93
|
-
```
|
|
94
|
-
|
|
95
|
-
Alternativa si `curl.exe` no está disponible:
|
|
96
|
-
|
|
97
|
-
```powershell
|
|
98
|
-
powershell -NoProfile -ExecutionPolicy Bypass -Command "irm 'https://raw.githubusercontent.com/eduardo191-star/opencode-free-pi/main/install.ps1' | iex"
|
|
99
|
-
```
|
|
100
|
-
|
|
101
|
-
### Linux, macOS y Termux
|
|
102
|
-
|
|
103
|
-
```bash
|
|
104
|
-
curl -fsSL "https://raw.githubusercontent.com/eduardo191-star/opencode-free-pi/main/install.sh" | bash
|
|
105
|
-
```
|
|
106
|
-
|
|
107
|
-
En Termux, si falta `curl`:
|
|
108
|
-
|
|
109
|
-
```bash
|
|
110
|
-
pkg install curl
|
|
111
|
-
```
|
|
112
|
-
|
|
113
|
-
## Después de instalar
|
|
114
|
-
|
|
115
|
-
OpenCode 2:
|
|
116
|
-
|
|
117
|
-
```bash
|
|
118
|
-
opencode auth login free-pi
|
|
119
|
-
opencode
|
|
120
|
-
```
|
|
121
|
-
|
|
122
|
-
OpenCode 1.x:
|
|
123
|
-
|
|
124
|
-
```bash
|
|
125
|
-
opencode auth login -p free-pi
|
|
126
|
-
opencode
|
|
127
|
-
```
|
|
128
|
-
|
|
129
|
-
El plugin se registra como proveedor `free-pi`, elige un modelo gratuito por
|
|
130
|
-
defecto y desactiva el agente `title` para no gastar una petición extra.
|
|
62
|
+
Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
131
63
|
|
|
132
64
|
## Qué hace
|
|
133
65
|
|
|
134
|
-
- Catálogo de modelos free-pi y free-pi-defense
|
|
135
|
-
-
|
|
66
|
+
- Catálogo en vivo de modelos **free-pi** y **free-pi-defense**.
|
|
67
|
+
- Integración nativa de OpenCode V2 para credenciales OAuth, clave y entorno.
|
|
136
68
|
- Cuota diaria, créditos premium y límites con mensajes claros.
|
|
137
69
|
- Anuncios e impresiones asociados al turno correcto.
|
|
138
|
-
-
|
|
139
|
-
|
|
140
|
-
|
|
70
|
+
- Cada agente y subagente usa su propio `x-session-id`, `x-turn-id` y contexto
|
|
71
|
+
de anuncios; nunca reutiliza los del agente principal.
|
|
72
|
+
- **Cierre de sesión**: free-pi limita la cuenta a 4 sesiones simultáneas. El
|
|
73
|
+
plugin finaliza la sesión del proveedor cuando la ejecución del modelo
|
|
74
|
+
termina (éxito, fallo o interrupción) y al apagar OpenCode.
|
|
141
75
|
- Recuperación automática del límite de sesiones concurrentes.
|
|
76
|
+
- **Catálogo y metadatos resistentes**: el catálogo de free-pi y el registro de
|
|
77
|
+
models.dev se guardan en disco; si la red falla al arrancar se usan las copias
|
|
78
|
+
locales en vez de quedarse sin modelos o sin límites de contexto.
|
|
142
79
|
- Compatible con rutas, credenciales y navegador de cada sistema operativo.
|
|
143
80
|
|
|
81
|
+
No incluye herramientas personalizadas. Usa las herramientas integradas de
|
|
82
|
+
OpenCode.
|
|
83
|
+
|
|
84
|
+
## Cabeceras enviadas
|
|
85
|
+
|
|
86
|
+
El plugin replica las cabeceras del plugin V1 de free-pi:
|
|
87
|
+
|
|
88
|
+
- **Modelo**: `authorization`, `x-session-id`, `x-client-version`,
|
|
89
|
+
`x-turn-id` y `x-freepi-cost-exp` (cuando el catálogo asigna un experimento).
|
|
90
|
+
- **Anuncios** (`/ads/next`): `authorization`, `x-session-id`,
|
|
91
|
+
`x-client-version`, `x-turn-id`, `x-ad-trigger`, `x-client-os`,
|
|
92
|
+
`x-client-arch`, `x-client-timezone`, `x-client-locale` y `x-ad-context`.
|
|
93
|
+
- **Impresión** (`/ads/impression`): `authorization`, `content-type` y
|
|
94
|
+
`x-session-id`.
|
|
95
|
+
- **Reset de sesión** (`/session/reset`): `authorization`,
|
|
96
|
+
`x-client-version` y, cuando aplica, `x-session-id`.
|
|
97
|
+
|
|
98
|
+
Las respuestas `429` de límites largos se reescriben a un `400` con el mensaje
|
|
99
|
+
amigable, igual que en el plugin V1.
|
|
100
|
+
|
|
144
101
|
## Rutas por plataforma
|
|
145
102
|
|
|
146
|
-
| Elemento | Windows | Linux / macOS / Termux
|
|
147
|
-
| --------------- | ------------------------------------------------------------ |
|
|
148
|
-
|
|
|
149
|
-
|
|
|
150
|
-
| Config OpenCode | `%USERPROFILE%\.config\opencode\opencode.json[c]` | `~/.config/opencode/opencode.json[c]` |
|
|
103
|
+
| Elemento | Windows | Linux / macOS / Termux |
|
|
104
|
+
| --------------- | ------------------------------------------------------------ | -------------------------------------- |
|
|
105
|
+
| Credenciales | `%USERPROFILE%\.free-pi\agent\credentials.json` | `~/.free-pi/agent/credentials.json` |
|
|
106
|
+
| Config OpenCode | `%USERPROFILE%\.config\opencode\opencode.json[c]` | `~/.config/opencode/opencode.json[c]` |
|
|
151
107
|
|
|
152
|
-
Si `XDG_CONFIG_HOME` o `OPENCODE_CONFIG_DIR` están definidos,
|
|
153
|
-
respeta.
|
|
108
|
+
Si `XDG_CONFIG_HOME` o `OPENCODE_CONFIG_DIR` están definidos, se respetan.
|
|
154
109
|
|
|
155
110
|
## Variables de entorno (opcionales)
|
|
156
111
|
|
|
@@ -162,44 +117,70 @@ respeta.
|
|
|
162
117
|
| `FREEPI_MODELS_URL` | Cambiar el registro de modelos. |
|
|
163
118
|
| `FREEPI_NO_BROWSER=1` | No abrir el navegador. |
|
|
164
119
|
| `FREEPI_DEVICE_LOGIN=1` | Forzar inicio de sesión por dispositivo. |
|
|
120
|
+
| `FREEPI_CONFIGURE=1` | Registrar el paquete en `opencode.json` al instalar. |
|
|
165
121
|
| `OPENCODE_CONFIG_DIR` | Directorio de configuración de OpenCode. |
|
|
122
|
+
| `FREE_PI_CACHE_DIR` | Directorio de caché del plugin. |
|
|
123
|
+
| `FREE_PI_LOG_FILE` | Ruta alternativa del archivo de log del plugin. |
|
|
166
124
|
|
|
167
|
-
No hay variables obligatorias.
|
|
168
|
-
para `HOME`, `USERPROFILE`, `XDG_CONFIG_HOME`, `APPDATA` cuando aplica, Termux y
|
|
169
|
-
Windows.
|
|
125
|
+
No hay variables obligatorias.
|
|
170
126
|
|
|
171
|
-
##
|
|
127
|
+
## Caché y logs
|
|
172
128
|
|
|
173
|
-
El
|
|
129
|
+
El plugin guarda el catálogo de free-pi y el registro de models.dev en:
|
|
174
130
|
|
|
175
|
-
```
|
|
176
|
-
|
|
177
|
-
|
|
131
|
+
```text
|
|
132
|
+
~/.cache/opencode/free-pi/catalog.json
|
|
133
|
+
~/.cache/opencode/free-pi/models-dev.json
|
|
178
134
|
```
|
|
179
135
|
|
|
180
|
-
|
|
136
|
+
En Windows es `%USERPROFILE%\.cache\opencode\free-pi\`. El catálogo se reutiliza
|
|
137
|
+
hasta 24 h y el registro hasta 7 días si la red falla; cuando la petición
|
|
138
|
+
funciona, las copias se refrescan solas.
|
|
181
139
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
140
|
+
Los mensajes del plugin se escriben en la consola con el prefijo `[free-pi]` y
|
|
141
|
+
también en:
|
|
142
|
+
|
|
143
|
+
```text
|
|
144
|
+
~/.cache/opencode/free-pi/plugin.log
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
El archivo rota a `plugin.log.1` al llegar a 1 MB. Ejemplo:
|
|
148
|
+
|
|
149
|
+
```text
|
|
150
|
+
2026-11-21T08:20:00.000Z INFO [free-pi] Loaded 20 free-pi model(s) and 7 defense model(s)
|
|
151
|
+
2026-11-21T08:20:00.000Z WARN [free-pi] models.dev is unreachable; using cached model metadata {"reason":"request timed out"}
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
## Instalación rápida con script
|
|
155
|
+
|
|
156
|
+
### Windows (PowerShell)
|
|
157
|
+
|
|
158
|
+
```powershell
|
|
159
|
+
curl.exe -fsSL "https://raw.githubusercontent.com/eduardo191-star/opencode-free-pi/main/install.ps1" | powershell -NoProfile -ExecutionPolicy Bypass -Command -
|
|
186
160
|
```
|
|
187
161
|
|
|
188
|
-
|
|
189
|
-
siendo útil si prefieres copiar el archivo directamente a la carpeta de plugins.
|
|
162
|
+
Si tu terminal no acepta la tubería:
|
|
190
163
|
|
|
191
|
-
|
|
164
|
+
```powershell
|
|
165
|
+
curl.exe -fsSL -o "$env:TEMP\install-free-pi.ps1" "https://raw.githubusercontent.com/eduardo191-star/opencode-free-pi/main/install.ps1"; powershell -NoProfile -ExecutionPolicy Bypass -File "$env:TEMP\install-free-pi.ps1"
|
|
166
|
+
```
|
|
192
167
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
168
|
+
### Linux, macOS y Termux
|
|
169
|
+
|
|
170
|
+
```bash
|
|
171
|
+
curl -fsSL "https://raw.githubusercontent.com/eduardo191-star/opencode-free-pi/main/install.sh" | bash
|
|
172
|
+
```
|
|
197
173
|
|
|
198
|
-
|
|
199
|
-
publicar, ejecuta el workflow manualmente con `publish = false`.
|
|
174
|
+
En Termux, si falta `curl`: `pkg install curl`.
|
|
200
175
|
|
|
201
|
-
|
|
202
|
-
|
|
176
|
+
## Paquete npm
|
|
177
|
+
|
|
178
|
+
El paquete incluye `dist/` compilado y tipos TypeScript:
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
npm pack
|
|
182
|
+
npm install -g ./eduardo191labs-opencode-free-pi-*.tgz
|
|
183
|
+
```
|
|
203
184
|
|
|
204
185
|
## Desarrollo
|
|
205
186
|
|
|
@@ -207,41 +188,54 @@ workflow.
|
|
|
207
188
|
npm install
|
|
208
189
|
npm run typecheck
|
|
209
190
|
npm run build
|
|
210
|
-
npm
|
|
191
|
+
npm test
|
|
211
192
|
```
|
|
212
193
|
|
|
213
194
|
Estructura:
|
|
214
195
|
|
|
215
196
|
```text
|
|
216
|
-
src/
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
197
|
+
src/
|
|
198
|
+
index.ts export público
|
|
199
|
+
plugin.ts entrada V2 (Plugin.define)
|
|
200
|
+
constants.ts identificadores y valores por defecto
|
|
201
|
+
types.ts tipos del dominio
|
|
202
|
+
state.ts estado mutable por instancia
|
|
203
|
+
deps.ts dependencias compartidas
|
|
204
|
+
logging.ts logger con prefijo [free-pi]
|
|
205
|
+
auth/ OAuth, JWT, credenciales y conexión
|
|
206
|
+
api/ cuota y reset de sesión
|
|
207
|
+
ads/ contexto, turnos e impresiones
|
|
208
|
+
catalog/ catálogo en vivo y registro models.dev
|
|
209
|
+
errors/ parseo, mensajes y reescritura de límites
|
|
210
|
+
integration/ integración y métodos de inicio de sesión
|
|
211
|
+
session/ hooks, eventos, seguimiento y uso
|
|
212
|
+
utils/ helpers pequeños (incluye cache.ts)
|
|
213
|
+
dist/ build ESM y tipos
|
|
214
|
+
scripts/postinstall.mjs registro en opencode.json
|
|
215
|
+
test/smoke.mjs prueba de humo del build
|
|
216
|
+
test/registry.mjs caché y tolerancia a fallos de models.dev
|
|
221
217
|
```
|
|
222
218
|
|
|
223
219
|
## Desinstalar
|
|
224
220
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
powershell -NoProfile -ExecutionPolicy Bypass -Command "$p=Join-Path $env:TEMP 'install-free-pi.ps1'; irm 'https://raw.githubusercontent.com/eduardo191-star/opencode-free-pi/main/install.ps1' -OutFile $p; & $p -Uninstall"
|
|
229
|
-
```
|
|
230
|
-
|
|
231
|
-
Linux/macOS/Termux:
|
|
221
|
+
1. Quita `@eduardo191labs/opencode-free-pi` de la lista `plugins` de tu
|
|
222
|
+
`opencode.json`.
|
|
223
|
+
2. Desinstala el paquete:
|
|
232
224
|
|
|
233
225
|
```bash
|
|
234
|
-
|
|
226
|
+
npm uninstall -g @eduardo191labs/opencode-free-pi
|
|
235
227
|
```
|
|
236
228
|
|
|
237
|
-
|
|
238
|
-
|
|
229
|
+
3. Si tenías una copia antigua, borra
|
|
230
|
+
`~/.config/opencode/plugins/opencode-free-pi.ts` (en Windows,
|
|
231
|
+
`%USERPROFILE%\.config\opencode\plugins\opencode-free-pi.ts`).
|
|
239
232
|
|
|
240
233
|
## Privacidad
|
|
241
234
|
|
|
242
235
|
El plugin se comunica con `https://api.freepi.ai` para autenticación, cuota,
|
|
243
|
-
anuncios y completions. El contexto de anuncios
|
|
244
|
-
incluye claves ni tokens en el
|
|
236
|
+
anuncios y completions. El contexto de anuncios se redacta antes de enviarse y
|
|
237
|
+
no se incluye en la petición al modelo. No incluye claves ni tokens en el
|
|
238
|
+
repositorio.
|
|
245
239
|
|
|
246
240
|
## Licencia
|
|
247
241
|
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Builds and redacts the ad context sent with a user turn. */
|
|
2
|
+
export declare function redactAdSecrets(text: string): string;
|
|
3
|
+
export declare function adContextText(text: string | undefined): string | undefined;
|
|
4
|
+
export declare function adContextFor(userText: string, assistantText?: string): string | undefined;
|
|
5
|
+
/** A message from either a session record or a provider request. */
|
|
6
|
+
export type AdMessage = {
|
|
7
|
+
type?: unknown;
|
|
8
|
+
role?: unknown;
|
|
9
|
+
id?: unknown;
|
|
10
|
+
text?: unknown;
|
|
11
|
+
content?: unknown;
|
|
12
|
+
};
|
|
13
|
+
/** Latest non-empty assistant text from a message list. */
|
|
14
|
+
export declare function latestAssistantText(messages: readonly AdMessage[]): string;
|
|
15
|
+
/** Latest user text from a message list. */
|
|
16
|
+
export declare function latestUserText(messages: readonly AdMessage[]): string;
|
|
17
|
+
/** Latest user message id from a message list. */
|
|
18
|
+
export declare function latestUserMessageID(messages: readonly AdMessage[]): string | undefined;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/** Builds and redacts the ad context sent with a user turn. */
|
|
2
|
+
import { AD_CONTEXT_MAX_CHARS } from "../constants.js";
|
|
3
|
+
import { cleanText } from "../utils/text.js";
|
|
4
|
+
const AD_SECRET_PATTERNS = [
|
|
5
|
+
[
|
|
6
|
+
"private_key",
|
|
7
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]{1,20000}?-----END [A-Z ]*PRIVATE KEY-----/g,
|
|
8
|
+
],
|
|
9
|
+
[
|
|
10
|
+
"private_key",
|
|
11
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\sA-Za-z0-9+/=]{20,20000}/g,
|
|
12
|
+
],
|
|
13
|
+
["anthropic_key", /\bsk-ant-[A-Za-z0-9_-]{20,255}/g],
|
|
14
|
+
["openrouter_key", /\bsk-or-v1-[A-Za-z0-9]{32,255}/g],
|
|
15
|
+
["api_key", /\bsk-[A-Za-z0-9_-]{20,255}/g],
|
|
16
|
+
["google_api_key", /\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])/g],
|
|
17
|
+
["stripe_secret", /\b[sr]k_(?:live|test)_[0-9A-Za-z]{20,255}/g],
|
|
18
|
+
["github_token", /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,255}/g],
|
|
19
|
+
["github_token", /\bgithub_pat_[A-Za-z0-9_]{22,255}/g],
|
|
20
|
+
["gitlab_token", /\bglpat-[A-Za-z0-9_-]{20,255}/g],
|
|
21
|
+
["aws_key_id", /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g],
|
|
22
|
+
["slack_token", /\bxox[baprs]-[A-Za-z0-9-]{10,255}/g],
|
|
23
|
+
[
|
|
24
|
+
"jwt",
|
|
25
|
+
/\beyJ[A-Za-z0-9_-]{8,512}\.[A-Za-z0-9_-]{8,8192}\.[A-Za-z0-9_-]{8,1024}(?![A-Za-z0-9_-])/g,
|
|
26
|
+
],
|
|
27
|
+
["bearer", /\bBearer\s+[A-Za-z0-9._~+/=-]{16,512}/gi],
|
|
28
|
+
];
|
|
29
|
+
const AD_SECRET_ASSIGNMENT = /(?<![A-Za-z0-9_.-])(["']?)([A-Za-z0-9_.-]+)\1?(\s*[:=]\s*)("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^\s"']{8,})/g;
|
|
30
|
+
const AD_SECRET_NAME = /api[_-]?key|secret|token|passwd|password|private[_-]?key|authorization/i;
|
|
31
|
+
export function redactAdSecrets(text) {
|
|
32
|
+
let output = text;
|
|
33
|
+
for (const [type, pattern] of AD_SECRET_PATTERNS) {
|
|
34
|
+
output = output.replace(pattern, `[REDACTED:${type}]`);
|
|
35
|
+
}
|
|
36
|
+
return output.replace(AD_SECRET_ASSIGNMENT, (match, _quote, name, _separator, value) => {
|
|
37
|
+
const head = match.slice(0, match.length - value.length);
|
|
38
|
+
if (!AD_SECRET_NAME.test(name)) {
|
|
39
|
+
return (head +
|
|
40
|
+
(value[0] === '"' || value[0] === "'"
|
|
41
|
+
? redactAdSecrets(value)
|
|
42
|
+
: value));
|
|
43
|
+
}
|
|
44
|
+
const quote = value[0] === '"' || value[0] === "'" ? value[0] : "";
|
|
45
|
+
return `${head}${quote}[REDACTED:secret]${quote}`;
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
export function adContextText(text) {
|
|
49
|
+
if (!text)
|
|
50
|
+
return undefined;
|
|
51
|
+
const value = redactAdSecrets(text).trim();
|
|
52
|
+
return value ? value.slice(0, AD_CONTEXT_MAX_CHARS) : undefined;
|
|
53
|
+
}
|
|
54
|
+
export function adContextFor(userText, assistantText) {
|
|
55
|
+
const payload = {};
|
|
56
|
+
const user = adContextText(userText);
|
|
57
|
+
const assistant = adContextText(assistantText);
|
|
58
|
+
if (user)
|
|
59
|
+
payload.user = user;
|
|
60
|
+
if (assistant)
|
|
61
|
+
payload.assistant = assistant;
|
|
62
|
+
if (!payload.user && !payload.assistant)
|
|
63
|
+
return undefined;
|
|
64
|
+
let encoded = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
65
|
+
while (encoded.length > 4096 && (payload.user || payload.assistant)) {
|
|
66
|
+
for (const key of ["user", "assistant"]) {
|
|
67
|
+
const value = payload[key];
|
|
68
|
+
if (value)
|
|
69
|
+
payload[key] = value.slice(0, Math.floor(value.length / 2));
|
|
70
|
+
}
|
|
71
|
+
encoded = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
72
|
+
}
|
|
73
|
+
return encoded;
|
|
74
|
+
}
|
|
75
|
+
function roleOf(message) {
|
|
76
|
+
const value = message.role ?? message.type;
|
|
77
|
+
return value === "user" || value === "assistant" ? value : undefined;
|
|
78
|
+
}
|
|
79
|
+
function contentText(content) {
|
|
80
|
+
if (typeof content === "string")
|
|
81
|
+
return content;
|
|
82
|
+
if (!Array.isArray(content))
|
|
83
|
+
return "";
|
|
84
|
+
return content
|
|
85
|
+
.filter((part) => part?.type === "text" &&
|
|
86
|
+
typeof part.text === "string" &&
|
|
87
|
+
part.synthetic !== true)
|
|
88
|
+
.map((part) => part.text)
|
|
89
|
+
.join("\n");
|
|
90
|
+
}
|
|
91
|
+
/** Latest non-empty assistant text from a message list. */
|
|
92
|
+
export function latestAssistantText(messages) {
|
|
93
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
94
|
+
const message = messages[index];
|
|
95
|
+
if (roleOf(message) !== "assistant")
|
|
96
|
+
continue;
|
|
97
|
+
const text = cleanText(contentText(message.content));
|
|
98
|
+
if (text)
|
|
99
|
+
return text;
|
|
100
|
+
}
|
|
101
|
+
return "";
|
|
102
|
+
}
|
|
103
|
+
/** Latest user text from a message list. */
|
|
104
|
+
export function latestUserText(messages) {
|
|
105
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
106
|
+
const message = messages[index];
|
|
107
|
+
if (roleOf(message) !== "user")
|
|
108
|
+
continue;
|
|
109
|
+
const text = cleanText(typeof message.text === "string" ? message.text : contentText(message.content));
|
|
110
|
+
if (text)
|
|
111
|
+
return text;
|
|
112
|
+
}
|
|
113
|
+
return "";
|
|
114
|
+
}
|
|
115
|
+
/** Latest user message id from a message list. */
|
|
116
|
+
export function latestUserMessageID(messages) {
|
|
117
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
118
|
+
const message = messages[index];
|
|
119
|
+
if (roleOf(message) !== "user")
|
|
120
|
+
continue;
|
|
121
|
+
if (typeof message.id === "string" && message.id)
|
|
122
|
+
return message.id;
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Fetches an ad for a turn and records its impression. */
|
|
2
|
+
import type { Deps } from "../deps.js";
|
|
3
|
+
import type { AdTurn } from "../types.js";
|
|
4
|
+
export declare function fireGravityImpression(ad: any): boolean;
|
|
5
|
+
export declare function postAdImpression(deps: Deps, token: string, sessionId: string, ad: any): Promise<void>;
|
|
6
|
+
export declare function fetchAdAndPostImpression(deps: Deps, token: string, sessionId: string, turn: AdTurn): Promise<void>;
|
|
7
|
+
export declare function ensureAdImpression(deps: Deps, token: string, sessionId: string, turn: AdTurn): Promise<void>;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** Fetches an ad for a turn and records its impression. */
|
|
2
|
+
import { AD_CONTEXT_HEADER, AD_IMPRESSION_LIMIT, AD_IMPRESSION_TIMEOUT_MS, AD_REQUEST_TIMEOUT_MS, } from "../constants.js";
|
|
3
|
+
import { trimMap } from "../utils/async.js";
|
|
4
|
+
import { adClientHeaders } from "../utils/device.js";
|
|
5
|
+
import { readJson } from "../utils/json.js";
|
|
6
|
+
import { resolveBaseUrl, safeUrl } from "../utils/urls.js";
|
|
7
|
+
export function fireGravityImpression(ad) {
|
|
8
|
+
const target = ad?.source === "gravity" ? safeUrl(ad.imp_url) : undefined;
|
|
9
|
+
if (!target)
|
|
10
|
+
return false;
|
|
11
|
+
try {
|
|
12
|
+
fetch(target, {
|
|
13
|
+
method: "GET",
|
|
14
|
+
signal: AbortSignal.timeout(AD_IMPRESSION_TIMEOUT_MS),
|
|
15
|
+
}).catch(() => undefined);
|
|
16
|
+
}
|
|
17
|
+
catch { }
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
export function postAdImpression(deps, token, sessionId, ad) {
|
|
21
|
+
const adId = typeof ad?.ad_id === "string" ? ad.ad_id : "";
|
|
22
|
+
const clickToken = typeof ad?.click_token === "string" ? ad.click_token : "";
|
|
23
|
+
if (!adId || !clickToken)
|
|
24
|
+
return Promise.resolve();
|
|
25
|
+
const existing = deps.state.adImpressions.get(clickToken);
|
|
26
|
+
if (existing)
|
|
27
|
+
return existing;
|
|
28
|
+
const promise = (async () => {
|
|
29
|
+
try {
|
|
30
|
+
const impFired = fireGravityImpression(ad);
|
|
31
|
+
const response = await fetch(`${resolveBaseUrl()}/ads/impression`, {
|
|
32
|
+
method: "POST",
|
|
33
|
+
headers: {
|
|
34
|
+
authorization: `Bearer ${token}`,
|
|
35
|
+
"content-type": "application/json",
|
|
36
|
+
"x-session-id": sessionId,
|
|
37
|
+
},
|
|
38
|
+
body: JSON.stringify({
|
|
39
|
+
ad_id: adId,
|
|
40
|
+
click_token: clickToken,
|
|
41
|
+
...(impFired ? { imp_fired: true } : {}),
|
|
42
|
+
}),
|
|
43
|
+
signal: AbortSignal.timeout(AD_IMPRESSION_TIMEOUT_MS),
|
|
44
|
+
}).catch(() => undefined);
|
|
45
|
+
if (!response?.ok)
|
|
46
|
+
deps.state.adImpressions.delete(clickToken);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
deps.state.adImpressions.delete(clickToken);
|
|
50
|
+
}
|
|
51
|
+
})();
|
|
52
|
+
trimMap(deps.state.adImpressions, AD_IMPRESSION_LIMIT);
|
|
53
|
+
deps.state.adImpressions.set(clickToken, promise);
|
|
54
|
+
return promise;
|
|
55
|
+
}
|
|
56
|
+
export async function fetchAdAndPostImpression(deps, token, sessionId, turn) {
|
|
57
|
+
try {
|
|
58
|
+
const headers = {
|
|
59
|
+
authorization: `Bearer ${token}`,
|
|
60
|
+
"x-session-id": sessionId,
|
|
61
|
+
"x-client-version": deps.state.latestClientVersion,
|
|
62
|
+
"x-turn-id": turn.turnId,
|
|
63
|
+
"x-ad-trigger": "user_message",
|
|
64
|
+
...adClientHeaders(),
|
|
65
|
+
...(turn.context ? { [AD_CONTEXT_HEADER]: turn.context } : {}),
|
|
66
|
+
};
|
|
67
|
+
const response = await fetch(`${resolveBaseUrl()}/ads/next?slot=banner`, {
|
|
68
|
+
headers,
|
|
69
|
+
signal: AbortSignal.timeout(AD_REQUEST_TIMEOUT_MS),
|
|
70
|
+
}).catch(() => undefined);
|
|
71
|
+
if (!response?.ok || response.status === 204)
|
|
72
|
+
return;
|
|
73
|
+
const ad = await readJson(response);
|
|
74
|
+
if (!ad)
|
|
75
|
+
return;
|
|
76
|
+
await postAdImpression(deps, token, sessionId, ad);
|
|
77
|
+
}
|
|
78
|
+
catch { }
|
|
79
|
+
}
|
|
80
|
+
export function ensureAdImpression(deps, token, sessionId, turn) {
|
|
81
|
+
if (!turn.impression) {
|
|
82
|
+
turn.impression = fetchAdAndPostImpression(deps, token, sessionId, turn).catch(() => undefined);
|
|
83
|
+
}
|
|
84
|
+
return turn.impression;
|
|
85
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Resolves (or creates) the ad turn for a session request. */
|
|
2
|
+
import type { Deps } from "../deps.js";
|
|
3
|
+
import type { AdTurn } from "../types.js";
|
|
4
|
+
import { type AdMessage } from "./context.js";
|
|
5
|
+
export type AdTurnRequest = {
|
|
6
|
+
readonly sessionID: string;
|
|
7
|
+
readonly agent: string | undefined;
|
|
8
|
+
readonly kind: string;
|
|
9
|
+
readonly messages?: readonly AdMessage[];
|
|
10
|
+
};
|
|
11
|
+
export declare function resolveAdTurn(deps: Deps, request: AdTurnRequest): Promise<AdTurn>;
|