opencode-apex 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +80 -48
- package/LICENSE +21 -0
- package/README.md +299 -151
- package/browser/endpoint.ts +4 -1
- package/browser.ts +2 -1
- package/core/compat.ts +6 -6
- 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 -190
- 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
|
@@ -1,89 +1,91 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: apex-callbacks
|
|
3
|
-
description:
|
|
3
|
+
description: Automations that wake an agent up from outside the conversation with opencode-apex (OpenCode V2). Use it when asked to watch something periodically ("check every 5 minutes whether X is up and diagnose it if it goes down"), to notify when a job finishes or after a reboot, to receive webhooks from external services (GitHub, n8n, Stripe…) or to use OpenCode tools (MCP, browser) from a script. Covers finding the server URL, subscribing, writing the watcher script, scheduling it with systemd/cron, the webhook relay and the tools.run RPC.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
#
|
|
6
|
+
# Automations with apex: callbacks, webhooks and watchers
|
|
7
7
|
|
|
8
|
-
##
|
|
8
|
+
## The idea in one sentence
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
OpenCode
|
|
12
|
-
|
|
13
|
-
|
|
10
|
+
The **clock** (cron/systemd) and the **door** (a webhook relay) live OUTSIDE OpenCode;
|
|
11
|
+
OpenCode only works when it is called through **RPC** (an authenticated HTTP request to
|
|
12
|
+
the OpenCode server). When something deserves attention, the outside process calls
|
|
13
|
+
`events.ingest` and a **subscription** wakes the agent up with the task.
|
|
14
14
|
|
|
15
15
|
```
|
|
16
|
-
|
|
16
|
+
outside process ──(tools.run: uses OpenCode tools, optional)──▶ OpenCode
|
|
17
17
|
│
|
|
18
|
-
└─
|
|
18
|
+
└─ criterion met? ──(events.ingest)──▶ subscription ──▶ the agent wakes up
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
**
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
segundos la primera vez).
|
|
21
|
+
**Never** keep the watching inside OpenCode (a `sleep` loop in the shell tool, a timer in a
|
|
22
|
+
plugin): OpenCode unloads the plugins of a directory after **60 minutes without activity**
|
|
23
|
+
and, after a restart, does not load them again until someone uses that directory. An RPC
|
|
24
|
+
call, instead, loads the directory by itself (a few seconds on the first call).
|
|
26
25
|
|
|
27
|
-
##
|
|
26
|
+
## Step 0 — Where do I point? (ask, do not guess)
|
|
28
27
|
|
|
29
|
-
|
|
28
|
+
Call the tool **`apex_callback_endpoint`**. It returns:
|
|
30
29
|
|
|
31
|
-
|
|
|
30
|
+
| Field | What it is |
|
|
32
31
|
| --- | --- |
|
|
33
|
-
| `baseUrl` | URL
|
|
34
|
-
| `rpc.ingest` / `rpc.toolsRun` | URLs
|
|
35
|
-
| `auth.username` |
|
|
36
|
-
| `auth.password` |
|
|
37
|
-
| `publicUrl` | URL
|
|
38
|
-
| `examples` | curl
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
- **
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
-
|
|
45
|
-
|
|
46
|
-
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
32
|
+
| `baseUrl` | URL of the OpenCode server from this machine (`null` → ask the user to set `events.server.url`) |
|
|
33
|
+
| `rpc.ingest` / `rpc.toolsRun` | Full URLs of the methods, already carrying this project's `location[directory]` |
|
|
34
|
+
| `auth.username` | always `opencode` (HTTP Basic) |
|
|
35
|
+
| `auth.password` | WHERE the password is: `{kind:"file", file, field}` (the service's `0600` record) or `{kind:"env", env}`; `shell` prints it in a terminal |
|
|
36
|
+
| `publicUrl` | URL for senders on **other** machines (tunnel/proxy), if one exists |
|
|
37
|
+
| `examples` | `curl` commands ready to copy |
|
|
38
|
+
|
|
39
|
+
Rules:
|
|
40
|
+
- **Never write the password** into scripts, systemd units, crontab or the conversation:
|
|
41
|
+
scripts read it when they run, from `auth.password.file` (the `pw` function below) or
|
|
42
|
+
from the variable named in `auth.password.env`.
|
|
43
|
+
- Use the `rpc.*` URLs as they are: `location[directory]` routes the call to THIS project
|
|
44
|
+
(its subscriptions, its MCP tools).
|
|
45
|
+
- Another machine cannot reach `127.0.0.1`: it needs a tunnel or proxy to `baseUrl`. Announce
|
|
46
|
+
it with `apex_set_callback_url({url})`, have the sender use that base instead of
|
|
47
|
+
`baseUrl`, and clear it with `{url: null}` when done.
|
|
48
|
+
|
|
49
|
+
## Step 1 — Subscribe (who wakes up, and with which task)
|
|
50
|
+
|
|
51
|
+
With the tool **`apex_subscribe`** (the subscription is bound to the session that calls it):
|
|
52
52
|
|
|
53
53
|
```jsonc
|
|
54
54
|
{
|
|
55
55
|
"filters": [{ "field": "type", "operator": "equals", "value": "server.down" }],
|
|
56
|
-
"agent": "build", //
|
|
57
|
-
"promptTemplate": "
|
|
58
|
-
"deliverAs": "prompt", // prompt =
|
|
56
|
+
"agent": "build", // agent the session switches to before delivery (optional)
|
|
57
|
+
"promptTemplate": "Server {{payload.host}} is down ({{payload.detail}}). Diagnose the cause and propose a fix.",
|
|
58
|
+
"deliverAs": "prompt", // prompt = a new turn of the agent
|
|
59
59
|
"delivery": "queue"
|
|
60
60
|
}
|
|
61
61
|
```
|
|
62
62
|
|
|
63
|
-
-
|
|
64
|
-
|
|
65
|
-
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
63
|
+
- Filter by `type` (and by `source` if there are several senders): a subscription without
|
|
64
|
+
filters matches **every** event.
|
|
65
|
+
- The task goes in the template: it is the prompt the agent will receive. Placeholders:
|
|
66
|
+
`{{type}}`, `{{source}}`, `{{eventID}}`, `{{payload}}` (whole payload as JSON),
|
|
67
|
+
`{{payload.<field>}}`.
|
|
68
|
+
- `deliverAs: "synthetic"` + `resume: true` also wakes the agent; with `resume: false` the
|
|
69
|
+
message stays passive until the next turn.
|
|
70
|
+
|
|
71
|
+
## Step 2 — The watcher script
|
|
72
|
+
|
|
73
|
+
What a good watcher does:
|
|
74
|
+
1. **Only notifies on state changes** (up → down, and optionally down → up), not on every
|
|
75
|
+
check: it keeps the last state in a file.
|
|
76
|
+
2. **Stable `eventID` per incident** (e.g. `server.down-<host>-<time it went down>`): sending
|
|
77
|
+
it again does not duplicate the delivery.
|
|
78
|
+
3. Tells "the service is down" apart from "I could not check" (network timeout, failing
|
|
79
|
+
MCP server): they are different events.
|
|
80
|
+
4. Retries the call to OpenCode with backoff: right after a restart it takes a few seconds.
|
|
79
81
|
|
|
80
82
|
```sh
|
|
81
83
|
#!/bin/sh
|
|
82
|
-
# watch-http.sh —
|
|
83
|
-
TARGET="https://
|
|
84
|
-
INGEST='<rpc.ingest
|
|
85
|
-
PASSWORD_FILE='<auth.password.file
|
|
86
|
-
#
|
|
84
|
+
# watch-http.sh — tells apex when a URL goes from up to down (and when it recovers).
|
|
85
|
+
TARGET="https://my-server.example.com/health"
|
|
86
|
+
INGEST='<rpc.ingest from apex_callback_endpoint>'
|
|
87
|
+
PASSWORD_FILE='<auth.password.file from apex_callback_endpoint>'
|
|
88
|
+
# The password is read on every run (if auth.password.kind is "env": printf %s "$OPENCODE_SERVER_PASSWORD").
|
|
87
89
|
pw() { sed -n 's/.*"password" *: *"\([^"]*\)".*/\1/p' "$PASSWORD_FILE"; }
|
|
88
90
|
STATE="$HOME/.local/state/apex-watch/$(printf %s "$TARGET" | md5sum | cut -c1-12)"
|
|
89
91
|
mkdir -p "$(dirname "$STATE")"
|
|
@@ -91,7 +93,7 @@ mkdir -p "$(dirname "$STATE")"
|
|
|
91
93
|
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 "$TARGET")
|
|
92
94
|
case "$code" in 2??|3??) now=up ;; *) now=down ;; esac
|
|
93
95
|
before=$(cat "$STATE" 2>/dev/null || echo up)
|
|
94
|
-
[ "$now" = "$before" ] && exit 0 #
|
|
96
|
+
[ "$now" = "$before" ] && exit 0 # no change: nobody gets bothered
|
|
95
97
|
echo "$now" > "$STATE"
|
|
96
98
|
|
|
97
99
|
type="server.$now"; since=$(date +%s)
|
|
@@ -105,88 +107,90 @@ done
|
|
|
105
107
|
exit 1
|
|
106
108
|
```
|
|
107
109
|
|
|
108
|
-
###
|
|
110
|
+
### If the check needs an OpenCode tool → `tools.run`
|
|
109
111
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
+
When what you have to check only exists inside OpenCode (an MCP server such as Easypanel,
|
|
113
|
+
the browser, `webfetch`…), the script runs that tool through RPC, without a model:
|
|
112
114
|
|
|
113
115
|
```sh
|
|
114
|
-
TOOLS_RUN='<rpc.toolsRun
|
|
116
|
+
TOOLS_RUN='<rpc.toolsRun from apex_callback_endpoint>'
|
|
115
117
|
out=$(curl -sS --max-time 150 -X POST "$TOOLS_RUN" -u "opencode:$(pw)" \
|
|
116
118
|
-H 'content-type: application/json' \
|
|
117
|
-
-d '{"input":{"tool":"<
|
|
118
|
-
echo "$out" | jq -e '.output.ok' >/dev/null || { echo "
|
|
119
|
+
-d '{"input":{"tool":"<exact tool id>","input":{ ... }}}')
|
|
120
|
+
echo "$out" | jq -e '.output.ok' >/dev/null || { echo "could not check: $(echo "$out" | jq -r '.output.error // .')"; exit 2; }
|
|
119
121
|
echo "$out" | jq -r '.output.content'
|
|
120
122
|
```
|
|
121
123
|
|
|
122
|
-
- `tool`
|
|
123
|
-
`<
|
|
124
|
-
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
124
|
+
- `tool` is the exact id of the tool as you see it (MCP tools are usually
|
|
125
|
+
`<server>_<tool>`). Try it by hand first and copy its input.
|
|
126
|
+
- Reply: `{"output":{"ok","tool","agent","output?","content?","metadata?","error?","durationMs"}}`.
|
|
127
|
+
Failures (denied, unknown tool, permission blocked, timeout) come as `ok: false` + `error`.
|
|
128
|
+
- The **permissions** of the agent `events.tools.agent` (default `build`) apply, or those of
|
|
129
|
+
the `agent` you pass in the call. With nobody watching, an "ask" permission waits for the
|
|
130
|
+
apex advisor or until `timeoutMs` (120 s by default): ask the user for an `allow` rule if
|
|
131
|
+
needed.
|
|
132
|
+
- `events.tools.allow` / `deny` limit which tools can be run this way (`question`,
|
|
133
|
+
`subagent`, `execute` and the `apex_*` tools are denied by default).
|
|
130
134
|
|
|
131
|
-
##
|
|
135
|
+
## Step 3 — Schedule it (the clock)
|
|
132
136
|
|
|
133
|
-
|
|
137
|
+
Preferred: a **systemd user timer** (survives reboots, keeps logs):
|
|
134
138
|
|
|
135
139
|
```sh
|
|
136
140
|
mkdir -p ~/.config/systemd/user ~/.local/bin
|
|
137
|
-
install -m 0755 watch-http.sh ~/.local/bin/apex-watch-
|
|
138
|
-
cat > ~/.config/systemd/user/apex-watch-
|
|
141
|
+
install -m 0755 watch-http.sh ~/.local/bin/apex-watch-my-server.sh
|
|
142
|
+
cat > ~/.config/systemd/user/apex-watch-my-server.service <<'EOF'
|
|
139
143
|
[Unit]
|
|
140
|
-
Description=apex watch:
|
|
144
|
+
Description=apex watch: my-server
|
|
141
145
|
[Service]
|
|
142
146
|
Type=oneshot
|
|
143
|
-
ExecStart=%h/.local/bin/apex-watch-
|
|
147
|
+
ExecStart=%h/.local/bin/apex-watch-my-server.sh
|
|
144
148
|
EOF
|
|
145
|
-
cat > ~/.config/systemd/user/apex-watch-
|
|
149
|
+
cat > ~/.config/systemd/user/apex-watch-my-server.timer <<'EOF'
|
|
146
150
|
[Unit]
|
|
147
|
-
Description=apex watch:
|
|
151
|
+
Description=apex watch: my-server every 5 min
|
|
148
152
|
[Timer]
|
|
149
153
|
OnBootSec=2min
|
|
150
154
|
OnUnitActiveSec=5min
|
|
151
155
|
[Install]
|
|
152
156
|
WantedBy=timers.target
|
|
153
157
|
EOF
|
|
154
|
-
systemctl --user daemon-reload && systemctl --user enable --now apex-watch-
|
|
155
|
-
systemctl --user list-timers | grep apex-watch #
|
|
156
|
-
journalctl --user -u apex-watch-
|
|
158
|
+
systemctl --user daemon-reload && systemctl --user enable --now apex-watch-my-server.timer
|
|
159
|
+
systemctl --user list-timers | grep apex-watch # check
|
|
160
|
+
journalctl --user -u apex-watch-my-server -n 20 # logs
|
|
157
161
|
```
|
|
158
162
|
|
|
159
|
-
|
|
163
|
+
Alternative: `crontab -e` → `*/5 * * * * ~/.local/bin/apex-watch-my-server.sh`.
|
|
160
164
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
165
|
+
Before calling the task done: **run the script once by hand** and, if you can, trigger the
|
|
166
|
+
event (or send a test `events.ingest`) to see the subscription wake the agent. Tell the user
|
|
167
|
+
what you installed and how to remove it:
|
|
164
168
|
|
|
165
169
|
```sh
|
|
166
|
-
systemctl --user disable --now apex-watch-
|
|
167
|
-
rm ~/.config/systemd/user/apex-watch-
|
|
170
|
+
systemctl --user disable --now apex-watch-my-server.timer
|
|
171
|
+
rm ~/.config/systemd/user/apex-watch-my-server.{service,timer} ~/.local/bin/apex-watch-my-server.sh
|
|
168
172
|
```
|
|
169
|
-
…
|
|
173
|
+
…plus `apex_unsubscribe({id})` for the subscription.
|
|
170
174
|
|
|
171
|
-
## Webhooks (
|
|
175
|
+
## Webhooks (external services that call over HTTP)
|
|
172
176
|
|
|
173
|
-
|
|
174
|
-
|
|
177
|
+
A webhook is a callback with an **intermediate process** that turns the service's HTTP call
|
|
178
|
+
into `events.ingest`. OpenCode does not expose a webhook URL of its own.
|
|
175
179
|
|
|
176
|
-
- **n8n**:
|
|
177
|
-
|
|
180
|
+
- **n8n**: *Webhook* node → *HTTP Request* node `POST <rpc.ingest>`, Basic auth (credential
|
|
181
|
+
`opencode` + password), body
|
|
178
182
|
`{"input":{"source":"github","type":"{{$json.headers['x-github-event']}}","eventID":"{{$json.headers['x-github-delivery']}}","payload":{{JSON.stringify($json.body)}}}}`.
|
|
179
|
-
|
|
180
|
-
- **
|
|
181
|
-
|
|
183
|
+
If n8n runs on another machine it needs to reach the server (tunnel/proxy, `publicUrl`).
|
|
184
|
+
- **Minimal relay** (Node ≥ 18, no dependencies) on the OpenCode machine, as a systemd user
|
|
185
|
+
service. It checks its own token before forwarding anything:
|
|
182
186
|
|
|
183
187
|
```js
|
|
184
188
|
// webhook-relay.mjs — POST http://<host>:<port>/<type>?token=<RELAY_TOKEN> → apex events.ingest
|
|
185
189
|
import { createServer } from "node:http"
|
|
186
190
|
import { readFileSync } from "node:fs"
|
|
187
191
|
const { INGEST, PASSWORD_FILE, RELAY_TOKEN, PORT = "8787", HOST = "127.0.0.1", SOURCE = "webhook" } = process.env
|
|
188
|
-
if (!INGEST || !RELAY_TOKEN) throw new Error("
|
|
189
|
-
//
|
|
192
|
+
if (!INGEST || !RELAY_TOKEN) throw new Error("INGEST or RELAY_TOKEN missing")
|
|
193
|
+
// Read on every request: survives service restarts without restarting the relay.
|
|
190
194
|
const password = () =>
|
|
191
195
|
PASSWORD_FILE ? JSON.parse(readFileSync(PASSWORD_FILE, "utf8")).password : process.env.OPENCODE_SERVER_PASSWORD
|
|
192
196
|
createServer(async (req, res) => {
|
|
@@ -207,33 +211,35 @@ createServer(async (req, res) => {
|
|
|
207
211
|
const r = await fetch(INGEST, { method: "POST", headers: { authorization: auth, "content-type": "application/json" }, body: JSON.stringify({ input }) })
|
|
208
212
|
res.writeHead(r.ok ? 202 : 502, { "content-type": "application/json" }).end(await r.text())
|
|
209
213
|
} catch (error) {
|
|
210
|
-
res.writeHead(502).end(String(error)) // OpenCode
|
|
214
|
+
res.writeHead(502).end(String(error)) // OpenCode stopped: the sender will retry
|
|
211
215
|
}
|
|
212
216
|
}).listen(Number(PORT), HOST)
|
|
213
217
|
```
|
|
214
218
|
|
|
215
|
-
|
|
216
|
-
`auth.password.kind`
|
|
217
|
-
`RELAY_TOKEN`
|
|
218
|
-
|
|
219
|
+
Configure it with `INGEST` and `PASSWORD_FILE` (from `apex_callback_endpoint`; if
|
|
220
|
+
`auth.password.kind` is `env`, export `OPENCODE_SERVER_PASSWORD` instead) and a random
|
|
221
|
+
`RELAY_TOKEN` (`openssl rand -hex 24`). To receive from the Internet, expose **the relay**
|
|
222
|
+
(not the OpenCode server) through a tunnel.
|
|
219
223
|
|
|
220
|
-
##
|
|
224
|
+
## Security
|
|
221
225
|
|
|
222
|
-
-
|
|
223
|
-
|
|
224
|
-
-
|
|
225
|
-
token
|
|
226
|
-
-
|
|
226
|
+
- Whoever can call `events.ingest` steers the agent, and `tools.run` runs tools: both
|
|
227
|
+
require the server password. Treat it as a credential.
|
|
228
|
+
- Files holding secrets: `0600`. A relay or tunnel exposed to the Internet carries its own
|
|
229
|
+
token and never forwards without checking it.
|
|
230
|
+
- Do not widen permissions to make a watcher work without telling the user.
|
|
227
231
|
|
|
228
|
-
##
|
|
232
|
+
## Contract
|
|
229
233
|
|
|
230
|
-
|
|
|
234
|
+
| RPC method | Input | Output |
|
|
231
235
|
| --- | --- | --- |
|
|
232
|
-
| `events.ingest` | `{source, type?, payload, eventID?}` | `{accepted, eventID, delivered[]}` |
|
|
236
|
+
| `events.ingest` | `{source, type?, payload, eventID?}` | `{accepted, eventID, delivered[]}` (or `error`) |
|
|
233
237
|
| `tools.run` | `{tool, input?, agent?, timeoutMs?}` | `{ok, tool, agent, output?, content?, metadata?, error?, durationMs}` |
|
|
234
|
-
| `server.info` | `{}` |
|
|
235
|
-
| `status` / `ping` | `{}` |
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
`{"input":{…}}`,
|
|
239
|
-
|
|
238
|
+
| `server.info` | `{}` | the same as `apex_callback_endpoint` (without `examples`) |
|
|
239
|
+
| `status` / `ping` | `{}` | plugin status / `{pong, timestamp}` |
|
|
240
|
+
|
|
241
|
+
All of them: `POST <baseUrl>/api/rpc/apex/<method>?location[directory]=<project>`, body
|
|
242
|
+
`{"input":{…}}`, reply `{"output":{…}}`, Basic `opencode:<password>`. A call missing a
|
|
243
|
+
required field is rejected with HTTP 400 (`rpc.invalid_input`). `delivered: []` means no
|
|
244
|
+
subscription received the event (check the filters and the target session) or the
|
|
245
|
+
`eventID` was already delivered in the last 5 minutes.
|