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/endpoints.ts
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Apex Endpoints — el agente publica endpoints y levanta microservicios que reaccionan
|
|
3
|
+
* a llamadas externas, a 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_service: un microservicio supervisado, con ruta pública opcional (up/list/down/restart/logs)
|
|
8
|
+
* - apex_daemon: estado del daemon, autoarranque y parada
|
|
9
|
+
*
|
|
10
|
+
* El trabajo lo hace el daemon (un proceso por usuario, fuera del plugin, que OpenCode
|
|
11
|
+
* descarga tras 60 min). Aquí solo se habla con él y se le dice cómo llegar al servidor
|
|
12
|
+
* de este proyecto para los events.ingest de los webhooks.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { Effect } from "effect"
|
|
16
|
+
import type { Scope } from "effect"
|
|
17
|
+
import type { Plugin } from "@opencode/plugin/effect"
|
|
18
|
+
import { daemonPaths } from "./daemon/shared.js"
|
|
19
|
+
import { ensureDaemon, hasRegistryEntries, serverTarget, type DaemonClient } from "./core/daemon-client.js"
|
|
20
|
+
import { autostartStatus, setAutostart } from "./core/autostart.js"
|
|
21
|
+
import type { ServerEndpoint } from "./core/server-endpoint.js"
|
|
22
|
+
|
|
23
|
+
interface EndpointsInput {
|
|
24
|
+
readonly version: string
|
|
25
|
+
/** Del módulo events (null si está apagado: sin events, un webhook no despierta a nadie). */
|
|
26
|
+
readonly endpoint: (() => ServerEndpoint) | null
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
type Args = Record<string, unknown>
|
|
30
|
+
type ToolContext = { sessionID?: string }
|
|
31
|
+
|
|
32
|
+
const PROVISIONING_HINT =
|
|
33
|
+
"The device tunnel is being created (first time only, about a minute while its certificate is issued). " +
|
|
34
|
+
"Call the list action shortly to get the URL."
|
|
35
|
+
|
|
36
|
+
function str(value: unknown): string | undefined {
|
|
37
|
+
return typeof value === "string" && value.length > 0 ? value : undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function withHint<T extends { url?: string | null; tunnel?: { state?: string; lastError?: string | null } }>(result: T) {
|
|
41
|
+
if (result.url) return result
|
|
42
|
+
const state = result.tunnel?.state
|
|
43
|
+
return {
|
|
44
|
+
...result,
|
|
45
|
+
hint:
|
|
46
|
+
state === "error"
|
|
47
|
+
? `Tunnel error: ${result.tunnel?.lastError ?? "unknown"}. It retries by itself; check apex_daemon status.`
|
|
48
|
+
: PROVISIONING_HINT,
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function register(ctx: Plugin.Context, input: EndpointsInput): Effect.Effect<void, never, Scope.Scope> {
|
|
53
|
+
return Effect.gen(function* () {
|
|
54
|
+
const directory = ctx.location.directory
|
|
55
|
+
const paths = daemonPaths()
|
|
56
|
+
|
|
57
|
+
/** Daemon vivo + el servidor de este proyecto al día (su URL cambia al reiniciar). */
|
|
58
|
+
const daemon = async (spawn = true): Promise<DaemonClient> => {
|
|
59
|
+
const client = await ensureDaemon({ version: input.version, spawn, paths })
|
|
60
|
+
if (!client) throw new Error("apex daemon is not running")
|
|
61
|
+
const target = input.endpoint ? serverTarget(input.endpoint()) : null
|
|
62
|
+
if (target) await client.request("POST", "/v1/server", { directory, target }).catch(() => undefined)
|
|
63
|
+
return client
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Al cargar: si hay endpoints que mantener (p. ej. tras reiniciar el equipo), que el
|
|
67
|
+
// daemon esté vivo. Sin registro no se lanza nada.
|
|
68
|
+
if (hasRegistryEntries(paths)) {
|
|
69
|
+
yield* Effect.promise(() =>
|
|
70
|
+
daemon().catch((error) => console.warn(`[apex.endpoints] daemon: ${String((error as Error).message ?? error)}`)),
|
|
71
|
+
)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const tool = (definition: {
|
|
75
|
+
name: string
|
|
76
|
+
description: string
|
|
77
|
+
properties: Record<string, unknown>
|
|
78
|
+
required?: string[]
|
|
79
|
+
run: (args: Args, toolCtx: ToolContext) => Promise<unknown>
|
|
80
|
+
}) =>
|
|
81
|
+
ctx.tool.transform((editor) => {
|
|
82
|
+
editor.add({
|
|
83
|
+
name: definition.name,
|
|
84
|
+
description: definition.description,
|
|
85
|
+
input: {
|
|
86
|
+
type: "object",
|
|
87
|
+
properties: definition.properties,
|
|
88
|
+
...(definition.required ? { required: definition.required } : {}),
|
|
89
|
+
additionalProperties: false,
|
|
90
|
+
},
|
|
91
|
+
output: { type: "object", additionalProperties: true },
|
|
92
|
+
execute: (raw: unknown, toolCtx: ToolContext) =>
|
|
93
|
+
Effect.promise(async () => {
|
|
94
|
+
try {
|
|
95
|
+
return { output: (await definition.run((raw ?? {}) as Args, toolCtx ?? {})) as Record<string, unknown> }
|
|
96
|
+
} catch (error) {
|
|
97
|
+
return { output: { ok: false, error: String((error as Error).message ?? error) } }
|
|
98
|
+
}
|
|
99
|
+
}),
|
|
100
|
+
} as never)
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
const ttl = {
|
|
104
|
+
type: "number",
|
|
105
|
+
description: "Minutes until it is removed automatically (omit or 0 = permanent). Use one for anything temporary",
|
|
106
|
+
}
|
|
107
|
+
const owner = (args: Args, toolCtx: ToolContext) => ({
|
|
108
|
+
directory,
|
|
109
|
+
sessionID: toolCtx.sessionID ?? null,
|
|
110
|
+
ttlMinutes: args.ttlMinutes,
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
yield* tool({
|
|
114
|
+
name: "apex_tunnel",
|
|
115
|
+
description:
|
|
116
|
+
"Publish a local port on a public HTTPS URL through OpenTunnel (same device tunnel as OpenCode remote " +
|
|
117
|
+
"access, own route). open → {id, url}; list; close {id}. Anyone with the URL reaches the port: the app " +
|
|
118
|
+
"behind it MUST authenticate requests. Never publish the OpenCode server port.",
|
|
119
|
+
properties: {
|
|
120
|
+
action: { type: "string", enum: ["open", "list", "close"] },
|
|
121
|
+
port: { type: "number", description: "open: local port" },
|
|
122
|
+
host: { type: "string", description: "open: local host (default 127.0.0.1)" },
|
|
123
|
+
name: { type: "string", description: "open: readable route name (default random, unguessable)" },
|
|
124
|
+
proxyProtocol: { type: "string", enum: ["v1", "v2"], description: "open: send a PROXY header (only if the app expects it)" },
|
|
125
|
+
ttlMinutes: ttl,
|
|
126
|
+
id: { type: "string", description: "close: tunnel id or route name" },
|
|
127
|
+
},
|
|
128
|
+
required: ["action"],
|
|
129
|
+
run: async (args, toolCtx) => {
|
|
130
|
+
const client = await daemon()
|
|
131
|
+
if (args.action === "list") {
|
|
132
|
+
const state = await client.request<{ tunnel: unknown; tunnels: unknown[] }>("GET", "/v1/state")
|
|
133
|
+
return { tunnel: state.tunnel, tunnels: state.tunnels }
|
|
134
|
+
}
|
|
135
|
+
if (args.action === "close") return client.request("DELETE", `/v1/tunnels/${encodeURIComponent(String(args.id ?? ""))}`)
|
|
136
|
+
const server = input.endpoint?.().baseUrl
|
|
137
|
+
if (server && Number(new URL(server).port) === Number(args.port))
|
|
138
|
+
throw new Error("that is the OpenCode server port: use OpenCode remote access (opencode service set remote true) instead")
|
|
139
|
+
const opened = await client.request<{ url?: string | null; tunnel?: { state?: string } }>("POST", "/v1/tunnels", {
|
|
140
|
+
...owner(args, toolCtx),
|
|
141
|
+
port: args.port,
|
|
142
|
+
host: str(args.host),
|
|
143
|
+
name: str(args.name),
|
|
144
|
+
proxyProtocol: args.proxyProtocol,
|
|
145
|
+
})
|
|
146
|
+
return withHint(opened)
|
|
147
|
+
},
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
yield* tool({
|
|
151
|
+
name: "apex_webhook",
|
|
152
|
+
description:
|
|
153
|
+
"Create a public webhook URL that verifies each call (github, stripe, slack, generic hmac or token) and " +
|
|
154
|
+
"then wakes this project's agents through events.ingest locally (the server password never leaves the " +
|
|
155
|
+
"machine). Pair it with apex_subscribe (filter source). create → {url, secretFile}; list; delete {id}.",
|
|
156
|
+
properties: {
|
|
157
|
+
action: { type: "string", enum: ["create", "list", "delete"] },
|
|
158
|
+
name: { type: "string", description: "create: unique name (also prefixes event IDs)" },
|
|
159
|
+
provider: {
|
|
160
|
+
type: "string",
|
|
161
|
+
enum: ["github", "stripe", "slack", "hmac", "token"],
|
|
162
|
+
description:
|
|
163
|
+
"create: github (X-Hub-Signature-256), stripe (Stripe-Signature, needs its whsec_ secret), slack " +
|
|
164
|
+
"(signing secret), hmac (HMAC-SHA256 of the body in a header), token (Bearer / X-Apex-Token / ?token=)",
|
|
165
|
+
},
|
|
166
|
+
secret: { type: "string", description: "create: secret the sender gives you (stripe, slack). Omit to generate one" },
|
|
167
|
+
header: { type: "string", description: "create, hmac: signature header (default X-Signature)" },
|
|
168
|
+
encoding: { type: "string", enum: ["hex", "base64"], description: "create, hmac: signature encoding (default hex)" },
|
|
169
|
+
source: { type: "string", description: "create: events.ingest source (default the provider)" },
|
|
170
|
+
ttlMinutes: ttl,
|
|
171
|
+
id: { type: "string", description: "delete: webhook id or name" },
|
|
172
|
+
},
|
|
173
|
+
required: ["action"],
|
|
174
|
+
run: async (args, toolCtx) => {
|
|
175
|
+
const client = await daemon()
|
|
176
|
+
if (args.action === "list") return { webhooks: (await client.request<{ webhooks: unknown[] }>("GET", "/v1/state")).webhooks }
|
|
177
|
+
if (args.action === "delete") return client.request("DELETE", `/v1/webhooks/${encodeURIComponent(String(args.id ?? ""))}`)
|
|
178
|
+
if (!input.endpoint) throw new Error("the events module is off (modules.events): a webhook would wake nobody")
|
|
179
|
+
if (!input.endpoint().baseUrl) throw new Error("OpenCode server URL unknown: set events.server.url in the apex config")
|
|
180
|
+
const hook = await client.request<{ url?: string | null; secretFile: string; source: string; provider: string }>(
|
|
181
|
+
"POST",
|
|
182
|
+
"/v1/webhooks",
|
|
183
|
+
{
|
|
184
|
+
...owner(args, toolCtx),
|
|
185
|
+
name: args.name,
|
|
186
|
+
provider: args.provider,
|
|
187
|
+
secret: str(args.secret),
|
|
188
|
+
header: str(args.header),
|
|
189
|
+
encoding: args.encoding,
|
|
190
|
+
source: str(args.source),
|
|
191
|
+
},
|
|
192
|
+
)
|
|
193
|
+
return withHint({
|
|
194
|
+
...hook,
|
|
195
|
+
secretShell: `cat '${hook.secretFile}'`,
|
|
196
|
+
next:
|
|
197
|
+
`Configure the sender with this URL and the secret read from secretFile at run time (never paste it in ` +
|
|
198
|
+
`the chat). Then apex_subscribe with filter {field:"source", operator:"equals", value:"${hook.source}"}.`,
|
|
199
|
+
})
|
|
200
|
+
},
|
|
201
|
+
})
|
|
202
|
+
|
|
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
|
+
yield* tool({
|
|
256
|
+
name: "apex_daemon",
|
|
257
|
+
description:
|
|
258
|
+
"The apex daemon that keeps tunnels, webhooks and services alive: status (tunnel, everything it keeps, " +
|
|
259
|
+
"log file), autostart {enabled} after a reboot (cron @reboot / Windows logon task; off by default), stop.",
|
|
260
|
+
properties: {
|
|
261
|
+
action: { type: "string", enum: ["status", "autostart", "stop"] },
|
|
262
|
+
enabled: { type: "boolean", description: "autostart: on or off" },
|
|
263
|
+
},
|
|
264
|
+
required: ["action"],
|
|
265
|
+
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
|
+
const client = await daemon(args.action !== "stop")
|
|
271
|
+
if (args.action === "stop") {
|
|
272
|
+
await client.request("POST", "/v1/shutdown", {}).catch(() => undefined)
|
|
273
|
+
return { stopped: true, note: "services keep running; the next apex tool call or plugin load restarts the daemon" }
|
|
274
|
+
}
|
|
275
|
+
const state = await client.request("GET", "/v1/state")
|
|
276
|
+
let autostart: unknown
|
|
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 }
|
|
283
|
+
},
|
|
284
|
+
})
|
|
285
|
+
})
|
|
286
|
+
}
|
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, verified webhooks and supervised microservices, kept
|
|
13
|
+
* by a per-user apex daemon 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.4.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, webhooks verificados y microservicios, 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, webhooks verificados y microservicios (daemon de apex, solo al usarlos)
|
|
45
|
+
"endpoints": true
|
|
44
46
|
},
|
|
45
47
|
|
|
46
48
|
|
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, tools.run, AI permission advisor, guard meta-permissions, temp-directory access
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Modular plugin for OpenCode V2 (>= 2.1): secret redaction, RPC callbacks/webhooks/watchers that wake agents, OpenTunnel endpoints + verified webhooks + supervised microservices (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": {
|
|
@@ -25,7 +25,10 @@
|
|
|
25
25
|
"automation",
|
|
26
26
|
"permissions",
|
|
27
27
|
"cdp",
|
|
28
|
-
"browser"
|
|
28
|
+
"browser",
|
|
29
|
+
"opentunnel",
|
|
30
|
+
"tunnel",
|
|
31
|
+
"microservices"
|
|
29
32
|
],
|
|
30
33
|
"engines": {
|
|
31
34
|
"opencode": ">=2.1.0"
|
|
@@ -36,6 +39,8 @@
|
|
|
36
39
|
"index.ts",
|
|
37
40
|
"redact.ts",
|
|
38
41
|
"events.ts",
|
|
42
|
+
"daemon",
|
|
43
|
+
"endpoints.ts",
|
|
39
44
|
"advisor.ts",
|
|
40
45
|
"guard.ts",
|
|
41
46
|
"browser.ts",
|
|
@@ -50,6 +55,7 @@
|
|
|
50
55
|
"dependencies": {
|
|
51
56
|
"@opencode/plugin": "^2.1.1",
|
|
52
57
|
"@opencode/plugin-browser": "^2.1.1",
|
|
58
|
+
"@opentunnel/client": "^0.7.0",
|
|
53
59
|
"jsonc-parser": "^3.3.1",
|
|
54
60
|
"ws": "^8.22.0",
|
|
55
61
|
"zod": "^3.24.0"
|
|
@@ -59,7 +65,7 @@
|
|
|
59
65
|
"bun-types": "^1.1.0"
|
|
60
66
|
},
|
|
61
67
|
"scripts": {
|
|
62
|
-
"test": "bun test/events.test.ts && bun test/guard.test.ts && bun test/process-context.test.ts && bun test/temp-access.test.ts",
|
|
68
|
+
"test": "bun test/events.test.ts && bun test/guard.test.ts && bun test/process-context.test.ts && bun test/temp-access.test.ts && bun test/endpoints.test.ts",
|
|
63
69
|
"typecheck": "tsc --noEmit -p .",
|
|
64
70
|
"check:install": "node scripts/check-install.mjs",
|
|
65
71
|
"prepublishOnly": "npm test && npm run typecheck && npm run check:install"
|
|
@@ -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.
|
|
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, and **`apex_service`** to keep it running. Skill **`apex-endpoints`** covers all three. 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,7 +140,11 @@ 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.
|
|
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`**.
|
|
144
148
|
|
|
145
149
|
## Before you call it done
|
|
146
150
|
|
|
@@ -178,3 +182,4 @@ All of them: `POST <baseUrl>/api/rpc/apex/<method>?location[directory]=<project>
|
|
|
178
182
|
| `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 |
|
|
179
183
|
| `references/run-anywhere.md` | Keeping a relay or watcher alive on Linux, macOS, Windows, Docker, pm2, and removing it |
|
|
180
184
|
| `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` / `apex_service` / `apex_daemon`: public URLs, verified webhooks and supervised microservices without writing a relay or units |
|
|
@@ -35,7 +35,9 @@ Look for it before reaching for a tunnel:
|
|
|
35
35
|
|
|
36
36
|
The tunnel client connects **out** to the provider. The provider gives you a public HTTPS URL that forwards to a local port. Point it at **the relay's port**, never at the OpenCode server.
|
|
37
37
|
|
|
38
|
-
**OpenTunnel (first choice)**: by Anomaly, the makers of OpenCode. No account. TLS ends on your machine, so the relay server cannot read the traffic.
|
|
38
|
+
**OpenTunnel (first choice)**: by Anomaly, the makers of OpenCode. No account. TLS ends on your machine, so the relay server cannot read the traffic.
|
|
39
|
+
|
|
40
|
+
**With apex you do not need the CLI.** `apex_tunnel({action:"open", port})` publishes a port. `apex_webhook` gives a verified webhook URL with no relay code. Both work on Linux, macOS and Windows, live in the apex daemon and accept a TTL (skill `apex-endpoints`). The CLI below is for machines without apex. It ships prebuilt for Linux and macOS.
|
|
39
41
|
- Install: `curl -fsSL https://opentunnel.xyz/install | sh`, `brew install anomalyco/tap/opentunnel`, or `npm install -g opentunnel`.
|
|
40
42
|
- Publish the relay:
|
|
41
43
|
```sh
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: apex-endpoints
|
|
3
|
+
description: Expose things to the Internet and keep them running with opencode-apex, on any OS, without systemd, launchd or a tunnel CLI. Use it when the agent must receive a webhook (GitHub, Stripe, Slack, n8n, any HMAC or token sender), publish a local port on a public HTTPS URL (temporary for a demo or test, or permanent), or write and run its own microservice or API that reacts to external calls and wakes agents. Tools apex_webhook, apex_tunnel, apex_service and apex_daemon, all through OpenTunnel (the makers of OpenCode) and the apex daemon.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Public endpoints and microservices (apex daemon + OpenTunnel)
|
|
7
|
+
|
|
8
|
+
## The model
|
|
9
|
+
|
|
10
|
+
```
|
|
11
|
+
Internet ──HTTPS──▶ OpenTunnel ──▶ apex daemon (one per user, outside OpenCode)
|
|
12
|
+
<route>.<id>.opentunnel.xyz ├─ webhook receiver: verify signature → events.ingest (local) → subscription → agent
|
|
13
|
+
├─ route → your microservice (127.0.0.1:PORT) ─ APEX_INGEST_URL ─▶ agent
|
|
14
|
+
└─ route → any local port
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
- **The apex daemon** keeps everything alive. It is one process per user, launched by the plugin with OpenCode's own binary. It survives the 60-minute plugin unload and OpenCode restarts, and works with any init system and on Windows. It starts on the first tool call. With nothing left to keep, it exits after 10 minutes.
|
|
18
|
+
- **OpenTunnel:** the daemon adds its **own routes** to this device's tunnel, the same one OpenCode remote access uses. Routes are cheap: new tunnels are limited to about 30 per hour per IP, routes are not. TLS ends on this machine.
|
|
19
|
+
- **Every entry** (webhook, tunnel, service) belongs to this project. It is either **temporary** (`ttlMinutes`) or **permanent** (no TTL), and the daemon removes temporary ones on time, even if OpenCode is closed.
|
|
20
|
+
|
|
21
|
+
## Pick the tool
|
|
22
|
+
|
|
23
|
+
| You need | Use |
|
|
24
|
+
| --- | --- |
|
|
25
|
+
| A service (GitHub, Stripe, Slack, n8n, a form…) must call in and wake an agent | **`apex_webhook`**: no code at all |
|
|
26
|
+
| An API or microservice you write, running in the background | **`apex_service`** (`public: true` to give it a URL) |
|
|
27
|
+
| A port you already started (dev server, demo, test) on a public URL | **`apex_tunnel`** |
|
|
28
|
+
| 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
|
+
|
|
30
|
+
Prefer a source's **outbound** mode (WebSocket, polling…) when it has one. Nothing is exposed then (skill `apex-callbacks`).
|
|
31
|
+
|
|
32
|
+
## Webhooks: `apex_webhook`
|
|
33
|
+
|
|
34
|
+
1. **Subscribe first**, so the first event lands somewhere: `apex_subscribe` with filters on `source` (and `type`), and a template that says the payload is third-party data.
|
|
35
|
+
2. **Create:**
|
|
36
|
+
```jsonc
|
|
37
|
+
apex_webhook({ "action": "create", "name": "gh-acme-api", "provider": "github", "ttlMinutes": 0 })
|
|
38
|
+
// → { url, secretFile, secretShell: "cat '<file>'", source: "github", route, next }
|
|
39
|
+
```
|
|
40
|
+
- `provider`:
|
|
41
|
+
- `github`: `X-Hub-Signature-256`.
|
|
42
|
+
- `stripe`: `Stripe-Signature`, with a 5-minute replay window. Pass its `whsec_…` as `secret`.
|
|
43
|
+
- `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`); a `sha256=` prefix is accepted.
|
|
45
|
+
- `token`: `Authorization: Bearer`, `X-Apex-Token` or `?token=`. Use it for senders that cannot sign (n8n, curl, IFTTT).
|
|
46
|
+
- Without `secret`, a random one is generated. **It is never returned**: only `secretFile` (`0600`). Configure the sender by reading the file at run time, for example `gh api repos/OWNER/REPO/hooks -f config[url]=<url> -f config[secret]="$(cat '<secretFile>')" -f config[content_type]=json -f 'events[]=pull_request'`. Never paste the secret in the chat.
|
|
47
|
+
3. **What the agent receives:**
|
|
48
|
+
- `source`: the provider, or your `source`.
|
|
49
|
+
- `type`, by provider:
|
|
50
|
+
- GitHub: `pull_request.opened`.
|
|
51
|
+
- Stripe: `invoice.paid`.
|
|
52
|
+
- Slack: the event type.
|
|
53
|
+
- hmac and token: `X-Event-Type`, else `payload.type`.
|
|
54
|
+
- `eventID`: `<name>:<delivery id>`. A redelivery is not delivered twice.
|
|
55
|
+
- `payload`: the parsed body, plus `_webhook: {name, provider, headers}`. Signatures and tokens are left out of `headers`.
|
|
56
|
+
4. **Replies to the sender:**
|
|
57
|
+
- `202`: verified and delivered.
|
|
58
|
+
- `401`: bad or missing signature. Nothing is delivered.
|
|
59
|
+
- `503`: OpenCode is down. Stripe and Slack retry; GitHub shows the failure under "Recent deliveries".
|
|
60
|
+
5. **Check:** `apex_webhook({action:"list"})` shows `stats` (`ok` / `rejected` / `failed`, `lastError`). Send one real test delivery and watch the agent wake up.
|
|
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.
|
|
86
|
+
|
|
87
|
+
## Ports: `apex_tunnel`
|
|
88
|
+
|
|
89
|
+
```jsonc
|
|
90
|
+
apex_tunnel({ "action": "open", "port": 5173, "ttlMinutes": 30 }) // → { id, route, url }
|
|
91
|
+
apex_tunnel({ "action": "open", "port": 3000, "name": "demo" }) // https://demo.<id>.opentunnel.xyz, permanent
|
|
92
|
+
apex_tunnel({ "action": "list" }) · apex_tunnel({ "action": "close", "id": "<id or route>" })
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
- 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. Set it only if the app expects a PROXY header.
|
|
97
|
+
- The OpenCode server port is refused: that is what remote access is for.
|
|
98
|
+
|
|
99
|
+
## Temporary or permanent
|
|
100
|
+
|
|
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: a webhook loses its URL and secret file, a service is stopped.
|
|
102
|
+
- **Permanent:** omit `ttlMinutes` only when the user wants it to stay. Then tell them how to remove it (`down`, `delete`, `close`).
|
|
103
|
+
- **After a reboot,** the daemon comes back when apex loads in any project. To bring it back at boot without that, run `apex_daemon({action:"autostart", enabled:true})` once. It uses `cron @reboot` on Linux, macOS and BSD (any init system: systemd, sysvinit, antiX…) and a logon task on Windows. Ask the user before turning it on.
|
|
104
|
+
- The URL stays the same while the device tunnel exists, so the entry keeps its URL across restarts.
|
|
105
|
+
|
|
106
|
+
## When it is not reachable
|
|
107
|
+
|
|
108
|
+
`apex_daemon({action:"status"})` returns:
|
|
109
|
+
- `tunnel.state`:
|
|
110
|
+
- `connected`: everything is fine.
|
|
111
|
+
- `provisioning`: first tunnel on this device; the certificate takes about 1 minute, then `url` appears in `list`.
|
|
112
|
+
- `reconnecting`: the network dropped; it retries on its own.
|
|
113
|
+
- `error`: read `lastError`.
|
|
114
|
+
- the entries the daemon keeps, the `log` file, and `autostart`.
|
|
115
|
+
|
|
116
|
+
Corporate proxy or custom CA:
|
|
117
|
+
- the daemon honours `HTTPS_PROXY` / `NO_PROXY` and `OPENTUNNEL_CA_CERT`;
|
|
118
|
+
- a SOCKS proxy is not supported;
|
|
119
|
+
- for a self-hosted OpenTunnel server, set `OPENTUNNEL_API` in OpenCode's environment, then `apex_daemon({action:"stop"})` so it restarts with it.
|
|
120
|
+
|
|
121
|
+
## Before you call it done
|
|
122
|
+
|
|
123
|
+
1. One real request through the public `url`: an actual delivery for a webhook, `curl -i <url>` with credentials for a service.
|
|
124
|
+
2. A **bad** request is refused (wrong signature or token: `401`).
|
|
125
|
+
3. Tell the user:
|
|
126
|
+
- the URL and what it reaches;
|
|
127
|
+
- temporary (until when) or permanent;
|
|
128
|
+
- where the logs are;
|
|
129
|
+
- how to remove it;
|
|
130
|
+
- the subscription id, if any.
|