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/CHANGELOG.md +70 -0
- package/README.md +46 -15
- package/core/compat.ts +102 -0
- package/core/config.ts +56 -22
- package/core/rpc.ts +105 -92
- package/core/server-endpoint.ts +172 -0
- package/core/skills.ts +63 -0
- package/core/tools-run.ts +167 -0
- package/docs/EVENTS.md +77 -34
- package/docs/TROUBLESHOOTING.md +30 -1
- package/events.ts +194 -230
- package/index.ts +18 -8
- package/opencode-apex.jsonc +21 -14
- package/package.json +20 -5
- package/skills/apex-callbacks/SKILL.md +239 -0
- package/core/ingest-listener.ts +0 -193
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [0.2.1] — 2026-10-23
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- El aviso de versiones desalineadas recomendaba `opencode plugin update`, que en OpenCode
|
|
8
|
+
2.1 solo gestiona plugins de TUI (`Plugin is not configured` para los de servidor). Ahora
|
|
9
|
+
indica el procedimiento que funciona: con OpenCode parado, borrar
|
|
10
|
+
`~/.cache/opencode/npm/opencode-apex@*` y arrancarlo.
|
|
11
|
+
|
|
12
|
+
## [0.2.0] — 2026-10-23
|
|
13
|
+
|
|
14
|
+
Automatizaciones que sobreviven a la descarga de plugins de OpenCode V2: todo entra por
|
|
15
|
+
el RPC del servidor.
|
|
16
|
+
|
|
17
|
+
### Breaking
|
|
18
|
+
|
|
19
|
+
- **Listener HTTP plano eliminado** (`events.listener`, puerto 4599). OpenCode descarga
|
|
20
|
+
los plugins de un directorio tras 60 min sin actividad de sesiones, y el listener se
|
|
21
|
+
cerraba con el plugin. La clave se ignora con un aviso. Los callbacks entran por
|
|
22
|
+
`apex/events.ingest`, y los webhooks por un relay (n8n o un daemon) que llama a ese RPC.
|
|
23
|
+
- `apex_set_callback_url` fija ahora la URL **pública del servidor**, para emisores de
|
|
24
|
+
otras máquinas (túnel o proxy hacia la URL base). Antes fijaba la URL del listener.
|
|
25
|
+
- `apex.status` devuelve `endpoint` en lugar de `callback`.
|
|
26
|
+
|
|
27
|
+
### Fixed
|
|
28
|
+
|
|
29
|
+
- **El RPC `apex` no se registraba en OpenCode ≥ 2.1.** La definición usaba `name`, y V2
|
|
30
|
+
indexa por `id`, así que todas las llamadas devolvían `rpc.unavailable`.
|
|
31
|
+
- **Estado compartido entre directorios.** El módulo se importa una vez por proceso, y
|
|
32
|
+
la sesión principal, el handler de ingest y la deduplicación eran variables de
|
|
33
|
+
módulo: un directorio podía entregar eventos en la sesión de otro, y descargar uno
|
|
34
|
+
rompía el ingest de los demás. Ahora el estado es por directorio.
|
|
35
|
+
- **Sesión principal ajena.** El bus de eventos de OpenCode es global, así que cada
|
|
36
|
+
instancia de apex se vinculaba también a las sesiones nuevas de OTROS directorios.
|
|
37
|
+
Ahora se ignoran los eventos de otro directorio.
|
|
38
|
+
- **No cargaba con OpenCode 2.1**: se fijaba `effect` 4.0.0-rc.112, mientras
|
|
39
|
+
`@opencode/plugin` 2.1 usa 4.0.1 (`Schema.isStartsWith is not a function`).
|
|
40
|
+
|
|
41
|
+
### Added
|
|
42
|
+
|
|
43
|
+
- **RPC `apex/tools.run`.** Un proceso externo ejecuta una herramienta de OpenCode
|
|
44
|
+
(nativa, de plugin o MCP) sin modelo.
|
|
45
|
+
- Configuración `events.tools`: `allow`, `deny`, `agent` cuyos permisos se aplican y
|
|
46
|
+
`timeoutMs`.
|
|
47
|
+
- Se ejecuta en una sesión runner oculta por directorio, con el agente `apex-runner`.
|
|
48
|
+
- **Descubrimiento del servidor:** la tool `apex_callback_endpoint` y el RPC `server.info`.
|
|
49
|
+
- Devuelven la URL base, las URLs RPC del directorio, la auth Basic y de dónde leer
|
|
50
|
+
el password (nunca el password), y ejemplos curl.
|
|
51
|
+
- La URL base sale de `events.server.url` > el registro del servicio (por pid) >
|
|
52
|
+
`opencode serve --port`.
|
|
53
|
+
- **La skill `apex-callbacks` viaja con el paquete** y se registra sola. Cubre:
|
|
54
|
+
- vigilantes con estado;
|
|
55
|
+
- systemd/cron;
|
|
56
|
+
- relay de webhooks y n8n;
|
|
57
|
+
- `tools.run`.
|
|
58
|
+
- **Compatibilidad sostenida con OpenCode.**
|
|
59
|
+
- `effect` deja de ser dependencia propia: pasa a peer opcional y usa la copia de
|
|
60
|
+
`@opencode/plugin`.
|
|
61
|
+
- `@opencode/plugin` y `@opencode/plugin-browser` pasan a `^2.1.1`.
|
|
62
|
+
- Aviso al cargar (`core/compat.ts`) si hay dos copias de effect o si OpenCode es más
|
|
63
|
+
nuevo que el `@opencode/plugin` instalado.
|
|
64
|
+
- `prepublishOnly` instala el paquete como OpenCode y falla si las dependencias se
|
|
65
|
+
desalinean (ver docs/TROUBLESHOOTING.md).
|
|
66
|
+
- Tests `test/events.test.ts` y scripts `npm test`, `npm run typecheck` y `npm run check:install`.
|
|
67
|
+
|
|
68
|
+
## [0.1.0]
|
|
69
|
+
|
|
70
|
+
Primera versión publicada.
|
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ API **Effect-native** (`Plugin.define({ id, effect })` de `@opencode/plugin/effe
|
|
|
11
11
|
| Módulo | Qué hace | Doc |
|
|
12
12
|
| ----------- | ----------------------------------------------------------------------------------------- | ------------------------- |
|
|
13
13
|
| **Redact** | Detecta secretos por regex, los cifra (AES-256-GCM) y los sustituye por un marcador legible. Restaura en el input de las tools | [docs/REDACT.md](docs/REDACT.md) |
|
|
14
|
-
| **Events** |
|
|
14
|
+
| **Events** | Callbacks, webhooks y vigilancias: ingesta de eventos por RPC, filtros por suscripción y entrega como prompt o mensaje sintético; `tools.run` para que un proceso externo use herramientas de OpenCode | [docs/EVENTS.md](docs/EVENTS.md) |
|
|
15
15
|
| **Advisor** | Decide `allow`/`deny` sobre el uso de herramientas usando un agente y una sesión laterales | [docs/ADVISOR.md](docs/ADVISOR.md) |
|
|
16
16
|
| **Guard** | Meta-permisos por agente, herramienta y ruta, con informe. El `deny` que la config no puede declarar sin romper el toolset | [docs/GUARD.md](docs/GUARD.md) |
|
|
17
17
|
| **Browser** | Sirve las tools `browser.*` contra un Chromium **externo** por CDP, local o remoto. Elige entre navegador externo y el de la app de escritorio | [docs/BROWSER.md](docs/BROWSER.md) |
|
|
@@ -24,11 +24,19 @@ Activación por módulo en `modules` (fuente única, no existe `<modulo>.enabled
|
|
|
24
24
|
|
|
25
25
|
## Instalación
|
|
26
26
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
Desde npm, en `opencode.json` (OpenCode instala el paquete y sus dependencias):
|
|
28
|
+
|
|
29
|
+
```jsonc
|
|
30
|
+
"plugins": [{ "package": "opencode-apex", "options": { "modules": { "events": true } } }]
|
|
30
31
|
```
|
|
31
32
|
|
|
33
|
+
En desarrollo, apunta por ruta de directorio (`"package": "/ruta/a/opencode-apex"`) y `bun install` en él.
|
|
34
|
+
|
|
35
|
+
Requiere OpenCode **≥ 2.1**. La caché npm de plugins no se refresca sola: para actualizar apex
|
|
36
|
+
(o tras actualizar OpenCode), con OpenCode parado borra `~/.cache/opencode/npm/opencode-apex@*` y
|
|
37
|
+
arráncalo. En 2.1, `opencode plugin update` solo gestiona plugins de TUI. apex avisa al cargar si
|
|
38
|
+
quedó desalineado.
|
|
39
|
+
|
|
32
40
|
## Configuración
|
|
33
41
|
|
|
34
42
|
Dos canales y jerarquía (ver [docs/CONFIG.md](docs/CONFIG.md)):
|
|
@@ -65,15 +73,25 @@ Dos canales y jerarquía (ver [docs/CONFIG.md](docs/CONFIG.md)):
|
|
|
65
73
|
}
|
|
66
74
|
```
|
|
67
75
|
|
|
68
|
-
## Callbacks (
|
|
76
|
+
## Callbacks, webhooks y vigilancias (despertar al agente desde fuera)
|
|
77
|
+
|
|
78
|
+
Patrón: el agente se **suscribe** → un proceso externo llama a **`apex/events.ingest`**
|
|
79
|
+
por el RPC del servidor → el agente recibe un prompt con el encargo. El reloj (cron,
|
|
80
|
+
systemd) y la puerta (relay de webhooks, n8n) viven **fuera** de OpenCode:
|
|
69
81
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
82
|
+
- OpenCode descarga los plugins de un directorio tras **60 min sin actividad** y no los
|
|
83
|
+
recarga tras un reinicio hasta que algo usa ese directorio. El RPC levanta el
|
|
84
|
+
directorio en la propia llamada; un listener o un temporizador del plugin moriría con él.
|
|
85
|
+
- Un **webhook** es un callback con un proceso intermedio que traduce la llamada HTTP a
|
|
86
|
+
`events.ingest`.
|
|
87
|
+
- Si la comprobación necesita una herramienta que solo existe en OpenCode (un MCP, el
|
|
88
|
+
navegador), el proceso externo la ejecuta con **`apex/tools.run`**, sin modelo.
|
|
89
|
+
- La tool **`apex_callback_endpoint`** le dice al agente la URL base de su propio servidor,
|
|
90
|
+
las URLs RPC de su directorio y de dónde leer el password (nunca lo devuelve).
|
|
74
91
|
|
|
75
|
-
|
|
76
|
-
|
|
92
|
+
La skill **`apex-callbacks`** viaja con el paquete y se registra sola: vigilantes con
|
|
93
|
+
estado, systemd/cron, relay de webhooks, n8n y `tools.run`. Detalle en
|
|
94
|
+
[docs/EVENTS.md](docs/EVENTS.md).
|
|
77
95
|
|
|
78
96
|
## Herramientas expuestas
|
|
79
97
|
|
|
@@ -82,8 +100,8 @@ entrega fiable): **`.opencode/skills/apex-callbacks/SKILL.md`**.
|
|
|
82
100
|
| `apex_subscribe` | events | Crea una suscripción para la sesión que llama |
|
|
83
101
|
| `apex_unsubscribe` | events | Elimina una suscripción dinámica por id |
|
|
84
102
|
| `apex_list_subscriptions` | events | Lista suscripciones (marca las estáticas de config) |
|
|
85
|
-
| `apex_callback_endpoint` | events |
|
|
86
|
-
| `apex_set_callback_url` | events | Anuncia/limpia la URL pública (túnel)
|
|
103
|
+
| `apex_callback_endpoint` | events | Cómo alcanza un proceso externo a este servidor: URL base, URLs RPC del directorio, auth y ejemplos curl |
|
|
104
|
+
| `apex_set_callback_url` | events | Anuncia/limpia la URL pública (túnel/proxy) del servidor para emisores de otras máquinas |
|
|
87
105
|
| `apex_advisor_decide` | advisor | Única tool del agente advisor: `allow` / `deny` + `reason` |
|
|
88
106
|
| `apex_guard_report` | guard | Informe de meta-permisos: qué intentó cada agente y qué se decidió |
|
|
89
107
|
| `browser_target` | browser | Elige qué navegador sirve `browser.*`: `external` (CDP), `in-app` (app de escritorio) o `auto` |
|
|
@@ -93,9 +111,14 @@ entrega fiable): **`.opencode/skills/apex-callbacks/SKILL.md`**.
|
|
|
93
111
|
| Método | Entrada | Salida |
|
|
94
112
|
| ---------------- | ---------------------------------------------- | ------------------------------------- |
|
|
95
113
|
| `apex.ping` | `{ payload? }` | `{ pong, timestamp }` |
|
|
96
|
-
| `apex.status` | `{}` | `{ modules, version, uptimeMs,
|
|
114
|
+
| `apex.status` | `{}` | `{ modules, version, uptimeMs, endpoint }` |
|
|
115
|
+
| `apex.server.info` | `{}` | lo mismo que `apex_callback_endpoint` |
|
|
97
116
|
| `apex.redact.process` | `{ text, mode? }` | `{ redacted, findings }` |
|
|
98
117
|
| `apex.events.ingest` | `{ source, type?, payload, eventID? }` | `{ accepted, eventID, delivered }` |
|
|
118
|
+
| `apex.tools.run` | `{ tool, input?, agent?, timeoutMs? }` | `{ ok, tool, agent, output?, content?, metadata?, error?, durationMs }` |
|
|
119
|
+
|
|
120
|
+
Llamada: `POST <baseUrl>/api/rpc/apex/<método>?location[directory]=<proyecto>` con cuerpo
|
|
121
|
+
`{"input":{…}}` y Basic `opencode:<password>`; responde `{"output":{…}}`.
|
|
99
122
|
|
|
100
123
|
## Estructura
|
|
101
124
|
|
|
@@ -121,12 +144,18 @@ entrega fiable): **`.opencode/skills/apex-callbacks/SKILL.md`**.
|
|
|
121
144
|
│ ├── bus.ts # Bus interno
|
|
122
145
|
│ ├── rpc.ts # Registro del namespace RPC "apex"
|
|
123
146
|
│ ├── guard.ts # Motor de meta-permisos
|
|
124
|
-
│ ├──
|
|
147
|
+
│ ├── server-endpoint.ts # URL base del servidor + auth para procesos externos
|
|
148
|
+
│ ├── tools-run.ts # RPC tools.run: allow/deny, agente de permisos, sesión runner
|
|
149
|
+
│ ├── skills.ts # Registro de las skills del paquete
|
|
150
|
+
│ ├── compat.ts # Aviso de versiones desalineadas con OpenCode (effect, @opencode/plugin)
|
|
125
151
|
│ ├── advisor-agent.ts # Definición del agente apex-advisor
|
|
126
152
|
│ ├── advisor-tool.ts # Tool apex_advisor_decide
|
|
127
153
|
│ └── advisor-session.ts # Sesión advisor por árbol + round-trip
|
|
154
|
+
├── skills/
|
|
155
|
+
│ └── apex-callbacks/ # Skill: callbacks, webhooks, vigilancias, tools.run
|
|
128
156
|
├── test/
|
|
129
157
|
│ ├── browser.test.ts # Suite del módulo browser (Chromium en TEST_CDP_URL)
|
|
158
|
+
│ ├── events.test.ts # RPC, descubrimiento del servidor, tools.run, skills
|
|
130
159
|
│ └── guard.test.ts # Suite del módulo guard
|
|
131
160
|
└── docs/ # CONFIG · REDACT · EVENTS · ADVISOR · GUARD · BROWSER · TROUBLESHOOTING
|
|
132
161
|
```
|
|
@@ -137,8 +166,10 @@ entrega fiable): **`.opencode/skills/apex-callbacks/SKILL.md`**.
|
|
|
137
166
|
./node_modules/.bin/tsc --noEmit # typecheck
|
|
138
167
|
./node_modules/.bin/tsc --noEmit --noUnusedLocals --noUnusedParameters # código muerto
|
|
139
168
|
bun -e "await import('./index.ts'); console.log('OK')" # smoke de carga
|
|
169
|
+
bun test/events.test.ts # events (56)
|
|
140
170
|
bun test test/guard.test.ts # guard (56)
|
|
141
171
|
TEST_CDP_URL=<puerto> bun test test/browser.test.ts # browser (10; p.ej. 9333)
|
|
172
|
+
node scripts/check-install.mjs # instala como OpenCode: 1 sola copia de effect
|
|
142
173
|
```
|
|
143
174
|
|
|
144
175
|
Para la suite de browser hace falta un Chromium headless con CDP en ese puerto:
|
package/core/compat.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compatibilidad con la versión de OpenCode que carga el plugin.
|
|
3
|
+
*
|
|
4
|
+
* apex usa `effect` sin declarar versión propia: la toma de `@opencode/plugin`
|
|
5
|
+
* (peer opcional en package.json), así que npm instala UNA sola copia y la versión
|
|
6
|
+
* sigue sola a la de OpenCode. Si aun así hubiera dos copias (una instalación vieja
|
|
7
|
+
* en caché, un gestor que no hoistea), los efectos de una no se entienden con la otra
|
|
8
|
+
* y el fallo llega críptico (`Schema.isStartsWith is not a function`, "missing TypeId").
|
|
9
|
+
* Aquí se detecta al cargar y se dice qué hacer.
|
|
10
|
+
*
|
|
11
|
+
* La caché npm de plugins de OpenCode no se refresca sola: tras actualizar OpenCode,
|
|
12
|
+
* apex sigue con las dependencias de cuando se instaló hasta que se reinstala.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { readFileSync, realpathSync } from "node:fs"
|
|
16
|
+
import { dirname, join } from "node:path"
|
|
17
|
+
import { fileURLToPath } from "node:url"
|
|
18
|
+
|
|
19
|
+
interface Resolved {
|
|
20
|
+
readonly dir: string
|
|
21
|
+
readonly version: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Directorio y versión del paquete `name` tal como lo encuentra un módulo de `fromDir`:
|
|
26
|
+
* el primer `node_modules/<name>` subiendo de directorio (la búsqueda de Node). No se usa
|
|
27
|
+
* `require.resolve` porque los paquetes de OpenCode solo exportan la condición `import`.
|
|
28
|
+
*/
|
|
29
|
+
function resolvePackage(name: string, fromDir: string): Resolved | null {
|
|
30
|
+
let dir = fromDir
|
|
31
|
+
for (;;) {
|
|
32
|
+
const candidate = join(dir, "node_modules", name)
|
|
33
|
+
const pkg = readPackage(candidate)
|
|
34
|
+
if (pkg?.name === name) return { dir: realpathSafe(candidate), version: pkg.version ?? "?" }
|
|
35
|
+
const parent = dirname(dir)
|
|
36
|
+
if (parent === dir) return null
|
|
37
|
+
dir = parent
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function realpathSafe(path: string): string {
|
|
42
|
+
try {
|
|
43
|
+
return realpathSync(path)
|
|
44
|
+
} catch {
|
|
45
|
+
return path
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function readPackage(dir: string): { name?: string; version?: string } | null {
|
|
50
|
+
try {
|
|
51
|
+
return JSON.parse(readFileSync(join(dir, "package.json"), "utf8"))
|
|
52
|
+
} catch {
|
|
53
|
+
return null
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Cómo forzar que OpenCode reinstale apex y sus dependencias. */
|
|
58
|
+
const REINSTALL =
|
|
59
|
+
"con OpenCode parado, borra ~/.cache/opencode/npm/opencode-apex@* y arráncalo " +
|
|
60
|
+
"(en 2.1 `opencode plugin update` solo gestiona plugins de TUI)"
|
|
61
|
+
|
|
62
|
+
/** major.minor numérico, o null si no se puede leer. */
|
|
63
|
+
function minor(version: string | undefined): [number, number] | null {
|
|
64
|
+
const match = /^(\d+)\.(\d+)/.exec(version ?? "")
|
|
65
|
+
return match ? [Number(match[1]), Number(match[2])] : null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** true si `a` (major.minor) es posterior a `b`. */
|
|
69
|
+
export function newerMinor(a: string | undefined, b: string | undefined): boolean {
|
|
70
|
+
const x = minor(a)
|
|
71
|
+
const y = minor(b)
|
|
72
|
+
if (!x || !y) return false
|
|
73
|
+
return x[0] > y[0] || (x[0] === y[0] && x[1] > y[1])
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Avisos de compatibilidad (vacío = todo bien).
|
|
78
|
+
* @param hostVersion versión de OpenCode (`ctx.app.version`)
|
|
79
|
+
*/
|
|
80
|
+
export function compatibilityWarnings(
|
|
81
|
+
hostVersion: string | undefined,
|
|
82
|
+
apexDir: string = dirname(dirname(fileURLToPath(import.meta.url))),
|
|
83
|
+
): string[] {
|
|
84
|
+
const warnings: string[] = []
|
|
85
|
+
const plugin = resolvePackage("@opencode/plugin", apexDir)
|
|
86
|
+
const ownEffect = resolvePackage("effect", apexDir)
|
|
87
|
+
const pluginEffect = plugin ? resolvePackage("effect", plugin.dir) : null
|
|
88
|
+
|
|
89
|
+
if (ownEffect && pluginEffect && ownEffect.dir !== pluginEffect.dir) {
|
|
90
|
+
warnings.push(
|
|
91
|
+
`dos copias de effect: apex usa ${ownEffect.version} y @opencode/plugin ${pluginEffect.version}. ` +
|
|
92
|
+
`Reinstala el plugin: ${REINSTALL}.`,
|
|
93
|
+
)
|
|
94
|
+
}
|
|
95
|
+
if (plugin && newerMinor(hostVersion, plugin.version)) {
|
|
96
|
+
warnings.push(
|
|
97
|
+
`OpenCode ${hostVersion} es más nuevo que @opencode/plugin ${plugin.version} instalado con apex. ` +
|
|
98
|
+
`Reinstálalo para alinear versiones: ${REINSTALL}.`,
|
|
99
|
+
)
|
|
100
|
+
}
|
|
101
|
+
return warnings
|
|
102
|
+
}
|
package/core/config.ts
CHANGED
|
@@ -66,27 +66,34 @@ export interface EventsConfig {
|
|
|
66
66
|
/** El toggle del módulo vive SOLO en `modules.events`. */
|
|
67
67
|
routing: "first" | "all"
|
|
68
68
|
subscriptions: Omit<EventSubscription, "id" | "readonly">[]
|
|
69
|
-
/**
|
|
70
|
-
|
|
69
|
+
/** Dónde alcanzan los procesos externos al servidor (lo descubre solo si no se fija). */
|
|
70
|
+
server: EventsServerConfig
|
|
71
|
+
/** RPC `apex/tools.run`: ejecutar herramientas de OpenCode desde fuera. */
|
|
72
|
+
tools: EventsToolsConfig
|
|
71
73
|
}
|
|
72
74
|
|
|
73
|
-
export interface
|
|
74
|
-
/**
|
|
75
|
-
|
|
76
|
-
/** Interfaz de escucha: 127.0.0.1 (loopback) | 0.0.0.0 | una IP LAN. */
|
|
77
|
-
host: string
|
|
78
|
-
/** Puerto de escucha. */
|
|
79
|
-
port: number
|
|
80
|
-
/** Token opcional; si se define, obligatorio en cada petición. */
|
|
81
|
-
token?: string
|
|
75
|
+
export interface EventsServerConfig {
|
|
76
|
+
/** URL base del servidor tal como la alcanzan los scripts locales. Vacío = descubrir. */
|
|
77
|
+
url?: string
|
|
82
78
|
/**
|
|
83
|
-
* URL pública por DEFECTO (
|
|
84
|
-
*
|
|
79
|
+
* URL pública por DEFECTO (túnel o proxy inverso hacia el servidor) para emisores
|
|
80
|
+
* de otras máquinas. El agente puede fijarla en runtime con `apex_set_callback_url`
|
|
85
81
|
* (precedencia: runtime > esta config).
|
|
86
82
|
*/
|
|
87
83
|
publicUrl?: string
|
|
88
84
|
}
|
|
89
85
|
|
|
86
|
+
export interface EventsToolsConfig {
|
|
87
|
+
enabled: boolean
|
|
88
|
+
/** Globs de herramientas ejecutables por RPC. */
|
|
89
|
+
allow: string[]
|
|
90
|
+
/** Globs denegados aunque casen con `allow` (gana deny). */
|
|
91
|
+
deny: string[]
|
|
92
|
+
/** Agente cuyos permisos se aplican por defecto. */
|
|
93
|
+
agent: string
|
|
94
|
+
timeoutMs: number
|
|
95
|
+
}
|
|
96
|
+
|
|
90
97
|
export interface AdvisorConfig {
|
|
91
98
|
model?: string
|
|
92
99
|
actions: string[]
|
|
@@ -143,21 +150,41 @@ const eventSubscriptionSchema = z.object({
|
|
|
143
150
|
enabled: z.boolean().default(true),
|
|
144
151
|
})
|
|
145
152
|
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
// un túnel) sin tocar la config. Cámbialo a false para no abrir el puerto.
|
|
149
|
-
enabled: z.boolean().default(true),
|
|
150
|
-
host: z.string().default("127.0.0.1"),
|
|
151
|
-
port: z.number().int().positive().default(4599),
|
|
152
|
-
token: z.string().optional(),
|
|
153
|
+
const eventsServerSchema = z.object({
|
|
154
|
+
url: z.string().optional(),
|
|
153
155
|
publicUrl: z.string().optional(),
|
|
154
156
|
})
|
|
155
157
|
|
|
158
|
+
const DEFAULT_EVENTS_TOOLS = {
|
|
159
|
+
enabled: true,
|
|
160
|
+
allow: ["*"],
|
|
161
|
+
// Sin nadie delante: `question` esperaría para siempre; `subagent`/`execute`
|
|
162
|
+
// lanzarían un modelo; las de apex no tienen sentido desde fuera.
|
|
163
|
+
deny: ["question", "subagent", "execute", "apex_*"],
|
|
164
|
+
agent: "build",
|
|
165
|
+
timeoutMs: 120000,
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const eventsToolsSchema = z.object({
|
|
169
|
+
enabled: z.boolean().default(DEFAULT_EVENTS_TOOLS.enabled),
|
|
170
|
+
allow: z.array(z.string()).default(() => [...DEFAULT_EVENTS_TOOLS.allow]),
|
|
171
|
+
deny: z.array(z.string()).default(() => [...DEFAULT_EVENTS_TOOLS.deny]),
|
|
172
|
+
agent: z.string().default(DEFAULT_EVENTS_TOOLS.agent),
|
|
173
|
+
timeoutMs: z.number().int().positive().default(DEFAULT_EVENTS_TOOLS.timeoutMs),
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
const defaultEventsTools = () => ({
|
|
177
|
+
...DEFAULT_EVENTS_TOOLS,
|
|
178
|
+
allow: [...DEFAULT_EVENTS_TOOLS.allow],
|
|
179
|
+
deny: [...DEFAULT_EVENTS_TOOLS.deny],
|
|
180
|
+
})
|
|
181
|
+
|
|
156
182
|
const eventsConfigSchema = z.object({
|
|
157
183
|
// El toggle del módulo vive SOLO en `modules.events` (evita duplicidad).
|
|
158
184
|
routing: z.enum(["first", "all"]).default("all"),
|
|
159
185
|
subscriptions: z.array(eventSubscriptionSchema).default([]),
|
|
160
|
-
|
|
186
|
+
server: eventsServerSchema.default(() => ({})),
|
|
187
|
+
tools: eventsToolsSchema.default(defaultEventsTools),
|
|
161
188
|
})
|
|
162
189
|
|
|
163
190
|
const advisorConfigSchema = z.object({
|
|
@@ -209,7 +236,7 @@ const browserConfigSchema = z.object({
|
|
|
209
236
|
|
|
210
237
|
export const apexConfigSchema = z.object({
|
|
211
238
|
redact: redactConfigSchema.default(() => ({ mode: "strict" as const, patterns: [], bundles: [...DEFAULT_BUNDLES], minConfidence: "medium" as const, allowlist: [], prefix: "[SECRET:", suffix: "]", key: "", restore: { toolInput: true } })),
|
|
212
|
-
events: eventsConfigSchema.default(() => ({ routing: "all" as const, subscriptions: [],
|
|
239
|
+
events: eventsConfigSchema.default(() => ({ routing: "all" as const, subscriptions: [], server: {}, tools: defaultEventsTools() })),
|
|
213
240
|
advisor: advisorConfigSchema.default(() => ({ actions: [], decisive: false, evaluate: "ask-only" as const, timeoutMs: 10000 })),
|
|
214
241
|
guard: guardConfigSchema.default(() => ({
|
|
215
242
|
mode: "report" as const,
|
|
@@ -441,6 +468,13 @@ export async function loadApexConfig(input: {
|
|
|
441
468
|
`[apex] "events.enabled" está obsoleto y se ignora; usa "modules.events" (valor indicado: ${String(legacyEnabled)})`,
|
|
442
469
|
)
|
|
443
470
|
}
|
|
471
|
+
// 0.2.0: el listener HTTP plano desapareció (se cerraba al descargarse el plugin
|
|
472
|
+
// por inactividad). Los callbacks y webhooks entran por el RPC.
|
|
473
|
+
if ((legacy as Record<string, unknown> | undefined)?.listener !== undefined) {
|
|
474
|
+
console.warn(
|
|
475
|
+
`[apex] "events.listener" ya no existe y se ignora: usa el RPC apex/events.ingest (tool apex_callback_endpoint)`,
|
|
476
|
+
)
|
|
477
|
+
}
|
|
444
478
|
|
|
445
479
|
const result = apexConfigSchema.safeParse(merged)
|
|
446
480
|
if (!result.success) {
|
package/core/rpc.ts
CHANGED
|
@@ -1,117 +1,130 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Core RPC module for opencode-apex (Effect-native).
|
|
3
|
-
* Registers the "apex" RPC namespace
|
|
3
|
+
* Registers the "apex" RPC namespace: `POST /api/rpc/apex/<method>?location[directory]=<dir>`.
|
|
4
|
+
*
|
|
5
|
+
* OpenCode registra los RPC por `definition.id` (antes de 0.2.0 apex declaraba `name`
|
|
6
|
+
* y su RPC quedaba registrado sin nombre: `rpc.unavailable`). Cada directorio registra
|
|
7
|
+
* el suyo, con los handlers de ESE directorio: nada sale de variables de módulo.
|
|
8
|
+
*
|
|
9
|
+
* La llamada RPC espera a que los plugins del directorio estén activos (y lo levanta
|
|
10
|
+
* si OpenCode lo había descargado por inactividad), así que es una entrada fiable
|
|
11
|
+
* para procesos externos de larga duración.
|
|
4
12
|
*/
|
|
5
13
|
|
|
6
14
|
import { Effect } from "effect"
|
|
7
15
|
import { emit as busEmit } from "./bus.js"
|
|
8
|
-
import {
|
|
16
|
+
import type { EventsHandles, IngestInput } from "../events.js"
|
|
17
|
+
import type { ServerEndpoint } from "./server-endpoint.js"
|
|
18
|
+
import type { ToolsRunInput } from "./tools-run.js"
|
|
9
19
|
import { redactHandler } from "../redact.js"
|
|
10
20
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
21
|
+
const ANY = { type: "object", additionalProperties: true } as const
|
|
22
|
+
|
|
23
|
+
/** Contrato del namespace "apex" (JSON Schema, igual que las tools). */
|
|
24
|
+
export const APEX_RPC_DEFINITION = {
|
|
25
|
+
id: "apex",
|
|
26
|
+
methods: {
|
|
27
|
+
/** Salud: `{ pong, timestamp }`. */
|
|
28
|
+
ping: { input: ANY, output: ANY },
|
|
29
|
+
/** `{ modules, version, uptimeMs, endpoint }`. */
|
|
30
|
+
status: { input: ANY, output: ANY },
|
|
31
|
+
/** `{ text, mode? }` → `{ redacted, findings }`. */
|
|
32
|
+
"redact.process": {
|
|
33
|
+
input: { type: "object", properties: { text: { type: "string" } }, required: ["text"], additionalProperties: true },
|
|
34
|
+
output: ANY,
|
|
35
|
+
},
|
|
36
|
+
/** `{ source, type?, payload, eventID? }` → `{ accepted, eventID, delivered }`. */
|
|
37
|
+
"events.ingest": {
|
|
38
|
+
input: {
|
|
39
|
+
type: "object",
|
|
40
|
+
properties: {
|
|
41
|
+
source: { type: "string" },
|
|
42
|
+
type: { type: "string" },
|
|
43
|
+
payload: { type: "object" },
|
|
44
|
+
eventID: { type: "string" },
|
|
45
|
+
},
|
|
46
|
+
required: ["source", "payload"],
|
|
47
|
+
additionalProperties: true,
|
|
48
|
+
},
|
|
49
|
+
output: ANY,
|
|
50
|
+
},
|
|
51
|
+
/** `{ tool, input?, agent?, timeoutMs? }` → `{ ok, tool, output?, content?, error?, durationMs }`. */
|
|
52
|
+
"tools.run": {
|
|
53
|
+
input: {
|
|
54
|
+
type: "object",
|
|
55
|
+
properties: {
|
|
56
|
+
tool: { type: "string" },
|
|
57
|
+
input: { type: "object" },
|
|
58
|
+
agent: { type: "string" },
|
|
59
|
+
timeoutMs: { type: "number" },
|
|
60
|
+
},
|
|
61
|
+
required: ["tool"],
|
|
62
|
+
additionalProperties: true,
|
|
63
|
+
},
|
|
64
|
+
output: ANY,
|
|
65
|
+
},
|
|
66
|
+
/** Dónde y cómo llamar a este servidor (lo mismo que la tool apex_callback_endpoint). */
|
|
67
|
+
"server.info": { input: ANY, output: ANY },
|
|
68
|
+
},
|
|
69
|
+
events: {
|
|
70
|
+
"config.changed": { schema: ANY },
|
|
71
|
+
},
|
|
72
|
+
} as const
|
|
73
|
+
|
|
74
|
+
export interface CentralRpcInput {
|
|
75
|
+
readonly version: string
|
|
76
|
+
readonly modules: Record<string, { enabled: boolean }>
|
|
77
|
+
/** null si el módulo events está desactivado. */
|
|
78
|
+
readonly events: EventsHandles | null
|
|
56
79
|
}
|
|
57
80
|
|
|
58
81
|
/**
|
|
59
82
|
* Register the central "apex" RPC namespace (Effect-native).
|
|
60
|
-
* Handlers delegate to module-level handler singletons set by each module's register().
|
|
61
83
|
*/
|
|
62
84
|
export function registerCentralRpc(
|
|
63
85
|
ctx: { rpc: import("@opencode/plugin/effect").Plugin.Context["rpc"] },
|
|
64
|
-
|
|
65
|
-
version: string,
|
|
86
|
+
input: CentralRpcInput,
|
|
66
87
|
): Effect.Effect<void, never, import("effect").Scope.Scope> {
|
|
67
88
|
return Effect.gen(function* () {
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
ping: { input: {} as any, output: {} as any },
|
|
73
|
-
status: { input: {} as any, output: {} as any },
|
|
74
|
-
"redact.process": { input: {} as any, output: {} as any },
|
|
75
|
-
"events.ingest": { input: {} as any, output: {} as any },
|
|
76
|
-
},
|
|
77
|
-
events: {
|
|
78
|
-
"config.changed": {} as any,
|
|
79
|
-
},
|
|
80
|
-
} as unknown as ApexRpcDefinition
|
|
89
|
+
const startedAt = Date.now()
|
|
90
|
+
const { modules, events } = input
|
|
91
|
+
const eventsOff = "módulo events desactivado (modules.events=false)"
|
|
92
|
+
const endpoint = (): ServerEndpoint | null => events?.endpoint() ?? null
|
|
81
93
|
|
|
82
|
-
yield* ctx.rpc.register(
|
|
83
|
-
ping: (
|
|
84
|
-
Effect.succeed({ pong:
|
|
94
|
+
yield* ctx.rpc.register(APEX_RPC_DEFINITION as never, {
|
|
95
|
+
ping: (rpcInput: { payload?: string }) =>
|
|
96
|
+
Effect.succeed({ pong: rpcInput?.payload ?? "pong", timestamp: Date.now() }),
|
|
85
97
|
status: () =>
|
|
86
|
-
Effect.
|
|
87
|
-
modules:
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
callback: getCallbackEndpoint(),
|
|
95
|
-
}),
|
|
96
|
-
"redact.process": (input: { text: string; mode?: "strict" | "warn" }) =>
|
|
98
|
+
Effect.sync(() => ({
|
|
99
|
+
modules: Object.fromEntries(Object.entries(modules).map(([name, module]) => [name, module?.enabled === true])),
|
|
100
|
+
version: input.version,
|
|
101
|
+
uptimeMs: Date.now() - startedAt,
|
|
102
|
+
endpoint: endpoint(),
|
|
103
|
+
})),
|
|
104
|
+
"server.info": () => Effect.sync(() => endpoint() ?? { error: eventsOff }),
|
|
105
|
+
"redact.process": (rpcInput: { text: string; mode?: "strict" | "warn" }) =>
|
|
97
106
|
redactHandler
|
|
98
|
-
? Effect.sync(() => redactHandler!(
|
|
99
|
-
: Effect.succeed({ redacted:
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
107
|
+
? Effect.sync(() => redactHandler!(rpcInput))
|
|
108
|
+
: Effect.succeed({ redacted: rpcInput.text, findings: [] }),
|
|
109
|
+
// Una entrada inválida vuelve como `error` legible, no como fallo interno opaco.
|
|
110
|
+
"events.ingest": (rpcInput: IngestInput) =>
|
|
111
|
+
events
|
|
112
|
+
? Effect.promise(() =>
|
|
113
|
+
events.ingest(rpcInput).catch((error: unknown) => ({
|
|
114
|
+
accepted: false,
|
|
115
|
+
eventID: "",
|
|
116
|
+
delivered: [],
|
|
117
|
+
error: error instanceof Error ? error.message : String(error),
|
|
118
|
+
})),
|
|
119
|
+
)
|
|
120
|
+
: Effect.succeed({ accepted: false, eventID: "", delivered: [], error: eventsOff }),
|
|
121
|
+
"tools.run": (rpcInput: ToolsRunInput) =>
|
|
122
|
+
events
|
|
123
|
+
? Effect.promise(() => events.toolsRun(rpcInput))
|
|
124
|
+
: Effect.succeed({ ok: false, tool: rpcInput?.tool ?? "", error: eventsOff, durationMs: 0 }),
|
|
111
125
|
} as never)
|
|
112
126
|
|
|
113
127
|
// Emit a config.changed event on the bus for subscribers
|
|
114
|
-
busEmit("config.changed", { modules
|
|
128
|
+
busEmit("config.changed", { modules }, "apex-rpc")
|
|
115
129
|
}) as Effect.Effect<void, never, import("effect").Scope.Scope>
|
|
116
130
|
}
|
|
117
|
-
|