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.
@@ -0,0 +1,261 @@
1
+ # Copyable examples
2
+
3
+ All of them take their values from `apex_callback_endpoint`:
4
+ - `INGEST` = `rpc.ingest`;
5
+ - `TOOLS_RUN` = `rpc.toolsRun`;
6
+ - `PASSWORD_FILE` = `auth.password.file`. If `auth.password.kind` is `env`, set `OPENCODE_SERVER_PASSWORD` instead.
7
+
8
+ They read the password on every call and never print it. Pick the language the machine already has. The contract is the same everywhere.
9
+
10
+ ## 1. Watcher in sh + curl (Linux, macOS, WSL)
11
+
12
+ Notifies only when a URL goes from up to down, and back:
13
+
14
+ ```sh
15
+ #!/bin/sh
16
+ # watch-http.sh — tells apex when a URL goes from up to down (and when it recovers).
17
+ TARGET="https://my-server.example.com/health"
18
+ INGEST='<rpc.ingest>'
19
+ PASSWORD_FILE='<auth.password.file>'
20
+ pw() { sed -n 's/.*"password" *: *"\([^"]*\)".*/\1/p' "$PASSWORD_FILE"; } # env kind: printf %s "$OPENCODE_SERVER_PASSWORD"
21
+ STATE="$HOME/.local/state/apex-watch/$(printf %s "$TARGET" | cksum | cut -d' ' -f1)"
22
+ mkdir -p "$(dirname "$STATE")"
23
+
24
+ code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 "$TARGET")
25
+ case "$code" in 2??|3??) now=up ;; *) now=down ;; esac
26
+ before=$(cat "$STATE" 2>/dev/null || echo up)
27
+ [ "$now" = "$before" ] && exit 0 # no change: nobody gets bothered
28
+ echo "$now" > "$STATE"
29
+
30
+ type="server.$now"; since=$(date +%s)
31
+ body=$(printf '{"input":{"source":"watch-http","type":"%s","eventID":"%s-%s","payload":{"host":"%s","detail":"HTTP %s"}}}' \
32
+ "$type" "$type" "$since" "$TARGET" "$code")
33
+ for i in 1 2 3 4 5; do
34
+ curl -sS --fail --max-time 30 -X POST "$INGEST" -u "opencode:$(pw)" \
35
+ -H 'content-type: application/json' -d "$body" && exit 0
36
+ sleep $((i * 10))
37
+ done
38
+ exit 1
39
+ ```
40
+
41
+ **With an OpenCode or MCP tool as the check** (`tools.run`, needs `jq`):
42
+
43
+ ```sh
44
+ TOOLS_RUN='<rpc.toolsRun>'
45
+ out=$(curl -sS --max-time 150 -X POST "$TOOLS_RUN" -u "opencode:$(pw)" \
46
+ -H 'content-type: application/json' \
47
+ -d '{"input":{"tool":"<exact tool id, e.g. easypanel_list_services>","input":{ },"timeoutMs":60000}}')
48
+ echo "$out" | jq -e '.output.ok' >/dev/null || { echo "could not check: $(echo "$out" | jq -r '.output.error // .')" >&2; exit 2; }
49
+ echo "$out" | jq -r '.output.content' # the tool's text output: decide here
50
+ ```
51
+
52
+ ## 2. Streaming relay in Python (stdlib only, any OS)
53
+
54
+ It reads an SSE stream and forwards each event.
55
+ - **Resume:** it resumes with `Last-Event-ID` and saves the cursor after each successful ingest.
56
+ - **Reconnect:** it reconnects with backoff.
57
+ - **Other sources:** for a WebSocket, IMAP or polling source, replace `events()` and keep the rest.
58
+
59
+ ```python
60
+ #!/usr/bin/env python3
61
+ """sse-relay.py: SSE stream -> apex events.ingest. Python >= 3.8, stdlib only, any OS."""
62
+ import base64, hashlib, json, os, pathlib, sys, time, urllib.request
63
+
64
+ STREAM = os.environ["STREAM_URL"] # the source's text/event-stream endpoint
65
+ STREAM_TOKEN = os.environ.get("STREAM_TOKEN", "") # its own credential, if any
66
+ INGEST = os.environ["INGEST"] # rpc.ingest
67
+ PASSWORD_FILE = os.environ.get("PASSWORD_FILE") # auth.password.file (or OPENCODE_SERVER_PASSWORD)
68
+ SOURCE = os.environ.get("SOURCE", "sse")
69
+ STATE = pathlib.Path(os.environ.get("STATE_DIR", pathlib.Path.home() / ".local" / "state" / "sse-relay"))
70
+ DRY_RUN = os.environ.get("DRY_RUN") == "1"
71
+
72
+
73
+ def log(*parts):
74
+ print(*parts, file=sys.stderr, flush=True)
75
+
76
+
77
+ def password():
78
+ # Read on every call: OpenCode's password changes when it restarts.
79
+ if PASSWORD_FILE:
80
+ return json.loads(pathlib.Path(PASSWORD_FILE).read_text())["password"]
81
+ return os.environ["OPENCODE_SERVER_PASSWORD"]
82
+
83
+
84
+ def ingest(event):
85
+ if DRY_RUN:
86
+ log("dry-run", json.dumps(event)[:300])
87
+ return {"delivered": []}
88
+ auth = "Basic " + base64.b64encode(f"opencode:{password()}".encode()).decode()
89
+ body = json.dumps({"input": event}).encode()
90
+ for attempt in range(8): # OpenCode restarting: wait and retry
91
+ try:
92
+ request = urllib.request.Request(INGEST, data=body, method="POST",
93
+ headers={"authorization": auth, "content-type": "application/json"})
94
+ with urllib.request.urlopen(request, timeout=30) as reply:
95
+ return json.load(reply).get("output", {})
96
+ except Exception as error:
97
+ log(f"ingest failed ({error}); retry {attempt + 1}")
98
+ time.sleep(min(60, 2 ** attempt))
99
+ raise RuntimeError("OpenCode unreachable")
100
+
101
+
102
+ def events():
103
+ """Yields {'id', 'event', 'data'} dicts from the stream (one per blank-line-terminated block)."""
104
+ headers = {"accept": "text/event-stream"}
105
+ if STREAM_TOKEN:
106
+ headers["authorization"] = f"Bearer {STREAM_TOKEN}"
107
+ cursor = STATE / "cursor"
108
+ if cursor.exists():
109
+ headers["last-event-id"] = cursor.read_text().strip()
110
+ # Read timeout: the source must send data or a ":" keep-alive at least every 90 s.
111
+ with urllib.request.urlopen(urllib.request.Request(STREAM, headers=headers), timeout=90) as stream:
112
+ message = {}
113
+ for raw in stream:
114
+ line = raw.decode("utf-8").rstrip("\r\n")
115
+ if not line:
116
+ if "data" in message:
117
+ yield message
118
+ message = {}
119
+ elif line.startswith(":") or ":" not in line:
120
+ continue
121
+ else:
122
+ field, _, value = line.partition(":")
123
+ value = value[1:] if value.startswith(" ") else value
124
+ message[field] = message[field] + "\n" + value if field == "data" and "data" in message else value
125
+
126
+
127
+ def to_event(message):
128
+ """Normalize, or return None to drop. Adapt this to your source."""
129
+ try:
130
+ data = json.loads(message["data"])
131
+ except ValueError:
132
+ data = {"text": message["data"]}
133
+ if data.get("from_me"): # never wake an agent for the user's own messages
134
+ return None
135
+ raw_id = message.get("id") or data.get("id") or hashlib.sha256(message["data"].encode()).hexdigest()[:16]
136
+ return {"source": SOURCE, "type": message.get("event", "message.received"),
137
+ "eventID": f"{SOURCE}:{raw_id}", "payload": data}
138
+
139
+
140
+ def main():
141
+ STATE.mkdir(parents=True, exist_ok=True)
142
+ delay = 1
143
+ while True:
144
+ try:
145
+ for message in events():
146
+ delay = 1
147
+ event = to_event(message)
148
+ if event:
149
+ out = ingest(event)
150
+ log(f"{event['type']} {event['eventID']} delivered={out.get('delivered')}")
151
+ if message.get("id"): # cursor only after a successful ingest
152
+ tmp = STATE / "cursor.tmp"
153
+ tmp.write_text(message["id"])
154
+ tmp.replace(STATE / "cursor")
155
+ except Exception as error:
156
+ log(f"stream lost ({error}); reconnecting in {delay}s")
157
+ time.sleep(delay)
158
+ delay = min(delay * 2, 60)
159
+
160
+
161
+ if __name__ == "__main__":
162
+ main()
163
+ ```
164
+
165
+ Run it with the four variables, `DRY_RUN=1` first, and keep it alive as in `run-anywhere.md`.
166
+
167
+ **Calling a tool from Python** (enrich before ingesting):
168
+
169
+ ```python
170
+ def run_tool(tools_run_url, tool, tool_input, timeout_ms=60000):
171
+ auth = "Basic " + base64.b64encode(f"opencode:{password()}".encode()).decode()
172
+ body = json.dumps({"input": {"tool": tool, "input": tool_input, "timeoutMs": timeout_ms}}).encode()
173
+ request = urllib.request.Request(tools_run_url, data=body, method="POST",
174
+ headers={"authorization": auth, "content-type": "application/json"})
175
+ with urllib.request.urlopen(request, timeout=timeout_ms / 1000 + 30) as reply:
176
+ out = json.load(reply)["output"]
177
+ return (out.get("content"), None) if out.get("ok") else (None, out.get("error"))
178
+ ```
179
+
180
+ ## 3. Webhook relay in Node (≥ 18, no dependencies)
181
+
182
+ It listens on a local port and checks its own token. If `GITHUB_SECRET` is set, it also checks GitHub's signature. Expose this port, not OpenCode, through a tunnel (`reachability.md`).
183
+
184
+ ```js
185
+ // webhook-relay.mjs — POST http://<host>:<port>/<type>?token=<RELAY_TOKEN> → apex events.ingest
186
+ import { createServer } from "node:http"
187
+ import { readFileSync } from "node:fs"
188
+ import { createHmac, timingSafeEqual } from "node:crypto"
189
+ const { INGEST, PASSWORD_FILE, RELAY_TOKEN, GITHUB_SECRET, PORT = "8787", HOST = "127.0.0.1", SOURCE = "webhook" } = process.env
190
+ if (!INGEST || !RELAY_TOKEN) throw new Error("INGEST or RELAY_TOKEN missing")
191
+ const same = (a, b) => {
192
+ const x = Buffer.from(String(a)), y = Buffer.from(String(b))
193
+ return x.length === y.length && timingSafeEqual(x, y)
194
+ }
195
+ // Read on every request: OpenCode's password changes when it restarts.
196
+ const password = () =>
197
+ PASSWORD_FILE ? JSON.parse(readFileSync(PASSWORD_FILE, "utf8")).password : process.env.OPENCODE_SERVER_PASSWORD
198
+ createServer(async (req, res) => {
199
+ const url = new URL(req.url, "http://relay")
200
+ if (req.method !== "POST" || !same(url.searchParams.get("token") ?? "", RELAY_TOKEN)) return res.writeHead(401).end()
201
+ const chunks = []
202
+ let size = 0
203
+ for await (const chunk of req) {
204
+ if ((size += chunk.length) > 1_000_000) return res.writeHead(413).end()
205
+ chunks.push(chunk)
206
+ }
207
+ const raw = Buffer.concat(chunks)
208
+ const h = req.headers
209
+ // GitHub signs the raw body: X-Hub-Signature-256 = "sha256=" + HMAC-SHA256(secret, body)
210
+ if (GITHUB_SECRET && !same(h["x-hub-signature-256"] ?? "", "sha256=" + createHmac("sha256", GITHUB_SECRET).update(raw).digest("hex")))
211
+ return res.writeHead(401).end()
212
+ let body
213
+ try { body = JSON.parse(raw.toString("utf8") || "{}") } catch { body = { raw: raw.toString("utf8").slice(0, 10_000) } }
214
+ const delivery = h["x-github-delivery"] ?? h["idempotency-key"] ?? h["x-request-id"]
215
+ const input = {
216
+ source: SOURCE,
217
+ type: url.pathname.slice(1) || String(h["x-github-event"] ?? h["x-event-type"] ?? "webhook"),
218
+ ...(delivery ? { eventID: `${SOURCE}:${delivery}` } : {}),
219
+ payload: { body, headers: { "content-type": h["content-type"], "user-agent": h["user-agent"] } },
220
+ }
221
+ try {
222
+ const auth = "Basic " + Buffer.from(`opencode:${password()}`).toString("base64")
223
+ const r = await fetch(INGEST, { method: "POST", headers: { authorization: auth, "content-type": "application/json" }, body: JSON.stringify({ input }) })
224
+ res.writeHead(r.ok ? 202 : 502, { "content-type": "application/json" }).end(await r.text())
225
+ } catch (error) {
226
+ res.writeHead(502).end(String(error)) // OpenCode stopped: the sender may retry
227
+ }
228
+ }).listen(Number(PORT), HOST)
229
+ ```
230
+
231
+ - Generate the token with `openssl rand -hex 24`, or `[guid]::NewGuid()` twice on Windows.
232
+ - The sender calls `https://<tunnel>/<type>?token=<RELAY_TOKEN>`.
233
+ - GitHub payloads are large. Before shipping, trim `payload.body` to the fields the agent needs.
234
+
235
+ ## 4. Ingest from PowerShell (Windows PowerShell 5.1 and PowerShell 7)
236
+
237
+ ```powershell
238
+ $ingest = '<rpc.ingest>'
239
+ $pwFile = '<auth.password.file>'
240
+ $pw = (Get-Content -Raw $pwFile | ConvertFrom-Json).password # env kind: $env:OPENCODE_SERVER_PASSWORD
241
+ $auth = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("opencode:$pw"))
242
+ $event = @{ input = @{
243
+ source = 'disk-watch'; type = 'disk.low'; eventID = "disk.low-C-$(Get-Date -Format yyyyMMdd)"
244
+ payload = @{ drive = 'C:'; freeGB = [math]::Round((Get-PSDrive C).Free / 1GB, 1) }
245
+ } }
246
+ $reply = Invoke-RestMethod -Method Post -Uri $ingest -Headers @{ Authorization = $auth } `
247
+ -ContentType 'application/json' -Body ($event | ConvertTo-Json -Depth 10)
248
+ "delivered: $($reply.output.delivered -join ', ')"
249
+ ```
250
+
251
+ `ConvertTo-Json` cuts nested objects at depth 2 by default: always pass `-Depth`.
252
+
253
+ ## 5. n8n as the receiver (no code)
254
+
255
+ Use a *Webhook* node, then an *HTTP Request* node: `POST <rpc.ingest>` with Basic auth (credential `opencode` + password) and this body:
256
+
257
+ ```
258
+ {"input":{"source":"github","type":"{{$json.headers['x-github-event']}}","eventID":"github:{{$json.headers['x-github-delivery']}}","payload":{{JSON.stringify($json.body)}}}}
259
+ ```
260
+
261
+ If n8n runs on another machine, it cannot reach OpenCode's loopback. Either tunnel to it and `apex_set_callback_url`, or let n8n store events while a local relay pulls them (`reachability.md`, option D).
@@ -0,0 +1,103 @@
1
+ # Reachability: who can connect to whom
2
+
3
+ Facts to start from:
4
+ - The **OpenCode server listens on loopback** (`127.0.0.1`) with Basic auth. Only programs on the same machine reach it.
5
+ - A laptop or home PC sits **behind NAT and a firewall**. Nothing on the Internet can open a connection to it.
6
+ - **Outbound HTTPS works almost everywhere**, so a relay that connects out to its source needs nothing special.
7
+ - Many machines sleep. While the relay is off, inbound webhooks are lost unless the provider retries. Stripe retries for days. GitHub does not retry automatically: failed deliveries must be redelivered by hand or by API within 3 days.
8
+
9
+ ## Decide
10
+
11
+ | Source | Relay runs | Works? | What to do |
12
+ | --- | --- | --- | --- |
13
+ | Stream or poll API (WebSocket, SSE, long-poll, IMAP, queue) | next to OpenCode | yes | default; nothing to expose |
14
+ | Internet webhook | next to OpenCode, behind NAT | **no** | A, B, C or D below |
15
+ | Service on the same LAN (n8n at home, a NAS) | next to OpenCode | yes, if routable | bind the relay to the LAN address, with a token and a firewall rule |
16
+ | Anything | on another machine (a VPS) | only if it can reach OpenCode | prefer D: the VPS stores events and the local relay pulls them. Otherwise tunnel to OpenCode plus `apex_set_callback_url` |
17
+ | Anything | OpenCode itself runs on a server with a public address | yes | the relay is local to it; expose the relay only |
18
+
19
+ ## A. The provider's outbound mode (best: nothing exposed)
20
+
21
+ Look for it before reaching for a tunnel:
22
+
23
+ | Provider | Outbound alternative to webhooks |
24
+ | --- | --- |
25
+ | Slack | Socket Mode (WebSocket) |
26
+ | Discord | Gateway (WebSocket) |
27
+ | Telegram Bot API | `getUpdates` long polling (instead of `setWebhook`) |
28
+ | Matrix (incl. bridges) | client `/sync` long polling |
29
+ | Gmail | `users.watch` to a Pub/Sub topic with a **pull** subscription, or IMAP IDLE |
30
+ | Any mailbox | IMAP IDLE / JMAP push |
31
+ | GitHub | `gh webhook forward` (extension `cli/gh-webhook`) forwards a repo's or org's webhooks to `localhost` over a socket. Meant for development, needs admin rights, one forwarder per hook. Polling the REST API or `gh run watch` also works |
32
+ | Stripe | `stripe listen --forward-to localhost:<port>/<path>`, for development and test mode |
33
+
34
+ ## B. A tunnel (public URL, outbound connection from your machine)
35
+
36
+ The tunnel client connects **out** to the provider. The provider gives you a public HTTPS URL that forwards to a local port. Point it at **the relay's port**, never at the OpenCode server.
37
+
38
+ **Cloudflare Tunnel (`cloudflared`)**
39
+ - **Quick tunnel**, no account, for tests: `cloudflared tunnel --url http://127.0.0.1:8787` prints a random `https://….trycloudflare.com`. The URL changes on every run and has no uptime guarantee.
40
+ - **Named tunnel**, stable. It needs a Cloudflare account and a domain on Cloudflare:
41
+ ```sh
42
+ cloudflared tunnel login
43
+ cloudflared tunnel create apex-relay
44
+ cloudflared tunnel route dns apex-relay hooks.example.com
45
+ # ~/.cloudflared/config.yml
46
+ # tunnel: <tunnel id>
47
+ # credentials-file: ~/.cloudflared/<tunnel id>.json
48
+ # ingress:
49
+ # - hostname: hooks.example.com
50
+ # service: http://127.0.0.1:8787
51
+ # - service: http_status:404
52
+ cloudflared tunnel run apex-relay # as a service: `cloudflared service install` (Linux/macOS/Windows)
53
+ ```
54
+ A tunnel created in the dashboard is installed with the token it shows: `cloudflared service install <token>`. Cloudflare Access or WAF rules can sit in front of it, but the provider's webhook must still get through. Prefer path secrets plus signature checks.
55
+
56
+ **Tailscale Funnel:** `tailscale funnel --bg 8787` publishes `https://<machine>.<tailnet>.ts.net`. Funnel must be allowed in the tailnet policy and listens only on ports 443, 8443 and 10000. **Tailscale Serve** does the same inside the tailnet only, for senders that are your own devices.
57
+
58
+ **ngrok:** `ngrok config add-authtoken <token>` once, then `ngrok http 8787`. The free plan includes one static domain: `ngrok http --url=<name>.ngrok-free.app 8787`.
59
+
60
+ Self-hostable alternatives: frp, rathole, zrok.
61
+
62
+ ## C. Reverse SSH to a VPS you control
63
+
64
+ ```sh
65
+ # on the PC: publish the local relay as 127.0.0.1:9000 on the VPS
66
+ ssh -N -o ServerAliveInterval=30 -o ExitOnForwardFailure=yes -R 127.0.0.1:9000:127.0.0.1:8787 user@vps
67
+ ```
68
+
69
+ On the VPS, a reverse proxy with TLS (Caddy, nginx) forwards `https://hooks.example.com` to `127.0.0.1:9000`. Keep the SSH session alive with `autossh` or as a service (`run-anywhere.md`). Binding to a public address on the VPS directly needs `GatewayPorts` in `sshd_config`. The proxy is cleaner.
70
+
71
+ ## D. Store-and-forward (survives the PC being off)
72
+
73
+ ```
74
+ provider ──webhook──▶ public receiver (VPS container, n8n, serverless function + queue)
75
+ verifies signature, stores event with an increasing id
76
+ local relay ──outbound SSE / long-poll / queue consumer──▶ receiver (cursor = last id)
77
+ local relay ──▶ events.ingest
78
+ ```
79
+
80
+ - Nothing is lost while the PC sleeps: events wait at the receiver.
81
+ - On reconnect the relay should skip or summarise old ones (`*.backlog`).
82
+ - The receiver needs no access to OpenCode, and OpenCode exposes nothing.
83
+ - n8n works as the receiver too: a Webhook node stores events, and the relay polls an n8n endpoint or a queue.
84
+
85
+ ## Calling OpenCode from another machine (only if you must)
86
+
87
+ Prefer running the relay next to OpenCode. If a remote sender really has to call `events.ingest` itself, for example n8n on a VPS:
88
+ 1. Tunnel or reverse-proxy **to the OpenCode server** with TLS. Anyone with the password then controls the agent, so restrict it at the edge if you can (IP allowlist, Access policy).
89
+ 2. Announce the URL with `apex_set_callback_url({url})` so `apex_callback_endpoint` reports it as `publicUrl`. The sender replaces the `baseUrl` part of `rpc.*` with it.
90
+ 3. Clear it with `apex_set_callback_url({url: null})` when done.
91
+
92
+ ## Securing an inbound relay
93
+
94
+ - **TLS** at the edge: tunnels and proxies provide it.
95
+ - **Its own secret**: a random token (`openssl rand -hex 24`) in the path or a header, compared in constant time.
96
+ - **The provider's signature**, computed over the raw body before parsing:
97
+ - GitHub: `X-Hub-Signature-256` = `sha256=` + HMAC-SHA256(secret, body).
98
+ - Stripe: `Stripe-Signature`, timestamped.
99
+ - Slack: `X-Slack-Signature`, `v0=` + HMAC of `v0:<timestamp>:<body>`.
100
+ - Reject old timestamps.
101
+ - **Limits**: maximum body size, rate limit, only `POST` on the expected path.
102
+ - **Answer fast** (2xx within a few seconds; GitHub gives up after 10 s), then ingest. Use the provider's delivery id as `eventID` for idempotency.
103
+ - Never forward headers that carry credentials into the payload.
@@ -0,0 +1,116 @@
1
+ # Relays: design guide (any language, any OS)
2
+
3
+ A relay is a long-running program that turns events from a source into `events.ingest` calls.
4
+ A watcher is the same logic run on a schedule. Everything below applies to both.
5
+
6
+ ## The loop
7
+
8
+ ```
9
+ load config, cursor and the set of recently seen ids
10
+ forever:
11
+ connect to the source outbound when possible (see reachability.md)
12
+ for each raw event:
13
+ normalize → {source, type, eventID, payload}
14
+ drop → own/outgoing items, duplicates, noise, items older than N minutes after a reconnect
15
+ enrich? → tools.run, only if the agent will need more than the event carries
16
+ decide → cheap rules here (keywords, sender, chat); judgement belongs to the agent
17
+ ingest → POST events.ingest; if OpenCode is down, keep it in an outbox and retry
18
+ checkpoint → save the cursor AFTER the ingest succeeded
19
+ on any error: log one line, wait (1 s → 2 s → … → 60 s, plus jitter), reconnect
20
+ ```
21
+
22
+ Rules that keep a relay out of trouble:
23
+ - **One responsibility.** The relay moves events. It does not reply, judge or summarise. Those are the agent's job once it is awake.
24
+ - **Never wake an agent in a loop.**
25
+ - Notify on changes, not on every check.
26
+ - Drop what the user sends themselves.
27
+ - After downtime, do not replay a flood. Skip items older than a few minutes, or send one `*.backlog` summary event.
28
+ - **Read the OpenCode URL and password on every call**, from the place `apex_callback_endpoint` named. They change when OpenCode restarts.
29
+ - **Log one line per event**: `type eventID delivered=[…]`. Never log the password, tokens or full payloads.
30
+ - Give it a **dry-run flag** that prints the normalized event instead of sending it.
31
+
32
+ ## Getting events: source catalog
33
+
34
+ | Source | Transport | Direction | Resume after a disconnect | Notes |
35
+ | --- | --- | --- | --- | --- |
36
+ | Chat apps with a socket API (Beeper Desktop `/v1/ws`, Discord Gateway, Slack Socket Mode, Home Assistant) | WebSocket | outbound | ids or timestamps you saved | Answer pings; the server closes idle sockets |
37
+ | Your own services, MCP servers that publish a stream (`/events`) | SSE (`text/event-stream`) | outbound | `Last-Event-ID` header | A blank line ends one event; `:` lines are keep-alives |
38
+ | Telegram Bot API `getUpdates`, Matrix `/sync`, many REST APIs | long polling | outbound | `offset`, `since` or `next_batch` token | Simplest to get right |
39
+ | Email | IMAP IDLE (or polling `UID SEARCH`) | outbound | `UIDVALIDITY` + last `UID` | Re-issue IDLE at least every 29 min (RFC 2177); JMAP has push too |
40
+ | Any API with "list since" | polling (watcher) | outbound | timestamp or id | Respect rate limits; poll at the slowest acceptable pace |
41
+ | Queues and brokers (MQTT, Redis Streams, NATS, AMQP, Google Pub/Sub pull, SQS) | consumer | outbound | the broker keeps the offset; ack after ingest | Best for store-and-forward from a public receiver |
42
+ | Databases | Postgres `LISTEN/NOTIFY`, change streams | outbound | a `seq`/`updated_at` column | Notify carries ids; read the row afterwards |
43
+ | Local machine | file watch, `journalctl -f`, `tail -F`, process exit | local | file offset | Watchers and CI wrappers |
44
+ | Webhooks (GitHub, Stripe, n8n, forms…) | HTTP POST to you | **inbound** | the provider's delivery id | Needs a public address: see `reachability.md` |
45
+ | An MCP server | `tools.run` from a watcher | outbound via OpenCode | whatever the tool returns | MCP has resource subscriptions on paper, rarely implemented: poll a tool instead |
46
+
47
+ If a service offers both a webhook and a socket or long-poll mode, **take the outbound one**: no tunnel, no public port, nothing lost while the relay restarts.
48
+
49
+ ## Event shape
50
+
51
+ ```jsonc
52
+ {
53
+ "source": "imap-work", // who sends: stable, one per relay/account
54
+ "type": "email.received", // what happened: dotted, noun.verb
55
+ "eventID": "imap-work:INBOX:4711:98213", // unique per real-world event (provider id, or a hash)
56
+ "payload": { // what the agent needs to act, small
57
+ "mailbox": "INBOX", "uid": 98213, "from": "ana@example.com",
58
+ "subject": "Invoice 2026-10", "snippet": "first 300 characters…", "url": "…"
59
+ }
60
+ }
61
+ ```
62
+
63
+ - **`eventID`:**
64
+ - apex ignores a repeated `eventID` for 5 minutes. Beyond that, deduplicate in the relay with a bounded set of recent ids, for example the last 5 000, stored in a file.
65
+ - Prefix it with the source, because ids from different sources can collide.
66
+ - **`payload`:**
67
+ - Ids first: chat id, message id, mailbox + UID, repo + run id. The agent uses them to act through its tools.
68
+ - Then short text. Bulky content stays at the source: the agent fetches it.
69
+ - No secrets, tokens or full headers: everything here ends up in a prompt.
70
+ - **`type`:** keep a small fixed set per relay, so subscriptions can filter on it. Use separate types for failures that are not real events, such as `relay.error` or `relay.backlog`.
71
+
72
+ ## State that survives restarts
73
+
74
+ | What | Where | Why |
75
+ | --- | --- | --- |
76
+ | cursor (last id, `Last-Event-ID`, IMAP UID, offset) | a small file, written atomically (temp file + rename) | resume without gaps or replays |
77
+ | recently seen ids | a bounded list in a file | dedupe beyond apex's 5 minutes |
78
+ | outbox | a file or folder of events whose ingest failed | OpenCode was restarting or asleep |
79
+ | last state (watchers) | a file per target | notify only on changes |
80
+
81
+ Put them in a per-user state directory: `~/.local/state/<relay>/` on Linux, `~/Library/Application Support/<relay>/` on macOS, `%LOCALAPPDATA%\<relay>\` on Windows. Mode `0600` if they contain anything personal.
82
+
83
+ ## Using OpenCode tools inside the relay (`tools.run`)
84
+
85
+ ```
86
+ function runTool(tool, input):
87
+ reply = POST rpc.toolsRun {"input": {"tool": tool, "input": input, "timeoutMs": 60000}}
88
+ if not reply.output.ok: return error(reply.output.error) // denied, unknown, MCP down, timeout
89
+ return reply.output.content // text; parse it yourself
90
+
91
+ on message event:
92
+ details = runTool("messaging_read_messages", {"chat_id": event.chatID, "limit": 5})
93
+ if error: ingest {type: "message.received", payload: {...event, enrichError: error}} // still wake, but say so
94
+ else: ingest {type: "message.received", payload: {...event, context: lastLines(details)}}
95
+ ```
96
+
97
+ - Get the exact tool id by asking the agent for its tool list. MCP tools are `<server>_<tool>`. Try the call by hand with the `curl` from `apex_callback_endpoint.examples.toolsRun` first, and copy its `input`.
98
+ - `tools.run` executes **one** tool with the permissions of `events.tools.agent` (default `build`):
99
+ - `ask` tools stall because nobody is there to approve, so keep writes out of the relay;
100
+ - `execute` (code mode), `question`, `subagent` and `apex_*` are denied by default;
101
+ - only the MCP servers connected in that project directory are available.
102
+ - It costs a full tool execution, so call it once per event that matters, not for every raw item.
103
+ - Keep "could not check" (`ok: false`) apart from "nothing happened". Send the first as its own `type` if the user should know.
104
+
105
+ ## Several projects or agents
106
+
107
+ - Each `location[directory]` has its own subscriptions and MCP servers. A relay can send the same event to several directories: keep a list in its config and call each `rpc.ingest`. Alternatively, route by rule, for example work chats to one project and personal chats to another.
108
+ - Many relays for one user: give each its own `source` (`whatsapp-personal`, `imap-work`). Subscriptions then pick precisely.
109
+
110
+ ## Testing checklist
111
+
112
+ 1. Dry run: the normalized events look right, and the noise is dropped.
113
+ 2. Send one hand-made event: `delivered: ["sub_…"]`.
114
+ 3. Restart the relay mid-stream: no gap, no replay.
115
+ 4. Stop OpenCode for a minute: the relay retries, and the outbox drains when it comes back.
116
+ 5. Kill the network: it reconnects with backoff, without a busy loop.
@@ -0,0 +1,133 @@
1
+ # Keeping a relay or watcher running (Linux, macOS, Windows, containers)
2
+
3
+ Requirements on every OS:
4
+ - **Relays:** start at boot or login, restart on crash, keep logs.
5
+ - **Watchers:** a scheduler that runs them every N minutes.
6
+ - Run as the **same user as OpenCode**, so the program can read the password record named by `apex_callback_endpoint`.
7
+ - Configuration goes in a file or environment file with mode `0600`, never in the unit or command line. Process lists are visible to other users.
8
+ - Tell the user how to see logs, stop it and remove it.
9
+
10
+ Below, `RELAY` stands for the command that starts your program, for example `python3 ~/.local/bin/my-relay.py` or `node ~/.local/bin/my-relay.mjs`.
11
+
12
+ ## Linux — systemd user units
13
+
14
+ ```ini
15
+ # ~/.config/systemd/user/my-relay.service
16
+ [Unit]
17
+ Description=apex relay: my-relay
18
+ After=network-online.target
19
+
20
+ [Service]
21
+ ExecStart=/usr/bin/python3 %h/.local/bin/my-relay.py
22
+ # mode 0600, KEY=value lines (systemd has no end-of-line comments)
23
+ EnvironmentFile=%h/.config/my-relay/env
24
+ Restart=always
25
+ RestartSec=5
26
+
27
+ [Install]
28
+ WantedBy=default.target
29
+ ```
30
+
31
+ ```sh
32
+ systemctl --user daemon-reload && systemctl --user enable --now my-relay
33
+ journalctl --user -u my-relay -f # logs
34
+ loginctl enable-linger "$USER" # keep running without an open login session (ask the user first)
35
+ ```
36
+
37
+ Watcher: a `Type=oneshot` service plus a timer.
38
+
39
+ ```ini
40
+ # ~/.config/systemd/user/my-watch.timer (my-watch.service: Type=oneshot, ExecStart=…)
41
+ [Timer]
42
+ OnBootSec=2min
43
+ OnUnitActiveSec=5min
44
+ [Install]
45
+ WantedBy=timers.target
46
+ ```
47
+
48
+ `systemctl --user enable --now my-watch.timer`, then check with `systemctl --user list-timers`. Without systemd, use `crontab -e`: `*/5 * * * * <command> >> ~/.local/state/my-watch.log 2>&1`.
49
+
50
+ Remove it: `systemctl --user disable --now my-relay`, then delete the unit and the script.
51
+
52
+ ## macOS — launchd LaunchAgent
53
+
54
+ ```xml
55
+ <!-- ~/Library/LaunchAgents/com.user.my-relay.plist -->
56
+ <?xml version="1.0" encoding="UTF-8"?>
57
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
58
+ <plist version="1.0"><dict>
59
+ <key>Label</key><string>com.user.my-relay</string>
60
+ <key>ProgramArguments</key><array>
61
+ <string>/usr/bin/python3</string><string>/Users/USER/.local/bin/my-relay.py</string>
62
+ </array>
63
+ <key>RunAtLoad</key><true/>
64
+ <key>KeepAlive</key><true/> <!-- relay: restart when it exits -->
65
+ <!-- watcher instead: drop KeepAlive and add <key>StartInterval</key><integer>300</integer> -->
66
+ <key>StandardOutPath</key><string>/Users/USER/Library/Logs/my-relay.log</string>
67
+ <key>StandardErrorPath</key><string>/Users/USER/Library/Logs/my-relay.log</string>
68
+ </dict></plist>
69
+ ```
70
+
71
+ ```sh
72
+ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.user.my-relay.plist
73
+ launchctl kickstart -k gui/$(id -u)/com.user.my-relay # restart after changes
74
+ launchctl bootout gui/$(id -u)/com.user.my-relay # stop and unload
75
+ ```
76
+
77
+ - launchd does not expand `~` or `$HOME`: write absolute paths.
78
+ - Environment variables go in an `EnvironmentVariables` dict, or better, the program reads its own `0600` config file.
79
+ - The `PATH` is minimal, so call interpreters by their full path (`which python3`).
80
+
81
+ ## Windows — Task Scheduler (no extra software)
82
+
83
+ ```powershell
84
+ # relay: start at logon, restart on failure, never time out
85
+ $action = New-ScheduledTaskAction -Execute "python.exe" -Argument "$env:USERPROFILE\relays\my-relay.py"
86
+ $trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
87
+ $settings = New-ScheduledTaskSettingsSet -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) `
88
+ -ExecutionTimeLimit ([TimeSpan]::Zero) -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
89
+ Register-ScheduledTask -TaskName "my-relay" -Action $action -Trigger $trigger -Settings $settings
90
+ Start-ScheduledTask -TaskName "my-relay"
91
+
92
+ # watcher: every 5 minutes
93
+ $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5)
94
+ Register-ScheduledTask -TaskName "my-watch" -Action $action -Trigger $trigger -Settings $settings
95
+
96
+ Unregister-ScheduledTask -TaskName "my-relay" -Confirm:$false # remove
97
+ ```
98
+
99
+ - Task Scheduler keeps no output, so the program writes its own log under `%LOCALAPPDATA%\my-relay\`. Wrap the command in `powershell -NoProfile -WindowStyle Hidden -Command "… *>> log.txt"` if it cannot.
100
+ - Use `pythonw.exe` (or a hidden PowerShell window) to avoid a console window popping up.
101
+ - To run before anyone logs in, a Windows service via **NSSM** (`nssm install my-relay <exe> <args>`) or **WinSW**, but check which account it runs as. A service running as `LocalSystem` cannot read the user's OpenCode password file unless configured to run as that user.
102
+
103
+ ## Containers (Docker / Podman)
104
+
105
+ ```sh
106
+ # --network host: on Linux, OpenCode is on the host's 127.0.0.1
107
+ # first -v: the folder of the password record named by apex_callback_endpoint (read-only)
108
+ docker run -d --name my-relay --restart unless-stopped \
109
+ --network host \
110
+ -v ~/.local/state/opencode:/opencode-state:ro \
111
+ -v ~/.config/my-relay:/config:ro \
112
+ my-relay-image
113
+ ```
114
+
115
+ - A container on the default bridge network **cannot reach the host's `127.0.0.1`**. On Linux use `--network host`.
116
+ - On Docker Desktop (macOS/Windows), `host.docker.internal` reaches the host. The `rpc.*` URLs then use that host instead of `127.0.0.1`.
117
+ - Inside the container, the password-file path differs from the host's. Pass the mounted path to the program.
118
+ - Containers only make sense if the user already runs Docker on that machine. A user service is simpler.
119
+
120
+ ## Any OS with Node — pm2
121
+
122
+ ```sh
123
+ npm install -g pm2
124
+ pm2 start ~/.local/bin/my-relay.mjs --name my-relay # also: pm2 start my-relay.py --interpreter python3
125
+ pm2 save && pm2 startup # prints the command that enables start at boot
126
+ pm2 logs my-relay pm2 delete my-relay
127
+ ```
128
+
129
+ ## After installing
130
+
131
+ 1. Check it is running (`systemctl --user status`, `launchctl print gui/$(id -u)/<label>`, `Get-ScheduledTask`, `docker ps`, `pm2 ls`).
132
+ 2. Reboot or log out and back in, if the user agrees, and check it came back.
133
+ 3. Write down for the user: the name, the log location, the stop and remove commands, and the subscription id.