opencode-apex 0.6.0 → 0.8.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/docs/CRED.md CHANGED
@@ -1,67 +1,150 @@
1
- # Cred — `/cred`
1
+ # Cred — `/cred` + `apex_cred`
2
2
 
3
- Secretos declarados explícitamente por el usuario, redactados del contexto del
4
- modelo. Complementa a `redact` (que detecta por forma/regex): aquí apex conoce
5
- el literal exacto, así que no hay falsos positivos ni heurística.
3
+ Almacén local de credenciales declaradas por el usuario. Complementa a `redact`
4
+ (que detecta por forma/regex): aquí apex conoce el literal exacto, así que no
5
+ hay falsos positivos ni heurística.
6
6
 
7
- ## Sin modelo (siempre disponible)
7
+ Dos superficies:
8
+
9
+ - `/cred` (comando TUI): el usuario guarda/lista/elimina credenciales.
10
+ - `apex_cred` (herramienta del agente): el agente lista metadatos y abre
11
+ canales temporales para usar una credencial **sin conocer el secreto**.
12
+
13
+ ## Comandos `/cred`
8
14
 
9
15
  ```
16
+ /cred help # manual completo (también /cred sin argumentos)
10
17
  /cred set <nombre>=<valor>
18
+ /cred set <nombre> <valor|uri>
11
19
  /cred set <nombre> --from-env VAR
12
20
  /cred set <nombre> --from-file ruta
21
+ /cred set <nombre> --url URL --username U --password P --kind K
22
+ /cred set <nombre> --secret.token TOK --field.header x-api-key
23
+ /cred get <nombre>
13
24
  /cred list
14
25
  /cred rm <nombre>
26
+ /cred kdbx status|reload|save
27
+ /cred learn <frase libre> # solo si cred.llm.enabled=true
28
+ /cred confirm | /cred discard
15
29
  ```
16
30
 
17
- El TUI de OpenCode no enmascara la entrada: `/cred set nombre=valor` deja el
18
- valor en el historial de comandos del terminal. Usa `--from-env`/`--from-file`
19
- para evitarlo.
20
-
21
- ## Con modelo local (opcional, off por defecto)
22
-
23
- ```
24
- cred.llm.enabled: true # en opencode-apex.jsonc
25
- /cred learn <frase libre> # "la contraseña de fulano es qweasd123"
26
- /cred confirm # guarda lo detectado
27
- /cred discard # lo descarta
28
- ```
31
+ Notas:
29
32
 
30
- El modelo solo propone; nunca guarda solo. La respuesta de `/cred learn` nunca
31
- incluye el valor (solo nombre y longitud) — confirmar no requiere volver a
32
- teclear el secreto. Si `cred.llm.enabled` es `false`, `/cred learn` responde
33
- explicando que hace falta un modelo y sugiere `/cred set` — no es un error.
33
+ - **Las respuestas de `/cred` no entran al contexto del modelo.** Son mensajes
34
+ `synthetic` con `metadata.apexUiOnly`, y el módulo los quita en los hooks
35
+ `context`, `compaction` y `generate`: se ven en la sesión pero el modelo no
36
+ los recibe ni acaban en un resumen de compactación. Se entregan con
37
+ `delivery: "steer"` y `resume: false`: esperan en la bandeja y pasan a la
38
+ transcripción junto a la siguiente llamada real al modelo, sin lanzar un
39
+ turno propio. Con el servidor en `--log-level debug`, cada descarte deja
40
+ `[apex.cred] context: N respuesta(s) de /cred fuera de la petición`.
41
+ - El TUI no enmascara la entrada: `/cred set nombre=valor` puede quedar en
42
+ historial del terminal. Preferir `--from-env` o `--from-file`.
43
+ - `set` acepta URIs como `ssh://user:pass@host:22`; apex extrae
44
+ usuario/password/host/kind.
45
+ - `get`/`list` solo muestran metadatos públicos (nunca secretos).
46
+ - `rm` elimina la credencial del almacén activo (memoria/KDBX según config).
34
47
 
