opencode-apex 0.5.1 → 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 ADDED
@@ -0,0 +1,150 @@
1
+ # Cred — `/cred` + `apex_cred`
2
+
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
+
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`
14
+
15
+ ```
16
+ /cred help # manual completo (también /cred sin argumentos)
17
+ /cred set <nombre>=<valor>
18
+ /cred set <nombre> <valor|uri>
19
+ /cred set <nombre> --from-env VAR
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>
24
+ /cred list
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
29
+ ```
30
+
31
+ Notas:
32
+
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).
47
+
48
+ ## KDBX (KeePassXC / KeePass)
49
+
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.
53
+
54
+ ```jsonc
55
+ {
56
+ "cred": {
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 }
68
+ },
69
+ "modules": { "cred": true }
70
+ }
71
+ ```
72
+
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/docs/REDACT.md CHANGED
@@ -120,6 +120,11 @@ The key comes from `redact.key`. apex resolves it in this order:
120
120
 
121
121
  ## Detectors and bundles
122
122
 
123
+ Regex-based: detects by shape (`ghp_…`, `AKIA…`…), not by content. A loose password or an
124
+ opaque token won't match. For secrets you want masked by exact value, see
125
+ [docs/CRED.md](CRED.md) (`/cred set`) — those literals feed this same engine as extra
126
+ patterns, applied live without a restart.
127
+
123
128
  apex ships **104 detectors in 41 bundles**:
124
129
 
125
130
  - 58 are copied from **opencode-warden**;
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
@@ -3,6 +3,8 @@
3
3
  *
4
4
  * Modules:
5
5
  * - redact: Secret detection (regex), encryption-based redaction, restore on tool input
6
+ * - cred: `/cred` command — user-declared secrets (literal match, no guessing), works
7
+ * with or without a local model (`/cred set` vs. optional `/cred learn`)
6
8
  * - events: RPC event ingestion (callbacks/webhooks), subscriptions, delivery, tools.run
7
9
  * - advisor: allow/deny permission decisions via a dedicated agent + side session
8
10
  * - guard: meta-permissions per agent/tool/path (opt-in)
@@ -21,6 +23,7 @@ import { homedir } from "node:os"
21
23
  import { loadApexConfig, loadConfig, type ApexConfig } from "./core/config.js"
22
24
  import { emit as busEmit } from "./core/bus.js"
23
25
  import { register as registerRedact, createDefaultRedactConfig, type RedactConfig } from "./redact.js"
26
+ import { register as registerCred, createDefaultCredConfig, type CredConfig } from "./cred.js"
24
27
  import { register as registerEvents, createDefaultEventsConfig, type EventsConfig } from "./events.js"
25
28
  import { register as registerAdvisor, createDefaultAdvisorConfig, type AdvisorConfig } from "./advisor.js"
26
29
  import { register as registerGuard, createDefaultGuardConfig, type GuardConfigShape } from "./guard.js"
@@ -32,10 +35,11 @@ import { registerTempAccess } from "./core/temp-access.js"
32
35
  import { register as registerEndpoints } from "./endpoints.js"
33
36
 
34
37
  // Plugin version
35
- const VERSION = "0.5.0"
38
+ const VERSION = "0.8.0"
36
39
 
37
40
  interface ModuleConfigs {
38
41
  redact: RedactConfig & { enabled: boolean }
42
+ cred: CredConfig & { enabled: boolean }
39
43
  events: EventsConfig & { enabled: boolean }
40
44
  advisor: AdvisorConfig & { enabled: boolean }
41
45
  guard: GuardConfigShape & { enabled: boolean }
@@ -48,6 +52,13 @@ interface ModuleConfigs {
48
52
  function getModuleConfigs(userConfig: ApexConfig): ModuleConfigs {
49
53
  return {
50
54
  redact: { ...createDefaultRedactConfig(), ...userConfig.redact, enabled: userConfig.modules?.redact ?? 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
+ },
51
62
  events: { ...createDefaultEventsConfig(), ...userConfig.events, enabled: userConfig.modules?.events ?? true } as ModuleConfigs["events"],
52
63
  advisor: { ...createDefaultAdvisorConfig(), ...userConfig.advisor, enabled: userConfig.modules?.advisor ?? true },
53
64
  // Opt-in: sin reglas no hace nada útil, y con reglas mal puestas bloquea al
@@ -136,6 +147,12 @@ export default Plugin.define({
136
147
  yield* registerRedact(ctx, moduleConfigs.redact)
137
148
  }
138
149
 
150
+ // Independiente de redact: expone `/cred` y suma sus literales al motor
151
+ // de redacción vía el singleton de core/cred.ts (getActiveCredStore).
152
+ if (moduleConfigs.cred.enabled) {
153
+ yield* registerCred(ctx, moduleConfigs.cred)
154
+ }
155
+
139
156
  const events = moduleConfigs.events.enabled ? yield* registerEvents(ctx, validatedConfig) : null
140
157
 
141
158
  // ANTES del advisor, y el orden es funcional, no estético: el host recorre
@@ -158,7 +175,12 @@ export default Plugin.define({
158
175
 
159
176
  // Túneles y webhooks verificados, vía el daemon de apex.
160
177
  if (validatedConfig.modules?.endpoints ?? true) {
161
- 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
+ })
162
184
  }
163
185
 
164
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.5.1",
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",
@@ -37,6 +37,7 @@
37
37
  "files": [
38
38
  "index.ts",
39
39
  "redact.ts",
40
+ "cred.ts",
40
41
  "events.ts",
41
42
  "daemon",
42
43
  "endpoints.ts",
@@ -52,19 +53,23 @@
52
53
  "LICENSE"
53
54
  ],
54
55
  "dependencies": {
55
- "@opencode/plugin": "^2.1.1",
56
- "@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",
57
59
  "@opentunnel/client": "^0.7.0",
60
+ "hash-wasm": "^4.12.0",
58
61
  "jsonc-parser": "^3.3.1",
62
+ "kdbxweb": "^2.1.1",
59
63
  "ws": "^8.22.0",
60
64
  "zod": "^3.24.0"
61
65
  },
62
66
  "devDependencies": {
63
- "typescript": "^5.5.0",
64
- "bun-types": "^1.1.0"
67
+ "@modelcontextprotocol/client": "2.4.0",
68
+ "bun-types": "^1.1.0",
69
+ "typescript": "^5.5.0"
65
70
  },
66
71
  "scripts": {
67
- "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",
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",
68
73
  "typecheck": "tsc --noEmit -p .",
69
74
  "check:install": "node scripts/check-install.mjs",
70
75
  "prepublishOnly": "npm test && npm run typecheck && npm run check:install"
package/redact.ts CHANGED
@@ -23,6 +23,7 @@ import type { Plugin } from "@opencode/plugin/effect"
23
23
  import { compilePatterns, DEFAULT_BUNDLES, type PatternDefinition } from "./core/patterns.js"
24
24
  import { createRedactEngine, type RedactEngine } from "./core/redact.js"
25
25
  import { resolveKey } from "./core/crypto.js"
26
+ import { getActiveCredStore } from "./core/cred.js"
26
27
  import type { RedactConfig } from "./core/config.js"
27
28
 
28
29
  export type { RedactConfig }
@@ -74,8 +75,10 @@ export function compileRedactConfig(config: RedactConfig): CompiledRedact {
74
75
  const { key, source, fingerprint } = resolveKey(config.key)
75
76
  console.info(`[apex.redact] Clave cargada (source=${source}, fp=${fingerprint}), ${patterns.length} patrones activos`)
76
77
 
78
+ // Getter: suma los literales de `/cred` (core/cred.ts) en cada redacción,
79
+ // sin recompilar el motor cuando se da de alta un secreto nuevo.
77
80
  const engine = createRedactEngine({
78
- patterns,
81
+ patterns: () => [...patterns, ...(getActiveCredStore()?.patterns() ?? [])],
79
82
  allowlist,
80
83
  prefix: config.prefix,
81
84
  suffix: config.suffix,
@@ -105,13 +108,14 @@ export function register(
105
108
 
106
109
  // Motores precompilados para el RPC (evita recompilar y re-resolver la clave
107
110
  // en cada llamada).
111
+ const rpcPatterns = () => [...patterns, ...(getActiveCredStore()?.patterns() ?? [])]
108
112
  const rpcEngines = {
109
113
  strict: createRedactEngine({
110
- patterns, allowlist, prefix: config.prefix, suffix: config.suffix,
114
+ patterns: rpcPatterns, allowlist, prefix: config.prefix, suffix: config.suffix,
111
115
  key, mode: "strict", onFinding: (f) => rpcFindings.push({ pattern: f.pattern }),
112
116
  }),
113
117
  warn: createRedactEngine({
114
- patterns, allowlist, prefix: config.prefix, suffix: config.suffix,
118
+ patterns: rpcPatterns, allowlist, prefix: config.prefix, suffix: config.suffix,
115
119
  key, mode: "warn", onFinding: (f) => rpcFindings.push({ pattern: f.pattern }),
116
120
  }),
117
121
  }
@@ -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: