opencode-apex 0.3.0 → 0.4.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 +37 -0
- package/README.md +6 -1
- package/core/autostart.ts +67 -0
- package/core/config.ts +2 -0
- package/core/daemon-client.ts +180 -0
- package/daemon/main.ts +1039 -0
- package/daemon/shared.ts +155 -0
- package/daemon/webhooks.ts +165 -0
- package/docs/CONFIG.md +2 -1
- package/docs/ENDPOINTS.md +87 -0
- package/endpoints.ts +286 -0
- package/index.ts +9 -1
- package/opencode-apex.jsonc +3 -1
- package/package.json +10 -4
- package/skills/apex-callbacks/SKILL.md +7 -2
- package/skills/apex-callbacks/references/reachability.md +3 -1
- package/skills/apex-endpoints/SKILL.md +130 -0
package/daemon/shared.ts
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lo que comparten el daemon de apex y el plugin: rutas en disco y forma del registro.
|
|
3
|
+
*
|
|
4
|
+
* El daemon es UN proceso por usuario (no por proyecto): mantiene las rutas de
|
|
5
|
+
* OpenTunnel, recibe webhooks y vigila los microservicios del agente. Vive fuera del
|
|
6
|
+
* plugin porque OpenCode descarga los plugins tras 60 min sin actividad.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { homedir } from "node:os"
|
|
10
|
+
import { join } from "node:path"
|
|
11
|
+
|
|
12
|
+
/** `<XDG_STATE_HOME|~/.local/state>/opencode-apex` (también en Windows, como OpenCode). */
|
|
13
|
+
export function daemonHome(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {
|
|
14
|
+
if (env.APEX_DAEMON_HOME && env.APEX_DAEMON_HOME.length > 0) return env.APEX_DAEMON_HOME
|
|
15
|
+
const base = env.XDG_STATE_HOME && env.XDG_STATE_HOME.length > 0 ? env.XDG_STATE_HOME : join(home, ".local", "state")
|
|
16
|
+
return join(base, "opencode-apex")
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface DaemonPaths {
|
|
20
|
+
readonly home: string
|
|
21
|
+
/** { pid, port, token, version, startedAt } — 0600. */
|
|
22
|
+
readonly info: string
|
|
23
|
+
readonly lock: string
|
|
24
|
+
/** Rutas, webhooks, servicios y servidores — 0600 (lleva secretos de webhooks). */
|
|
25
|
+
readonly registry: string
|
|
26
|
+
readonly log: string
|
|
27
|
+
readonly logs: string
|
|
28
|
+
/** Lanzador que usa el autoarranque; el plugin lo reescribe con las rutas actuales. */
|
|
29
|
+
readonly launcher: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function daemonPaths(home = daemonHome()): DaemonPaths {
|
|
33
|
+
return {
|
|
34
|
+
home,
|
|
35
|
+
info: join(home, "daemon.json"),
|
|
36
|
+
lock: join(home, "daemon.lock"),
|
|
37
|
+
registry: join(home, "registry.json"),
|
|
38
|
+
log: join(home, "daemon.log"),
|
|
39
|
+
logs: join(home, "logs"),
|
|
40
|
+
launcher: join(home, process.platform === "win32" ? "launch.cmd" : "launch.sh"),
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface DaemonInfo {
|
|
45
|
+
readonly pid: number
|
|
46
|
+
/** Puerto de control (solo 127.0.0.1, nunca se publica por el túnel). */
|
|
47
|
+
readonly port: number
|
|
48
|
+
readonly token: string
|
|
49
|
+
readonly version: string
|
|
50
|
+
readonly startedAt: number
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Cómo llama el daemon al RPC `events.ingest` de un proyecto (el password nunca sale de la máquina). */
|
|
54
|
+
export interface ServerTarget {
|
|
55
|
+
readonly baseUrl: string
|
|
56
|
+
/** file: se lee en cada llamada (el servicio lo reescribe al reiniciar) · value: `opencode serve` con variable. */
|
|
57
|
+
readonly password: { readonly kind: "file"; readonly file: string; readonly field: string } | { readonly kind: "value"; readonly value: string } | null
|
|
58
|
+
readonly updatedAt: number
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export type ProxyProtocol = "v1" | "v2"
|
|
62
|
+
|
|
63
|
+
interface Owned {
|
|
64
|
+
readonly id: string
|
|
65
|
+
/** Proyecto que lo creó (las llamadas a events.ingest van a este directorio). */
|
|
66
|
+
readonly directory: string
|
|
67
|
+
readonly sessionID: string | null
|
|
68
|
+
readonly createdAt: number
|
|
69
|
+
/** null = permanente. */
|
|
70
|
+
readonly expiresAt: number | null
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Puerto local publicado en una ruta del túnel. */
|
|
74
|
+
export interface TunnelEntry extends Owned {
|
|
75
|
+
readonly kind: "tunnel"
|
|
76
|
+
readonly route: string
|
|
77
|
+
readonly target: string
|
|
78
|
+
readonly proxyProtocol?: ProxyProtocol
|
|
79
|
+
/** Ruta creada por un servicio o webhook (se borra con él). */
|
|
80
|
+
readonly ownerID?: string
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export type WebhookProvider = "github" | "stripe" | "slack" | "hmac" | "token"
|
|
84
|
+
|
|
85
|
+
export interface WebhookEntry extends Owned {
|
|
86
|
+
readonly kind: "webhook"
|
|
87
|
+
readonly name: string
|
|
88
|
+
readonly provider: WebhookProvider
|
|
89
|
+
readonly secret: string
|
|
90
|
+
/** Fichero 0600 con el secreto, para configurarlo en el emisor sin pasarlo por la conversación. */
|
|
91
|
+
readonly secretFile: string
|
|
92
|
+
/** hmac: cabecera con la firma (por defecto x-signature) y codificación. */
|
|
93
|
+
readonly header?: string
|
|
94
|
+
readonly encoding?: "hex" | "base64"
|
|
95
|
+
/** `source` de events.ingest (por defecto el proveedor). */
|
|
96
|
+
readonly source: string
|
|
97
|
+
readonly route: string
|
|
98
|
+
readonly stats: { ok: number; rejected: number; failed: number; lastAt: number | null; lastError: string | null }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type RestartPolicy = "always" | "on-failure" | "never"
|
|
102
|
+
|
|
103
|
+
export interface ServiceEntry extends Owned {
|
|
104
|
+
readonly kind: "service"
|
|
105
|
+
readonly name: string
|
|
106
|
+
/** Línea de shell (sh -c / cmd /c). */
|
|
107
|
+
readonly command: string
|
|
108
|
+
readonly cwd: string
|
|
109
|
+
readonly env: Readonly<Record<string, string>>
|
|
110
|
+
readonly port: number | null
|
|
111
|
+
readonly restart: RestartPolicy
|
|
112
|
+
/** Token con el que el servicio llama al ingest local del daemon (APEX_INGEST_TOKEN). */
|
|
113
|
+
readonly ingestToken: string
|
|
114
|
+
readonly logFile: string
|
|
115
|
+
/** Estado de ejecución (lo actualiza el daemon). */
|
|
116
|
+
pid: number | null
|
|
117
|
+
/** Arranque del sistema en el que corre `pid` (un pid de otro arranque no vale). */
|
|
118
|
+
bootAt: number | null
|
|
119
|
+
status: "starting" | "running" | "backoff" | "stopped" | "failed"
|
|
120
|
+
restarts: number
|
|
121
|
+
lastExit: { code: number | null; signal: string | null; at: number } | null
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface Registry {
|
|
125
|
+
version: 1
|
|
126
|
+
tunnels: TunnelEntry[]
|
|
127
|
+
webhooks: WebhookEntry[]
|
|
128
|
+
services: ServiceEntry[]
|
|
129
|
+
/** directorio → cómo llegar a su servidor. */
|
|
130
|
+
servers: Record<string, ServerTarget>
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function emptyRegistry(): Registry {
|
|
134
|
+
return { version: 1, tunnels: [], webhooks: [], services: [], servers: {} }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Nombre de ruta aleatorio: 16 hex, como los del CLI de OpenTunnel (no aparecen en los logs de certificados). */
|
|
138
|
+
export function randomRoute(): string {
|
|
139
|
+
const bytes = crypto.getRandomValues(new Uint8Array(8))
|
|
140
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Etiqueta DNS válida para una ruta elegida a mano. */
|
|
144
|
+
export function validRouteName(name: string): boolean {
|
|
145
|
+
return /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(name)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function randomToken(bytes = 32): string {
|
|
149
|
+
return Array.from(crypto.getRandomValues(new Uint8Array(bytes)), (b) => b.toString(16).padStart(2, "0")).join("")
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Marca del arranque actual del sistema, redondeada a 10 s (os.uptime oscila). */
|
|
153
|
+
export function bootStamp(now = Date.now(), uptimeSeconds: number): number {
|
|
154
|
+
return Math.round((now - uptimeSeconds * 1000) / 10_000) * 10_000
|
|
155
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Verificación de webhooks y traducción a `events.ingest`. Puro (sin red ni disco) para
|
|
3
|
+
* poder probarlo.
|
|
4
|
+
*
|
|
5
|
+
* Nada se fía de la petición: por el túnel todo llega desde 127.0.0.1 con el `Host` que
|
|
6
|
+
* eligió el visitante (docs/trust-boundary.md de OpenTunnel). Solo vale la firma o el
|
|
7
|
+
* token del webhook, comparados en tiempo constante.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { createHmac, timingSafeEqual } from "node:crypto"
|
|
11
|
+
import type { WebhookEntry } from "./shared.js"
|
|
12
|
+
|
|
13
|
+
export type Headers = Readonly<Record<string, string | undefined>>
|
|
14
|
+
|
|
15
|
+
export interface Verdict {
|
|
16
|
+
readonly ok: boolean
|
|
17
|
+
readonly reason?: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Ventana de reloj para Stripe y Slack (anti-replay), como sus SDKs. */
|
|
21
|
+
export const TOLERANCE_SECONDS = 300
|
|
22
|
+
|
|
23
|
+
function safeEqual(a: string, b: string): boolean {
|
|
24
|
+
const left = Buffer.from(a)
|
|
25
|
+
const right = Buffer.from(b)
|
|
26
|
+
return left.length === right.length && timingSafeEqual(left, right)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function hmac(secret: string, data: Buffer | string, encoding: "hex" | "base64" = "hex"): string {
|
|
30
|
+
return createHmac("sha256", secret).update(data).digest(encoding)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function fresh(timestamp: string | undefined, nowSeconds: number): boolean {
|
|
34
|
+
const t = Number(timestamp)
|
|
35
|
+
return Number.isFinite(t) && Math.abs(nowSeconds - t) <= TOLERANCE_SECONDS
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function verify(
|
|
39
|
+
hook: Pick<WebhookEntry, "provider" | "secret" | "header" | "encoding">,
|
|
40
|
+
headers: Headers,
|
|
41
|
+
body: Buffer,
|
|
42
|
+
url: URL,
|
|
43
|
+
nowSeconds = Math.floor(Date.now() / 1000),
|
|
44
|
+
): Verdict {
|
|
45
|
+
switch (hook.provider) {
|
|
46
|
+
case "github": {
|
|
47
|
+
const signature = headers["x-hub-signature-256"]
|
|
48
|
+
if (!signature) return { ok: false, reason: "missing x-hub-signature-256" }
|
|
49
|
+
return safeEqual(signature, `sha256=${hmac(hook.secret, body)}`) ? { ok: true } : { ok: false, reason: "bad signature" }
|
|
50
|
+
}
|
|
51
|
+
case "stripe": {
|
|
52
|
+
const header = headers["stripe-signature"]
|
|
53
|
+
if (!header) return { ok: false, reason: "missing stripe-signature" }
|
|
54
|
+
const parts = header.split(",").map((part) => part.trim().split("=") as [string, string | undefined])
|
|
55
|
+
const t = parts.find(([key]) => key === "t")?.[1]
|
|
56
|
+
if (!fresh(t, nowSeconds)) return { ok: false, reason: "stale or missing timestamp" }
|
|
57
|
+
const expected = hmac(hook.secret, `${t}.${body.toString("utf8")}`)
|
|
58
|
+
const match = parts.some(([key, value]) => key === "v1" && value !== undefined && safeEqual(value, expected))
|
|
59
|
+
return match ? { ok: true } : { ok: false, reason: "bad signature" }
|
|
60
|
+
}
|
|
61
|
+
case "slack": {
|
|
62
|
+
const timestamp = headers["x-slack-request-timestamp"]
|
|
63
|
+
const signature = headers["x-slack-signature"]
|
|
64
|
+
if (!signature) return { ok: false, reason: "missing x-slack-signature" }
|
|
65
|
+
if (!fresh(timestamp, nowSeconds)) return { ok: false, reason: "stale or missing timestamp" }
|
|
66
|
+
const expected = `v0=${hmac(hook.secret, `v0:${timestamp}:${body.toString("utf8")}`)}`
|
|
67
|
+
return safeEqual(signature, expected) ? { ok: true } : { ok: false, reason: "bad signature" }
|
|
68
|
+
}
|
|
69
|
+
case "hmac": {
|
|
70
|
+
const name = (hook.header ?? "x-signature").toLowerCase()
|
|
71
|
+
const raw = headers[name]
|
|
72
|
+
if (!raw) return { ok: false, reason: `missing ${name}` }
|
|
73
|
+
// Algunos emisores anteponen el algoritmo (`sha256=...`).
|
|
74
|
+
const signature = raw.replace(/^sha256=/i, "")
|
|
75
|
+
return safeEqual(signature, hmac(hook.secret, body, hook.encoding ?? "hex"))
|
|
76
|
+
? { ok: true }
|
|
77
|
+
: { ok: false, reason: "bad signature" }
|
|
78
|
+
}
|
|
79
|
+
case "token": {
|
|
80
|
+
const bearer = headers.authorization?.replace(/^Bearer\s+/i, "")
|
|
81
|
+
const candidate = headers["x-apex-token"] ?? bearer ?? url.searchParams.get("token") ?? undefined
|
|
82
|
+
if (!candidate) return { ok: false, reason: "missing token" }
|
|
83
|
+
return safeEqual(candidate, hook.secret) ? { ok: true } : { ok: false, reason: "bad token" }
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Cuerpo → objeto: JSON, formulario (Slack manda `payload=<json>`) o texto. */
|
|
89
|
+
export function parseBody(body: Buffer, contentType: string | undefined): Record<string, unknown> {
|
|
90
|
+
const text = body.toString("utf8")
|
|
91
|
+
const type = (contentType ?? "").toLowerCase()
|
|
92
|
+
if (type.includes("application/x-www-form-urlencoded")) {
|
|
93
|
+
const form = Object.fromEntries(new URLSearchParams(text))
|
|
94
|
+
if (typeof form.payload === "string") {
|
|
95
|
+
try {
|
|
96
|
+
const inner = JSON.parse(form.payload)
|
|
97
|
+
if (inner && typeof inner === "object" && !Array.isArray(inner)) return inner as Record<string, unknown>
|
|
98
|
+
} catch {
|
|
99
|
+
// payload que no es JSON: se queda como campo
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return form
|
|
103
|
+
}
|
|
104
|
+
if (text.trim().length === 0) return {}
|
|
105
|
+
try {
|
|
106
|
+
const parsed = JSON.parse(text)
|
|
107
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : { body: parsed }
|
|
108
|
+
} catch {
|
|
109
|
+
return { body: text }
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Cabeceras que llegan al agente: las del proveedor, nunca firmas ni credenciales. */
|
|
114
|
+
const FORWARDED = /^(x-github-|x-gitlab-event|x-event-|x-request-id|user-agent$|content-type$)/
|
|
115
|
+
const HIDDEN = /signature|token|authorization|cookie|secret/
|
|
116
|
+
|
|
117
|
+
export function forwardedHeaders(headers: Headers): Record<string, string> {
|
|
118
|
+
const out: Record<string, string> = {}
|
|
119
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
120
|
+
if (value !== undefined && FORWARDED.test(key) && !HIDDEN.test(key)) out[key] = value
|
|
121
|
+
}
|
|
122
|
+
return out
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export interface IngestCall {
|
|
126
|
+
readonly source: string
|
|
127
|
+
readonly type?: string
|
|
128
|
+
readonly eventID?: string
|
|
129
|
+
readonly payload: Record<string, unknown>
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Tipo e id del evento según el proveedor (el id deduplica reintentos en apex). */
|
|
133
|
+
export function toIngest(hook: Pick<WebhookEntry, "provider" | "source" | "name">, headers: Headers, payload: Record<string, unknown>): IngestCall {
|
|
134
|
+
let type: string | undefined
|
|
135
|
+
let eventID: string | undefined
|
|
136
|
+
if (hook.provider === "github") {
|
|
137
|
+
const event = headers["x-github-event"]
|
|
138
|
+
const action = typeof payload.action === "string" ? payload.action : undefined
|
|
139
|
+
type = event ? (action ? `${event}.${action}` : event) : undefined
|
|
140
|
+
eventID = headers["x-github-delivery"]
|
|
141
|
+
} else if (hook.provider === "stripe") {
|
|
142
|
+
type = typeof payload.type === "string" ? payload.type : undefined
|
|
143
|
+
eventID = typeof payload.id === "string" ? payload.id : undefined
|
|
144
|
+
} else if (hook.provider === "slack") {
|
|
145
|
+
const inner = payload.event as { type?: unknown } | undefined
|
|
146
|
+
type = typeof inner?.type === "string" ? inner.type : typeof payload.type === "string" ? payload.type : undefined
|
|
147
|
+
eventID = typeof payload.event_id === "string" ? payload.event_id : undefined
|
|
148
|
+
} else {
|
|
149
|
+
type = headers["x-event-type"] ?? (typeof payload.type === "string" ? payload.type : undefined)
|
|
150
|
+
eventID = headers["x-event-id"] ?? headers["x-request-id"]
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
source: hook.source,
|
|
154
|
+
...(type ? { type } : {}),
|
|
155
|
+
...(eventID ? { eventID: `${hook.name}:${eventID}` } : {}),
|
|
156
|
+
payload: { ...payload, _webhook: { name: hook.name, provider: hook.provider, headers: forwardedHeaders(headers) } },
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Slack verifica la URL con un `url_verification` que hay que contestar con el challenge. */
|
|
161
|
+
export function slackChallenge(hook: Pick<WebhookEntry, "provider">, payload: Record<string, unknown>): string | null {
|
|
162
|
+
return hook.provider === "slack" && payload.type === "url_verification" && typeof payload.challenge === "string"
|
|
163
|
+
? payload.challenge
|
|
164
|
+
: null
|
|
165
|
+
}
|
package/docs/CONFIG.md
CHANGED
|
@@ -81,7 +81,7 @@ but are overridden by the local file.
|
|
|
81
81
|
Each module has exactly one switch, under `modules`:
|
|
82
82
|
|
|
83
83
|
```jsonc
|
|
84
|
-
"modules": { "redact": true, "events": true, "advisor": true, "guard": false, "browser": false, "tempAccess": true }
|
|
84
|
+
"modules": { "redact": true, "events": true, "advisor": true, "guard": false, "browser": false, "tempAccess": true, "endpoints": true }
|
|
85
85
|
```
|
|
86
86
|
|
|
87
87
|
| Module | Default when the key is omitted |
|
|
@@ -92,6 +92,7 @@ Each module has exactly one switch, under `modules`:
|
|
|
92
92
|
| `guard` | **off** (it can block the agent if its rules are wrong, so you opt in) |
|
|
93
93
|
| `browser` | **off** since 0.3.0 (deprecated: use OpenCode's [browse](https://opencode.ai/product/browse)) |
|
|
94
94
|
| `tempAccess` | on |
|
|
95
|
+
| `endpoints` | on (the daemon starts only when an `apex_webhook` / `apex_tunnel` / `apex_service` tool is used, see [ENDPOINTS.md](ENDPOINTS.md)) |
|
|
95
96
|
|
|
96
97
|
There is no `<module>.enabled` key. A legacy `events.enabled` is ignored and logs a
|
|
97
98
|
warning. So does `events.listener`: the HTTP listener was removed in 0.2.0, see
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# Endpoints: OpenTunnel routes, verified webhooks and microservices
|
|
2
|
+
|
|
3
|
+
With this module, agents can:
|
|
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.
|
|
9
|
+
|
|
10
|
+
## Architecture
|
|
11
|
+
|
|
12
|
+
```
|
|
13
|
+
Internet ─HTTPS─▶ OpenTunnel ─▶ apex daemon ─┬─ webhook listener (127.0.0.1) ── verify ──▶ POST events.ingest (local, Basic auth)
|
|
14
|
+
<route>.<id>.opentunnel.xyz ├─ route ──▶ microservice 127.0.0.1:PORT
|
|
15
|
+
└─ route ──▶ any local port
|
|
16
|
+
control API (127.0.0.1, token; never routed) ◀── plugin tools
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
- **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` / `apex_service` call, and again on plugin load whenever its registry is not empty.
|
|
22
|
+
- A lockfile ensures there is only one.
|
|
23
|
+
- It exits after 10 minutes with nothing to keep.
|
|
24
|
+
- **Runtime:** OpenCode's own executable in bun mode (`BUN_BE_BUN=1`). Nothing extra to install, and it works on every platform OpenCode runs on. It uses no systemd and no launchd.
|
|
25
|
+
- **Tunnel:** the daemon uses the `@opentunnel/client` SDK (pure JavaScript, so it also works on Windows). It connects to the device's `default` profile, the same tunnel OpenCode remote access uses, and claims **its own routes**.
|
|
26
|
+
- Routes are cheap. New tunnels are not: about 30 per hour per IP.
|
|
27
|
+
- The first use on a device without a tunnel issues its certificate, which takes about a minute.
|
|
28
|
+
- **Webhooks:** the daemon is the intermediate program between the Internet and OpenCode's RPC.
|
|
29
|
+
- Each webhook has its own random route and secret.
|
|
30
|
+
- The listener verifies the signature or token in constant time.
|
|
31
|
+
- Only then does it call `events.ingest` on loopback. The server password never leaves the machine.
|
|
32
|
+
- **Microservices:** started with `sh -c` / `cmd /c` in their own process group.
|
|
33
|
+
- Their output goes straight to `logs/<name>.log`.
|
|
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.
|
|
42
|
+
|
|
43
|
+
## Files
|
|
44
|
+
|
|
45
|
+
`<XDG_STATE_HOME or ~/.local/state>/opencode-apex/`, on every OS. `APEX_DAEMON_HOME` overrides it.
|
|
46
|
+
|
|
47
|
+
| File | What |
|
|
48
|
+
| --- | --- |
|
|
49
|
+
| `daemon.json` (0600) | pid, control port, control token, version |
|
|
50
|
+
| `daemon.lock` | single-instance lock (pid) |
|
|
51
|
+
| `registry.json` (0600) | tunnels, webhooks (with their secrets), services, how to reach each project's server |
|
|
52
|
+
| `secrets/<hook>.secret` (0600) | each webhook's secret, for configuring the sender without pasting it |
|
|
53
|
+
| `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
|
+
|
|
66
|
+
## Security
|
|
67
|
+
|
|
68
|
+
- The control API listens on 127.0.0.1 and requires a token from a 0600 file. The tunnel never routes it.
|
|
69
|
+
- 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
|
+
- Services must authenticate their own requests: a random route is not authentication.
|
|
71
|
+
- Tool output never contains secrets: webhook secrets are returned as `secretFile` only, and services' ingest tokens and `env` values are never returned.
|
|
72
|
+
- Services inherit the daemon's environment **minus** `OPENCODE_SERVER_PASSWORD` / `OPENCODE_PASSWORD`.
|
|
73
|
+
- Publishing the OpenCode server's own port is refused. Use OpenCode remote access (`opencode service set remote true`), which has its own password.
|
|
74
|
+
|
|
75
|
+
## Network
|
|
76
|
+
|
|
77
|
+
The daemon inherits OpenCode's environment:
|
|
78
|
+
- `HTTPS_PROXY` / `NO_PROXY` and `OPENTUNNEL_CA_CERT` apply. A SOCKS proxy is not supported by OpenTunnel.
|
|
79
|
+
- `OPENTUNNEL_API` points it at a self-hosted OpenTunnel server.
|
|
80
|
+
|
|
81
|
+
After changing any of these, run `apex_daemon({action:"stop"})`; the next tool call starts the daemon with the new values.
|
|
82
|
+
|
|
83
|
+
## Turning it off
|
|
84
|
+
|
|
85
|
+
`"modules": { "endpoints": false }` removes the four tools, and the plugin no longer launches the daemon. To stop a running daemon and its services:
|
|
86
|
+
1. `apex_service({action:"down"})` for each service;
|
|
87
|
+
2. `apex_daemon({action:"stop"})`.
|