35
- El endpoint debe ser local (`127.0.0.1`/`localhost`) salvo
36
- `cred.llm.allowRemote: true` explícito: un extractor en la nube sacaría el
37
- secreto de la máquina para identificarlo, que es justo lo que se quiere evitar.
48
+ ## KDBX (KeePassXC / KeePass)
38
49
 
39
- ## Config (`opencode-apex.jsonc`)
50
+ Opcional. Cuando `cred.kdbx.enabled=true`, el fichero `.kdbx` es la fuente de
51
+ verdad: interoperable con apps externas. apex lo lee al arrancar, vigila cambios
52
+ (`watch`) y recarga; los secretos protegidos se añaden al motor de redacción.
40
53
 
41
54
  ```jsonc
42
55
  {
43
56
  "cred": {
44
- "minLength": 6, // secretos más cortos se rechazan
45
- "llm": {
46
- "enabled": false,
47
- "endpoint": "http://127.0.0.1:11434/v1",
48
- "model": "qwen2.5:3b",
49
- "timeoutMs": 4000,
50
- "allowRemote": false
51
- }
57
+ "minLength": 6,
58
+ "kdbx": {
59
+ "enabled": true,
60
+ "path": "~/.config/opencode/apex-creds.kdbx",
61
+ "password": "env:APEX_CRED_KDBX_PASSWORD",
62
+ "keyFile": "",
63
+ "createIfMissing": true,
64
+ "watch": true,
65
+ "group": "apex"
66
+ },
67
+ "llm": { "enabled": false }
52
68
  },
53
69
  "modules": { "cred": true }
54
70
  }
55
71
  ```
56
72
 
