opencode-apex 0.2.1 → 0.2.2

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.
@@ -1,232 +1,267 @@
1
1
  # Troubleshooting — opencode-apex
2
2
 
3
- Guía de diagnóstico para errores de carga y ejecución del plugin. Creada tras el incidente del 2026-09-23 (plugin no cargaba en OpenCode v1).
3
+ > **OpenCode V2 only (2.1 or newer).** OpenCode V1 has a different plugin system
4
+ > (`@opencode-ai/plugin`, config key `plugin`). apex is written for V2 (`@opencode/plugin`,
5
+ > config key `plugins`) and cannot load on V1. That is not a bug.
4
6
 
5
- ---
7
+ This page has two parts:
6
8
 
7
- ## 1. Matriz de compatibilidad — LÉELA ANTES DE TOCAR IMPORTS
9
+ - [Troubleshooting](#troubleshooting): symptom → cause → fix, for anyone using apex.
10
+ - [Developer notes](#developer-notes): gotchas for people changing apex's code.
8
11
 
9
- | | OpenCode v1 (≤1.x) | OpenCode v2 (≥2.0) |
10
- |---|---|---|
11
- | **Paquete SDK** | `@opencode-ai/plugin` | `@opencode/plugin` |
12
- | **API de entrada** | `plugin(input, options) => Promise<Hooks>` | `Plugin.define({ id, setup(ctx) })` |
13
- | **Subrutas** | `.`, `./tool`, `./tui` | `.`, `./effect`, `./promise/*`, `./tui`, ... |
14
- | **Contexto** | `PluginInput` (client, project, directory, $) | `ctx.rpc/storage/session/tool/event/permission/...` |
15
- | **Este plugin** | ❌ NO carga | ✅ Diseñado para esto |
12
+ ## Before you start: where to look
16
13
 
17
- **Regla de oro**: este plugin está escrito contra la API **v2** (`@opencode/plugin`, tag `v2.0.14`). Si el host es v1, el plugin **no puede cargar** — no es un bug del plugin.
14
+ | What | Where |
15
+ | --- | --- |
16
+ | OpenCode version | `opencode --version` (the desktop app ships the same CLI, e.g. `/opt/OpenCode/resources/opencode-cli` on Linux) |
17
+ | Server log (plugin loading, apex warnings) | `~/.local/share/opencode/log/opencode.log`. For a foreground server, `opencode serve --print-logs`. |
18
+ | Installed copy of apex | `~/.cache/opencode/npm/opencode-apex@<spec>/<generation>/node_modules/opencode-apex` |
18
19
 
19
- ### Cómo saber qué versión corre tu binario
20
+ Useful log searches:
20
21
 
21
22
  ```bash
22
- opencode --version # v1.18.32 = v1 (SDK @opencode-ai/plugin)
23
- cat .opencode/node_modules/@opencode-ai/plugin/package.json | grep version # si existe → host v1
24
- npm view @opencode/plugin version # 2.0.14 = SDK v2 (existe en npm)
23
+ grep -a "failed to load plugin" ~/.local/share/opencode/log/opencode.log | tail
24
+ grep -a "\[apex" ~/.local/share/opencode/log/opencode.log | tail
25
25
  ```
26
26
 
27
- ### Síntoma exacto en el log (host v1 cargando plugin v2)
27
+ On every load apex logs a `[apex] config: inline=… global=… local=…` line, which says
28
+ which config sources it found.
28
29
 
29
- ```
30
- ~/.local/share/opencode/log/opencode.log:
31
- level=WARN message="failed to load plugin" target=<plugin-dir>
32
- cause="Cannot find package '@opencode/plugin' imported from <plugin>/index.ts"
33
- ```
30
+ ---
34
31
 
35
- Si ves `Cannot find package '@opencode/plugin'` → el host es v1. Soluciones:
36
- - **A (recomendada)**: ejecutar v2 desde el repo (`cd opencode-v2 && bun install && bun run dev`)
37
- - **B**: `mv .opencode/plugins/apex .opencode/plugins/apex.disabled` para silenciarlo en v1
32
+ # Troubleshooting
38
33
 
39
- ---
34
+ ## The plugin does not load
40
35
 
41
- ## 2. Cómo ejecutar v2 desde el repo
36
+ **Symptom:** apex tools such as `apex_subscribe` do not exist, and the log shows
37
+ `failed to load plugin … target=opencode-apex`.
42
38
 
43
- ```bash
44
- cd opencode-v2
45
- bun install # la primera vez (tarda; usar pty si la red es lenta)
46
- bun run dev # TUI dev
47
- bun run dev:live [dir] # TUI contra el server electo (preferido para testing)
48
- bun run --cwd packages/cli src/index.ts serve --port <port> # server headless
49
- ```
39
+ | Cause in the log | Fix |
40
+ | --- | --- |
41
+ | `Cannot find package '@opencode/plugin'`, or OpenCode reports a 1.x version | You are on OpenCode V1. Upgrade to V2 (2.1+). |
42
+ | `Schema.isStartsWith is not a function`, `missing TypeId`, or other errors from inside `effect` | Two copies of the `effect` library are mixed (see next section). Force a reinstall. |
43
+ | `Plugin must export a default definition…` | You pointed `package` at a file. Point it at the plugin **directory** or at the npm name `opencode-apex`. |
44
+ | `Plugin entrypoint not found` | The path in `package` is wrong, or the directory has no `index.ts`. |
50
45
 
51
- Verificación de carga del plugin: arranca el server y grep del log:
46
+ ## Version mismatch with OpenCode (`effect`)
52
47
 
53
- ```bash
54
- grep -i "apex\|failed to load plugin" ~/.local/share/opencode/log/opencode.log | tail
55
- ```
48
+ apex is written with the [`effect`](https://effect.website) library, and so is OpenCode.
49
+ Every `@opencode/plugin` release pins one exact version of `effect`: 4.0.0-rc.112 up to
50
+ 2.0.x, 4.0.1 in 2.1. If apex ran on a *different* copy than `@opencode/plugin`, values
51
+ created by one copy would not be recognized by the other, and loading fails with errors
52
+ from deep inside `effect`.
56
53
 
57
- ---
54
+ **How apex avoids it (since 0.2.0):**
58
55
 
59
- ## 3. Gotchas de bun (aprendidos por las malas)
56
+ 1. apex does **not** declare its own `effect` version. `effect` is an **optional peer
57
+ dependency** (`^4.0.0`), satisfied by the copy `@opencode/plugin` brings, so npm
58
+ installs **one** copy and it always matches OpenCode.
59
+ 2. `@opencode/plugin` and `@opencode/plugin-browser` use caret ranges (`^2.1.1`), so a fresh
60
+ install follows OpenCode 2.x releases.
61
+ 3. On load, apex warns (`[apex] …` in the log) when it finds two copies of `effect`, or
62
+ when OpenCode is a newer minor version than the `@opencode/plugin` installed with
63
+ apex.
64
+ 4. Before every publish, `scripts/check-install.mjs` installs the package the way
65
+ OpenCode does and refuses to publish if it finds more than one copy of `effect`.
60
66
 
61
- ### 3.1 `bun -e` resuelve imports bare relativo al CWD, no al archivo importado
67
+ **The one thing you have to do yourself:** OpenCode caches installed plugins and **does
68
+ not refresh them on its own**. After upgrading OpenCode, or to move to a new apex
69
+ release, force a reinstall:
62
70
 
63
- ```bash
64
- # FALLA/cuelga desde la raíz del repo (no encuentra 'effect'):
65
- bun -e "await import('/abs/path/plugin/module.ts')"
66
- # OK — ejecutar desde el directorio del plugin (ahí resuelve node_modules):
67
- cd .opencode/plugins/apex && bun -e "await import('./index.ts')"
68
- ```
71
+ 1. Stop OpenCode: `opencode service stop` for the background service, or close the app.
72
+ 2. Delete the cached copy: `rm -rf ~/.cache/opencode/npm/opencode-apex@*`.
73
+ 3. Start OpenCode again. The first time a directory is used, it installs apex again
74
+ (this takes a few seconds).
69
75
 
70
- ### 3.2 `bun add`/`bun install` se cuelga si una dep no existe en npm
76
+ In OpenCode 2.1.1, `opencode plugin update` only manages **TUI** plugins (those in
77
+ `cli.json`). For apex it answers `Plugin is not configured`, so use the steps above.
71
78
 
72
- Si `package.json` referencia un paquete inexistente (ej. `@opencode/plugin` cuando el host es v1 y el registry no lo tiene cacheado), el install puede colgarse sin output. Diagnóstico: `npm view <pkg> version` primero; si no existe, no intentes `bun add`.
79
+ A breaking OpenCode 3.x is deliberately **not** covered by the `^2` ranges: it would need
80
+ code changes, not just new dependencies.
73
81
 
74
- ### 3.3 Re-exports de tipos: bun ESM es estricto
82
+ ## RPC calls fail
75
83
 
76
- ```ts
77
- // ❌ FALLA en runtime bun: "export 'ApexBus' not found" (ApexBus es type-only)
78
- export { apexBus, ApexBus } from "./bus"
84
+ apex's RPC methods are HTTP endpoints of the OpenCode server:
79
85
 
80
- // ✅ Separar valor y tipo:
81
- export { apexBus } from "./bus"
82
- export type { ApexBus } from "./bus"
83
86
  ```
87
+ POST <server>/api/rpc/apex/<method>?location%5Bdirectory%5D=<url-encoded project dir>
88
+ Authorization: Basic <base64 of "opencode:<server password>">
89
+ Content-Type: application/json
84
90
 
85
- ### 3.4 Symlinks obsoletos de node_modules
91
+ {"input": { … }}
92
+ ```
86
93
 
87
- Un `node_modules` symlink a un directorio temporal de tests (ej. `/tmp/...`) provoca errores `Not a directory` en el log del server y rompe la resolución. Antes de diagnosticar carga: `ls -la .opencode/plugins/*/node_modules` y eliminar symlinks ajenos.
94
+ The `apex_callback_endpoint` tool prints the exact URLs, and tells you where the
95
+ password is stored, for the current project.
96
+
97
+ | Response | Cause | Fix |
98
+ | --- | --- | --- |
99
+ | `401 Unauthorized` | No or wrong Basic auth | Username `opencode`, plus the server password (see `apex_callback_endpoint` → `auth.password`). |
100
+ | `rpc.unavailable` — "RPC is unavailable: apex" | apex is not loaded **in the directory you targeted**: it failed to load (see above), it is configured only for another project, or the location parameter is wrong | Check the log. Use `location[directory]=…` (URL-encoded `location%5Bdirectory%5D=`). `?directory=` is **ignored**. |
101
+ | The call works but acts on the wrong project | The location parameter was missing or misspelled, so the server used its **default** directory | Same fix: always send `location[directory]`. |
102
+ | `rpc.invalid_input` — e.g. `Missing key at ["payload"]` | The body does not match the method | The body must be `{"input": {…}}`. `events.ingest` needs `source` and `payload`; `tools.run` needs `tool`. |
103
+ | `rpc.unavailable` with apex **0.1.x** | 0.1.x registered its RPC under the wrong key and never worked on OpenCode 2.1 | Upgrade apex (see the reinstall steps). |
104
+ | `events.ingest` returns an `error` about the events module being disabled | `modules.events` is `false` | Turn the module on. |
105
+
106
+ ## `events.ingest` succeeds but nobody wakes up
107
+
108
+ `{"accepted": true, "delivered": []}` means the event was received but **no subscription
109
+ matched it**.
110
+
111
+ - Check the subscription's `filters` against the event's `type` and `source`.
112
+ - A subscription with an empty `sessionID` is bound to the project's **main session**
113
+ (the root session you opened). If that session was deleted, there is nothing to
114
+ deliver to until a new root session appears. For long-running automations, give the
115
+ subscription an explicit `sessionID`.
116
+ - `deliverAs: "synthetic"` with `resume: false` only *stores* the message; the agent
117
+ reads it on its next turn. Use `deliverAs: "prompt"`, or `resume: true`, to wake it.
118
+ - Re-sending the same `eventID` within 5 minutes is deduplicated on purpose: the second
119
+ call returns `delivered: []`.
120
+
121
+ ## Automations stop after an hour, or after a restart
122
+
123
+ This is expected OpenCode V2 behavior, not an apex bug. OpenCode loads plugins **per
124
+ project directory** and **unloads** a directory's plugins after **60 minutes without
125
+ session activity** there. The value is fixed in OpenCode 2.1.1. After a restart, nothing
126
+ is loaded until something uses that directory.
127
+
128
+ So nothing that runs *inside* the plugin survives on its own: timers, open ports,
129
+ watchers. apex 0.2.0 removed its HTTP listener for exactly this reason. What does
130
+ survive is the **RPC**: the server waits for the directory's plugins and loads them if
131
+ needed, as part of the call itself.
132
+
133
+ **Rule:** keep the clock (cron, systemd timer) and the door (webhook relay, n8n)
134
+ **outside** OpenCode, and have them call the RPC. The bundled `apex-callbacks` skill
135
+ explains the pattern step by step.
136
+
137
+ ## The first call is slow
138
+
139
+ - **First use after installing or upgrading:** OpenCode downloads apex and its
140
+ dependencies from npm. Expect 20–30 s once.
141
+ - **First call to a directory that is not loaded** (idle unload or restart): the server
142
+ loads every plugin of that directory first, about 5 s. Later calls are fast.
143
+ - Scripts should use generous timeouts and retry with backoff on that first call.
144
+
145
+ ## `tools.run` fails
146
+
147
+ | `error` | Cause | Fix |
148
+ | --- | --- | --- |
149
+ | `tool denied for tools.run (events.tools.deny): …` | The tool matches `events.tools.deny` (`question`, `subagent`, `execute` and `apex_*` by default) | Adjust `events.tools.deny` if you really need it. |
150
+ | `tool not in events.tools.allow: …` | The tool is not in `events.tools.allow` | Add it, or a glob such as `easypanel_*`. |
151
+ | `tool not registered in this project: …` | No tool with that exact id in this project, e.g. an MCP server not enabled there | Use the exact tool id as the agent sees it (MCP tools are usually `<server>_<tool>`). |
152
+ | `timed out after … ms` | The permission check answered "ask" and nobody approved it | Add an `allow` rule for that action to the agent in `events.tools.agent` (default `build`), or enable the apex advisor. |
153
+ | A generic message such as `Unable to write …` | The tool ran but was blocked by a permission rule (`deny`) or failed | Check that agent's permissions, and the log. |
154
+ | `tools.run is disabled (events.tools.enabled=false)` | Turned off in config | Set `events.tools.enabled: true`. |
155
+
156
+ ## Configuration does not seem to apply
157
+
158
+ apex merges three sources. Each one overrides the previous:
159
+
160
+ 1. `~/.config/opencode/opencode-apex.jsonc` — global file
161
+ 2. the `options` object of the apex entry in `opencode.json` — global and project
162
+ `opencode.json` are already merged by OpenCode
163
+ 3. `<project>/.opencode/opencode-apex.jsonc` — project file
164
+
165
+ - The `[apex] config: inline=… global=… local=…` log line shows which ones were found.
166
+ - An invalid config is reported (`[apex] … inválida`) and apex falls back to defaults.
167
+ - Keys that no longer exist are ignored with a warning: `events.enabled` (use
168
+ `modules.events`), `events.listener` (removed in 0.2.0).
169
+ - Modules are switched on and off **only** in `modules` (`"modules": { "guard": true }`).
170
+ - Config is read when the plugin loads: after editing, restart OpenCode or wait for the
171
+ directory to reload.
172
+
173
+ ## The browser tools say "No desktop browser is connected"
174
+
175
+ See [BROWSER.md](BROWSER.md): a session only gets a browser after `browser_target` or
176
+ `/browser-target` asks for one.
88
177
 
89
178
  ---
90
179
 
91
- ## 4. Puntos ciegos del LSP — el runtime es la única verdad
180
+ # Developer notes
92
181
 
93
- El LSP **NO detecta** estos errores (reportaba 0 errores con el plugin roto):
182
+ ## Running a local checkout
94
183
 
95
- 1. **Imports de exports inexistentes cross-file** (`import { apexSnapshot } from "./core/snapshot.js"` cuando el export no existe).
96
- 2. **Re-exports type-only en cláusula de valor** (ver 3.3).
184
+ Point OpenCode at the plugin **directory** (not a file):
97
185
 
98
- **Protocolo de verificación obligatorio antes de dar un módulo por terminado:**
99
-
100
- ```bash
101
- cd .opencode/plugins/apex
102
- bun -e "await import('./index.ts'); console.log('OK')" # smoke de carga real
186
+ ```jsonc
187
+ // opencode.json
188
+ { "plugins": [{ "package": "/path/to/opencode-apex" }] }
103
189
  ```
104
190
 
105
- Verificación de carga obligatoria (sustituye al antiguo harness de `/tmp`):
191
+ Then, in that directory:
106
192
 
107
193
  ```bash
108
- bun -e "await import('./index.ts'); console.log('OK')" # smoke de carga real
109
- bun x tsc --noEmit # typecheck
110
- bun test test/guard.test.ts # guard
111
- TEST_CDP_URL=<puerto> bun test test/browser.test.ts # browser (Chromium headless en ese puerto)
194
+ bun install
195
+ npm run typecheck # tsc --noEmit
196
+ npm test # events + guard suites
197
+ npm run check:install # install like OpenCode does: one effect copy, plugin imports
198
+ bun -e "await import('./index.ts'); console.log('OK')" # load smoke test
199
+ TEST_CDP_URL=9333 bun test test/browser.test.ts # needs a Chromium with CDP on that port
112
200
  ```
113
201
 
114
- ---
115
-
116
- ## 5. Dependencias runtime del plugin
117
-
118
- `package.json` del plugin declara:
119
-
120
- | Dep | Uso |
121
- |---|---|
122
- | `effect` | Efectos/Scope del runtime `@opencode/plugin/effect` |
123
- | `zod` | Validación de config (core/config.ts) |
124
- | `jsonc-parser` | Parseo de la config (JSONC + `#`) |
125
- | `ws` | Cliente CDP del módulo browser (browser/cdp.ts) |
126
- | `@opencode/plugin-browser` | Protocolo `browser.*` (schemas Browser, RPC del host) |
127
-
128
- Si añades un import runtime nuevo a cualquier módulo → añádelo a `package.json` y re-ejecuta el smoke. Los `import type` no necesitan esto (se borran en runtime).
129
-
130
- ### 5.1 Config ausente NO debe crashear el setup() (incidente 2026-09-23)
131
-
132
- `loadConfig()` lanzaba ENOENT si el fichero de config no existía en el directorio del proyecto → `setup()` fallaba completo → el plugin no cargaba aunque todo lo demás estuviera bien. **Fix aplicado**: fichero ausente → defaults del schema (`apexConfigSchema.parse({})`); fichero corrupto → throw (el manager last-good lo gestiona).
133
-
134
- **Regla**: un plugin SIEMPRE debe arrancar sin configuración. Los defaults viven en el schema Zod (`core/config.ts`, cada campo con `.default()`). Si añades un campo nuevo al schema, dale `.default()` — nunca hagas un campo requerido en el nivel raíz.
135
-
136
- Verificación de los 3 caminos de config:
137
-
138
- ```bash
139
- cd .opencode/plugins/apex && bun -e "
140
- const { loadConfig } = await import('./core/config.ts');
141
- console.log(await loadConfig('/tmp/no-existe.jsonc')); // -> defaults, sin throw
142
- console.log(await loadConfig('<proyecto>/.opencode/opencode-apex.jsonc')); // -> config real
143
- "
144
-
145
- ---
146
-
147
- ## 6. Checklist para nuevos módulos del plugin
148
-
149
- - [ ] Imports solo desde `@opencode/plugin` (v2) — nunca `@opencode-ai/plugin`
150
- - [ ] `bun -e "await import('./<modulo>.ts')"` pasa desde el dir del plugin
151
- - [ ] Exports usados por otros módulos existen (grep cruzado, no confiar en LSP)
152
- - [ ] Re-exports de tipos separados (`export type {...}`)
153
- - [ ] Deps runtime añadidas a package.json
154
- - [ ] Smoke `bun -e "import('./index.ts')"` + `tsc --noEmit` + suites del módulo pasan
155
- - [ ] Sin `as any` / `@ts-ignore` nuevos
156
- - [ ] Sin `globalThis` hacks (usar exports de módulo)
157
-
158
- ---
159
-
160
- ## 7. Historial del incidente (2026-09-23)
161
-
162
- - **Síntoma**: `failed to load plugin ... Cannot find package '@opencode/plugin'` (err_8eabfefe y similares) para apex y claude-hooks.
163
- - **Causa**: binario host v1.18.32 con SDK v1; plugin escrito contra API v2. Además, symlink node_modules obsoleto causaba errores secundarios.
164
- - **Fix aplicado**: eliminado symlink; deps instaladas en el plugin (`bun install`); verificado `import('./index.ts')` OK con SDK real npm (`@opencode/plugin@2.0.14`).
165
- - **Pendiente**: QA end-to-end con server v2 del repo (requiere `bun install` en opencode-v2).
166
-
167
- ## Incidente 4 (2026-09-23): "disabled plugin after transform failure" — ast._tag
168
-
169
- - **Síntoma**: `WARN disabled plugin after transform failure plugin.id=apex state=tool cause="Die(TypeError: undefined is not an object (evaluating 'ast._tag'))"`
170
- - **Causa**: los tools definían `input`/`output` con `Schema.Struct` de `effect` importado desde el node_modules del plugin. El server valida el schema con SU copia bundled de effect; la instancia del plugin no se reconoce como `Schema.Codec` → `.ast` undefined → `ast._tag` TypeError.
171
- - **Fix**: usar **JSON Schema plano** para `input` de los tools (contrato oficial, ver `packages/core/test/plugin/promise-tool.test.ts`): `{ type: "object", properties: {...}, additionalProperties: false }`. `output` es opcional → omitido. `execute` devuelve `{ output: <data> }` (shape `Tool.Result`).
172
- - **Regla**: NUNCA importar `effect` en el plugin. Los schemas de tools van en JSON Schema plano. `Tool.Context` SÍ tiene `sessionID`.
173
-
174
- ## Migración a la API Effect-native (2026-09-23)
175
-
176
- - **Motivo**: la API promise acumulaba fallos de contrato (rpc 1-arg, tool execute Promise, ast._tag). La doc oficial (https://opencode.ai/v2/docs/build/plugins/effect/) usa `Plugin.define({ id, effect })` de `@opencode/plugin/effect`.
177
- - **CRÍTICO — versión de effect**: `@opencode/plugin` trae su propia versión exacta de effect (rc.112 hasta 2.0.x, **4.0.1 desde 2.1**). Si apex usa otra, los tipos `Effect` chocan por el brand TypeId ("missing TypeID") o, en ejecución, el código de `@opencode/schema` cae sobre la copia equivocada (`Schema.isStartsWith is not a function`). **Desde 0.2.0 la regla es estructural**, ver "Versiones de effect" abajo.
178
- - **API Effect 4 (no 3)**: `Effect.catch` (no catchAll), `Effect.andThen` (no zipRight), `Effect.promise`, `Stream.tap/runDrain/forkScoped`.
179
- - **Conversión aplicada**: los 5 módulos (redact, events, advisor, guard, browser) + core exportan `register(ctx: Plugin.Context, config): Effect<void, never, Scope>`; registros con `yield* ctx.tool.transform(...)`, `yield* ctx.session.hook(...)`, `yield* ctx.permission.hook(...)`; cleanup vía `Effect.addFinalizer`. Storage/session bridges con `Effect.runPromise` en helpers async.
180
- - **tsconfig**: `skipLibCheck: true`; `cli/` excluido (herramienta WIP con `commander` no instalado).
181
- - **Verificación**: `tsc --noEmit` 0 errores; `bun -e "import('./index.ts')"` → plugin id "apex".
182
-
183
- ## Auditoría independiente (2026-09-24): hallazgos y fixes
184
-
185
- - **CRÍTICO/latente — clave persistida sin lectura** (`core/crypto.ts`): `generatePersistedKey()` escribía `~/.config/opencode/apex.key` pero nada lo leía; tras un reinicio sin env/config se generaba OTRA clave y los marcadores previos quedaban huérfanos (no restaurables). Fix: `readPersistedKey()` valida 32 bytes base64 y `resolveKey` la reutiliza.
186
- - **ALTO — path traversal en plantillas** (`core/templates.ts`): `resolveTemplatePath` rechazaba absolutas pero no `../`. Como además se lee (contenido → prompt del agente) y se escribe (`mkdir -p` + defaults), era una primitiva de lectura/escritura fuera de proyecto/home, alcanzable desde `apex_subscribe`. Fix: normalización + contención dentro del base dir (semántica POSIX y win32).
187
- - **MEDIO — tool advisor fail-open** (`core/advisor-tool.ts`): `decision` inválida se coaccionaba a `"allow"`. Fix: validación estricta (lanza). Además `requestID` era predecible (`req_<ts>_<counter>`) y la tool es visible para todos los agentes → ahora `req_<randomUUID()>`.
188
- - **MEDIO — `#` en `/* */` rompía el parseo** (`core/config.ts`): el stripper cortaba en el `#` aunque estuviera dentro de un bloque, dejando `/**/`... (válido pero frágil) — reescrito con máquina de 4 estados (string, line-comment, block-comment, normal) que preserva bloques.
189
- - **BAJO — contrato RPC honestista** (`core/rpc.ts`): eliminados `module.toggled`/`profile.switched` (declarados, nunca emitidos). `IngestInput.sessionID` eliminado (declarado en tipo+RPC+skill, nunca leído).
190
- - **BAJO — comentarios obsoletos**: header de `index.ts` (módulos eliminados), `(con caché)` en `resolveTemplate`, campo muerto `validate` en `Hit`.
191
- - **BAJO — `advisor.location` relativa**: se resuelve contra el cwd del proceso (antes se pasaba tal cual y el server podía rechazarla).
192
-
193
- ## 2026-10-02: eliminación del módulo webprovider
194
-
195
- - **Motivo**: `webprovider` (hub WebSocket + extensión de Chromium para modelos web)
196
- se confundía con el módulo `browser` (tools `browser.*` contra CDP), que es el
197
- control de navegador del plugin.
198
- - **Quitado**: `webprovider.ts`, `core/web/`, `extension/`, `docs/WEBPROVIDER.md`,
199
- sus suites (`test/webprovider-concurrency.test.ts`, `test/ledger-identity.test.ts`),
200
- config (`apexConfigSchema.webprovider`, `modules.webprovider`) y dep `@ai-sdk/provider`.
201
- - **Copia de seguridad** (el repo no usa git): `/tmp/opencode/opencode-apex-webprovider-removed/`.
202
- - **Verificación**: `tsc --noEmit` y `--noUnusedLocals` a 0; browser 10/10, guard 56/56;
203
- `bun -e "import('./index.ts')"` → plugin `apex`.
204
-
205
- ## Versiones de effect: cómo no volver a desalinearlas (0.2.0)
206
-
207
- - **Síntoma (2026-10-23)**: con OpenCode 2.1.1, el apex local no cargaba:
208
- `failed to load plugin … Schema.isStartsWith is not a function`.
209
- - **Causa**: apex fijaba `"effect": "4.0.0-rc.112"` y pedía `@opencode/plugin: "latest"`.
210
- Desde 2.1, `@opencode/plugin` usa effect **4.0.1**. Cada versión de OpenCode puede subirlo
211
- de nuevo, así que un pin propio se desalinea tarde o temprano.
212
- - **Solución (cuatro piezas)**:
213
- 1. **Sin versión propia de effect.** `effect` es `peerDependency` **opcional** (`^4.0.0`).
214
- npm no instala una copia aparte: el `import "effect"` de apex resuelve a la que trae
215
- `@opencode/plugin`, que queda única en `node_modules`. La versión sigue sola a OpenCode.
216
- 2. **Rangos caret** para `@opencode/plugin` y `@opencode/plugin-browser` (`^2.1.1`): siguen
217
- las versiones 2.x de OpenCode. Ni `latest` ni versión exacta.
218
- 3. **Aviso al cargar** (`core/compat.ts`), en el log del servidor y en la consola:
219
- - si apex y `@opencode/plugin` resuelven copias distintas de effect;
220
- - si OpenCode (`ctx.app.version`) es de un minor más nuevo que el `@opencode/plugin`
221
- instalado. Pasa tras actualizar OpenCode, porque la caché npm de plugins no se
222
- refresca sola.
223
- En ambos casos, la solución es reinstalarlo (ver abajo).
224
- 4. **`prepublishOnly` → `scripts/check-install.mjs`**: empaqueta, instala como OpenCode
225
- (npm, `--ignore-scripts`) en un directorio temporal y falla si hay más de una copia de
226
- effect o si el plugin no se importa. Una dependencia desalineada no llega a publicarse.
227
- - **Tras actualizar OpenCode** (o para pasar a una apex nueva): con OpenCode parado, borra
228
- `~/.cache/opencode/npm/opencode-apex@*` y arráncalo. Reinstala apex con el
229
- `@opencode/plugin` nuevo. En 2.1.1, `opencode plugin update` responde
230
- `Plugin is not configured` para los plugins de servidor: solo gestiona los de TUI (`cli.json`).
231
- - **Rotura de API (OpenCode 3.x)**: el rango `^2` no la absorbe a propósito. Eso exige
232
- revisar el código, no solo las dependencias.
202
+ `prepublishOnly` runs `test`, `typecheck` and `check:install`. A misaligned dependency
203
+ cannot be published.
204
+
205
+ To watch the plugin load, run a throwaway server in the foreground:
206
+ `opencode serve --port 4096 --print-logs --log-level info`.
207
+
208
+ ## Rules that keep apex loading
209
+
210
+ - **V2 imports only:** `@opencode/plugin` and `@opencode/plugin/effect`, never the V1
211
+ package `@opencode-ai/plugin`.
212
+ - **No own `effect` version** (see the version mismatch section above). Import `effect`
213
+ freely for control flow, but never declare it as a regular dependency.
214
+ - **Tool and RPC schemas are plain JSON Schema**, not `Schema.Struct` from `effect`.
215
+ OpenCode validates them with its own `effect`. A schema object built by another copy
216
+ is not recognized, and the plugin is disabled with
217
+ `undefined is not an object (evaluating 'ast._tag')`.
218
+ - **The RPC definition needs an `id`** (`{ id: "apex", methods, events }`). OpenCode
219
+ registers RPCs by `id`.
220
+ - **The plugin must start with no configuration at all.** A missing config file means
221
+ defaults, and every field of the Zod schema in `core/config.ts` has a `.default()`.
222
+ Never add a required top-level field.
223
+ - **No per-directory state at module level.** The module is imported once per process
224
+ and registered once per directory, so mutable state belongs inside `register()`.
225
+ - **The event bus is global.** `ctx.event.subscribe()` delivers events from every
226
+ directory. Filter session events by `event.location.directory`.
227
+
228
+ ## Effect 4, not 3
229
+
230
+ The API names changed: `Effect.catch` (not `catchAll`), `Effect.andThen` (not
231
+ `zipRight`), `Effect.promise`, `Stream.tap` / `Stream.runDrain` / `Effect.forkScoped`.
232
+ Each module exports `register(ctx, config): Effect<…, never, Scope>`. Registrations use
233
+ `yield* ctx.tool.transform(…)`, `ctx.session.hook(…)` or `ctx.permission.hook(…)`, and
234
+ cleanup goes in `Effect.addFinalizer`.
235
+
236
+ ## Bun quirks
237
+
238
+ - **`bun -e` resolves bare imports from the current directory**, not from the imported
239
+ file. Run smoke tests from the plugin directory, or `effect` will not be found.
240
+ - **`bun install` can hang silently** when `package.json` references a package that does
241
+ not exist on npm. Check with `npm view <pkg> version` first.
242
+ - **Type-only re-exports must be marked:** `export { apexBus, ApexBus }` fails at run time
243
+ if `ApexBus` is a type. Write `export { apexBus }` plus `export type { ApexBus }`.
244
+ - **Stale `node_modules` symlinks** (for example to a temporary test directory) cause
245
+ `Not a directory` errors when loading. Remove them before debugging anything else.
246
+
247
+ ## The editor will not catch these — the runtime will
248
+
249
+ The TypeScript language server reported zero errors on builds that failed to load:
250
+
251
+ 1. importing a name that another file does not export;
252
+ 2. type-only re-exports in a value position (see above).
253
+
254
+ Always run the load smoke test and `npm run typecheck` before calling a change done.
255
+
256
+ ## Checklist for a new module
257
+
258
+ - [ ] Imports only from `@opencode/plugin` (V2)
259
+ - [ ] `bun -e "await import('./<module>.ts')"` passes from the plugin directory
260
+ - [ ] Names imported from other modules really exist (grep, do not trust the editor)
261
+ - [ ] Type re-exports use `export type { … }`
262
+ - [ ] New runtime dependencies are in `package.json`, and `npm run check:install` passes
263
+ - [ ] Tool and RPC schemas are JSON Schema
264
+ - [ ] No module-level per-directory state; events filtered by directory
265
+ - [ ] Config fields have defaults; the module is switched by `modules.<name>`
266
+ - [ ] `npm test` and `npm run typecheck` pass
267
+ - [ ] No new `as any`, `@ts-ignore` or `globalThis` hacks
package/events.ts CHANGED
@@ -279,11 +279,13 @@ export function resolveTemplate(
279
279
  return subscription.promptTemplate
280
280
  }
281
281
 
282
- function renderPromptTemplate(template: string, event: InternalEvent): string {
282
+ export function renderPromptTemplate(template: string, event: InternalEvent): string {
283
283
  return template
284
284
  .replace(/\{\{eventID\}\}/g, event.eventID)
285
285
  .replace(/\{\{source\}\}/g, event.source)
286
286
  .replace(/\{\{type\}\}/g, event.type ?? "")
287
+ // `{{payload}}` a secas: el payload entero en JSON (lo usa la plantilla por defecto).
288
+ .replace(/\{\{payload\}\}/g, () => JSON.stringify(event.payload))
287
289
  .replace(/\{\{payload\.([^}]+)\}\}/g, (_match, path) => {
288
290
  const value = path.split(".").reduce((acc: unknown, key: string) => {
289
291
  return (acc as Record<string, unknown>)?.[key]
@@ -450,21 +452,21 @@ function registerCallbackEndpointTool(
450
452
  editor.add({
451
453
  name: "apex_callback_endpoint",
452
454
  description:
453
- "Devuelve cómo alcanza un proceso externo (script, cron, systemd, n8n, relay de webhooks) a ESTE " +
454
- "servidor de OpenCode: URL base, URLs RPC de apex para este directorio (events.ingest para notificar " +
455
- "eventos que despiertan a un agente, tools.run para ejecutar herramientas de OpenCode), auth Basic y " +
456
- "de dónde leer el password, y ejemplos curl. Úsala antes de escribir cualquier script o bucle externo.",
455
+ "Returns how an external program (script, cron, systemd, n8n, webhook relay) reaches THIS OpenCode " +
456
+ "server: base URL, the apex RPC URLs for this project (events.ingest to notify events that wake an " +
457
+ "agent, tools.run to run OpenCode tools), Basic auth and where to read the password (never the " +
458
+ "password itself), plus curl examples. Call it before writing any external script or loop.",
457
459
  input: { type: "object", properties: {}, additionalProperties: false },
458
460
  output: {
459
461
  type: "object",
460
462
  properties: {
461
- baseUrl: { type: ["string", "null"], description: "URL base del servidor (local)" },
462
- source: { type: ["string", "null"], description: "De dónde salió baseUrl: config | service | argv" },
463
- publicUrl: { type: ["string", "null"], description: "URL para emisores de otras máquinas (túnel/proxy)" },
464
- directory: { type: "string", description: "Valor de location[directory] de cada llamada" },
465
- auth: { type: "object", description: "Basic opencode:<password>; password.shell lo imprime" },
466
- rpc: { type: "object", description: "URLs completas: ingest, toolsRun, status, ping" },
467
- examples: { type: "object", description: "curl listos para ingest y toolsRun" },
463
+ baseUrl: { type: ["string", "null"], description: "Server base URL, as reachable from this machine" },
464
+ source: { type: ["string", "null"], description: "Where baseUrl came from: config | service | argv" },
465
+ publicUrl: { type: ["string", "null"], description: "URL for senders on other machines (tunnel/proxy)" },
466
+ directory: { type: "string", description: "Value of location[directory] for every call" },
467
+ auth: { type: "object", description: "Basic opencode:<password>; password says where it is, password.shell prints it" },
468
+ rpc: { type: "object", description: "Full URLs: ingest, toolsRun, status, ping" },
469
+ examples: { type: "object", description: "Ready-to-run curl for ingest and toolsRun" },
468
470
  hint: { type: "string" },
469
471
  },
470
472
  additionalProperties: true,
@@ -506,15 +508,15 @@ function registerSetCallbackUrlTool(
506
508
  editor.add({
507
509
  name: "apex_set_callback_url",
508
510
  description:
509
- "Fija (o limpia) la URL pública por la que procesos de OTRAS máquinas alcanzan este servidor de " +
510
- "OpenCode — p. ej. la de un túnel (cloudflared/ngrok) que apunta a su URL base. Queda persistida y " +
511
- "aparece en apex_callback_endpoint. Usa null para limpiarla. Precedencia: runtime > config.",
511
+ "Sets (or clears) the public URL through which programs on OTHER machines reach this OpenCode " +
512
+ "server, e.g. a tunnel (cloudflared/ngrok) pointing at its base URL. It is persisted and shown by " +
513
+ "apex_callback_endpoint. Pass null to clear it. Precedence: runtime > config.",
512
514
  input: {
513
515
  type: "object",
514
516
  properties: {
515
517
  url: {
516
518
  type: ["string", "null"],
517
- description: "URL pública base del servidor (p. ej. https://x.trycloudflare.com) o null para limpiar",
519
+ description: "Public base URL of the server (e.g. https://x.trycloudflare.com) or null to clear",
518
520
  },
519
521
  },
520
522
  required: ["url"],
@@ -569,8 +571,8 @@ function registerSubscribeTool(ctx: Plugin.Context): Effect.Effect<void, never,
569
571
  additionalProperties: false,
570
572
  },
571
573
  },
572
- agent: { type: "string", description: "Restrict subscription to an agent" },
573
- promptTemplate: { type: "string", description: "Inline prompt template with {{payload.x}}, {{source}}, {{type}}, {{eventID}} placeholders" },
574
+ agent: { type: "string", description: "Agent to switch the target session to before delivering (the switch persists)" },
575
+ promptTemplate: { type: "string", description: "Inline prompt template with {{payload}}, {{payload.x}}, {{source}}, {{type}}, {{eventID}} placeholders" },
574
576
  promptTemplateFile: { type: "string", description: "Path to a prompt template file (takes priority over promptTemplate)" },
575
577
  deliverAs: { type: "string", enum: ["synthetic", "prompt"], description: "Deliver as synthetic message or user prompt (default prompt)" },
576
578
  resume: { type: "boolean", description: "Synthetic only: wake the agent loop so the model processes the message (default false = passive)" },
@@ -674,7 +676,10 @@ function registerUnsubscribeTool(ctx: Plugin.Context): Effect.Effect<void, never
674
676
  }
675
677
 
676
678
  /** Tool: apex_list_subscriptions — list all subscriptions (static marked readonly) */
677
- function registerListSubscriptionsTool(ctx: Plugin.Context): Effect.Effect<void, never, Scope.Scope> {
679
+ function registerListSubscriptionsTool(
680
+ ctx: Plugin.Context,
681
+ staticSubscriptions: EventSubscription[],
682
+ ): Effect.Effect<void, never, Scope.Scope> {
678
683
  return Effect.gen(function* () {
679
684
  yield* ctx.tool.transform((editor) => {
680
685
  editor.add({
@@ -690,7 +695,8 @@ function registerListSubscriptionsTool(ctx: Plugin.Context): Effect.Effect<void,
690
695
  },
691
696
  execute: () =>
692
697
  Effect.promise(async () => {
693
- const subscriptions = await loadSubscriptions(ctx)
698
+ // Las de config (readonly: true) primero, igual que en la entrega.
699
+ const subscriptions = [...staticSubscriptions, ...(await loadSubscriptions(ctx))]
694
700
  return { output: { subscriptions } }
695
701
  }),
696
702
  })
@@ -850,7 +856,7 @@ export function register(
850
856
  // Register tools
851
857
  yield* registerSubscribeTool(ctx)
852
858
  yield* registerUnsubscribeTool(ctx)
853
- yield* registerListSubscriptionsTool(ctx)
859
+ yield* registerListSubscriptionsTool(ctx, staticSubscriptions)
854
860
 
855
861
  // Dirección del servidor: se resuelve en cada consulta (el servicio puede haber
856
862
  // reescrito su registro tras un reinicio).
@@ -874,7 +880,7 @@ export function register(
874
880
 
875
881
  const current = endpoint()
876
882
  console.log(
877
- `[Apex Events] Event system initialized · RPC ${current.baseUrl ?? "(URL del servidor desconocida)"} · ` +
883
+ `[Apex Events] Event system initialized · RPC ${current.baseUrl ?? "(server URL unknown)"} · ` +
878
884
  `tools.run ${eventsConfig.tools.enabled ? `on (agente ${eventsConfig.tools.agent})` : "off"}`,
879
885
  )
880
886
 
package/index.ts CHANGED
@@ -26,7 +26,7 @@ import { registerSkills } from "./core/skills.js"
26
26
  import { compatibilityWarnings } from "./core/compat.js"
27
27
 
28
28
  // Plugin version
29
- const VERSION = "0.2.1"
29
+ const VERSION = "0.2.2"
30
30
 
31
31
  interface ModuleConfigs {
32
32
  redact: RedactConfig & { enabled: boolean }
@@ -46,7 +46,14 @@ function getModuleConfigs(userConfig: ApexConfig): ModuleConfigs {
46
46
  advisor: { ...createDefaultAdvisorConfig(), ...userConfig.advisor, enabled: userConfig.modules?.advisor ?? true },
47
47
  // Opt-in: sin reglas no hace nada útil, y con reglas mal puestas bloquea al
48
48
  // agente, así que se activa a mano.
49
- guard: { ...createDefaultGuardConfig(), ...userConfig.guard, enabled: userConfig.modules?.guard ?? false },
49
+ // `agents` se mezcla por agente: la config validada siempre trae `agents: {}` y,
50
+ // con un spread plano, borraba las reglas por defecto de apex-advisor.
51
+ guard: {
52
+ ...createDefaultGuardConfig(),
53
+ ...userConfig.guard,
54
+ agents: { ...createDefaultGuardConfig().agents, ...userConfig.guard?.agents },
55
+ enabled: userConfig.modules?.guard ?? false,
56
+ },
50
57
  // Activado por defecto; en modo `external` puede abrir un popup de Chrome por conexión.
51
58
  browser: {
52
59
  ...createDefaultBrowserConfig(),