opencode-apex 0.2.6 → 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 +50 -0
- package/README.md +15 -6
- package/core/autostart.ts +67 -0
- package/core/config.ts +3 -1
- 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/BROWSER.md +14 -2
- package/docs/CONFIG.md +4 -2
- package/docs/ENDPOINTS.md +87 -0
- package/docs/TROUBLESHOOTING.md +5 -2
- package/endpoints.ts +286 -0
- package/index.ts +19 -4
- package/opencode-apex.jsonc +6 -3
- 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/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,56 @@ All notable changes to `opencode-apex`. Format based on
|
|
|
5
5
|
|
|
6
6
|
## [Unreleased]
|
|
7
7
|
|
|
8
|
+
## [0.4.0] — 2026-11-25
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`endpoints` module (on by default): public URLs, verified webhooks and supervised
|
|
13
|
+
microservices.** Four tools:
|
|
14
|
+
- `apex_webhook` creates a webhook URL that verifies GitHub, Stripe or Slack signatures,
|
|
15
|
+
a generic HMAC-SHA256 or a token, then calls `events.ingest` on loopback. Senders never
|
|
16
|
+
get the server password, and the agent writes no relay code.
|
|
17
|
+
- `apex_tunnel` publishes a local port on an OpenTunnel HTTPS URL.
|
|
18
|
+
- `apex_service` runs a microservice the agent wrote. It restarts with backoff, keeps
|
|
19
|
+
logs, can have a public URL, and wakes agents through a local ingest with its own token.
|
|
20
|
+
- `apex_daemon` reports status, turns autostart on or off, and stops the daemon.
|
|
21
|
+
|
|
22
|
+
Webhooks, tunnels and services can have a TTL, so they are temporary or permanent.
|
|
23
|
+
- **apex daemon.** One process per user keeps these alive, outside the plugin that OpenCode
|
|
24
|
+
unloads after 60 minutes.
|
|
25
|
+
- It runs on OpenCode's own executable in bun mode (`BUN_BE_BUN=1`), so it works on
|
|
26
|
+
Linux with any init system, on macOS and on Windows, without systemd, launchd or the
|
|
27
|
+
opentunnel CLI.
|
|
28
|
+
- A lockfile ensures there is only one.
|
|
29
|
+
- It uses `@opentunnel/client` on the device's `default` tunnel, alongside OpenCode
|
|
30
|
+
remote access, with its own routes.
|
|
31
|
+
- It applies TTLs even with OpenCode closed.
|
|
32
|
+
- A newer daemon adopts the services of the one it replaces instead of restarting them.
|
|
33
|
+
- It exits after 10 minutes with nothing to keep.
|
|
34
|
+
- **Optional autostart** after a reboot: a crontab `@reboot` line on Linux, macOS and BSD,
|
|
35
|
+
a logon task on Windows. Off by default.
|
|
36
|
+
- **New packaged skill `apex-endpoints`.** `apex-callbacks` now points to `apex_webhook`
|
|
37
|
+
and `apex_service` before hand-written relays and OS units. See
|
|
38
|
+
[docs/ENDPOINTS.md](docs/ENDPOINTS.md).
|
|
39
|
+
|
|
40
|
+
### Dependencies
|
|
41
|
+
|
|
42
|
+
- `@opentunnel/client` ^0.7.0. Its peer `effect` is the one `@opencode/plugin` already
|
|
43
|
+
brings.
|
|
44
|
+
|
|
45
|
+
## [0.3.0] — 2026-11-25
|
|
46
|
+
|
|
47
|
+
### Deprecated
|
|
48
|
+
|
|
49
|
+
- **The browser module is deprecated and now off by default.** OpenCode's own
|
|
50
|
+
[browse](https://opencode.ai/product/browse) (an MCP server plus a Chromium extension)
|
|
51
|
+
lets agents use your real browser: your tabs and logins, no remote debugging and no
|
|
52
|
+
consent prompt, handoffs for logins and 2FA, tab recordings. With both on, the agent
|
|
53
|
+
got two browser toolsets that overlapped. The module stays for what browse does not do:
|
|
54
|
+
serving OpenCode's `browser.*` tools from a headless or remote Chromium over CDP, and the
|
|
55
|
+
`browser.*` performance captures. Turn it back on with `"modules": { "browser": true }`;
|
|
56
|
+
it logs a deprecation warning. It may be removed in a later release.
|
|
57
|
+
|
|
8
58
|
## [0.2.6] — 2026-11-25
|
|
9
59
|
|
|
10
60
|
### Added
|
package/README.md
CHANGED
|
@@ -5,7 +5,9 @@
|
|
|
5
5
|
- event-driven automations (callbacks, webhooks, scheduled watchers that wake an agent up);
|
|
6
6
|
- AI-assisted permission decisions;
|
|
7
7
|
- per-agent meta-permissions;
|
|
8
|
-
-
|
|
8
|
+
- access to OpenCode's temporary directory without prompts;
|
|
9
|
+
- (deprecated) `browser.*` tools driven by a headless or remote Chromium over CDP. To let
|
|
10
|
+
agents use your own browser, use OpenCode's [browse](https://opencode.ai/product/browse).
|
|
9
11
|
|
|
10
12
|
> [!IMPORTANT]
|
|
11
13
|
> **OpenCode V2 only (OpenCode ≥ 2.1).** apex is written against the V2 plugin runtime
|
|
@@ -58,13 +60,14 @@ apex is one plugin with six independent modules. Each one can be switched on or
|
|
|
58
60
|
| **Events** | Lets programs outside OpenCode (scripts, cron jobs, webhooks, n8n…) notify an agent. **Subscriptions** decide which session receives what. `tools.run` lets those programs use OpenCode tools. | on | [docs/EVENTS.md](docs/EVENTS.md) |
|
|
59
61
|
| **Advisor** | When a tool call needs permission ("ask"), a small dedicated agent decides `allow` or `deny`, so you aren't asked about every step. For `kill`/`pkill` it is told whose process each target is (read from `/proc`). | on | [docs/ADVISOR.md](docs/ADVISOR.md) |
|
|
60
62
|
| **Guard** | Meta-permissions per agent, tool and path, with a report of what was attempted and decided. | **off** | [docs/GUARD.md](docs/GUARD.md) |
|
|
61
|
-
| **Browser** | Serves OpenCode's `browser.*` tools against an **external** Chromium over CDP
|
|
63
|
+
| **Browser** *(deprecated)* | Serves OpenCode's `browser.*` tools against an **external** Chromium over CDP. Superseded by OpenCode's [browse](https://opencode.ai/product/browse) for your own browser; kept for a headless or remote Chromium and for `browser.*` performance captures. | **off** | [docs/BROWSER.md](docs/BROWSER.md) |
|
|
62
64
|
| **Temp access** | Allows `external_directory` in OpenCode's temporary directory (`<tmpdir>/opencode`, `/tmp/opencode` on Linux) without asking. OpenCode tells the model to use it but no rule approves it. A deny you configure for that path still wins. | on | — |
|
|
65
|
+
| **Endpoints** | Public URLs through [OpenTunnel](https://opentunnel.xyz) (same device tunnel as OpenCode remote access, own routes), **verified webhooks** (GitHub, Stripe, Slack, HMAC, token) that wake agents without exposing the server password, and **supervised microservices** the agent writes. All with optional TTL, kept by a per-user apex daemon that outlives the plugin. Linux (any init), macOS, Windows; no systemd/launchd and no tunnel CLI. The daemon starts only when a tool is used. | on | [docs/ENDPOINTS.md](docs/ENDPOINTS.md) |
|
|
63
66
|
|
|
64
67
|
Turn modules on or off in `modules`. That is the only switch: there is no `<module>.enabled`.
|
|
65
68
|
|
|
66
69
|
```jsonc
|
|
67
|
-
"modules": { "redact": true, "events": true, "advisor": true, "guard": false, "browser": true }
|
|
70
|
+
"modules": { "redact": true, "events": true, "advisor": true, "guard": false, "browser": false, "tempAccess": true, "endpoints": true }
|
|
68
71
|
```
|
|
69
72
|
|
|
70
73
|
## Requirements
|
|
@@ -72,7 +75,9 @@ Turn modules on or off in `modules`. That is the only switch: there is no `<modu
|
|
|
72
75
|
- **OpenCode ≥ 2.1** (V2). Nothing else: OpenCode downloads the plugin and its dependencies
|
|
73
76
|
itself.
|
|
74
77
|
- For the automation examples, a shell with `curl` and `sed`.
|
|
75
|
-
- Optional:
|
|
78
|
+
- Optional: `bun` if you want to hack on apex. For browsers, OpenCode's
|
|
79
|
+
[browse](https://opencode.ai/product/browse); apex's deprecated Browser module needs a
|
|
80
|
+
Chromium with remote debugging.
|
|
76
81
|
|
|
77
82
|
## Install
|
|
78
83
|
|
|
@@ -87,7 +92,7 @@ Add apex to the `plugins` list of your OpenCode config:
|
|
|
87
92
|
{
|
|
88
93
|
"package": "opencode-apex",
|
|
89
94
|
"options": {
|
|
90
|
-
"modules": { "redact": true, "events": true, "advisor": true, "guard": false
|
|
95
|
+
"modules": { "redact": true, "events": true, "advisor": true, "guard": false }
|
|
91
96
|
}
|
|
92
97
|
}
|
|
93
98
|
]
|
|
@@ -236,9 +241,13 @@ curl -sS -u "opencode:$PW" -H 'content-type: application/json' \
|
|
|
236
241
|
| `apex_list_subscriptions` | events | Lists subscriptions; config ones are marked read-only |
|
|
237
242
|
| `apex_callback_endpoint` | events | How an external program reaches this server: URL, RPC URLs for this project, auth, curl examples |
|
|
238
243
|
| `apex_set_callback_url` | events | Sets or clears the server's public URL (tunnel / reverse proxy), for senders on other machines |
|
|
244
|
+
| `apex_webhook` | endpoints | Verified webhook URL (github, stripe, slack, hmac, token) that calls `events.ingest` locally: create / list / delete, TTL |
|
|
245
|
+
| `apex_tunnel` | endpoints | Publishes a local port on an OpenTunnel HTTPS URL: open / list / close, TTL |
|
|
246
|
+
| `apex_service` | endpoints | Supervised microservice (restart with backoff, logs, TTL, optional public URL, local ingest without the server password): up / list / down / restart / logs |
|
|
247
|
+
| `apex_daemon` | endpoints | Daemon status, autostart after reboot (cron `@reboot` / Windows logon task), stop |
|
|
239
248
|
| `apex_advisor_decide` | advisor | The advisor agent's only tool: `allow` / `deny` + reason |
|
|
240
249
|
| `apex_guard_report` | guard | Report of what each agent attempted and what was decided |
|
|
241
|
-
| `browser_target` | browser | Chooses which browser serves `browser.*`: `external` (CDP), `in-app` (desktop app) or `auto` |
|
|
250
|
+
| `browser_target` | browser (deprecated, off by default) | Chooses which browser serves `browser.*`: `external` (CDP), `in-app` (desktop app) or `auto` |
|
|
242
251
|
|
|
243
252
|
apex also registers two hidden agents: `apex-advisor` for the Advisor and `apex-runner`, the
|
|
244
253
|
technical session behind `tools.run`.
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Autoarranque del daemon tras reiniciar el equipo, sin systemd ni launchd:
|
|
3
|
+
* - Linux / macOS / BSD: una línea `@reboot` en el crontab del usuario (vale con
|
|
4
|
+
* cualquier init: systemd, sysvinit, runit, OpenRC…).
|
|
5
|
+
* - Windows: una tarea programada al iniciar sesión (`schtasks /SC ONLOGON`).
|
|
6
|
+
*
|
|
7
|
+
* Lo que se arranca es el lanzador (`launch.sh` / `launch.cmd`) que el plugin reescribe
|
|
8
|
+
* con las rutas actuales cada vez que lanza el daemon, así una actualización de OpenCode
|
|
9
|
+
* o de apex no deja el autoarranque apuntando a un binario que ya no existe.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { spawnSync } from "node:child_process"
|
|
13
|
+
import { daemonPaths, type DaemonPaths } from "../daemon/shared.js"
|
|
14
|
+
|
|
15
|
+
export const CRON_MARKER = "# opencode-apex-daemon"
|
|
16
|
+
export const TASK_NAME = "opencode-apex-daemon"
|
|
17
|
+
|
|
18
|
+
export interface AutostartStatus {
|
|
19
|
+
readonly enabled: boolean
|
|
20
|
+
readonly method: "crontab" | "schtasks"
|
|
21
|
+
readonly detail?: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** El crontab con (o sin) la línea de apex, sin tocar el resto. */
|
|
25
|
+
export function editCrontab(current: string, launcher: string, enable: boolean): string {
|
|
26
|
+
const kept = current.split("\n").filter((line) => !line.includes(CRON_MARKER))
|
|
27
|
+
while (kept.length > 0 && kept[kept.length - 1] === "") kept.pop()
|
|
28
|
+
if (enable) kept.push(`@reboot /bin/sh '${launcher.replaceAll("'", `'\\''`)}' ${CRON_MARKER}`)
|
|
29
|
+
return kept.length > 0 ? `${kept.join("\n")}\n` : ""
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function run(command: string, args: string[], input?: string) {
|
|
33
|
+
const result = spawnSync(command, args, { encoding: "utf8", input, windowsHide: true })
|
|
34
|
+
return { ok: result.status === 0, out: result.stdout ?? "", err: (result.stderr ?? "") || (result.error?.message ?? "") }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function autostartStatus(paths: DaemonPaths = daemonPaths()): AutostartStatus {
|
|
38
|
+
if (process.platform === "win32") {
|
|
39
|
+
const query = run("schtasks", ["/Query", "/TN", TASK_NAME])
|
|
40
|
+
return { enabled: query.ok, method: "schtasks" }
|
|
41
|
+
}
|
|
42
|
+
const list = run("crontab", ["-l"])
|
|
43
|
+
return {
|
|
44
|
+
enabled: list.ok && list.out.split("\n").some((line) => line.includes(CRON_MARKER) && line.includes(paths.launcher)),
|
|
45
|
+
method: "crontab",
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function setAutostart(enable: boolean, paths: DaemonPaths = daemonPaths()): AutostartStatus {
|
|
50
|
+
if (process.platform === "win32") {
|
|
51
|
+
const result = enable
|
|
52
|
+
? run("schtasks", ["/Create", "/TN", TASK_NAME, "/TR", `"${paths.launcher}"`, "/SC", "ONLOGON", "/RL", "LIMITED", "/F"])
|
|
53
|
+
: run("schtasks", ["/Delete", "/TN", TASK_NAME, "/F"])
|
|
54
|
+
if (!result.ok && enable) throw new Error(`schtasks failed: ${result.err.trim()}`)
|
|
55
|
+
return autostartStatus(paths)
|
|
56
|
+
}
|
|
57
|
+
const list = run("crontab", ["-l"])
|
|
58
|
+
// Sin crontab previo, `crontab -l` falla con "no crontab for <user>": se parte de vacío.
|
|
59
|
+
if (!list.ok && !/no crontab/i.test(list.err)) {
|
|
60
|
+
if (/ENOENT|not found/i.test(list.err)) throw new Error("crontab is not installed (install cron, e.g. apt install cron)")
|
|
61
|
+
throw new Error(`crontab -l failed: ${list.err.trim()}`)
|
|
62
|
+
}
|
|
63
|
+
const next = editCrontab(list.ok ? list.out : "", paths.launcher, enable)
|
|
64
|
+
const write = next.length > 0 ? run("crontab", ["-"], next) : run("crontab", ["-r"])
|
|
65
|
+
if (!write.ok && next.length > 0) throw new Error(`crontab write failed: ${write.err.trim()}`)
|
|
66
|
+
return { ...autostartStatus(paths), detail: "runs at boot via cron @reboot (any init system)" }
|
|
67
|
+
}
|
package/core/config.ts
CHANGED
|
@@ -262,10 +262,12 @@ export const apexConfigSchema = z.object({
|
|
|
262
262
|
events: z.boolean().optional(),
|
|
263
263
|
advisor: z.boolean().optional(),
|
|
264
264
|
guard: z.boolean().optional(),
|
|
265
|
-
//
|
|
265
|
+
// Obsoleto, desactivado por defecto: para tu navegador, `browse` de OpenCode.
|
|
266
266
|
browser: z.boolean().optional(),
|
|
267
267
|
// Activado por defecto: external_directory sin preguntar en <tmpdir>/opencode.
|
|
268
268
|
tempAccess: z.boolean().optional(),
|
|
269
|
+
// Activado por defecto: apex_tunnel/webhook/service/daemon (el daemon solo se lanza al usarlas).
|
|
270
|
+
endpoints: z.boolean().optional(),
|
|
269
271
|
})
|
|
270
272
|
.default(() => ({})),
|
|
271
273
|
})
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lado plugin del daemon de apex: lo encuentra, lo lanza si hace falta y le habla por
|
|
3
|
+
* su API de control (127.0.0.1 + token de daemon.json, 0600).
|
|
4
|
+
*
|
|
5
|
+
* Se lanza desacoplado con el binario que ejecuta este plugin: dentro de OpenCode es su
|
|
6
|
+
* propio ejecutable, que con `BUN_BE_BUN=1` se comporta como bun (todas las plataformas).
|
|
7
|
+
* Así sobrevive a que OpenCode descargue el plugin o se reinicie.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { spawn } from "node:child_process"
|
|
11
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from "node:fs"
|
|
12
|
+
import { fileURLToPath } from "node:url"
|
|
13
|
+
import { daemonPaths, type DaemonInfo, type DaemonPaths, type ServerTarget } from "../daemon/shared.js"
|
|
14
|
+
import type { ServerEndpoint } from "./server-endpoint.js"
|
|
15
|
+
|
|
16
|
+
export const DAEMON_SCRIPT = fileURLToPath(new URL("../daemon/main.ts", import.meta.url))
|
|
17
|
+
|
|
18
|
+
export class DaemonError extends Error {
|
|
19
|
+
constructor(
|
|
20
|
+
message: string,
|
|
21
|
+
readonly status?: number,
|
|
22
|
+
) {
|
|
23
|
+
super(message)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** a > b en semver simple (x.y.z); lo demás cuenta como igual. */
|
|
28
|
+
export function newerVersion(a: string, b: string): boolean {
|
|
29
|
+
const parse = (v: string) => v.split(/[.-]/).slice(0, 3).map((n) => Number(n))
|
|
30
|
+
const [x, y] = [parse(a), parse(b)]
|
|
31
|
+
for (let i = 0; i < 3; i++) {
|
|
32
|
+
const l = x[i] ?? 0
|
|
33
|
+
const r = y[i] ?? 0
|
|
34
|
+
if (!Number.isFinite(l) || !Number.isFinite(r)) return false
|
|
35
|
+
if (l !== r) return l > r
|
|
36
|
+
}
|
|
37
|
+
return false
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Cómo lanzar el daemon: el ejecutable actual en modo bun. */
|
|
41
|
+
export function daemonCommand(version: string, execPath = process.execPath, script = DAEMON_SCRIPT, home?: string) {
|
|
42
|
+
const env: Record<string, string> = { BUN_BE_BUN: "1", APEX_DAEMON_VERSION: version }
|
|
43
|
+
if (home) env.APEX_DAEMON_HOME = home
|
|
44
|
+
return { command: execPath, args: [script], env }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Lanzador para el autoarranque (crontab @reboot / tarea de Windows), con las rutas de hoy. */
|
|
48
|
+
export function launcherText(version: string, paths: DaemonPaths, platform = process.platform, execPath = process.execPath): string {
|
|
49
|
+
const { command, args, env } = daemonCommand(version, execPath, DAEMON_SCRIPT, paths.home)
|
|
50
|
+
// La identidad de OpenTunnel vive en XDG_DATA_HOME: cron no la hereda.
|
|
51
|
+
if (process.env.XDG_DATA_HOME) env.XDG_DATA_HOME = process.env.XDG_DATA_HOME
|
|
52
|
+
if (platform === "win32") {
|
|
53
|
+
const sets = Object.entries(env).map(([key, value]) => `set "${key}=${value}"`)
|
|
54
|
+
return ["@echo off", ...sets, `"${command}" "${args[0]}" >> "${paths.log}" 2>&1`, ""].join("\r\n")
|
|
55
|
+
}
|
|
56
|
+
const quote = (s: string) => `'${s.replaceAll("'", `'\\''`)}'`
|
|
57
|
+
const exports = Object.entries(env).map(([key, value]) => `export ${key}=${quote(value)}`)
|
|
58
|
+
return ["#!/bin/sh", ...exports, `exec ${quote(command)} ${quote(args[0]!)} >> ${quote(paths.log)} 2>&1`, ""].join("\n")
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function readInfo(paths: DaemonPaths): DaemonInfo | null {
|
|
62
|
+
try {
|
|
63
|
+
return JSON.parse(readFileSync(paths.info, "utf8")) as DaemonInfo
|
|
64
|
+
} catch {
|
|
65
|
+
return null
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function call<T>(info: DaemonInfo, method: string, path: string, body?: unknown, timeoutMs = 10_000): Promise<T> {
|
|
70
|
+
const response = await fetch(`http://127.0.0.1:${info.port}${path}`, {
|
|
71
|
+
method,
|
|
72
|
+
headers: { authorization: `Bearer ${info.token}`, "content-type": "application/json" },
|
|
73
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
74
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
75
|
+
})
|
|
76
|
+
const text = await response.text()
|
|
77
|
+
let data: unknown
|
|
78
|
+
try {
|
|
79
|
+
data = JSON.parse(text)
|
|
80
|
+
} catch {
|
|
81
|
+
data = { error: text }
|
|
82
|
+
}
|
|
83
|
+
if (!response.ok) throw new DaemonError((data as { error?: string }).error || `daemon HTTP ${response.status} on ${method} ${path}`, response.status)
|
|
84
|
+
return data as T
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function healthy(info: DaemonInfo | null): Promise<{ version: string } | null> {
|
|
88
|
+
if (!info) return null
|
|
89
|
+
try {
|
|
90
|
+
return await call<{ version: string }>(info, "GET", "/v1/health", undefined, 1500)
|
|
91
|
+
} catch {
|
|
92
|
+
return null
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
97
|
+
|
|
98
|
+
export interface DaemonClient {
|
|
99
|
+
readonly info: DaemonInfo
|
|
100
|
+
readonly request: <T = Record<string, unknown>>(method: string, path: string, body?: unknown) => Promise<T>
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface EnsureOptions {
|
|
104
|
+
readonly version: string
|
|
105
|
+
/** false: solo si ya corre (no lanzar). */
|
|
106
|
+
readonly spawn: boolean
|
|
107
|
+
readonly paths?: DaemonPaths
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** El daemon vivo, lanzándolo (o sustituyéndolo por uno más nuevo) si hace falta. */
|
|
111
|
+
export async function ensureDaemon(options: EnsureOptions): Promise<DaemonClient | null> {
|
|
112
|
+
const paths = options.paths ?? daemonPaths()
|
|
113
|
+
let info = readInfo(paths)
|
|
114
|
+
let health = await healthy(info)
|
|
115
|
+
if (health && info && newerVersion(options.version, health.version)) {
|
|
116
|
+
// Plugin actualizado: el daemon viejo cede (los servicios siguen vivos y el nuevo los adopta).
|
|
117
|
+
await call(info, "POST", "/v1/shutdown", {}).catch(() => undefined)
|
|
118
|
+
for (let i = 0; i < 50 && (await healthy(info)); i++) await sleep(100)
|
|
119
|
+
health = null
|
|
120
|
+
}
|
|
121
|
+
if (health && info) return client(info)
|
|
122
|
+
if (!options.spawn) return null
|
|
123
|
+
|
|
124
|
+
mkdirSync(paths.home, { recursive: true, mode: 0o700 })
|
|
125
|
+
writeLauncher(options.version, paths)
|
|
126
|
+
const { command, args, env } = daemonCommand(options.version, process.execPath, DAEMON_SCRIPT, paths.home)
|
|
127
|
+
const fd = openSync(paths.log, "a", 0o600)
|
|
128
|
+
try {
|
|
129
|
+
const child = spawn(command, args, {
|
|
130
|
+
cwd: paths.home,
|
|
131
|
+
env: { ...process.env, ...env },
|
|
132
|
+
detached: true,
|
|
133
|
+
stdio: ["ignore", fd, fd],
|
|
134
|
+
windowsHide: true,
|
|
135
|
+
})
|
|
136
|
+
child.on("error", () => {})
|
|
137
|
+
child.unref()
|
|
138
|
+
} finally {
|
|
139
|
+
closeSync(fd)
|
|
140
|
+
}
|
|
141
|
+
for (let i = 0; i < 100; i++) {
|
|
142
|
+
await sleep(100)
|
|
143
|
+
info = readInfo(paths)
|
|
144
|
+
if (info && (await healthy(info))) return client(info)
|
|
145
|
+
}
|
|
146
|
+
throw new DaemonError(`apex daemon did not start; see ${paths.log}`)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function client(info: DaemonInfo): DaemonClient {
|
|
150
|
+
return { info, request: (method, path, body) => call(info, method, path, body) }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function writeLauncher(version: string, paths: DaemonPaths = daemonPaths()): void {
|
|
154
|
+
try {
|
|
155
|
+
writeFileSync(paths.launcher, launcherText(version, paths), { mode: 0o700 })
|
|
156
|
+
} catch {
|
|
157
|
+
// best-effort: solo lo usa el autoarranque
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** ¿Hay algo que mantener? (sin registro no se lanza nada al cargar el plugin). */
|
|
162
|
+
export function hasRegistryEntries(paths: DaemonPaths = daemonPaths()): boolean {
|
|
163
|
+
if (!existsSync(paths.registry)) return false
|
|
164
|
+
try {
|
|
165
|
+
const registry = JSON.parse(readFileSync(paths.registry, "utf8")) as Record<string, unknown[] | undefined>
|
|
166
|
+
return ["tunnels", "webhooks", "services"].some((key) => (registry[key]?.length ?? 0) > 0)
|
|
167
|
+
} catch {
|
|
168
|
+
return false
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Cómo llega el daemon al servidor de este proyecto, desde lo que ya resuelve events. */
|
|
173
|
+
export function serverTarget(endpoint: ServerEndpoint, env: NodeJS.ProcessEnv = process.env): ServerTarget | null {
|
|
174
|
+
if (!endpoint.baseUrl) return null
|
|
175
|
+
const source = endpoint.auth.password
|
|
176
|
+
let password: ServerTarget["password"] = null
|
|
177
|
+
if (source?.kind === "file" && source.file) password = { kind: "file", file: source.file, field: source.field ?? "password" }
|
|
178
|
+
else if (source?.kind === "env" && source.env && env[source.env]) password = { kind: "value", value: env[source.env]! }
|
|
179
|
+
return { baseUrl: endpoint.baseUrl, password, updatedAt: Date.now() }
|
|
180
|
+
}
|