57
- ## Cómo se aplica (detalle interno)
58
-
59
- - `core/cred.ts` guarda el literal en memoria y lo persiste cifrado
60
- (AES-256-GCM, misma clave que `redact`) en `ctx.storage["apex:cred"]`.
61
- - Variantes redactadas además del literal: URL-encoded, base64, JSON-escaped.
62
- - `redact.ts` suma los literales como patrones adicionales vía un **getter**
63
- (`core/redact.ts`), evaluado en cada redacción — dar de alta un secreto
64
- nuevo se aplica sin recompilar el motor ni reiniciar el plugin.
65
- - La restauración hacia la herramienta sigue el mismo camino que `redact`
66
- (`tool.execute.before`): el marcador `[SECRET:cred-<nombre>:…]` se descifra
67
- igual que cualquier otro.
73
+ - `password`/`keyFile`: soportan `env:VAR`, `file:/ruta` o literal. Preferir
74
+ `env:`/`file:` con permisos restrictivos.
75
+ - KDBX4 usa Argon2; la apertura se hace con `kdbxweb` + `hash-wasm` (WASM puro).
76
+ - `watch`: recarga en cambios externos (se vigila el directorio, así que
77
+ sobrevive a los guardados atómicos de KeePassXC); si falla, se mantiene el
78
+ último índice válido en memoria.
79
+ - Todos los secretos del fichero se redactan: dos entradas con el mismo título
80
+ aparecen como `nombre` y `nombre#2`, y una sin título como `entry-<uuid>`.
81
+ - El fichero se escribe con permisos `0600`.
82
+ - Interoperabilidad: KeePassXC u otra app puede editar el `.kdbx`; apex recarga.
83
+ Credenciales creadas por `/cred set` se guardan en el KDBX.
84
+
85
+ ## Herramienta del agente: `apex_cred`
86
+
87
+ El agente no recibe secretos. Flujo:
88
+
89
+ 1. `apex_cred { action: "list" }` o `get` → metadatos públicos (nombre, tipo,
90
+ host, usuario; la URL sale sin credenciales ni query).
91
+ 2. `apex_cred { action: "open", name: "mi-cred" }` → crea un canal y publica una
92
+ herramienta efímera `apex_cred_use_<handle>`. Abrir dos veces la misma
93
+ credencial devuelve el mismo canal.
94
+ 3. El agente llama a `apex_cred_use_<handle>` las veces que haga falta; apex
95
+ inyecta el secreto y devuelve la salida limpia. `apex_cred { action: "use",
96
+ handle, do, params }` hace lo mismo, por si el host aún no ha refrescado la
97
+ lista de herramientas del turno.
98
+ 4. `apex_cred { action: "close", handle }` cierra el canal y retira su
99
+ herramienta. `handles` lista los abiertos (máximo 16).
100
+
101
+ **El destino lo fija la credencial, no el agente.** Si el agente pudiera elegir
102
+ host, le bastaría apuntar el canal a un servidor suyo para recibir el secreto:
103
+
104
+ - `ssh` (`action: "exec", params: { command, stdin?, timeoutMs? }`): host,
105
+ puerto y usuario salen de la credencial (`ssh://host[:puerto]`). La contraseña
106
+ se entrega por `SSH_ASKPASS` (OpenSSH ≥ 8.4): no va en argv ni necesita
107
+ `sshpass`.
108
+ - `http-bearer` / `http-basic` / `api-key` (`action: "request", params: {
109
+ method?, path?, headers?, body?, timeoutMs? }`): solo se llama al mismo origen
110
+ (esquema + host + puerto) que la URL guardada; otro origen se rechaza sin
111
+ enviar nada, las redirecciones no se siguen y la cabecera de autenticación no
112
+ se puede sustituir. `api-key` usa la cabecera del campo `header`
113
+ (`x-api-key` por defecto) y el secreto del campo protegido `apiKey`.
114
+ - Una credencial sin URL, o de otro tipo (`database`, `generic`), no abre canal.
115
+
116
+ `mode` en `open` elige cómo presentar el secreto (`auto` por defecto: sigue el
117
+ `kind` y la URL de la credencial).
118
+
119
+ La salida del canal se limpia de cualquier secreto del almacén (y del base64 de
120
+ Basic) antes de volver al agente. Un canal cuya credencial se borra se cierra
121
+ solo. `apex_cred` no es invocable desde fuera por `tools.run`: el `deny` por
122
+ defecto de `events.tools` cubre `apex_*`.
123
+
124
+ Límite conocido: un comando ssh lo ejecuta el servidor remoto con los permisos
125
+ de esa cuenta; el canal protege el secreto, no lo que el agente haga con el
126
+ acceso.
127
+
128
+ ## Modelo local opcional (`/cred learn`)
129
+
130
+ ```
131
+ cred.llm.enabled: true
132
+ /cred learn "la contraseña de fulano es qweasd123"
133
+ /cred confirm
134
+ /cred discard
135
+ ```
136
+
137
+ - El modelo solo propone `{name,value}`; nunca guarda solo.
138
+ - La respuesta no incluye el valor (solo nombre y longitud).
139
+ - Endpoint local por defecto; remoto solo con `cred.llm.allowRemote=true`.
140
+
141
+ ## Cómo se aplica
142
+
143
+ - `core/cred.ts`: índice en memoria, variantes redactadas (literal, URL-encoded,
144
+ base64, base64url, JSON-escaped), persistencia cifrada AES-256-GCM con la
145
+ misma clave que `redact` (o KDBX como backing).
146
+ - `core/kdbx.ts`: lectura/escritura KDBX vía `kdbxweb` + Argon2 `hash-wasm`.
147
+ - `redact.ts` suma los patrones de cred vía getter en cada redacción; un alta
148
+ nueva se aplica sin recompilar el motor.
149
+ - La restauración hacia herramientas sigue el camino normal de `redact`
150
+ (`tool.execute.before`).
package/docs/ENDPOINTS.md CHANGED
@@ -7,13 +7,18 @@ This module lets agents receive webhooks and publish local ports on public HTTPS
7
7
  ```
8
8
  Internet ─HTTPS─▶ OpenTunnel ─▶ apex daemon ─┬─ webhook listener (127.0.0.1) ── verify ──▶ POST events.ingest (local, Basic auth)
9
9
  <route>.<id>.opentunnel.xyz └─ route ──▶ any local port
10
- control API (127.0.0.1, token; never routed) ◀── plugin tools
10
+ control API (127.0.0.1, token; never routed) ◀── plugin tools, events.ingest forwards
11
+ MCP Events (127.0.0.1, own token; never routed) ◀── OpenCode automations (server "apex")
11
12
  ```
12
13
 
