opencode-apex 0.4.0 → 0.5.0
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 +23 -0
- package/README.md +2 -3
- package/core/config.ts +1 -1
- package/core/daemon-client.ts +3 -26
- package/daemon/main.ts +21 -372
- package/daemon/shared.ts +3 -39
- package/docs/CONFIG.md +1 -1
- package/docs/ENDPOINTS.md +25 -48
- package/endpoints.ts +8 -73
- package/index.ts +4 -4
- package/opencode-apex.jsonc +1 -1
- package/package.json +3 -4
- package/skills/apex-callbacks/SKILL.md +3 -7
- package/skills/apex-endpoints/SKILL.md +46 -62
- package/core/autostart.ts +0 -67
package/docs/ENDPOINTS.md
CHANGED
|
@@ -1,87 +1,64 @@
|
|
|
1
|
-
# Endpoints: OpenTunnel routes
|
|
1
|
+
# Endpoints: OpenTunnel routes and verified webhooks
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
- receive webhooks;
|
|
5
|
-
- publish local ports on public HTTPS URLs;
|
|
6
|
-
- run microservices they write themselves.
|
|
7
|
-
|
|
8
|
-
Each of these can be temporary (with a TTL) or permanent. The agent-facing guide is the packaged skill `apex-endpoints`. This page covers how the module works and how to run it.
|
|
3
|
+
This module lets agents receive webhooks and publish local ports on public HTTPS URLs. Each one can be temporary (it has a TTL) or permanent. The agent-facing guide is the packaged skill `apex-endpoints`.
|
|
9
4
|
|
|
10
5
|
## Architecture
|
|
11
6
|
|
|
12
7
|
```
|
|
13
8
|
Internet ─HTTPS─▶ OpenTunnel ─▶ apex daemon ─┬─ webhook listener (127.0.0.1) ── verify ──▶ POST events.ingest (local, Basic auth)
|
|
14
|
-
<route>.<id>.opentunnel.xyz
|
|
15
|
-
└─ route ──▶ any local port
|
|
9
|
+
<route>.<id>.opentunnel.xyz └─ route ──▶ any local port
|
|
16
10
|
control API (127.0.0.1, token; never routed) ◀── plugin tools
|
|
17
11
|
```
|
|
18
12
|
|
|
19
13
|
- **Why a daemon?** OpenCode unloads a directory's plugins after 60 minutes without activity, and a tunnel or listener inside the plugin dies with it.
|
|
20
|
-
- The daemon is a separate process, **one per user
|
|
21
|
-
- The plugin launches it detached on the first `apex_webhook` / `apex_tunnel`
|
|
22
|
-
- A lockfile ensures there is only one.
|
|
14
|
+
- The daemon is a separate process, **one per user**, and a lockfile keeps it that way.
|
|
15
|
+
- The plugin launches it detached on the first `apex_webhook` / `apex_tunnel` call, and again on plugin load whenever its registry is not empty.
|
|
23
16
|
- It exits after 10 minutes with nothing to keep.
|
|
24
|
-
-
|
|
25
|
-
- **
|
|
26
|
-
-
|
|
27
|
-
-
|
|
17
|
+
- After a reboot, it comes back when apex loads in any project.
|
|
18
|
+
- **Runtime:** OpenCode's own executable in bun mode (`BUN_BE_BUN=1`).
|
|
19
|
+
- Nothing to install, and it runs on every platform OpenCode runs on.
|
|
20
|
+
- No systemd or launchd involved.
|
|
21
|
+
- **Tunnel:** the `@opentunnel/client` SDK, which is pure JavaScript.
|
|
22
|
+
- It uses the device's `default` profile, the same tunnel OpenCode remote access uses, and claims **its own routes**.
|
|
23
|
+
- Routes are cheap; new tunnels are limited to about 30 per hour per IP.
|
|
24
|
+
- On a device without a tunnel, the first use issues its certificate, which takes about a minute.
|
|
28
25
|
- **Webhooks:** the daemon is the intermediate program between the Internet and OpenCode's RPC.
|
|
29
26
|
- Each webhook has its own random route and secret.
|
|
30
27
|
- The listener verifies the signature or token in constant time.
|
|
31
28
|
- Only then does it call `events.ingest` on loopback. The server password never leaves the machine.
|
|
32
|
-
- **
|
|
33
|
-
|
|
34
|
-
- They restart with backoff from 1 s up to 60 s, according to `restart`.
|
|
35
|
-
- When the daemon restarts (an update, a crash), the new one **adopts** live services by pid and boot stamp instead of restarting them.
|
|
36
|
-
- Services wake agents through the daemon's local `/v1/ingest` with their own token (`APEX_INGEST_URL`, `APEX_INGEST_TOKEN`).
|
|
37
|
-
- **TTL:** the daemon removes expired entries every 15 seconds, even with OpenCode closed:
|
|
38
|
-
- a tunnel's route is removed;
|
|
39
|
-
- a webhook's route and secret file are removed;
|
|
40
|
-
- a service is stopped and its route removed.
|
|
41
|
-
- **Updates:** a plugin with a newer version asks the old daemon to exit and starts its own. Services keep running and are adopted.
|
|
29
|
+
- **TTL:** every 15 seconds the daemon removes expired routes and webhooks, along with each webhook's secret file. This happens even with OpenCode closed.
|
|
30
|
+
- **Updates:** a plugin with a newer version stops the old daemon and starts its own. The registry is kept.
|
|
42
31
|
|
|
43
32
|
## Files
|
|
44
33
|
|
|
45
|
-
`<XDG_STATE_HOME or ~/.local/state>/opencode-apex
|
|
34
|
+
They live in `<XDG_STATE_HOME or ~/.local/state>/opencode-apex/` on every OS. `APEX_DAEMON_HOME` overrides the location.
|
|
46
35
|
|
|
47
36
|
| File | What |
|
|
48
37
|
| --- | --- |
|
|
49
38
|
| `daemon.json` (0600) | pid, control port, control token, version |
|
|
50
39
|
| `daemon.lock` | single-instance lock (pid) |
|
|
51
|
-
| `registry.json` (0600) | tunnels, webhooks (with their secrets),
|
|
40
|
+
| `registry.json` (0600) | tunnels, webhooks (with their secrets), how to reach each project's server |
|
|
52
41
|
| `secrets/<hook>.secret` (0600) | each webhook's secret, for configuring the sender without pasting it |
|
|
53
42
|
| `daemon.log` | daemon log |
|
|
54
|
-
| `logs/<service>.log` | each service's stdout/stderr (rotated at 10 MB) |
|
|
55
|
-
| `launch.sh` / `launch.cmd` | launcher used by autostart, rewritten with current paths on every launch |
|
|
56
|
-
|
|
57
|
-
## Autostart after a reboot
|
|
58
|
-
|
|
59
|
-
Without autostart, the daemon comes back as soon as apex loads in any project. `apex_daemon({action:"autostart", enabled:true})` makes it start at boot:
|
|
60
|
-
|
|
61
|
-
- **Linux / macOS / BSD:** a `@reboot` line in the user's crontab, tagged `# opencode-apex-daemon`. It works with any init system (systemd, sysvinit, OpenRC, runit, antiX…) and needs `cron` installed.
|
|
62
|
-
- **Windows:** a scheduled task `opencode-apex-daemon` that runs at logon (`schtasks /SC ONLOGON`).
|
|
63
|
-
|
|
64
|
-
`enabled:false` removes only that line or task.
|
|
65
43
|
|
|
66
44
|
## Security
|
|
67
45
|
|
|
68
|
-
- The control API listens on 127.0.0.1 and
|
|
46
|
+
- The control API listens on 127.0.0.1 and needs a token from a 0600 file. The tunnel never routes it.
|
|
69
47
|
- Behind OpenTunnel, every request arrives from 127.0.0.1 with a `Host` the visitor chose. The webhook listener uses `Host` only to **select** a webhook; the signature decides.
|
|
70
|
-
-
|
|
71
|
-
-
|
|
72
|
-
- Services inherit the daemon's environment **minus** `OPENCODE_SERVER_PASSWORD` / `OPENCODE_PASSWORD`.
|
|
48
|
+
- Whatever you publish with `apex_tunnel` must authenticate its own requests: a random route is not authentication.
|
|
49
|
+
- Webhook secrets are never returned by the tools, only `secretFile`.
|
|
73
50
|
- Publishing the OpenCode server's own port is refused. Use OpenCode remote access (`opencode service set remote true`), which has its own password.
|
|
74
51
|
|
|
75
52
|
## Network
|
|
76
53
|
|
|
77
54
|
The daemon inherits OpenCode's environment:
|
|
78
|
-
|
|
79
|
-
- `
|
|
55
|
+
|
|
56
|
+
- `HTTPS_PROXY` / `NO_PROXY` and `OPENTUNNEL_CA_CERT` apply. OpenTunnel does not support a SOCKS proxy.
|
|
57
|
+
- `OPENTUNNEL_API` points the daemon at a self-hosted OpenTunnel server.
|
|
80
58
|
|
|
81
59
|
After changing any of these, run `apex_daemon({action:"stop"})`; the next tool call starts the daemon with the new values.
|
|
82
60
|
|
|
83
61
|
## Turning it off
|
|
84
62
|
|
|
85
|
-
`"modules": { "endpoints": false }` removes the
|
|
86
|
-
|
|
87
|
-
2. `apex_daemon({action:"stop"})`.
|
|
63
|
+
- `"modules": { "endpoints": false }` removes the tools, and the plugin no longer launches the daemon.
|
|
64
|
+
- `apex_daemon({action:"stop"})` stops a running daemon.
|
package/endpoints.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Apex Endpoints — el agente publica endpoints
|
|
3
|
-
*
|
|
2
|
+
* Apex Endpoints — el agente publica endpoints que reaccionan a llamadas externas, a
|
|
3
|
+
* través del daemon de apex (daemon/main.ts):
|
|
4
4
|
*
|
|
5
5
|
* - apex_tunnel: un puerto local en una ruta del túnel OpenTunnel (open/list/close, TTL)
|
|
6
6
|
* - apex_webhook: un webhook con firma verificada que despierta al agente (create/list/delete)
|
|
7
|
-
* -
|
|
8
|
-
* - apex_daemon: estado del daemon, autoarranque y parada
|
|
7
|
+
* - apex_daemon: estado y parada del daemon
|
|
9
8
|
*
|
|
10
9
|
* El trabajo lo hace el daemon (un proceso por usuario, fuera del plugin, que OpenCode
|
|
11
10
|
* descarga tras 60 min). Aquí solo se habla con él y se le dice cómo llegar al servidor
|
|
@@ -17,7 +16,6 @@ import type { Scope } from "effect"
|
|
|
17
16
|
import type { Plugin } from "@opencode/plugin/effect"
|
|
18
17
|
import { daemonPaths } from "./daemon/shared.js"
|
|
19
18
|
import { ensureDaemon, hasRegistryEntries, serverTarget, type DaemonClient } from "./core/daemon-client.js"
|
|
20
|
-
import { autostartStatus, setAutostart } from "./core/autostart.js"
|
|
21
19
|
import type { ServerEndpoint } from "./core/server-endpoint.js"
|
|
22
20
|
|
|
23
21
|
interface EndpointsInput {
|
|
@@ -200,86 +198,23 @@ export function register(ctx: Plugin.Context, input: EndpointsInput): Effect.Eff
|
|
|
200
198
|
},
|
|
201
199
|
})
|
|
202
200
|
|
|
203
|
-
yield* tool({
|
|
204
|
-
name: "apex_service",
|
|
205
|
-
description:
|
|
206
|
-
"Run a microservice you wrote as a supervised background process that outlives this session (restart " +
|
|
207
|
-
"with backoff, logs, optional TTL) and optionally publish its port through OpenTunnel. It gets PORT, " +
|
|
208
|
-
"APEX_PUBLIC_URL, and APEX_INGEST_URL + APEX_INGEST_TOKEN (POST {source,type,payload} to wake agents of " +
|
|
209
|
-
"this project). up; list; down {id}; restart {id}; logs {id, lines}.",
|
|
210
|
-
properties: {
|
|
211
|
-
action: { type: "string", enum: ["up", "list", "down", "restart", "logs"] },
|
|
212
|
-
name: { type: "string", description: "up: unique name" },
|
|
213
|
-
command: { type: "string", description: "up: shell command line, e.g. 'node server.js' (bind 127.0.0.1:$PORT)" },
|
|
214
|
-
cwd: { type: "string", description: "up: working directory (default the project)" },
|
|
215
|
-
env: { type: "object", additionalProperties: { type: "string" }, description: "up: extra environment" },
|
|
216
|
-
port: { type: "number", description: "up: port the service listens on (exported as PORT)" },
|
|
217
|
-
public: { type: "boolean", description: "up: publish the port through OpenTunnel" },
|
|
218
|
-
route: { type: "string", description: "up, public: readable route name (default random)" },
|
|
219
|
-
restart: { type: "string", enum: ["always", "on-failure", "never"], description: "up: default always" },
|
|
220
|
-
ttlMinutes: ttl,
|
|
221
|
-
id: { type: "string", description: "down/restart/logs: service id or name" },
|
|
222
|
-
lines: { type: "number", description: "logs: last N lines (default 100)" },
|
|
223
|
-
},
|
|
224
|
-
required: ["action"],
|
|
225
|
-
run: async (args, toolCtx) => {
|
|
226
|
-
const client = await daemon()
|
|
227
|
-
const id = encodeURIComponent(String(args.id ?? ""))
|
|
228
|
-
switch (args.action) {
|
|
229
|
-
case "list":
|
|
230
|
-
return { services: (await client.request<{ services: unknown[] }>("GET", "/v1/state")).services }
|
|
231
|
-
case "down":
|
|
232
|
-
return client.request("DELETE", `/v1/services/${id}`)
|
|
233
|
-
case "restart":
|
|
234
|
-
return client.request("POST", `/v1/services/${id}/restart`, {})
|
|
235
|
-
case "logs":
|
|
236
|
-
return client.request("GET", `/v1/services/${id}/logs?lines=${Number(args.lines ?? 100) || 100}`)
|
|
237
|
-
default: {
|
|
238
|
-
const up = await client.request<{ url?: string | null; tunnel?: { state?: string } }>("POST", "/v1/services", {
|
|
239
|
-
...owner(args, toolCtx),
|
|
240
|
-
name: args.name,
|
|
241
|
-
command: args.command,
|
|
242
|
-
cwd: str(args.cwd),
|
|
243
|
-
env: args.env,
|
|
244
|
-
port: args.port,
|
|
245
|
-
public: args.public === true,
|
|
246
|
-
route: str(args.route),
|
|
247
|
-
restart: args.restart,
|
|
248
|
-
})
|
|
249
|
-
return args.public === true ? withHint(up) : up
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
},
|
|
253
|
-
})
|
|
254
|
-
|
|
255
201
|
yield* tool({
|
|
256
202
|
name: "apex_daemon",
|
|
257
203
|
description:
|
|
258
|
-
"The apex daemon that keeps tunnels
|
|
259
|
-
"
|
|
204
|
+
"The apex daemon that keeps tunnels and webhooks alive: status (tunnel state, everything it keeps, log " +
|
|
205
|
+
"file) or stop (the next apex tool call or plugin load starts it again).",
|
|
260
206
|
properties: {
|
|
261
|
-
action: { type: "string", enum: ["status", "
|
|
262
|
-
enabled: { type: "boolean", description: "autostart: on or off" },
|
|
207
|
+
action: { type: "string", enum: ["status", "stop"] },
|
|
263
208
|
},
|
|
264
209
|
required: ["action"],
|
|
265
210
|
run: async (args) => {
|
|
266
|
-
if (args.action === "autostart") {
|
|
267
|
-
if (args.enabled === true) await daemon() // escribe el lanzador con las rutas actuales
|
|
268
|
-
return { autostart: setAutostart(args.enabled === true, paths) }
|
|
269
|
-
}
|
|
270
211
|
const client = await daemon(args.action !== "stop")
|
|
271
212
|
if (args.action === "stop") {
|
|
272
213
|
await client.request("POST", "/v1/shutdown", {}).catch(() => undefined)
|
|
273
|
-
return { stopped: true
|
|
214
|
+
return { stopped: true }
|
|
274
215
|
}
|
|
275
216
|
const state = await client.request("GET", "/v1/state")
|
|
276
|
-
|
|
277
|
-
try {
|
|
278
|
-
autostart = autostartStatus(paths)
|
|
279
|
-
} catch (error) {
|
|
280
|
-
autostart = { error: String((error as Error).message ?? error) }
|
|
281
|
-
}
|
|
282
|
-
return { ...state, autostart, log: paths.log, home: paths.home }
|
|
217
|
+
return { ...state, log: paths.log, home: paths.home }
|
|
283
218
|
},
|
|
284
219
|
})
|
|
285
220
|
})
|
package/index.ts
CHANGED
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
* - browser: (deprecated, off by default; OpenCode's browse replaces it) browser.* tools
|
|
10
10
|
* against a headless or remote Chromium over CDP (attach on request)
|
|
11
11
|
* - tempAccess: external_directory without prompts in OpenCode's temp directory
|
|
12
|
-
* - endpoints: OpenTunnel routes
|
|
13
|
-
*
|
|
12
|
+
* - endpoints: OpenTunnel routes and verified webhooks, kept by a per-user apex daemon
|
|
13
|
+
* that outlives the plugin (daemon/main.ts)
|
|
14
14
|
*
|
|
15
15
|
* Built on the official Effect plugin API: https://opencode.ai/v2/docs/build/plugins/effect/
|
|
16
16
|
*/
|
|
@@ -32,7 +32,7 @@ import { registerTempAccess } from "./core/temp-access.js"
|
|
|
32
32
|
import { register as registerEndpoints } from "./endpoints.js"
|
|
33
33
|
|
|
34
34
|
// Plugin version
|
|
35
|
-
const VERSION = "0.
|
|
35
|
+
const VERSION = "0.5.0"
|
|
36
36
|
|
|
37
37
|
interface ModuleConfigs {
|
|
38
38
|
redact: RedactConfig & { enabled: boolean }
|
|
@@ -156,7 +156,7 @@ export default Plugin.define({
|
|
|
156
156
|
yield* registerAdvisor(ctx, moduleConfigs.advisor)
|
|
157
157
|
}
|
|
158
158
|
|
|
159
|
-
// Túneles
|
|
159
|
+
// Túneles y webhooks verificados, vía el daemon de apex.
|
|
160
160
|
if (validatedConfig.modules?.endpoints ?? true) {
|
|
161
161
|
yield* registerEndpoints(ctx, { version: VERSION, endpoint: events?.endpoint ?? null })
|
|
162
162
|
}
|
package/opencode-apex.jsonc
CHANGED
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"browser": false,
|
|
42
42
|
// external_directory without asking in <tmpdir>/opencode (OpenCode's temp dir)
|
|
43
43
|
"tempAccess": true,
|
|
44
|
-
// Túneles OpenTunnel
|
|
44
|
+
// Túneles OpenTunnel y webhooks verificados (daemon de apex, solo al usarlos)
|
|
45
45
|
"endpoints": true
|
|
46
46
|
},
|
|
47
47
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-apex",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Modular plugin for OpenCode V2 (>= 2.1): secret redaction, RPC callbacks/webhooks/watchers that wake agents, OpenTunnel endpoints + verified webhooks
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "Modular plugin for OpenCode V2 (>= 2.1): secret redaction, RPC callbacks/webhooks/watchers that wake agents, OpenTunnel endpoints + verified webhooks (cross-platform daemon), tools.run, AI permission advisor, guard meta-permissions, temp-directory access",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Antonio Orizondo Leyva",
|
|
7
7
|
"repository": {
|
|
@@ -27,8 +27,7 @@
|
|
|
27
27
|
"cdp",
|
|
28
28
|
"browser",
|
|
29
29
|
"opentunnel",
|
|
30
|
-
"tunnel"
|
|
31
|
-
"microservices"
|
|
30
|
+
"tunnel"
|
|
32
31
|
],
|
|
33
32
|
"engines": {
|
|
34
33
|
"opencode": ">=2.1.0"
|
|
@@ -101,7 +101,7 @@ Patterns, the source catalog (WebSocket, SSE, IMAP, polling, queues…), state a
|
|
|
101
101
|
- A relay that **connects out** to the source can run on a laptop behind NAT next to OpenCode. Examples: WebSocket, SSE, long-poll, IMAP IDLE, polling an API, consuming a queue. This is the default: prefer it whenever the service offers it.
|
|
102
102
|
- A **webhook** means the service connects **in**. A relay on `127.0.0.1` or a home PC behind NAT **cannot be reached from the Internet** unless you add one of these:
|
|
103
103
|
1. the service's outbound mode (Slack Socket Mode, Discord Gateway, Telegram `getUpdates`, Gmail via Pub/Sub pull);
|
|
104
|
-
2. **`apex_webhook`**, the shortest path: a public OpenTunnel URL that checks the GitHub, Stripe or Slack signature, a generic HMAC or a token, then calls `events.ingest` locally. You write no relay code. Use **`apex_tunnel`** to publish a relay of your own
|
|
104
|
+
2. **`apex_webhook`**, the shortest path: a public OpenTunnel URL that checks the GitHub, Stripe or Slack signature, a generic HMAC or a token, then calls `events.ingest` locally. You write no relay code. Use **`apex_tunnel`** to publish a relay of your own (skill **`apex-endpoints`**). Without apex: `opentunnel route add <relay port>`, Cloudflare Tunnel, Tailscale Funnel or ngrok;
|
|
105
105
|
3. a reverse SSH connection to a VPS;
|
|
106
106
|
4. a small public receiver that stores events while the local relay pulls them (store-and-forward, which survives the PC being off).
|
|
107
107
|
- OpenCode listens on loopback. Run the relay **on the same machine** and expose **the relay**, with its own token, never the OpenCode server: the URL and password of the server give full control of OpenCode. Third-party webhooks (GitHub, Stripe…) always go to a relay.
|
|
@@ -140,11 +140,7 @@ A relay must:
|
|
|
140
140
|
- keep logs;
|
|
141
141
|
- read secrets from `0600` files, never from the unit or command line.
|
|
142
142
|
|
|
143
|
-
Run it as the **same user** as OpenCode, so it can read the password record.
|
|
144
|
-
|
|
145
|
-
**First choice, on any OS: `apex_service`**. The apex daemon supervises it: restarts with backoff, keeps a log, applies an optional TTL and can give it a public URL. It survives the plugin unload and works with any init system (systemd, sysvinit…) and on Windows. The service gets `APEX_INGEST_URL` + `APEX_INGEST_TOKEN`, so it wakes agents **without the server password**. To survive a reboot, turn on `apex_daemon({action:"autostart", enabled:true})` once (see skill `apex-endpoints`).
|
|
146
|
-
|
|
147
|
-
A watcher needs a scheduler instead of a supervisor. For a watcher, or when you need OS units (systemd, launchd, Task Scheduler, NSSM/WinSW, Docker, pm2), read **`references/run-anywhere.md`**.
|
|
143
|
+
Run it as the **same user** as OpenCode, so it can read the password record. A watcher needs a scheduler instead of a supervisor. Ready-made units for systemd (Linux), launchd (macOS), Task Scheduler and NSSM/WinSW (Windows), Docker and pm2 are in **`references/run-anywhere.md`**. If the only job is turning a third-party webhook into an event, `apex_webhook` needs no program at all.
|
|
148
144
|
|
|
149
145
|
## Before you call it done
|
|
150
146
|
|
|
@@ -182,4 +178,4 @@ All of them: `POST <baseUrl>/api/rpc/apex/<method>?location[directory]=<project>
|
|
|
182
178
|
| `references/reachability.md` | Webhooks or senders on other machines: outbound modes, OpenTunnel and OpenCode remote access, Cloudflare/Tailscale/ngrok tunnels, reverse SSH, store-and-forward, signature checks |
|
|
183
179
|
| `references/run-anywhere.md` | Keeping a relay or watcher alive on Linux, macOS, Windows, Docker, pm2, and removing it |
|
|
184
180
|
| `references/examples.md` | Copyable code: sh watcher, Python SSE relay, Node webhook relay, PowerShell ingest, n8n recipe, `tools.run` calls |
|
|
185
|
-
| skill `apex-endpoints` | `apex_webhook` / `apex_tunnel` / `
|
|
181
|
+
| skill `apex-endpoints` | `apex_webhook` / `apex_tunnel` / `apex_daemon`: verified webhooks without a relay, public URLs for your own service |
|
|
@@ -1,37 +1,41 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: apex-endpoints
|
|
3
|
-
description: Expose things to the Internet
|
|
3
|
+
description: Expose things to the Internet with opencode-apex, on any OS, without a tunnel CLI. Use it when the agent must receive a webhook (GitHub, Stripe, Slack, n8n, any HMAC or token sender) that wakes an agent, or publish a local port (a service, API or demo you started) on a public HTTPS URL, temporary or permanent. Tools apex_webhook, apex_tunnel and apex_daemon, through OpenTunnel (the makers of OpenCode) and the apex daemon.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
# Public endpoints
|
|
6
|
+
# Public endpoints (apex daemon + OpenTunnel)
|
|
7
7
|
|
|
8
8
|
## The model
|
|
9
9
|
|
|
10
10
|
```
|
|
11
11
|
Internet ──HTTPS──▶ OpenTunnel ──▶ apex daemon (one per user, outside OpenCode)
|
|
12
|
-
<route>.<id>.opentunnel.xyz ├─ webhook
|
|
13
|
-
|
|
14
|
-
└─ route → any local port
|
|
12
|
+
<route>.<id>.opentunnel.xyz ├─ webhook: verify signature → events.ingest (local) → subscription → agent
|
|
13
|
+
└─ route → any local port (your service)
|
|
15
14
|
```
|
|
16
15
|
|
|
17
|
-
- **The apex daemon** keeps
|
|
18
|
-
-
|
|
19
|
-
-
|
|
16
|
+
- **The apex daemon** keeps routes and webhooks alive. It is one process per user, launched by the plugin with OpenCode's own binary.
|
|
17
|
+
- It survives the 60-minute plugin unload and OpenCode restarts.
|
|
18
|
+
- It works with any init system and on Windows.
|
|
19
|
+
- It starts on the first tool call. With nothing left to keep, it exits after 10 minutes.
|
|
20
|
+
- After a reboot, it comes back when apex loads in any project.
|
|
21
|
+
- **OpenTunnel:** the daemon adds its **own routes** to this device's tunnel, the same one OpenCode remote access uses. TLS ends on this machine. New routes are cheap; new tunnels are limited to about 30 per hour per IP.
|
|
22
|
+
- **Every entry** belongs to this project. It is either **temporary** (`ttlMinutes`) or **permanent** (no TTL). The daemon removes temporary ones on time, even with OpenCode closed.
|
|
20
23
|
|
|
21
24
|
## Pick the tool
|
|
22
25
|
|
|
23
26
|
| You need | Use |
|
|
24
27
|
| --- | --- |
|
|
25
28
|
| A service (GitHub, Stripe, Slack, n8n, a form…) must call in and wake an agent | **`apex_webhook`**: no code at all |
|
|
26
|
-
|
|
|
27
|
-
| A port you already started (dev server, demo, test) on a public URL | **`apex_tunnel`** |
|
|
29
|
+
| A port you started (your API, microservice, dev server, demo) on a public URL | **`apex_tunnel`** |
|
|
28
30
|
| A sender **you control** on another machine must call OpenCode's RPC itself | Not this skill: OpenCode remote access (skill `apex-callbacks`, Step 3) |
|
|
29
31
|
|
|
30
32
|
Prefer a source's **outbound** mode (WebSocket, polling…) when it has one. Nothing is exposed then (skill `apex-callbacks`).
|
|
31
33
|
|
|
32
34
|
## Webhooks: `apex_webhook`
|
|
33
35
|
|
|
34
|
-
1. **Subscribe first
|
|
36
|
+
1. **Subscribe first** with `apex_subscribe`, so the first event lands somewhere:
|
|
37
|
+
- filter on `source` (and `type`);
|
|
38
|
+
- in the template, say the payload is third-party data.
|
|
35
39
|
2. **Create:**
|
|
36
40
|
```jsonc
|
|
37
41
|
apex_webhook({ "action": "create", "name": "gh-acme-api", "provider": "github", "ttlMinutes": 0 })
|
|
@@ -41,9 +45,12 @@ Prefer a source's **outbound** mode (WebSocket, polling…) when it has one. Not
|
|
|
41
45
|
- `github`: `X-Hub-Signature-256`.
|
|
42
46
|
- `stripe`: `Stripe-Signature`, with a 5-minute replay window. Pass its `whsec_…` as `secret`.
|
|
43
47
|
- `slack`: signing secret, with a 5-minute replay window. Pass it as `secret`. The `url_verification` challenge is answered for you.
|
|
44
|
-
- `hmac`: HMAC-SHA256 of the raw body, hex or base64, in `header` (default `X-Signature`)
|
|
45
|
-
- `token`: `Authorization: Bearer`, `X-Apex-Token` or `?token=`.
|
|
46
|
-
- Without `secret`, a random one is generated. **It is never returned**: only `secretFile` (`0600`).
|
|
48
|
+
- `hmac`: HMAC-SHA256 of the raw body, hex or base64, in `header` (default `X-Signature`). A `sha256=` prefix is accepted.
|
|
49
|
+
- `token`: `Authorization: Bearer`, `X-Apex-Token` or `?token=`. For senders that cannot sign (n8n, curl, IFTTT).
|
|
50
|
+
- Without `secret`, a random one is generated. **It is never returned**: you get only `secretFile` (`0600`).
|
|
51
|
+
- Configure the sender by reading the file at run time, for example:
|
|
52
|
+
`gh api repos/OWNER/REPO/hooks -f config[url]=<url> -f config[secret]="$(cat '<secretFile>')" -f config[content_type]=json -f 'events[]=pull_request'`.
|
|
53
|
+
Never paste the secret in the chat.
|
|
47
54
|
3. **What the agent receives:**
|
|
48
55
|
- `source`: the provider, or your `source`.
|
|
49
56
|
- `type`, by provider:
|
|
@@ -52,37 +59,12 @@ Prefer a source's **outbound** mode (WebSocket, polling…) when it has one. Not
|
|
|
52
59
|
- Slack: the event type.
|
|
53
60
|
- hmac and token: `X-Event-Type`, else `payload.type`.
|
|
54
61
|
- `eventID`: `<name>:<delivery id>`. A redelivery is not delivered twice.
|
|
55
|
-
- `payload`: the parsed body
|
|
56
|
-
4. **
|
|
62
|
+
- `payload`: the parsed body plus `_webhook: {name, provider, headers}`. Signatures and tokens are left out of `headers`.
|
|
63
|
+
4. **What the sender gets back:**
|
|
57
64
|
- `202`: verified and delivered.
|
|
58
65
|
- `401`: bad or missing signature. Nothing is delivered.
|
|
59
|
-
- `503`: OpenCode is down. Stripe and Slack retry; GitHub shows
|
|
60
|
-
5. **Check:** `apex_webhook({action:"list"})` shows `stats
|
|
61
|
-
|
|
62
|
-
## Microservices: `apex_service`
|
|
63
|
-
|
|
64
|
-
Write the service in any language. Contract:
|
|
65
|
-
- **Listen on `127.0.0.1:$PORT`.** The tunnel reaches loopback, and binding to `0.0.0.0` exposes it to the LAN too.
|
|
66
|
-
- **Authenticate every request.** Behind the tunnel, every request comes from `127.0.0.1` with a `Host` the visitor chose, so "is it local?" checks are worthless. A random route is not authentication.
|
|
67
|
-
- **To wake agents:** `POST $APEX_INGEST_URL` with `Authorization: Bearer $APEX_INGEST_TOKEN` and `{"source"?, "type", "eventID"?, "payload"}`. It reaches this project's `events.ingest` without the OpenCode password. The default `source` is `service:<name>`.
|
|
68
|
-
- **Other variables:** `APEX_PUBLIC_URL` (when public) and `APEX_SERVICE_NAME`, plus your `env`. Keep secrets in `0600` files read at start, not in `env`: the registry is private, but `env` is shown by `list` (keys only).
|
|
69
|
-
- **Logs:** print them to stdout/stderr; they go to `<state>/opencode-apex/logs/<name>.log`.
|
|
70
|
-
|
|
71
|
-
```jsonc
|
|
72
|
-
apex_service({ "action": "up", "name": "invoice-api", "command": "node server.mjs", "port": 8787,
|
|
73
|
-
"public": true, "restart": "always", "ttlMinutes": 120 })
|
|
74
|
-
// → { id, status: "running", pid, url, logFile }
|
|
75
|
-
apex_service({ "action": "logs", "id": "invoice-api", "lines": 50 })
|
|
76
|
-
apex_service({ "action": "restart", "id": "invoice-api" }) // after editing the code
|
|
77
|
-
apex_service({ "action": "down", "id": "invoice-api" }) // stops it and removes its route
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
- `restart`:
|
|
81
|
-
- `always` (default): restarts with backoff from 1 s up to 60 s. The counter resets after a minute up.
|
|
82
|
-
- `on-failure`: restarts only on a non-zero exit.
|
|
83
|
-
- `never`: one run (for a batch job).
|
|
84
|
-
- `command` is a shell line: `sh -c` on Unix, `cmd /c` on Windows. `cwd` defaults to the project.
|
|
85
|
-
- Services keep running while the daemon restarts or updates: the new daemon adopts them.
|
|
66
|
+
- `503`: OpenCode is down. Stripe and Slack retry; GitHub shows it under "Recent deliveries".
|
|
67
|
+
5. **Check:** `apex_webhook({action:"list"})` shows `stats`: `ok` / `rejected` / `failed`, and `lastError`. Send one real test delivery and watch the agent wake up.
|
|
86
68
|
|
|
87
69
|
## Ports: `apex_tunnel`
|
|
88
70
|
|
|
@@ -93,38 +75,40 @@ apex_tunnel({ "action": "list" }) · apex_tunnel({ "action": "close", "id": "<
|
|
|
93
75
|
```
|
|
94
76
|
|
|
95
77
|
- Routes are random by default: 16 hex characters that never appear in certificate logs. Use `name` only when a readable URL matters.
|
|
96
|
-
- `proxyProtocol: "v2"` sends the visitor's IP to the app.
|
|
78
|
+
- `proxyProtocol: "v2"` sends the visitor's IP to the app. Only use it if the app expects a PROXY header.
|
|
97
79
|
- The OpenCode server port is refused: that is what remote access is for.
|
|
98
80
|
|
|
81
|
+
**Your own microservice behind a route:**
|
|
82
|
+
- **Listen on `127.0.0.1`.** The tunnel reaches loopback, and binding to `0.0.0.0` also exposes it to the LAN.
|
|
83
|
+
- **Authenticate every request.** Behind the tunnel, every request comes from `127.0.0.1` with a `Host` the visitor chose, so "is it local?" checks are worthless. A random route is not authentication either.
|
|
84
|
+
- **To wake agents,** call `events.ingest` (`apex_callback_endpoint`, read the password from its file on every call). If it only needs to turn a third-party call into an event, use `apex_webhook` instead and write no service at all.
|
|
85
|
+
- **The tunnel route does not keep the process alive.** Run it so it survives the session (skill `apex-callbacks`, `references/run-anywhere.md`). Keep the route's lifetime matched to the process: a TTL for temporary ones, closing the route when you stop the service.
|
|
86
|
+
|
|
99
87
|
## Temporary or permanent
|
|
100
88
|
|
|
101
|
-
- **Temporary:** always set `ttlMinutes` for tests, demos, one-off callbacks (an OAuth redirect, a payment test) and anything "for now". The daemon removes the entry on time
|
|
102
|
-
- **Permanent:** omit `ttlMinutes` only when the user wants it to stay.
|
|
103
|
-
-
|
|
104
|
-
- The URL stays the same while the device tunnel exists, so the entry keeps its URL across restarts.
|
|
89
|
+
- **Temporary:** always set `ttlMinutes` for tests, demos, one-off callbacks (an OAuth redirect, a payment test) and anything "for now". The daemon removes the entry on time; a webhook also loses its URL and secret file.
|
|
90
|
+
- **Permanent:** omit `ttlMinutes` only when the user wants it to stay. Tell them how to remove it (`delete`, `close`).
|
|
91
|
+
- The URL stays the same while the device tunnel exists.
|
|
105
92
|
|
|
106
93
|
## When it is not reachable
|
|
107
94
|
|
|
108
|
-
`apex_daemon({action:"status"})` returns:
|
|
109
|
-
- `
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
- `error`: read `lastError`.
|
|
114
|
-
- the entries the daemon keeps, the `log` file, and `autostart`.
|
|
95
|
+
`apex_daemon({action:"status"})` returns `tunnel.state` and the `log` file:
|
|
96
|
+
- `connected`: everything is fine.
|
|
97
|
+
- `provisioning`: the device's first tunnel. The certificate takes about 1 minute; then `url` appears in `list`.
|
|
98
|
+
- `reconnecting`: the network dropped. It retries on its own.
|
|
99
|
+
- `error`: read `lastError`.
|
|
115
100
|
|
|
116
|
-
|
|
117
|
-
- the daemon honours `HTTPS_PROXY` / `NO_PROXY` and `OPENTUNNEL_CA_CERT
|
|
118
|
-
-
|
|
119
|
-
-
|
|
101
|
+
Proxy and network settings:
|
|
102
|
+
- A corporate proxy or custom CA: the daemon honours `HTTPS_PROXY` / `NO_PROXY` and `OPENTUNNEL_CA_CERT`. SOCKS is not supported.
|
|
103
|
+
- A self-hosted OpenTunnel server: set `OPENTUNNEL_API` in OpenCode's environment.
|
|
104
|
+
- After changing any of these, run `apex_daemon({action:"stop"})` so it restarts with them.
|
|
120
105
|
|
|
121
106
|
## Before you call it done
|
|
122
107
|
|
|
123
|
-
1.
|
|
124
|
-
2.
|
|
108
|
+
1. Send one real request through the public `url`: an actual delivery for a webhook, `curl -i <url>` with credentials for a service.
|
|
109
|
+
2. Send a **bad** request and check it is refused: a wrong signature or token gets `401`.
|
|
125
110
|
3. Tell the user:
|
|
126
111
|
- the URL and what it reaches;
|
|
127
112
|
- temporary (until when) or permanent;
|
|
128
|
-
- where the logs are;
|
|
129
113
|
- how to remove it;
|
|
130
114
|
- the subscription id, if any.
|
package/core/autostart.ts
DELETED
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Autoarranque del daemon tras reiniciar el equipo, sin systemd ni launchd:
|
|
3
|
-
* - Linux / macOS / BSD: una línea `@reboot` en el crontab del usuario (vale con
|
|
4
|
-
* cualquier init: systemd, sysvinit, runit, OpenRC…).
|
|
5
|
-
* - Windows: una tarea programada al iniciar sesión (`schtasks /SC ONLOGON`).
|
|
6
|
-
*
|
|
7
|
-
* Lo que se arranca es el lanzador (`launch.sh` / `launch.cmd`) que el plugin reescribe
|
|
8
|
-
* con las rutas actuales cada vez que lanza el daemon, así una actualización de OpenCode
|
|
9
|
-
* o de apex no deja el autoarranque apuntando a un binario que ya no existe.
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import { spawnSync } from "node:child_process"
|
|
13
|
-
import { daemonPaths, type DaemonPaths } from "../daemon/shared.js"
|
|
14
|
-
|
|
15
|
-
export const CRON_MARKER = "# opencode-apex-daemon"
|
|
16
|
-
export const TASK_NAME = "opencode-apex-daemon"
|
|
17
|
-
|
|
18
|
-
export interface AutostartStatus {
|
|
19
|
-
readonly enabled: boolean
|
|
20
|
-
readonly method: "crontab" | "schtasks"
|
|
21
|
-
readonly detail?: string
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/** El crontab con (o sin) la línea de apex, sin tocar el resto. */
|
|
25
|
-
export function editCrontab(current: string, launcher: string, enable: boolean): string {
|
|
26
|
-
const kept = current.split("\n").filter((line) => !line.includes(CRON_MARKER))
|
|
27
|
-
while (kept.length > 0 && kept[kept.length - 1] === "") kept.pop()
|
|
28
|
-
if (enable) kept.push(`@reboot /bin/sh '${launcher.replaceAll("'", `'\\''`)}' ${CRON_MARKER}`)
|
|
29
|
-
return kept.length > 0 ? `${kept.join("\n")}\n` : ""
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function run(command: string, args: string[], input?: string) {
|
|
33
|
-
const result = spawnSync(command, args, { encoding: "utf8", input, windowsHide: true })
|
|
34
|
-
return { ok: result.status === 0, out: result.stdout ?? "", err: (result.stderr ?? "") || (result.error?.message ?? "") }
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function autostartStatus(paths: DaemonPaths = daemonPaths()): AutostartStatus {
|
|
38
|
-
if (process.platform === "win32") {
|
|
39
|
-
const query = run("schtasks", ["/Query", "/TN", TASK_NAME])
|
|
40
|
-
return { enabled: query.ok, method: "schtasks" }
|
|
41
|
-
}
|
|
42
|
-
const list = run("crontab", ["-l"])
|
|
43
|
-
return {
|
|
44
|
-
enabled: list.ok && list.out.split("\n").some((line) => line.includes(CRON_MARKER) && line.includes(paths.launcher)),
|
|
45
|
-
method: "crontab",
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export function setAutostart(enable: boolean, paths: DaemonPaths = daemonPaths()): AutostartStatus {
|
|
50
|
-
if (process.platform === "win32") {
|
|
51
|
-
const result = enable
|
|
52
|
-
? run("schtasks", ["/Create", "/TN", TASK_NAME, "/TR", `"${paths.launcher}"`, "/SC", "ONLOGON", "/RL", "LIMITED", "/F"])
|
|
53
|
-
: run("schtasks", ["/Delete", "/TN", TASK_NAME, "/F"])
|
|
54
|
-
if (!result.ok && enable) throw new Error(`schtasks failed: ${result.err.trim()}`)
|
|
55
|
-
return autostartStatus(paths)
|
|
56
|
-
}
|
|
57
|
-
const list = run("crontab", ["-l"])
|
|
58
|
-
// Sin crontab previo, `crontab -l` falla con "no crontab for <user>": se parte de vacío.
|
|
59
|
-
if (!list.ok && !/no crontab/i.test(list.err)) {
|
|
60
|
-
if (/ENOENT|not found/i.test(list.err)) throw new Error("crontab is not installed (install cron, e.g. apt install cron)")
|
|
61
|
-
throw new Error(`crontab -l failed: ${list.err.trim()}`)
|
|
62
|
-
}
|
|
63
|
-
const next = editCrontab(list.ok ? list.out : "", paths.launcher, enable)
|
|
64
|
-
const write = next.length > 0 ? run("crontab", ["-"], next) : run("crontab", ["-r"])
|
|
65
|
-
if (!write.ok && next.length > 0) throw new Error(`crontab write failed: ${write.err.trim()}`)
|
|
66
|
-
return { ...autostartStatus(paths), detail: "runs at boot via cron @reboot (any init system)" }
|
|
67
|
-
}
|