opencode-apex 0.2.1 → 0.2.3
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 +102 -48
- package/LICENSE +21 -0
- package/README.md +308 -152
- package/browser/endpoint.ts +4 -1
- package/browser.ts +2 -1
- package/core/compat.ts +13 -12
- 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 +211 -90
- package/docs/GUARD.md +142 -104
- package/docs/REDACT.md +143 -89
- package/docs/TROUBLESHOOTING.md +237 -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 +139 -200
- package/skills/apex-callbacks/references/examples.md +261 -0
- package/skills/apex-callbacks/references/reachability.md +103 -0
- package/skills/apex-callbacks/references/relays.md +116 -0
- package/skills/apex-callbacks/references/run-anywhere.md +133 -0
package/README.md
CHANGED
|
@@ -1,186 +1,342 @@
|
|
|
1
1
|
# opencode-apex
|
|
2
2
|
|
|
3
|
-
**
|
|
4
|
-
|
|
5
|
-
(
|
|
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
|
-
|
|
65
|
+
```jsonc
|
|
66
|
+
"modules": { "redact": true, "events": true, "advisor": true, "guard": false, "browser": true }
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Requirements
|
|
8
70
|
|
|
9
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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`.
|
|
28
102
|
|
|
29
|
-
|
|
30
|
-
"plugins": [{ "package": "opencode-apex", "options": { "modules": { "events": true } } }]
|
|
31
|
-
```
|
|
103
|
+
## Update / reinstall
|
|
32
104
|
|
|
33
|
-
|
|
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:
|
|
34
107
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
quedó desalineado.
|
|
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.
|
|
39
111
|
|
|
40
|
-
|
|
112
|
+
Do this **after upgrading OpenCode** too. apex warns in the server log if its dependencies no
|
|
113
|
+
longer match the running OpenCode.
|
|
41
114
|
|
|
42
|
-
|
|
115
|
+
## Configuration
|
|
43
116
|
|
|
44
|
-
|
|
45
|
-
| - | ----------------------------------------------------- | ----------- |
|
|
46
|
-
| 1 | Fichero global `~/.config/opencode/opencode-apex.jsonc` | global-file |
|
|
47
|
-
| 2 | `options` del plugin en `opencode.json` | inline |
|
|
48
|
-
| 3 | Fichero local `<proyecto>/.opencode/opencode-apex.jsonc` | local-file |
|
|
117
|
+
apex reads its settings from three places, merged in this order (later wins):
|
|
49
118
|
|
|
50
|
-
|
|
51
|
-
-
|
|
52
|
-
|
|
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 |
|
|
53
124
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
},
|
|
72
|
-
"advisor": { "model": "opencode/big-pickle", "decisive": true, "evaluate": "ask-only" }
|
|
73
|
-
}
|
|
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:
|
|
137
|
+
|
|
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
|
|
74
142
|
```
|
|
75
143
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
| `apex.status` | `{}` | `{ modules, version, uptimeMs, endpoint }` |
|
|
115
|
-
| `apex.server.info` | `{}` | lo mismo que `apex_callback_endpoint` |
|
|
116
|
-
| `apex.redact.process` | `{ text, mode? }` | `{ redacted, findings }` |
|
|
117
|
-
| `apex.events.ingest` | `{ source, type?, payload, eventID? }` | `{ accepted, eventID, delivered }` |
|
|
118
|
-
| `apex.tools.run` | `{ tool, input?, agent?, timeoutMs? }` | `{ ok, tool, agent, output?, content?, metadata?, error?, durationMs }` |
|
|
119
|
-
|
|
120
|
-
Llamada: `POST <baseUrl>/api/rpc/apex/<método>?location[directory]=<proyecto>` con cuerpo
|
|
121
|
-
`{"input":{…}}` y Basic `opencode:<password>`; responde `{"output":{…}}`.
|
|
122
|
-
|
|
123
|
-
## Estructura
|
|
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.
|
|
152
|
+
|
|
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.
|
|
158
|
+
|
|
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 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.
|
|
162
|
+
|
|
163
|
+
The same idea covers any always-on event source: a relay keeps an outbound connection to a
|
|
164
|
+
chat app, a mailbox (IMAP IDLE), an SSE or WebSocket stream or a queue, and forwards what
|
|
165
|
+
matters.
|
|
166
|
+
|
|
167
|
+
apex registers a skill, **`apex-callbacks`**, that teaches agents the whole recipe:
|
|
168
|
+
- discovering the server URL;
|
|
169
|
+
- subscribing;
|
|
170
|
+
- designing a relay or watcher in any language and running it on any OS (systemd, launchd,
|
|
171
|
+
Task Scheduler, Docker, pm2);
|
|
172
|
+
- calling OpenCode and MCP tools from relay code with `tools.run`, and its limits;
|
|
173
|
+
- reachability: why a relay behind NAT can't receive Internet webhooks, and the workarounds
|
|
174
|
+
(outbound modes, Cloudflare/Tailscale/ngrok tunnels, reverse SSH, store-and-forward);
|
|
175
|
+
- copyable examples in sh, Python, Node and PowerShell, plus an n8n recipe.
|
|
176
|
+
|
|
177
|
+
Full reference: [docs/EVENTS.md](docs/EVENTS.md).
|
|
178
|
+
|
|
179
|
+
## Calling apex over RPC
|
|
180
|
+
|
|
181
|
+
Every apex RPC method is an HTTP POST to the OpenCode server:
|
|
124
182
|
|
|
125
183
|
```
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
├── guard.ts # Módulo guard: meta-permisos + informe
|
|
132
|
-
├── browser.ts # Módulo browser: attachment CDP, tool browser.target, comando
|
|
133
|
-
├── browser/
|
|
134
|
-
│ ├── cdp.ts # Cliente CDP: WebSocket, TabRegistry, colectores
|
|
135
|
-
│ ├── endpoint.ts # DevToolsActivePort vs /json/version, ws/wss remoto
|
|
136
|
-
│ └── actions.ts # Las 45 Browser.Action → CDP
|
|
137
|
-
├── core/
|
|
138
|
-
│ ├── config.ts # Jerarquía, merge, comentarios, schema Zod
|
|
139
|
-
│ ├── templates.ts # Resolución/creación de plantillas (relativas)
|
|
140
|
-
│ ├── crypto.ts # AES-256-GCM, resolución de clave
|
|
141
|
-
│ ├── patterns.ts # 41 bundles / 104 patrones (secret-redactor + warden)
|
|
142
|
-
│ ├── redact.ts # Motor de redacción/restauración
|
|
143
|
-
│ ├── conditions.ts # Evaluación de condiciones de filtros
|
|
144
|
-
│ ├── bus.ts # Bus interno
|
|
145
|
-
│ ├── rpc.ts # Registro del namespace RPC "apex"
|
|
146
|
-
│ ├── guard.ts # Motor de meta-permisos
|
|
147
|
-
│ ├── server-endpoint.ts # URL base del servidor + auth para procesos externos
|
|
148
|
-
│ ├── tools-run.ts # RPC tools.run: allow/deny, agente de permisos, sesión runner
|
|
149
|
-
│ ├── skills.ts # Registro de las skills del paquete
|
|
150
|
-
│ ├── compat.ts # Aviso de versiones desalineadas con OpenCode (effect, @opencode/plugin)
|
|
151
|
-
│ ├── advisor-agent.ts # Definición del agente apex-advisor
|
|
152
|
-
│ ├── advisor-tool.ts # Tool apex_advisor_decide
|
|
153
|
-
│ └── advisor-session.ts # Sesión advisor por árbol + round-trip
|
|
154
|
-
├── skills/
|
|
155
|
-
│ └── apex-callbacks/ # Skill: callbacks, webhooks, vigilancias, tools.run
|
|
156
|
-
├── test/
|
|
157
|
-
│ ├── browser.test.ts # Suite del módulo browser (Chromium en TEST_CDP_URL)
|
|
158
|
-
│ ├── events.test.ts # RPC, descubrimiento del servidor, tools.run, skills
|
|
159
|
-
│ └── guard.test.ts # Suite del módulo guard
|
|
160
|
-
└── docs/ # CONFIG · REDACT · EVENTS · ADVISOR · GUARD · BROWSER · TROUBLESHOOTING
|
|
184
|
+
POST <server-url>/api/rpc/apex/<method>?location[directory]=<project-path>
|
|
185
|
+
Authorization: Basic base64("opencode:<server-password>")
|
|
186
|
+
Content-Type: application/json
|
|
187
|
+
|
|
188
|
+
{"input": { ...method input... }} → {"output": { ...result... }}
|
|
161
189
|
```
|
|
162
190
|
|
|
163
|
-
|
|
191
|
+
- **`<server-url>`**: where your OpenCode server listens. For the background service it's the
|
|
192
|
+
`url` field of `~/.local/state/opencode/service.json` (or `$XDG_STATE_HOME/opencode/`). For
|
|
193
|
+
`opencode serve --port N` it's `http://127.0.0.1:N`.
|
|
194
|
+
- **`<server-password>`**: the user is always `opencode`; the password is:
|
|
195
|
+
- for the service, the `password` field of that same file (mode 0600);
|
|
196
|
+
- for `opencode serve`, `OPENCODE_SERVER_PASSWORD`, or the password printed at startup.
|
|
197
|
+
- **`location[directory]`**: the project whose apex should handle the call: its subscriptions,
|
|
198
|
+
its MCP tools, its permissions. URL-encode it if the path contains spaces. In curl, write
|
|
199
|
+
the brackets as `%5B` `%5D`.
|
|
200
|
+
|
|
201
|
+
You don't have to work this out by hand. The tool **`apex_callback_endpoint`**, or the RPC
|
|
202
|
+
`apex/server.info`, returns:
|
|
203
|
+
- the server URL;
|
|
204
|
+
- the ready-made method URLs for the current project;
|
|
205
|
+
- *where* the password is (never the password itself);
|
|
206
|
+
- copy-paste curl examples.
|
|
207
|
+
|
|
208
|
+
A first call from a terminal, against the background service:
|
|
209
|
+
|
|
210
|
+
```sh
|
|
211
|
+
STATE=~/.local/state/opencode/service.json
|
|
212
|
+
URL=$(sed -n 's/.*"url" *: *"\([^"]*\)".*/\1/p' "$STATE")
|
|
213
|
+
PW=$(sed -n 's/.*"password" *: *"\([^"]*\)".*/\1/p' "$STATE")
|
|
214
|
+
|
|
215
|
+
curl -sS -u "opencode:$PW" -H 'content-type: application/json' \
|
|
216
|
+
-X POST "$URL/api/rpc/apex/status?location%5Bdirectory%5D=$PWD" -d '{"input":{}}'
|
|
217
|
+
# → {"output":{"modules":{...},"version":"0.2.x","uptimeMs":...,"endpoint":{...}}}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
Run a tool from a script, here `read` in the current project:
|
|
221
|
+
|
|
222
|
+
```sh
|
|
223
|
+
curl -sS -u "opencode:$PW" -H 'content-type: application/json' \
|
|
224
|
+
-X POST "$URL/api/rpc/apex/tools.run?location%5Bdirectory%5D=$PWD" \
|
|
225
|
+
-d '{"input":{"tool":"read","input":{"path":"README.md"}}}'
|
|
226
|
+
# → {"output":{"ok":true,"tool":"read","agent":"build","content":"...","durationMs":14}}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
## Tools added to your agents
|
|
230
|
+
|
|
231
|
+
| Tool | Module | What it does |
|
|
232
|
+
| --- | --- | --- |
|
|
233
|
+
| `apex_subscribe` | events | Creates an event subscription for the calling session (filters, prompt template, agent to switch to, delivery mode) |
|
|
234
|
+
| `apex_unsubscribe` | events | Removes a subscription by id. Subscriptions from config are read-only |
|
|
235
|
+
| `apex_list_subscriptions` | events | Lists subscriptions; config ones are marked read-only |
|
|
236
|
+
| `apex_callback_endpoint` | events | How an external program reaches this server: URL, RPC URLs for this project, auth, curl examples |
|
|
237
|
+
| `apex_set_callback_url` | events | Sets or clears the server's public URL (tunnel / reverse proxy), for senders on other machines |
|
|
238
|
+
| `apex_advisor_decide` | advisor | The advisor agent's only tool: `allow` / `deny` + reason |
|
|
239
|
+
| `apex_guard_report` | guard | Report of what each agent attempted and what was decided |
|
|
240
|
+
| `browser_target` | browser | Chooses which browser serves `browser.*`: `external` (CDP), `in-app` (desktop app) or `auto` |
|
|
241
|
+
|
|
242
|
+
apex also registers two hidden agents: `apex-advisor` for the Advisor and `apex-runner`, the
|
|
243
|
+
technical session behind `tools.run`.
|
|
244
|
+
|
|
245
|
+
## RPC reference
|
|
246
|
+
|
|
247
|
+
Namespace `apex`. Inputs and outputs go inside the `input` / `output` envelopes shown above.
|
|
248
|
+
|
|
249
|
+
| Method | Input | Output |
|
|
250
|
+
| --- | --- | --- |
|
|
251
|
+
| `ping` | `{ payload? }` | `{ pong, timestamp }` |
|
|
252
|
+
| `status` | `{}` | `{ modules, version, uptimeMs, endpoint }` |
|
|
253
|
+
| `server.info` | `{}` | same as the `apex_callback_endpoint` tool |
|
|
254
|
+
| `events.ingest` | `{ source, type?, payload, eventID? }` | `{ accepted, eventID, delivered[] }` |
|
|
255
|
+
| `tools.run` | `{ tool, input?, agent?, timeoutMs? }` | `{ ok, tool, agent, output?, content?, metadata?, error?, durationMs }` |
|
|
256
|
+
| `redact.process` | `{ text, mode? }` | `{ redacted, findings }` |
|
|
257
|
+
|
|
258
|
+
- `events.ingest`:
|
|
259
|
+
- `delivered` lists the subscriptions that received the event. An empty list means none
|
|
260
|
+
matched.
|
|
261
|
+
- Re-sending the same `eventID` within 5 minutes is ignored, so retries are safe.
|
|
262
|
+
- `tools.run` runs **one** tool, with the permissions of the agent `events.tools.agent`
|
|
263
|
+
(default `build`) or the `agent` you pass.
|
|
264
|
+
- `events.tools.allow` / `deny` limit which tools can be run this way.
|
|
265
|
+
- `question`, `subagent`, `execute` and the `apex_*` tools are denied by default.
|
|
266
|
+
- Nobody is around to answer an "ask" permission: it waits for the Advisor, or until
|
|
267
|
+
`timeoutMs` (default 120 s).
|
|
268
|
+
|
|
269
|
+
## Security notes
|
|
270
|
+
|
|
271
|
+
- **The server password is a full credential.** Anyone who has it can drive your agents
|
|
272
|
+
through the OpenCode API. With `events.ingest` they can inject prompts; with `tools.run`
|
|
273
|
+
they can run tools. Keep the file at mode 0600, and don't paste the password into scripts,
|
|
274
|
+
unit files or chats: read it at run time, as the examples do.
|
|
275
|
+
- To receive webhooks from the Internet, expose the **relay**, protected by its own token.
|
|
276
|
+
Never expose the OpenCode server itself.
|
|
277
|
+
- Redact encrypts with the key in `redact.key` (`env:VAR`, `file:/path`, `hex:…`, `base64:…`).
|
|
278
|
+
Without one, it generates a key and keeps it in `~/.config/opencode/apex.key` (mode 0600).
|
|
279
|
+
Back that key up: if you lose it, the markers already in your session history can't be
|
|
280
|
+
restored.
|
|
281
|
+
|
|
282
|
+
## Troubleshooting
|
|
283
|
+
|
|
284
|
+
See [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). The most common cases:
|
|
285
|
+
|
|
286
|
+
| Symptom | Fix |
|
|
287
|
+
| --- | --- |
|
|
288
|
+
| `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). |
|
|
289
|
+
| Plugin fails to load after an OpenCode upgrade | Reinstall it, see [Update / reinstall](#update--reinstall). |
|
|
290
|
+
| The automation stopped after an hour | Expected if it lived inside OpenCode. Move the clock outside (cron / systemd). |
|
|
291
|
+
|
|
292
|
+
## Development
|
|
164
293
|
|
|
165
294
|
```bash
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
bun -e "await import('./index.ts'); console.log('OK')" # smoke de carga
|
|
169
|
-
bun test/events.test.ts # events (56)
|
|
170
|
-
bun test test/guard.test.ts # guard (56)
|
|
171
|
-
TEST_CDP_URL=<puerto> bun test test/browser.test.ts # browser (10; p.ej. 9333)
|
|
172
|
-
node scripts/check-install.mjs # instala como OpenCode: 1 sola copia de effect
|
|
295
|
+
git clone https://github.com/aorizondo/opencode-apex.git
|
|
296
|
+
cd opencode-apex && bun install
|
|
173
297
|
```
|
|
174
298
|
|
|
175
|
-
|
|
299
|
+
To run the local checkout instead of the npm package, point OpenCode at the directory:
|
|
300
|
+
`"plugins": [{ "package": "/path/to/opencode-apex" }]`.
|
|
176
301
|
|
|
177
302
|
```bash
|
|
178
|
-
|
|
179
|
-
|
|
303
|
+
bun test/events.test.ts # events, RPC, server discovery, tools.run, skills
|
|
304
|
+
bun test test/guard.test.ts # guard
|
|
305
|
+
TEST_CDP_URL=9333 bun test test/browser.test.ts # browser (needs Chromium with --remote-debugging-port=9333)
|
|
306
|
+
npm run typecheck # tsc --noEmit
|
|
307
|
+
npm run check:install # installs the package like OpenCode does; fails on duplicate `effect`
|
|
180
308
|
```
|
|
181
309
|
|
|
182
|
-
|
|
310
|
+
`npm publish` runs tests, typecheck and the install check first (`prepublishOnly`).
|
|
311
|
+
|
|
312
|
+
**Dependency rule.** OpenCode (≥ 2.1) serves `effect` and `@opencode/plugin` to plugins from
|
|
313
|
+
its own copy, so apex never pins `effect`: it is only an optional peer. The other `@opencode/*`
|
|
314
|
+
packages, such as `@opencode/schema`, do come from apex's own install and must match the host.
|
|
315
|
+
That's why `@opencode/plugin` is a `^2.1.1` dependency, and why apex is reinstalled after
|
|
316
|
+
upgrading OpenCode. See [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) before changing
|
|
317
|
+
dependencies.
|
|
318
|
+
|
|
319
|
+
```
|
|
320
|
+
opencode-apex/
|
|
321
|
+
├── index.ts # entry point: Plugin.define, config loading, module registration
|
|
322
|
+
├── redact.ts · events.ts · advisor.ts · guard.ts · browser.ts # the five modules
|
|
323
|
+
├── browser/ # CDP client, endpoint discovery, the 45 browser actions
|
|
324
|
+
├── core/
|
|
325
|
+
│ ├── config.ts # config hierarchy, merge, comments, Zod schema
|
|
326
|
+
│ ├── rpc.ts # the "apex" RPC namespace
|
|
327
|
+
│ ├── server-endpoint.ts# server URL + auth discovery for external programs
|
|
328
|
+
│ ├── tools-run.ts # tools.run: allow/deny, permission agent, runner session
|
|
329
|
+
│ ├── skills.ts # registers the skills shipped in skills/
|
|
330
|
+
│ ├── compat.ts # load-time warnings when versions drift from OpenCode
|
|
331
|
+
│ └── … # redact engine, patterns, crypto, conditions, guard, advisor
|
|
332
|
+
├── skills/apex-callbacks/ # agent guide: SKILL.md + references/ (relays, reachability, run-anywhere, examples)
|
|
333
|
+
├── scripts/check-install.mjs # pre-publish install check
|
|
334
|
+
├── test/ # events, guard, browser suites
|
|
335
|
+
└── docs/ # CONFIG · REDACT · EVENTS · ADVISOR · GUARD · BROWSER · TROUBLESHOOTING
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
Changes: [CHANGELOG.md](CHANGELOG.md).
|
|
339
|
+
|
|
340
|
+
## License
|
|
183
341
|
|
|
184
|
-
|
|
185
|
-
conocidos (`ast._tag`, ENOENT de config, versiones de `effect`), y checklist para
|
|
186
|
-
módulos nuevos.
|
|
342
|
+
[MIT](LICENSE)
|
package/browser/endpoint.ts
CHANGED
|
@@ -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
|
|
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
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Compatibilidad con la versión de OpenCode que carga el plugin.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* (
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* Aquí se detecta al cargar
|
|
4
|
+
* Desde 2.1, OpenCode sirve a los plugins `effect` y `@opencode/plugin` desde SU copia
|
|
5
|
+
* (packages/plugin/src/runtime.ts): esos dos nunca se desalinean. Lo que sí viene del
|
|
6
|
+
* node_modules de apex son los demás `@opencode/*` (`@opencode/schema`, `@opencode/client`,
|
|
7
|
+
* `@opencode/plugin-browser`), que corren sobre el `effect` del host: si son de una versión
|
|
8
|
+
* anterior, el fallo llega críptico (`Schema.isStartsWith is not a function`).
|
|
9
|
+
* Aquí se detecta al cargar (OpenCode más nuevo que el `@opencode/plugin` instalado, o dos
|
|
10
|
+
* copias de `effect` en disco) y se dice qué hacer.
|
|
10
11
|
*
|
|
11
12
|
* La caché npm de plugins de OpenCode no se refresca sola: tras actualizar OpenCode,
|
|
12
13
|
* apex sigue con las dependencias de cuando se instaló hasta que se reinstala.
|
|
@@ -56,8 +57,8 @@ function readPackage(dir: string): { name?: string; version?: string } | null {
|
|
|
56
57
|
|
|
57
58
|
/** Cómo forzar que OpenCode reinstale apex y sus dependencias. */
|
|
58
59
|
const REINSTALL =
|
|
59
|
-
"
|
|
60
|
-
"(
|
|
60
|
+
"stop OpenCode, delete ~/.cache/opencode/npm/opencode-apex@* and start it again " +
|
|
61
|
+
"(in 2.1 `opencode plugin update` only handles TUI plugins)"
|
|
61
62
|
|
|
62
63
|
/** major.minor numérico, o null si no se puede leer. */
|
|
63
64
|
function minor(version: string | undefined): [number, number] | null {
|
|
@@ -88,14 +89,14 @@ export function compatibilityWarnings(
|
|
|
88
89
|
|
|
89
90
|
if (ownEffect && pluginEffect && ownEffect.dir !== pluginEffect.dir) {
|
|
90
91
|
warnings.push(
|
|
91
|
-
`
|
|
92
|
-
`
|
|
92
|
+
`two copies of effect: apex uses ${ownEffect.version} and @opencode/plugin ${pluginEffect.version}. ` +
|
|
93
|
+
`Reinstall the plugin: ${REINSTALL}.`,
|
|
93
94
|
)
|
|
94
95
|
}
|
|
95
96
|
if (plugin && newerMinor(hostVersion, plugin.version)) {
|
|
96
97
|
warnings.push(
|
|
97
|
-
`OpenCode ${hostVersion}
|
|
98
|
-
`
|
|
98
|
+
`OpenCode ${hostVersion} is newer than the @opencode/plugin ${plugin.version} installed with apex. ` +
|
|
99
|
+
`Reinstall it to realign versions: ${REINSTALL}.`,
|
|
99
100
|
)
|
|
100
101
|
}
|
|
101
102
|
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
|
|
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"
|
|
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
|
|
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()
|