14
+ The MCP Events listener turns accepted `events.ingest` calls into `apex.event` triggers for
15
+ OpenCode automations; see [EVENTS.md](EVENTS.md#automations-apexevent-as-a-trigger-opencode--241).
16
+
13
17
  - **Why a daemon?** OpenCode unloads a directory's plugins after 60 minutes without activity, and a tunnel or listener inside the plugin dies with it.
14
18
  - The daemon is a separate process, **one per user**, and a lockfile keeps it that way.
15
19
  - The plugin launches it detached on the first `apex_webhook` / `apex_tunnel` call, and again on plugin load whenever its registry is not empty.
16
- - It exits after 10 minutes with nothing to keep.
20
+ - With the automations bridge on (the default), the plugin launches it on load and pings it every minute.
21
+ - It exits after 10 minutes with nothing to keep: no routes, no webhooks, no open event streams and no calls from a plugin or MCP client.
17
22
  - After a reboot, it comes back when apex loads in any project.
18
23
  - **Runtime:** OpenCode's own executable in bun mode (`BUN_BE_BUN=1`).
19
24
  - Nothing to install, and it runs on every platform OpenCode runs on.
@@ -38,6 +43,7 @@ They live in `<XDG_STATE_HOME or ~/.local/state>/opencode-apex/` on every OS. `A
38
43
  | `daemon.json` (0600) | pid, control port, control token, version |
39
44
  | `daemon.lock` | single-instance lock (pid) |
40
45
  | `registry.json` (0600) | tunnels, webhooks (with their secrets), how to reach each project's server |
46
+ | `mcp.json` (0600) | MCP Events port and token, reused across restarts so OpenCode's `apex` MCP entry stays valid |
41
47
  | `secrets/<hook>.secret` (0600) | each webhook's secret, for configuring the sender without pasting it |
42
48
  | `daemon.log` | daemon log |
43
49
 
@@ -47,6 +53,7 @@ They live in `<XDG_STATE_HOME or ~/.local/state>/opencode-apex/` on every OS. `A
47
53
  - Behind OpenTunnel, every request arrives from 127.0.0.1 with a `Host` the visitor chose. The webhook listener uses `Host` only to **select** a webhook; the signature decides.
48
54
  - Whatever you publish with `apex_tunnel` must authenticate its own requests: a random route is not authentication.
49
55
  - Webhook secrets are never returned by the tools, only `secretFile`.
56
+ - The MCP Events listener is loopback only, needs its own token (in OpenCode's MCP config and `mcp.json`, 0600) and serves only the `2026-07-28` protocol. It exposes no tools: it only streams events already accepted by `events.ingest`.
50
57
  - Publishing the OpenCode server's own port is refused. Use OpenCode remote access (`opencode service set remote true`), which has its own password.
51
58
 
52
59
  ## Network
@@ -60,5 +67,6 @@ After changing any of these, run `apex_daemon({action:"stop"})`; the next tool c
60
67
 
61
68
  ## Turning it off
62
69
 
63
- - `"modules": { "endpoints": false }` removes the tools, and the plugin no longer launches the daemon.
70
+ - `"modules": { "endpoints": false }` removes the tools and the automations bridge, and the plugin no longer launches the daemon.
71
+ - `"modules": { "automations": false }` keeps the tools but drops the `apex` MCP server; the daemon is then launched only for routes and webhooks.
64
72
  - `apex_daemon({action:"stop"})` stops a running daemon.
package/docs/EVENTS.md CHANGED
@@ -252,6 +252,48 @@ from the Internet, expose the relay (with its own token), never the OpenCode ser
252
252
  behind NAT needs the provider's outbound mode, a tunnel, a reverse connection or a public
253
253
  receiver that stores events for it: the skill's `references/reachability.md` compares them.
254
254
 
255
+ ## Automations: `apex.event` as a trigger (OpenCode ≥ 2.4.1)
256
+
257
+ OpenCode's **automations** (the `automation` tool) run a prompt, Code Mode or a shell command
258
+ on a timer (`at`, `every`, `cron`) or on an **MCP event**. They have no webhook or HTTP
259
+ trigger of their own, and that is the part apex fills: every event `events.ingest` accepts
260
+ (from a script, a relay or a verified `apex_webhook`) is also published on the MCP server
261
+ **`apex`**, which apex adds to this project's MCP config by itself.
262
+
263
+ | Need | Use |
264
+ | --- | --- |
265
+ | Something on a schedule: "every 5 minutes check X", "at 9:00 summarize Y" | an automation with `every` / `cron` (no external cron, no relay) |
266
+ | Something that happens outside: GitHub, Stripe, a chat, a monitor, a CI job | apex (`apex_webhook`, or a relay calling `events.ingest`) |
267
+ | …and react to it without a session listening | automation with trigger `{ type: "event", server: "apex", event: "apex.event" }` |
268
+ | …and wake a specific conversation | `apex_subscribe` (as before) |
269
+
270
+ Both paths receive the same events; use whichever fits. An automation trigger:
271
+
272
+ ```json
273
+ {
274
+ "type": "event",
275
+ "server": "apex",
276
+ "event": "apex.event",
277
+ "args": { "source": "github", "type": "pull_request.opened" }
278
+ }
279
+ ```
280
+
281
+ - `args` filters by exact `source` and `type`; both are optional. Any other argument is rejected.
282
+ - A `code` action gets the event as `input.event.data` = `{ id, source, type?, payload, receivedAt }`.
283
+ A `prompt` action gets it appended as untrusted data.
284
+ - Only this project's events: the MCP URL carries the project directory.
285
+ - If OpenCode was away, the automation resumes from its last cursor and the daemon replays what
286
+ it still has (the last 500 events in memory, at most one hour old by default). Events from
287
+ before a daemon restart are gone; the automation is told some may be missing (`truncated`).
288
+
289
+ How it works: the apex daemon (see [ENDPOINTS.md](ENDPOINTS.md)) serves an MCP server with the
290
+ Events extension (protocol `2026-07-28`) on 127.0.0.1, with its own token and a port that stays
291
+ the same across restarts (`mcp.json`). The plugin registers it as `apex` with
292
+ `{ type: "remote", protocol: "2026-07-28", oauth: false, codemode: false }` and forwards each
293
+ accepted `events.ingest` to it. While apex is loaded the daemon stays up (a ping every minute),
294
+ so automations can always be created. A server you named `apex` yourself takes precedence and
295
+ the bridge stays off. Turn it off with `"modules": { "automations": false }`.
296
+
255
297
  ## Tools
256
298
 
257
299
  - `apex_subscribe` — creates a subscription bound to the **calling session**.
package/endpoints.ts CHANGED
@@ -5,6 +5,9 @@
5
5
  * - apex_tunnel: un puerto local en una ruta del túnel OpenTunnel (open/list/close, TTL)
6
6
  * - apex_webhook: un webhook con firma verificada que despierta al agente (create/list/delete)
7
7
  * - apex_daemon: estado y parada del daemon
8
+ * - servidor MCP `apex` (automations): registra en OpenCode el servidor MCP Events del
9
+ * daemon y le reenvía cada events.ingest aceptado, para triggers
10
+ * `{ type: "event", server: "apex", event: "apex.event" }`
8
11
  *
9
12
  * El trabajo lo hace el daemon (un proceso por usuario, fuera del plugin, que OpenCode
10
13
  * descarga tras 60 min). Aquí solo se habla con él y se le dice cómo llegar al servidor
@@ -14,7 +17,9 @@
14
17
  import { Effect } from "effect"
15
18
  import type { Scope } from "effect"
16
19
  import type { Plugin } from "@opencode/plugin/effect"
17
- import { daemonPaths } from "./daemon/shared.js"
20
+ import { subscribe } from "./core/bus.js"
21
+ import { mcpPath } from "./daemon/mcp.js"
22
+ import { daemonPaths, type McpInfo } from "./daemon/shared.js"
18
23
  import { ensureDaemon, hasRegistryEntries, serverTarget, type DaemonClient } from "./core/daemon-client.js"
19
24
  import type { ServerEndpoint } from "./core/server-endpoint.js"
20
25
 
@@ -22,6 +27,35 @@ interface EndpointsInput {
22
27
  readonly version: string
23
28
  /** Del módulo events (null si está apagado: sin events, un webhook no despierta a nadie). */
24
29
  readonly endpoint: (() => ServerEndpoint) | null
30
+ /** Registrar el servidor MCP `apex` para las automations (modules.automations, requiere events). */
31
+ readonly automations: boolean
32
+ }
33
+
34
+ /** Nombre del servidor MCP en OpenCode (el `server` de los triggers de automations). */
35
+ export const MCP_SERVER = "apex"
36
+ const PING_MS = Number(process.env.APEX_MCP_PING_MS ?? 60_000)
37
+
38
+ /** Entrada MCP de OpenCode para el servidor Events del daemon, solo para este proyecto. */
39
+ export function mcpConfig(info: McpInfo, directory: string) {
40
+ return {
41
+ type: "remote" as const,
42
+ url: `http://127.0.0.1:${info.port}${mcpPath(directory)}`,
43
+ headers: { authorization: `Bearer ${info.token}` },
44
+ oauth: false as const,
45
+ // Sin tools: nada que pasar por Code Mode (y así no se añade ?codemode=false a la URL).
46
+ codemode: false,
47
+ // Events solo existe en 2026-07-28; sin "auto" no hay sondeo legacy que el daemon rechace.
48
+ protocol: "2026-07-28" as const,
49
+ }
50
+ }
51
+
52
+ /** Lo que el bus de apex lleva en `apex:event` (lo emite events.ts al aceptar un ingest). */
53
+ interface IngestedEvent {
54
+ eventID: string
55
+ source: string
56
+ type?: string
57
+ payload: Record<string, unknown>
58
+ location: string
25
59
  }
26
60
 
27
61
  type Args = Record<string, unknown>
@@ -63,12 +97,14 @@ export function register(ctx: Plugin.Context, input: EndpointsInput): Effect.Eff
63
97
 
64
98
  // Al cargar: si hay endpoints que mantener (p. ej. tras reiniciar el equipo), que el
65
99
  // daemon esté vivo. Sin registro no se lanza nada.
66
- if (hasRegistryEntries(paths)) {
100
+ if (hasRegistryEntries(paths) && !input.automations) {
67
101
  yield* Effect.promise(() =>
68
102
  daemon().catch((error) => console.warn(`[apex.endpoints] daemon: ${String((error as Error).message ?? error)}`)),
69
103
  )
70
104
  }
71
105
 
106
+ if (input.automations) yield* registerAutomationsBridge(ctx, daemon)
107
+
72
108
  const tool = (definition: {
73
109
  name: string
74
110
  description: string
@@ -219,3 +255,71 @@ export function register(ctx: Plugin.Context, input: EndpointsInput): Effect.Eff
219
255
  })
220
256
  })
221
257
  }
