opencode-apex 0.4.1 → 0.5.1

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/daemon/main.ts CHANGED
@@ -5,8 +5,7 @@
5
5
  * - rutas propias en el túnel OpenTunnel del perfil `default`, el mismo que usa el acceso
6
6
  * remoto de OpenCode (cada uno reclama sus rutas), con caducidad;
7
7
  * - el receptor de webhooks: verifica la firma o el token de cada uno y solo entonces
8
- * llama en local a `events.ingest` (el password del servidor no sale de la máquina);
9
- * - los microservicios del agente: arranque, reinicio con espera creciente, logs y TTL.
8
+ * llama en local a `events.ingest` (el password del servidor no sale de la máquina).
10
9
  *
11
10
  * Multiplataforma a propósito: sin systemd ni launchd. Lo lanza el plugin desacoplado con
12
11
  * el propio binario de OpenCode en modo bun (`BUN_BE_BUN=1`); un lockfile evita dos.
@@ -16,7 +15,6 @@
16
15
  * ser local, en un listener que nunca se enruta.
17
16
  */
18
17
 
19
- import { spawn, type ChildProcess } from "node:child_process"
20
18
  import {
21
19
  chmodSync,
22
20
  closeSync,
@@ -25,17 +23,14 @@ import {
25
23
  openSync,
26
24
  readFileSync,
27
25
  renameSync,
28
- statSync,
29
26
  unlinkSync,
30
27
  writeFileSync,
31
28
  writeSync,
32
29
  } from "node:fs"
33
30
  import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"
34
- import { uptime } from "node:os"
35
31
  import { join } from "node:path"
36
32
  import { rpcUrl, tunnelDirectory } from "../core/server-endpoint.js"
37
33
  import {
38
- bootStamp,
39
34
  daemonPaths,
40
35
  emptyRegistry,
41
36
  randomRoute,
@@ -44,9 +39,7 @@ import {
44
39
  type DaemonInfo,
45
40
  type ProxyProtocol,
46
41
  type Registry,
47
- type RestartPolicy,
48
42
  type ServerTarget,
49
- type ServiceEntry,
50
43
  type TunnelEntry,
51
44
  type WebhookEntry,
52
45
  type WebhookProvider,
@@ -112,7 +105,7 @@ function writePrivate(file: string, data: string): void {
112
105
  }
113
106
  }
114
107
 
115
- function loadRegistry(): Registry & { ports?: { control?: number; hooks?: number } } {
108
+ function loadRegistry(): Registry {
116
109
  try {
117
110
  const parsed = JSON.parse(readFileSync(paths.registry, "utf8"))
118
111
  return { ...emptyRegistry(), ...parsed }
@@ -189,11 +182,10 @@ let controlPort = 0
189
182
 
190
183
  function routeTable(): Record<string, string | { target: string; proxyProtocol: ProxyProtocol }> {
191
184
  const routes: Record<string, string | { target: string; proxyProtocol: ProxyProtocol }> = {}
192
- for (const entry of registry.tunnels) {
193
- // Las rutas de webhooks apuntan al listener de webhooks, cuyo puerto puede cambiar.
194
- const target = registry.webhooks.some((hook) => hook.id === entry.ownerID) ? `127.0.0.1:${hooksPort}` : entry.target
195
- routes[entry.route] = entry.proxyProtocol ? { target, proxyProtocol: entry.proxyProtocol } : target
196
- }
185
+ for (const entry of registry.tunnels)
186
+ routes[entry.route] = entry.proxyProtocol ? { target: entry.target, proxyProtocol: entry.proxyProtocol } : entry.target
187
+ // Todos los webhooks comparten el listener de webhooks; el Host elige cuál.
188
+ for (const hook of registry.webhooks) routes[hook.route] = `127.0.0.1:${hooksPort}`
197
189
  return routes
198
190
  }
199
191
 
@@ -290,7 +282,7 @@ function onTunnelStopped(connection: Connection, error: unknown): void {
290
282
  }
291
283
 
292
284
  function scheduleRetry(): void {
293
- if (tunnel.retry || registry.tunnels.length === 0) return
285
+ if (tunnel.retry || Object.keys(routeTable()).length === 0) return
294
286
  const delay = Math.min(1000 * 2 ** tunnel.failures, 60_000)
295
287
  tunnel.failures++
296
288
  tunnel.retry = setTimeout(() => {
@@ -299,201 +291,6 @@ function scheduleRetry(): void {
299
291
  }, delay)
300
292
  }
301
293
 
302
- // ============================================================================
303
- // Microservicios
304
- // ============================================================================
305
-
306
- const children = new Map<string, ChildProcess>()
307
- const stopping = new Set<string>()
308
- const startedAt = new Map<string, number>()
309
- const restartTimers = new Map<string, ReturnType<typeof setTimeout>>()
310
- const currentBoot = () => bootStamp(Date.now(), uptime())
311
-
312
- /** Entorno de un servicio: el del daemon menos credenciales de OpenCode, más lo suyo. */
313
- function serviceEnv(service: ServiceEntry): NodeJS.ProcessEnv {
314
- const env: NodeJS.ProcessEnv = { ...process.env }
315
- for (const key of ["OPENCODE_SERVER_PASSWORD", "OPENCODE_PASSWORD", "BUN_BE_BUN", "APEX_DAEMON_VERSION"]) delete env[key]
316
- const route = registry.tunnels.find((entry) => entry.ownerID === service.id)
317
- return {
318
- ...env,
319
- ...service.env,
320
- ...(service.port ? { PORT: String(service.port) } : {}),
321
- ...(route && urlOf(route.route) ? { APEX_PUBLIC_URL: urlOf(route.route)! } : {}),
322
- APEX_SERVICE_NAME: service.name,
323
- APEX_INGEST_URL: `http://127.0.0.1:${controlPort}/v1/ingest`,
324
- APEX_INGEST_TOKEN: service.ingestToken,
325
- }
326
- }
327
-
328
- function rotate(file: string, max: number): void {
329
- try {
330
- if (statSync(file).size > max) renameSync(file, `${file}.1`)
331
- } catch {
332
- // no existe todavía
333
- }
334
- }
335
-
336
- function startService(service: ServiceEntry): void {
337
- if (children.has(service.id)) return
338
- mkdirSync(paths.logs, { recursive: true, mode: 0o700 })
339
- rotate(service.logFile, 10 * 1024 * 1024)
340
- const fd = openSync(service.logFile, "a", 0o600)
341
- writeSync(fd, `\n--- ${new Date().toISOString()} start: ${service.command}\n`)
342
- let child: ChildProcess
343
- try {
344
- // detached: grupo propio (se para entero) y sobrevive a un reinicio del daemon,
345
- // que lo adopta por pid. La salida va directa al fichero, sin pasar por el daemon.
346
- child = spawn(service.command, {
347
- cwd: service.cwd,
348
- env: serviceEnv(service),
349
- shell: true,
350
- detached: true,
351
- stdio: ["ignore", fd, fd],
352
- windowsHide: true,
353
- })
354
- } catch (error) {
355
- closeSync(fd)
356
- service.status = "failed"
357
- service.lastExit = { code: null, signal: String((error as Error).message), at: Date.now() }
358
- save()
359
- return
360
- }
361
- closeSync(fd)
362
- children.set(service.id, child)
363
- startedAt.set(service.id, Date.now())
364
- service.pid = child.pid ?? null
365
- service.bootAt = currentBoot()
366
- service.status = "running"
367
- save()
368
- child.on("exit", (code, signal) => {
369
- children.delete(service.id)
370
- onServiceExit(service.id, code, signal)
371
- })
372
- child.on("error", (error) => {
373
- log(`service ${service.name}:`, error.message)
374
- // Sin proceso (no hubo spawn): no llegará exit.
375
- if (child.pid === undefined) {
376
- children.delete(service.id)
377
- service.pid = null
378
- service.status = "failed"
379
- service.lastExit = { code: null, signal: error.message, at: Date.now() }
380
- save()
381
- }
382
- })
383
- child.unref()
384
- }
385
-
386
- function onServiceExit(id: string, code: number | null, signal: string | null): void {
387
- const service = registry.services.find((entry) => entry.id === id)
388
- if (!service) return
389
- service.pid = null
390
- service.lastExit = { code, signal, at: Date.now() }
391
- if (stopping.has(id)) {
392
- stopping.delete(id)
393
- service.status = "stopped"
394
- save()
395
- return
396
- }
397
- // Estable más de un minuto: el contador de reinicios vuelve a cero.
398
- if (Date.now() - (startedAt.get(id) ?? 0) > 60_000) service.restarts = 0
399
- const again = service.restart === "always" || (service.restart === "on-failure" && code !== 0)
400
- if (!again) {
401
- service.status = code === 0 ? "stopped" : "failed"
402
- save()
403
- return
404
- }
405
- const delay = Math.min(1000 * 2 ** service.restarts, 60_000)
406
- service.restarts++
407
- service.status = "backoff"
408
- save()
409
- restartTimers.set(
410
- id,
411
- setTimeout(() => {
412
- restartTimers.delete(id)
413
- const current = registry.services.find((entry) => entry.id === id)
414
- if (current && current.status === "backoff") startService(current)
415
- }, delay),
416
- )
417
- }
418
-
419
- /** Mata el grupo del servicio: SIGTERM y, a los 5 s, SIGKILL (Windows: taskkill /T /F). */
420
- function killTree(pid: number): void {
421
- if (process.platform === "win32") {
422
- spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on("error", () => {})
423
- return
424
- }
425
- const signal = (sig: NodeJS.Signals) => {
426
- try {
427
- process.kill(-pid, sig)
428
- } catch {
429
- try {
430
- process.kill(pid, sig)
431
- } catch {
432
- // ya no existe
433
- }
434
- }
435
- }
436
- signal("SIGTERM")
437
- setTimeout(() => {
438
- if (alive(pid)) signal("SIGKILL")
439
- }, 5000).unref()
440
- }
441
-
442
- function stopService(service: ServiceEntry): void {
443
- const timer = restartTimers.get(service.id)
444
- if (timer) {
445
- clearTimeout(timer)
446
- restartTimers.delete(service.id)
447
- }
448
- if (service.pid && alive(service.pid)) {
449
- stopping.add(service.id)
450
- killTree(service.pid)
451
- // Adoptado (sin ChildProcess): no habrá evento exit.
452
- if (!children.has(service.id)) {
453
- stopping.delete(service.id)
454
- service.pid = null
455
- service.status = "stopped"
456
- }
457
- } else {
458
- service.pid = null
459
- service.status = "stopped"
460
- }
461
- save()
462
- }
463
-
464
- /** Al arrancar: adopta los servicios vivos del daemon anterior; arranca el resto. */
465
- function resumeServices(restartAll: boolean): void {
466
- const boot = currentBoot()
467
- for (const service of registry.services) {
468
- if (service.status === "stopped" || service.status === "failed") continue
469
- const sameBoot = service.bootAt !== null && Math.abs(boot - service.bootAt) <= 20_000
470
- if (service.pid && sameBoot && alive(service.pid)) {
471
- if (restartAll) {
472
- // El puerto de control cambió: APEX_INGEST_URL del servicio ya no vale.
473
- killTree(service.pid)
474
- service.pid = null
475
- setTimeout(() => startService(service), 1500)
476
- continue
477
- }
478
- service.status = "running"
479
- log(`adopted service ${service.name} (pid ${service.pid})`)
480
- continue
481
- }
482
- service.pid = null
483
- startService(service)
484
- }
485
- save()
486
- }
487
-
488
- /** Vigila los adoptados (sin evento exit): cuando mueren, se tratan como una salida. */
489
- function watchAdopted(): void {
490
- for (const service of registry.services) {
491
- if (service.status === "running" && service.pid && !children.has(service.id) && !alive(service.pid)) {
492
- onServiceExit(service.id, null, null)
493
- }
494
- }
495
- }
496
-
497
294
  // ============================================================================
498
295
  // Altas, bajas y caducidad
499
296
  // ============================================================================
@@ -507,7 +304,7 @@ function pickRoute(name: unknown): string {
507
304
  if (typeof name === "string" && name.length > 0) {
508
305
  const route = name.toLowerCase()
509
306
  if (!validRouteName(route)) throw new HttpError(400, `invalid route name "${name}" (lowercase letters, digits, dashes)`)
510
- if (registry.tunnels.some((entry) => entry.route === route)) throw new HttpError(409, `route "${route}" already in use`)
307
+ if (route in routeTable()) throw new HttpError(409, `route "${route}" already in use`)
511
308
  return route
512
309
  }
513
310
  return randomRoute()
@@ -529,13 +326,12 @@ function assertNotServerPort(host: string, port: number): void {
529
326
 
530
327
  function removeTunnel(id: string): boolean {
531
328
  const before = registry.tunnels.length
532
- registry.tunnels = registry.tunnels.filter((entry) => entry.id !== id && entry.ownerID !== id)
329
+ registry.tunnels = registry.tunnels.filter((entry) => entry.id !== id && entry.route !== id)
533
330
  return registry.tunnels.length !== before
534
331
  }
535
332
 
536
333
  function removeWebhook(hook: WebhookEntry): void {
537
334
  registry.webhooks = registry.webhooks.filter((entry) => entry.id !== hook.id)
538
- removeTunnel(hook.id)
539
335
  try {
540
336
  unlinkSync(hook.secretFile)
541
337
  } catch {
@@ -543,19 +339,13 @@ function removeWebhook(hook: WebhookEntry): void {
543
339
  }
544
340
  }
545
341
 
546
- function removeService(service: ServiceEntry): void {
547
- stopService(service)
548
- registry.services = registry.services.filter((entry) => entry.id !== service.id)
549
- removeTunnel(service.id)
550
- }
551
-
552
342
  let idleSince: number | null = null
553
343
 
554
344
  function sweep(): void {
555
345
  const now = Date.now()
556
346
  let changed = false
557
347
  for (const entry of [...registry.tunnels]) {
558
- if (!entry.ownerID && entry.expiresAt !== null && entry.expiresAt <= now) {
348
+ if (entry.expiresAt !== null && entry.expiresAt <= now) {
559
349
  log(`expired tunnel ${entry.route}`)
560
350
  changed = removeTunnel(entry.id) || changed
561
351
  }
@@ -567,19 +357,11 @@ function sweep(): void {
567
357
  changed = true
568
358
  }
569
359
  }
570
- for (const service of [...registry.services]) {
571
- if (service.expiresAt !== null && service.expiresAt <= now) {
572
- log(`expired service ${service.name}`)
573
- removeService(service)
574
- changed = true
575
- }
576
- }
577
- watchAdopted()
578
360
  if (changed) {
579
361
  save()
580
362
  void syncRoutes()
581
363
  }
582
- const empty = registry.tunnels.length === 0 && registry.webhooks.length === 0 && registry.services.length === 0
364
+ const empty = registry.tunnels.length === 0 && registry.webhooks.length === 0
583
365
  idleSince = empty ? (idleSince ?? now) : null
584
366
  if (idleSince !== null && now - idleSince >= IDLE_EXIT_MS) {
585
367
  log("idle: nothing to keep, exiting")
@@ -637,14 +419,7 @@ function lowerHeaders(request: IncomingMessage): Headers {
637
419
  /** Lo que ve el plugin de un webhook: nunca el secreto, solo su fichero. */
638
420
  function publicHook(hook: WebhookEntry) {
639
421
  const { secret: _secret, ...rest } = hook
640
- const route = registry.tunnels.find((entry) => entry.ownerID === hook.id)
641
- return { ...rest, url: route ? urlOf(route.route) : null }
642
- }
643
-
644
- function publicService(service: ServiceEntry) {
645
- const { ingestToken: _token, env, ...rest } = service
646
- const route = registry.tunnels.find((entry) => entry.ownerID === service.id)
647
- return { ...rest, envKeys: Object.keys(env), url: route ? urlOf(route.route) : null }
422
+ return { ...rest, url: urlOf(hook.route) }
648
423
  }
649
424
 
650
425
  function publicTunnel(entry: TunnelEntry) {
@@ -681,24 +456,9 @@ async function control(request: IncomingMessage, response: ServerResponse, token
681
456
  const method = request.method ?? "GET"
682
457
  const auth = request.headers.authorization ?? ""
683
458
 
684
- // Ingest de los servicios: su propio token, no el del daemon.
685
- if (url.pathname === "/v1/ingest" && method === "POST") {
686
- const service = registry.services.find((entry) => auth === `Bearer ${entry.ingestToken}`)
687
- if (!service) return send(response, 401, { error: "unauthorized" })
688
- const body = parseBody(await readBody(request), "application/json")
689
- const payload = (body.payload && typeof body.payload === "object" ? body.payload : body) as Record<string, unknown>
690
- const result = await ingest(service.directory, {
691
- source: typeof body.source === "string" ? body.source : `service:${service.name}`,
692
- ...(typeof body.type === "string" ? { type: body.type } : {}),
693
- ...(typeof body.eventID === "string" ? { eventID: body.eventID } : {}),
694
- payload,
695
- })
696
- return send(response, result.ok ? 202 : 502, result)
697
- }
698
-
699
459
  if (auth !== `Bearer ${token}`) return send(response, 401, { error: "unauthorized" })
700
460
  const body = method === "POST" ? (parseBody(await readBody(request), "application/json") as Record<string, unknown>) : {}
701
- const [, , kind, id, action] = url.pathname.split("/")
461
+ const [, , kind, id] = url.pathname.split("/")
702
462
 
703
463
  if (url.pathname === "/v1/health") return send(response, 200, { ok: true, version: VERSION, pid: process.pid, startedAt: info.startedAt })
704
464
 
@@ -710,9 +470,8 @@ async function control(request: IncomingMessage, response: ServerResponse, token
710
470
  startedAt: info.startedAt,
711
471
  ports: { control: controlPort, hooks: hooksPort },
712
472
  tunnel: tunnelStatus(),
713
- tunnels: registry.tunnels.filter((entry) => !entry.ownerID).map(publicTunnel),
473
+ tunnels: registry.tunnels.map(publicTunnel),
714
474
  webhooks: registry.webhooks.map(publicHook),
715
- services: registry.services.map(publicService),
716
475
  servers: Object.keys(registry.servers),
717
476
  })
718
477
  }
@@ -755,7 +514,7 @@ async function control(request: IncomingMessage, response: ServerResponse, token
755
514
  return send(response, 201, { ...publicTunnel(entry), tunnel: tunnelStatus() })
756
515
  }
757
516
  if (method === "DELETE" && id) {
758
- const removed = removeTunnel(id) || removeTunnel(registry.tunnels.find((entry) => entry.route === id)?.id ?? "")
517
+ const removed = removeTunnel(id)
759
518
  save()
760
519
  void syncRoutes()
761
520
  return send(response, removed ? 200 : 404, { removed })
@@ -793,17 +552,6 @@ async function control(request: IncomingMessage, response: ServerResponse, token
793
552
  stats: { ok: 0, rejected: 0, failed: 0, lastAt: null, lastError: null },
794
553
  }
795
554
  registry.webhooks.push(hook)
796
- registry.tunnels.push({
797
- kind: "tunnel",
798
- id: newId("tun"),
799
- directory: hook.directory,
800
- sessionID: hook.sessionID,
801
- createdAt: hook.createdAt,
802
- expiresAt: hook.expiresAt,
803
- route,
804
- target: `127.0.0.1:${hooksPort}`,
805
- ownerID: hook.id,
806
- })
807
555
  save()
808
556
  void syncRoutes()
809
557
  await knownHostname()
@@ -819,91 +567,6 @@ async function control(request: IncomingMessage, response: ServerResponse, token
819
567
  }
820
568
  }
821
569
 
822
- if (kind === "services") {
823
- const service = id ? registry.services.find((entry) => entry.id === id || entry.name === id) : undefined
824
- if (method === "POST" && !id) {
825
- const name = String(body.name ?? "")
826
- if (!/^[\w.-]{1,64}$/.test(name)) throw new HttpError(400, "name: 1-64 letters, digits, dot, dash, underscore")
827
- if (registry.services.some((entry) => entry.name === name)) throw new HttpError(409, `service "${name}" already exists (down it first)`)
828
- const command = String(body.command ?? "")
829
- if (!command.trim()) throw new HttpError(400, "command is required")
830
- const port = body.port === undefined || body.port === null ? null : Number(body.port)
831
- if (port !== null && (!Number.isInteger(port) || port <= 0 || port > 65535)) throw new HttpError(400, "port must be 1-65535")
832
- if (body.public === true && port === null) throw new HttpError(400, "a public service needs its port")
833
- if (body.public === true && port !== null) assertNotServerPort("127.0.0.1", port)
834
- const restart: RestartPolicy = body.restart === "never" || body.restart === "on-failure" ? body.restart : "always"
835
- const env: Record<string, string> = {}
836
- for (const [key, value] of Object.entries((body.env ?? {}) as Record<string, unknown>)) env[key] = String(value)
837
- const base = owned(body)
838
- const cwd = typeof body.cwd === "string" && body.cwd.length > 0 ? body.cwd : base.directory
839
- if (!existsSync(cwd)) throw new HttpError(400, `cwd does not exist: ${cwd}`)
840
- const serviceId = newId("svc")
841
- const entry: ServiceEntry = {
842
- kind: "service",
843
- id: serviceId,
844
- ...base,
845
- name,
846
- command,
847
- cwd,
848
- env,
849
- port,
850
- restart,
851
- ingestToken: randomToken(24),
852
- logFile: join(paths.logs, `${name}.log`),
853
- pid: null,
854
- bootAt: null,
855
- status: "starting",
856
- restarts: 0,
857
- lastExit: null,
858
- }
859
- registry.services.push(entry)
860
- if (body.public === true && port !== null) {
861
- registry.tunnels.push({
862
- kind: "tunnel",
863
- id: newId("tun"),
864
- directory: base.directory,
865
- sessionID: base.sessionID,
866
- createdAt: base.createdAt,
867
- expiresAt: base.expiresAt,
868
- route: pickRoute(body.route),
869
- target: `127.0.0.1:${port}`,
870
- ...(body.proxyProtocol === "v1" || body.proxyProtocol === "v2" ? { proxyProtocol: body.proxyProtocol } : {}),
871
- ownerID: serviceId,
872
- })
873
- await knownHostname()
874
- void syncRoutes()
875
- }
876
- save()
877
- startService(entry)
878
- return send(response, 201, { ...publicService(entry), tunnel: tunnelStatus() })
879
- }
880
- if (!service) return send(response, 404, { error: "no such service" })
881
- if (method === "DELETE") {
882
- removeService(service)
883
- save()
884
- void syncRoutes()
885
- return send(response, 200, { removed: true })
886
- }
887
- if (method === "POST" && action === "restart") {
888
- stopService(service)
889
- service.restarts = 0
890
- service.status = "starting"
891
- setTimeout(() => startService(service), 1000)
892
- return send(response, 200, { restarting: true })
893
- }
894
- if (method === "GET" && action === "logs") {
895
- const lines = Math.min(Math.max(Number(url.searchParams.get("lines") ?? 100) || 100, 1), 2000)
896
- let text = ""
897
- try {
898
- const data = readFileSync(service.logFile, "utf8")
899
- text = data.split("\n").slice(-lines - 1).join("\n")
900
- } catch {
901
- text = ""
902
- }
903
- return send(response, 200, { file: service.logFile, status: service.status, text })
904
- }
905
- }
906
-
907
570
  return send(response, 404, { error: `no route ${method} ${url.pathname}` })
908
571
  }
909
572
 
@@ -950,19 +613,10 @@ function wrap(handler: (request: IncomingMessage, response: ServerResponse) => P
950
613
  }
951
614
  }
952
615
 
953
- function listen(server: Server, preferred: number | undefined): Promise<number> {
616
+ function listen(server: Server): Promise<number> {
954
617
  return new Promise((resolve, reject) => {
955
- const attempt = (port: number) => {
956
- server.once("error", (error: NodeJS.ErrnoException) => {
957
- if (port !== 0 && error.code === "EADDRINUSE") attempt(0)
958
- else reject(error)
959
- })
960
- server.listen(port, "127.0.0.1", () => {
961
- const address = server.address()
962
- resolve(typeof address === "object" && address ? address.port : port)
963
- })
964
- }
965
- attempt(preferred ?? 0)
618
+ server.once("error", reject)
619
+ server.listen(0, "127.0.0.1", () => resolve((server.address() as { port: number }).port))
966
620
  })
967
621
  }
968
622
 
@@ -981,7 +635,6 @@ async function shutdown(code: number): Promise<never> {
981
635
  closing = true
982
636
  log("shutting down")
983
637
  clearInterval(sweeper)
984
- // Los servicios siguen vivos (desacoplados): el próximo daemon los adopta.
985
638
  try {
986
639
  await tunnel.connection?.close()
987
640
  await tunnel.client?.dispose()
@@ -1009,13 +662,10 @@ async function main(): Promise<void> {
1009
662
  process.exit(0)
1010
663
  }
1011
664
  const token = randomToken(24)
1012
- const previous = registry.ports ?? {}
1013
665
  controlServer = createServer(wrap((request, response) => control(request, response, token)))
1014
666
  hooksServer = createServer(wrap(hooks))
1015
- controlPort = await listen(controlServer, previous.control)
1016
- hooksPort = await listen(hooksServer, previous.hooks)
1017
- const portsChanged = previous.control !== undefined && previous.control !== controlPort
1018
- registry.ports = { control: controlPort, hooks: hooksPort }
667
+ controlPort = await listen(controlServer)
668
+ hooksPort = await listen(hooksServer)
1019
669
  info = { pid: process.pid, port: controlPort, token, version: VERSION, startedAt: Date.now() }
1020
670
  writePrivate(paths.info, JSON.stringify(info))
1021
671
  save()
@@ -1025,14 +675,13 @@ async function main(): Promise<void> {
1025
675
  process.on("uncaughtException", (error) => log("uncaught:", error))
1026
676
  process.on("unhandledRejection", (error) => log("unhandled:", error))
1027
677
 
1028
- resumeServices(portsChanged)
1029
678
  // Carga el SDK ya: si apex se actualiza, su directorio viejo puede desaparecer.
1030
679
  tunnel.client = await loadClient().catch((error) => {
1031
680
  tunnel.lastError = `OpenTunnel SDK unavailable: ${String((error as Error).message ?? error)}`
1032
681
  log(tunnel.lastError)
1033
682
  return null
1034
683
  })
1035
- if (registry.tunnels.length > 0) void syncRoutes()
684
+ if (Object.keys(routeTable()).length > 0) void syncRoutes()
1036
685
  sweeper = setInterval(sweep, SWEEP_MS)
1037
686
  }
1038
687
 
package/daemon/shared.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Lo que comparten el daemon de apex y el plugin: rutas en disco y forma del registro.
3
3
  *
4
4
  * El daemon es UN proceso por usuario (no por proyecto): mantiene las rutas de
5
- * OpenTunnel, recibe webhooks y vigila los microservicios del agente. Vive fuera del
5
+ * OpenTunnel y recibe webhooks. Vive fuera del
6
6
  * plugin porque OpenCode descarga los plugins tras 60 min sin actividad.
7
7
  */
8
8
 
@@ -21,12 +21,9 @@ export interface DaemonPaths {
21
21
  /** { pid, port, token, version, startedAt } — 0600. */
22
22
  readonly info: string
23
23
  readonly lock: string
24
- /** Rutas, webhooks, servicios y servidores — 0600 (lleva secretos de webhooks). */
24
+ /** Rutas, webhooks y servidores — 0600 (lleva secretos de webhooks). */
25
25
  readonly registry: string
26
26
  readonly log: string
27
- readonly logs: string
28
- /** Lanzador que usa el autoarranque; el plugin lo reescribe con las rutas actuales. */
29
- readonly launcher: string
30
27
  }
31
28
 
32
29
  export function daemonPaths(home = daemonHome()): DaemonPaths {
@@ -36,8 +33,6 @@ export function daemonPaths(home = daemonHome()): DaemonPaths {
36
33
  lock: join(home, "daemon.lock"),
37
34
  registry: join(home, "registry.json"),
38
35
  log: join(home, "daemon.log"),
39
- logs: join(home, "logs"),
40
- launcher: join(home, process.platform === "win32" ? "launch.cmd" : "launch.sh"),
41
36
  }
42
37
  }
43
38
 
@@ -76,8 +71,6 @@ export interface TunnelEntry extends Owned {
76
71
  readonly route: string
77
72
  readonly target: string
78
73
  readonly proxyProtocol?: ProxyProtocol
79
- /** Ruta creada por un servicio o webhook (se borra con él). */
80
- readonly ownerID?: string
81
74
  }
82
75
 
83
76
  export type WebhookProvider = "github" | "stripe" | "slack" | "hmac" | "token"
@@ -98,40 +91,16 @@ export interface WebhookEntry extends Owned {
98
91
  readonly stats: { ok: number; rejected: number; failed: number; lastAt: number | null; lastError: string | null }
99
92
  }
100
93
 
101
- export type RestartPolicy = "always" | "on-failure" | "never"
102
-
103
- export interface ServiceEntry extends Owned {
104
- readonly kind: "service"
105
- readonly name: string
106
- /** Línea de shell (sh -c / cmd /c). */
107
- readonly command: string
108
- readonly cwd: string
109
- readonly env: Readonly<Record<string, string>>
110
- readonly port: number | null
111
- readonly restart: RestartPolicy
112
- /** Token con el que el servicio llama al ingest local del daemon (APEX_INGEST_TOKEN). */
113
- readonly ingestToken: string
114
- readonly logFile: string
115
- /** Estado de ejecución (lo actualiza el daemon). */
116
- pid: number | null
117
- /** Arranque del sistema en el que corre `pid` (un pid de otro arranque no vale). */
118
- bootAt: number | null
119
- status: "starting" | "running" | "backoff" | "stopped" | "failed"
120
- restarts: number
121
- lastExit: { code: number | null; signal: string | null; at: number } | null
122
- }
123
-
124
94
  export interface Registry {
125
95
  version: 1
126
96
  tunnels: TunnelEntry[]
127
97
  webhooks: WebhookEntry[]
128
- services: ServiceEntry[]
129
98
  /** directorio → cómo llegar a su servidor. */
130
99
  servers: Record<string, ServerTarget>
131
100
  }
132
101
 
133
102
  export function emptyRegistry(): Registry {
134
- return { version: 1, tunnels: [], webhooks: [], services: [], servers: {} }
103
+ return { version: 1, tunnels: [], webhooks: [], servers: {} }
135
104
  }
136
105
 
137
106
  /** Nombre de ruta aleatorio: 16 hex, como los del CLI de OpenTunnel (no aparecen en los logs de certificados). */
@@ -148,8 +117,3 @@ export function validRouteName(name: string): boolean {
148
117
  export function randomToken(bytes = 32): string {
149
118
  return Array.from(crypto.getRandomValues(new Uint8Array(bytes)), (b) => b.toString(16).padStart(2, "0")).join("")
150
119
  }
151
-
152
- /** Marca del arranque actual del sistema, redondeada a 10 s (os.uptime oscila). */
153
- export function bootStamp(now = Date.now(), uptimeSeconds: number): number {
154
- return Math.round((now - uptimeSeconds * 1000) / 10_000) * 10_000
155
- }
package/docs/CONFIG.md CHANGED
@@ -92,7 +92,7 @@ Each module has exactly one switch, under `modules`:
92
92
  | `guard` | **off** (it can block the agent if its rules are wrong, so you opt in) |
93
93
  | `browser` | **off** since 0.3.0 (deprecated: use OpenCode's [browse](https://opencode.ai/product/browse)) |
94
94
  | `tempAccess` | on |
95
- | `endpoints` | on (the daemon starts only when an `apex_webhook` / `apex_tunnel` / `apex_service` tool is used, see [ENDPOINTS.md](ENDPOINTS.md)) |
95
+ | `endpoints` | on (the daemon starts only when an `apex_webhook` / `apex_tunnel` tool is used, see [ENDPOINTS.md](ENDPOINTS.md)) |
96
96
 
97
97
  There is no `<module>.enabled` key. A legacy `events.enabled` is ignored and logs a
98
98
  warning. So does `events.listener`: the HTTP listener was removed in 0.2.0, see