opencode-apex 0.2.0 → 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.
package/README.md CHANGED
@@ -1,184 +1,334 @@
1
1
  # opencode-apex
2
2
 
3
- **Plugin modular para OpenCode V2** — redacción de secretos por cifrado, eventos con
4
- suscripciones, decisiones de permiso mediante una sesión advisor dedicada, meta-permisos
5
- (guard) y tools `browser.*` contra un Chromium externo por CDP.
3
+ **A modular plugin for [OpenCode](https://opencode.ai) V2** that adds:
4
+ - secret redaction;
5
+ - event-driven automations (callbacks, webhooks, scheduled watchers that wake an agent up);
6
+ - AI-assisted permission decisions;
7
+ - per-agent meta-permissions;
8
+ - `browser.*` tools driven by your own Chromium.
9
+
10
+ > [!IMPORTANT]
11
+ > **OpenCode V2 only (OpenCode ≥ 2.1).** apex is written against the V2 plugin runtime
12
+ > (`Plugin.define` from `@opencode/plugin/effect`). It does **not** load in OpenCode V1, and
13
+ > versions of OpenCode V2 older than 2.1 are not supported. Check yours with
14
+ > `opencode --version`.
15
+
16
+ ---
17
+
18
+ ## Contents
19
+
20
+ - [What is this, in plain words](#what-is-this-in-plain-words)
21
+ - [Modules](#modules)
22
+ - [Requirements](#requirements)
23
+ - [Install](#install)
24
+ - [Update / reinstall](#update--reinstall)
25
+ - [Configuration](#configuration)
26
+ - [Automations: waking an agent from outside](#automations-waking-an-agent-from-outside)
27
+ - [Calling apex over RPC](#calling-apex-over-rpc)
28
+ - [Tools added to your agents](#tools-added-to-your-agents)
29
+ - [RPC reference](#rpc-reference)
30
+ - [Security notes](#security-notes)
31
+ - [Troubleshooting](#troubleshooting)
32
+ - [Development](#development)
33
+ - [License](#license)
34
+
35
+ ---
36
+
37
+ ## What is this, in plain words
38
+
39
+ A few OpenCode terms used throughout these docs:
40
+
41
+ | Term | What it means |
42
+ | --- | --- |
43
+ | **OpenCode server** | OpenCode is a client/server app. The TUI, the desktop app and `opencode run` all talk to a local **server** process over HTTP. The desktop app starts it as a background *service*; `opencode serve` starts one by hand. |
44
+ | **Plugin** | A package the server loads to add features: new tools, agents, permission logic, skills… You list plugins in `opencode.json` and OpenCode installs them from npm. |
45
+ | **Session** | One conversation with an agent. |
46
+ | **Agent** | A configured assistant (`build`, `plan`, your own…) with its own model, prompt and permissions. |
47
+ | **Tool** | Something an agent can call: `read`, `shell`, `edit`, MCP tools, browser tools… |
48
+ | **Skill** | A Markdown guide an agent can load when a task needs it. apex ships one. |
49
+ | **RPC** | Here, an **authenticated HTTP POST to the OpenCode server** that runs a method a plugin registered: `POST <server>/api/rpc/apex/<method>`. It lets scripts and other programs talk to apex. |
50
+
51
+ apex is one plugin with five independent modules. Each one can be switched on or off.
52
+
53
+ ## Modules
54
+
55
+ | Module | What it does | Default | Docs |
56
+ | --- | --- | --- | --- |
57
+ | **Redact** | Detects secrets (API keys, tokens, private keys…) in what the agent sees, encrypts them (AES-256-GCM) and replaces them with a readable marker. When the agent passes the marker back to a tool, the real value is restored. 41 bundles / 104 patterns. | on | [docs/REDACT.md](docs/REDACT.md) |
58
+ | **Events** | Lets programs outside OpenCode (scripts, cron jobs, webhooks, n8n…) notify an agent. **Subscriptions** decide which session receives what. `tools.run` lets those programs use OpenCode tools. | on | [docs/EVENTS.md](docs/EVENTS.md) |
59
+ | **Advisor** | When a tool call needs permission ("ask"), a small dedicated agent decides `allow` or `deny`, so you aren't asked about every step. | on | [docs/ADVISOR.md](docs/ADVISOR.md) |
60
+ | **Guard** | Meta-permissions per agent, tool and path, with a report of what was attempted and decided. | **off** | [docs/GUARD.md](docs/GUARD.md) |
61
+ | **Browser** | Serves OpenCode's `browser.*` tools against an **external** Chromium over CDP (local or remote). You can also switch to the desktop app's built-in browser. 45 actions. | on | [docs/BROWSER.md](docs/BROWSER.md) |
62
+
63
+ Turn modules on or off in `modules`. That is the only switch: there is no `<module>.enabled`.
6
64
 
7
- API **Effect-native** (`Plugin.define({ id, effect })` de `@opencode/plugin/effect`).
65
+ ```jsonc
66
+ "modules": { "redact": true, "events": true, "advisor": true, "guard": false, "browser": true }
67
+ ```
68
+
69
+ ## Requirements
8
70
 
9
- ## Módulos
71
+ - **OpenCode ≥ 2.1** (V2). Nothing else: OpenCode downloads the plugin and its dependencies
72
+ itself.
73
+ - For the automation examples, a shell with `curl` and `sed`.
74
+ - Optional: Chromium/Chrome for the Browser module, and `bun` if you want to hack on apex.
10
75
 
11
- | Módulo | Qué hace | Doc |
12
- | ----------- | ----------------------------------------------------------------------------------------- | ------------------------- |
13
- | **Redact** | Detecta secretos por regex, los cifra (AES-256-GCM) y los sustituye por un marcador legible. Restaura en el input de las tools | [docs/REDACT.md](docs/REDACT.md) |
14
- | **Events** | Callbacks, webhooks y vigilancias: ingesta de eventos por RPC, filtros por suscripción y entrega como prompt o mensaje sintético; `tools.run` para que un proceso externo use herramientas de OpenCode | [docs/EVENTS.md](docs/EVENTS.md) |
15
- | **Advisor** | Decide `allow`/`deny` sobre el uso de herramientas usando un agente y una sesión laterales | [docs/ADVISOR.md](docs/ADVISOR.md) |
16
- | **Guard** | Meta-permisos por agente, herramienta y ruta, con informe. El `deny` que la config no puede declarar sin romper el toolset | [docs/GUARD.md](docs/GUARD.md) |
17
- | **Browser** | Sirve las tools `browser.*` contra un Chromium **externo** por CDP, local o remoto. Elige entre navegador externo y el de la app de escritorio | [docs/BROWSER.md](docs/BROWSER.md) |
76
+ ## Install
18
77
 
19
- Activación por módulo en `modules` (fuente única, no existe `<modulo>.enabled`):
78
+ Add apex to the `plugins` list of your OpenCode config:
79
+ - global: `~/.config/opencode/opencode.json`, applies to every project;
80
+ - project: `opencode.json` at the project root.
20
81
 
21
82
  ```jsonc
22
- "modules": { "redact": true, "events": true, "advisor": false, "guard": false, "browser": true }
83
+ {
84
+ "$schema": "https://opencode.ai/config.json",
85
+ "plugins": [
86
+ {
87
+ "package": "opencode-apex",
88
+ "options": {
89
+ "modules": { "redact": true, "events": true, "advisor": true, "guard": false, "browser": true }
90
+ }
91
+ }
92
+ ]
93
+ }
23
94
  ```
24
95
 
25
- ## Instalación
96
+ Restart OpenCode (close and reopen the desktop app, or `opencode service restart`). The first
97
+ time a project uses apex, OpenCode installs it from npm. That takes a few seconds; the first
98
+ request may fail while the install finishes, so retry it.
26
99
 
27
- Desde npm, en `opencode.json` (OpenCode instala el paquete y sus dependencias):
100
+ **Check that it loaded:** ask an agent to call `apex_callback_endpoint`, or see
101
+ [Calling apex over RPC](#calling-apex-over-rpc) → `apex/status`.
102
+
103
+ ## Update / reinstall
104
+
105
+ OpenCode caches installed plugins and **does not refresh them on its own**. In OpenCode 2.1,
106
+ `opencode plugin update` only handles TUI plugins, so for apex:
107
+
108
+ 1. Stop OpenCode (close the app, or `opencode service stop`).
109
+ 2. Delete apex's cache entry: `rm -rf ~/.cache/opencode/npm/opencode-apex@*`
110
+ 3. Start OpenCode again. It reinstalls the latest apex with matching dependencies.
111
+
112
+ Do this **after upgrading OpenCode** too. apex warns in the server log if its dependencies no
113
+ longer match the running OpenCode.
114
+
115
+ ## Configuration
116
+
117
+ apex reads its settings from three places, merged in this order (later wins):
118
+
119
+ | # | Source | Scope |
120
+ | - | --- | --- |
121
+ | 1 | `~/.config/opencode/opencode-apex.jsonc` | global file |
122
+ | 2 | `options` of the plugin entry in `opencode.json` (OpenCode merges global + project) | inline |
123
+ | 3 | `<project>/.opencode/opencode-apex.jsonc` | project file |
124
+
125
+ - Comments are allowed: `//`, `/* */` and `#`.
126
+ - Environment variables can be referenced inside values. See [docs/CONFIG.md](docs/CONFIG.md)
127
+ for the exact syntax, every key and its default.
128
+ - [`opencode-apex.jsonc`](opencode-apex.jsonc) is a fully commented template.
129
+
130
+ ## Automations: waking an agent from outside
131
+
132
+ Typical request to an agent:
133
+
134
+ > *"Check every 5 minutes whether server X is up; if it goes down, diagnose it."*
135
+
136
+ With apex the agent sets this up itself:
28
137
 
29
- ```jsonc
30
- "plugins": [{ "package": "opencode-apex", "options": { "modules": { "events": true } } }]
138
+ ```
139
+ cron / systemd timer ──▶ watcher script ──(needs an OpenCode tool? apex/tools.run)──▶ OpenCode
140
+ │
141
+ └─ condition met? ──(apex/events.ingest)──▶ subscription ──▶ agent wakes up
31
142
  ```
32
143
 
33
- En desarrollo, apunta por ruta de directorio (`"package": "/ruta/a/opencode-apex"`) y `bun install` en él.
144
+ 1. **Subscribe.** The agent calls `apex_subscribe`: "when an event of type `server.down`
145
+ arrives, send this session a prompt: *diagnose it*".
146
+ 2. **Watch.** The agent writes a small script and schedules it with a systemd timer or cron.
147
+ The script checks the server. If the check needs something that only exists inside
148
+ OpenCode (an MCP tool, the browser…), it calls `apex/tools.run`. No model is involved and
149
+ no tokens are spent.
150
+ 3. **Notify.** When the state changes, the script calls `apex/events.ingest`. The
151
+ subscription delivers the prompt and the agent starts working.
34
152
 
35
- Requiere OpenCode **≥ 2.1**. Tras actualizar OpenCode, `opencode plugin update`: la caché
36
- npm de plugins no se refresca sola, y apex avisa al cargar si quedó desalineado.
153
+ Why the clock lives **outside** OpenCode: OpenCode unloads a project's plugins after **60
154
+ minutes without session activity**, and after a restart it doesn't load them until something
155
+ uses that project. A timer or HTTP listener inside a plugin would silently stop. An RPC call,
156
+ on the other hand, loads the project on demand. The first call after an idle period takes a
157
+ few seconds.
37
158
 
38
- ## Configuración
159
+ **Webhooks** work the same way, with one extra piece. A service such as GitHub or Stripe calls a
160
+ small **relay** (n8n, or the ~30-line Node relay in the bundled skill). The relay turns that HTTP
161
+ call into `apex/events.ingest`. OpenCode itself doesn't expose a webhook URL.
39
162
 
40
- Dos canales y jerarquía (ver [docs/CONFIG.md](docs/CONFIG.md)):
163
+ apex registers a skill, **`apex-callbacks`**, that teaches agents the whole recipe:
164
+ - discovering the server URL;
165
+ - subscribing;
166
+ - a stateful watcher script;
167
+ - systemd and cron;
168
+ - the webhook relay and n8n;
169
+ - `tools.run`.
41
170
 
42
- | # | Fuente | Nivel |
43
- | - | ----------------------------------------------------- | ----------- |
44
- | 1 | Fichero global `~/.config/opencode/opencode-apex.jsonc` | global-file |
45
- | 2 | `options` del plugin en `opencode.json` | inline |
46
- | 3 | Fichero local `<proyecto>/.opencode/opencode-apex.jsonc` | local-file |
171
+ Full reference: [docs/EVENTS.md](docs/EVENTS.md).
47
172
 
48
- - Precedencia: **el ámbito manda** (local > global) y **dentro de cada ámbito el fichero gana al inline** ⇒ `local-inline > global-file`.
49
- - Comentarios: `#`, `//` y `/* */`.
50
- - Plantillas de prompt: **solo rutas relativas** (al proyecto o `~/home`); si el fichero no existe **se crea con defaults**.
173
+ ## Calling apex over RPC
174
+
175
+ Every apex RPC method is an HTTP POST to the OpenCode server:
51
176
 
52
- ```jsonc
53
- {
54
- "modules": { "redact": true, "events": true, "advisor": false },
55
- "redact": {
56
- "mode": "strict",
57
- "bundles": ["aws", "github", "jwt", "env"],
58
- "minConfidence": "medium",
59
- "prefix": "[SECRET:",
60
- "suffix": "]",
61
- "key": "env:APEX_REDACT_KEY",
62
- "restore": { "toolInput": true }
63
- },
64
- "events": {
65
- "routing": "all",
66
- "subscriptions": [
67
- { "sessionID": "", "filters": [{ "field": "type", "operator": "equals", "value": "ci.failed" }] }
68
- ]
69
- },
70
- "advisor": { "model": "opencode/big-pickle", "decisive": true, "evaluate": "ask-only" }
71
- }
72
177
  ```
178
+ POST <server-url>/api/rpc/apex/<method>?location[directory]=<project-path>
179
+ Authorization: Basic base64("opencode:<server-password>")
180
+ Content-Type: application/json
73
181
 
74
- ## Callbacks, webhooks y vigilancias (despertar al agente desde fuera)
75
-
76
- Patrón: el agente se **suscribe** → un proceso externo llama a **`apex/events.ingest`**
77
- por el RPC del servidor → el agente recibe un prompt con el encargo. El reloj (cron,
78
- systemd) y la puerta (relay de webhooks, n8n) viven **fuera** de OpenCode:
79
-
80
- - OpenCode descarga los plugins de un directorio tras **60 min sin actividad** y no los
81
- recarga tras un reinicio hasta que algo usa ese directorio. El RPC levanta el
82
- directorio en la propia llamada; un listener o un temporizador del plugin moriría con él.
83
- - Un **webhook** es un callback con un proceso intermedio que traduce la llamada HTTP a
84
- `events.ingest`.
85
- - Si la comprobación necesita una herramienta que solo existe en OpenCode (un MCP, el
86
- navegador), el proceso externo la ejecuta con **`apex/tools.run`**, sin modelo.
87
- - La tool **`apex_callback_endpoint`** le dice al agente la URL base de su propio servidor,
88
- las URLs RPC de su directorio y de dónde leer el password (nunca lo devuelve).
89
-
90
- La skill **`apex-callbacks`** viaja con el paquete y se registra sola: vigilantes con
91
- estado, systemd/cron, relay de webhooks, n8n y `tools.run`. Detalle en
92
- [docs/EVENTS.md](docs/EVENTS.md).
93
-
94
- ## Herramientas expuestas
95
-
96
- | Tool | Módulo | Qué hace |
97
- | ------------------------- | ------- | ----------------------------------------------------------- |
98
- | `apex_subscribe` | events | Crea una suscripción para la sesión que llama |
99
- | `apex_unsubscribe` | events | Elimina una suscripción dinámica por id |
100
- | `apex_list_subscriptions` | events | Lista suscripciones (marca las estáticas de config) |
101
- | `apex_callback_endpoint` | events | Cómo alcanza un proceso externo a este servidor: URL base, URLs RPC del directorio, auth y ejemplos curl |
102
- | `apex_set_callback_url` | events | Anuncia/limpia la URL pública (túnel/proxy) del servidor para emisores de otras máquinas |
103
- | `apex_advisor_decide` | advisor | Única tool del agente advisor: `allow` / `deny` + `reason` |
104
- | `apex_guard_report` | guard | Informe de meta-permisos: qué intentó cada agente y qué se decidió |
105
- | `browser_target` | browser | Elige qué navegador sirve `browser.*`: `external` (CDP), `in-app` (app de escritorio) o `auto` |
106
-
107
- ## RPC (namespace `apex`)
108
-
109
- | Método | Entrada | Salida |
110
- | ---------------- | ---------------------------------------------- | ------------------------------------- |
111
- | `apex.ping` | `{ payload? }` | `{ pong, timestamp }` |
112
- | `apex.status` | `{}` | `{ modules, version, uptimeMs, endpoint }` |
113
- | `apex.server.info` | `{}` | lo mismo que `apex_callback_endpoint` |
114
- | `apex.redact.process` | `{ text, mode? }` | `{ redacted, findings }` |
115
- | `apex.events.ingest` | `{ source, type?, payload, eventID? }` | `{ accepted, eventID, delivered }` |
116
- | `apex.tools.run` | `{ tool, input?, agent?, timeoutMs? }` | `{ ok, tool, agent, output?, content?, metadata?, error?, durationMs }` |
117
-
118
- Llamada: `POST <baseUrl>/api/rpc/apex/<método>?location[directory]=<proyecto>` con cuerpo
119
- `{"input":{…}}` y Basic `opencode:<password>`; responde `{"output":{…}}`.
120
-
121
- ## Estructura
182
+ {"input": { ...method input... }} → {"output": { ...result... }}
183
+ ```
122
184
 
185
+ - **`<server-url>`**: where your OpenCode server listens. For the background service it's the
186
+ `url` field of `~/.local/state/opencode/service.json` (or `$XDG_STATE_HOME/opencode/`). For
187
+ `opencode serve --port N` it's `http://127.0.0.1:N`.
188
+ - **`<server-password>`**: the user is always `opencode`; the password is:
189
+ - for the service, the `password` field of that same file (mode 0600);
190
+ - for `opencode serve`, `OPENCODE_SERVER_PASSWORD`, or the password printed at startup.
191
+ - **`location[directory]`**: the project whose apex should handle the call: its subscriptions,
192
+ its MCP tools, its permissions. URL-encode it if the path contains spaces. In curl, write
193
+ the brackets as `%5B` `%5D`.
194
+
195
+ You don't have to work this out by hand. The tool **`apex_callback_endpoint`**, or the RPC
196
+ `apex/server.info`, returns:
197
+ - the server URL;
198
+ - the ready-made method URLs for the current project;
199
+ - *where* the password is (never the password itself);
200
+ - copy-paste curl examples.
201
+
202
+ A first call from a terminal, against the background service:
203
+
204
+ ```sh
205
+ STATE=~/.local/state/opencode/service.json
206
+ URL=$(sed -n 's/.*"url" *: *"\([^"]*\)".*/\1/p' "$STATE")
207
+ PW=$(sed -n 's/.*"password" *: *"\([^"]*\)".*/\1/p' "$STATE")
208
+
209
+ curl -sS -u "opencode:$PW" -H 'content-type: application/json' \
210
+ -X POST "$URL/api/rpc/apex/status?location%5Bdirectory%5D=$PWD" -d '{"input":{}}'
211
+ # → {"output":{"modules":{...},"version":"0.2.x","uptimeMs":...,"endpoint":{...}}}
123
212
  ```
124
- .opencode/plugins/apex/
125
- ├── index.ts # Entrada: Plugin.define + carga de config + registro de módulos
126
- ├── redact.ts # Módulo redact: hooks context / execute.before
127
- ├── events.ts # Módulo events: tools, ingest, routing, auto-vinculación
128
- ├── advisor.ts # Módulo advisor: agente + hook de permisos
129
- ├── guard.ts # Módulo guard: meta-permisos + informe
130
- ├── browser.ts # Módulo browser: attachment CDP, tool browser.target, comando
131
- ├── browser/
132
- │ ├── cdp.ts # Cliente CDP: WebSocket, TabRegistry, colectores
133
- │ ├── endpoint.ts # DevToolsActivePort vs /json/version, ws/wss remoto
134
- │ └── actions.ts # Las 45 Browser.Action → CDP
135
- ├── core/
136
- │ ├── config.ts # Jerarquía, merge, comentarios, schema Zod
137
- │ ├── templates.ts # Resolución/creación de plantillas (relativas)
138
- │ ├── crypto.ts # AES-256-GCM, resolución de clave
139
- │ ├── patterns.ts # 41 bundles / 104 patrones (secret-redactor + warden)
140
- │ ├── redact.ts # Motor de redacción/restauración
141
- │ ├── conditions.ts # Evaluación de condiciones de filtros
142
- │ ├── bus.ts # Bus interno
143
- │ ├── rpc.ts # Registro del namespace RPC "apex"
144
- │ ├── guard.ts # Motor de meta-permisos
145
- │ ├── server-endpoint.ts # URL base del servidor + auth para procesos externos
146
- │ ├── tools-run.ts # RPC tools.run: allow/deny, agente de permisos, sesión runner
147
- │ ├── skills.ts # Registro de las skills del paquete
148
- │ ├── compat.ts # Aviso de versiones desalineadas con OpenCode (effect, @opencode/plugin)
149
- │ ├── advisor-agent.ts # Definición del agente apex-advisor
150
- │ ├── advisor-tool.ts # Tool apex_advisor_decide
151
- │ └── advisor-session.ts # Sesión advisor por árbol + round-trip
152
- ├── skills/
153
- │ └── apex-callbacks/ # Skill: callbacks, webhooks, vigilancias, tools.run
154
- ├── test/
155
- │ ├── browser.test.ts # Suite del módulo browser (Chromium en TEST_CDP_URL)
156
- │ ├── events.test.ts # RPC, descubrimiento del servidor, tools.run, skills
157
- │ └── guard.test.ts # Suite del módulo guard
158
- └── docs/ # CONFIG · REDACT · EVENTS · ADVISOR · GUARD · BROWSER · TROUBLESHOOTING
213
+
214
+ Run a tool from a script, here `read` in the current project:
215
+
216
+ ```sh
217
+ curl -sS -u "opencode:$PW" -H 'content-type: application/json' \
218
+ -X POST "$URL/api/rpc/apex/tools.run?location%5Bdirectory%5D=$PWD" \
219
+ -d '{"input":{"tool":"read","input":{"path":"README.md"}}}'
220
+ # → {"output":{"ok":true,"tool":"read","agent":"build","content":"...","durationMs":14}}
159
221
  ```
160
222
 
161
- ## Desarrollo
223
+ ## Tools added to your agents
224
+
225
+ | Tool | Module | What it does |
226
+ | --- | --- | --- |
227
+ | `apex_subscribe` | events | Creates an event subscription for the calling session (filters, prompt template, agent to switch to, delivery mode) |
228
+ | `apex_unsubscribe` | events | Removes a subscription by id. Subscriptions from config are read-only |
229
+ | `apex_list_subscriptions` | events | Lists subscriptions; config ones are marked read-only |
230
+ | `apex_callback_endpoint` | events | How an external program reaches this server: URL, RPC URLs for this project, auth, curl examples |
231
+ | `apex_set_callback_url` | events | Sets or clears the server's public URL (tunnel / reverse proxy), for senders on other machines |
232
+ | `apex_advisor_decide` | advisor | The advisor agent's only tool: `allow` / `deny` + reason |
233
+ | `apex_guard_report` | guard | Report of what each agent attempted and what was decided |
234
+ | `browser_target` | browser | Chooses which browser serves `browser.*`: `external` (CDP), `in-app` (desktop app) or `auto` |
235
+
236
+ apex also registers two hidden agents: `apex-advisor` for the Advisor and `apex-runner`, the
237
+ technical session behind `tools.run`.
238
+
239
+ ## RPC reference
240
+
241
+ Namespace `apex`. Inputs and outputs go inside the `input` / `output` envelopes shown above.
242
+
243
+ | Method | Input | Output |
244
+ | --- | --- | --- |
245
+ | `ping` | `{ payload? }` | `{ pong, timestamp }` |
246
+ | `status` | `{}` | `{ modules, version, uptimeMs, endpoint }` |
247
+ | `server.info` | `{}` | same as the `apex_callback_endpoint` tool |
248
+ | `events.ingest` | `{ source, type?, payload, eventID? }` | `{ accepted, eventID, delivered[] }` |
249
+ | `tools.run` | `{ tool, input?, agent?, timeoutMs? }` | `{ ok, tool, agent, output?, content?, metadata?, error?, durationMs }` |
250
+ | `redact.process` | `{ text, mode? }` | `{ redacted, findings }` |
251
+
252
+ - `events.ingest`:
253
+ - `delivered` lists the subscriptions that received the event. An empty list means none
254
+ matched.
255
+ - Re-sending the same `eventID` within 5 minutes is ignored, so retries are safe.
256
+ - `tools.run` runs **one** tool, with the permissions of the agent `events.tools.agent`
257
+ (default `build`) or the `agent` you pass.
258
+ - `events.tools.allow` / `deny` limit which tools can be run this way.
259
+ - `question`, `subagent`, `execute` and the `apex_*` tools are denied by default.
260
+ - Nobody is around to answer an "ask" permission: it waits for the Advisor, or until
261
+ `timeoutMs` (default 120 s).
262
+
263
+ ## Security notes
264
+
265
+ - **The server password is a full credential.** Anyone who has it can drive your agents
266
+ through the OpenCode API. With `events.ingest` they can inject prompts; with `tools.run`
267
+ they can run tools. Keep the file at mode 0600, and don't paste the password into scripts,
268
+ unit files or chats: read it at run time, as the examples do.
269
+ - To receive webhooks from the Internet, expose the **relay**, protected by its own token.
270
+ Never expose the OpenCode server itself.
271
+ - Redact encrypts with the key in `redact.key` (`env:VAR`, `file:/path`, `hex:…`, `base64:…`).
272
+ Without one, it generates a key and keeps it in `~/.config/opencode/apex.key` (mode 0600).
273
+ Back that key up: if you lose it, the markers already in your session history can't be
274
+ restored.
275
+
276
+ ## Troubleshooting
277
+
278
+ See [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). The most common cases:
279
+
280
+ | Symptom | Fix |
281
+ | --- | --- |
282
+ | `RPC is unavailable: apex` | apex isn't loaded in that project. Check `location[directory]` and the plugin entry, then retry (the first load installs it). |
283
+ | Plugin fails to load after an OpenCode upgrade | Reinstall it, see [Update / reinstall](#update--reinstall). |
284
+ | The automation stopped after an hour | Expected if it lived inside OpenCode. Move the clock outside (cron / systemd). |
285
+
286
+ ## Development
162
287
 
163
288
  ```bash
164
- ./node_modules/.bin/tsc --noEmit # typecheck
165
- ./node_modules/.bin/tsc --noEmit --noUnusedLocals --noUnusedParameters # código muerto
166
- bun -e "await import('./index.ts'); console.log('OK')" # smoke de carga
167
- bun test/events.test.ts # events (56)
168
- bun test test/guard.test.ts # guard (56)
169
- TEST_CDP_URL=<puerto> bun test test/browser.test.ts # browser (10; p.ej. 9333)
170
- node scripts/check-install.mjs # instala como OpenCode: 1 sola copia de effect
289
+ git clone https://github.com/aorizondo/opencode-apex.git
290
+ cd opencode-apex && bun install
171
291
  ```
172
292
 
173
- Para la suite de browser hace falta un Chromium headless con CDP en ese puerto:
293
+ To run the local checkout instead of the npm package, point OpenCode at the directory:
294
+ `"plugins": [{ "package": "/path/to/opencode-apex" }]`.
174
295
 
175
296
  ```bash
176
- google-chrome --headless=new --remote-debugging-port=9333 \
177
- --user-data-dir=/tmp/opencode/cdp-probe about:blank
297
+ bun test/events.test.ts # events, RPC, server discovery, tools.run, skills
298
+ bun test test/guard.test.ts # guard
299
+ TEST_CDP_URL=9333 bun test test/browser.test.ts # browser (needs Chromium with --remote-debugging-port=9333)
300
+ npm run typecheck # tsc --noEmit
301
+ npm run check:install # installs the package like OpenCode does; fails on duplicate `effect`
178
302
  ```
179
303
 
180
- ## Troubleshooting
304
+ `npm publish` runs tests, typecheck and the install check first (`prepublishOnly`).
305
+
306
+ **Dependency rule.** apex doesn't pin its own `effect`. It uses the copy that
307
+ `@opencode/plugin` brings: `effect` is an optional peer dependency, and `@opencode/plugin` is a
308
+ `^2.1.1` dependency. That keeps apex aligned with each OpenCode release. See
309
+ [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) before changing dependencies.
310
+
311
+ ```
312
+ opencode-apex/
313
+ ├── index.ts # entry point: Plugin.define, config loading, module registration
314
+ ├── redact.ts · events.ts · advisor.ts · guard.ts · browser.ts # the five modules
315
+ ├── browser/ # CDP client, endpoint discovery, the 45 browser actions
316
+ ├── core/
317
+ │ ├── config.ts # config hierarchy, merge, comments, Zod schema
318
+ │ ├── rpc.ts # the "apex" RPC namespace
319
+ │ ├── server-endpoint.ts# server URL + auth discovery for external programs
320
+ │ ├── tools-run.ts # tools.run: allow/deny, permission agent, runner session
321
+ │ ├── skills.ts # registers the skills shipped in skills/
322
+ │ ├── compat.ts # load-time warnings when versions drift from OpenCode
323
+ │ └── … # redact engine, patterns, crypto, conditions, guard, advisor
324
+ ├── skills/apex-callbacks/SKILL.md # agent guide: callbacks, webhooks, watchers, tools.run
325
+ ├── scripts/check-install.mjs # pre-publish install check
326
+ ├── test/ # events, guard, browser suites
327
+ └── docs/ # CONFIG · REDACT · EVENTS · ADVISOR · GUARD · BROWSER · TROUBLESHOOTING
328
+ ```
329
+
330
+ Changes: [CHANGELOG.md](CHANGELOG.md).
331
+
332
+ ## License
181
333
 
182
- Ver [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) — matriz v1/v2, errores
183
- conocidos (`ast._tag`, ENOENT de config, versiones de `effect`), y checklist para
184
- módulos nuevos.
334
+ [MIT](LICENSE)
@@ -123,7 +123,10 @@ export interface ResolveInput {
123
123
  * 3. "auto" → DevToolsActivePort local, 9222 preferido.
124
124
  * 4. http://host:puerto → derivar perfil local, luego /json/version.
125
125
  */
126
- export async function resolveEndpoint({ cdpUrl = "auto", profileDir }: ResolveInput = {}): Promise<Endpoint> {
126
+ export async function resolveEndpoint({ cdpUrl = "auto", profileDir: rawProfileDir }: ResolveInput = {}): Promise<Endpoint> {
127
+ // `~/…` en la config: el shell no está para expandirlo.
128
+ const profileDir =
129
+ rawProfileDir === "~" || rawProfileDir?.startsWith("~/") ? join(homedir(), rawProfileDir.slice(1)) : rawProfileDir
127
130
  // 0. Endpoint remoto explícito: ws:// o wss://. Sin discovery posible.
128
131
  if (/^wss?:\/\//i.test(cdpUrl)) {
129
132
  let parsed: URL
package/browser.ts CHANGED
@@ -433,7 +433,8 @@ export function register(ctx: Plugin.Context, config: BrowserConfigShape): Effec
433
433
  "browser.* only work after this tool or /browser-target has asked for a browser. " +
434
434
  "`cdpUrl` is `auto` (read DevToolsActivePort from known profiles), a port like `9222`, or a full " +
435
435
  "`ws://`/`wss://` websocket URL for a remote browser behind a tunnel. `profile` is a Chromium user-data " +
436
- "directory; it wins over `cdpUrl` and requires no remote debugging toggle. Using `external` may raise " +
436
+ "directory (`~/` allowed); it wins over `cdpUrl` and reads that profile's DevToolsActivePort, so remote " +
437
+ "debugging must be enabled in it (chrome://inspect/#remote-debugging). Using `external` may raise " +
437
438
  "an \"Allow remote debugging?\" prompt in the browser: approve it once, the connection is then kept open.",
438
439
  input: {
439
440
  mode: {
package/core/compat.ts CHANGED
@@ -7,6 +7,9 @@
7
7
  * en caché, un gestor que no hoistea), los efectos de una no se entienden con la otra
8
8
  * y el fallo llega críptico (`Schema.isStartsWith is not a function`, "missing TypeId").
9
9
  * Aquí se detecta al cargar y se dice qué hacer.
10
+ *
11
+ * La caché npm de plugins de OpenCode no se refresca sola: tras actualizar OpenCode,
12
+ * apex sigue con las dependencias de cuando se instaló hasta que se reinstala.
10
13
  */
11
14
 
12
15
  import { readFileSync, realpathSync } from "node:fs"
@@ -51,6 +54,11 @@ function readPackage(dir: string): { name?: string; version?: string } | null {
51
54
  }
52
55
  }
53
56
 
57
+ /** Cómo forzar que OpenCode reinstale apex y sus dependencias. */
58
+ const REINSTALL =
59
+ "stop OpenCode, delete ~/.cache/opencode/npm/opencode-apex@* and start it again " +
60
+ "(in 2.1 `opencode plugin update` only handles TUI plugins)"
61
+
54
62
  /** major.minor numérico, o null si no se puede leer. */
55
63
  function minor(version: string | undefined): [number, number] | null {
56
64
  const match = /^(\d+)\.(\d+)/.exec(version ?? "")
@@ -80,14 +88,14 @@ export function compatibilityWarnings(
80
88
 
81
89
  if (ownEffect && pluginEffect && ownEffect.dir !== pluginEffect.dir) {
82
90
  warnings.push(
83
- `dos copias de effect: apex usa ${ownEffect.version} y @opencode/plugin ${pluginEffect.version}. ` +
84
- `Reinstala el plugin ("opencode plugin update", o borra su entrada en ~/.cache/opencode/npm).`,
91
+ `two copies of effect: apex uses ${ownEffect.version} and @opencode/plugin ${pluginEffect.version}. ` +
92
+ `Reinstall the plugin: ${REINSTALL}.`,
85
93
  )
86
94
  }
87
95
  if (plugin && newerMinor(hostVersion, plugin.version)) {
88
96
  warnings.push(
89
- `OpenCode ${hostVersion} es más nuevo que @opencode/plugin ${plugin.version} instalado con apex. ` +
90
- `Actualiza el plugin con "opencode plugin update" para alinear versiones.`,
97
+ `OpenCode ${hostVersion} is newer than the @opencode/plugin ${plugin.version} installed with apex. ` +
98
+ `Reinstall it to realign versions: ${REINSTALL}.`,
91
99
  )
92
100
  }
93
101
  return warnings
package/core/config.ts CHANGED
@@ -6,7 +6,7 @@ import { z } from "zod"
6
6
  import type { GuardConfigShape } from "./guard.js"
7
7
  import { DEFAULT_BUNDLES } from "./patterns.js"
8
8
  import { readFile } from "fs/promises"
9
- import { parse as parseJsonc } from "jsonc-parser"
9
+ import { parse as parseJsonc, printParseErrorCode, type ParseError } from "jsonc-parser"
10
10
  import { join } from "node:path"
11
11
 
12
12
  // ============================================================================
@@ -358,7 +358,18 @@ export function stripHashComments(text: string): string {
358
358
 
359
359
  /** Parsea un texto de configuración (JSONC + comentarios `#`). */
360
360
  export function parseConfigText(text: string, path: string): Record<string, unknown> {
361
- const parsed = parseJsonc(stripHashComments(text), [], { disallowComments: false, allowTrailingComma: true })
361
+ const errors: ParseError[] = []
362
+ const source = stripHashComments(text)
363
+ const parsed = parseJsonc(source, errors, { disallowComments: false, allowTrailingComma: true })
364
+ // jsonc-parser recupera lo que puede: sin este aviso, una coma o una comilla de más
365
+ // dejaba claves fuera de la config sin decir nada.
366
+ if (errors.length > 0) {
367
+ const where = errors
368
+ .slice(0, 3)
369
+ .map((e) => `${printParseErrorCode(e.error)} @ line ${source.slice(0, e.offset).split("\n").length}`)
370
+ .join(", ")
371
+ console.warn(`[apex] config syntax errors in ${path} (${where}): the affected keys may be missing`)
372
+ }
362
373
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
363
374
  throw new Error(`Configuración inválida en ${path}: se esperaba un objeto`)
364
375
  }
@@ -472,7 +483,7 @@ export async function loadApexConfig(input: {
472
483
  // por inactividad). Los callbacks y webhooks entran por el RPC.
473
484
  if ((legacy as Record<string, unknown> | undefined)?.listener !== undefined) {
474
485
  console.warn(
475
- `[apex] "events.listener" ya no existe y se ignora: usa el RPC apex/events.ingest (tool apex_callback_endpoint)`,
486
+ `[apex] "events.listener" no longer exists and is ignored: use the apex/events.ingest RPC (tool apex_callback_endpoint)`,
476
487
  )
477
488
  }
478
489
 
package/core/crypto.ts CHANGED
@@ -106,7 +106,8 @@ function resolveKeyMaterial(
106
106
  }
107
107
 
108
108
  if (raw.startsWith("file:")) {
109
- const path = raw.slice(5).trim()
109
+ const spec = raw.slice(5).trim()
110
+ const path = spec === "~" || spec.startsWith("~/") ? join(homedir(), spec.slice(1)) : spec
110
111
  try {
111
112
  if (existsSync(path)) {
112
113
  const value = readFileSync(path, "utf8").trim()
package/core/rpc.ts CHANGED
@@ -88,7 +88,7 @@ export function registerCentralRpc(
88
88
  return Effect.gen(function* () {
89
89
  const startedAt = Date.now()
90
90
  const { modules, events } = input
91
- const eventsOff = "módulo events desactivado (modules.events=false)"
91
+ const eventsOff = "the events module is disabled (modules.events=false)"
92
92
  const endpoint = (): ServerEndpoint | null => events?.endpoint() ?? null
93
93
 
94
94
  yield* ctx.rpc.register(APEX_RPC_DEFINITION as never, {
@@ -156,7 +156,7 @@ export function resolveServerEndpoint(input: {
156
156
  },
157
157
  ...(baseUrl
158
158
  ? {}
159
- : { hint: "URL del servidor desconocida: fija events.server.url en la config de apex (p. ej. http://127.0.0.1:4096)" }),
159
+ : { hint: "Server URL unknown: set events.server.url in the apex config (e.g. http://127.0.0.1:4096)" }),
160
160
  }
161
161
  }
162
162