opencode-apex 0.6.0 → 0.8.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 +84 -0
- package/advisor.ts +12 -8
- package/browser.ts +26 -0
- package/core/advisor-session.ts +102 -3
- package/core/config.ts +43 -1
- package/core/cred-channel.ts +300 -0
- package/core/cred.ts +145 -24
- package/core/kdbx.ts +374 -0
- package/core/tools-run.ts +22 -7
- package/cred.ts +803 -130
- package/daemon/main.ts +89 -7
- package/daemon/mcp.ts +261 -0
- package/daemon/shared.ts +9 -0
- package/docs/ADVISOR.md +10 -1
- package/docs/CONFIG.md +3 -1
- package/docs/CRED.md +127 -44
- package/docs/ENDPOINTS.md +11 -3
- package/docs/EVENTS.md +42 -0
- package/endpoints.ts +106 -2
- package/index.ts +14 -3
- package/opencode-apex.jsonc +3 -1
- package/package.json +10 -6
- package/skills/apex-callbacks/SKILL.md +7 -0
package/daemon/main.ts
CHANGED
|
@@ -10,9 +10,13 @@
|
|
|
10
10
|
* Multiplataforma a propósito: sin systemd ni launchd. Lo lanza el plugin desacoplado con
|
|
11
11
|
* el propio binario de OpenCode en modo bun (`BUN_BE_BUN=1`); un lockfile evita dos.
|
|
12
12
|
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
13
|
+
* - el servidor MCP Events (daemon/mcp.ts): lo que entra por `events.ingest` se publica
|
|
14
|
+
* como evento `apex.event` para los triggers `event` de las automations de OpenCode.
|
|
15
|
+
*
|
|
16
|
+
* Tres listeners en 127.0.0.1: control (token del daemon; nunca se publica), webhooks
|
|
17
|
+
* (lo único que apunta el túnel) y MCP (token propio, puerto estable entre arranques porque
|
|
18
|
+
* la config MCP de OpenCode lo apunta). Separarlos es lo que pide OpenTunnel: lo que solo
|
|
19
|
+
* debe ser local, en un listener que nunca se enruta.
|
|
16
20
|
*/
|
|
17
21
|
|
|
18
22
|
import {
|
|
@@ -37,6 +41,7 @@ import {
|
|
|
37
41
|
randomToken,
|
|
38
42
|
validRouteName,
|
|
39
43
|
type DaemonInfo,
|
|
44
|
+
type McpInfo,
|
|
40
45
|
type ProxyProtocol,
|
|
41
46
|
type Registry,
|
|
42
47
|
type ServerTarget,
|
|
@@ -44,6 +49,7 @@ import {
|
|
|
44
49
|
type WebhookEntry,
|
|
45
50
|
type WebhookProvider,
|
|
46
51
|
} from "./shared.js"
|
|
52
|
+
import { createEventsServer, type EventsServer } from "./mcp.js"
|
|
47
53
|
import { parseBody, slackChallenge, toIngest, verify, type Headers } from "./webhooks.js"
|
|
48
54
|
|
|
49
55
|
const VERSION = process.env.APEX_DAEMON_VERSION ?? "dev"
|
|
@@ -340,6 +346,8 @@ function removeWebhook(hook: WebhookEntry): void {
|
|
|
340
346
|
}
|
|
341
347
|
|
|
342
348
|
let idleSince: number | null = null
|
|
349
|
+
/** Última petición de control: el plugin cargado hace ping para que el servidor MCP siga vivo. */
|
|
350
|
+
let lastControlAt = Date.now()
|
|
343
351
|
|
|
344
352
|
function sweep(): void {
|
|
345
353
|
const now = Date.now()
|
|
@@ -361,9 +369,11 @@ function sweep(): void {
|
|
|
361
369
|
save()
|
|
362
370
|
void syncRoutes()
|
|
363
371
|
}
|
|
364
|
-
const empty = registry.tunnels.length === 0 && registry.webhooks.length === 0
|
|
372
|
+
const empty = registry.tunnels.length === 0 && registry.webhooks.length === 0 && (events?.streams() ?? 0) === 0
|
|
365
373
|
idleSince = empty ? (idleSince ?? now) : null
|
|
366
|
-
|
|
374
|
+
// Inactivo de verdad: nada que mantener y nadie (plugin ni cliente MCP) ha llamado últimamente.
|
|
375
|
+
const quiet = Math.max(idleSince ?? now, lastControlAt, events?.lastRequestAt() ?? 0)
|
|
376
|
+
if (idleSince !== null && now - quiet >= IDLE_EXIT_MS) {
|
|
367
377
|
log("idle: nothing to keep, exiting")
|
|
368
378
|
void shutdown(0)
|
|
369
379
|
}
|
|
@@ -457,6 +467,7 @@ async function control(request: IncomingMessage, response: ServerResponse, token
|
|
|
457
467
|
const auth = request.headers.authorization ?? ""
|
|
458
468
|
|
|
459
469
|
if (auth !== `Bearer ${token}`) return send(response, 401, { error: "unauthorized" })
|
|
470
|
+
lastControlAt = Date.now()
|
|
460
471
|
const body = method === "POST" ? (parseBody(await readBody(request), "application/json") as Record<string, unknown>) : {}
|
|
461
472
|
const [, , kind, id] = url.pathname.split("/")
|
|
462
473
|
|
|
@@ -468,7 +479,8 @@ async function control(request: IncomingMessage, response: ServerResponse, token
|
|
|
468
479
|
version: VERSION,
|
|
469
480
|
pid: process.pid,
|
|
470
481
|
startedAt: info.startedAt,
|
|
471
|
-
ports: { control: controlPort, hooks: hooksPort },
|
|
482
|
+
ports: { control: controlPort, hooks: hooksPort, mcp: mcp?.port ?? null },
|
|
483
|
+
mcp: { streams: events?.streams() ?? 0, error: mcpError },
|
|
472
484
|
tunnel: tunnelStatus(),
|
|
473
485
|
tunnels: registry.tunnels.map(publicTunnel),
|
|
474
486
|
webhooks: registry.webhooks.map(publicHook),
|
|
@@ -485,6 +497,28 @@ async function control(request: IncomingMessage, response: ServerResponse, token
|
|
|
485
497
|
return send(response, 200, { ok: true })
|
|
486
498
|
}
|
|
487
499
|
|
|
500
|
+
// El plugin registra el servidor MCP en OpenCode con esto (URL por proyecto + token).
|
|
501
|
+
if (url.pathname === "/v1/mcp" && method === "GET") {
|
|
502
|
+
if (!mcp) throw new HttpError(503, mcpError ?? "MCP server not running")
|
|
503
|
+
return send(response, 200, { port: mcp.port, token: mcp.token })
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// events.ingest aceptado en un proyecto → a sus streams MCP (triggers de automations).
|
|
507
|
+
if (url.pathname === "/v1/events" && method === "POST") {
|
|
508
|
+
const directory = typeof body.directory === "string" ? body.directory : ""
|
|
509
|
+
const event = (body.event ?? {}) as Record<string, unknown>
|
|
510
|
+
if (!directory || typeof event.id !== "string" || typeof event.source !== "string" || !event.payload || typeof event.payload !== "object")
|
|
511
|
+
throw new HttpError(400, "directory and event {id, source, payload} are required")
|
|
512
|
+
if (!events) throw new HttpError(503, mcpError ?? "MCP server not running")
|
|
513
|
+
events.publish(directory, {
|
|
514
|
+
id: event.id,
|
|
515
|
+
source: event.source,
|
|
516
|
+
type: typeof event.type === "string" ? event.type : null,
|
|
517
|
+
payload: event.payload as Record<string, unknown>,
|
|
518
|
+
})
|
|
519
|
+
return send(response, 202, { ok: true, streams: events.streams() })
|
|
520
|
+
}
|
|
521
|
+
|
|
488
522
|
if (url.pathname === "/v1/shutdown" && method === "POST") {
|
|
489
523
|
send(response, 200, { ok: true })
|
|
490
524
|
setTimeout(() => void shutdown(0), 50)
|
|
@@ -629,6 +663,49 @@ let controlServer: Server
|
|
|
629
663
|
let hooksServer: Server
|
|
630
664
|
let sweeper: ReturnType<typeof setInterval>
|
|
631
665
|
let closing = false
|
|
666
|
+
let mcp: McpInfo | null = null
|
|
667
|
+
let mcpServer: ReturnType<typeof Bun.serve> | null = null
|
|
668
|
+
let events: EventsServer | null = null
|
|
669
|
+
let mcpError: string | null = null
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* Servidor MCP Events. Puerto y token se reutilizan (mcp.json) para que la entrada MCP que
|
|
673
|
+
* el plugin dio a OpenCode siga valiendo tras reiniciar el daemon; si el puerto está
|
|
674
|
+
* ocupado se toma otro y el plugin lo vuelve a registrar al cargar.
|
|
675
|
+
*/
|
|
676
|
+
function startMcp(): void {
|
|
677
|
+
let stored: Partial<McpInfo> = {}
|
|
678
|
+
try {
|
|
679
|
+
stored = JSON.parse(readFileSync(paths.mcp, "utf8")) as Partial<McpInfo>
|
|
680
|
+
} catch {
|
|
681
|
+
// primera vez
|
|
682
|
+
}
|
|
683
|
+
const token = typeof stored.token === "string" && stored.token.length >= 32 ? stored.token : randomToken(24)
|
|
684
|
+
events = createEventsServer({ version: VERSION, token })
|
|
685
|
+
const serve = (port: number) =>
|
|
686
|
+
Bun.serve({
|
|
687
|
+
hostname: "127.0.0.1",
|
|
688
|
+
port,
|
|
689
|
+
// Los streams de eventos son largos; los heartbeats los mantienen, no un timeout de inactividad.
|
|
690
|
+
idleTimeout: 0,
|
|
691
|
+
fetch: (request) => events!.fetch(request),
|
|
692
|
+
})
|
|
693
|
+
const preferred = Number.isInteger(stored.port) && stored.port! > 0 ? stored.port! : 0
|
|
694
|
+
try {
|
|
695
|
+
try {
|
|
696
|
+
mcpServer = serve(preferred)
|
|
697
|
+
} catch (error) {
|
|
698
|
+
if (preferred === 0) throw error
|
|
699
|
+
log(`mcp: port ${preferred} busy, taking another`)
|
|
700
|
+
mcpServer = serve(0)
|
|
701
|
+
}
|
|
702
|
+
mcp = { port: mcpServer.port!, token }
|
|
703
|
+
writePrivate(paths.mcp, JSON.stringify(mcp))
|
|
704
|
+
} catch (error) {
|
|
705
|
+
mcpError = `MCP server failed: ${String((error as Error).message ?? error)}`
|
|
706
|
+
log(mcpError)
|
|
707
|
+
}
|
|
708
|
+
}
|
|
632
709
|
|
|
633
710
|
async function shutdown(code: number): Promise<never> {
|
|
634
711
|
if (!closing) {
|
|
@@ -643,6 +720,8 @@ async function shutdown(code: number): Promise<never> {
|
|
|
643
720
|
}
|
|
644
721
|
controlServer?.close()
|
|
645
722
|
hooksServer?.close()
|
|
723
|
+
await events?.close().catch(() => undefined)
|
|
724
|
+
mcpServer?.stop(true)
|
|
646
725
|
save()
|
|
647
726
|
for (const file of [paths.info, paths.lock]) {
|
|
648
727
|
try {
|
|
@@ -666,10 +745,13 @@ async function main(): Promise<void> {
|
|
|
666
745
|
hooksServer = createServer(wrap(hooks))
|
|
667
746
|
controlPort = await listen(controlServer)
|
|
668
747
|
hooksPort = await listen(hooksServer)
|
|
748
|
+
startMcp()
|
|
669
749
|
info = { pid: process.pid, port: controlPort, token, version: VERSION, startedAt: Date.now() }
|
|
670
750
|
writePrivate(paths.info, JSON.stringify(info))
|
|
671
751
|
save()
|
|
672
|
-
log(
|
|
752
|
+
log(
|
|
753
|
+
`apex daemon ${VERSION} pid ${process.pid} · control 127.0.0.1:${controlPort} · hooks 127.0.0.1:${hooksPort} · mcp ${mcp ? `127.0.0.1:${mcp.port}` : "off"}`,
|
|
754
|
+
)
|
|
673
755
|
|
|
674
756
|
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, () => void shutdown(0))
|
|
675
757
|
process.on("uncaughtException", (error) => log("uncaught:", error))
|
package/daemon/mcp.ts
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Servidor MCP del daemon con la extensión Events (SEP-3415, protocolo 2026-07-28): lo que
|
|
3
|
+
* llega a `events.ingest` (webhooks verificados, relays, scripts) se publica como el tipo de
|
|
4
|
+
* evento `apex.event`, y una automation de OpenCode se dispara con él:
|
|
5
|
+
*
|
|
6
|
+
* { type: "event", server: "apex", event: "apex.event", args: { source: "github" } }
|
|
7
|
+
*
|
|
8
|
+
* Reparto: apex es la puerta de entrada externa; automations programa y ejecuta.
|
|
9
|
+
*
|
|
10
|
+
* - Un único tipo de evento, solo `push`. `arguments` filtra por `source` y `type` (exactos).
|
|
11
|
+
* - Cada proyecto tiene su URL (`/mcp/<directorio en base64url>`): solo ve sus eventos.
|
|
12
|
+
* - Buffer circular en memoria; el cursor es `<epoch>.<seq>` (epoch = arranque del daemon).
|
|
13
|
+
* Un cursor de otro arranque o ya fuera del buffer reabre con `truncated`.
|
|
14
|
+
*
|
|
15
|
+
* El SDK pone el transporte (createMcpHandler, solo era moderna); `events/list` y
|
|
16
|
+
* `events/stream` van a mano porque el SDK 2.4 aún no trae servidor de Events.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { timingSafeEqual } from "node:crypto"
|
|
20
|
+
import { createMcpHandler, ProtocolError, Server } from "@modelcontextprotocol/server"
|
|
21
|
+
import { z } from "zod"
|
|
22
|
+
|
|
23
|
+
export const EVENT_NAME = "apex.event"
|
|
24
|
+
const EXTENSION = "io.modelcontextprotocol/events"
|
|
25
|
+
const SUBSCRIPTION_ID = "io.modelcontextprotocol/subscriptionId"
|
|
26
|
+
const BUFFER_SIZE = Number(process.env.APEX_MCP_BUFFER ?? 500)
|
|
27
|
+
const HEARTBEAT_MS = Number(process.env.APEX_MCP_HEARTBEAT_MS ?? 15_000)
|
|
28
|
+
// Códigos de la extensión Events.
|
|
29
|
+
const NOT_FOUND = -32023
|
|
30
|
+
const INVALID_PARAMS = -32602
|
|
31
|
+
|
|
32
|
+
/** Lo que recibe la automation en `input.event.data` (y el prompt, como datos no fiables). */
|
|
33
|
+
export interface ApexEventData {
|
|
34
|
+
readonly id: string
|
|
35
|
+
readonly source: string
|
|
36
|
+
readonly type?: string
|
|
37
|
+
readonly payload: Record<string, unknown>
|
|
38
|
+
readonly receivedAt: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface Buffered {
|
|
42
|
+
readonly seq: number
|
|
43
|
+
readonly at: number
|
|
44
|
+
readonly directory: string
|
|
45
|
+
readonly data: ApexEventData
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface Filter {
|
|
49
|
+
readonly source?: string
|
|
50
|
+
readonly type?: string
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface Listener {
|
|
54
|
+
readonly directory: string
|
|
55
|
+
readonly filter: Filter
|
|
56
|
+
readonly push: (event: Buffered) => void
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export const EVENT_TYPE = {
|
|
60
|
+
name: EVENT_NAME,
|
|
61
|
+
description:
|
|
62
|
+
"An event that reached this project through apex: a verified webhook (apex_webhook) or an events.ingest call " +
|
|
63
|
+
"from a script, relay or service. Filter with arguments { source?, type? } (exact match).",
|
|
64
|
+
delivery: ["push"],
|
|
65
|
+
inputSchema: {
|
|
66
|
+
type: "object",
|
|
67
|
+
properties: {
|
|
68
|
+
source: { type: "string", description: "Only events from this source (github, stripe, the webhook's source...)" },
|
|
69
|
+
type: { type: "string", description: "Only events of this type (e.g. pull_request.opened)" },
|
|
70
|
+
},
|
|
71
|
+
additionalProperties: false,
|
|
72
|
+
},
|
|
73
|
+
payloadSchema: {
|
|
74
|
+
type: "object",
|
|
75
|
+
properties: {
|
|
76
|
+
id: { type: "string", description: "Event ID (deduplicated by apex)" },
|
|
77
|
+
source: { type: "string" },
|
|
78
|
+
type: { type: "string" },
|
|
79
|
+
payload: { type: "object", additionalProperties: true, description: "The event body as received (untrusted data)" },
|
|
80
|
+
receivedAt: { type: "string", description: "ISO-8601" },
|
|
81
|
+
},
|
|
82
|
+
required: ["id", "source", "payload", "receivedAt"],
|
|
83
|
+
additionalProperties: false,
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** `/mcp/<base64url(directorio)>`: cada proyecto solo ve sus eventos. */
|
|
88
|
+
export function mcpPath(directory: string): string {
|
|
89
|
+
return `/mcp/${Buffer.from(directory, "utf8").toString("base64url")}`
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function directoryOf(pathname: string): string | null {
|
|
93
|
+
const match = /^\/mcp\/([A-Za-z0-9_-]+)\/?$/.exec(pathname)
|
|
94
|
+
if (!match) return null
|
|
95
|
+
const directory = Buffer.from(match[1]!, "base64url").toString("utf8")
|
|
96
|
+
return directory.length > 0 ? directory : null
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function sameToken(given: string, expected: string): boolean {
|
|
100
|
+
const a = Buffer.from(given)
|
|
101
|
+
const b = Buffer.from(expected)
|
|
102
|
+
return a.length === b.length && timingSafeEqual(a, b)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface EventsServer {
|
|
106
|
+
/** Sirve una petición HTTP (comprueba el token y el directorio de la ruta). */
|
|
107
|
+
readonly fetch: (request: Request) => Promise<Response>
|
|
108
|
+
/** Publica un evento de `directory` a sus streams abiertos (y al buffer, para replay). */
|
|
109
|
+
readonly publish: (directory: string, input: { id: string; source: string; type?: string | null; payload: Record<string, unknown> }) => void
|
|
110
|
+
/** Streams `events/stream` abiertos ahora (el daemon no sale por inactividad con alguno). */
|
|
111
|
+
readonly streams: () => number
|
|
112
|
+
/** Cuándo llegó la última petición MCP (para la inactividad del daemon). */
|
|
113
|
+
readonly lastRequestAt: () => number
|
|
114
|
+
readonly close: () => Promise<void>
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function createEventsServer(options: { version: string; token: string; epoch?: number }): EventsServer {
|
|
118
|
+
const epoch = String(options.epoch ?? Date.now())
|
|
119
|
+
const buffer: Buffered[] = []
|
|
120
|
+
const listeners = new Set<Listener>()
|
|
121
|
+
let seq = 0
|
|
122
|
+
let lastRequestAt = Date.now()
|
|
123
|
+
|
|
124
|
+
const head = () => `${epoch}.${seq}`
|
|
125
|
+
const matches = (listener: Pick<Listener, "directory" | "filter">, event: Buffered) =>
|
|
126
|
+
event.directory === listener.directory &&
|
|
127
|
+
(listener.filter.source === undefined || listener.filter.source === event.data.source) &&
|
|
128
|
+
(listener.filter.type === undefined || listener.filter.type === event.data.type)
|
|
129
|
+
|
|
130
|
+
/** Lo que hay que reenviar al reabrir desde `cursor`, y si se ha perdido algo por el camino. */
|
|
131
|
+
const replay = (cursor: string | null | undefined, maxAgeMs: number | undefined) => {
|
|
132
|
+
if (cursor === null || cursor === undefined) return { events: [] as Buffered[], truncated: false }
|
|
133
|
+
const [from, at] = cursor.split(".")
|
|
134
|
+
const after = Number(at)
|
|
135
|
+
const fresh = (event: Buffered) => maxAgeMs === undefined || event.at >= Date.now() - maxAgeMs
|
|
136
|
+
// De otro arranque del daemon (o ilegible): lo que quede en el buffer, avisando del hueco.
|
|
137
|
+
if (from !== epoch || !Number.isInteger(after)) return { events: buffer.filter(fresh), truncated: true }
|
|
138
|
+
const oldest = buffer[0]?.seq ?? seq + 1
|
|
139
|
+
const events = buffer.filter((event) => event.seq > after && fresh(event))
|
|
140
|
+
return { events, truncated: after < oldest - 1 || events.length < buffer.filter((event) => event.seq > after).length }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const factory = ({ requestInfo }: { requestInfo?: Request }) => {
|
|
144
|
+
const directory = requestInfo ? directoryOf(new URL(requestInfo.url).pathname) : null
|
|
145
|
+
const server = new Server(
|
|
146
|
+
{ name: "apex", version: options.version },
|
|
147
|
+
{
|
|
148
|
+
capabilities: { extensions: { [EXTENSION]: {} } } as never,
|
|
149
|
+
instructions:
|
|
150
|
+
`apex publishes the events that reach this project (verified webhooks, events.ingest) as the "${EVENT_NAME}" ` +
|
|
151
|
+
`event type. Use it as an automation trigger: { type: "event", server: "apex", event: "${EVENT_NAME}", ` +
|
|
152
|
+
`args: { source?, type? } }.`,
|
|
153
|
+
},
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
server.setRequestHandler("events/list", { params: z.object({ cursor: z.string().optional() }).passthrough() }, async () => ({
|
|
157
|
+
events: [EVENT_TYPE],
|
|
158
|
+
}))
|
|
159
|
+
|
|
160
|
+
server.setRequestHandler(
|
|
161
|
+
"events/stream",
|
|
162
|
+
{
|
|
163
|
+
params: z
|
|
164
|
+
.object({
|
|
165
|
+
name: z.string(),
|
|
166
|
+
arguments: z.record(z.unknown()).optional(),
|
|
167
|
+
cursor: z.string().nullish(),
|
|
168
|
+
maxAgeMs: z.number().optional(),
|
|
169
|
+
})
|
|
170
|
+
.passthrough(),
|
|
171
|
+
},
|
|
172
|
+
async (params, ctx) => {
|
|
173
|
+
if (params.name !== EVENT_NAME) throw new ProtocolError(NOT_FOUND, `Unknown event type ${params.name}`)
|
|
174
|
+
if (!directory) throw new ProtocolError(INVALID_PARAMS, "No project in the URL (/mcp/<directory>)")
|
|
175
|
+
const filter = parseFilter(params.arguments ?? {})
|
|
176
|
+
const meta = { [SUBSCRIPTION_ID]: ctx.mcpReq.id }
|
|
177
|
+
// Todo sale por una cola: el replay y lo que llegue en vivo no se adelantan entre sí.
|
|
178
|
+
let chain = Promise.resolve()
|
|
179
|
+
const notify = (method: string, body: Record<string, unknown>) => {
|
|
180
|
+
chain = chain
|
|
181
|
+
.then(() => ctx.mcpReq.notify({ method, params: { ...body, _meta: meta } } as never))
|
|
182
|
+
.catch(() => undefined)
|
|
183
|
+
}
|
|
184
|
+
const toEvent = (event: Buffered) => ({
|
|
185
|
+
eventId: event.data.id,
|
|
186
|
+
name: EVENT_NAME,
|
|
187
|
+
timestamp: event.data.receivedAt,
|
|
188
|
+
data: event.data,
|
|
189
|
+
cursor: `${epoch}.${event.seq}`,
|
|
190
|
+
})
|
|
191
|
+
|
|
192
|
+
const listener: Listener = { directory, filter, push: (event) => notify("notifications/events/event", toEvent(event)) }
|
|
193
|
+
const backlog = replay(params.cursor, params.maxAgeMs)
|
|
194
|
+
listeners.add(listener)
|
|
195
|
+
notify("notifications/events/active", {
|
|
196
|
+
heartbeatMs: HEARTBEAT_MS,
|
|
197
|
+
cursor: params.cursor ?? head(),
|
|
198
|
+
...(backlog.truncated ? { truncated: true } : {}),
|
|
199
|
+
})
|
|
200
|
+
for (const event of backlog.events) if (matches(listener, event)) listener.push(event)
|
|
201
|
+
|
|
202
|
+
const heartbeat = setInterval(() => notify("notifications/events/heartbeat", { cursor: head() }), HEARTBEAT_MS)
|
|
203
|
+
try {
|
|
204
|
+
await new Promise<void>((resolve) => {
|
|
205
|
+
if (ctx.mcpReq.signal.aborted) return resolve()
|
|
206
|
+
ctx.mcpReq.signal.addEventListener("abort", () => resolve(), { once: true })
|
|
207
|
+
})
|
|
208
|
+
} finally {
|
|
209
|
+
clearInterval(heartbeat)
|
|
210
|
+
listeners.delete(listener)
|
|
211
|
+
}
|
|
212
|
+
return {}
|
|
213
|
+
},
|
|
214
|
+
)
|
|
215
|
+
return server
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const handler = createMcpHandler(factory, { legacy: "reject" })
|
|
219
|
+
|
|
220
|
+
return {
|
|
221
|
+
fetch: async (request) => {
|
|
222
|
+
const auth = request.headers.get("authorization") ?? ""
|
|
223
|
+
if (!sameToken(auth, `Bearer ${options.token}`)) return Response.json({ error: "unauthorized" }, { status: 401 })
|
|
224
|
+
if (!directoryOf(new URL(request.url).pathname)) return Response.json({ error: "use /mcp/<directory>" }, { status: 404 })
|
|
225
|
+
lastRequestAt = Date.now()
|
|
226
|
+
return handler.fetch(request)
|
|
227
|
+
},
|
|
228
|
+
publish: (directory, input) => {
|
|
229
|
+
seq++
|
|
230
|
+
const event: Buffered = {
|
|
231
|
+
seq,
|
|
232
|
+
at: Date.now(),
|
|
233
|
+
directory,
|
|
234
|
+
data: {
|
|
235
|
+
id: input.id,
|
|
236
|
+
source: input.source,
|
|
237
|
+
...(typeof input.type === "string" && input.type.length > 0 ? { type: input.type } : {}),
|
|
238
|
+
payload: input.payload,
|
|
239
|
+
receivedAt: new Date().toISOString(),
|
|
240
|
+
},
|
|
241
|
+
}
|
|
242
|
+
buffer.push(event)
|
|
243
|
+
if (buffer.length > BUFFER_SIZE) buffer.shift()
|
|
244
|
+
for (const listener of listeners) if (matches(listener, event)) listener.push(event)
|
|
245
|
+
},
|
|
246
|
+
streams: () => listeners.size,
|
|
247
|
+
lastRequestAt: () => lastRequestAt,
|
|
248
|
+
close: () => handler.close(),
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function parseFilter(args: Record<string, unknown>): Filter {
|
|
253
|
+
const unknown = Object.keys(args).filter((key) => key !== "source" && key !== "type")
|
|
254
|
+
if (unknown.length > 0) throw new ProtocolError(INVALID_PARAMS, `Unknown arguments: ${unknown.join(", ")} (use source, type)`)
|
|
255
|
+
for (const key of ["source", "type"] as const)
|
|
256
|
+
if (args[key] !== undefined && typeof args[key] !== "string") throw new ProtocolError(INVALID_PARAMS, `${key} must be a string`)
|
|
257
|
+
return {
|
|
258
|
+
...(typeof args.source === "string" ? { source: args.source } : {}),
|
|
259
|
+
...(typeof args.type === "string" ? { type: args.type } : {}),
|
|
260
|
+
}
|
|
261
|
+
}
|
package/daemon/shared.ts
CHANGED
|
@@ -24,6 +24,8 @@ export interface DaemonPaths {
|
|
|
24
24
|
/** Rutas, webhooks y servidores — 0600 (lleva secretos de webhooks). */
|
|
25
25
|
readonly registry: string
|
|
26
26
|
readonly log: string
|
|
27
|
+
/** { port, token } del servidor MCP Events — 0600; estable entre arranques (la config MCP de OpenCode lo apunta). */
|
|
28
|
+
readonly mcp: string
|
|
27
29
|
}
|
|
28
30
|
|
|
29
31
|
export function daemonPaths(home = daemonHome()): DaemonPaths {
|
|
@@ -33,6 +35,7 @@ export function daemonPaths(home = daemonHome()): DaemonPaths {
|
|
|
33
35
|
lock: join(home, "daemon.lock"),
|
|
34
36
|
registry: join(home, "registry.json"),
|
|
35
37
|
log: join(home, "daemon.log"),
|
|
38
|
+
mcp: join(home, "mcp.json"),
|
|
36
39
|
}
|
|
37
40
|
}
|
|
38
41
|
|
|
@@ -45,6 +48,12 @@ export interface DaemonInfo {
|
|
|
45
48
|
readonly startedAt: number
|
|
46
49
|
}
|
|
47
50
|
|
|
51
|
+
/** Servidor MCP Events del daemon (loopback, Bearer token). */
|
|
52
|
+
export interface McpInfo {
|
|
53
|
+
readonly port: number
|
|
54
|
+
readonly token: string
|
|
55
|
+
}
|
|
56
|
+
|
|
48
57
|
/** Cómo llama el daemon al RPC `events.ingest` de un proyecto (el password nunca sale de la máquina). */
|
|
49
58
|
export interface ServerTarget {
|
|
50
59
|
readonly baseUrl: string
|
package/docs/ADVISOR.md
CHANGED
|
@@ -79,9 +79,18 @@ the original permission is left untouched: you get the normal prompt.
|
|
|
79
79
|
- **One advisor session per session tree.** Your main session and all its subagents share
|
|
80
80
|
it, so the advisor sees every earlier request and answer. The session is kept, which also
|
|
81
81
|
makes it a complete audit trail of what was asked and decided.
|
|
82
|
+
- **Named after the session it advises.** The advisor session's title is
|
|
83
|
+
`apex advisor → <target title> [<target id>]`, where the target is the root of the tree it
|
|
84
|
+
guards. So you can tell which advisor decides for which conversation at a glance. If the
|
|
85
|
+
target has no title yet, it reads `apex advisor → sesión <target id>`. The short id in
|
|
86
|
+
brackets is stable even when you rename the target, and disambiguates two targets that share
|
|
87
|
+
a title. Every permission evaluation refreshes the title — even when the verdict is served
|
|
88
|
+
from the 10-minute decision cache — so a rename is picked up on the very next permission
|
|
89
|
+
prompt, with no model round trip.
|
|
82
90
|
- **Archived automatically.** It would otherwise clutter the desktop app's session list — you
|
|
83
91
|
never need to open it by hand. It still exists and is still a real audit trail; it just
|
|
84
|
-
doesn't show up in the default list.
|
|
92
|
+
doesn't show up in the default list. (If you want to see it, unarchive it; the distinctive
|
|
93
|
+
title makes it identifiable in any view.)
|
|
85
94
|
|
|
86
95
|
## `decisive`
|
|
87
96
|
|
package/docs/CONFIG.md
CHANGED
|
@@ -81,18 +81,20 @@ 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, "endpoints": true }
|
|
84
|
+
"modules": { "redact": true, "cred": true, "events": true, "advisor": true, "guard": false, "browser": false, "tempAccess": true, "endpoints": true, "automations": true }
|
|
85
85
|
```
|
|
86
86
|
|
|
87
87
|
| Module | Default when the key is omitted |
|
|
88
88
|
| --- | --- |
|
|
89
89
|
| `redact` | on |
|
|
90
|
+
| `cred` | on |
|
|
90
91
|
| `events` | on |
|
|
91
92
|
| `advisor` | on |
|
|
92
93
|
| `guard` | **off** (it can block the agent if its rules are wrong, so you opt in) |
|
|
93
94
|
| `browser` | **off** since 0.3.0 (deprecated: use OpenCode's [browse](https://opencode.ai/product/browse)) |
|
|
94
95
|
| `tempAccess` | on |
|
|
95
96
|
| `endpoints` | on (the daemon starts only when an `apex_webhook` / `apex_tunnel` tool is used, see [ENDPOINTS.md](ENDPOINTS.md)) |
|
|
97
|
+
| `automations` | on when `events` and `endpoints` are on: adds the MCP server `apex` whose `apex.event` triggers OpenCode automations, and starts the daemon on load (see [EVENTS.md](EVENTS.md#automations-apexevent-as-a-trigger-opencode--241)) |
|
|
96
98
|
|
|
97
99
|
There is no `<module>.enabled` key. A legacy `events.enabled` is ignored and logs a
|
|
98
100
|
warning. So does `events.listener`: the HTTP listener was removed in 0.2.0, see
|