opencode-apex 0.1.0 → 0.2.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/index.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Modules:
5
5
  * - redact: Secret detection (regex), encryption-based redaction, restore on tool input
6
- * - events: RPC + plaintext-listener event ingestion, subscriptions, delivery
6
+ * - events: RPC event ingestion (callbacks/webhooks), subscriptions, delivery, tools.run
7
7
  * - advisor: allow/deny permission decisions via a dedicated agent + side session
8
8
  * - guard: meta-permissions per agent/tool/path (opt-in)
9
9
  * - browser: browser.* tools against an external Chromium over CDP (attach on request)
@@ -22,9 +22,11 @@ import { register as registerAdvisor, createDefaultAdvisorConfig, type AdvisorCo
22
22
  import { register as registerGuard, createDefaultGuardConfig, type GuardConfigShape } from "./guard.js"
23
23
  import { register as registerBrowser, createDefaultBrowserConfig, type BrowserConfigShape } from "./browser.js"
24
24
  import { registerCentralRpc } from "./core/rpc.js"
25
+ import { registerSkills } from "./core/skills.js"
26
+ import { compatibilityWarnings } from "./core/compat.js"
25
27
 
26
28
  // Plugin version
27
- const VERSION = "0.1.0"
29
+ const VERSION = "0.2.1"
28
30
 
29
31
  interface ModuleConfigs {
30
32
  redact: RedactConfig & { enabled: boolean }
@@ -61,8 +63,11 @@ export default Plugin.define({
61
63
  id: "apex",
62
64
  effect: (ctx) =>
63
65
  Effect.gen(function* () {
64
- // Track start time for uptime
65
- ;(globalThis as any).__apexStartTime = Date.now()
66
+ // Versiones desalineadas con OpenCode: avisar con la solución antes de fallar críptico.
67
+ for (const warning of compatibilityWarnings(ctx.app?.version)) {
68
+ console.warn(`[apex] ${warning}`)
69
+ yield* Effect.logWarning(`[apex] ${warning}`)
70
+ }
66
71
 
67
72
  // Configuración con JERARQUÍA y dos canales.
68
73
  // precedencia (menor → mayor): fichero global
@@ -116,9 +121,7 @@ export default Plugin.define({
116
121
  yield* registerRedact(ctx, moduleConfigs.redact)
117
122
  }
118
123
 
119
- if (moduleConfigs.events.enabled) {
120
- yield* registerEvents(ctx, validatedConfig)
121
- }
124
+ const events = moduleConfigs.events.enabled ? yield* registerEvents(ctx, validatedConfig) : null
122
125
 
123
126
  // ANTES del advisor, y el orden es funcional, no estético: el host recorre
124
127
  // los hooks de `permission.evaluate` en orden de registro sobre el mismo
@@ -138,7 +141,14 @@ export default Plugin.define({
138
141
  }
139
142
 
140
143
  // --- Central RPC registration (the "apex" namespace) ---
141
- yield* registerCentralRpc(ctx, moduleConfigs as unknown as Record<string, { enabled: boolean }>, VERSION)
144
+ yield* registerCentralRpc(ctx, {
145
+ version: VERSION,
146
+ modules: moduleConfigs as unknown as Record<string, { enabled: boolean }>,
147
+ events,
148
+ })
149
+
150
+ // --- Skills que viajan con el paquete (callbacks, webhooks, tools.run) ---
151
+ if (events) yield* registerSkills(ctx)
142
152
 
143
153
  }),
144
154
  })
@@ -97,22 +97,29 @@
97
97
  // --------------------------------------------------------------------------
98
98
  "events": {
99
99
  "routing": "all",
100
- // Listener HTTP plano: expone EL MISMO events.ingest para scripts sin
101
- // credenciales (curl desde otra máquina, hook de arranque, túnel…).
102
- // host: "127.0.0.1" (loopback) | "0.0.0.0" | una IP LAN. Fuera de loopback
103
- // define token (quien pueda llamarlo puede inyectar prompts al agente).
104
- "listener": {
105
- // Activo por defecto en loopback (el agente puede montar callbacks,
106
- // incluido un túnel, sin tocar la config). Ponlo a false para no abrir puerto.
107
- "enabled": true,
108
- "host": "127.0.0.1",
109
- "port": 4599,
110
- "token": "",
111
- // Fallback de URL pública. Normalmente NO hace falta: el agente fija la
112
- // URL del túnel en runtime con la tool apex_set_callback_url
113
- // (precedencia: runtime > esta config).
100
+ // Todo entra por el RPC del servidor (POST /api/rpc/apex/<método>, Basic auth).
101
+ // No hay listener propio: OpenCode descarga los plugins tras 60 min sin uso y
102
+ // el RPC levanta el directorio en la propia llamada. Webhooks → un relay (n8n,
103
+ // un daemon) que traduce la llamada HTTP a events.ingest (skill apex-callbacks).
104
+ "server": {
105
+ // URL base del servidor para scripts locales. Vacío = descubrirla (registro
106
+ // del servicio o --port de `opencode serve`). Fíjala detrás de un proxy.
107
+ "url": "",
108
+ // URL pública (túnel/proxy) para emisores de otras máquinas. El agente puede
109
+ // fijarla en runtime con apex_set_callback_url (precedencia: runtime > config).
114
110
  "publicUrl": ""
115
111
  },
112
+ // RPC apex/tools.run: un proceso externo ejecuta una herramienta de OpenCode
113
+ // (nativa, de plugin o MCP) sin modelo. Gana deny; luego deciden los permisos
114
+ // del agente `agent` (o el que pase la llamada). Sin nadie delante, un "ask"
115
+ // espera al advisor o hasta timeoutMs.
116
+ "tools": {
117
+ "enabled": true,
118
+ "allow": ["*"],
119
+ "deny": ["question", "subagent", "execute", "apex_*"],
120
+ "agent": "build",
121
+ "timeoutMs": 120000
122
+ },
116
123
  "subscriptions": [
117
124
  {
118
125
  "sessionID": "",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-apex",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Modular monolithic plugin for OpenCode V2 — redaction, events, advisor permissions, guard meta-permissions, external browser over CDP",
5
5
  "type": "module",
6
6
  "main": "index.ts",
@@ -17,12 +17,13 @@
17
17
  "browser",
18
18
  "core",
19
19
  "docs",
20
- "opencode-apex.jsonc"
20
+ "opencode-apex.jsonc",
21
+ "skills",
22
+ "CHANGELOG.md"
21
23
  ],
22
24
  "dependencies": {
23
- "@opencode/plugin": "latest",
24
- "@opencode/plugin-browser": "^2.0.21",
25
- "effect": "4.0.0-rc.112",
25
+ "@opencode/plugin": "^2.1.1",
26
+ "@opencode/plugin-browser": "^2.1.1",
26
27
  "jsonc-parser": "^3.3.1",
27
28
  "ws": "^8.22.0",
28
29
  "zod": "^3.24.0"
@@ -30,5 +31,19 @@
30
31
  "devDependencies": {
31
32
  "typescript": "^5.5.0",
32
33
  "bun-types": "^1.1.0"
34
+ },
35
+ "scripts": {
36
+ "test": "bun test/events.test.ts && bun test/guard.test.ts",
37
+ "typecheck": "tsc --noEmit -p .",
38
+ "check:install": "node scripts/check-install.mjs",
39
+ "prepublishOnly": "npm test && npm run typecheck && npm run check:install"
40
+ },
41
+ "peerDependencies": {
42
+ "effect": "^4.0.0"
43
+ },
44
+ "peerDependenciesMeta": {
45
+ "effect": {
46
+ "optional": true
47
+ }
33
48
  }
34
49
  }
@@ -0,0 +1,239 @@
1
+ ---
2
+ name: apex-callbacks
3
+ description: Automatizaciones que despiertan a un agente desde fuera de la conversación con opencode-apex. Úsala cuando te pidan vigilar algo periódicamente ("comprueba cada 5 minutos si X funciona y si cae diagnostica"), avisar al terminar un job o tras un reinicio, recibir webhooks de servicios externos (GitHub, n8n, Stripe…) o usar herramientas de OpenCode (MCP, navegador) desde un script. Cubre descubrir la URL del servidor, suscribirse, el script vigilante, programarlo con systemd/cron, el relay de webhooks y el RPC tools.run.
4
+ ---
5
+
6
+ # Automatizaciones con apex: callbacks, webhooks y vigilancias
7
+
8
+ ## La idea en una frase
9
+
10
+ El **reloj** (cron/systemd) y la **puerta** (relay de webhooks) viven FUERA de OpenCode;
11
+ OpenCode solo trabaja cuando le llaman por **RPC**. Cuando algo merece atención, el
12
+ proceso externo llama a `events.ingest` y una **suscripción** despierta al agente con
13
+ el encargo.
14
+
15
+ ```
16
+ proceso externo ──(tools.run: usa herramientas de OpenCode, opcional)──▶ OpenCode
17
+ │
18
+ └─ ¿criterio cumplido? ──(events.ingest)──▶ suscripción ──▶ el agente despierta
19
+ ```
20
+
21
+ **Nunca** dejes la vigilancia dentro de OpenCode (un `sleep` en bucle en el shell, un
22
+ temporizador en un plugin): OpenCode descarga los plugins de un directorio tras **60
23
+ minutos sin actividad** y no los recarga tras un reinicio hasta que alguien usa ese
24
+ directorio. El RPC, en cambio, levanta el directorio en la propia llamada (unos
25
+ segundos la primera vez).
26
+
27
+ ## Paso 0 — ¿A dónde apunto? (pregúntalo, no lo adivines)
28
+
29
+ Llama a la tool **`apex_callback_endpoint`**. Devuelve:
30
+
31
+ | Campo | Qué es |
32
+ | --- | --- |
33
+ | `baseUrl` | URL del servidor de OpenCode desde esta máquina (`null` → pide al usuario `events.server.url`) |
34
+ | `rpc.ingest` / `rpc.toolsRun` | URLs completas de los métodos, ya con `location[directory]` de este proyecto |
35
+ | `auth.username` | siempre `opencode` (HTTP Basic) |
36
+ | `auth.password` | DÓNDE está el password: `{kind:"file", file, field}` (registro 0600 del servicio) o `{kind:"env", env}`; `shell` lo imprime en una terminal |
37
+ | `publicUrl` | URL para emisores de **otras** máquinas (túnel/proxy), si existe |
38
+ | `examples` | curl listos para copiar |
39
+
40
+ Reglas:
41
+ - **El password no se escribe nunca** en scripts, unidades systemd, crontab ni en la
42
+ conversación: los scripts lo leen al ejecutarse de `auth.password.file` (función
43
+ `pw` de abajo) o de la variable `auth.password.env`.
44
+ - Usa las URLs `rpc.*` tal cual: el `location[directory]` dirige la llamada a ESTE
45
+ proyecto (sus suscripciones, sus herramientas MCP).
46
+ - Otra máquina no alcanza `127.0.0.1`: necesita un túnel o proxy hacia `baseUrl`;
47
+ anúncialo con `apex_set_callback_url({url})` y límpialo con `{url: null}` al acabar.
48
+
49
+ ## Paso 1 — Suscribirse (quién despierta y con qué encargo)
50
+
51
+ Con la tool **`apex_subscribe`** (queda ligada a la sesión que la llama):
52
+
53
+ ```jsonc
54
+ {
55
+ "filters": [{ "field": "type", "operator": "equals", "value": "server.down" }],
56
+ "agent": "build", // agente que debe despertar (opcional)
57
+ "promptTemplate": "El servidor {{payload.host}} está caído ({{payload.detail}}). Diagnostica la causa y propón el arreglo.",
58
+ "deliverAs": "prompt", // prompt = turno nuevo del agente
59
+ "delivery": "queue"
60
+ }
61
+ ```
62
+
63
+ - Filtra por `type` (y por `source` si hay varios emisores): un evento sin filtro
64
+ despertaría a todas las suscripciones.
65
+ - El encargo va en la plantilla: es el prompt que recibirá el agente.
66
+ - `deliverAs: "synthetic"` + `resume: true` también despierta; con `resume: false` el
67
+ mensaje queda pasivo hasta el siguiente turno.
68
+
69
+ ## Paso 2 — El script vigilante
70
+
71
+ Requisitos de un buen vigilante:
72
+ 1. **Solo avisa en los cambios de estado** (OK → caído, y opcionalmente caído → OK),
73
+ no en cada comprobación: guarda el último estado en un fichero.
74
+ 2. **`eventID` estable por incidente** (p. ej. `server.down-<host>-<timestamp de caída>`):
75
+ reenviarlo no duplica la entrega.
76
+ 3. Distingue "el servicio está caído" de "no pude comprobarlo" (timeout de red, MCP
77
+ que falla): son eventos distintos.
78
+ 4. Reintenta la llamada a OpenCode con backoff: tras un reinicio tarda unos segundos.
79
+
80
+ ```sh
81
+ #!/bin/sh
82
+ # watch-http.sh — avisa a apex cuando una URL pasa de OK a caída (y al recuperarse).
83
+ TARGET="https://mi-servidor.example.com/health"
84
+ INGEST='<rpc.ingest de apex_callback_endpoint>'
85
+ PASSWORD_FILE='<auth.password.file de apex_callback_endpoint>'
86
+ # El password se lee en cada ejecución (si auth.password.kind es "env": printf %s "$OPENCODE_SERVER_PASSWORD").
87
+ pw() { sed -n 's/.*"password" *: *"\([^"]*\)".*/\1/p' "$PASSWORD_FILE"; }
88
+ STATE="$HOME/.local/state/apex-watch/$(printf %s "$TARGET" | md5sum | cut -c1-12)"
89
+ mkdir -p "$(dirname "$STATE")"
90
+
91
+ code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 "$TARGET")
92
+ case "$code" in 2??|3??) now=up ;; *) now=down ;; esac
93
+ before=$(cat "$STATE" 2>/dev/null || echo up)
94
+ [ "$now" = "$before" ] && exit 0 # sin cambio: no se molesta a nadie
95
+ echo "$now" > "$STATE"
96
+
97
+ type="server.$now"; since=$(date +%s)
98
+ body=$(printf '{"input":{"source":"watch-http","type":"%s","eventID":"%s-%s","payload":{"host":"%s","detail":"HTTP %s"}}}' \
99
+ "$type" "$type" "$since" "$TARGET" "$code")
100
+ for i in 1 2 3 4 5; do
101
+ curl -sS --fail --max-time 30 -X POST "$INGEST" -u "opencode:$(pw)" \
102
+ -H 'content-type: application/json' -d "$body" && exit 0
103
+ sleep $((i * 10))
104
+ done
105
+ exit 1
106
+ ```
107
+
108
+ ### Si la comprobación necesita una herramienta de OpenCode → `tools.run`
109
+
110
+ Cuando lo que hay que consultar solo existe dentro de OpenCode (un MCP como Easypanel,
111
+ el navegador, `webfetch`…), el script la ejecuta por RPC, sin modelo:
112
+
113
+ ```sh
114
+ TOOLS_RUN='<rpc.toolsRun de apex_callback_endpoint>'
115
+ out=$(curl -sS --max-time 150 -X POST "$TOOLS_RUN" -u "opencode:$(pw)" \
116
+ -H 'content-type: application/json' \
117
+ -d '{"input":{"tool":"<id exacto de la herramienta>","input":{ ... }}}')
118
+ echo "$out" | jq -e '.output.ok' >/dev/null || { echo "no pude comprobar: $(echo "$out" | jq -r '.output.error // .')"; exit 2; }
119
+ echo "$out" | jq -r '.output.content'
120
+ ```
121
+
122
+ - `tool` es el id exacto de la herramienta tal como la ves tú (las MCP suelen ser
123
+ `<servidor>_<tool>`). Pruébala antes a mano y copia su input.
124
+ - Respuesta: `{"output":{"ok","tool","agent","output?","content?","metadata?","error?","durationMs"}}`.
125
+ - Se aplican los **permisos** del agente `events.tools.agent` (por defecto `build`) o el
126
+ `agent` que pases en la llamada. Sin nadie delante, un permiso "ask" espera al advisor
127
+ o hasta `timeoutMs` (120 s por defecto): pide al usuario una regla `allow` si hace falta.
128
+ - `events.tools.allow` / `deny` limitan qué herramientas se pueden lanzar así
129
+ (`question`, `subagent`, `execute` y las `apex_*` están denegadas por defecto).
130
+
131
+ ## Paso 3 — Programarlo (el reloj)
132
+
133
+ Preferido: **temporizador systemd de usuario** (sobrevive a reinicios, guarda logs):
134
+
135
+ ```sh
136
+ mkdir -p ~/.config/systemd/user ~/.local/bin
137
+ install -m 0755 watch-http.sh ~/.local/bin/apex-watch-mi-servidor.sh
138
+ cat > ~/.config/systemd/user/apex-watch-mi-servidor.service <<'EOF'
139
+ [Unit]
140
+ Description=apex watch: mi-servidor
141
+ [Service]
142
+ Type=oneshot
143
+ ExecStart=%h/.local/bin/apex-watch-mi-servidor.sh
144
+ EOF
145
+ cat > ~/.config/systemd/user/apex-watch-mi-servidor.timer <<'EOF'
146
+ [Unit]
147
+ Description=apex watch: mi-servidor cada 5 min
148
+ [Timer]
149
+ OnBootSec=2min
150
+ OnUnitActiveSec=5min
151
+ [Install]
152
+ WantedBy=timers.target
153
+ EOF
154
+ systemctl --user daemon-reload && systemctl --user enable --now apex-watch-mi-servidor.timer
155
+ systemctl --user list-timers | grep apex-watch # comprobar
156
+ journalctl --user -u apex-watch-mi-servidor -n 20 # logs
157
+ ```
158
+
159
+ Alternativa: `crontab -e` → `*/5 * * * * ~/.local/bin/apex-watch-mi-servidor.sh`.
160
+
161
+ Antes de dar por terminado el encargo: **ejecuta el script una vez a mano** y, si
162
+ puedes, provoca el evento (o envía un `events.ingest` de prueba) para ver que la
163
+ suscripción despierta al agente. Dile al usuario qué instalaste y cómo quitarlo:
164
+
165
+ ```sh
166
+ systemctl --user disable --now apex-watch-mi-servidor.timer
167
+ rm ~/.config/systemd/user/apex-watch-mi-servidor.{service,timer} ~/.local/bin/apex-watch-mi-servidor.sh
168
+ ```
169
+ …y `apex_unsubscribe({id})` para la suscripción.
170
+
171
+ ## Webhooks (servicios externos que llaman por HTTP)
172
+
173
+ Un webhook es un callback con un **proceso intermedio** que traduce la llamada HTTP del
174
+ servicio a `events.ingest`. OpenCode no expone una URL de webhook propia.
175
+
176
+ - **n8n**: nodo *Webhook* → nodo *HTTP Request* `POST <rpc.ingest>`, auth Basic
177
+ (credencial `opencode` + password), body
178
+ `{"input":{"source":"github","type":"{{$json.headers['x-github-event']}}","eventID":"{{$json.headers['x-github-delivery']}}","payload":{{JSON.stringify($json.body)}}}}`.
179
+ Si n8n corre en otra máquina necesita alcanzar el servidor (túnel/proxy, `publicUrl`).
180
+ - **Relay mínimo** (Node ≥ 18, sin dependencias) en la máquina de OpenCode, como servicio
181
+ systemd de usuario. Valida un token propio antes de reenviar nada:
182
+
183
+ ```js
184
+ // webhook-relay.mjs — POST http://<host>:<port>/<type>?token=<RELAY_TOKEN> → apex events.ingest
185
+ import { createServer } from "node:http"
186
+ import { readFileSync } from "node:fs"
187
+ const { INGEST, PASSWORD_FILE, RELAY_TOKEN, PORT = "8787", HOST = "127.0.0.1", SOURCE = "webhook" } = process.env
188
+ if (!INGEST || !RELAY_TOKEN) throw new Error("faltan INGEST o RELAY_TOKEN")
189
+ // Se lee en cada petición: sobrevive a reinicios del servicio sin reiniciar el relay.
190
+ const password = () =>
191
+ PASSWORD_FILE ? JSON.parse(readFileSync(PASSWORD_FILE, "utf8")).password : process.env.OPENCODE_SERVER_PASSWORD
192
+ createServer(async (req, res) => {
193
+ const url = new URL(req.url, "http://relay")
194
+ if (req.method !== "POST" || url.searchParams.get("token") !== RELAY_TOKEN) return res.writeHead(401).end()
195
+ let raw = ""
196
+ for await (const chunk of req) if ((raw += chunk).length > 1_000_000) return res.writeHead(413).end()
197
+ let body; try { body = JSON.parse(raw || "{}") } catch { body = { raw } }
198
+ const h = req.headers
199
+ const input = {
200
+ source: SOURCE,
201
+ type: url.pathname.slice(1) || String(h["x-github-event"] ?? h["x-event-type"] ?? "webhook"),
202
+ eventID: String(h["x-github-delivery"] ?? h["idempotency-key"] ?? h["x-request-id"] ?? "") || undefined,
203
+ payload: { body, headers: { "content-type": h["content-type"], "user-agent": h["user-agent"] } },
204
+ }
205
+ try {
206
+ const auth = "Basic " + Buffer.from(`opencode:${password()}`).toString("base64")
207
+ const r = await fetch(INGEST, { method: "POST", headers: { authorization: auth, "content-type": "application/json" }, body: JSON.stringify({ input }) })
208
+ res.writeHead(r.ok ? 202 : 502, { "content-type": "application/json" }).end(await r.text())
209
+ } catch (error) {
210
+ res.writeHead(502).end(String(error)) // OpenCode parado: el emisor reintentará
211
+ }
212
+ }).listen(Number(PORT), HOST)
213
+ ```
214
+
215
+ Configúralo con `INGEST` y `PASSWORD_FILE` (de `apex_callback_endpoint`; si
216
+ `auth.password.kind` es `env`, exporta `OPENCODE_SERVER_PASSWORD` en su lugar) y un
217
+ `RELAY_TOKEN` aleatorio (`openssl rand -hex 24`). Para recibir desde Internet,
218
+ expón **el relay** (no el servidor de OpenCode) con un túnel.
219
+
220
+ ## Seguridad
221
+
222
+ - Quien pueda llamar a `events.ingest` dirige al agente, y `tools.run` ejecuta
223
+ herramientas: ambos exigen el password del servidor. Trátalo como una credencial.
224
+ - Ficheros con secretos: `0600`. Un relay o túnel expuesto a Internet lleva su propio
225
+ token y nunca reenvía sin validarlo.
226
+ - No amplíes permisos para que un vigilante funcione sin decírselo al usuario.
227
+
228
+ ## Contrato
229
+
230
+ | Método RPC | Entrada | Salida |
231
+ | --- | --- | --- |
232
+ | `events.ingest` | `{source, type?, payload, eventID?}` | `{accepted, eventID, delivered[]}` |
233
+ | `tools.run` | `{tool, input?, agent?, timeoutMs?}` | `{ok, tool, agent, output?, content?, metadata?, error?, durationMs}` |
234
+ | `server.info` | `{}` | lo mismo que `apex_callback_endpoint` |
235
+ | `status` / `ping` | `{}` | estado del plugin / `{pong, timestamp}` |
236
+
237
+ Todas: `POST <baseUrl>/api/rpc/apex/<método>?location[directory]=<proyecto>`, cuerpo
238
+ `{"input":{…}}`, respuesta `{"output":{…}}`, Basic `opencode:<password>`.
239
+ `delivered: []` significa que ninguna suscripción casó (revisa filtros y sesión).
@@ -1,193 +0,0 @@
1
- /**
2
- * Apex Events — listener HTTP plano para disparar la ingesta de eventos.
3
- *
4
- * Expone EL MISMO `events.ingest` (mismo handler, mismo contrato de payload),
5
- * pensado para scripts que no pueden custodiar credenciales del servidor:
6
- * un `curl` desde otra máquina, un hook de arranque, un túnel, etc.
7
- *
8
- * Seguridad:
9
- * - `host` configurable (por defecto loopback). Bind a una interfaz LAN solo
10
- * si confías en la red; bind a 0.0.0.0 sin token es peligroso (cualquiera
11
- * podría inyectar prompts al agente).
12
- * - `token` opcional: si está definido se exige (header `x-apex-token` o
13
- * segmento de path `/ingest/<token>`).
14
- * - Límite de cuerpo (64 KB por defecto) y JSON estricto.
15
- */
16
-
17
- import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
18
- import { timingSafeEqual } from "node:crypto"
19
- import { networkInterfaces } from "node:os"
20
-
21
- export interface IngestListenerOptions {
22
- /** Interfaz de escucha (p. ej. "127.0.0.1" o "0.0.0.0" o una IP LAN). */
23
- readonly host: string
24
- /** Puerto de escucha. */
25
- readonly port: number
26
- /** Token opcional (si se define, es obligatorio en cada petición). */
27
- readonly token?: string
28
- /** Handler de ingesta: el mismo que usa `apex.events.ingest`. */
29
- readonly ingest: (input: unknown) => Promise<unknown>
30
- /** Límite de cuerpo en bytes (default 64 KB). */
31
- readonly maxBodyBytes?: number
32
- }
33
-
34
- export interface IngestListener {
35
- readonly host: string
36
- readonly port: number
37
- readonly close: () => Promise<void>
38
- }
39
-
40
- /**
41
- * URLs por las que se puede alcanzar el listener.
42
- * - host concreto (loopback o IP LAN) → solo esa
43
- * - `0.0.0.0`/`::` → loopback + todas las IPv4 no internas de la máquina
44
- */
45
- export function listenerUrls(host: string, port: number, token?: string): string[] {
46
- const suffix = token && token.length > 0 ? `/${token}` : ""
47
- const path = `/ingest${suffix}`
48
- const wildcard = host === "0.0.0.0" || host === "::" || host === "[::]"
49
-
50
- if (!wildcard) return [`http://${host}:${port}${path}`]
51
-
52
- const urls = [`http://127.0.0.1:${port}${path}`]
53
- for (const entries of Object.values(networkInterfaces())) {
54
- for (const entry of entries ?? []) {
55
- if (entry.family === "IPv4" && !entry.internal) urls.push(`http://${entry.address}:${port}${path}`)
56
- }
57
- }
58
- return urls
59
- }
60
-
61
- const DEFAULT_MAX_BODY = 64 * 1024
62
-
63
- /** Comparación de tokens en tiempo constante. */
64
- function tokenMatches(expected: string, received: string): boolean {
65
- const a = Buffer.from(expected)
66
- const b = Buffer.from(received)
67
- if (a.length !== b.length) return false
68
- return timingSafeEqual(a, b)
69
- }
70
-
71
- function json(res: ServerResponse, status: number, payload: unknown): void {
72
- const body = JSON.stringify(payload)
73
- res.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(body) })
74
- res.end(body)
75
- }
76
-
77
- function readBody(req: IncomingMessage, limit: number): Promise<string> {
78
- return new Promise((resolve, reject) => {
79
- let size = 0
80
- const chunks: Buffer[] = []
81
- req.on("data", (chunk: Buffer) => {
82
- size += chunk.length
83
- if (size > limit) {
84
- // No destruimos el socket: drenamos para poder responder 413 y cerrar limpio.
85
- reject(new Error("payload too large"))
86
- req.resume()
87
- return
88
- }
89
- chunks.push(chunk)
90
- })
91
- req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")))
92
- req.on("error", reject)
93
- })
94
- }
95
-
96
- /**
97
- * Arranca el listener. Lanza si el puerto no se puede abrir (el llamador decide
98
- * si eso desactiva el listener sin romper el módulo).
99
- */
100
- export async function startIngestListener(options: IngestListenerOptions): Promise<IngestListener> {
101
- const maxBody = options.maxBodyBytes ?? DEFAULT_MAX_BODY
102
- const token = options.token && options.token.length > 0 ? options.token : undefined
103
- const loopback = options.host === "127.0.0.1" || options.host === "localhost" || options.host === "::1"
104
-
105
- if (!loopback && !token) {
106
- console.warn(
107
- `[Apex Events] listener de ingesta en ${options.host} SIN token: cualquiera con acceso a esa ` +
108
- `interfaz puede inyectar prompts al agente. Define events.listener.token o usa 127.0.0.1.`,
109
- )
110
- }
111
-
112
- const server = createServer((req, res) => {
113
- void handle(req, res)
114
- })
115
-
116
- async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
117
- try {
118
- const url = new URL(req.url ?? "/", `http://${options.host}`)
119
- const segments = url.pathname.split("/").filter((s) => s.length > 0)
120
-
121
- // GET /health → comprobación para túneles/monitorización
122
- if (req.method === "GET" && (url.pathname === "/health" || url.pathname === "/")) {
123
- json(res, 200, { ok: true, listener: "apex.events.ingest", host: options.host, port: options.port })
124
- return
125
- }
126
-
127
- // POST /ingest · POST /ingest/<token>
128
- if (segments[0] !== "ingest") {
129
- json(res, 404, { error: "not_found", hint: "usa POST /ingest" })
130
- return
131
- }
132
- if (req.method !== "POST") {
133
- json(res, 405, { error: "method_not_allowed", hint: "usa POST" })
134
- return
135
- }
136
-
137
- if (token) {
138
- const fromPath = segments[1]
139
- const fromHeader = req.headers["x-apex-token"]
140
- const provided = fromPath ?? (typeof fromHeader === "string" ? fromHeader : undefined)
141
- if (!provided || !tokenMatches(token, provided)) {
142
- json(res, 401, { error: "unauthorized" })
143
- return
144
- }
145
- }
146
-
147
- const raw = await readBody(req, maxBody)
148
- let parsed: unknown
149
- try {
150
- parsed = raw.length > 0 ? JSON.parse(raw) : {}
151
- } catch {
152
- json(res, 400, { error: "invalid_json" })
153
- return
154
- }
155
-
156
- // Acepta el payload directo o el envoltorio del RPC ({ input: … })
157
- const input =
158
- parsed && typeof parsed === "object" && "input" in (parsed as Record<string, unknown>)
159
- ? (parsed as Record<string, unknown>).input
160
- : parsed
161
-
162
- const output = await options.ingest(input)
163
- json(res, 200, output ?? { accepted: false })
164
- } catch (error) {
165
- const message = error instanceof Error ? error.message : String(error)
166
- if (message === "payload too large") {
167
- json(res, 413, { error: "payload_too_large", maxBytes: maxBody })
168
- return
169
- }
170
- json(res, 500, { error: "ingest_failed", message })
171
- }
172
- }
173
-
174
- await new Promise<void>((resolve, reject) => {
175
- server.once("error", reject)
176
- server.listen(options.port, options.host, () => {
177
- server.removeListener("error", reject)
178
- resolve()
179
- })
180
- })
181
-
182
- const address = server.address()
183
- const boundPort = typeof address === "object" && address !== null ? address.port : options.port
184
-
185
- return {
186
- host: options.host,
187
- port: boundPort,
188
- close: () =>
189
- new Promise<void>((resolve) => {
190
- server.close(() => resolve())
191
- }),
192
- }
193
- }