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.
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Dónde alcanza un proceso externo a ESTE servidor de OpenCode y cómo se autentica.
3
+ *
4
+ * Un agente que deja un bucle externo corriendo (cron, systemd, n8n, un relay de
5
+ * webhooks) necesita saber a qué URL apuntar. El plugin corre dentro del proceso
6
+ * del servidor, pero la API de plugins no expone su dirección, así que se descubre:
7
+ *
8
+ * 1. `events.server.url` de la config (proxy inverso, host fijo…)
9
+ * 2. el registro del servicio en segundo plano — `<state>/opencode/service*.json`,
10
+ * que escribe `opencode serve --service` con { url, pid, password } (modo 0600) —
11
+ * cuando su pid es este proceso
12
+ * 3. los argumentos `--hostname`/`--port` de `opencode serve`
13
+ *
14
+ * La auth es HTTP Basic `opencode:<password>`. El password NUNCA se devuelve: solo
15
+ * dónde leerlo, para que no acabe en la conversación (ni en el proveedor del modelo).
16
+ */
17
+
18
+ import { readdirSync, readFileSync } from "node:fs"
19
+ import { homedir } from "node:os"
20
+ import { join } from "node:path"
21
+
22
+ export const SERVER_USERNAME = "opencode"
23
+
24
+ export interface PasswordSource {
25
+ /** "file": fichero JSON + campo · "env": variable con la que arrancó el servidor. */
26
+ readonly kind: "file" | "env"
27
+ readonly file?: string
28
+ readonly field?: string
29
+ readonly env?: string
30
+ /** Fragmento de shell que imprime el password (para scripts). */
31
+ readonly shell: string
32
+ }
33
+
34
+ export interface ServerEndpoint {
35
+ /** URL base del servidor, alcanzable desde esta máquina (null = desconocida). */
36
+ readonly baseUrl: string | null
37
+ readonly source: "config" | "service" | "argv" | null
38
+ /** URL para procesos FUERA de esta máquina (túnel / proxy inverso), si se declaró. */
39
+ readonly publicUrl: string | null
40
+ /** Directorio del proyecto al que deben ir las llamadas RPC (`location[directory]`). */
41
+ readonly directory: string
42
+ readonly auth: { readonly scheme: "basic"; readonly username: string; readonly password: PasswordSource | null }
43
+ /** URLs completas de los métodos RPC de apex para este directorio. */
44
+ readonly rpc: Readonly<Record<"ingest" | "toolsRun" | "status" | "ping", string>>
45
+ readonly hint?: string
46
+ }
47
+
48
+ /** `<state>/opencode` — respeta XDG_STATE_HOME igual que OpenCode. */
49
+ export function stateDirectory(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {
50
+ const base = env.XDG_STATE_HOME && env.XDG_STATE_HOME.length > 0 ? env.XDG_STATE_HOME : join(home, ".local", "state")
51
+ return join(base, "opencode")
52
+ }
53
+
54
+ /** Host/puerto de `opencode serve` según su argv; null si no es un serve con puerto explícito. */
55
+ export function parseServeArgv(argv: readonly string[]): { host: string; port: number } | null {
56
+ if (!argv.includes("serve")) return null
57
+ const value = (flag: string): string | undefined => {
58
+ for (let i = 0; i < argv.length; i++) {
59
+ const arg = argv[i]!
60
+ if (arg === flag) return argv[i + 1]
61
+ if (arg.startsWith(`${flag}=`)) return arg.slice(flag.length + 1)
62
+ }
63
+ return undefined
64
+ }
65
+ const port = Number(value("--port"))
66
+ if (!Number.isInteger(port) || port <= 0) return null
67
+ const host = value("--hostname") ?? "127.0.0.1"
68
+ // Escuchar en todas las interfaces no es una dirección: desde aquí, loopback.
69
+ return { host: host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host, port }
70
+ }
71
+
72
+ interface ServiceRecord {
73
+ readonly url?: string
74
+ readonly pid?: number
75
+ }
76
+
77
+ /** El registro del servicio (ruta + url) cuyo pid es `pid`, entre `<state>/opencode/service*.json`. */
78
+ export function findServiceRecord(dir: string, pid: number): { file: string; url: string } | null {
79
+ let names: string[]
80
+ try {
81
+ names = readdirSync(dir).filter((name) => /^service(-[\w.-]+)?\.json$/.test(name))
82
+ } catch {
83
+ return null
84
+ }
85
+ for (const name of names) {
86
+ const file = join(dir, name)
87
+ try {
88
+ const record = JSON.parse(readFileSync(file, "utf8")) as ServiceRecord
89
+ if (record.pid === pid && typeof record.url === "string" && record.url.length > 0) return { file, url: record.url }
90
+ } catch {
91
+ // registro ilegible o a medio escribir: no es el nuestro
92
+ }
93
+ }
94
+ return null
95
+ }
96
+
97
+ /** `<base>/api/rpc/apex/<método>?location[directory]=<dir>` (corchetes codificados, para curl). */
98
+ export function rpcUrl(base: string, method: string, directory: string): string {
99
+ return `${base.replace(/\/+$/, "")}/api/rpc/apex/${method}?location%5Bdirectory%5D=${encodeURIComponent(directory)}`
100
+ }
101
+
102
+ export function resolveServerEndpoint(input: {
103
+ readonly directory: string
104
+ readonly configUrl?: string
105
+ readonly publicUrl?: string | null
106
+ readonly argv?: readonly string[]
107
+ readonly pid?: number
108
+ readonly stateDir?: string
109
+ }): ServerEndpoint {
110
+ const argv = input.argv ?? process.argv
111
+ const pid = input.pid ?? process.pid
112
+ const stateDir = input.stateDir ?? stateDirectory()
113
+ const service = findServiceRecord(stateDir, pid)
114
+ const serve = service ? null : parseServeArgv(argv)
115
+
116
+ let baseUrl: string | null = null
117
+ let source: ServerEndpoint["source"] = null
118
+ if (input.configUrl && input.configUrl.trim().length > 0) {
119
+ baseUrl = input.configUrl.trim()
120
+ source = "config"
121
+ } else if (service) {
122
+ baseUrl = service.url
123
+ source = "service"
124
+ } else if (serve) {
125
+ baseUrl = `http://${serve.host.includes(":") ? `[${serve.host}]` : serve.host}:${serve.port}`
126
+ source = "argv"
127
+ }
128
+
129
+ // El password lo custodia quien arrancó el servidor: el registro del servicio, o
130
+ // la variable de entorno con la que se lanzó `opencode serve`.
131
+ // `sed` y no `jq`: está en cualquier máquina y el registro es JSON plano.
132
+ const password: PasswordSource | null = service
133
+ ? {
134
+ kind: "file",
135
+ file: service.file,
136
+ field: "password",
137
+ shell: `sed -n 's/.*"password" *: *"\\([^"]*\\)".*/\\1/p' '${service.file}'`,
138
+ }
139
+ : serve
140
+ ? { kind: "env", env: "OPENCODE_SERVER_PASSWORD", shell: "printenv OPENCODE_SERVER_PASSWORD" }
141
+ : null
142
+
143
+ const base = baseUrl ?? "<server-url>"
144
+ const publicUrl = input.publicUrl && input.publicUrl.trim().length > 0 ? input.publicUrl.trim() : null
145
+ return {
146
+ baseUrl,
147
+ source,
148
+ publicUrl,
149
+ directory: input.directory,
150
+ auth: { scheme: "basic", username: SERVER_USERNAME, password },
151
+ rpc: {
152
+ ingest: rpcUrl(base, "events.ingest", input.directory),
153
+ toolsRun: rpcUrl(base, "tools.run", input.directory),
154
+ status: rpcUrl(base, "status", input.directory),
155
+ ping: rpcUrl(base, "ping", input.directory),
156
+ },
157
+ ...(baseUrl
158
+ ? {}
159
+ : { hint: "URL del servidor desconocida: fija events.server.url en la config de apex (p. ej. http://127.0.0.1:4096)" }),
160
+ }
161
+ }
162
+
163
+ /** curl listo para una llamada RPC (el password se lee al ejecutar, nunca va en claro). */
164
+ export function curlExample(endpoint: ServerEndpoint, method: "ingest" | "toolsRun", body: unknown): string {
165
+ const password = endpoint.auth.password?.shell ?? 'printenv OPENCODE_SERVER_PASSWORD'
166
+ return [
167
+ `curl -sS -X POST '${endpoint.rpc[method]}' \\`,
168
+ ` -u "${endpoint.auth.username}:$(${password})" \\`,
169
+ ` -H 'content-type: application/json' \\`,
170
+ ` -d '${JSON.stringify({ input: body })}'`,
171
+ ].join("\n")
172
+ }
package/core/skills.ts ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Skills que viajan con el paquete (`skills/<id>/SKILL.md`) y se registran en cada
3
+ * directorio donde carga apex, sin copiar nada a `~/.config/opencode/skills`.
4
+ *
5
+ * Mismo contrato que las skills de fichero de OpenCode: id = nombre de la carpeta,
6
+ * `name`/`description` del frontmatter, contenido = el cuerpo sin frontmatter.
7
+ */
8
+
9
+ import { existsSync, readdirSync, readFileSync } from "node:fs"
10
+ import { join } from "node:path"
11
+ import { fileURLToPath } from "node:url"
12
+ import { Effect } from "effect"
13
+ import type { Scope } from "effect"
14
+ import type { Plugin } from "@opencode/plugin/effect"
15
+
16
+ const SKILLS_DIR = fileURLToPath(new URL("../skills", import.meta.url))
17
+
18
+ export interface PackagedSkill {
19
+ readonly id: string
20
+ readonly name: string
21
+ readonly description?: string
22
+ readonly path: string
23
+ readonly content: string
24
+ }
25
+
26
+ /** Frontmatter YAML plano (`clave: valor` por línea) + cuerpo. */
27
+ export function parseSkillFile(id: string, path: string, text: string): PackagedSkill {
28
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text)
29
+ const fields: Record<string, string> = {}
30
+ if (match) {
31
+ for (const line of match[1]!.split(/\r?\n/)) {
32
+ const pair = /^([A-Za-z][\w-]*):\s*(.*)$/.exec(line)
33
+ if (pair) fields[pair[1]!] = pair[2]!.trim().replace(/^(["'])(.*)\1$/, "$2")
34
+ }
35
+ }
36
+ return {
37
+ id,
38
+ name: fields.name || id,
39
+ ...(fields.description ? { description: fields.description } : {}),
40
+ path,
41
+ content: match ? text.slice(match[0].length) : text,
42
+ }
43
+ }
44
+
45
+ export function loadPackagedSkills(dir: string = SKILLS_DIR): PackagedSkill[] {
46
+ if (!existsSync(dir)) return []
47
+ return readdirSync(dir, { withFileTypes: true })
48
+ .filter((entry) => entry.isDirectory() && existsSync(join(dir, entry.name, "SKILL.md")))
49
+ .map((entry) => {
50
+ const path = join(dir, entry.name, "SKILL.md")
51
+ return parseSkillFile(entry.name, path, readFileSync(path, "utf8"))
52
+ })
53
+ }
54
+
55
+ export function registerSkills(ctx: Plugin.Context): Effect.Effect<void, never, Scope.Scope> {
56
+ return Effect.gen(function* () {
57
+ const skills = loadPackagedSkills()
58
+ if (skills.length === 0) return
59
+ yield* ctx.skill.transform((editor) => {
60
+ for (const skill of skills) editor.add(skill as never)
61
+ })
62
+ })
63
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * RPC `apex/tools.run` — ejecuta UNA herramienta de OpenCode (nativa, de plugin o MCP)
3
+ * desde fuera del servidor y devuelve su resultado.
4
+ *
5
+ * Es la pieza que permite que un bucle externo (cron, systemd, n8n) use herramientas
6
+ * que solo existen dentro de OpenCode — el MCP de Easypanel, el navegador… — sin
7
+ * modelo de por medio. La llamada RPC levanta el directorio si estaba descargado
8
+ * (inactividad o reinicio), así que no depende de que el plugin siga vivo.
9
+ *
10
+ * Dos barreras, en este orden:
11
+ * 1. `events.tools.allow` / `deny`: qué herramientas se pueden lanzar por aquí.
12
+ * 2. los permisos del agente `events.tools.agent` (o el `agent` de la llamada): son
13
+ * los que evalúa cada herramienta. Sin nadie delante, un "ask" espera al advisor
14
+ * o hasta el timeout.
15
+ *
16
+ * Las herramientas corren en nombre de una sesión "runner" propia (una por
17
+ * directorio, persistida), con el agente oculto `apex-runner`: así no se confunde
18
+ * con la sesión principal ni aparece entre los agentes seleccionables.
19
+ */
20
+
21
+ import { Effect } from "effect"
22
+ import type { Scope } from "effect"
23
+ import type { Plugin } from "@opencode/plugin/effect"
24
+ import type { EventsToolsConfig } from "./config.js"
25
+
26
+ export const RUNNER_AGENT_ID = "apex-runner"
27
+ const RUNNER_SESSION_KEY = "apex:tools:runnerSession"
28
+
29
+ export type ToolsRunConfig = EventsToolsConfig
30
+
31
+ export interface ToolsRunInput {
32
+ readonly tool: string
33
+ readonly input?: Record<string, unknown>
34
+ /** Agente cuyos permisos se aplican a ESTA llamada (por defecto el de config). */
35
+ readonly agent?: string
36
+ readonly timeoutMs?: number
37
+ }
38
+
39
+ export interface ToolsRunOutput {
40
+ readonly ok: boolean
41
+ readonly tool: string
42
+ readonly agent?: string
43
+ /** Salida estructurada de la herramienta, si la declara. */
44
+ readonly output?: unknown
45
+ /** Texto que vería el modelo. */
46
+ readonly content?: string
47
+ readonly metadata?: unknown
48
+ readonly error?: string
49
+ readonly durationMs: number
50
+ }
51
+
52
+ /** Glob con `*` (cualquier secuencia) y `?` (un carácter); el resto literal. */
53
+ export function wildcard(pattern: string, value: string): boolean {
54
+ const source = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")
55
+ return new RegExp(`^${source}$`).test(value)
56
+ }
57
+
58
+ export function checkTool(name: string, config: Pick<ToolsRunConfig, "allow" | "deny">): string | null {
59
+ if (config.deny.some((pattern) => wildcard(pattern, name))) return `herramienta denegada para tools.run: ${name}`
60
+ if (!config.allow.some((pattern) => wildcard(pattern, name))) return `herramienta fuera de events.tools.allow: ${name}`
61
+ return null
62
+ }
63
+
64
+ /** Texto de un `Tool.Result.content` (string o lista de partes). */
65
+ export function contentText(content: unknown): string | undefined {
66
+ if (content === undefined || content === null) return undefined
67
+ if (typeof content === "string") return content
68
+ if (!Array.isArray(content)) return JSON.stringify(content)
69
+ return content
70
+ .map((part: { type?: string; text?: string }) => (typeof part?.text === "string" ? part.text : `[${part?.type ?? "?"}]`))
71
+ .join("\n")
72
+ }
73
+
74
+ function errorText(error: unknown): string {
75
+ if (error instanceof Error) return error.message
76
+ if (error && typeof error === "object" && "message" in error) return String((error as { message: unknown }).message)
77
+ return String(error)
78
+ }
79
+
80
+ /** Agente oculto que identifica a la sesión runner (sus permisos no se usan: manda el de la llamada). */
81
+ export function ensureRunnerAgent(ctx: Plugin.Context): Effect.Effect<void, never, Scope.Scope> {
82
+ return Effect.gen(function* () {
83
+ yield* ctx.agent.transform((editor) => {
84
+ editor.update(RUNNER_AGENT_ID, (agent) => {
85
+ agent.name = RUNNER_AGENT_ID as never
86
+ agent.description = "Sesión técnica de apex para tools.run (RPC); no es un agente de trabajo"
87
+ agent.mode = "subagent"
88
+ agent.hidden = true
89
+ agent.permissions = [{ action: "*", resource: "*", effect: "deny" }] as never
90
+ })
91
+ })
92
+ })
93
+ }
94
+
95
+ /** Crea el ejecutor de `tools.run` de un directorio (estado propio, nada global). */
96
+ export function makeToolsRunner(ctx: Plugin.Context, config: ToolsRunConfig) {
97
+ let runnerSession: string | null = null
98
+ let creating: Promise<string> | null = null
99
+ let seq = 0
100
+
101
+ const session = async (): Promise<string> => {
102
+ if (runnerSession) return runnerSession
103
+ creating ??= (async () => {
104
+ const stored = await Effect.runPromise(ctx.storage.get(RUNNER_SESSION_KEY)).catch(() => undefined)
105
+ if (typeof stored === "string" && stored.length > 0) {
106
+ const alive = await Effect.runPromise(ctx.session.get({ sessionID: stored as never })).catch(() => undefined)
107
+ if (alive) return stored
108
+ }
109
+ const created = await Effect.runPromise(
110
+ ctx.session.create({ title: "apex · tools.run", agent: RUNNER_AGENT_ID as never }),
111
+ )
112
+ await Effect.runPromise(ctx.storage.set(RUNNER_SESSION_KEY, created.id as never)).catch(() => undefined)
113
+ return created.id as string
114
+ })().finally(() => {
115
+ creating = null
116
+ })
117
+ runnerSession = await creating
118
+ return runnerSession
119
+ }
120
+
121
+ return async (input: ToolsRunInput): Promise<ToolsRunOutput> => {
122
+ const started = Date.now()
123
+ const tool = typeof input?.tool === "string" ? input.tool.trim() : ""
124
+ const fail = (error: string, agent?: string): ToolsRunOutput => ({
125
+ ok: false,
126
+ tool,
127
+ ...(agent ? { agent } : {}),
128
+ error,
129
+ durationMs: Date.now() - started,
130
+ })
131
+ if (!config.enabled) return fail("tools.run desactivado (events.tools.enabled=false)")
132
+ if (!tool) return fail("falta 'tool'")
133
+ const blocked = checkTool(tool, config)
134
+ if (blocked) return fail(blocked)
135
+
136
+ const agent = input.agent && input.agent.trim().length > 0 ? input.agent.trim() : config.agent
137
+ try {
138
+ const tools = await Effect.runPromise(ctx.tool.list())
139
+ const found = tools.find((candidate) => candidate.id === tool)
140
+ if (!found) return fail(`herramienta no registrada en este directorio: ${tool}`, agent)
141
+
142
+ const sessionID = await session()
143
+ const result = await Effect.runPromise(
144
+ found.execute(input.input ?? {}, {
145
+ sessionID: sessionID as never,
146
+ agent: agent as never,
147
+ messageID: `msg_apexrun${Date.now().toString(36)}` as never,
148
+ id: `apex_run_${Date.now().toString(36)}_${++seq}` as never,
149
+ progress: () => Effect.void,
150
+ }),
151
+ { signal: AbortSignal.timeout(input.timeoutMs ?? config.timeoutMs) },
152
+ )
153
+ return {
154
+ ok: true,
155
+ tool,
156
+ agent,
157
+ ...(result.output !== undefined ? { output: result.output } : {}),
158
+ ...(result.content !== undefined ? { content: contentText(result.content) } : {}),
159
+ ...(result.metadata !== undefined ? { metadata: result.metadata } : {}),
160
+ durationMs: Date.now() - started,
161
+ }
162
+ } catch (error) {
163
+ const timedOut = Date.now() - started >= (input.timeoutMs ?? config.timeoutMs)
164
+ return fail(timedOut ? `timeout tras ${input.timeoutMs ?? config.timeoutMs} ms` : errorText(error), agent)
165
+ }
166
+ }
167
+ }
package/docs/EVENTS.md CHANGED
@@ -30,7 +30,8 @@ automáticamente a la **sesión principal activa**: la sesión **raíz** (sin
30
30
 
31
31
  No se vincula nunca a:
32
32
  - sesiones de **subagentes** (tienen `parentID`),
33
- - la sesión del **advisor** (`agent === "apex-advisor"`).
33
+ - la sesión del **advisor** (`agent === "apex-advisor"`),
34
+ - la sesión **runner** de `tools.run` (`agent === "apex-runner"`).
34
35
 
35
36
  ### Mecanismo
36
37
 
@@ -38,7 +39,7 @@ El módulo observa el stream de eventos de sesión (`ctx.event.subscribe()`):
38
39
 
39
40
  | Evento | Condición | Acción |
40
41
  | ----------------- | ---------------------------------- | --------------------------------------------- |
41
- | `session.created` | sin `parentID` y no advisor | vincula (y persiste en storage) |
42
+ | `session.created` | sin `parentID`, ni advisor ni runner | vincula (y persiste en storage) |
42
43
  | `session.deleted` | es la sesión vinculada | **desvincula** (auto-desuscripción) y persiste |
43
44
  | (arranque) | binding persistido | se restaura si la sesión sigue viva; si no, se limpia |
44
45
 
@@ -49,50 +50,86 @@ cree una nueva sesión principal — entonces se re-vincula sola.
49
50
  Entrega: si una suscripción no tiene destino resoluble (vacío y sin principal
50
51
  activa), **no se entrega** y se registra un aviso (no se rompe el ingest).
51
52
 
52
- ## Listener HTTP plano (para scripts sin credenciales)
53
+ ## Entrada: el RPC del servidor (0.2.0)
53
54
 
54
- Expone **el mismo `events.ingest`** por HTTP sin credenciales del servidor
55
- (opcionalmente con token propio). Pensado para scripts, otras máquinas y túneles.
55
+ Todo entra por el RPC de OpenCode, por directorio:
56
+
57
+ ```
58
+ POST <baseUrl>/api/rpc/apex/<método>?location[directory]=<proyecto>
59
+ Authorization: Basic base64("opencode:<password>")
60
+ {"input":{…}} → {"output":{…}}
61
+ ```
62
+
63
+ | Método | Entrada | Salida |
64
+ | --- | --- | --- |
65
+ | `events.ingest` | `{source, type?, payload, eventID?}` | `{accepted, eventID, delivered[]}` (o `error`) |
66
+ | `tools.run` | `{tool, input?, agent?, timeoutMs?}` | `{ok, tool, agent, output?, content?, metadata?, error?, durationMs}` |
67
+ | `server.info` | `{}` | dirección y auth de este servidor (ver abajo) |
68
+ | `status` · `ping` | `{}` | `{modules, version, uptimeMs, endpoint}` · `{pong, timestamp}` |
69
+
70
+ **Por qué no hay listener propio.** OpenCode descarga los plugins de un directorio tras
71
+ **60 minutos sin eventos de sesión** (`LocationActivity`, sin opción para cambiarlo) y,
72
+ tras un reinicio, no los carga hasta que algo usa ese directorio. El listener HTTP de
73
+ 0.1.x se cerraba con el plugin; el RPC espera a que los plugins estén activos y levanta
74
+ el directorio en la propia llamada (unos segundos la primera vez). Desde 0.2.0
75
+ `events.listener` se ignora con un aviso.
76
+
77
+ El RPC de 0.1.x tampoco funcionaba en OpenCode ≥ 2.1: se registraba con `name` y V2
78
+ indexa por `id` (`rpc.unavailable`).
79
+
80
+ ## Descubrir la dirección del servidor
81
+
82
+ La tool **`apex_callback_endpoint`** (y el RPC `server.info`) devuelve cómo llega un
83
+ proceso externo a ESTE servidor:
84
+
85
+ | Campo | Contenido |
86
+ | --- | --- |
87
+ | `baseUrl` · `source` | URL base y de dónde salió: `config` (`events.server.url`) > `service` (registro `<state>/opencode/service*.json` cuyo `pid` es este proceso) > `argv` (`opencode serve --port`) |
88
+ | `rpc.*` | URLs completas de `ingest`, `toolsRun`, `status`, `ping` con el `location[directory]` del proyecto |
89
+ | `auth` | Basic `opencode` + **dónde** está el password (`file`+`field` o `env`) y un `shell` que lo imprime. El password nunca se devuelve |
90
+ | `publicUrl` | URL para emisores de otras máquinas (túnel/proxy al servidor); runtime (`apex_set_callback_url`) > `events.server.publicUrl` |
91
+ | `examples` | curl listos para `ingest` y `toolsRun` |
56
92
 
57
93
  ```jsonc
58
94
  "events": {
59
- "listener": {
60
- "enabled": true, // ← ACTIVO POR DEFECTO en loopback
61
- "host": "127.0.0.1", // loopback · "0.0.0.0" · IP LAN
62
- "port": 4599, // 0 = puerto efímero (se anuncia el real)
63
- "token": "opcional-pero-recomendado",
64
- "publicUrl": "" // fallback; normalmente lo fija el agente en runtime
65
- }
95
+ "server": { "url": "", "publicUrl": "" } // vacío = descubrir
66
96
  }
67
97
  ```
68
98
 
69
- | Ruta | Método | Resultado |
70
- | --------------------------- | ------ | ------------------------------------------------------ |
71
- | `/ingest` · `/ingest/<token>` | POST | Ejecuta el ingest y devuelve `{accepted, eventID, delivered}` |
72
- | `/health` · `/` | GET | `{ok:true,…}` (para túneles/monitorización) |
99
+ ## `tools.run`: herramientas de OpenCode desde fuera
73
100
 
74
- **Descubrimiento**: la tool **`apex_callback_endpoint`** devuelve al agente dónde
75
- recibe los mensajes: `urls` (loopback y, con `0.0.0.0`, las IPs LAN), `publicUrl`,
76
- `recommended`, `token`, `rpcPath`. El endpoint también aparece en `apex.status`
77
- (campo `callback`).
101
+ Un proceso externo ejecuta UNA herramienta (nativa, de plugin o MCP) y recibe su
102
+ resultado, sin modelo. Sirve para vigilancias que dependen de algo que solo existe en
103
+ OpenCode (el MCP de Easypanel, el navegador…).
78
104
 
79
- **Flujo autónomo**: el agente levanta el túnel él mismo, captura la URL y la
80
- anuncia con la tool **`apex_set_callback_url({url})`** (persistida; precedencia
81
- **runtime > config**). Al terminar la limpia con `{url: null}`. Así no hace falta
82
- que el usuario configure nada por cada sesión.
105
+ ```jsonc
106
+ "events": {
107
+ "tools": {
108
+ "enabled": true,
109
+ "allow": ["*"], // globs de herramientas
110
+ "deny": ["question", "subagent", "execute", "apex_*"], // gana a allow
111
+ "agent": "build", // permisos que se aplican
112
+ "timeoutMs": 120000
113
+ }
114
+ }
115
+ ```
83
116
 
84
- Acepta el payload directo o `{"input":{…}}`. Límites: **64 KB** (413), JSON
85
- estricto (400), ruta (404), método (405), token (401). El token se acepta por
86
- header `x-apex-token` o como segmento de path.
117
+ - Orden: `deny` → `allow` → **permisos del agente** (`agent` de la llamada o de config),
118
+ los mismos que evalúa la herramienta cuando la usa ese agente. Sin nadie delante, un
119
+ "ask" espera al advisor (si está activo) o hasta `timeoutMs`.
120
+ - Corre en una sesión **runner** por directorio (agente oculto `apex-runner`, persistida en
121
+ storage): no cuenta como sesión principal ni aparece entre los agentes.
122
+ - Las llamadas no quedan en el historial de ninguna sesión ni disparan los hooks
123
+ `tool.execute.before/after`.
124
+ - Quien tenga el password del servidor ya puede hacer esto por la API de sesiones; `allow`
125
+ y `deny` acotan esta vía en concreto.
87
126
 
88
- > **Seguridad**: el ingest inyecta prompts al agente. Fuera de loopback, define
89
- > `token` — el listener avisa por consola si bindeas a una interfaz no-loopback
90
- > sin token. Para callbacks a través de Internet, expón **el listener** (no el API
91
- > autenticado) mediante túnel, y protege la URL.
127
+ ## Webhooks
92
128
 
93
- Ver la skill **`apex-callbacks`** (`.opencode/skills/apex-callbacks/SKILL.md`) para
94
- los patrones completos: fire-and-forget, LAN, túneles, hooks de arranque y
95
- entrega fiable.
129
+ Un webhook es un callback con un **proceso intermedio**: el servicio externo llama por
130
+ HTTP a un relay (n8n, un daemon) que traduce la llamada a `events.ingest`. La skill
131
+ `apex-callbacks` trae un relay mínimo en Node y la receta de n8n. Para recibir desde
132
+ Internet se expone el relay, nunca el servidor de OpenCode.
96
133
 
97
134
  ## Herramientas
98
135
 
@@ -100,3 +137,9 @@ entrega fiable.
100
137
  - `apex_unsubscribe` — elimina una suscripción dinámica por id (las estáticas de
101
138
  config son `readonly`).
102
139
  - `apex_list_subscriptions` — lista todas (marca las estáticas).
140
+ - `apex_callback_endpoint` — dirección, URLs RPC y auth del servidor (ver arriba).
141
+ - `apex_set_callback_url` — fija/limpia la URL pública del servidor (túnel/proxy).
142
+
143
+ La skill **`apex-callbacks`** (en el paquete, `skills/apex-callbacks/SKILL.md`) se
144
+ registra sola donde carga apex: vigilantes con estado, systemd/cron, webhooks y
145
+ `tools.run`.
@@ -174,7 +174,7 @@ console.log(await loadConfig('<proyecto>/.opencode/opencode-apex.jsonc')); // ->
174
174
  ## Migración a la API Effect-native (2026-09-23)
175
175
 
176
176
  - **Motivo**: la API promise acumulaba fallos de contrato (rpc 1-arg, tool execute Promise, ast._tag). La doc oficial (https://opencode.ai/v2/docs/build/plugins/effect/) usa `Plugin.define({ id, effect })` de `@opencode/plugin/effect`.
177
- - **CRÍTICO — versión de effect**: `@opencode/plugin` depende de **effect 4.0.0-rc.112**. Si el plugin instala otra mayor (p.ej. 3.x), los tipos `Effect` chocan por el brand TypeId → errores masivos "missing TypeID". Alinear SIEMPRE: `"effect": "4.0.0-rc.112"`.
177
+ - **CRÍTICO — versión de effect**: `@opencode/plugin` trae su propia versión exacta de effect (rc.112 hasta 2.0.x, **4.0.1 desde 2.1**). Si apex usa otra, los tipos `Effect` chocan por el brand TypeId ("missing TypeID") o, en ejecución, el código de `@opencode/schema` cae sobre la copia equivocada (`Schema.isStartsWith is not a function`). **Desde 0.2.0 la regla es estructural**, ver "Versiones de effect" abajo.
178
178
  - **API Effect 4 (no 3)**: `Effect.catch` (no catchAll), `Effect.andThen` (no zipRight), `Effect.promise`, `Stream.tap/runDrain/forkScoped`.
179
179
  - **Conversión aplicada**: los 5 módulos (redact, events, advisor, guard, browser) + core exportan `register(ctx: Plugin.Context, config): Effect<void, never, Scope>`; registros con `yield* ctx.tool.transform(...)`, `yield* ctx.session.hook(...)`, `yield* ctx.permission.hook(...)`; cleanup vía `Effect.addFinalizer`. Storage/session bridges con `Effect.runPromise` en helpers async.
180
180
  - **tsconfig**: `skipLibCheck: true`; `cli/` excluido (herramienta WIP con `commander` no instalado).
@@ -201,3 +201,32 @@ console.log(await loadConfig('<proyecto>/.opencode/opencode-apex.jsonc')); // ->
201
201
  - **Copia de seguridad** (el repo no usa git): `/tmp/opencode/opencode-apex-webprovider-removed/`.
202
202
  - **Verificación**: `tsc --noEmit` y `--noUnusedLocals` a 0; browser 10/10, guard 56/56;
203
203
  `bun -e "import('./index.ts')"` → plugin `apex`.
204
+
205
+ ## Versiones de effect: cómo no volver a desalinearlas (0.2.0)
206
+
207
+ - **Síntoma (2026-10-23)**: con OpenCode 2.1.1, el apex local no cargaba:
208
+ `failed to load plugin … Schema.isStartsWith is not a function`.
209
+ - **Causa**: apex fijaba `"effect": "4.0.0-rc.112"` y pedía `@opencode/plugin: "latest"`.
210
+ Desde 2.1, `@opencode/plugin` usa effect **4.0.1**. Cada versión de OpenCode puede subirlo
211
+ de nuevo, así que un pin propio se desalinea tarde o temprano.
212
+ - **Solución (cuatro piezas)**:
213
+ 1. **Sin versión propia de effect.** `effect` es `peerDependency` **opcional** (`^4.0.0`).
214
+ npm no instala una copia aparte: el `import "effect"` de apex resuelve a la que trae
215
+ `@opencode/plugin`, que queda única en `node_modules`. La versión sigue sola a OpenCode.
216
+ 2. **Rangos caret** para `@opencode/plugin` y `@opencode/plugin-browser` (`^2.1.1`): siguen
217
+ las versiones 2.x de OpenCode. Ni `latest` ni versión exacta.
218
+ 3. **Aviso al cargar** (`core/compat.ts`), en el log del servidor y en la consola:
219
+ - si apex y `@opencode/plugin` resuelven copias distintas de effect;
220
+ - si OpenCode (`ctx.app.version`) es de un minor más nuevo que el `@opencode/plugin`
221
+ instalado. Pasa tras actualizar OpenCode, porque la caché npm de plugins no se
222
+ refresca sola.
223
+ En ambos casos, la solución es reinstalarlo (ver abajo).
224
+ 4. **`prepublishOnly` → `scripts/check-install.mjs`**: empaqueta, instala como OpenCode
225
+ (npm, `--ignore-scripts`) en un directorio temporal y falla si hay más de una copia de
226
+ effect o si el plugin no se importa. Una dependencia desalineada no llega a publicarse.
227
+ - **Tras actualizar OpenCode** (o para pasar a una apex nueva): con OpenCode parado, borra
228
+ `~/.cache/opencode/npm/opencode-apex@*` y arráncalo. Reinstala apex con el
229
+ `@opencode/plugin` nuevo. En 2.1.1, `opencode plugin update` responde
230
+ `Plugin is not configured` para los plugins de servidor: solo gestiona los de TUI (`cli.json`).
231
+ - **Rotura de API (OpenCode 3.x)**: el rango `^2` no la absorbe a propósito. Eso exige
232
+ revisar el código, no solo las dependencias.