opencode-apex 0.2.3 → 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
@@ -5,6 +5,55 @@ All notable changes to `opencode-apex`. Format based on
5
5
 
6
6
  ## [Unreleased]
7
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
+
8
57
  ## [0.2.3] — 2026-10-25
9
58
 
10
59
  ### Changed
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
 
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/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,