258
+
259
+ /**
260
+ * Puente con automations: el servidor MCP Events del daemon entra en la config MCP de
261
+ * OpenCode como `apex` (URL de este proyecto), y cada events.ingest aceptado aquí se le
262
+ * reenvía. Un ping periódico mantiene vivo el daemon mientras el plugin esté cargado (sin
263
+ * él, una automation no podría crearse: OpenCode comprueba el tipo de evento al crearla) y,
264
+ * si el daemon cambió de puerto o token, recarga la entrada MCP.
265
+ */
266
+ function registerAutomationsBridge(
267
+ ctx: Plugin.Context,
268
+ daemon: (spawn?: boolean) => Promise<DaemonClient>,
269
+ ): Effect.Effect<void, never, Scope.Scope> {
270
+ return Effect.gen(function* () {
271
+ const directory = ctx.location.directory
272
+ const warn = (what: string, error: unknown) =>
273
+ console.warn(`[apex.automations] ${what}: ${String((error as Error)?.message ?? error)}`)
274
+ // OpenCode < 2.1 no deja a los plugins tocar la config MCP.
275
+ const mcp = (ctx as { mcp?: Plugin.Context["mcp"] }).mcp
276
+ if (!mcp?.transform) {
277
+ warn("MCP bridge off", "this OpenCode has no ctx.mcp.transform")
278
+ return
279
+ }
280
+
281
+ const fetchInfo = () =>
282
+ daemon()
283
+ .then((client) => client.request<McpInfo>("GET", "/v1/mcp"))
284
+ .catch((error) => {
285
+ warn("daemon", error)
286
+ return null
287
+ })
288
+ let info = yield* Effect.promise(fetchInfo)
289
+ let shadowed = false
290
+
291
+ yield* mcp.transform((editor) => {
292
+ if (!info) return
293
+ // Un `apex` puesto a mano en la config del usuario manda.
294
+ if (editor.get(MCP_SERVER)) {
295
+ if (!shadowed) warn("MCP bridge off", `an MCP server named "${MCP_SERVER}" is already configured`)
296
+ shadowed = true
297
+ return
298
+ }
299
+ editor.set(MCP_SERVER, mcpConfig(info, directory) as never)
300
+ })
301
+
302
+ // Reenvío: el bus es de proceso y lo comparten todos los directorios cargados.
303
+ const forwarding = subscribe<IngestedEvent>("apex:event", (event) => {
304
+ const ingested = event.payload
305
+ if (ingested.location !== directory) return
306
+ void daemon()
307
+ .then((client) =>
308
+ client.request("POST", "/v1/events", {
309
+ directory,
310
+ event: { id: ingested.eventID, source: ingested.source, type: ingested.type, payload: ingested.payload },
311
+ }),
312
+ )
313
+ .catch((error) => warn("forward event", error))
314
+ })
315
+ yield* Effect.addFinalizer(() => Effect.sync(() => forwarding.unsubscribe()))
316
+
317
+ yield* Effect.gen(function* () {
318
+ yield* Effect.sleep(`${PING_MS} millis`)
319
+ const next = yield* Effect.promise(fetchInfo)
320
+ if (!next || (next.port === info?.port && next.token === info?.token)) return
321
+ info = next
322
+ yield* mcp.reload()
323
+ }).pipe(Effect.forever, Effect.forkScoped)
324
+ })
325
+ }
package/index.ts CHANGED
@@ -35,7 +35,7 @@ import { registerTempAccess } from "./core/temp-access.js"
35
35
  import { register as registerEndpoints } from "./endpoints.js"
