opencode-apex 0.2.2 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,77 @@
3
3
  All notable changes to `opencode-apex`. Format based on
4
4
  [Keep a Changelog](https://keepachangelog.com/); versioning follows [SemVer](https://semver.org/).
5
5
 
6
+ ## [Unreleased]
7
+
8
+ ## [0.2.5] — 2026-11-24
9
+
10
+ 0.2.4 was never published to npm. Its changes are part of this release.
11
+
12
+ ### Added
13
+
14
+ - **`apex_callback_endpoint` finds OpenCode's remote access on its own.** When the
15
+ background service has remote access on (`opencode service set remote true`, an
16
+ OpenTunnel tunnel that OpenCode keeps up), `publicUrl` reports its address and the new
17
+ `publicUrlSource` says `service-remote`. Precedence is `apex_set_callback_url` (runtime)
18
+ > `events.server.publicUrl` (config) > remote access. apex reads the same files as
19
+ OpenCode: the route from the service config and the tunnel hostname from OpenTunnel's
20
+ `default` profile. It says that remote access is configured, not that the tunnel is
21
+ connected right now. `opencode serve` run in a terminal never reports it, because only
22
+ the service serves the tunnel.
23
+ - `publicRpc`: the `rpc.*` URLs built on `publicUrl`, for senders on other machines.
24
+ - The `apex-callbacks` skill makes OpenTunnel the first tunnel to try. It covers
25
+ publishing a relay with `opentunnel route add <port>` and what that relay may trust:
26
+ every request comes from loopback, so it must always check its token or signature. It
27
+ also covers remote access for senders the user controls. Third-party webhooks always
28
+ go to a relay, never to the server URL and password, which give full control of
29
+ OpenCode.
30
+
31
+ ## [0.2.4] — 2026-11-02
32
+
33
+ ### Added
34
+
35
+ - **The advisor now knows whose process a `kill` targets.** Before asking about a `shell`
36
+ permission that contains `kill`, `pkill`, `killall` or `kill $(pgrep …)`, apex reads
37
+ `/proc` and adds a `{{processes}}` block to the request. For each target it gives the
38
+ owner, the command, who launched it, and whether it is critical. Critical means the
39
+ OpenCode server itself, one of its parents, or PID 1. Who launched it comes from
40
+ `OPENCODE_SESSION_ID`, which OpenCode's `shell` tool exports to every command. The
41
+ possible values are this conversation (any session in the same tree), another
42
+ OpenCode conversation, the user, another user, or unknown. `kill -1`, `kill 0`,
43
+ process groups and patterns that match nothing get an explicit note.
44
+
45
+ Before this change the advisor only saw `kill 705875`. With a rule like "deny killing
46
+ processes that are not ours", it denied every plain `kill <PID>`, including processes
47
+ the agent had just started.
48
+ - `advisor.processContext` (default `true`) turns it off. It only works on Linux; on other
49
+ systems, or when `/proc` cannot be read, the request is unchanged.
50
+
51
+ ### Changed
52
+
53
+ - The advisor's cache key includes the process block. An answer for `kill 1234` is not
54
+ reused once PID 1234 belongs to a different process.
55
+ - A custom `promptTemplate` without `{{processes}}` gets the block appended at the end.
56
+
57
+ ## [0.2.3] — 2026-10-25
58
+
59
+ ### Changed
60
+
61
+ - The `apex-callbacks` skill now teaches relays in general, not only watchers and webhooks.
62
+ It covers:
63
+ - any source: messaging, email, SSE/WebSocket streams, queues, webhooks;
64
+ - any language and OS;
65
+ - what relay code can do with OpenCode and MCP tools through `tools.run`, and its limits;
66
+ - reachability: a relay behind NAT can't receive Internet webhooks without an outbound
67
+ mode, a tunnel (Cloudflare, Tailscale, ngrok), reverse SSH or store-and-forward.
68
+
69
+ `SKILL.md` stays short. The detail moved to `references/` (relays, reachability,
70
+ run-anywhere, examples), with a Python SSE relay, PowerShell ingest and GitHub signature
71
+ checks in the Node webhook relay. It also documents the subscription filter operators.
72
+
73
+ - Corrected the dependency explanation. OpenCode ≥ 2.1 serves `effect` and
74
+ `@opencode/plugin` to plugins from its own copy. What has to match the host are the other
75
+ `@opencode/*` packages installed with apex.
76
+
6
77
  ## [0.2.2] — 2026-10-23
7
78
 
8
79
  ### Fixed
package/README.md CHANGED
@@ -56,7 +56,7 @@ apex is one plugin with five independent modules. Each one can be switched on or
56
56
  | --- | --- | --- | --- |
57
57
  | **Redact** | Detects secrets (API keys, tokens, private keys…) in what the agent sees, encrypts them (AES-256-GCM) and replaces them with a readable marker. When the agent passes the marker back to a tool, the real value is restored. 41 bundles / 104 patterns. | on | [docs/REDACT.md](docs/REDACT.md) |
58
58
  | **Events** | Lets programs outside OpenCode (scripts, cron jobs, webhooks, n8n…) notify an agent. **Subscriptions** decide which session receives what. `tools.run` lets those programs use OpenCode tools. | on | [docs/EVENTS.md](docs/EVENTS.md) |
59
- | **Advisor** | When a tool call needs permission ("ask"), a small dedicated agent decides `allow` or `deny`, so you aren't asked about every step. | on | [docs/ADVISOR.md](docs/ADVISOR.md) |
59
+ | **Advisor** | When a tool call needs permission ("ask"), a small dedicated agent decides `allow` or `deny`, so you aren't asked about every step. For `kill`/`pkill` it is told whose process each target is (read from `/proc`). | on | [docs/ADVISOR.md](docs/ADVISOR.md) |
60
60
  | **Guard** | Meta-permissions per agent, tool and path, with a report of what was attempted and decided. | **off** | [docs/GUARD.md](docs/GUARD.md) |
61
61
  | **Browser** | Serves OpenCode's `browser.*` tools against an **external** Chromium over CDP (local or remote). You can also switch to the desktop app's built-in browser. 45 actions. | on | [docs/BROWSER.md](docs/BROWSER.md) |
62
62
 
@@ -157,16 +157,22 @@ on the other hand, loads the project on demand. The first call after an idle per
157
157
  few seconds.
158
158
 
159
159
  **Webhooks** work the same way, with one extra piece. A service such as GitHub or Stripe calls a
160
- small **relay** (n8n, or the ~30-line Node relay in the bundled skill). The relay turns that HTTP
160
+ small **relay** (n8n, or the Node relay in the bundled skill). The relay turns that HTTP
161
161
  call into `apex/events.ingest`. OpenCode itself doesn't expose a webhook URL.
162
162
 
163
+ The same idea covers any always-on event source: a relay keeps an outbound connection to a
164
+ chat app, a mailbox (IMAP IDLE), an SSE or WebSocket stream or a queue, and forwards what
165
+ matters.
166
+
163
167
  apex registers a skill, **`apex-callbacks`**, that teaches agents the whole recipe:
164
168
  - discovering the server URL;
165
169
  - subscribing;
166
- - a stateful watcher script;
167
- - systemd and cron;
168
- - the webhook relay and n8n;
169
- - `tools.run`.
170
+ - designing a relay or watcher in any language and running it on any OS (systemd, launchd,
171
+ Task Scheduler, Docker, pm2);
172
+ - calling OpenCode and MCP tools from relay code with `tools.run`, and its limits;
173
+ - reachability: why a relay behind NAT can't receive Internet webhooks, and the workarounds
174
+ (outbound modes, Cloudflare/Tailscale/ngrok tunnels, reverse SSH, store-and-forward);
175
+ - copyable examples in sh, Python, Node and PowerShell, plus an n8n recipe.
170
176
 
171
177
  Full reference: [docs/EVENTS.md](docs/EVENTS.md).
172
178
 
@@ -303,10 +309,12 @@ npm run check:install # installs the package like OpenCode
303
309
 
304
310
  `npm publish` runs tests, typecheck and the install check first (`prepublishOnly`).
305
311
 
306
- **Dependency rule.** apex doesn't pin its own `effect`. It uses the copy that
307
- `@opencode/plugin` brings: `effect` is an optional peer dependency, and `@opencode/plugin` is a
308
- `^2.1.1` dependency. That keeps apex aligned with each OpenCode release. See
309
- [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) before changing dependencies.
312
+ **Dependency rule.** OpenCode (≥ 2.1) serves `effect` and `@opencode/plugin` to plugins from
313
+ its own copy, so apex never pins `effect`: it is only an optional peer. The other `@opencode/*`
314
+ packages, such as `@opencode/schema`, do come from apex's own install and must match the host.
315
+ That's why `@opencode/plugin` is a `^2.1.1` dependency, and why apex is reinstalled after
316
+ upgrading OpenCode. See [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) before changing
317
+ dependencies.
310
318
 
311
319
  ```
312
320
  opencode-apex/
@@ -321,7 +329,7 @@ opencode-apex/
321
329
  │ ├── skills.ts # registers the skills shipped in skills/
322
330
  │ ├── compat.ts # load-time warnings when versions drift from OpenCode
323
331
  │ └── … # redact engine, patterns, crypto, conditions, guard, advisor
324
- ├── skills/apex-callbacks/SKILL.md # agent guide: callbacks, webhooks, watchers, tools.run
332
+ ├── skills/apex-callbacks/ # agent guide: SKILL.md + references/ (relays, reachability, run-anywhere, examples)
325
333
  ├── scripts/check-install.mjs # pre-publish install check
326
334
  ├── test/ # events, guard, browser suites
327
335
  └── docs/ # CONFIG · REDACT · EVENTS · ADVISOR · GUARD · BROWSER · TROUBLESHOOTING
package/advisor.ts CHANGED
@@ -24,6 +24,7 @@ import { ADVISOR_AGENT_ID, ensureAdvisorAgent } from "./core/advisor-agent.js"
24
24
  import { readOrCreateTemplate } from "./core/templates.js"
25
25
  import { registerAdvisorTool } from "./core/advisor-tool.js"
26
26
  import {
27
+ buildProcessContext,
27
28
  DEFAULT_ADVISOR_REQUEST_TEMPLATE,
28
29
  isAdvisorSession,
29
30
  requestAdvisorDecision,
@@ -63,6 +64,13 @@ export interface AdvisorConfig {
63
64
  * ancestros del home; el AGENTS.md global de ~/.config/opencode sigue aplicando.
64
65
  */
65
66
  location?: string
67
+ /**
68
+ * Antes de consultar un `kill`/`pkill`/`killall`, lee `/proc` y le dice al advisor
69
+ * de quién es cada proceso: dueño, comando, si lo lanzó un agente de esta
70
+ * conversación y si es crítico (el propio opencode). Por defecto `true`. Sin
71
+ * esto el advisor ve `kill 1234` y nada más. Solo Linux; en otro sistema no añade nada.
72
+ */
73
+ processContext?: boolean
66
74
  }
67
75
 
68
76
  // ---------------------------------------------------------------------------
@@ -102,9 +110,14 @@ interface PermissionEvaluationEvent {
102
110
  message?: string
103
111
  }
104
112
 
105
- function generateCacheKey(action: string, resources: readonly string[]): string {
113
+ /**
114
+ * `context` entra en la clave porque cambia la respuesta correcta: `kill 1234`
115
+ * aprobado cuando 1234 era el servidor de pruebas del agente no vale cuando ese
116
+ * PID se ha reciclado y ahora es el navegador del usuario.
117
+ */
118
+ function generateCacheKey(action: string, resources: readonly string[], context = ""): string {
106
119
  const sorted = [...resources].sort()
107
- const input = action + JSON.stringify(sorted)
120
+ const input = action + JSON.stringify(sorted) + context
108
121
  return createHash("sha256").update(input).digest("hex").slice(0, 32)
109
122
  }
110
123
 
@@ -168,6 +181,7 @@ export function register(
168
181
  const template = templateFile.content ?? config.promptTemplate ?? DEFAULT_ADVISOR_REQUEST_TEMPLATE
169
182
  const evaluateAll = config.evaluate === "all"
170
183
  const actionFilter = new Set(config.actions ?? [])
184
+ const processContext = config.processContext ?? true
171
185
 
172
186
  // 1. Agente advisor dedicado (upsert)
173
187
  yield* ensureAdvisorAgent(ctx, { model: config.model, system: config.system, decisive })
@@ -192,7 +206,13 @@ export function register(
192
206
  if (!evaluateAll && e.effect !== "ask") return
193
207
 
194
208
  const startedAt = Date.now()
195
- const cacheKey = generateCacheKey(e.action, e.resources)
209
+ // Se calcula ANTES de la caché: forma parte de la clave.
210
+ const processes = processContext
211
+ ? await buildProcessContext(ctx, { sessionID: e.sessionID, action: e.action, resources: e.resources }).catch(
212
+ () => null,
213
+ )
214
+ : null
215
+ const cacheKey = generateCacheKey(e.action, e.resources, processes?.text)
196
216
 
197
217
  // Camino rápido: veredicto cacheado
198
218
  const cached = cache.get(cacheKey)
@@ -219,6 +239,7 @@ export function register(
219
239
  timeoutMs,
220
240
  template,
221
241
  location: config.location,
242
+ processes: processes?.text,
222
243
  })
223
244
 
224
245
  if (!decision) {
@@ -286,5 +307,6 @@ export function createDefaultAdvisorConfig(): AdvisorConfig {
286
307
  timeoutMs: DEFAULT_TIMEOUT_MS,
287
308
  actions: [],
288
309
  promptTemplate: DEFAULT_ADVISOR_REQUEST_TEMPLATE,
310
+ processContext: true,
289
311
  }
290
312
  }
@@ -20,6 +20,13 @@ import { randomUUID } from "node:crypto"
20
20
  import { Effect } from "effect"
21
21
  import type { Plugin } from "@opencode/plugin/effect"
22
22
  import { ADVISOR_AGENT_ID } from "./advisor-agent.js"
23
+ import {
24
+ currentUid,
25
+ formatProcessContext,
26
+ launchers,
27
+ processTargetsFor,
28
+ type TargetDescription,
29
+ } from "./process-context.js"
23
30
 
24
31
  export interface AdvisorDecision {
25
32
  readonly decision: "allow" | "deny"
@@ -39,6 +46,11 @@ export interface AdvisorRequest {
39
46
  readonly template: string
40
47
  /** Directorio de la sesión advisor (aislado del proyecto por defecto). */
41
48
  readonly location?: string
49
+ /**
50
+ * Bloque `{{processes}}` ya calculado (ver `buildProcessContext`). Vacío o
51
+ * ausente si el comando no mata ningún proceso.
52
+ */
53
+ readonly processes?: string
42
54
  }
43
55
 
44
56
  // ---------------------------------------------------------------------------
@@ -209,6 +221,10 @@ export async function getOrCreateAdvisorSession(
209
221
 
210
222
  /** Renderiza la petición para el advisor (placeholders de la plantilla). */
211
223
  export function renderAdvisorRequest(template: string, input: AdvisorRequest, requestID: string): string {
224
+ // Una plantilla propia escrita antes de 0.2.4 no trae `{{processes}}`, y sin
225
+ // ese bloque el advisor vuelve a juzgar un `kill <PID>` a ciegas. Se añade al
226
+ // final en vez de exigir que cada usuario edite su plantilla.
227
+ if (input.processes && !template.includes("{{processes}}")) template = `${template}\n\n{{processes}}`
212
228
  const enforcement = input.decisive
213
229
  ? "Tu decisión se APLICA automáticamente."
214
230
  : "Tu decisión se muestra al usuario, que decide."
@@ -220,6 +236,7 @@ export function renderAdvisorRequest(template: string, input: AdvisorRequest, re
220
236
  .replace(/\{\{sessionID\}\}/g, input.sessionID)
221
237
  .replace(/\{\{agent\}\}/g, input.agent ?? "default")
222
238
  .replace(/\{\{enforcement\}\}/g, enforcement)
239
+ .replace(/\{\{processes\}\}/g, input.processes ?? "")
223
240
  .replace(/\{\{metadata\.([^}]+)\}\}/g, (_m, path: string) => {
224
241
  const value = path
225
242
  .split(".")
@@ -234,10 +251,35 @@ export const DEFAULT_ADVISOR_REQUEST_TEMPLATE = `Solicitud de permiso {{requestI
234
251
  Herramienta: {{action}}
235
252
  Recursos: {{resources}}
236
253
  Sesión solicitante: {{sessionID}} · Agente: {{agent}}
254
+ {{processes}}
237
255
  {{enforcement}}
238
256
 
239
257
  Decidí con \`apex_advisor_decide\` (requestID={{requestID}}). Si denegás, incluí un motivo.`
240
258
 
259
+ /**
260
+ * Bloque de procesos para un permiso de `shell` que mata algo, o "" si no mata nada.
261
+ *
262
+ * «De esta conversación» significa del mismo ÁRBOL que la sesión solicitante: un
263
+ * proceso arrancado por el agente principal y matado por un subagente (o al revés)
264
+ * es trabajo propio. Para saberlo, cada sesión que aparece como lanzadora en /proc
265
+ * se sube hasta su raíz y se compara con la raíz de quien pide el permiso. Solo se
266
+ * resuelven las sesiones que aparecen — normalmente una o ninguna.
267
+ */
268
+ export async function buildProcessContext(
269
+ ctx: Plugin.Context,
270
+ input: { sessionID: string; action: string; resources: readonly string[] },
271
+ ): Promise<{ text: string; targets: TargetDescription[] } | null> {
272
+ const targets = processTargetsFor(input.action, input.resources)
273
+ if (!targets) return null
274
+ const rootID = await resolveRootSessionID(ctx, input.sessionID)
275
+ const tree = new Set<string>([input.sessionID, rootID])
276
+ for (const launcher of launchers(targets)) {
277
+ if (tree.has(launcher)) continue
278
+ if ((await resolveRootSessionID(ctx, launcher)) === rootID) tree.add(launcher)
279
+ }
280
+ return { text: formatProcessContext(targets, { selfUid: currentUid(), treeSessions: tree }), targets }
281
+ }
282
+
241
283
  /**
242
284
  * Pide una decisión al advisor del árbol.
243
285
  * Devuelve null si: la sesión solicitante es la del advisor, no hay sesión
package/core/compat.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  /**
2
2
  * Compatibilidad con la versión de OpenCode que carga el plugin.
3
3
  *
4
- * apex usa `effect` sin declarar versión propia: la toma de `@opencode/plugin`
5
- * (peer opcional en package.json), así que npm instala UNA sola copia y la versión
6
- * sigue sola a la de OpenCode. Si aun así hubiera dos copias (una instalación vieja
7
- * en caché, un gestor que no hoistea), los efectos de una no se entienden con la otra
8
- * y el fallo llega críptico (`Schema.isStartsWith is not a function`, "missing TypeId").
9
- * Aquí se detecta al cargar y se dice qué hacer.
4
+ * Desde 2.1, OpenCode sirve a los plugins `effect` y `@opencode/plugin` desde SU copia
5
+ * (packages/plugin/src/runtime.ts): esos dos nunca se desalinean. Lo que sí viene del
6
+ * node_modules de apex son los demás `@opencode/*` (`@opencode/schema`, `@opencode/client`,
7
+ * `@opencode/plugin-browser`), que corren sobre el `effect` del host: si son de una versión
8
+ * anterior, el fallo llega críptico (`Schema.isStartsWith is not a function`).
9
+ * Aquí se detecta al cargar (OpenCode más nuevo que el `@opencode/plugin` instalado, o dos
10
+ * copias de `effect` en disco) y se dice qué hacer.
10
11
  *
11
12
  * La caché npm de plugins de OpenCode no se refresca sola: tras actualizar OpenCode,
12
13
  * apex sigue con las dependencias de cuando se instaló hasta que se reinstala.
package/core/config.ts CHANGED
@@ -78,7 +78,7 @@ export interface EventsServerConfig {
78
78
  /**
79
79
  * URL pública por DEFECTO (túnel o proxy inverso hacia el servidor) para emisores
80
80
  * de otras máquinas. El agente puede fijarla en runtime con `apex_set_callback_url`
81
- * (precedencia: runtime > esta config).
81
+ * (precedencia: runtime > esta config > acceso remoto del servicio, que se descubre solo).
82
82
  */
83
83
  publicUrl?: string
84
84
  }
@@ -197,6 +197,8 @@ const advisorConfigSchema = z.object({
197
197
  evaluate: z.enum(["ask-only", "all"]).default("ask-only"),
198
198
  timeoutMs: z.number().int().positive().default(10000),
199
199
  location: z.string().optional(),
200
+ // Lee /proc antes de juzgar un kill: de quién es cada PID. Ver core/process-context.ts.
201
+ processContext: z.boolean().default(true),
200
202
  })
201
203
 
202
204
  const guardRuleSchema = z.object({
@@ -237,7 +239,7 @@ const browserConfigSchema = z.object({
237
239
  export const apexConfigSchema = z.object({
238
240
  redact: redactConfigSchema.default(() => ({ mode: "strict" as const, patterns: [], bundles: [...DEFAULT_BUNDLES], minConfidence: "medium" as const, allowlist: [], prefix: "[SECRET:", suffix: "]", key: "", restore: { toolInput: true } })),
239
241
  events: eventsConfigSchema.default(() => ({ routing: "all" as const, subscriptions: [], server: {}, tools: defaultEventsTools() })),
240
- advisor: advisorConfigSchema.default(() => ({ actions: [], decisive: false, evaluate: "ask-only" as const, timeoutMs: 10000 })),
242
+ advisor: advisorConfigSchema.default(() => ({ actions: [], decisive: false, evaluate: "ask-only" as const, timeoutMs: 10000, processContext: true })),
241
243
  guard: guardConfigSchema.default(() => ({
242
244
  mode: "report" as const,
243
245
  fallback: "keep" as const,