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/CHANGELOG.md +85 -44
- package/LICENSE +21 -0
- package/README.md +299 -149
- package/browser/endpoint.ts +4 -1
- package/browser.ts +2 -1
- package/core/compat.ts +12 -4
- package/core/config.ts +14 -3
- package/core/crypto.ts +2 -1
- package/core/rpc.ts +1 -1
- package/core/server-endpoint.ts +1 -1
- package/core/tools-run.ts +7 -7
- package/docs/ADVISOR.md +129 -71
- package/docs/BROWSER.md +185 -158
- package/docs/CONFIG.md +145 -55
- package/docs/EVENTS.md +206 -89
- package/docs/GUARD.md +142 -104
- package/docs/REDACT.md +143 -89
- package/docs/TROUBLESHOOTING.md +225 -189
- package/events.ts +28 -22
- package/index.ts +9 -2
- package/opencode-apex.jsonc +150 -132
- package/package.json +32 -6
- package/redact.ts +5 -4
- package/skills/apex-callbacks/SKILL.md +129 -123
package/docs/TROUBLESHOOTING.md
CHANGED
|
@@ -1,231 +1,267 @@
|
|
|
1
1
|
# Troubleshooting — opencode-apex
|
|
2
2
|
|
|
3
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
20
|
+
Useful log searches:
|
|
20
21
|
|
|
21
22
|
```bash
|
|
22
|
-
|
|
23
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
-
|
|
46
|
+
## Version mismatch with OpenCode (`effect`)
|
|
52
47
|
|
|
53
|
-
|
|
54
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
82
|
+
## RPC calls fail
|
|
75
83
|
|
|
76
|
-
|
|
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
|
-
|
|
91
|
+
{"input": { … }}
|
|
92
|
+
```
|
|
86
93
|
|
|
87
|
-
|
|
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
|
-
|
|
180
|
+
# Developer notes
|
|
92
181
|
|
|
93
|
-
|
|
182
|
+
## Running a local checkout
|
|
94
183
|
|
|
95
|
-
|
|
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
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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
|
-
|
|
191
|
+
Then, in that directory:
|
|
106
192
|
|
|
107
193
|
```bash
|
|
108
|
-
bun
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
-
|
|
117
|
-
|
|
118
|
-
`
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
-
|
|
151
|
-
|
|
152
|
-
-
|
|
153
|
-
|
|
154
|
-
-
|
|
155
|
-
|
|
156
|
-
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
-
|
|
171
|
-
-
|
|
172
|
-
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
-
|
|
177
|
-
-
|
|
178
|
-
-
|
|
179
|
-
-
|
|
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 `opencode plugin update`.
|
|
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**: `opencode plugin update` (o borrar
|
|
228
|
-
`~/.cache/opencode/npm/opencode-apex@*`) para que el plugin reinstale sus dependencias
|
|
229
|
-
con el `@opencode/plugin` nuevo.
|
|
230
|
-
- **Rotura de API (OpenCode 3.x)**: el rango `^2` no la absorbe a propósito. Eso exige
|
|
231
|
-
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
|
-
"
|
|
454
|
-
"
|
|
455
|
-
"
|
|
456
|
-
"
|
|
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: "
|
|
462
|
-
source: { type: ["string", "null"], description: "
|
|
463
|
-
publicUrl: { type: ["string", "null"], description: "URL
|
|
464
|
-
directory: { type: "string", description: "
|
|
465
|
-
auth: { type: "object", description: "Basic opencode:<password>; password.shell
|
|
466
|
-
rpc: { type: "object", description: "URLs
|
|
467
|
-
examples: { type: "object", description: "curl
|
|
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
|
-
"
|
|
510
|
-
"
|
|
511
|
-
"
|
|
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
|
|
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: "
|
|
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(
|
|
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
|
-
|
|
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
|
|
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.
|
|
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
|
-
|
|
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(),
|