opencode-apex 0.1.0 → 0.2.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/events.ts CHANGED
@@ -1,16 +1,26 @@
1
1
  /**
2
- * Apex Events — RPC-based generic event ingestion + subscription + delivery system.
2
+ * Apex Events — ingesta genérica de eventos por RPC + suscripciones + entrega.
3
3
  *
4
- * Replaces: webhook receiver (Bun.serve), SSE client, Telegram long-poll,
5
- * cron scheduler, file watchers, and reaction system.
4
+ * Todo entra por el RPC del servidor de OpenCode (`/api/rpc/apex/<método>`):
5
+ * - `events.ingest`: un proceso externo (script, cron, n8n, un relay de webhooks)
6
+ * notifica un evento → las suscripciones que casan lo entregan a su sesión.
7
+ * - `tools.run`: el mismo proceso ejecuta una herramienta de OpenCode (ver core/tools-run.ts).
6
8
  *
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
9
+ * Por qué solo RPC (0.2.0): OpenCode descarga los plugins de un directorio tras 60 min
10
+ * sin actividad de sesiones, y no los vuelve a cargar tras un reinicio hasta que algo
11
+ * toca ese directorio. Un listener propio del plugin se cerraba con él; el RPC, en
12
+ * cambio, levanta el directorio en la propia llamada. Un webhook es un callback con
13
+ * un proceso intermedio que traduce la llamada HTTP a `events.ingest`.
14
+ *
15
+ * Estado por directorio: el módulo se importa una sola vez por proceso y se registra
16
+ * en cada directorio, así que nada de lo que depende del directorio vive a nivel de
17
+ * módulo (antes la sesión principal y el handler de ingest eran globales).
18
+ *
19
+ * - Bus interno (`apex:event`)
20
+ * - Suscripciones con filtros (evaluador de condiciones de core/conditions.ts)
21
+ * - Entrega vía session.switchAgent + session.prompt / synthetic
22
+ * - Deduplicación por eventID con TTL
23
+ * - Suscripciones estáticas (config) + dinámicas (storage)
14
24
  */
15
25
 
16
26
  import { homedir } from "node:os"
@@ -23,8 +33,15 @@ import type { ApexConfig, EventsConfig, EventSubscription } from "./core/config.
23
33
  export type { EventSubscription } from "./core/config.js"
24
34
  import { evaluateCondition, type RuleCondition } from "./core/conditions.js"
25
35
  import { readOrCreateTemplate } from "./core/templates.js"
26
- import { listenerUrls, startIngestListener } from "./core/ingest-listener.js"
27
36
  import { ADVISOR_AGENT_ID } from "./core/advisor-agent.js"
37
+ import { curlExample, resolveServerEndpoint, type ServerEndpoint } from "./core/server-endpoint.js"
38
+ import {
39
+ ensureRunnerAgent,
40
+ makeToolsRunner,
41
+ RUNNER_AGENT_ID,
42
+ type ToolsRunInput,
43
+ type ToolsRunOutput,
44
+ } from "./core/tools-run.js"
28
45
 
29
46
  /** JSON value type accepted by plugin storage */
30
47
  type StorageJson = Parameters<Plugin.Context["storage"]["set"]>[1]
@@ -33,7 +50,6 @@ type StorageJson = Parameters<Plugin.Context["storage"]["set"]>[1]
33
50
  // Types
34
51
  // ============================================================================
35
52
 
36
- /** Event subscription stored in ctx.storage */
37
53
  /** Events module configuration */
38
54
  export type { EventsConfig } from "./core/config.js"
39
55
 
@@ -69,6 +85,23 @@ interface InternalEvent {
69
85
  timestamp: number
70
86
  }
71
87
 
