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 +60 -0
- package/README.md +5 -1
- package/core/config.ts +2 -0
- package/core/daemon-client.ts +157 -0
- package/daemon/main.ts +688 -0
- package/daemon/shared.ts +119 -0
- package/daemon/webhooks.ts +165 -0
- package/docs/CONFIG.md +2 -1
- package/docs/ENDPOINTS.md +64 -0
- package/endpoints.ts +221 -0
- package/index.ts +9 -1
- package/opencode-apex.jsonc +3 -1
- package/package.json +9 -4
- package/skills/apex-callbacks/SKILL.md +3 -2
- package/skills/apex-callbacks/references/reachability.md +3 -1
- package/skills/apex-endpoints/SKILL.md +114 -0
package/daemon/shared.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
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 y recibe webhooks. 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 y servidores — 0600 (lleva secretos de webhooks). */
|
|
25
|
+
readonly registry: string
|
|
26
|
+
readonly log: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function daemonPaths(home = daemonHome()): DaemonPaths {
|
|
30
|
+
return {
|
|
31
|
+
home,
|
|
32
|
+
info: join(home, "daemon.json"),
|
|
33
|
+
lock: join(home, "daemon.lock"),
|
|
34
|
+
registry: join(home, "registry.json"),
|
|
35
|
+
log: join(home, "daemon.log"),
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface DaemonInfo {
|
|
40
|
+
readonly pid: number
|
|
41
|
+
/** Puerto de control (solo 127.0.0.1, nunca se publica por el túnel). */
|
|
42
|
+
readonly port: number
|
|
43
|
+
readonly token: string
|
|
44
|
+
readonly version: string
|
|
45
|
+
readonly startedAt: number
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Cómo llama el daemon al RPC `events.ingest` de un proyecto (el password nunca sale de la máquina). */
|
|
49
|
+
export interface ServerTarget {
|
|
50
|
+
readonly baseUrl: string
|
|
51
|
+
/** file: se lee en cada llamada (el servicio lo reescribe al reiniciar) · value: `opencode serve` con variable. */
|
|
52
|
+
readonly password: { readonly kind: "file"; readonly file: string; readonly field: string } | { readonly kind: "value"; readonly value: string } | null
|
|
53
|
+
readonly updatedAt: number
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export type ProxyProtocol = "v1" | "v2"
|
|
57
|
+
|
|
58
|
+
interface Owned {
|
|
59
|
+
readonly id: string
|
|
60
|
+
/** Proyecto que lo creó (las llamadas a events.ingest van a este directorio). */
|
|
61
|
+
readonly directory: string
|
|
62
|
+
readonly sessionID: string | null
|
|
63
|
+
readonly createdAt: number
|
|
64
|
+
/** null = permanente. */
|
|
65
|
+
readonly expiresAt: number | null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Puerto local publicado en una ruta del túnel. */
|
|
69
|
+
export interface TunnelEntry extends Owned {
|
|
70
|
+
readonly kind: "tunnel"
|
|
71
|
+
readonly route: string
|
|
72
|
+
readonly target: string
|
|
73
|
+
readonly proxyProtocol?: ProxyProtocol
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export type WebhookProvider = "github" | "stripe" | "slack" | "hmac" | "token"
|
|
77
|
+
|
|
78
|
+
export interface WebhookEntry extends Owned {
|
|
79
|
+
readonly kind: "webhook"
|
|
80
|
+
readonly name: string
|
|
81
|
+
readonly provider: WebhookProvider
|
|
82
|
+
readonly secret: string
|
|
83
|
+
/** Fichero 0600 con el secreto, para configurarlo en el emisor sin pasarlo por la conversación. */
|
|
84
|
+
readonly secretFile: string
|
|
85
|
+
/** hmac: cabecera con la firma (por defecto x-signature) y codificación. */
|
|
86
|
+
readonly header?: string
|
|
87
|
+
readonly encoding?: "hex" | "base64"
|
|
88
|
+
/** `source` de events.ingest (por defecto el proveedor). */
|
|
89
|
+
readonly source: string
|
|
90
|
+
readonly route: string
|
|
91
|
+
readonly stats: { ok: number; rejected: number; failed: number; lastAt: number | null; lastError: string | null }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface Registry {
|
|
95
|
+
version: 1
|
|
96
|
+
tunnels: TunnelEntry[]
|
|
97
|
+
webhooks: WebhookEntry[]
|
|
98
|
+
/** directorio → cómo llegar a su servidor. */
|
|
99
|
+
servers: Record<string, ServerTarget>
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function emptyRegistry(): Registry {
|
|
103
|
+
return { version: 1, tunnels: [], webhooks: [], servers: {} }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Nombre de ruta aleatorio: 16 hex, como los del CLI de OpenTunnel (no aparecen en los logs de certificados). */
|
|
107
|
+
export function randomRoute(): string {
|
|
108
|
+
const bytes = crypto.getRandomValues(new Uint8Array(8))
|
|
109
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Etiqueta DNS válida para una ruta elegida a mano. */
|
|
113
|
+
export function validRouteName(name: string): boolean {
|
|
114
|
+
return /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(name)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function randomToken(bytes = 32): string {
|
|
118
|
+
return Array.from(crypto.getRandomValues(new Uint8Array(bytes)), (b) => b.toString(16).padStart(2, "0")).join("")
|
|
119
|
+
}
|
|
@@ -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` 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,64 @@
|
|
|
1
|
+
# Endpoints: OpenTunnel routes and verified webhooks
|
|
2
|
+
|
|
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`.
|
|
4
|
+
|
|
5
|
+
## Architecture
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
Internet ─HTTPS─▶ OpenTunnel ─▶ apex daemon ─┬─ webhook listener (127.0.0.1) ── verify ──▶ POST events.ingest (local, Basic auth)
|
|
9
|
+
<route>.<id>.opentunnel.xyz └─ route ──▶ any local port
|
|
10
|
+
control API (127.0.0.1, token; never routed) ◀── plugin tools
|
|
11
|
+
```
|
|
12
|
+
|
|
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.
|
|
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.
|
|
16
|
+
- It exits after 10 minutes with nothing to keep.
|
|
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.
|
|
25
|
+
- **Webhooks:** the daemon is the intermediate program between the Internet and OpenCode's RPC.
|
|
26
|
+
- Each webhook has its own random route and secret.
|
|
27
|
+
- The listener verifies the signature or token in constant time.
|
|
28
|
+
- Only then does it call `events.ingest` on loopback. The server password never leaves the machine.
|
|
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.
|
|
31
|
+
|
|
32
|
+
## Files
|
|
33
|
+
|
|
34
|
+
They live in `<XDG_STATE_HOME or ~/.local/state>/opencode-apex/` on every OS. `APEX_DAEMON_HOME` overrides the location.
|
|
35
|
+
|
|
36
|
+
| File | What |
|
|
37
|
+
| --- | --- |
|
|
38
|
+
| `daemon.json` (0600) | pid, control port, control token, version |
|
|
39
|
+
| `daemon.lock` | single-instance lock (pid) |
|
|
40
|
+
| `registry.json` (0600) | tunnels, webhooks (with their secrets), how to reach each project's server |
|
|
41
|
+
| `secrets/<hook>.secret` (0600) | each webhook's secret, for configuring the sender without pasting it |
|
|
42
|
+
| `daemon.log` | daemon log |
|
|
43
|
+
|
|
44
|
+
## Security
|
|
45
|
+
|
|
46
|
+
- The control API listens on 127.0.0.1 and needs a token from a 0600 file. The tunnel never routes it.
|
|
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.
|
|
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`.
|
|
50
|
+
- Publishing the OpenCode server's own port is refused. Use OpenCode remote access (`opencode service set remote true`), which has its own password.
|
|
51
|
+
|
|
52
|
+
## Network
|
|
53
|
+
|
|
54
|
+
The daemon inherits OpenCode's environment:
|
|
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.
|
|
58
|
+
|
|
59
|
+
After changing any of these, run `apex_daemon({action:"stop"})`; the next tool call starts the daemon with the new values.
|
|
60
|
+
|
|
61
|
+
## Turning it off
|
|
62
|
+
|
|
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
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Apex Endpoints — el agente publica endpoints que reaccionan a llamadas externas, a
|
|
3
|
+
* través del daemon de apex (daemon/main.ts):
|
|
4
|
+
*
|
|
5
|
+
* - apex_tunnel: un puerto local en una ruta del túnel OpenTunnel (open/list/close, TTL)
|
|
6
|
+
* - apex_webhook: un webhook con firma verificada que despierta al agente (create/list/delete)
|
|
7
|
+
* - apex_daemon: estado y parada del daemon
|
|
8
|
+
*
|
|
9
|
+
* El trabajo lo hace el daemon (un proceso por usuario, fuera del plugin, que OpenCode
|
|
10
|
+
* descarga tras 60 min). Aquí solo se habla con él y se le dice cómo llegar al servidor
|
|
11
|
+
* de este proyecto para los events.ingest de los webhooks.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { Effect } from "effect"
|
|
15
|
+
import type { Scope } from "effect"
|
|
16
|
+
import type { Plugin } from "@opencode/plugin/effect"
|
|
17
|
+
import { daemonPaths } from "./daemon/shared.js"
|
|
18
|
+
import { ensureDaemon, hasRegistryEntries, serverTarget, type DaemonClient } from "./core/daemon-client.js"
|
|
19
|
+
import type { ServerEndpoint } from "./core/server-endpoint.js"
|
|
20
|
+
|
|
21
|
+
interface EndpointsInput {
|
|
22
|
+
readonly version: string
|
|
23
|
+
/** Del módulo events (null si está apagado: sin events, un webhook no despierta a nadie). */
|
|
24
|
+
readonly endpoint: (() => ServerEndpoint) | null
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type Args = Record<string, unknown>
|
|
28
|
+
type ToolContext = { sessionID?: string }
|
|
29
|
+
|
|
30
|
+
const PROVISIONING_HINT =
|
|
31
|
+
"The device tunnel is being created (first time only, about a minute while its certificate is issued). " +
|
|
32
|
+
"Call the list action shortly to get the URL."
|
|
33
|
+
|
|
34
|
+
function str(value: unknown): string | undefined {
|
|
35
|
+
return typeof value === "string" && value.length > 0 ? value : undefined
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function withHint<T extends { url?: string | null; tunnel?: { state?: string; lastError?: string | null } }>(result: T) {
|
|
39
|
+
if (result.url) return result
|
|
40
|
+
const state = result.tunnel?.state
|
|
41
|
+
return {
|
|
42
|
+
...result,
|
|
43
|
+
hint:
|
|
44
|
+
state === "error"
|
|
45
|
+
? `Tunnel error: ${result.tunnel?.lastError ?? "unknown"}. It retries by itself; check apex_daemon status.`
|
|
46
|
+
: PROVISIONING_HINT,
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function register(ctx: Plugin.Context, input: EndpointsInput): Effect.Effect<void, never, Scope.Scope> {
|
|
51
|
+
return Effect.gen(function* () {
|
|
52
|
+
const directory = ctx.location.directory
|
|
53
|
+
const paths = daemonPaths()
|
|
54
|
+
|
|
55
|
+
/** Daemon vivo + el servidor de este proyecto al día (su URL cambia al reiniciar). */
|
|
56
|
+
const daemon = async (spawn = true): Promise<DaemonClient> => {
|
|
57
|
+
const client = await ensureDaemon({ version: input.version, spawn, paths })
|
|
58
|
+
if (!client) throw new Error("apex daemon is not running")
|
|
59
|
+
const target = input.endpoint ? serverTarget(input.endpoint()) : null
|
|
60
|
+
if (target) await client.request("POST", "/v1/server", { directory, target }).catch(() => undefined)
|
|
61
|
+
return client
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Al cargar: si hay endpoints que mantener (p. ej. tras reiniciar el equipo), que el
|
|
65
|
+
// daemon esté vivo. Sin registro no se lanza nada.
|
|
66
|
+
if (hasRegistryEntries(paths)) {
|
|
67
|
+
yield* Effect.promise(() =>
|
|
68
|
+
daemon().catch((error) => console.warn(`[apex.endpoints] daemon: ${String((error as Error).message ?? error)}`)),
|
|
69
|
+
)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const tool = (definition: {
|
|
73
|
+
name: string
|
|
74
|
+
description: string
|
|
75
|
+
properties: Record<string, unknown>
|
|
76
|
+
required?: string[]
|
|
77
|
+
run: (args: Args, toolCtx: ToolContext) => Promise<unknown>
|
|
78
|
+
}) =>
|
|
79
|
+
ctx.tool.transform((editor) => {
|
|
80
|
+
editor.add({
|
|
81
|
+
name: definition.name,
|
|
82
|
+
description: definition.description,
|
|
83
|
+
input: {
|
|
84
|
+
type: "object",
|
|
85
|
+
properties: definition.properties,
|
|
86
|
+
...(definition.required ? { required: definition.required } : {}),
|
|
87
|
+
additionalProperties: false,
|
|
88
|
+
},
|
|
89
|
+
output: { type: "object", additionalProperties: true },
|
|
90
|
+
execute: (raw: unknown, toolCtx: ToolContext) =>
|
|
91
|
+
Effect.promise(async () => {
|
|
92
|
+
try {
|
|
93
|
+
return { output: (await definition.run((raw ?? {}) as Args, toolCtx ?? {})) as Record<string, unknown> }
|
|
94
|
+
} catch (error) {
|
|
95
|
+
return { output: { ok: false, error: String((error as Error).message ?? error) } }
|
|
96
|
+
}
|
|
97
|
+
}),
|
|
98
|
+
} as never)
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
const ttl = {
|
|
102
|
+
type: "number",
|
|
103
|
+
description: "Minutes until it is removed automatically (omit or 0 = permanent). Use one for anything temporary",
|
|
104
|
+
}
|
|
105
|
+
const owner = (args: Args, toolCtx: ToolContext) => ({
|
|
106
|
+
directory,
|
|
107
|
+
sessionID: toolCtx.sessionID ?? null,
|
|
108
|
+
ttlMinutes: args.ttlMinutes,
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
yield* tool({
|
|
112
|
+
name: "apex_tunnel",
|
|
113
|
+
description:
|
|
114
|
+
"Publish a local port on a public HTTPS URL through OpenTunnel (same device tunnel as OpenCode remote " +
|
|
115
|
+
"access, own route). open → {id, url}; list; close {id}. Anyone with the URL reaches the port: the app " +
|
|
116
|
+
"behind it MUST authenticate requests. Never publish the OpenCode server port.",
|
|
117
|
+
properties: {
|
|
118
|
+
action: { type: "string", enum: ["open", "list", "close"] },
|
|
119
|
+
port: { type: "number", description: "open: local port" },
|
|
120
|
+
host: { type: "string", description: "open: local host (default 127.0.0.1)" },
|
|
121
|
+
name: { type: "string", description: "open: readable route name (default random, unguessable)" },
|
|
122
|
+
proxyProtocol: { type: "string", enum: ["v1", "v2"], description: "open: send a PROXY header (only if the app expects it)" },
|
|
123
|
+
ttlMinutes: ttl,
|
|
124
|
+
id: { type: "string", description: "close: tunnel id or route name" },
|
|
125
|
+
},
|
|
126
|
+
required: ["action"],
|
|
127
|
+
run: async (args, toolCtx) => {
|
|
128
|
+
const client = await daemon()
|
|
129
|
+
if (args.action === "list") {
|
|
130
|
+
const state = await client.request<{ tunnel: unknown; tunnels: unknown[] }>("GET", "/v1/state")
|
|
131
|
+
return { tunnel: state.tunnel, tunnels: state.tunnels }
|
|
132
|
+
}
|
|
133
|
+
if (args.action === "close") return client.request("DELETE", `/v1/tunnels/${encodeURIComponent(String(args.id ?? ""))}`)
|
|
134
|
+
const server = input.endpoint?.().baseUrl
|
|
135
|
+
if (server && Number(new URL(server).port) === Number(args.port))
|
|
136
|
+
throw new Error("that is the OpenCode server port: use OpenCode remote access (opencode service set remote true) instead")
|
|
137
|
+
const opened = await client.request<{ url?: string | null; tunnel?: { state?: string } }>("POST", "/v1/tunnels", {
|
|
138
|
+
...owner(args, toolCtx),
|
|
139
|
+
port: args.port,
|
|
140
|
+
host: str(args.host),
|
|
141
|
+
name: str(args.name),
|
|
142
|
+
proxyProtocol: args.proxyProtocol,
|
|
143
|
+
})
|
|
144
|
+
return withHint(opened)
|
|
145
|
+
},
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
yield* tool({
|
|
149
|
+
name: "apex_webhook",
|
|
150
|
+
description:
|
|
151
|
+
"Create a public webhook URL that verifies each call (github, stripe, slack, generic hmac or token) and " +
|
|
152
|
+
"then wakes this project's agents through events.ingest locally (the server password never leaves the " +
|
|
153
|
+
"machine). Pair it with apex_subscribe (filter source). create → {url, secretFile}; list; delete {id}.",
|
|
154
|
+
properties: {
|
|
155
|
+
action: { type: "string", enum: ["create", "list", "delete"] },
|
|
156
|
+
name: { type: "string", description: "create: unique name (also prefixes event IDs)" },
|
|
157
|
+
provider: {
|
|
158
|
+
type: "string",
|
|
159
|
+
enum: ["github", "stripe", "slack", "hmac", "token"],
|
|
160
|
+
description:
|
|
161
|
+
"create: github (X-Hub-Signature-256), stripe (Stripe-Signature, needs its whsec_ secret), slack " +
|
|
162
|
+
"(signing secret), hmac (HMAC-SHA256 of the body in a header), token (Bearer / X-Apex-Token / ?token=)",
|
|
163
|
+
},
|
|
164
|
+
secret: { type: "string", description: "create: secret the sender gives you (stripe, slack). Omit to generate one" },
|
|
165
|
+
header: { type: "string", description: "create, hmac: signature header (default X-Signature)" },
|
|
166
|
+
encoding: { type: "string", enum: ["hex", "base64"], description: "create, hmac: signature encoding (default hex)" },
|
|
167
|
+
source: { type: "string", description: "create: events.ingest source (default the provider)" },
|
|
168
|
+
ttlMinutes: ttl,
|
|
169
|
+
id: { type: "string", description: "delete: webhook id or name" },
|
|
170
|
+
},
|
|
171
|
+
required: ["action"],
|
|
172
|
+
run: async (args, toolCtx) => {
|
|
173
|
+
const client = await daemon()
|
|
174
|
+
if (args.action === "list") return { webhooks: (await client.request<{ webhooks: unknown[] }>("GET", "/v1/state")).webhooks }
|
|
175
|
+
if (args.action === "delete") return client.request("DELETE", `/v1/webhooks/${encodeURIComponent(String(args.id ?? ""))}`)
|
|
176
|
+
if (!input.endpoint) throw new Error("the events module is off (modules.events): a webhook would wake nobody")
|
|
177
|
+
if (!input.endpoint().baseUrl) throw new Error("OpenCode server URL unknown: set events.server.url in the apex config")
|
|
178
|
+
const hook = await client.request<{ url?: string | null; secretFile: string; source: string; provider: string }>(
|
|
179
|
+
"POST",
|
|
180
|
+
"/v1/webhooks",
|
|
181
|
+
{
|
|
182
|
+
...owner(args, toolCtx),
|
|
183
|
+
name: args.name,
|
|
184
|
+
provider: args.provider,
|
|
185
|
+
secret: str(args.secret),
|
|
186
|
+
header: str(args.header),
|
|
187
|
+
encoding: args.encoding,
|
|
188
|
+
source: str(args.source),
|
|
189
|
+
},
|
|
190
|
+
)
|
|
191
|
+
return withHint({
|
|
192
|
+
...hook,
|
|
193
|
+
secretShell: `cat '${hook.secretFile}'`,
|
|
194
|
+
next:
|
|
195
|
+
`Configure the sender with this URL and the secret read from secretFile at run time (never paste it in ` +
|
|
196
|
+
`the chat). Then apex_subscribe with filter {field:"source", operator:"equals", value:"${hook.source}"}.`,
|
|
197
|
+
})
|
|
198
|
+
},
|
|
199
|
+
})
|
|
200
|
+
|
|
201
|
+
yield* tool({
|
|
202
|
+
name: "apex_daemon",
|
|
203
|
+
description:
|
|
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).",
|
|
206
|
+
properties: {
|
|
207
|
+
action: { type: "string", enum: ["status", "stop"] },
|
|
208
|
+
},
|
|
209
|
+
required: ["action"],
|
|
210
|
+
run: async (args) => {
|
|
211
|
+
const client = await daemon(args.action !== "stop")
|
|
212
|
+
if (args.action === "stop") {
|
|
213
|
+
await client.request("POST", "/v1/shutdown", {}).catch(() => undefined)
|
|
214
|
+
return { stopped: true }
|
|
215
|
+
}
|
|
216
|
+
const state = await client.request("GET", "/v1/state")
|
|
217
|
+
return { ...state, log: paths.log, home: paths.home }
|
|
218
|
+
},
|
|
219
|
+
})
|
|
220
|
+
})
|
|
221
|
+
}
|
package/index.ts
CHANGED
|
@@ -9,6 +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 and verified webhooks, kept by a per-user apex daemon
|
|
13
|
+
* that outlives the plugin (daemon/main.ts)
|
|
12
14
|
*
|
|
13
15
|
* Built on the official Effect plugin API: https://opencode.ai/v2/docs/build/plugins/effect/
|
|
14
16
|
*/
|
|
@@ -27,9 +29,10 @@ import { registerCentralRpc } from "./core/rpc.js"
|
|
|
27
29
|
import { registerSkills } from "./core/skills.js"
|
|
28
30
|
import { compatibilityWarnings } from "./core/compat.js"
|
|
29
31
|
import { registerTempAccess } from "./core/temp-access.js"
|
|
32
|
+
import { register as registerEndpoints } from "./endpoints.js"
|
|
30
33
|
|
|
31
34
|
// Plugin version
|
|
32
|
-
const VERSION = "0.
|
|
35
|
+
const VERSION = "0.5.0"
|
|
33
36
|
|
|
34
37
|
interface ModuleConfigs {
|
|
35
38
|
redact: RedactConfig & { enabled: boolean }
|
|
@@ -153,6 +156,11 @@ export default Plugin.define({
|
|
|
153
156
|
yield* registerAdvisor(ctx, moduleConfigs.advisor)
|
|
154
157
|
}
|
|
155
158
|
|
|
159
|
+
// Túneles y webhooks verificados, vía el daemon de apex.
|
|
160
|
+
if (validatedConfig.modules?.endpoints ?? true) {
|
|
161
|
+
yield* registerEndpoints(ctx, { version: VERSION, endpoint: events?.endpoint ?? null })
|
|
162
|
+
}
|
|
163
|
+
|
|
156
164
|
if (moduleConfigs.browser.enabled) {
|
|
157
165
|
yield* Effect.logWarning(
|
|
158
166
|
"[apex.browser] deprecated: use OpenCode's browse (https://opencode.ai/product/browse) to drive your browser; keep this module only for a headless or remote Chromium over CDP",
|
package/opencode-apex.jsonc
CHANGED
|
@@ -40,7 +40,9 @@
|
|
|
40
40
|
// Deprecated: use OpenCode's browse for your browser (docs/BROWSER.md)
|
|
41
41
|
"browser": false,
|
|
42
42
|
// external_directory without asking in <tmpdir>/opencode (OpenCode's temp dir)
|
|
43
|
-
"tempAccess": true
|
|
43
|
+
"tempAccess": true,
|
|
44
|
+
// Túneles OpenTunnel y webhooks verificados (daemon de apex, solo al usarlos)
|
|
45
|
+
"endpoints": true
|
|
44
46
|
},
|
|
45
47
|
|
|
46
48
|
|