opencode-apex 0.2.1 → 0.2.3

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/core/rpc.ts CHANGED
@@ -88,7 +88,7 @@ export function registerCentralRpc(
88
88
  return Effect.gen(function* () {
89
89
  const startedAt = Date.now()
90
90
  const { modules, events } = input
91
- const eventsOff = "módulo events desactivado (modules.events=false)"
91
+ const eventsOff = "the events module is disabled (modules.events=false)"
92
92
  const endpoint = (): ServerEndpoint | null => events?.endpoint() ?? null
93
93
 
94
94
  yield* ctx.rpc.register(APEX_RPC_DEFINITION as never, {
@@ -156,7 +156,7 @@ export function resolveServerEndpoint(input: {
156
156
  },
157
157
  ...(baseUrl
158
158
  ? {}
159
- : { hint: "URL del servidor desconocida: fija events.server.url en la config de apex (p. ej. http://127.0.0.1:4096)" }),
159
+ : { hint: "Server URL unknown: set events.server.url in the apex config (e.g. http://127.0.0.1:4096)" }),
160
160
  }
161
161
  }
162
162
 
package/core/tools-run.ts CHANGED
@@ -56,8 +56,8 @@ export function wildcard(pattern: string, value: string): boolean {
56
56
  }
57
57
 
58
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}`
59
+ if (config.deny.some((pattern) => wildcard(pattern, name))) return `tool denied for tools.run (events.tools.deny): ${name}`
60
+ if (!config.allow.some((pattern) => wildcard(pattern, name))) return `tool not in events.tools.allow: ${name}`
61
61
  return null
62
62
  }
63
63
 
@@ -83,7 +83,7 @@ export function ensureRunnerAgent(ctx: Plugin.Context): Effect.Effect<void, neve
83
83
  yield* ctx.agent.transform((editor) => {
84
84
  editor.update(RUNNER_AGENT_ID, (agent) => {
85
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"
86
+ agent.description = "apex technical session for tools.run (RPC); not a working agent"
87
87
  agent.mode = "subagent"
88
88
  agent.hidden = true
89
89
  agent.permissions = [{ action: "*", resource: "*", effect: "deny" }] as never
@@ -128,8 +128,8 @@ export function makeToolsRunner(ctx: Plugin.Context, config: ToolsRunConfig) {
128
128
  error,
129
129
  durationMs: Date.now() - started,
130
130
  })
131
- if (!config.enabled) return fail("tools.run desactivado (events.tools.enabled=false)")
132
- if (!tool) return fail("falta 'tool'")
131
+ if (!config.enabled) return fail("tools.run is disabled (events.tools.enabled=false)")
132
+ if (!tool) return fail("missing 'tool'")
133
133
  const blocked = checkTool(tool, config)
134
134
  if (blocked) return fail(blocked)
135
135
 
@@ -137,7 +137,7 @@ export function makeToolsRunner(ctx: Plugin.Context, config: ToolsRunConfig) {
137
137
  try {
138
138
  const tools = await Effect.runPromise(ctx.tool.list())
139
139
  const found = tools.find((candidate) => candidate.id === tool)
140
- if (!found) return fail(`herramienta no registrada en este directorio: ${tool}`, agent)
140
+ if (!found) return fail(`tool not registered in this project: ${tool}`, agent)
141
141
 
142
142
  const sessionID = await session()
143
143
  const result = await Effect.runPromise(
@@ -161,7 +161,7 @@ export function makeToolsRunner(ctx: Plugin.Context, config: ToolsRunConfig) {
161
161
  }
162
162
  } catch (error) {
163
163
  const timedOut = Date.now() - started >= (input.timeoutMs ?? config.timeoutMs)
164
- return fail(timedOut ? `timeout tras ${input.timeoutMs ?? config.timeoutMs} ms` : errorText(error), agent)
164
+ return fail(timedOut ? `timed out after ${input.timeoutMs ?? config.timeoutMs} ms` : errorText(error), agent)
165
165
  }
166
166
  }
167
167
  }
package/docs/ADVISOR.md CHANGED
@@ -1,91 +1,149 @@
1
- # Apex Advisor — decisiones de permiso con sesión dedicada
2
-
3
- ## Arquitectura
1
+ # Apex Advisor — let a second model answer permission prompts
2
+
3
+ > **OpenCode V2 only (>= 2.1).** This module uses the V2 plugin API (`permission.evaluate`
4
+ > hook, agents and sessions created by plugins). It does not work on OpenCode V1.
5
+
6
+ The advisor answers "may this tool run?" questions for you. When OpenCode would normally
7
+ stop and show you a permission prompt, apex asks a dedicated, cheap model instead, and
8
+ either applies its answer (`decisive: true`) or shows it to you next to the prompt
9
+ (`decisive: false`).
10
+
11
+ ## Background: how permissions work in OpenCode V2
12
+
13
+ You do not need to know OpenCode internals to use the advisor, but these few facts explain
14
+ what it can and cannot do.
15
+
16
+ - **Every tool call is checked against rules.** A rule looks like
17
+ `{ "action": "shell", "resource": "git *", "effect": "allow" }`:
18
+ - `action` is the tool or permission name: `read`, `edit`, `shell`, an MCP tool…
19
+ - `resource` is what the tool touches: a path, a command line…
20
+ - `effect` is `allow`, `deny` or `ask`.
21
+ - Both `action` and `resource` accept `*` wildcards.
22
+ - **The last matching rule wins.** The rules of the current agent come first, then the
23
+ rules of the session. A rule added later overrides an earlier one. If no rule matches, the
24
+ result is `ask`.
25
+ - **`ask` means "show the user a prompt"**: the tool call waits until someone answers
26
+ Allow / Deny. If you answered "Always allow" before, that saved answer turns a later `ask`
27
+ into `allow`.
28
+ - **`deny` is final.** OpenCode stops a denied call *before* any plugin sees it. Plugins can
29
+ only act on calls whose effect is `allow` or `ask`.
30
+ - **Plugins can rewrite the decision.** For every call that is not hard-denied, OpenCode runs
31
+ the `permission.evaluate` hook of every plugin, in the order they registered. Each hook may
32
+ change the effect (`allow` / `ask` / `deny`) and attach a message. The advisor is one such
33
+ hook.
34
+
35
+ ## How it works
4
36
 
5
37
  ```
6
- sesión raíz (agente ↔ usuario)
38
+ your session (agent ↔ you)
7
39
  ├── tool call ─┐
8
- ├── subagente A → tool call ├─► UNA sesión advisor del árbol ─► agente apex-advisor
9
- └── subagente B → tool call ─┘ (contexto completo, modelo barato)
40
+ ├── subagent A → tool call ├─► ONE advisor session for the whole tree ─► agent apex-advisor
41
+ └── subagent B → tool call ─┘ (full history, cheap model)
10
42
  │
11
43
  apex_advisor_decide(requestID, allow | deny + reason)
12
44
  ```
13
45
 
14
- - **Una sola sesión advisor por ÁRBOL de sesiones.** La raíz se resuelve subiendo
15
- por `parentID` (`Session.Info.parentID`); todos los subagentes de esa raíz
16
- comparten la misma sesión advisor.
17
- - **Agente dedicado** `apex-advisor`: el plugin lo define por *upsert*
18
- (`agent.transform` → `editor.update`, que en v2 crea el agente si no existe).
19
- Es `mode: "subagent"`, `hidden: true`, con su propio `model` y un ruleset que
20
- le permite **exclusivamente** la herramienta de decisión.
21
- - **Una única herramienta**: `apex_advisor_decide`. El vocabulario es
22
- `allow` (aprobar la ejecución) o `deny` + `reason` (denegar).
23
- - **Auditable**: la sesión advisor queda registrada completa — es el histórico
24
- de cada evaluación allow/deny pedida por otras sesiones.
25
-
26
- ## Flujo
27
-
28
- 1. Se dispara el hook `permission.evaluate` para una tool de cualquier sesión del árbol.
29
- 2. Guardas: se ignora si la sesión es la del advisor; filtro de `actions`; por
30
- defecto solo si el efecto es `"ask"` (`evaluate: "ask-only"`).
31
- 3. Caché por `(action, resources)` con TTL 10 min → si hay veredicto previo, no se consulta.
32
- 4. Se resuelve la raíz y se obtiene/crea la sesión advisor (mapeo persistido en storage).
33
- 5. Se registra una decisión pendiente (`requestID` → promesa) y se envía la petición
34
- con `session.prompt({ delivery: "steer", resume: true })`.
35
- 6. El agente advisor responde llamando a `apex_advisor_decide`, que resuelve la promesa.
36
- 7. Se aplica la decisión según `decisive` y se anota en el audit log.
37
-
38
- Si no llega decisión (timeout/error) **no se altera el permiso original**.
39
-
40
- ## Semántica de `decisive`
41
-
42
- | `decisive` | Efecto sobre el permiso | `message` |
43
- | ---------- | ----------------------- | --------- |
44
- | `true` | `allow`/`deny` sustituyen el efecto; `deny` bloquea | motivo de la denegación |
45
- | `false` | **no se toca** el efecto | se anexa `⚖ apex.advisor: <decisión> — <motivo>` |
46
-
47
- ## Configuración
46
+ 1. A tool call in any session of the tree reaches the `permission.evaluate` hook.
47
+ 2. The advisor skips it when:
48
+ - it comes from the advisor's own session or agent;
49
+ - the tool is not in `actions` (when you set a filter);
50
+ - its effect is not `ask`. This is the default, `evaluate: "ask-only"`; with
51
+ `evaluate: "all"` the advisor also judges calls that were already `allow`.
52
+ 3. **Cache:** if the same `(action, resources)` pair was decided in the last 10 minutes,
53
+ that answer is reused without asking the model. The cache is stored in plugin storage,
54
+ so it survives reloads.
55
+ 4. Otherwise apex finds the **root** of the session tree (it follows `parentID` upwards,
56
+ at most 25 levels) and gets or creates the advisor session for that root.
57
+ 5. It sends the request to the advisor session as a prompt (`delivery: "steer"`,
58
+ `resume: true`), so the advisor agent wakes up.
59
+ 6. The advisor agent answers by calling its only tool, `apex_advisor_decide`, with the
60
+ request id and `allow` or `deny` + `reason`. A deny without a reason is rejected, and so
61
+ is any value other than `allow` / `deny`.
62
+ 7. apex applies the answer according to `decisive` and writes it to an audit log (the last
63
+ 100 decisions, in plugin storage).
64
+
65
+ **If no answer arrives in time** (`timeoutMs`, 10 s by default) or something fails,
66
+ the original permission is left untouched: you get the normal prompt.
67
+
68
+ ### The advisor agent and its session
69
+
70
+ - apex creates (or updates) a hidden agent **`apex-advisor`**:
71
+ - `mode: "subagent"` and `hidden: true`, so it never appears in your agent list;
72
+ - it uses its own `model`;
73
+ - its permission rules deny everything except `execute` and `apex_advisor_decide`.
74
+
75
+ `execute` is needed because in OpenCode V2 models call tools from a JavaScript sandbox
76
+ ("Code Mode"). Without it the advisor could decide but never deliver its answer. Every
77
+ tool called from that sandbox still goes through the same rules, so the advisor cannot
78
+ touch your files.
79
+ - **One advisor session per session tree.** Your main session and all its subagents share
80
+ it, so the advisor sees every earlier request and answer. The session is kept, which also
81
+ makes it a complete audit trail of what was asked and decided.
82
+
83
+ ## `decisive`
84
+
85
+ | `decisive` | Effect on the permission | Message |
86
+ | --- | --- | --- |
87
+ | `true` | the advisor's `allow` / `deny` replaces the effect. A `deny` blocks the call | the deny reason |
88
+ | `false` (default) | the effect is **not** changed: you still get the prompt | `⚖ apex.advisor: <decision> — <reason>` is added to it |
89
+
90
+ ## Configuration
91
+
92
+ The advisor module is **on by default** (`modules.advisor`). Set `"advisor": false` in
93
+ `modules` to turn it off. The values below are the defaults, except `model` and `decisive`:
48
94
 
49
95
  ```jsonc
96
+ "modules": { "advisor": true },
50
97
  "advisor": {
51
- "model": "opencode/big-pickle", // modelo del agente advisor (rápido/barato)
52
- "decisive": true,
53
- "evaluate": "ask-only", // "ask-only" | "all" (cada tool call)
54
- "timeoutMs": 10000,
55
- "actions": [], // vacío = todas las tools
56
- "system": "…", // opcional: system prompt del agente
57
- "promptTemplate": "…" // opcional: plantilla de la petición
98
+ "model": "opencode/big-pickle", // "providerID/modelID"; pick a fast, cheap one. Unset = the default model
99
+ "decisive": true, // default false: only advise, never change the effect
100
+ "evaluate": "ask-only", // "ask-only" | "all" (every tool call — much slower)
101
+ "timeoutMs": 10000, // wait this long for an answer, then leave the permission as it was
102
+ "actions": [], // tool names to judge; empty = all
103
+ "location": "", // advisor session directory; empty = <tmp>/opencode-apex-advisor
104
+ "system": "…", // optional: replaces the advisor's system prompt
105
+ "promptTemplate": "…", // optional: the request text sent to the advisor
106
+ "promptTemplateFile": "…" // optional: same, from a file (wins over promptTemplate)
58
107
  }
59
108
  ```
60
109
 
61
- ## Aislamiento de instrucciones (AGENTS.md)
110
+ - **Template placeholders:** `{{requestID}}`, `{{action}}`, `{{resources}}`, `{{sessionID}}`,
111
+ `{{agent}}`, `{{enforcement}}` (a sentence that tells the advisor whether its decision is
112
+ applied) and `{{metadata.<path>}}`.
113
+ - **`promptTemplateFile`** must be a relative path, inside the project or your home
114
+ directory. If the file does not exist, it is created with the default template.
62
115
 
63
- V2 **no** permite instrucciones por agente: `ConfigAgent` no tiene campo
64
- `instructions` y `agent.system` solo sustituye el prompt de sistema por defecto
65
- (las instrucciones descubiertas se anexan siempre en `baseTranscript`). PERO la
66
- discovery de instrucciones es **por location** (`InstructionDiscovery` es un
67
- `makeLocationNode`) y el proyecto solo entra si la sesión está dentro de su root:
116
+ ## Keeping the project's AGENTS.md away from the advisor
68
117
 
69
- ```ts
70
- const project = discovery.project && FSUtil.contains(root, start)
71
- const projectSource = () => { if (!project) return [] }
72
- ```
118
+ OpenCode V2 has no per-agent instructions. Every session gets the instruction files found
119
+ for its **directory**: the project's `AGENTS.md`, plus files found walking up from it. An
120
+ advisor that reads your repo's coding rules is slower and gets confused about its job.
121
+
122
+ That is why apex creates the advisor session in a dedicated directory **outside the
123
+ project** (`advisor.location`, by default `<tmp>/opencode-apex-advisor`):
124
+
125
+ - ✅ the repository's `AGENTS.md` and its parent directories are not loaded;
126
+ - ✅ being outside your home, the home-directory chain is not walked either;
127
+ - ⚠️ the **global** `~/.config/opencode/AGENTS.md` and `instructions` from your config still
128
+ apply. A plugin cannot turn those off.
73
129
 
74
- Por eso la sesión advisor se crea en un **directorio dedicado fuera del proyecto**
75
- (`advisor.location`, por defecto `${tmpdir}/opencode-apex-advisor`):
130
+ Changing `advisor.location` makes apex create a new advisor session. The location is stored
131
+ in the session's `metadata.apexAdvisorLocation`.
76
132
 
77
- - ✅ NO se inyecta el `AGENTS.md` del repositorio ni la cadena de ancestros del proyecto.
78
- - ✅ Fuera de `$HOME` tampoco se camina la cadena del home.
79
- - ⚠️ El `AGENTS.md` global (`~/.config/opencode/AGENTS.md`) y `config.instructions`
80
- **sí aplican** — no son controlables desde un plugin.
133
+ ## Limitations
81
134
 
82
- Cambiar `advisor.location` invalida la sesión advisor anterior y crea una nueva
83
- (la location queda registrada en `metadata.apexAdvisorLocation`).
135
+ - **The advisor session is a sibling, not a child, of your session.** OpenCode 2.1 lets a
136
+ plugin create a session with `parentID`, but then the plugin cannot choose its directory:
137
+ it would run in your project and load its `AGENTS.md`. apex keeps it separate and stores
138
+ the link in `metadata.apexAdvisorFor`.
139
+ - **Each uncached decision costs one model round trip.** With `evaluate: "all"`, every tool
140
+ call waits for it.
141
+ - **The cache key is only `(action, resources)`.** An answer given for one agent is reused
142
+ for any other agent asking the same thing within 10 minutes.
143
+ - **A missing answer never blocks you:** after `timeoutMs` the normal prompt appears.
84
144
 
85
- ## Limitaciones conocidas
145
+ ## Working with the guard
86
146
 
87
- - `session.create` **no acepta `parentID`**, así que la sesión advisor es lateral
88
- (sin padre), no un hijo del árbol. El vínculo se guarda en `metadata.apexAdvisorFor`.
89
- - El advisor añade una ronda de modelo por evaluación no cacheada: con
90
- `evaluate: "all"` y sin caché, cada tool call paga esa latencia.
91
- - Un `parentID` más profundo que 25 niveles se trata como raíz (protección).
147
+ If the [guard](GUARD.md) module is also on, it is registered **before** the advisor. The
148
+ guard resolves what its rules cover, and the advisor only judges what is still `ask`
149
+ afterwards. See [GUARD.md § Order](GUARD.md#order-guard-first-then-advisor).