opencode-apex 0.3.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 CHANGED
@@ -5,6 +5,66 @@ All notable changes to `opencode-apex`. Format based on
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.5.0] — 2026-11-25
9
+
10
+ ### Removed
11
+
12
+ - **`apex_service` (supervised microservices) and daemon autostart.** They made the apex
13
+ daemon much larger without being needed to receive webhooks or publish a port. What was
14
+ removed:
15
+ - the supervisor: restarts with backoff, adopting processes from a previous daemon, logs,
16
+ and the per-service ingest token;
17
+ - autostart: the crontab or Windows logon task, and its launcher script.
18
+
19
+ The daemon now does two things: OpenTunnel routes and verified webhooks. To expose its own
20
+ microservice, the agent runs it (skill `apex-callbacks`, `run-anywhere.md`) and publishes
21
+ its port with `apex_tunnel`. After a reboot, the daemon comes back when apex loads in any
22
+ project.
23
+
24
+ ### Changed
25
+
26
+ - Webhook routes are read straight from the webhook entries instead of being duplicated as
27
+ tunnel entries.
28
+ - The daemon's ports are no longer persisted between runs.
29
+ - A newer plugin simply stops the old daemon and starts its own.
30
+
31
+ ## [0.4.0] — 2026-11-25
32
+
33
+ ### Added
34
+
35
+ - **`endpoints` module (on by default): public URLs, verified webhooks and supervised
36
+ microservices.** Four tools:
37
+ - `apex_webhook` creates a webhook URL that verifies GitHub, Stripe or Slack signatures,
38
+ a generic HMAC-SHA256 or a token, then calls `events.ingest` on loopback. Senders never
39
+ get the server password, and the agent writes no relay code.
40
+ - `apex_tunnel` publishes a local port on an OpenTunnel HTTPS URL.
41
+ - `apex_service` runs a microservice the agent wrote. It restarts with backoff, keeps
42
+ logs, can have a public URL, and wakes agents through a local ingest with its own token.
43
+ - `apex_daemon` reports status, turns autostart on or off, and stops the daemon.
44
+
45
+ Webhooks, tunnels and services can have a TTL, so they are temporary or permanent.
46
+ - **apex daemon.** One process per user keeps these alive, outside the plugin that OpenCode
47
+ unloads after 60 minutes.
48
+ - It runs on OpenCode's own executable in bun mode (`BUN_BE_BUN=1`), so it works on
49
+ Linux with any init system, on macOS and on Windows, without systemd, launchd or the
50
+ opentunnel CLI.
51
+ - A lockfile ensures there is only one.
52
+ - It uses `@opentunnel/client` on the device's `default` tunnel, alongside OpenCode
53
+ remote access, with its own routes.
54
+ - It applies TTLs even with OpenCode closed.
55
+ - A newer daemon adopts the services of the one it replaces instead of restarting them.
56
+ - It exits after 10 minutes with nothing to keep.
57
+ - **Optional autostart** after a reboot: a crontab `@reboot` line on Linux, macOS and BSD,
58
+ a logon task on Windows. Off by default.
59
+ - **New packaged skill `apex-endpoints`.** `apex-callbacks` now points to `apex_webhook`
60
+ and `apex_service` before hand-written relays and OS units. See
61
+ [docs/ENDPOINTS.md](docs/ENDPOINTS.md).
62
+
63
+ ### Dependencies
64
+
65
+ - `@opentunnel/client` ^0.7.0. Its peer `effect` is the one `@opencode/plugin` already
66
+ brings.
67
+
8
68
  ## [0.3.0] — 2026-11-25
9
69
 
10
70
  ### Deprecated
package/README.md CHANGED
@@ -62,11 +62,12 @@ apex is one plugin with six independent modules. Each one can be switched on or
62
62
  | **Guard** | Meta-permissions per agent, tool and path, with a report of what was attempted and decided. | **off** | [docs/GUARD.md](docs/GUARD.md) |
63
63
  | **Browser** *(deprecated)* | Serves OpenCode's `browser.*` tools against an **external** Chromium over CDP. Superseded by OpenCode's [browse](https://opencode.ai/product/browse) for your own browser; kept for a headless or remote Chromium and for `browser.*` performance captures. | **off** | [docs/BROWSER.md](docs/BROWSER.md) |
64
64
  | **Temp access** | Allows `external_directory` in OpenCode's temporary directory (`<tmpdir>/opencode`, `/tmp/opencode` on Linux) without asking. OpenCode tells the model to use it but no rule approves it. A deny you configure for that path still wins. | on | — |
65
+ | **Endpoints** | Public URLs through [OpenTunnel](https://opentunnel.xyz) (same device tunnel as OpenCode remote access, own routes) and **verified webhooks** (GitHub, Stripe, Slack, HMAC, token) that wake agents without exposing the server password. Optional TTL. Kept by a per-user apex daemon that outlives the plugin; Linux, macOS, Windows, no tunnel CLI. The daemon starts only when a tool is used. | on | [docs/ENDPOINTS.md](docs/ENDPOINTS.md) |
65
66
 
66
67
  Turn modules on or off in `modules`. That is the only switch: there is no `<module>.enabled`.
67
68
 
68
69
  ```jsonc
69
- "modules": { "redact": true, "events": true, "advisor": true, "guard": false, "browser": false, "tempAccess": true }
70
+ "modules": { "redact": true, "events": true, "advisor": true, "guard": false, "browser": false, "tempAccess": true, "endpoints": true }
70
71
  ```
71
72
 
72
73
  ## Requirements
@@ -240,6 +241,9 @@ curl -sS -u "opencode:$PW" -H 'content-type: application/json' \
240
241
  | `apex_list_subscriptions` | events | Lists subscriptions; config ones are marked read-only |
241
242
  | `apex_callback_endpoint` | events | How an external program reaches this server: URL, RPC URLs for this project, auth, curl examples |
242
243
  | `apex_set_callback_url` | events | Sets or clears the server's public URL (tunnel / reverse proxy), for senders on other machines |
244
+ | `apex_webhook` | endpoints | Verified webhook URL (github, stripe, slack, hmac, token) that calls `events.ingest` locally: create / list / delete, TTL |
245
+ | `apex_tunnel` | endpoints | Publishes a local port on an OpenTunnel HTTPS URL: open / list / close, TTL |
246
+ | `apex_daemon` | endpoints | Daemon status and stop |
243
247
  | `apex_advisor_decide` | advisor | The advisor agent's only tool: `allow` / `deny` + reason |
244
248
  | `apex_guard_report` | guard | Report of what each agent attempted and what was decided |
245
249
  | `browser_target` | browser (deprecated, off by default) | Chooses which browser serves `browser.*`: `external` (CDP), `in-app` (desktop app) or `auto` |
package/core/config.ts CHANGED
@@ -266,6 +266,8 @@ export const apexConfigSchema = z.object({
266
266
  browser: z.boolean().optional(),
267
267
  // Activado por defecto: external_directory sin preguntar en <tmpdir>/opencode.
268
268
  tempAccess: z.boolean().optional(),
269
+ // Activado por defecto: apex_tunnel/webhook/daemon (el daemon solo se lanza al usarlas).
270
+ endpoints: z.boolean().optional(),
269
271
  })
270
272
  .default(() => ({})),
271
273
  })
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Lado plugin del daemon de apex: lo encuentra, lo lanza si hace falta y le habla por
3
+ * su API de control (127.0.0.1 + token de daemon.json, 0600).
4
+ *
5
+ * Se lanza desacoplado con el binario que ejecuta este plugin: dentro de OpenCode es su
6
+ * propio ejecutable, que con `BUN_BE_BUN=1` se comporta como bun (todas las plataformas).
7
+ * Así sobrevive a que OpenCode descargue el plugin o se reinicie.
8
+ */
9
+
10
+ import { spawn } from "node:child_process"
11
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync } from "node:fs"
12
+ import { fileURLToPath } from "node:url"
13
+ import { daemonPaths, type DaemonInfo, type DaemonPaths, type ServerTarget } from "../daemon/shared.js"
14
+ import type { ServerEndpoint } from "./server-endpoint.js"
15
+
16
+ export const DAEMON_SCRIPT = fileURLToPath(new URL("../daemon/main.ts", import.meta.url))
17
+
18
+ export class DaemonError extends Error {
19
+ constructor(
20
+ message: string,
21
+ readonly status?: number,
22
+ ) {
23
+ super(message)
24
+ }
25
+ }
26
+
27
+ /** a > b en semver simple (x.y.z); lo demás cuenta como igual. */
28
+ export function newerVersion(a: string, b: string): boolean {
29
+ const parse = (v: string) => v.split(/[.-]/).slice(0, 3).map((n) => Number(n))
30
+ const [x, y] = [parse(a), parse(b)]
31
+ for (let i = 0; i < 3; i++) {
32
+ const l = x[i] ?? 0
33
+ const r = y[i] ?? 0
34
+ if (!Number.isFinite(l) || !Number.isFinite(r)) return false
35
+ if (l !== r) return l > r
36
+ }
37
+ return false
38
+ }
39
+
40
+ /** Cómo lanzar el daemon: el ejecutable actual en modo bun. */
41
+ export function daemonCommand(version: string, execPath = process.execPath, script = DAEMON_SCRIPT, home?: string) {
42
+ const env: Record<string, string> = { BUN_BE_BUN: "1", APEX_DAEMON_VERSION: version }
43
+ if (home) env.APEX_DAEMON_HOME = home
44
+ return { command: execPath, args: [script], env }
45
+ }
46
+
47
+ function readInfo(paths: DaemonPaths): DaemonInfo | null {
48
+ try {
49
+ return JSON.parse(readFileSync(paths.info, "utf8")) as DaemonInfo
50
+ } catch {
51
+ return null
52
+ }
53
+ }
54
+
55
+ async function call<T>(info: DaemonInfo, method: string, path: string, body?: unknown, timeoutMs = 10_000): Promise<T> {
56
+ const response = await fetch(`http://127.0.0.1:${info.port}${path}`, {
57
+ method,
58
+ headers: { authorization: `Bearer ${info.token}`, "content-type": "application/json" },
59
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
60
+ signal: AbortSignal.timeout(timeoutMs),
61
+ })
62
+ const text = await response.text()
63
+ let data: unknown
64
+ try {
65
+ data = JSON.parse(text)
66
+ } catch {
67
+ data = { error: text }
68
+ }
69
+ if (!response.ok) throw new DaemonError((data as { error?: string }).error || `daemon HTTP ${response.status} on ${method} ${path}`, response.status)
70
+ return data as T
71
+ }
72
+
73
+ async function healthy(info: DaemonInfo | null): Promise<{ version: string } | null> {
74
+ if (!info) return null
75
+ try {
76
+ return await call<{ version: string }>(info, "GET", "/v1/health", undefined, 1500)
77
+ } catch {
78
+ return null
79
+ }
80
+ }
81
+
82
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
83
+
84
+ export interface DaemonClient {
85
+ readonly info: DaemonInfo
86
+ readonly request: <T = Record<string, unknown>>(method: string, path: string, body?: unknown) => Promise<T>
87
+ }
88
+
89
+ export interface EnsureOptions {
90
+ readonly version: string
91
+ /** false: solo si ya corre (no lanzar). */
92
+ readonly spawn: boolean
93
+ readonly paths?: DaemonPaths
94
+ }
95
+
96
+ /** El daemon vivo, lanzándolo (o sustituyéndolo por uno más nuevo) si hace falta. */
97
+ export async function ensureDaemon(options: EnsureOptions): Promise<DaemonClient | null> {
98
+ const paths = options.paths ?? daemonPaths()
99
+ let info = readInfo(paths)
100
+ let health = await healthy(info)
101
+ if (health && info && newerVersion(options.version, health.version)) {
102
+ // Plugin actualizado: el daemon viejo se cierra y arranca el nuevo.
103
+ await call(info, "POST", "/v1/shutdown", {}).catch(() => undefined)
104
+ for (let i = 0; i < 50 && (await healthy(info)); i++) await sleep(100)
105
+ health = null
106
+ }
107
+ if (health && info) return client(info)
108
+ if (!options.spawn) return null
109
+
110
+ mkdirSync(paths.home, { recursive: true, mode: 0o700 })
111
+ const { command, args, env } = daemonCommand(options.version, process.execPath, DAEMON_SCRIPT, paths.home)
112
+ const fd = openSync(paths.log, "a", 0o600)
113
+ try {
114
+ const child = spawn(command, args, {
115
+ cwd: paths.home,
116
+ env: { ...process.env, ...env },
117
+ detached: true,
118
+ stdio: ["ignore", fd, fd],
119
+ windowsHide: true,
120
+ })
121
+ child.on("error", () => {})
122
+ child.unref()
123
+ } finally {
124
+ closeSync(fd)
125
+ }
126
+ for (let i = 0; i < 100; i++) {
127
+ await sleep(100)
128
+ info = readInfo(paths)
129
+ if (info && (await healthy(info))) return client(info)
130
+ }
131
+ throw new DaemonError(`apex daemon did not start; see ${paths.log}`)
132
+ }
133
+
134
+ function client(info: DaemonInfo): DaemonClient {
135
+ return { info, request: (method, path, body) => call(info, method, path, body) }
136
+ }
137
+
138
+ /** ¿Hay algo que mantener? (sin registro no se lanza nada al cargar el plugin). */
139
+ export function hasRegistryEntries(paths: DaemonPaths = daemonPaths()): boolean {
140
+ if (!existsSync(paths.registry)) return false
141
+ try {
142
+ const registry = JSON.parse(readFileSync(paths.registry, "utf8")) as Record<string, unknown[] | undefined>
143
+ return ["tunnels", "webhooks"].some((key) => (registry[key]?.length ?? 0) > 0)
144
+ } catch {
145
+ return false
146
+ }
147
+ }
148
+
149
+ /** Cómo llega el daemon al servidor de este proyecto, desde lo que ya resuelve events. */
150
+ export function serverTarget(endpoint: ServerEndpoint, env: NodeJS.ProcessEnv = process.env): ServerTarget | null {
151
+ if (!endpoint.baseUrl) return null
152
+ const source = endpoint.auth.password
153
+ let password: ServerTarget["password"] = null
154
+ if (source?.kind === "file" && source.file) password = { kind: "file", file: source.file, field: source.field ?? "password" }
155
+ else if (source?.kind === "env" && source.env && env[source.env]) password = { kind: "value", value: env[source.env]! }
156
+ return { baseUrl: endpoint.baseUrl, password, updatedAt: Date.now() }
157
+ }