88
+ /** Estado del módulo en UN directorio. */
89
+ export interface EventsState {
90
+ /** Sesión principal activa (raíz, no advisor ni runner). null si no hay ninguna. */
91
+ autoBoundSessionID: string | null
92
+ /** URL pública del servidor fijada en runtime por el agente (túnel). Gana a la config. */
93
+ runtimePublicUrl: string | null
94
+ /** eventID → timestamp de la primera vez que se vio. */
95
+ readonly dedup: Map<string, number>
96
+ }
97
+
98
+ /** Lo que el módulo publica por RPC (lo cablea core/rpc.ts). */
99
+ export interface EventsHandles {
100
+ readonly ingest: (input: IngestInput) => Promise<IngestOutput>
101
+ readonly endpoint: () => ServerEndpoint
102
+ readonly toolsRun: (input: ToolsRunInput) => Promise<ToolsRunOutput>
103
+ }
104
+
72
105
  // ============================================================================
73
106
  // Constants
74
107
  // ============================================================================
@@ -80,9 +113,6 @@ const DEFAULT_DELIVER_AS: "synthetic" | "prompt" = "prompt"
80
113
  const DEFAULT_RESUME = false
81
114
  const DEFAULT_PRIORITY = 0
82
115
 
83
- // In-memory deduplication cache: eventID -> timestamp
84
- const dedupCache = new Map<string, number>()
85
-
86
116
  // ---------------------------------------------------------------------------
87
117
  // Auto-vinculación de suscripciones a la sesión principal
88
118
  // ---------------------------------------------------------------------------
@@ -90,59 +120,26 @@ const dedupCache = new Map<string, number>()
90
120
  const AUTO_SESSION_STORAGE_KEY = "apex:events:autoSession"
91
121
  const PUBLIC_URL_STORAGE_KEY = "apex:events:publicUrl"
92
122
 
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
+ export function createEventsState(): EventsState {
124
+ return { autoBoundSessionID: null, runtimePublicUrl: null, dedup: new Map() }
123
125
  }
124
126
 
125
127
  /**
126
128
  * Fija (o limpia) la URL pública en runtime y la persiste.
127
129
  * Lo usa la tool `apex_set_callback_url` (el agente monta el túnel y la anuncia).
128
130
  */
129
- export async function setRuntimePublicUrl(ctx: Plugin.Context, url: string | null): Promise<void> {
130
- runtimePublicUrl = url && url.trim().length > 0 ? url.trim() : null
131
+ async function setRuntimePublicUrl(ctx: Plugin.Context, state: EventsState, url: string | null): Promise<void> {
132
+ state.runtimePublicUrl = url && url.trim().length > 0 ? url.trim() : null
131
133
  try {
132
- await Effect.runPromise(ctx.storage.set(PUBLIC_URL_STORAGE_KEY, (runtimePublicUrl ?? "") as never))
134
+ await Effect.runPromise(ctx.storage.set(PUBLIC_URL_STORAGE_KEY, (state.runtimePublicUrl ?? "") as never))
133
135
  } catch {
134
136
  // persistencia best-effort
135
137
  }
136
138
  }
137
139
 
138
- /** Diagnóstico/tests. */
139
- export function getAutoBoundSession(): string | null {
140
- return autoBoundSessionID
141
- }
142
-
143
140
  /** 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
141
+ async function setAutoBoundSession(ctx: Plugin.Context, state: EventsState, sessionID: string | null): Promise<void> {
142
+ state.autoBoundSessionID = sessionID
146
143
  try {
147
144
  await Effect.runPromise(
148
145
  ctx.storage.set(AUTO_SESSION_STORAGE_KEY, (sessionID ?? "") as never),
@@ -154,14 +151,14 @@ async function setAutoBoundSession(ctx: Plugin.Context, sessionID: string | null
154
151
 
155
152
  /**
156
153
  * ¿Esta sesión puede ser la principal?
157
- * Debe ser RAÍZ (sin parentID) y no ser una sesión del advisor.
154
+ * Debe ser RAÍZ (sin parentID) y no ser una sesión técnica de apex (advisor, runner).
158
155
  */
159
156
  export function isPrimaryCandidate(info: {
160
157
  parentID?: string | null
161
158
  agent?: string | null
162
159
  }): boolean {
163
160
  if (info.parentID) return false
164
- if (info.agent === ADVISOR_AGENT_ID) return false
161
+ if (info.agent === ADVISOR_AGENT_ID || info.agent === RUNNER_AGENT_ID) return false
165
162
  return true
166
163
  }
167
164
 
@@ -169,14 +166,27 @@ export function isPrimaryCandidate(info: {
169
166
  * Resuelve la sesión destino de una suscripción:
170
167
  * `sessionID` explícito → ese; vacío/null/ausente → la sesión principal activa.
171
168
  */
172
- export function resolveTargetSession(subscription: { sessionID?: string | null }): string | null {
169
+ export function resolveTargetSession(state: EventsState, subscription: { sessionID?: string | null }): string | null {
173
170
  const explicit = typeof subscription.sessionID === "string" ? subscription.sessionID.trim() : ""
174
171
  if (explicit.length > 0) return explicit
175
- return autoBoundSessionID
172
+ return state.autoBoundSessionID
173
+ }
174
+
175
+ /** ¿El evento es de otro directorio? El bus de OpenCode es global: llegan los de todos. */
176
+ export function isForeignEvent(event: { location?: { directory?: string } | null }, directory: string): boolean {
177
+ const other = event.location?.directory
178
+ if (!other) return false
179
+ const trim = (path: string) => path.replace(/\/+$/, "")
180
+ return trim(other) !== trim(directory)
176
181
  }
177
182
 
178
183
  /** 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> {
184
+ export async function handleLifecycleEvent(
185
+ ctx: Plugin.Context,
186
+ state: EventsState,
187
+ event: { type: string; data: unknown; location?: { directory?: string } | null },
188
+ ): Promise<void> {
189
+ if (isForeignEvent(event, ctx.location.directory)) return
180
190
  const data = (event.data ?? {}) as {
181
191
  sessionID?: string
182
192
  parentID?: string | null
@@ -187,23 +197,19 @@ export async function handleLifecycleEvent(ctx: Plugin.Context, event: { type: s
187
197
 
188
198
  if (event.type === "session.created") {
189
199
  if (!isPrimaryCandidate(data)) return
190
- if (autoBoundSessionID === sessionID) return
191
- await setAutoBoundSession(ctx, sessionID)
200
+ if (state.autoBoundSessionID === sessionID) return
201
+ await setAutoBoundSession(ctx, state, sessionID)
192
202
  console.log(`[Apex Events] suscripciones auto vinculadas a la sesión principal ${sessionID}`)
193
203
  return
194
204
  }
195
205
 
196
206
  if (event.type === "session.deleted") {
197
- if (autoBoundSessionID !== sessionID) return
198
- await setAutoBoundSession(ctx, null)
207
+ if (state.autoBoundSessionID !== sessionID) return
208
+ await setAutoBoundSession(ctx, state, null)
199
209
  console.log(`[Apex Events] sesión principal ${sessionID} cerrada: suscripciones auto desvinculadas`)
200
210
  }
201
211
  }
202
212
 
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
213
  // ============================================================================
208
214
  // Helper Functions
209
215
  // ============================================================================
@@ -213,25 +219,13 @@ function generateEventID(): string {
213
219
  return crypto.randomUUID()
214
220
  }
215
221
 
216
- /** Clean expired entries from deduplication cache */
217
- function cleanDedupCache(): void {
222
+ /** Check if eventID was recently seen (within TTL), cleaning expired entries */
223
+ function isDuplicate(state: EventsState, eventID: string): boolean {
218
224
  const now = Date.now()
219
- for (const [eventID, timestamp] of dedupCache.entries()) {
220
- if (now - timestamp > DEDUP_TTL_MS) {
221
- dedupCache.delete(eventID)
222
- }
225
+ for (const [id, timestamp] of state.dedup.entries()) {
226
+ if (now - timestamp > DEDUP_TTL_MS) state.dedup.delete(id)
223
227
  }
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())
228
+ return state.dedup.has(eventID)
235
229
  }
236
230
 
237
231
  /** Load subscriptions from storage */
@@ -258,7 +252,6 @@ async function saveSubscriptions(ctx: Plugin.Context, subscriptions: EventSubscr
258
252
  }
259
253
  }
260
254
 
261
- /** Render prompt template with event data */
262
255
  /** Plantilla por defecto que se escribe si el fichero no existe. */
263
256
  export const DEFAULT_EVENT_PROMPT_TEMPLATE = `Evento {{type}} de {{source}} ({{eventID}})
264
257
  Payload: {{payload}}
@@ -330,12 +323,13 @@ function matchesSubscription(subscription: EventSubscription, event: InternalEve
330
323
  }
331
324
 
332
325
  /** Deliver event to a single subscription */
333
- export async function deliverToSubscription(
326
+ async function deliverToSubscription(
334
327
  ctx: Plugin.Context,
328
+ state: EventsState,
335
329
  subscription: EventSubscription,
336
330
  event: InternalEvent,
337
331
  ): Promise<boolean> {
338
- const targetSession = resolveTargetSession(subscription)
332
+ const targetSession = resolveTargetSession(state, subscription)
339
333
  if (!targetSession) {
340
334
  console.warn(
341
335
  `[Apex Events] suscripción ${subscription.id} sin sesión destino (sessionID vacío y sin sesión principal activa)`,
@@ -395,13 +389,14 @@ export async function deliverToSubscription(
395
389
  /** Process event delivery according to routing policy */
396
390
  async function processDelivery(
397
391
  ctx: Plugin.Context,
392
+ state: EventsState,
398
393
  subscriptions: EventSubscription[],
399
394
  event: InternalEvent,
400
395
  routing: "first" | "all",
401
396
  ): Promise<string[]> {
402
397
  // Find matching subscriptions con sesión destino resoluble
403
398
  const matching = subscriptions.filter(
404
- (sub) => matchesSubscription(sub, event) && resolveTargetSession(sub) !== null,
399
+ (sub) => matchesSubscription(sub, event) && resolveTargetSession(state, sub) !== null,
405
400
  )
406
401
 
407
402
  if (matching.length === 0) {
@@ -417,7 +412,7 @@ async function processDelivery(
417
412
  // Only deliver to highest priority match
418
413
  const top = matching[0]
419
414
  if (top) {
420
- const success = await deliverToSubscription(ctx, top, event)
415
+ const success = await deliverToSubscription(ctx, state, top, event)
421
416
  if (success) {
422
417
  delivered.push(top.id)
423
418
  }
@@ -426,7 +421,7 @@ async function processDelivery(
426
421
  // Fan-out to all matches
427
422
  await Promise.all(
428
423
  matching.map(async (sub) => {
429
- const success = await deliverToSubscription(ctx, sub, event)
424
+ const success = await deliverToSubscription(ctx, state, sub, event)
430
425
  if (success) {
431
426
  delivered.push(sub.id)
432
427
  }
@@ -442,52 +437,52 @@ async function processDelivery(
442
437
  // ============================================================================
443
438
 
444
439
  /**
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).
440
+ * Tool: apex_callback_endpoint — informa al agente de DÓNDE y CÓMO llama un proceso
441
+ * externo a este servidor: URL base, URLs de los métodos RPC para este directorio,
442
+ * auth (sin el password: solo de dónde leerlo) y ejemplos curl.
447
443
  */
448
- function registerCallbackEndpointTool(ctx: Plugin.Context): Effect.Effect<void, never, Scope.Scope> {
444
+ function registerCallbackEndpointTool(
445
+ ctx: Plugin.Context,
446
+ endpoint: () => ServerEndpoint,
447
+ ): Effect.Effect<void, never, Scope.Scope> {
449
448
  return Effect.gen(function* () {
450
449
  yield* ctx.tool.transform((editor) => {
451
450
  editor.add({
452
451
  name: "apex_callback_endpoint",
453
452
  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.",
453
+ "Devuelve cómo alcanza un proceso externo (script, cron, systemd, n8n, relay de webhooks) a ESTE " +
454
+ "servidor de OpenCode: URL base, URLs RPC de apex para este directorio (events.ingest para notificar " +
455
+ "eventos que despiertan a un agente, tools.run para ejecutar herramientas de OpenCode), auth Basic y " +
456
+ "de dónde leer el password, y ejemplos curl. Úsala antes de escribir cualquier script o bucle externo.",
457
457
  input: { type: "object", properties: {}, additionalProperties: false },
458
458
  output: {
459
459
  type: "object",
460
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" },
461
+ baseUrl: { type: ["string", "null"], description: "URL base del servidor (local)" },
462
+ source: { type: ["string", "null"], description: "De dónde salió baseUrl: config | service | argv" },
463
+ publicUrl: { type: ["string", "null"], description: "URL para emisores de otras máquinas (túnel/proxy)" },
464
+ directory: { type: "string", description: "Valor de location[directory] de cada llamada" },
465
+ auth: { type: "object", description: "Basic opencode:<password>; password.shell lo imprime" },
466
+ rpc: { type: "object", description: "URLs completas: ingest, toolsRun, status, ping" },
467
+ examples: { type: "object", description: "curl listos para ingest y toolsRun" },
468
+ hint: { type: "string" },
469
469
  },
470
- additionalProperties: false,
470
+ additionalProperties: true,
471
471
  },
472
472
  execute: () =>
473
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] ?? "")
474
+ const current = endpoint()
484
475
  return {
485
476
  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)",
477
+ ...current,
478
+ examples: {
479
+ ingest: curlExample(current, "ingest", {
480
+ source: "monitor",
481
+ type: "server.down",
482
+ payload: { host: "example.com" },
483
+ }),
484
+ toolsRun: curlExample(current, "toolsRun", { tool: "read", input: { path: "README.md" } }),
485
+ },
491
486
  },
492
487
  }
493
488
  }),
@@ -497,25 +492,29 @@ function registerCallbackEndpointTool(ctx: Plugin.Context): Effect.Effect<void,
497
492
  }
498
493
 
499
494
  /**
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.
495
+ * Tool: apex_set_callback_url — el agente anuncia (o limpia) la URL pública por la
496
+ * que procesos de OTRAS máquinas alcanzan este servidor (túnel o proxy inverso hacia
497
+ * él). Para scripts locales no hace falta: usan la URL base.
503
498
  */
504
- function registerSetCallbackUrlTool(ctx: Plugin.Context): Effect.Effect<void, never, Scope.Scope> {
499
+ function registerSetCallbackUrlTool(
500
+ ctx: Plugin.Context,
501
+ state: EventsState,
502
+ endpoint: () => ServerEndpoint,
503
+ ): Effect.Effect<void, never, Scope.Scope> {
505
504
  return Effect.gen(function* () {
506
505
  yield* ctx.tool.transform((editor) => {
507
506
  editor.add({
508
507
  name: "apex_set_callback_url",
509
508
  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.",
509
+ "Fija (o limpia) la URL pública por la que procesos de OTRAS máquinas alcanzan este servidor de " +
510
+ "OpenCode — p. ej. la de un túnel (cloudflared/ngrok) que apunta a su URL base. Queda persistida y " +
511
+ "aparece en apex_callback_endpoint. Usa null para limpiarla. Precedencia: runtime > config.",
513
512
  input: {
514
513
  type: "object",
515
514
  properties: {
516
515
  url: {
517
516
  type: ["string", "null"],
518
- description: "URL pública (p. ej. https://x.trycloudflare.com/ingest) o null para limpiar",
517
+ description: "URL pública base del servidor (p. ej. https://x.trycloudflare.com) o null para limpiar",
519
518
  },
520
519
  },
521
520
  required: ["url"],
@@ -524,10 +523,8 @@ function registerSetCallbackUrlTool(ctx: Plugin.Context): Effect.Effect<void, ne
524
523
  output: {
525
524
  type: "object",
526
525
  properties: {
527
- publicUrl: { type: "string" },
528
- recommended: { type: "string" },
529
- listenerEnabled: { type: "boolean" },
530
- urls: { type: "array", items: { type: "string" } },
526
+ publicUrl: { type: ["string", "null"] },
527
+ baseUrl: { type: ["string", "null"] },
531
528
  },
532
529
  additionalProperties: false,
533
530
  },
@@ -535,16 +532,9 @@ function registerSetCallbackUrlTool(ctx: Plugin.Context): Effect.Effect<void, ne
535
532
  Effect.promise(async () => {
536
533
  const input = rawInput as { url?: string | null }
537
534
  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
- }
535
+ await setRuntimePublicUrl(ctx, state, next)
536
+ const current = endpoint()
537
+ return { output: { publicUrl: current.publicUrl, baseUrl: current.baseUrl } }
548
538
  }),
549
539
  })
550
540
  })
@@ -715,12 +705,13 @@ function registerListSubscriptionsTool(ctx: Plugin.Context): Effect.Effect<void,
715
705
  /** Handle ingest RPC call */
716
706
  async function handleIngest(
717
707
  ctx: Plugin.Context,
708
+ state: EventsState,
718
709
  input: IngestInput,
719
710
  staticSubscriptions: EventSubscription[],
720
711
  routing: "first" | "all",
721
712
  ): Promise<IngestOutput> {
722
713
  // Validate input
723
- if (!input.source || typeof input.source !== "string") {
714
+ if (!input?.source || typeof input.source !== "string") {
724
715
  throw new Error("Invalid input: 'source' is required and must be a string")
725
716
  }
726
717
  if (!input.payload || typeof input.payload !== "object") {
@@ -731,13 +722,13 @@ async function handleIngest(
731
722
  const eventID = input.eventID ?? generateEventID()
732
723
 
733
724
  // Deduplication check
734
- if (isDuplicate(eventID)) {
725
+ if (isDuplicate(state, eventID)) {
735
726
  // Idempotent: return previous result shape with empty delivered
736
727
  return { accepted: true, eventID, delivered: [] }
737
728
  }
738
729
 
739
730
  // Mark as seen
740
- markSeen(eventID)
731
+ state.dedup.set(eventID, Date.now())
741
732
 
742
733
  // Load dynamic subscriptions
743
734
  const dynamicSubscriptions = await loadSubscriptions(ctx)
@@ -759,7 +750,7 @@ async function handleIngest(
759
750
  await emit("apex:event", internalEvent, "apex-events")
760
751
 
761
752
  // Process delivery using the routing policy captured from config in register()
762
- const delivered = await processDelivery(ctx, allSubscriptions, internalEvent, routing)
753
+ const delivered = await processDelivery(ctx, state, allSubscriptions, internalEvent, routing)
763
754
 
764
755
  return { accepted: true, eventID, delivered }
765
756
  }
@@ -773,18 +764,33 @@ export function createDefaultEventsConfig(): EventsConfig {
773
764
  return {
774
765
  routing: "all",
775
766
  subscriptions: [],
776
- listener: { enabled: false, host: "127.0.0.1", port: 4599 },
767
+ server: {},
768
+ tools: {
769
+ enabled: true,
770
+ allow: ["*"],
771
+ deny: ["question", "subagent", "execute", "apex_*"],
772
+ agent: "build",
773
+ timeoutMs: 120000,
774
+ },
777
775
  }
778
776
  }
779
777
 
780
- /** Register events module (Effect-native) */
778
+ /** Register events module (Effect-native). Devuelve los handlers que publica el RPC. */
781
779
  export function register(
782
780
  ctx: Plugin.Context,
783
781
  config: ApexConfig,
784
- ): Effect.Effect<void, never, Scope.Scope> {
782
+ ): Effect.Effect<EventsHandles, never, Scope.Scope> {
785
783
  return Effect.gen(function* () {
786
784
  // El gating del módulo lo hace index.ts con `modules.events`.
787
- const eventsConfig = (config.events as unknown as EventsConfig) ?? createDefaultEventsConfig()
785
+ const defaults = createDefaultEventsConfig()
786
+ const configured = (config.events as unknown as Partial<EventsConfig>) ?? {}
787
+ const eventsConfig: EventsConfig = {
788
+ ...defaults,
789
+ ...configured,
790
+ server: { ...defaults.server, ...configured.server },
791
+ tools: { ...defaults.tools, ...configured.tools },
792
+ }
793
+ const state = createEventsState()
788
794
 
789
795
  console.log("[Apex Events] Initializing RPC-based event system...")
790
796
 
@@ -803,15 +809,10 @@ export function register(
803
809
  )
804
810
 
805
811
  // 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
- }
812
+ const storedUrl = yield* Effect.promise(() =>
813
+ Effect.runPromise(ctx.storage.get(PUBLIC_URL_STORAGE_KEY)).catch(() => undefined),
814
+ )
815
+ if (typeof storedUrl === "string" && storedUrl.length > 0) state.runtimePublicUrl = storedUrl
815
816
 
816
817
  // Restaurar la vinculación persistida (se valida que la sesión siga viva).
817
818
  const restored = yield* Effect.promise(async (): Promise<string | null> => {
@@ -827,18 +828,20 @@ export function register(
827
828
  }
828
829
  })
829
830
  if (restored) {
830
- autoBoundSessionID = restored
831
+ state.autoBoundSessionID = restored
831
832
  console.log(`[Apex Events] sesión principal restaurada: ${restored}`)
832
833
  } else {
833
- yield* Effect.promise(() => setAutoBoundSession(ctx, null))
834
+ yield* Effect.promise(() => setAutoBoundSession(ctx, state, null))
834
835
  }
835
836
 
836
837
  // 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)
838
+ // - session.created (raíz, no advisor/runner) → vincula
839
+ // - session.deleted de la vinculada → desvincula (auto-desuscripción)
839
840
  yield* ctx.event.subscribe().pipe(
840
841
  Stream.tap((event) =>
841
- Effect.promise(() => handleLifecycleEvent(ctx, event as { type: string; data: unknown })),
842
+ Effect.promise(() =>
843
+ handleLifecycleEvent(ctx, state, event as { type: string; data: unknown; location?: { directory?: string } }),
844
+ ),
842
845
  ),
843
846
  Stream.runDrain,
844
847
  Effect.forkScoped,
@@ -849,86 +852,47 @@ export function register(
849
852
  yield* registerUnsubscribeTool(ctx)
850
853
  yield* registerListSubscriptionsTool(ctx)
851
854
 
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
- }
855
+ // Dirección del servidor: se resuelve en cada consulta (el servicio puede haber
856
+ // reescrito su registro tras un reinicio).
857
+ const endpoint = (): ServerEndpoint =>
858
+ resolveServerEndpoint({
859
+ directory: ctx.location.directory,
860
+ configUrl: eventsConfig.server.url,
861
+ publicUrl: state.runtimePublicUrl ?? eventsConfig.server.publicUrl ?? null,
880
862
  })
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
- }
863
+ yield* registerCallbackEndpointTool(ctx, endpoint)
864
+ yield* registerSetCallbackUrlTool(ctx, state, endpoint)
865
+
866
+ // tools.run: agente oculto de la sesión runner + ejecutor de este directorio.
867
+ yield* ensureRunnerAgent(ctx)
868
+ const toolsRun = makeToolsRunner(ctx, eventsConfig.tools)
911
869
 
912
870
  // Subscribe to internal bus for any apex:event (optional, for logging/debugging)
913
871
  const busSubscription = subscribe("apex:event", (event) => {
914
872
  console.debug(`[Apex Events] Bus event: ${event.type}`, event.payload)
915
873
  })
916
874
 
917
- console.log("[Apex Events] Event system initialized")
875
+ const current = endpoint()
876
+ console.log(
877
+ `[Apex Events] Event system initialized · RPC ${current.baseUrl ?? "(URL del servidor desconocida)"} · ` +
878
+ `tools.run ${eventsConfig.tools.enabled ? `on (agente ${eventsConfig.tools.agent})` : "off"}`,
879
+ )
918
880
 
919
881
  // Finalizer: cleanup when the plugin scope closes
920
882
  yield* Effect.addFinalizer(() =>
921
883
  Effect.sync(() => {
922
884
  console.log("[Apex Events] Cleaning up...")
923
885
  busSubscription.unsubscribe()
924
- // Clear deduplication cache
925
- dedupCache.clear()
926
- // Clear module-level handler reference
927
- ingestHandler = null
886
+ state.dedup.clear()
928
887
  // La vinculación persistida se conserva para la próxima carga
929
- autoBoundSessionID = null
930
888
  console.log("[Apex Events] Cleanup complete")
931
889
  }),
932
890
  )
891
+
892
+ return {
893
+ ingest: (input: IngestInput) => handleIngest(ctx, state, input, staticSubscriptions, eventsConfig.routing),
894
+ endpoint,
895
+ toolsRun,
896
+ } satisfies EventsHandles
933
897
  })
934
- }
898
+ }