opencode-apex 0.1.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/events.ts ADDED
@@ -0,0 +1,934 @@
1
+ /**
2
+ * Apex Events — RPC-based generic event ingestion + subscription + delivery system.
3
+ *
4
+ * Replaces: webhook receiver (Bun.serve), SSE client, Telegram long-poll,
5
+ * cron scheduler, file watchers, and reaction system.
6
+ *
7
+ * New architecture:
8
+ * - Generic `ingest` RPC for external event submission
9
+ * - Internal event bus emission (`apex:event`)
10
+ * - Subscription registry with filter evaluation (reuses rules.ts condition evaluator)
11
+ * - Delivery via session.switchAgent + session.prompt
12
+ * - Deduplication by eventID with TTL
13
+ * - Static subscriptions from config + dynamic from storage
14
+ */
15
+
16
+ import { homedir } from "node:os"
17
+ import { Effect, Stream } from "effect"
18
+ import type { Scope } from "effect"
19
+ import { emit, subscribe } from "./core/bus.js"
20
+ import type { Plugin } from "@opencode/plugin/effect"
21
+ import type { ApexConfig, EventsConfig, EventSubscription } from "./core/config.js"
22
+
23
+ export type { EventSubscription } from "./core/config.js"
24
+ import { evaluateCondition, type RuleCondition } from "./core/conditions.js"
25
+ import { readOrCreateTemplate } from "./core/templates.js"
26
+ import { listenerUrls, startIngestListener } from "./core/ingest-listener.js"
27
+ import { ADVISOR_AGENT_ID } from "./core/advisor-agent.js"
28
+
29
+ /** JSON value type accepted by plugin storage */
30
+ type StorageJson = Parameters<Plugin.Context["storage"]["set"]>[1]
31
+
32
+ // ============================================================================
33
+ // Types
34
+ // ============================================================================
35
+
36
+ /** Event subscription stored in ctx.storage */
37
+ /** Events module configuration */
38
+ export type { EventsConfig } from "./core/config.js"
39
+
40
+ /** Ingest RPC input */
41
+ export interface IngestInput {
42
+ /** Event source identifier (e.g., "github", "webhook", "custom") */
43
+ source: string
44
+ /** Optional event type/category */
45
+ type?: string
46
+ /** Event payload */
47
+ readonly payload: Record<string, unknown>
48
+ /** Optional event ID for deduplication (auto-generated if not provided) */
49
+ readonly eventID?: string
50
+ }
51
+
52
+ /** Ingest RPC output */
53
+ export interface IngestOutput {
54
+ /** Whether event was accepted (always true unless validation fails) */
55
+ accepted: boolean
56
+ /** Event ID (generated or provided) */
57
+ eventID: string
58
+ /** Subscription IDs that received the event */
59
+ delivered: string[]
60
+ }
61
+
62
+ /** Internal event emitted on bus */
63
+ interface InternalEvent {
64
+ eventID: string
65
+ source: string
66
+ type: string | undefined
67
+ payload: Record<string, unknown>
68
+ location: string
69
+ timestamp: number
70
+ }
71
+
72
+ // ============================================================================
73
+ // Constants
74
+ // ============================================================================
75
+
76
+ const SUBSCRIPTIONS_STORAGE_KEY = "apex:subscriptions"
77
+ const DEDUP_TTL_MS = 5 * 60 * 1000 // 5 minutes
78
+ const DEFAULT_DELIVERY: "queue" | "steer" = "queue"
79
+ const DEFAULT_DELIVER_AS: "synthetic" | "prompt" = "prompt"
80
+ const DEFAULT_RESUME = false
81
+ const DEFAULT_PRIORITY = 0
82
+
83
+ // In-memory deduplication cache: eventID -> timestamp
84
+ const dedupCache = new Map<string, number>()
85
+
86
+ // ---------------------------------------------------------------------------
87
+ // Auto-vinculación de suscripciones a la sesión principal
88
+ // ---------------------------------------------------------------------------
89
+
90
+ const AUTO_SESSION_STORAGE_KEY = "apex:events:autoSession"
91
+ const PUBLIC_URL_STORAGE_KEY = "apex:events:publicUrl"
92
+
93
+ /** URL pública fijada en RUNTIME por el agente (túnel). Tiene prioridad sobre la config. */
94
+ let runtimePublicUrl: string | null = null
95
+
96
+ /** Sesión principal activa (raíz, no advisor). null si no hay ninguna. */
97
+ let autoBoundSessionID: string | null = null
98
+
99
+ /** Endpoint de callback anunciado al agente (lo fija register). */
100
+ export interface CallbackEndpoint {
101
+ readonly listenerEnabled: boolean
102
+ readonly host?: string
103
+ readonly port?: number
104
+ /** URLs alcanzables del listener (loopback, LAN…). */
105
+ readonly urls: readonly string[]
106
+ /** URL pública declarada (túnel) — la que deben usar emisores externos. */
107
+ readonly publicUrl?: string
108
+ /** ¿El listener exige token? */
109
+ readonly tokenRequired: boolean
110
+ /** Token del listener (el agente lo necesita para construir el callback). */
111
+ readonly token?: string
112
+ /** Ruta del RPC autenticado equivalente. */
113
+ readonly rpcPath: string
114
+ }
115
+
116
+ let callbackEndpoint: CallbackEndpoint | null = null
117
+
118
+ /** Endpoint de callback actual (diagnóstico, tool y RPC). */
119
+ export function getCallbackEndpoint(): CallbackEndpoint | null {
120
+ if (!callbackEndpoint) return null
121
+ const publicUrl = runtimePublicUrl ?? callbackEndpoint.publicUrl
122
+ return { ...callbackEndpoint, publicUrl }
123
+ }
124
+
125
+ /**
126
+ * Fija (o limpia) la URL pública en runtime y la persiste.
127
+ * Lo usa la tool `apex_set_callback_url` (el agente monta el túnel y la anuncia).
128
+ */
129
+ export async function setRuntimePublicUrl(ctx: Plugin.Context, url: string | null): Promise<void> {
130
+ runtimePublicUrl = url && url.trim().length > 0 ? url.trim() : null
131
+ try {
132
+ await Effect.runPromise(ctx.storage.set(PUBLIC_URL_STORAGE_KEY, (runtimePublicUrl ?? "") as never))
133
+ } catch {
134
+ // persistencia best-effort
135
+ }
136
+ }
137
+
138
+ /** Diagnóstico/tests. */
139
+ export function getAutoBoundSession(): string | null {
140
+ return autoBoundSessionID
141
+ }
142
+
143
+ /** Fija (o limpia) la sesión principal y la persiste. */
144
+ async function setAutoBoundSession(ctx: Plugin.Context, sessionID: string | null): Promise<void> {
145
+ autoBoundSessionID = sessionID
146
+ try {
147
+ await Effect.runPromise(
148
+ ctx.storage.set(AUTO_SESSION_STORAGE_KEY, (sessionID ?? "") as never),
149
+ )
150
+ } catch {
151
+ // la persistencia es best-effort
152
+ }
153
+ }
154
+
155
+ /**
156
+ * ¿Esta sesión puede ser la principal?
157
+ * Debe ser RAÍZ (sin parentID) y no ser una sesión del advisor.
158
+ */
159
+ export function isPrimaryCandidate(info: {
160
+ parentID?: string | null
161
+ agent?: string | null
162
+ }): boolean {
163
+ if (info.parentID) return false
164
+ if (info.agent === ADVISOR_AGENT_ID) return false
165
+ return true
166
+ }
167
+
168
+ /**
169
+ * Resuelve la sesión destino de una suscripción:
170
+ * `sessionID` explícito → ese; vacío/null/ausente → la sesión principal activa.
171
+ */
172
+ export function resolveTargetSession(subscription: { sessionID?: string | null }): string | null {
173
+ const explicit = typeof subscription.sessionID === "string" ? subscription.sessionID.trim() : ""
174
+ if (explicit.length > 0) return explicit
175
+ return autoBoundSessionID
176
+ }
177
+
178
+ /** Procesa eventos de ciclo de vida para (des)vincular la sesión principal. */
179
+ export async function handleLifecycleEvent(ctx: Plugin.Context, event: { type: string; data: unknown }): Promise<void> {
180
+ const data = (event.data ?? {}) as {
181
+ sessionID?: string
182
+ parentID?: string | null
183
+ agent?: string | null
184
+ }
185
+ const sessionID = data.sessionID
186
+ if (!sessionID) return
187
+
188
+ if (event.type === "session.created") {
189
+ if (!isPrimaryCandidate(data)) return
190
+ if (autoBoundSessionID === sessionID) return
191
+ await setAutoBoundSession(ctx, sessionID)
192
+ console.log(`[Apex Events] suscripciones auto vinculadas a la sesión principal ${sessionID}`)
193
+ return
194
+ }
195
+
196
+ if (event.type === "session.deleted") {
197
+ if (autoBoundSessionID !== sessionID) return
198
+ await setAutoBoundSession(ctx, null)
199
+ console.log(`[Apex Events] sesión principal ${sessionID} cerrada: suscripciones auto desvinculadas`)
200
+ }
201
+ }
202
+
203
+ // Module-level ingest handler, set by register() and consumed by index.ts RPC wiring.
204
+ // Avoids the globalThis hack and lets register() capture the configured routing policy.
205
+ export let ingestHandler: ((input: IngestInput) => Promise<IngestOutput>) | null = null
206
+
207
+ // ============================================================================
208
+ // Helper Functions
209
+ // ============================================================================
210
+
211
+ /** Generate a unique event ID */
212
+ function generateEventID(): string {
213
+ return crypto.randomUUID()
214
+ }
215
+
216
+ /** Clean expired entries from deduplication cache */
217
+ function cleanDedupCache(): void {
218
+ const now = Date.now()
219
+ for (const [eventID, timestamp] of dedupCache.entries()) {
220
+ if (now - timestamp > DEDUP_TTL_MS) {
221
+ dedupCache.delete(eventID)
222
+ }
223
+ }
224
+ }
225
+
226
+ /** Check if eventID was recently seen (within TTL) */
227
+ function isDuplicate(eventID: string): boolean {
228
+ cleanDedupCache()
229
+ return dedupCache.has(eventID)
230
+ }
231
+
232
+ /** Mark eventID as seen */
233
+ function markSeen(eventID: string): void {
234
+ dedupCache.set(eventID, Date.now())
235
+ }
236
+
237
+ /** Load subscriptions from storage */
238
+ async function loadSubscriptions(ctx: Plugin.Context): Promise<EventSubscription[]> {
239
+ try {
240
+ const stored = await Effect.runPromise(ctx.storage.get(SUBSCRIPTIONS_STORAGE_KEY))
241
+ if (stored && Array.isArray(stored)) {
242
+ return stored as EventSubscription[]
243
+ }
244
+ } catch {
245
+ // Ignore storage errors
246
+ }
247
+ return []
248
+ }
249
+
250
+ /** Save subscriptions to storage */
251
+ async function saveSubscriptions(ctx: Plugin.Context, subscriptions: EventSubscription[]): Promise<void> {
252
+ try {
253
+ await Effect.runPromise(
254
+ ctx.storage.set(SUBSCRIPTIONS_STORAGE_KEY, subscriptions as unknown as StorageJson),
255
+ )
256
+ } catch (error) {
257
+ console.error("[Apex Events] Failed to save subscriptions:", error)
258
+ }
259
+ }
260
+
261
+ /** Render prompt template with event data */
262
+ /** Plantilla por defecto que se escribe si el fichero no existe. */
263
+ export const DEFAULT_EVENT_PROMPT_TEMPLATE = `Evento {{type}} de {{source}} ({{eventID}})
264
+ Payload: {{payload}}
265
+ `
266
+
267
+ /**
268
+ * Resuelve el texto de la plantilla: fichero si `promptTemplateFile` está
269
+ * definido (solo rutas relativas; se crea con defaults si no existe), si no
270
+ * el texto inline. Si la ruta es inválida se degrada al inline y se avisa.
271
+ */
272
+ export function resolveTemplate(
273
+ ctx: Plugin.Context,
274
+ subscription: EventSubscription,
275
+ ): string | undefined {
276
+ const file = subscription.promptTemplateFile
277
+ if (!file) return subscription.promptTemplate
278
+
279
+ // Solo rutas relativas (proyecto o ~/home); si no existe se crea con defaults.
280
+ const { content } = readOrCreateTemplate(
281
+ file,
282
+ { projectDir: ctx.location?.directory ?? process.cwd(), home: homedir() },
283
+ DEFAULT_EVENT_PROMPT_TEMPLATE,
284
+ )
285
+ if (content !== null) return content
286
+ return subscription.promptTemplate
287
+ }
288
+
289
+ function renderPromptTemplate(template: string, event: InternalEvent): string {
290
+ return template
291
+ .replace(/\{\{eventID\}\}/g, event.eventID)
292
+ .replace(/\{\{source\}\}/g, event.source)
293
+ .replace(/\{\{type\}\}/g, event.type ?? "")
294
+ .replace(/\{\{payload\.([^}]+)\}\}/g, (_match, path) => {
295
+ const value = path.split(".").reduce((acc: unknown, key: string) => {
296
+ return (acc as Record<string, unknown>)?.[key]
297
+ }, event.payload)
298
+ if (value === undefined || value === null) return ""
299
+ // Los strings se insertan tal cual (sin comillas); el resto en JSON.
300
+ return typeof value === "string" ? value : JSON.stringify(value)
301
+ })
302
+ }
303
+
304
+ /** Get default prompt for event */
305
+ function getDefaultPrompt(event: InternalEvent): string {
306
+ return JSON.stringify({
307
+ eventID: event.eventID,
308
+ source: event.source,
309
+ type: event.type,
310
+ payload: event.payload,
311
+ timestamp: new Date(event.timestamp).toISOString(),
312
+ }, null, 2)
313
+ }
314
+
315
+ /** Evaluate subscription filters against event context */
316
+ function matchesSubscription(subscription: EventSubscription, event: InternalEvent): boolean {
317
+ if (!subscription.enabled) return false
318
+ if (subscription.filters.length === 0) return true
319
+
320
+ const context: Record<string, unknown> = {
321
+ source: event.source,
322
+ type: event.type,
323
+ payload: event.payload,
324
+ location: event.location,
325
+ eventID: event.eventID,
326
+ timestamp: event.timestamp,
327
+ }
328
+
329
+ return subscription.filters.every((condition) => evaluateCondition(condition, context))
330
+ }
331
+
332
+ /** Deliver event to a single subscription */
333
+ export async function deliverToSubscription(
334
+ ctx: Plugin.Context,
335
+ subscription: EventSubscription,
336
+ event: InternalEvent,
337
+ ): Promise<boolean> {
338
+ const targetSession = resolveTargetSession(subscription)
339
+ if (!targetSession) {
340
+ console.warn(
341
+ `[Apex Events] suscripción ${subscription.id} sin sesión destino (sessionID vacío y sin sesión principal activa)`,
342
+ )
343
+ return false
344
+ }
345
+
346
+ try {
347
+ // Switch agent if specified
348
+ if (subscription.agent) {
349
+ await Effect.runPromise(
350
+ ctx.session.switchAgent({
351
+ sessionID: targetSession as never,
352
+ agent: subscription.agent as never,
353
+ }),
354
+ )
355
+ }
356
+
357
+ // Render prompt (fichero de plantilla con prioridad sobre el inline)
358
+ const template = resolveTemplate(ctx, subscription)
359
+ const promptText = template
360
+ ? renderPromptTemplate(template, event)
361
+ : getDefaultPrompt(event)
362
+
363
+ // Entrega según el modo elegido
364
+ if (subscription.deliverAs === "synthetic") {
365
+ // Mensaje sintético. `resume` controla si se despierta el bucle del agente:
366
+ // resume=true → execution.wake → el modelo procesa el mensaje
367
+ // resume=false → inyección pasiva (solo aparece en la sesión)
368
+ await Effect.runPromise(
369
+ ctx.session.synthetic({
370
+ sessionID: targetSession as never,
371
+ text: promptText,
372
+ description: `apex event: ${event.type ?? event.source}`,
373
+ delivery: subscription.delivery,
374
+ resume: subscription.resume ?? DEFAULT_RESUME,
375
+ } as never),
376
+ )
377
+ } else {
378
+ // User prompt: entra en la cola/inbox de la sesión
379
+ await Effect.runPromise(
380
+ ctx.session.prompt({
381
+ sessionID: targetSession as never,
382
+ text: promptText,
383
+ delivery: subscription.delivery,
384
+ } as never),
385
+ )
386
+ }
387
+
388
+ return true
389
+ } catch (error) {
390
+ console.error(`[Apex Events] Delivery failed for subscription ${subscription.id}:`, error)
391
+ return false
392
+ }
393
+ }
394
+
395
+ /** Process event delivery according to routing policy */
396
+ async function processDelivery(
397
+ ctx: Plugin.Context,
398
+ subscriptions: EventSubscription[],
399
+ event: InternalEvent,
400
+ routing: "first" | "all",
401
+ ): Promise<string[]> {
402
+ // Find matching subscriptions con sesión destino resoluble
403
+ const matching = subscriptions.filter(
404
+ (sub) => matchesSubscription(sub, event) && resolveTargetSession(sub) !== null,
405
+ )
406
+
407
+ if (matching.length === 0) {
408
+ return []
409
+ }
410
+
411
+ // Sort by priority (highest first)
412
+ matching.sort((a, b) => b.priority - a.priority)
413
+
414
+ const delivered: string[] = []
415
+
416
+ if (routing === "first") {
417
+ // Only deliver to highest priority match
418
+ const top = matching[0]
419
+ if (top) {
420
+ const success = await deliverToSubscription(ctx, top, event)
421
+ if (success) {
422
+ delivered.push(top.id)
423
+ }
424
+ }
425
+ } else {
426
+ // Fan-out to all matches
427
+ await Promise.all(
428
+ matching.map(async (sub) => {
429
+ const success = await deliverToSubscription(ctx, sub, event)
430
+ if (success) {
431
+ delivered.push(sub.id)
432
+ }
433
+ }),
434
+ )
435
+ }
436
+
437
+ return delivered
438
+ }
439
+
440
+ // ============================================================================
441
+ // Tools (Effect Schema pattern from awareness.ts)
442
+ // ============================================================================
443
+
444
+ /**
445
+ * Tool: apex_callback_endpoint — informa al agente de DÓNDE recibirá los
446
+ * mensajes (URLs del listener, URL pública/túnel, token y ruta del RPC).
447
+ */
448
+ function registerCallbackEndpointTool(ctx: Plugin.Context): Effect.Effect<void, never, Scope.Scope> {
449
+ return Effect.gen(function* () {
450
+ yield* ctx.tool.transform((editor) => {
451
+ editor.add({
452
+ name: "apex_callback_endpoint",
453
+ description:
454
+ "Devuelve el endpoint donde esta sesión recibirá los eventos: URLs del listener HTTP plano " +
455
+ "(loopback/LAN), la URL pública (túnel) si está declarada, el token y la ruta del RPC autenticado. " +
456
+ "Úsala antes de configurar un callback desde un script, otra máquina o un túnel.",
457
+ input: { type: "object", properties: {}, additionalProperties: false },
458
+ output: {
459
+ type: "object",
460
+ properties: {
461
+ listenerEnabled: { type: "boolean" },
462
+ urls: { type: "array", items: { type: "string" }, description: "URLs alcanzables del listener" },
463
+ publicUrl: { type: "string", description: "URL pública/túnel a usar desde fuera (si está declarada)" },
464
+ recommended: { type: "string", description: "URL que deben usar los emisores" },
465
+ tokenRequired: { type: "boolean" },
466
+ token: { type: "string", description: "Token del listener (si aplica)" },
467
+ rpcPath: { type: "string", description: "RPC autenticado equivalente" },
468
+ authHint: { type: "string" },
469
+ },
470
+ additionalProperties: false,
471
+ },
472
+ execute: () =>
473
+ Effect.sync(() => {
474
+ const endpoint = getCallbackEndpoint() ?? {
475
+ listenerEnabled: false,
476
+ urls: [],
477
+ tokenRequired: false,
478
+ rpcPath: "/api/rpc/apex/events.ingest",
479
+ }
480
+ const recommended =
481
+ endpoint.publicUrl && endpoint.publicUrl.length > 0
482
+ ? endpoint.publicUrl
483
+ : (endpoint.urls[0] ?? "")
484
+ return {
485
+ output: {
486
+ ...endpoint,
487
+ recommended,
488
+ authHint: endpoint.listenerEnabled
489
+ ? "Listener plano: sin credenciales del servidor (token propio si tokenRequired)"
490
+ : "Listener desactivado: usa el RPC con Basic auth (opencode:<password> del fichero de registro)",
491
+ },
492
+ }
493
+ }),
494
+ })
495
+ })
496
+ })
497
+ }
498
+
499
+ /**
500
+ * Tool: apex_set_callback_url — el agente anuncia (o limpia) la URL pública
501
+ * desde la que recibirá los mensajes. Pensada para el flujo autónomo:
502
+ * el agente levanta el túnel (cloudflared/ngrok), captura la URL y la registra.
503
+ */
504
+ function registerSetCallbackUrlTool(ctx: Plugin.Context): Effect.Effect<void, never, Scope.Scope> {
505
+ return Effect.gen(function* () {
506
+ yield* ctx.tool.transform((editor) => {
507
+ editor.add({
508
+ name: "apex_set_callback_url",
509
+ description:
510
+ "Fija (o limpia) la URL pública desde la que esta sesión recibirá los eventos — p. ej. la URL " +
511
+ "de un túnel que acabas de levantar con cloudflared/ngrok. Pásala también a quien vaya a notificar. " +
512
+ "Usa null para limpiarla al terminar. Precedencia: runtime > config.",
513
+ input: {
514
+ type: "object",
515
+ properties: {
516
+ url: {
517
+ type: ["string", "null"],
518
+ description: "URL pública (p. ej. https://x.trycloudflare.com/ingest) o null para limpiar",
519
+ },
520
+ },
521
+ required: ["url"],
522
+ additionalProperties: false,
523
+ },
524
+ output: {
525
+ type: "object",
526
+ properties: {
527
+ publicUrl: { type: "string" },
528
+ recommended: { type: "string" },
529
+ listenerEnabled: { type: "boolean" },
530
+ urls: { type: "array", items: { type: "string" } },
531
+ },
532
+ additionalProperties: false,
533
+ },
534
+ execute: (rawInput: unknown) =>
535
+ Effect.promise(async () => {
536
+ const input = rawInput as { url?: string | null }
537
+ const next = input.url === null || input.url === undefined || input.url === "" ? null : input.url
538
+ await setRuntimePublicUrl(ctx, next)
539
+ const endpoint = getCallbackEndpoint()
540
+ return {
541
+ output: {
542
+ publicUrl: endpoint?.publicUrl ?? "",
543
+ recommended: endpoint?.publicUrl ?? endpoint?.urls[0] ?? "",
544
+ listenerEnabled: endpoint?.listenerEnabled ?? false,
545
+ urls: [...(endpoint?.urls ?? [])],
546
+ },
547
+ }
548
+ }),
549
+ })
550
+ })
551
+ })
552
+ }
553
+
554
+ /** Tool: apex_subscribe — create a new event subscription */
555
+ function registerSubscribeTool(ctx: Plugin.Context): Effect.Effect<void, never, Scope.Scope> {
556
+ return Effect.gen(function* () {
557
+ yield* ctx.tool.transform((editor) => {
558
+ editor.add({
559
+ name: "apex_subscribe",
560
+ description: "Create an event subscription with filters. Captures sessionID from execution context.",
561
+ input: {
562
+ type: "object",
563
+ properties: {
564
+ filters: {
565
+ type: "array",
566
+ description: "Filter conditions to match events",
567
+ items: {
568
+ type: "object",
569
+ properties: {
570
+ field: { type: "string" },
571
+ operator: {
572
+ type: "string",
573
+ enum: ["equals", "contains", "matches", "gt", "lt", "in", "notIn", "exists", "notExists"],
574
+ },
575
+ value: {},
576
+ pattern: { type: "string" },
577
+ },
578
+ required: ["field", "operator"],
579
+ additionalProperties: false,
580
+ },
581
+ },
582
+ agent: { type: "string", description: "Restrict subscription to an agent" },
583
+ promptTemplate: { type: "string", description: "Inline prompt template with {{payload.x}}, {{source}}, {{type}}, {{eventID}} placeholders" },
584
+ promptTemplateFile: { type: "string", description: "Path to a prompt template file (takes priority over promptTemplate)" },
585
+ deliverAs: { type: "string", enum: ["synthetic", "prompt"], description: "Deliver as synthetic message or user prompt (default prompt)" },
586
+ resume: { type: "boolean", description: "Synthetic only: wake the agent loop so the model processes the message (default false = passive)" },
587
+ delivery: { type: "string", enum: ["queue", "steer"], description: "Inbox delivery mode when deliverAs=prompt (default queue)" },
588
+ priority: { type: "number", description: "Subscription priority" },
589
+ },
590
+ additionalProperties: false,
591
+ },
592
+ output: {
593
+ type: "object",
594
+ properties: { id: { type: "string" } },
595
+ required: ["id"],
596
+ },
597
+ execute: (rawInput: unknown, toolCtx: { sessionID: string }) =>
598
+ Effect.promise(async () => {
599
+ const input = rawInput as {
600
+ filters?: RuleCondition[]
601
+ agent?: string
602
+ promptTemplate?: string
603
+ promptTemplateFile?: string
604
+ deliverAs?: "synthetic" | "prompt"
605
+ resume?: boolean
606
+ delivery?: "queue" | "steer"
607
+ priority?: number
608
+ }
609
+ const sessionID = toolCtx.sessionID
610
+ if (!sessionID) {
611
+ throw new Error("No sessionID available in tool context")
612
+ }
613
+
614
+ const subscriptions = await loadSubscriptions(ctx)
615
+ const id = `sub_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`
616
+
617
+ const subscription: EventSubscription = {
618
+ id,
619
+ sessionID,
620
+ agent: input.agent,
621
+ filters: input.filters ?? [],
622
+ promptTemplate: input.promptTemplate,
623
+ promptTemplateFile: input.promptTemplateFile,
624
+ deliverAs: input.deliverAs ?? DEFAULT_DELIVER_AS,
625
+ resume: input.resume ?? DEFAULT_RESUME,
626
+ delivery: input.delivery ?? DEFAULT_DELIVERY,
627
+ priority: input.priority ?? DEFAULT_PRIORITY,
628
+ enabled: true,
629
+ readonly: false,
630
+ }
631
+
632
+ subscriptions.push(subscription)
633
+ await saveSubscriptions(ctx, subscriptions)
634
+
635
+ return { output: { id } }
636
+ })
637
+ })
638
+ })
639
+ })
640
+ }
641
+
642
+ /** Tool: apex_unsubscribe — remove an event subscription */
643
+ function registerUnsubscribeTool(ctx: Plugin.Context): Effect.Effect<void, never, Scope.Scope> {
644
+ return Effect.gen(function* () {
645
+ yield* ctx.tool.transform((editor) => {
646
+ editor.add({
647
+ name: "apex_unsubscribe",
648
+ description: "Remove an event subscription by ID",
649
+ input: {
650
+ type: "object",
651
+ properties: { id: { type: "string", description: "Subscription ID to remove" } },
652
+ required: ["id"],
653
+ additionalProperties: false,
654
+ },
655
+ output: {
656
+ type: "object",
657
+ properties: { success: { type: "boolean" } },
658
+ required: ["success"],
659
+ },
660
+ execute: (rawInput: unknown) =>
661
+ Effect.promise(async () => {
662
+ const input = rawInput as { id: string }
663
+ const subscriptions = await loadSubscriptions(ctx)
664
+ const index = subscriptions.findIndex((s) => s.id === input.id)
665
+
666
+ if (index === -1) {
667
+ return { output: { success: false } }
668
+ }
669
+
670
+ // Prevent deletion of static subscriptions
671
+ const sub = subscriptions[index]
672
+ if (sub && sub.readonly) {
673
+ throw new Error("Cannot unsubscribe from static subscription (readonly)")
674
+ }
675
+
676
+ subscriptions.splice(index, 1)
677
+ await saveSubscriptions(ctx, subscriptions)
678
+
679
+ return { output: { success: true } }
680
+ }),
681
+ })
682
+ })
683
+ })
684
+ }
685
+
686
+ /** Tool: apex_list_subscriptions — list all subscriptions (static marked readonly) */
687
+ function registerListSubscriptionsTool(ctx: Plugin.Context): Effect.Effect<void, never, Scope.Scope> {
688
+ return Effect.gen(function* () {
689
+ yield* ctx.tool.transform((editor) => {
690
+ editor.add({
691
+ name: "apex_list_subscriptions",
692
+ description: "List all event subscriptions. Static subscriptions from config are marked readonly.",
693
+ input: { type: "object", properties: {}, additionalProperties: false },
694
+ output: {
695
+ type: "object",
696
+ properties: {
697
+ subscriptions: { type: "array", items: { type: "object" } },
698
+ },
699
+ required: ["subscriptions"],
700
+ },
701
+ execute: () =>
702
+ Effect.promise(async () => {
703
+ const subscriptions = await loadSubscriptions(ctx)
704
+ return { output: { subscriptions } }
705
+ }),
706
+ })
707
+ })
708
+ })
709
+ }
710
+
711
+ // ============================================================================
712
+ // RPC Handler: ingest
713
+ // ============================================================================
714
+
715
+ /** Handle ingest RPC call */
716
+ async function handleIngest(
717
+ ctx: Plugin.Context,
718
+ input: IngestInput,
719
+ staticSubscriptions: EventSubscription[],
720
+ routing: "first" | "all",
721
+ ): Promise<IngestOutput> {
722
+ // Validate input
723
+ if (!input.source || typeof input.source !== "string") {
724
+ throw new Error("Invalid input: 'source' is required and must be a string")
725
+ }
726
+ if (!input.payload || typeof input.payload !== "object") {
727
+ throw new Error("Invalid input: 'payload' is required and must be an object")
728
+ }
729
+
730
+ // Generate or use provided eventID
731
+ const eventID = input.eventID ?? generateEventID()
732
+
733
+ // Deduplication check
734
+ if (isDuplicate(eventID)) {
735
+ // Idempotent: return previous result shape with empty delivered
736
+ return { accepted: true, eventID, delivered: [] }
737
+ }
738
+
739
+ // Mark as seen
740
+ markSeen(eventID)
741
+
742
+ // Load dynamic subscriptions
743
+ const dynamicSubscriptions = await loadSubscriptions(ctx)
744
+
745
+ // Merge static + dynamic (static first, then dynamic)
746
+ const allSubscriptions = [...staticSubscriptions, ...dynamicSubscriptions]
747
+
748
+ // Create internal event
749
+ const internalEvent: InternalEvent = {
750
+ eventID,
751
+ source: input.source,
752
+ type: input.type,
753
+ payload: input.payload,
754
+ location: ctx.location?.directory ?? "unknown",
755
+ timestamp: Date.now(),
756
+ }
757
+
758
+ // Emit on internal bus
759
+ await emit("apex:event", internalEvent, "apex-events")
760
+
761
+ // Process delivery using the routing policy captured from config in register()
762
+ const delivered = await processDelivery(ctx, allSubscriptions, internalEvent, routing)
763
+
764
+ return { accepted: true, eventID, delivered }
765
+ }
766
+
767
+ // ============================================================================
768
+ // Main Register Function
769
+ // ============================================================================
770
+
771
+ /** Create default events configuration */
772
+ export function createDefaultEventsConfig(): EventsConfig {
773
+ return {
774
+ routing: "all",
775
+ subscriptions: [],
776
+ listener: { enabled: false, host: "127.0.0.1", port: 4599 },
777
+ }
778
+ }
779
+
780
+ /** Register events module (Effect-native) */
781
+ export function register(
782
+ ctx: Plugin.Context,
783
+ config: ApexConfig,
784
+ ): Effect.Effect<void, never, Scope.Scope> {
785
+ return Effect.gen(function* () {
786
+ // El gating del módulo lo hace index.ts con `modules.events`.
787
+ const eventsConfig = (config.events as unknown as EventsConfig) ?? createDefaultEventsConfig()
788
+
789
+ console.log("[Apex Events] Initializing RPC-based event system...")
790
+
791
+ // Convert static subscriptions from config (add auto-generated IDs and readonly flag)
792
+ const staticSubscriptions: EventSubscription[] = (eventsConfig.subscriptions ?? []).map(
793
+ (sub, index) => ({
794
+ ...sub,
795
+ id: `static-${index}`,
796
+ readonly: true,
797
+ deliverAs: sub.deliverAs ?? DEFAULT_DELIVER_AS,
798
+ resume: sub.resume ?? DEFAULT_RESUME,
799
+ delivery: sub.delivery ?? DEFAULT_DELIVERY,
800
+ priority: sub.priority ?? DEFAULT_PRIORITY,
801
+ enabled: sub.enabled ?? true,
802
+ }),
803
+ )
804
+
805
+ // Restaurar la URL pública fijada en runtime (túnel anunciado por el agente).
806
+ try {
807
+ const storedUrl = yield* Effect.promise(() => Effect.runPromise(ctx.storage.get(PUBLIC_URL_STORAGE_KEY)))
808
+ if (typeof storedUrl === "string" && storedUrl.length > 0) {
809
+ runtimePublicUrl = storedUrl
810
+ console.log(`[Apex Events] URL pública restaurada: ${storedUrl}`)
811
+ }
812
+ } catch {
813
+ runtimePublicUrl = null
814
+ }
815
+
816
+ // Restaurar la vinculación persistida (se valida que la sesión siga viva).
817
+ const restored = yield* Effect.promise(async (): Promise<string | null> => {
818
+ try {
819
+ const stored = await Effect.runPromise(ctx.storage.get(AUTO_SESSION_STORAGE_KEY))
820
+ if (typeof stored !== "string" || stored.length === 0) return null
821
+ const info = (await Effect.runPromise(ctx.session.get({ sessionID: stored as never }))) as
822
+ | { id?: string; parentID?: string | null; agent?: string | null }
823
+ | undefined
824
+ return info?.id && isPrimaryCandidate(info) ? stored : null
825
+ } catch {
826
+ return null
827
+ }
828
+ })
829
+ if (restored) {
830
+ autoBoundSessionID = restored
831
+ console.log(`[Apex Events] sesión principal restaurada: ${restored}`)
832
+ } else {
833
+ yield* Effect.promise(() => setAutoBoundSession(ctx, null))
834
+ }
835
+
836
+ // Watcher de ciclo de vida: vincula/desvincula la sesión principal.
837
+ // - session.created (raíz, no advisor) → vincula
838
+ // - session.deleted de la vinculada → desvincula (auto-desuscripción)
839
+ yield* ctx.event.subscribe().pipe(
840
+ Stream.tap((event) =>
841
+ Effect.promise(() => handleLifecycleEvent(ctx, event as { type: string; data: unknown })),
842
+ ),
843
+ Stream.runDrain,
844
+ Effect.forkScoped,
845
+ )
846
+
847
+ // Register tools
848
+ yield* registerSubscribeTool(ctx)
849
+ yield* registerUnsubscribeTool(ctx)
850
+ yield* registerListSubscriptionsTool(ctx)
851
+
852
+ // Expose the ingest handler for the RPC registration in index.ts.
853
+ // Captures the configured routing policy so it reaches the handler.
854
+ ingestHandler = async (input: IngestInput): Promise<IngestOutput> => {
855
+ return handleIngest(ctx, input, staticSubscriptions, eventsConfig.routing)
856
+ }
857
+
858
+ // Tools de callback: informar del endpoint y anunciar la URL pública (túnel).
859
+ yield* registerCallbackEndpointTool(ctx)
860
+ yield* registerSetCallbackUrlTool(ctx)
861
+
862
+ // Listener HTTP plano: expone EL MISMO ingest para scripts sin credenciales.
863
+ // Host y puerto configurables (loopback por defecto; LAN si se indica).
864
+ const listenerConfig = eventsConfig.listener
865
+ if (listenerConfig?.enabled) {
866
+ const started = yield* Effect.promise(async () => {
867
+ try {
868
+ return await startIngestListener({
869
+ host: listenerConfig.host,
870
+ port: listenerConfig.port,
871
+ token: listenerConfig.token,
872
+ ingest: (input) => handleIngest(ctx, input as IngestInput, staticSubscriptions, eventsConfig.routing),
873
+ })
874
+ } catch (error) {
875
+ console.error(
876
+ `[Apex Events] no se pudo abrir el listener en ${listenerConfig.host}:${listenerConfig.port}: ${String(error)}`,
877
+ )
878
+ return null
879
+ }
880
+ })
881
+ if (started) {
882
+ const urls = listenerUrls(started.host, started.port, listenerConfig.token)
883
+ callbackEndpoint = {
884
+ listenerEnabled: true,
885
+ host: started.host,
886
+ port: started.port,
887
+ urls,
888
+ publicUrl: listenerConfig.publicUrl,
889
+ tokenRequired: typeof listenerConfig.token === "string" && listenerConfig.token.length > 0,
890
+ token: listenerConfig.token,
891
+ rpcPath: "/api/rpc/apex/events.ingest",
892
+ }
893
+ console.log(`[Apex Events] listener de ingesta: ${urls.join(", ")}`)
894
+ if (listenerConfig.publicUrl) console.log(`[Apex Events] URL pública anunciada: ${listenerConfig.publicUrl}`)
895
+ yield* Effect.addFinalizer(() =>
896
+ Effect.promise(async () => {
897
+ callbackEndpoint = null
898
+ await started.close()
899
+ }),
900
+ )
901
+ }
902
+ } else {
903
+ // Listener desactivado: el agente igualmente puede usar el RPC autenticado.
904
+ callbackEndpoint = {
905
+ listenerEnabled: false,
906
+ urls: [],
907
+ tokenRequired: false,
908
+ rpcPath: "/api/rpc/apex/events.ingest",
909
+ }
910
+ }
911
+
912
+ // Subscribe to internal bus for any apex:event (optional, for logging/debugging)
913
+ const busSubscription = subscribe("apex:event", (event) => {
914
+ console.debug(`[Apex Events] Bus event: ${event.type}`, event.payload)
915
+ })
916
+
917
+ console.log("[Apex Events] Event system initialized")
918
+
919
+ // Finalizer: cleanup when the plugin scope closes
920
+ yield* Effect.addFinalizer(() =>
921
+ Effect.sync(() => {
922
+ console.log("[Apex Events] Cleaning up...")
923
+ busSubscription.unsubscribe()
924
+ // Clear deduplication cache
925
+ dedupCache.clear()
926
+ // Clear module-level handler reference
927
+ ingestHandler = null
928
+ // La vinculación persistida se conserva para la próxima carga
929
+ autoBoundSessionID = null
930
+ console.log("[Apex Events] Cleanup complete")
931
+ }),
932
+ )
933
+ })
934
+ }