@eduardo191labs/opencode-free-pi 0.2.6 → 0.3.0
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 +118 -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 +4 -0
- package/dist/catalog/catalog.js +43 -0
- package/dist/catalog/models.d.ts +15 -0
- package/dist/catalog/models.js +206 -0
- package/dist/catalog/registry.d.ts +4 -0
- package/dist/catalog/registry.js +46 -0
- package/dist/catalog/v2.d.ts +18 -0
- package/dist/catalog/v2.js +93 -0
- package/dist/constants.d.ts +40 -0
- package/dist/constants.js +40 -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 +19 -0
- package/dist/plugin.d.ts +4 -0
- package/dist/plugin.js +106 -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/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 +4 -3
- 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 +42 -0
- package/src/catalog/models.ts +291 -0
- package/src/catalog/registry.ts +51 -0
- package/src/catalog/v2.ts +124 -0
- package/src/constants.ts +55 -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 +26 -0
- package/src/plugin.ts +140 -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/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,108 @@
|
|
|
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`.
|
|
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 })`.
|
|
19
9
|
|
|
20
|
-
|
|
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).
|
|
10
|
+
## Requisitos
|
|
26
11
|
|
|
27
|
-
|
|
28
|
-
|
|
12
|
+
- OpenCode **2.3.2+**
|
|
13
|
+
- Node.js **20+**
|
|
14
|
+
- Una cuenta de free-pi (GitHub) o un JWT de free-pi
|
|
29
15
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
OpenCode 2 usa la entrada `plugins` (plural) y carga el paquete desde su
|
|
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`.
|
|
77
|
-
|
|
78
|
-
## Instalación rápida con script
|
|
79
|
-
|
|
80
|
-
> Pasa el cursor por el bloque de comandos y usa el icono de copiar de GitHub.
|
|
81
|
-
> No necesitas definir variables de entorno para instalar.
|
|
82
|
-
|
|
83
|
-
### Windows (PowerShell + curl)
|
|
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
|
|
52
|
+
Métodos disponibles:
|
|
102
53
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
En Termux, si falta `curl`:
|
|
108
|
-
|
|
109
|
-
```bash
|
|
110
|
-
pkg install curl
|
|
111
|
-
```
|
|
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`.
|
|
112
58
|
|
|
113
|
-
|
|
59
|
+
El plugin también lee `~/.free-pi/agent/credentials.json`, el archivo que crea
|
|
60
|
+
`free-pi-cli`, como respaldo.
|
|
114
61
|
|
|
115
|
-
OpenCode
|
|
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.
|
|
142
76
|
- Compatible con rutas, credenciales y navegador de cada sistema operativo.
|
|
143
77
|
|
|
78
|
+
No incluye herramientas personalizadas. Usa las herramientas integradas de
|
|
79
|
+
OpenCode.
|
|
80
|
+
|
|
81
|
+
## Cabeceras enviadas
|
|
82
|
+
|
|
83
|
+
El plugin replica las cabeceras del plugin V1 de free-pi:
|
|
84
|
+
|
|
85
|
+
- **Modelo**: `authorization`, `x-session-id`, `x-client-version`,
|
|
86
|
+
`x-turn-id` y `x-freepi-cost-exp` (cuando el catálogo asigna un experimento).
|
|
87
|
+
- **Anuncios** (`/ads/next`): `authorization`, `x-session-id`,
|
|
88
|
+
`x-client-version`, `x-turn-id`, `x-ad-trigger`, `x-client-os`,
|
|
89
|
+
`x-client-arch`, `x-client-timezone`, `x-client-locale` y `x-ad-context`.
|
|
90
|
+
- **Impresión** (`/ads/impression`): `authorization`, `content-type` y
|
|
91
|
+
`x-session-id`.
|
|
92
|
+
- **Reset de sesión** (`/session/reset`): `authorization`,
|
|
93
|
+
`x-client-version` y, cuando aplica, `x-session-id`.
|
|
94
|
+
|
|
95
|
+
Las respuestas `429` de límites largos se reescriben a un `400` con el mensaje
|
|
96
|
+
amigable, igual que en el plugin V1.
|
|
97
|
+
|
|
144
98
|
## Rutas por plataforma
|
|
145
99
|
|
|
146
|
-
| Elemento | Windows | Linux / macOS / Termux
|
|
147
|
-
| --------------- | ------------------------------------------------------------ |
|
|
148
|
-
|
|
|
149
|
-
|
|
|
150
|
-
| Config OpenCode | `%USERPROFILE%\.config\opencode\opencode.json[c]` | `~/.config/opencode/opencode.json[c]` |
|
|
100
|
+
| Elemento | Windows | Linux / macOS / Termux |
|
|
101
|
+
| --------------- | ------------------------------------------------------------ | -------------------------------------- |
|
|
102
|
+
| Credenciales | `%USERPROFILE%\.free-pi\agent\credentials.json` | `~/.free-pi/agent/credentials.json` |
|
|
103
|
+
| Config OpenCode | `%USERPROFILE%\.config\opencode\opencode.json[c]` | `~/.config/opencode/opencode.json[c]` |
|
|
151
104
|
|
|
152
|
-
Si `XDG_CONFIG_HOME` o `OPENCODE_CONFIG_DIR` están definidos,
|
|
153
|
-
respeta.
|
|
105
|
+
Si `XDG_CONFIG_HOME` o `OPENCODE_CONFIG_DIR` están definidos, se respetan.
|
|
154
106
|
|
|
155
107
|
## Variables de entorno (opcionales)
|
|
156
108
|
|
|
@@ -162,44 +114,41 @@ respeta.
|
|
|
162
114
|
| `FREEPI_MODELS_URL` | Cambiar el registro de modelos. |
|
|
163
115
|
| `FREEPI_NO_BROWSER=1` | No abrir el navegador. |
|
|
164
116
|
| `FREEPI_DEVICE_LOGIN=1` | Forzar inicio de sesión por dispositivo. |
|
|
117
|
+
| `FREEPI_CONFIGURE=1` | Registrar el paquete en `opencode.json` al instalar. |
|
|
165
118
|
| `OPENCODE_CONFIG_DIR` | Directorio de configuración de OpenCode. |
|
|
166
119
|
|
|
167
|
-
No hay variables obligatorias.
|
|
168
|
-
para `HOME`, `USERPROFILE`, `XDG_CONFIG_HOME`, `APPDATA` cuando aplica, Termux y
|
|
169
|
-
Windows.
|
|
120
|
+
No hay variables obligatorias.
|
|
170
121
|
|
|
171
|
-
##
|
|
122
|
+
## Instalación rápida con script
|
|
172
123
|
|
|
173
|
-
|
|
124
|
+
### Windows (PowerShell)
|
|
174
125
|
|
|
175
|
-
```
|
|
176
|
-
|
|
177
|
-
npm install -g ./eduardo191labs-opencode-free-pi-*.tgz
|
|
126
|
+
```powershell
|
|
127
|
+
curl.exe -fsSL "https://raw.githubusercontent.com/eduardo191-star/opencode-free-pi/main/install.ps1" | powershell -NoProfile -ExecutionPolicy Bypass -Command -
|
|
178
128
|
```
|
|
179
129
|
|
|
180
|
-
|
|
130
|
+
Si tu terminal no acepta la tubería:
|
|
181
131
|
|
|
182
|
-
```
|
|
183
|
-
|
|
184
|
-
"plugin": ["@eduardo191labs/opencode-free-pi"]
|
|
185
|
-
}
|
|
132
|
+
```powershell
|
|
133
|
+
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"
|
|
186
134
|
```
|
|
187
135
|
|
|
188
|
-
|
|
189
|
-
siendo útil si prefieres copiar el archivo directamente a la carpeta de plugins.
|
|
136
|
+
### Linux, macOS y Termux
|
|
190
137
|
|
|
191
|
-
|
|
138
|
+
```bash
|
|
139
|
+
curl -fsSL "https://raw.githubusercontent.com/eduardo191-star/opencode-free-pi/main/install.sh" | bash
|
|
140
|
+
```
|
|
192
141
|
|
|
193
|
-
|
|
194
|
-
comprueba la última versión en npm, sube un patch si ya existe, publica el
|
|
195
|
-
paquete y crea el commit `chore(release): vX.Y.Z [skip ci]` con el tag
|
|
196
|
-
`vX.Y.Z`. El workflow también actualiza `dist/` en ese commit.
|
|
142
|
+
En Termux, si falta `curl`: `pkg install curl`.
|
|
197
143
|
|
|
198
|
-
|
|
199
|
-
publicar, ejecuta el workflow manualmente con `publish = false`.
|
|
144
|
+
## Paquete npm
|
|
200
145
|
|
|
201
|
-
|
|
202
|
-
|
|
146
|
+
El paquete incluye `dist/` compilado y tipos TypeScript:
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
npm pack
|
|
150
|
+
npm install -g ./eduardo191labs-opencode-free-pi-*.tgz
|
|
151
|
+
```
|
|
203
152
|
|
|
204
153
|
## Desarrollo
|
|
205
154
|
|
|
@@ -207,41 +156,53 @@ workflow.
|
|
|
207
156
|
npm install
|
|
208
157
|
npm run typecheck
|
|
209
158
|
npm run build
|
|
210
|
-
npm
|
|
159
|
+
npm test
|
|
211
160
|
```
|
|
212
161
|
|
|
213
162
|
Estructura:
|
|
214
163
|
|
|
215
164
|
```text
|
|
216
|
-
src/
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
165
|
+
src/
|
|
166
|
+
index.ts export público
|
|
167
|
+
plugin.ts entrada V2 (Plugin.define)
|
|
168
|
+
constants.ts identificadores y valores por defecto
|
|
169
|
+
types.ts tipos del dominio
|
|
170
|
+
state.ts estado mutable por instancia
|
|
171
|
+
deps.ts dependencias compartidas
|
|
172
|
+
logging.ts logger con prefijo [free-pi]
|
|
173
|
+
auth/ OAuth, JWT, credenciales y conexión
|
|
174
|
+
api/ cuota y reset de sesión
|
|
175
|
+
ads/ contexto, turnos e impresiones
|
|
176
|
+
catalog/ catálogo en vivo y registro models.dev
|
|
177
|
+
errors/ parseo, mensajes y reescritura de límites
|
|
178
|
+
integration/ integración y métodos de inicio de sesión
|
|
179
|
+
session/ hooks, eventos, seguimiento y uso
|
|
180
|
+
utils/ helpers pequeños
|
|
181
|
+
dist/ build ESM y tipos
|
|
182
|
+
scripts/postinstall.mjs registro en opencode.json
|
|
183
|
+
test/smoke.mjs prueba de humo del build
|
|
221
184
|
```
|
|
222
185
|
|
|
223
186
|
## Desinstalar
|
|
224
187
|
|
|
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:
|
|
188
|
+
1. Quita `@eduardo191labs/opencode-free-pi` de la lista `plugins` de tu
|
|
189
|
+
`opencode.json`.
|
|
190
|
+
2. Desinstala el paquete:
|
|
232
191
|
|
|
233
192
|
```bash
|
|
234
|
-
|
|
193
|
+
npm uninstall -g @eduardo191labs/opencode-free-pi
|
|
235
194
|
```
|
|
236
195
|
|
|
237
|
-
|
|
238
|
-
|
|
196
|
+
3. Si tenías una copia antigua, borra
|
|
197
|
+
`~/.config/opencode/plugins/opencode-free-pi.ts` (en Windows,
|
|
198
|
+
`%USERPROFILE%\.config\opencode\plugins\opencode-free-pi.ts`).
|
|
239
199
|
|
|
240
200
|
## Privacidad
|
|
241
201
|
|
|
242
202
|
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
|
|
203
|
+
anuncios y completions. El contexto de anuncios se redacta antes de enviarse y
|
|
204
|
+
no se incluye en la petición al modelo. No incluye claves ni tokens en el
|
|
205
|
+
repositorio.
|
|
245
206
|
|
|
246
207
|
## Licencia
|
|
247
208
|
|
|
@@ -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>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Resolves (or creates) the ad turn for a session request. */
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { adContextFor, latestAssistantText, latestUserMessageID, latestUserText, } from "./context.js";
|
|
4
|
+
import { adTurnKey, getAdTurn, rememberAdTurn } from "./turns.js";
|
|
5
|
+
/**
|
|
6
|
+
* Uses the request messages for primary requests and the stored session for
|
|
7
|
+
* auxiliary ones, where the request messages are synthetic (for example a
|
|
8
|
+
* title prompt).
|
|
9
|
+
*/
|
|
10
|
+
async function contextMessages(deps, request) {
|
|
11
|
+
const provided = request.messages ?? [];
|
|
12
|
+
if (request.kind !== "title" && provided.length > 0)
|
|
13
|
+
return provided;
|
|
14
|
+
const stored = await deps.readContext(request.sessionID).catch(() => []);
|
|
15
|
+
return stored.length > 0 ? stored : provided;
|
|
16
|
+
}
|
|
17
|
+
export async function resolveAdTurn(deps, request) {
|
|
18
|
+
const messages = await contextMessages(deps, request);
|
|
19
|
+
const messageID = latestUserMessageID(messages) ??
|
|
20
|
+
latestUserMessageID(request.messages ?? []);
|
|
21
|
+
const key = messageID
|
|
22
|
+
? adTurnKey(messageID, request.agent)
|
|
23
|
+
: `${request.sessionID}\u0000${request.agent ?? ""}`;
|
|
24
|
+
let turn = getAdTurn(deps, key);
|
|
25
|
+
if (!turn) {
|
|
26
|
+
turn = rememberAdTurn(deps, key, {
|
|
27
|
+
turnId: randomUUID(),
|
|
28
|
+
context: adContextFor(latestUserText(messages), latestAssistantText(messages)),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
else if (!turn.context) {
|
|
32
|
+
turn.context = adContextFor(latestUserText(messages), latestAssistantText(messages));
|
|
33
|
+
}
|
|
34
|
+
return turn;
|
|
35
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Per-turn ad bookkeeping keyed by user message and agent. */
|
|
2
|
+
import type { Deps } from "../deps.js";
|
|
3
|
+
import type { AdTurn } from "../types.js";
|
|
4
|
+
export declare function adTurnKey(messageId: string, agent: string | undefined): string;
|
|
5
|
+
export declare function rememberAdTurn(deps: Deps, key: string, turn: AdTurn): AdTurn;
|
|
6
|
+
export declare function getAdTurn(deps: Deps, key: string): AdTurn | undefined;
|