36
36
 
37
37
  // Plugin version
38
- const VERSION = "0.5.0"
38
+ const VERSION = "0.8.0"
39
39
 
40
40
  interface ModuleConfigs {
41
41
  redact: RedactConfig & { enabled: boolean }
@@ -52,7 +52,13 @@ interface ModuleConfigs {
52
52
  function getModuleConfigs(userConfig: ApexConfig): ModuleConfigs {
53
53
  return {
54
54
  redact: { ...createDefaultRedactConfig(), ...userConfig.redact, enabled: userConfig.modules?.redact ?? true },
55
- cred: { ...createDefaultCredConfig(), ...userConfig.cred, enabled: userConfig.modules?.cred ?? true },
55
+ cred: {
56
+ ...createDefaultCredConfig(),
57
+ ...userConfig.cred,
58
+ llm: { ...createDefaultCredConfig().llm, ...userConfig.cred?.llm },
59
+ kdbx: { ...createDefaultCredConfig().kdbx, ...userConfig.cred?.kdbx },
60
+ enabled: userConfig.modules?.cred ?? true,
61
+ },
56
62
  events: { ...createDefaultEventsConfig(), ...userConfig.events, enabled: userConfig.modules?.events ?? true } as ModuleConfigs["events"],
57
63
  advisor: { ...createDefaultAdvisorConfig(), ...userConfig.advisor, enabled: userConfig.modules?.advisor ?? true },
58
64
  // Opt-in: sin reglas no hace nada útil, y con reglas mal puestas bloquea al
@@ -169,7 +175,12 @@ export default Plugin.define({
169
175
 
170
176
  // Túneles y webhooks verificados, vía el daemon de apex.
171
177
  if (validatedConfig.modules?.endpoints ?? true) {
172
- yield* registerEndpoints(ctx, { version: VERSION, endpoint: events?.endpoint ?? null })
178
+ yield* registerEndpoints(ctx, {
179
+ version: VERSION,
180
+ endpoint: events?.endpoint ?? null,
181
+ // Servidor MCP `apex` para triggers de automations; se alimenta de events.ingest.
182
+ automations: events !== null && (validatedConfig.modules?.automations ?? true),
183
+ })
173
184
  }
174
185
 
175
186
  if (moduleConfigs.browser.enabled) {
@@ -42,7 +42,9 @@
42
42
  // external_directory without asking in <tmpdir>/opencode (OpenCode's temp dir)
43
43
  "tempAccess": true,
44
44
  // Túneles OpenTunnel y webhooks verificados (daemon de apex, solo al usarlos)
45
- "endpoints": true
45
+ "endpoints": true,
46
+ // Servidor MCP `apex` (MCP Events): events.ingest como trigger de automations de OpenCode
47
+ "automations": true
46
48
  },
47
49
 
48
50
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-apex",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Modular plugin for OpenCode V2 (>= 2.1): secret redaction, RPC callbacks/webhooks/watchers that wake agents, OpenTunnel endpoints + verified webhooks (cross-platform daemon), tools.run, AI permission advisor, guard meta-permissions, temp-directory access",
5
5
  "license": "MIT",
6
6
  "author": "Antonio Orizondo Leyva",
@@ -53,19 +53,23 @@
53
53
  "LICENSE"
54
54
  ],
55
55
  "dependencies": {
56
- "@opencode/plugin": "^2.1.1",
57
- "@opencode/plugin-browser": "^2.1.1",
56
+ "@modelcontextprotocol/server": "2.4.0",
57
+ "@opencode/plugin": "^2.4.3",
58
+ "@opencode/plugin-browser": "^2.4.3",
58
59
  "@opentunnel/client": "^0.7.0",
60
+ "hash-wasm": "^4.12.0",
59
61
  "jsonc-parser": "^3.3.1",
62
+ "kdbxweb": "^2.1.1",
60
63
  "ws": "^8.22.0",
61
64
  "zod": "^3.24.0"
62
65
  },
63
66
  "devDependencies": {
64
- "typescript": "^5.5.0",
65
- "bun-types": "^1.1.0"
67
+ "@modelcontextprotocol/client": "2.4.0",
68
+ "bun-types": "^1.1.0",
69
+ "typescript": "^5.5.0"
66
70
  },
67
71
  "scripts": {
68
- "test": "bun test/events.test.ts && bun test/guard.test.ts && bun test/process-context.test.ts && bun test/temp-access.test.ts && bun test/endpoints.test.ts && bun test/cred.test.ts && bun test/advisor-session.test.ts",
72
+ "test": "bun test/events.test.ts && bun test/guard.test.ts && bun test/process-context.test.ts && bun test/temp-access.test.ts && bun test/endpoints.test.ts && bun test/automations.test.ts && bun test/cred.test.ts && bun test/advisor-session.test.ts",
69
73
  "typecheck": "tsc --noEmit -p .",
70
74
  "check:install": "node scripts/check-install.mjs",
71
75
  "prepublishOnly": "npm test && npm run typecheck && npm run check:install"
@@ -28,6 +28,13 @@ Three pieces. Only the last one lives inside OpenCode:
28
28
  | **Relay (pull)** | always on | holding an outbound connection: WebSocket, SSE, long-poll, IMAP IDLE, queue consumer | messaging, email, chat bots, event streams |
29
29
  | **Relay (webhook)** | always on, listening on a port | the service calls it over HTTP | GitHub, Stripe, n8n, forms |
30
30
 
31
+ **OpenCode ≥ 2.4.1 has automations** (the `automation` tool). Prefer them over writing a program when you can:
32
+
33
+ - **Schedules and checks** ("every 5 minutes, is X up?", "at 9:00 do Y"): an automation with `every` / `cron` and a `code` or `prompt` action. No watcher, no crontab, no `events.ingest`.
34
+ - **Something outside happens** (webhook, chat, monitor): apex is still the way in (`apex_webhook`, or a relay calling `events.ingest`). To react without a session listening, create an automation with trigger `{ "type": "event", "server": "apex", "event": "apex.event", "args": { "source": "<source>" } }`; it receives `{ id, source, type, payload, receivedAt }`. To wake a specific conversation, `apex_subscribe` as below.
35
+
36
+ The `apex` MCP server is added by apex itself (unless `modules.automations` is off); details in `docs/EVENTS.md`.
37
+
31
38
  ## Step 0 — Where do I point? (ask, do not guess)
32
39
 
33
40
  Call **`apex_callback_endpoint`**. It returns: