opencode-apex 0.2.1 → 0.2.2

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/docs/GUARD.md CHANGED
@@ -1,65 +1,88 @@
1
- # Apex Guard — meta-permisos por agente
1
+ # Apex Guard — per-agent permission rules, decided by the plugin
2
2
 
3
- Decide `allow` / `deny` / `ask` por agente, herramienta y ruta, **desde el plugin**,
4
- y deja constancia de cada decisión.
3
+ > **OpenCode V2 only (>= 2.1).** The guard is a `permission.evaluate` hook of the V2 plugin
4
+ > API.
5
5
 
6
- ## Por qué no basta con `permission` en la config
6
+ The guard lets you say, per agent, which tools and paths are allowed, denied or must be
7
+ asked about, and it keeps a report of every decision. It is **off by default**
8
+ (`modules.guard`). When you turn it on, it starts in `report` mode: it only records what it
9
+ *would* do.
7
10
 
8
- Dos motivos, los dos medidos:
11
+ ## Background: OpenCode V2 permissions in 30 seconds
9
12
 
10
- **1. Un `deny` en la config esconde la herramienta, y el free tier de Zen rechaza al
11
- agente al que le falte una.** El mensaje es *«OpenCode's free tier can only be used from
12
- within OpenCode»*, que suena a otra cosa. Basta una regla:
13
+ (Longer version in [ADVISOR.md § Background](ADVISOR.md#background-how-permissions-work-in-opencode-v2).)
13
14
 
14
- | Frontmatter del agente | Resultado |
15
+ - **Rules.** OpenCode checks each tool call against rules
16
+ `{ action, resource, effect: "allow" | "deny" | "ask" }`. Wildcards `*` are allowed, the
17
+ **last matching rule wins**, and no match means `ask`, which prompts you.
18
+ - **Where rules come from.** The agent's rules come first, then the session's.
19
+ - **Plugins.** They see each call in the `permission.evaluate` hook and may change the
20
+ effect, **except** for calls already denied by those rules. A `deny` in your config ends
21
+ the evaluation before any plugin runs.
22
+
23
+ ## Why not just write `deny` rules in the config?
24
+
25
+ Two observed reasons. Each one is enough on its own.
26
+
27
+ **1. A config `deny` on a native tool can get the agent rejected by OpenCode Zen's free
28
+ tier.** A `deny` removes the tool from the agent's toolset. In our tests, a custom agent with
29
+ any native tool removed was refused by the Zen free models with *"OpenCode's free tier can
30
+ only be used from within OpenCode"*, an error that does not hint at the cause. One rule was
31
+ enough:
32
+
33
+ | Custom agent (`agents/*.md` frontmatter) | Result on Zen free models |
15
34
  | --- | --- |
16
- | sin `permission`, o solo con `allow` / `ask` | OK |
17
- | `temperature`, system prompt propio de 3 600 caracteres | OK |
18
- | **`permission: { shell: deny }`** | **RECHAZADO** |
19
- | **`tools: { shell: false }`** | **RECHAZADO** |
35
+ | no `permission`, or only `allow` / `ask` | OK |
36
+ | `temperature`, own 3 600-character system prompt | OK |
37
+ | **`permission: { shell: deny }`** | **rejected** |
38
+ | **`tools: { shell: false }`** | **rejected** |
20
39
 
21
- Solo afecta al **toolset nativo**. Un `deny` sobre tools de MCP o de plugin
22
- (`hindsight_*`, `apex_*`) no dispara nada — comprobado con `nemotron-3-ultra-free` y
23
- `hindsight_banks_delete_bank`. Esas se siguen denegando en `permission`, que es más
24
- simple; el guard solo gobierna lo nativo.
40
+ Notes on these observations:
25
41
 
26
- `space-bunny-free` es el único gratuito exento del gate.
42
+ - **Scope.** Only native tools trigger this. Denying MCP or plugin tools (`hindsight_*`,
43
+ `apex_*`) did not. Tested with `nemotron-3-ultra-free` and `hindsight_banks_delete_bank`.
44
+ For those tools, a plain config `deny` is fine.
45
+ - **Exception.** `space-bunny-free` was the only free model not affected.
46
+ - **Not fully explained.** OpenCode's own `explore` agent ships with
47
+ `{ action: "*", resource: "*", effect: "deny" }` (`packages/core/src/plugin/agent.ts`). Its
48
+ toolset is filtered the same way (`registry.snapshot(permissions)` in
49
+ `session/context.ts`), and yet it is *not* rejected. Something else tells built-in agents
50
+ from custom ones.
51
+ - **What is reproducible** is the table above: 3 out of 3 rejections for a `deny` in a custom
52
+ `.md` agent.
27
53
 
28
- **Qué NO está explicado.** El agente `explore` que trae opencode lleva
29
- `{ action: "*", effect: "deny" }` de fábrica (`packages/core/src/plugin/agent.ts`), su
30
- catálogo se filtra igual que el de cualquiera (`registry.snapshot(permissions)` en
31
- `session/context.ts`) y aun así **no** lo rechazan. O sea que «toolset recortado» describe
32
- el patrón pero no es el mecanismo: algo distingue un agente nativo de uno propio. Lo
33
- medido y reproducible es lo de la tabla — un `deny` en un `.md` propio, 3 de 3 rechazos —,
34
- y sobre eso se apoya este módulo. La regla práctica no cambia: en tus agentes, ningún
35
- `deny` sobre herramientas nativas.
54
+ The practical rule: **in your own agents, do not `deny` native tools in the config.**
36
55
 
37
- **2. Un `deny` de config no llega a los plugins.** El host corta antes:
56
+ **2. A config `deny` never reaches plugins.** OpenCode stops before the hooks:
38
57
 
39
58
  ```ts
40
- // packages/core/src/permission.ts
41
- if (denied(input, rules)) return { effect: "deny", rules } // sin pasar por hooks
42
- const event = yield* hooks.trigger("permission", "evaluate", …)
59
+ // packages/core/src/permission.ts (OpenCode 2.1.1)
60
+ if (denied(input, rules)) return { effect: "deny", rules } // no hooks run
61
+ …
62
+ const event = yield* hooks.trigger("permission", "evaluate", { …, effect })
43
63
  ```
44
64
 
45
- Así que un `deny` declarado ahí no se puede interceptar, matizar por ruta ni auditar.
65
+ So a config `deny` cannot be refined per path, cannot be logged, and cannot be reported.
46
66
 
47
- **El reparto que sale de ahí**: en `permission` y en los `agents/*.md` no hay ningún
48
- `deny` sobre herramientas nativas — todo es `allow` o `ask`, el toolset queda entero — y
49
- la prohibición se decide aquí, sobre el `ask` que sí llega al hook.
67
+ **The resulting split:**
68
+ - In the config and in `agents/*.md`, native tools only get `allow` or `ask`, so the toolset
69
+ stays complete.
70
+ - The actual prohibition is decided here, in the guard, on the `ask` / `allow` that does
71
+ reach the hook.
50
72
 
51
- ## Configuración
73
+ ## Configuration
52
74
 
53
75
  ```jsonc
76
+ "modules": { "guard": true },
54
77
  "guard": {
55
- "mode": "enforce", // "report" = anota sin aplicar
56
- "fallback": "keep", // sin regla que coincida, no se toca el permiso
57
- "keep": 500, // decisiones que conserva el informe
78
+ "mode": "enforce", // default "report": record only, never change the permission
79
+ "fallback": "keep", // default "keep": when no rule matches, leave the permission as it is
80
+ "keep": 500, // default 500: decisions kept in the in-memory report
58
81
  "agents": {
59
82
  "code-reviewer": [
60
- { "action": "write", "effect": "deny", "reason": "code-reviewer no modifica el proyecto" },
61
- { "action": "edit", "effect": "deny", "reason": "code-reviewer no modifica el proyecto" },
62
- { "action": "shell", "effect": "deny", "reason": "code-reviewer no ejecuta comandos" },
83
+ { "action": "write", "effect": "deny", "reason": "code-reviewer does not modify the project" },
84
+ { "action": "edit", "effect": "deny", "reason": "code-reviewer does not modify the project" },
85
+ { "action": "shell", "effect": "deny", "reason": "code-reviewer does not run commands" },
63
86
  { "action": "write", "resource": ".opencode/code-reviewer/**", "effect": "allow" },
64
87
  { "action": "edit", "resource": ".opencode/code-reviewer/**", "effect": "allow" }
65
88
  ]
@@ -67,63 +90,78 @@ la prohibición se decide aquí, sobre el `ask` que sí llega al hook.
67
90
  }
68
91
  ```
69
92
 
70
- **La última coincidencia gana** — el mismo criterio del ruleset del host, donde las
71
- reglas del agente se añaden al final. Ese orden es lo que permite «nada, salvo esta
72
- ruta»: primero el `deny` amplio, después el `allow` estrecho. Las reglas de la clave
73
- `"*"` se evalúan antes que las del agente.
93
+ How rules are matched:
94
+
95
+ - **The last matching rule wins**, as in OpenCode's own rules. That is what makes "nothing,
96
+ except this path" possible: first the broad `deny`, then the narrow `allow`.
97
+ - **The `"*"` key** holds rules for every agent. They are checked *before* the agent's own
98
+ rules, so an agent's rules can override them.
99
+ - **`action` and `resource` are patterns**, where `*` matches anything, `/` included.
100
+ `resource` defaults to `"*"`. If a call touches several resources, the rule matches when
101
+ any one of them matches.
102
+ - **Relative paths** in `resource` are tested both **as written** and **expanded** against
103
+ the project directory (`~/…` expands to your home), because OpenCode hands over resources
104
+ both ways: `read` arrives as `package.json`, while OpenCode's own rules use absolute paths
105
+ like `/home/…/.opencode/plan/*`. Patterns that contain spaces, such as shell commands,
106
+ are never expanded.
107
+
108
+ ### `mode`
74
109
 
75
- `action` y `resource` son patrones con `*`, que cubre cualquier cosa incluidas las
76
- barras. Un `resource` relativo se prueba **tal cual y expandido** contra el directorio
77
- del proyecto, porque el host entrega el recurso de las dos formas: `read` llega como
78
- `package.json` mientras las reglas del propio opencode hablan de
79
- `/home/…/.opencode/plan/*`.
110
+ - `report` (default) records the decision but leaves the permission untouched.
111
+ - `enforce` applies it. Start with `report`, read the report, fix the rules, and only then
112
+ switch to `enforce`. A freshly written guard that starts denying can break a session
113
+ before you have seen a single rule in action.
80
114
 
81
115
  ### `fallback`
82
116
 
83
- `"keep"` deja el permiso como venía, y es el único default seguro. Cualquier otro valor
84
- reescribe en masa lo que decidió el host: con `fallback: "allow"` todos los `ask` pasan a
85
- `allow`, lo que anula las reglas de `shell` de la config y deja al advisor sin nada que
86
- juzgar. Pasó durante el desarrollo — un `rm -r` se ejecutó sin preguntar.
117
+ What happens when no rule matches:
87
118
 
88
- Un `allow` de regla **sí** eleva un `ask`, y es deliberado: es lo que deja a un subagente
89
- escribir en su propio directorio sin molestar al usuario. La elevación exige una regla
90
- explícita; nunca sale del fallback.
119
+ - **`keep`** (default) leaves the permission as OpenCode decided it, and it is the only safe
120
+ default.
121
+ - **Any other value** rewrites every unmatched decision, for every agent. With
122
+ `fallback: "allow"`, every `ask` becomes `allow`: your config's `shell` rules stop
123
+ prompting, and the advisor has nothing left to judge. During development this let an
124
+ `rm -r` run without asking.
91
125
 
92
- ## Orden respecto al advisor
126
+ A matching `allow` rule **does** upgrade an `ask` to `allow`, on purpose: that is how a
127
+ subagent can write into its own directory without bothering you. The upgrade always needs
128
+ an explicit rule; it never comes from the fallback.
93
129
 
94
- El guard se registra **antes**. `hooks.trigger` recorre los callbacks en orden de
95
- registro sobre el mismo evento, y el advisor solo interviene cuando el efecto sigue en
96
- `"ask"`. Con el guard delante, lo que él resuelve no llega al advisor, y lo que deja en
97
- `ask` es exactamente lo que el advisor debe juzgar. Al revés, el advisor aprobaría cosas
98
- que el guard iba a prohibir.
130
+ When the guard denies a call in `enforce` mode, the message reads
131
+ `⛔ apex.guard: <reason> [<rule>]`.
99
132
 
100
- El hook va envuelto en `try/catch` por el mismo motivo: `trigger` hace `yield* result`,
101
- así que un hook que lance corta la cadena y **desactiva silenciosamente los que vengan
102
- detrás**.
133
+ ## Order: guard first, then advisor
103
134
 
104
- ## El propio advisor
135
+ The guard registers its hook **before** the [advisor](ADVISOR.md). OpenCode runs the
136
+ `permission.evaluate` hooks in registration order on the same event, and the advisor only
137
+ acts while the effect is still `ask`. So what the guard decides never reaches the advisor,
138
+ and whatever the guard leaves as `ask` is exactly what the advisor should judge. The other
139
+ way round, the advisor would approve calls the guard was about to forbid.
105
140
 
106
- `apex-advisor` pasa por el guard como cualquier otro, y es el único con `* deny`:
141
+ The guard's hook is wrapped in `try/catch`. OpenCode runs the hooks one after another, and a
142
+ hook that throws stops the chain, so every hook registered after it, the advisor included,
143
+ would silently stop running.
107
144
 
108
- ```jsonc
109
- "apex-advisor": [
110
- { "action": "*", "effect": "deny", "reason": "el advisor decide permisos; no toca nada más" },
111
- { "action": "execute", "effect": "allow" },
112
- { "action": "apex_advisor_decide", "effect": "allow" }
113
- ]
114
- ```
145
+ ## The advisor itself
146
+
147
+ The `apex-advisor` agent is restricted by the permission rules apex gives it when it creates
148
+ the agent: deny everything except `execute` and `apex_advisor_decide`. Those are ordinary
149
+ OpenCode rules, so they apply whether the guard is on or not. If the advisor's model tries
150
+ `write`, OpenCode denies it before any hook runs. No model is consulted, so no recursion is
151
+ possible.
115
152
 
116
- `execute` es imprescindible: opencode v2 invoca las herramientas desde el sandbox JS, no
117
- como function calls, de modo que sin él el advisor no puede ni emitir su decisión. Si su
118
- modelo intenta `write`, el guard lo corta sin consultarle a él mismo — el guard no llama
119
- a ningún modelo, así que no hay recursión posible. Verificado con una sonda temporal en
120
- su system prompt: el fichero no se creó.
153
+ > When the guard is on, it applies the same three rules to `apex-advisor` as a second layer.
154
+ > They come from `createDefaultGuardConfig()` and are merged per agent with your
155
+ > `guard.agents`. Defining `guard.agents["apex-advisor"]` yourself replaces them. Before 0.2.2
156
+ > your (empty) `guard.agents` map dropped them by mistake. The advisor's main protection is
157
+ > still its agent ruleset.
121
158
 
122
- ## El informe
159
+ ## The report
123
160
 
124
- La tool `apex_guard_report` (`limit`, `agent`, `effect`) devuelve texto, no JSON: un
125
- objeto con claves dinámicas lo rechaza el validador de salida del host, y una tabla
126
- compacta cuesta bastantes menos tokens.
161
+ The tool **`apex_guard_report`** returns the recorded decisions:
162
+ - **Inputs:** `limit` (default 40), `agent` and `effect`, which filters by the applied effect.
163
+ - **Output:** text, not JSON. An object with dynamic keys is rejected by OpenCode's tool
164
+ output validator, and a compact table costs far fewer tokens.
127
165
 
128
166
  ```
129
167
  apex.guard · modo=enforce · fallback=keep · 17 decisiones registradas
@@ -137,29 +175,29 @@ resumen (allow/deny/ask por agente):
137
175
  15:08:33 code-reviewer grep guard\.ts → allow
138
176
  ```
139
177
 
140
- El informe vive en `Symbol.for("apex.guard.report.v1")`: opencode instancia el plugin una
141
- vez por location — el advisor corre en `/tmp/opencode-apex-advisor`, que es otra — y con
142
- el estado en ámbito de módulo el hook de una instancia anota donde la tool de otra no
143
- mira, con lo que el informe sale vacío teniendo el guard funcionando.
144
-
145
- `APEX_GUARD_TRACE=1` escribe además cada decisión por consola.
146
-
147
- ## Rodaje
178
+ (The report text itself is currently in Spanish.)
148
179
 
149
- Empezar en `mode: "report"`, trabajar normal, leer `apex_guard_report` para ver qué se
150
- habría bloqueado, ajustar las reglas y solo entonces pasar a `"enforce"`. Un guard recién
151
- escrito que arranque denegando rompe la sesión antes de que nadie haya visto una regla en
152
- acción; por eso el default del módulo es `report` y viene desactivado.
180
+ - **Lifetime.** The report lives in memory only, and is shared by the whole OpenCode process
181
+ (`Symbol.for("apex.guard.report.v1")`). OpenCode loads the plugin once per directory: the
182
+ advisor runs in another one, `<tmp>/opencode-apex-advisor`. With per-module state, the hook
183
+ of one instance would record decisions where the tool of another never looks, and the
184
+ report would come out empty while the guard was working.
185
+ - **Trace.** Set `APEX_GUARD_TRACE=1` to also print every decision to the server console.
153
186
 
154
- ## Prompts
187
+ ## Tell your agents about their toolset
155
188
 
156
- Cada agente lleva al final de su `.md` un bloque **Tu toolset** generado desde estas
157
- mismas reglas: qué usar, qué no, y las excepciones por ruta. El modelo ve todas las
158
- herramientas —el toolset está entero, para eso es todo esto— así que hay que decirle
159
- cuáles son suyas, o gastará turnos en llamadas que el guard va a cortar.
189
+ The guard keeps every tool visible to the model, which is the whole point of not using
190
+ config `deny`. So the model does not know which tools it may use, and it will waste turns on
191
+ calls the guard is going to block. **Recommended:** end each agent's prompt with a short
192
+ "your toolset" section that mirrors its guard rules: what to use, what not to use, and the
193
+ path exceptions. apex does not generate this section for you.
160
194
 
161
195
  ## Tests
162
196
 
163
- `bun test/guard.test.ts` — 56 comprobaciones sobre el motor: patrones, expansión de
164
- recursos con ruta relativa y absoluta, precedencia por orden, la política del advisor, el
165
- anillo del informe y la semántica de `keep`.
197
+ `bun test/guard.test.ts` runs 56 checks on the engine:
198
+ - pattern matching;
199
+ - resource expansion for relative and absolute paths;
200
+ - order precedence;
201
+ - the advisor policy;
202
+ - the report ring buffer;
203
+ - the `keep` fallback.
package/docs/REDACT.md CHANGED
@@ -1,80 +1,100 @@
1
- # Apex Redact — redacción de secretos por cifrado
1
+ # Redact: keep secrets away from the model
2
2
 
3
- Módulo de `opencode-apex` que detecta secretos por expresión regular, los **cifra** y los
4
- sustituye por un marcador autocontenido. No existe mapping en memoria: la restauración
5
- descifra el propio marcador.
3
+ > **OpenCode V2 only (2.1 or newer).**
6
4
 
7
- ## Formato del marcador
5
+ The redact module finds secrets in everything OpenCode is about to send to the model:
6
+ API keys, tokens, connection strings and so on. It **encrypts** each one and replaces it
7
+ with a readable marker. The model only ever sees the marker. When the model passes that
8
+ marker to a tool, apex decrypts it back, so the tool still receives the real value.
8
9
 
9
- ```
10
- {prefix}{nombreDelPatron}:{base64url(iv || tag || ciphertext)}{suffix}
11
- # p. ej. [SECRET:github-pat:AbC123...]
12
- ```
13
-
14
- El **nombre del patrón** hace el marcador legible: el usuario sabe *qué* se
15
- redactó aunque no pueda ver el secreto.
16
-
17
- - Algoritmo: **AES-256-GCM** (autenticado: un payload manipulado no descifra).
18
- - `iv`: 12 bytes aleatorios por cifrado · `tag`: 16 bytes · payload en `base64url`.
19
- - `prefix`/`suffix` configurables (por defecto `[SECRET:` y `]`).
20
- - Un texto con forma de marcador que **no** fue generado por nosotros no descifra y se
21
- deja intacto (degradación segura).
22
-
23
- ## Clave
24
-
25
- Se resuelve desde `redact.key` en `.opencode/opencode-apex.jsonc`:
26
-
27
- | Formato | Ejemplo | Descripción |
28
- | ----------------- | ----------------------------- | ------------------------------------ |
29
- | literal | `"mi-frase-secreta"` | el propio texto es el material |
30
- | `env:VAR` | `"env:APEX_REDACT_KEY"` | variable de entorno |
31
- | `file:/ruta` | `"file:~/.config/opencode/apex.key"` | contenido del fichero (trim) |
32
- | `hex:...` | `"hex:0011aaff..."` | material en hexadecimal |
33
- | `base64:...` | `"base64:AAEC..."` | material en base64 |
34
-
35
- El material se deriva a 32 bytes con SHA-256 (determinista ⇒ descifrable entre sesiones).
36
- Sin clave disponible se genera una aleatoria y se persiste en `~/.config/opencode/apex.key`
37
- (0600), con aviso: fíjala en la configuración para que sea estable.
38
-
39
- ## Flujo de hooks (crítico)
40
-
41
- **Entrada al modelo → REDACTAR**
42
-
43
- | Hook | Campo | Qué cubre |
44
- | ---------------------- | ---------------------------- | --------------------------------------------- |
45
- | `session.hook("context")` | `event.system/messages/tools` | system prompt + mensajes (prompt del usuario, resultados de tools) + definiciones de tools |
46
-
47
- Un único punto, transport-agnostic: funciona con HTTP, WebSocket y providers ACP
48
- porque corre en la construcción de la petición, antes del transporte.
49
-
50
- **Salida hacia la herramienta → RESTAURAR**
10
+ There is no lookup table in memory: the marker *is* the encrypted secret, so nothing is
11
+ lost when OpenCode restarts. The encryption key is the only thing you need to keep.
51
12
 
52
- | Hook | Campo | Qué cubre |
53
- | ------------------------- | ------------ | -------------------------------------------------- |
54
- | `tool.hook("execute.before")` | `event.input` | argumentos de tool (el modelo emitió marcadores; la herramienta necesita el secreto real) |
13
+ ## What a marker looks like
55
14
 
56
- **No se restaura**: respuesta del modelo ni razonamiento. El usuario ve el
57
- marcador legible. El store de sesión conserva el texto original: solo se redacta
58
- de cara al modelo.
59
-
60
- ## Garantías de implementación
61
-
62
- 1. **Pasada única**: todas las coincidencias se recogen sobre el texto original y se
63
- resuelven solapes (gana la más larga). Un patrón nunca puede re-cifrar un marcador
64
- ya generado.
65
- 2. **Idempotencia**: los marcadores existentes son regiones protegidas. El mismo texto
66
- puede atravesar `prompt → context → tool result` sin doble cifrado.
67
- 3. **Degradación segura**: marcador corrupto o ajeno ⇒ intacto. Payload inválido ⇒ `null`.
68
- 4. **Sin mapping**: nada que perder al reiniciar; la clave es la única pieza a custodiar.
15
+ ```
16
+ {prefix}{patternName}:{base64url(iv || tag || ciphertext)}{suffix}
17
+ e.g. [SECRET:github-pat:AbC123...]
18
+ ```
69
19
 
70
- ## Configuración
20
+ - **`patternName`** is the name of the detector that matched (for example `github-pat`,
21
+ `aws-access-key-id` or `custom-0`), so a human reading the conversation knows *what*
22
+ was hidden without seeing it.
23
+ - **Encryption** is AES-256-GCM, which is authenticated: a tampered payload does not
24
+ decrypt. The IV is 12 random bytes per secret, the tag is 16 bytes, and the payload is
25
+ base64url.
26
+ - **`prefix` and `suffix`** are configurable; the defaults are `[SECRET:` and `]`.
27
+ - **Unknown markers are left untouched**: text that looks like a marker but was not
28
+ produced with your key does not decrypt.
29
+
30
+ ## When redaction and restoration happen
31
+
32
+ OpenCode plugins react to events through *hooks*. apex uses two:
33
+
34
+ | Direction | Hook | What it touches |
35
+ | --- | --- | --- |
36
+ | **To the model → redact** | `session.hook("context")` | The system prompt, every message (your prompts, previous answers, tool results) and the tool definitions, right before each request is sent. |
37
+ | **To a tool → restore** | `tool.hook("execute.before")` | The arguments of each tool call (only when `restore.toolInput` is `true`, the default). |
38
+
39
+ - The redaction hook runs while the request is being built, before any transport, so it
40
+ works the same over HTTP, WebSocket or ACP providers.
41
+ - **Nothing else is restored.** Model answers and reasoning keep the markers, so you see
42
+ `[SECRET:…]` in the chat.
43
+ - **The session history keeps the original text.** Redaction applies only to what is sent
44
+ to the model.
45
+
46
+ ## The encryption key
47
+
48
+ The key comes from `redact.key`. apex resolves it in this order:
49
+
50
+ | `redact.key` value | Example | Key material |
51
+ | --- | --- | --- |
52
+ | `env:NAME` | `"env:APEX_REDACT_KEY"` | The value of that environment variable |
53
+ | `file:/path` | `"file:/home/me/.config/opencode/apex.key"` | The file's content, trimmed |
54
+ | `hex:…` | `"hex:0011aaff…"` | The hex string (must be hex digits) |
55
+ | `base64:…` | `"base64:AAEC…"` | The base64 string |
56
+ | any other text | `"my secret phrase"` | The text itself |
57
+ | empty (default) | `""` | The `APEX_REDACT_KEY` environment variable, if set |
58
+
59
+ 1. The material is turned into a 32-byte key with SHA-256. The same material always gives
60
+ the same key, so markers stay decryptable across restarts and machines.
61
+ 2. If none of the above yields any material (empty value, unset variable, missing or empty
62
+ file), apex reuses the key saved in `~/.config/opencode/apex.key`.
63
+ 3. If that file does not exist either, apex generates a random key, saves it there (mode
64
+ `0600`) and logs a warning.
65
+
66
+ **Pitfalls:**
67
+
68
+ - `file:` paths may start with `~/` (your home directory). Any other relative path is
69
+ resolved against the server's working directory, so prefer `~/…` or an absolute path.
70
+ - If `env:NAME` points to a variable that is not set, apex goes straight to the saved key
71
+ file. It does **not** fall back to `APEX_REDACT_KEY`.
72
+ - **Changing the key orphans existing markers**: markers created with the old key no
73
+ longer decrypt and reach tools as plain marker text. Pick a key once (an environment
74
+ variable is the usual choice) and keep it.
75
+ - The server log shows which source was used and a short fingerprint, never the key:
76
+ `[apex.redact] Clave cargada (source=env, fp=1a2b3c4d), 96 patrones activos`.
77
+
78
+ ## Guarantees
79
+
80
+ 1. **Single pass.** All matches of all detectors are collected on the original text;
81
+ overlaps are resolved (the longest match wins). A detector can never match inside a
82
+ marker produced in the same pass.
83
+ 2. **Idempotent.** Existing markers are protected regions, so the same text can flow
84
+ through prompt → context → tool result → context again without being encrypted twice.
85
+ 3. **Safe degradation.** A corrupt or foreign marker is left as is; an invalid payload
86
+ decrypts to nothing and the text is kept.
87
+ 4. **No state to lose.** There is no mapping table; only the key matters.
88
+
89
+ ## Configuration
71
90
 
72
91
  ```jsonc
73
92
  "redact": {
74
- "mode": "strict", // "strict" redacta · "warn" solo registra
75
- "patterns": ["\\bmi-patron-[A-Za-z0-9]{16}\\b"], // regex propias (ojo: \\ en JSON)
76
- "bundles": ["aws", "github", "jwt", "env", "openai", "..."],
77
- "allowlist": ["^sk-test-"], // regex que NUNCA se redactan
93
+ "mode": "strict", // "strict" replaces · "warn" only logs
94
+ "patterns": ["\\bmy-token-[A-Za-z0-9]{16}\\b"], // your own regexes (note the \\)
95
+ "bundles": ["aws", "github", "jwt", "env", "openai"], // replaces the default list
96
+ "minConfidence": "medium", // low | medium | high
97
+ "allowlist": ["^sk-test-"], // regexes that are never redacted
78
98
  "prefix": "[SECRET:",
79
99
  "suffix": "]",
80
100
  "key": "env:APEX_REDACT_KEY",
@@ -82,17 +102,34 @@ de cara al modelo.
82
102
  }
83
103
  ```
84
104
 
85
- > **Escapes en JSONC**: `\b` en JSON es *backspace*. Para un límite de palabra regex hay
86
- > que escribir `\\b`. Los patrones inválidos se ignoran con aviso (nunca rompen el arranque).
105
+ | Key | Default | Meaning |
106
+ | --- | --- | --- |
107
+ | `mode` | `"strict"` | `strict` replaces secrets with markers. `warn` sends the text unchanged and only logs each finding (debug level) |
108
+ | `bundles` | the 38 default bundles | Named groups of detectors (see below). Setting it **replaces** the whole default list |
109
+ | `patterns` | `[]` | Your own regexes, added on top of the bundles. Each becomes `custom-<index>` in the marker, is always active (treated as high confidence) and is case-sensitive (JavaScript `g` flag only) |
110
+ | `minConfidence` | `"medium"` | Drops bundle detectors below this confidence |
111
+ | `allowlist` | `[]` | Regexes tested against each **matched secret**; a match that fits any of them is left in clear |
112
+ | `prefix` / `suffix` | `"[SECRET:"` / `"]"` | Marker delimiters |
113
+ | `key` | `""` | See [The encryption key](#the-encryption-key) |
114
+ | `restore.toolInput` | `true` | Decrypt markers in tool arguments |
115
+
116
+ - **Escaping in JSON:** `\b` in a JSON string is a backspace character. For a regex word
117
+ boundary write `\\b`. An invalid regex is skipped with a warning; it never stops the
118
+ plugin.
119
+ - **Unknown bundle names** are skipped with a warning that lists the valid names.
120
+
121
+ ## Detectors and bundles
122
+
123
+ apex ships **104 detectors in 41 bundles**:
87
124
 
88
- ## Patrones
125
+ - 58 are copied from **opencode-warden**;
126
+ - 45 from **opencode-secret-redactor@0.5.1**;
127
+ - 1 is apex's own (`db-uri-credentials`).
89
128
 
90
- Los patrones por defecto se copiaron íntegramente de **opencode-secret-redactor@0.5.1**
91
- y **opencode-warden** (74 patrones), más los propios de apex. Cada patrón declara
92
- `confidence` (low/medium/high) y opcionalmente un `validate()` (Luhn para tarjetas,
93
- exclusión de IPs privadas).
129
+ Each detector has a confidence level (`low`, `medium`, `high`). Some also have an extra
130
+ check: the Luhn checksum for credit cards, and excluding private ranges for IPv4.
94
131
 
95
- **Bundles activos por defecto** (38):
132
+ **Enabled by default (38 bundles):**
96
133
 
97
134
  ```
98
135
  aws github gitlab slack jwt pem bearer env
@@ -102,20 +139,37 @@ observability pypi rubygems twilio sendgrid postman mailgun mailchimp
102
139
  linear shopify square docker kubernetes cohere huggingface discord
103
140
  ```
104
141
 
105
- **Opt-in** (ruidosos o PII — NO activos por defecto): `pii` (email, teléfono, SSN,
106
- tarjeta), `network` (IPv4 públicas), `datadog`.
142
+ **Opt-in** (noisy or personal data; add them to `bundles` explicitly):
107
143
 
108
- **`minConfidence`** (default `medium`) filtra los patrones ruidosos. Con `medium` se
109
- excluyen los de confianza `low` (cohere, datadog, docker-compose-env-secret, IPv4,
110
- teléfono internacional, redis URI). Bajarlo a `low` activa todo; subirlo a `high` deja
111
- solo los detectores inequívocos.
144
+ | Bundle | Detects |
145
+ | --- | --- |
146
+ | `pii` | email, US phone number, US SSN, credit card (Luhn-checked) |
147
+ | `network` | public IPv4 addresses |
148
+ | `datadog` | Datadog API keys |
112
149
 
113
- > **Aviso**: apex redacta el contexto COMPLETO (system prompt + historial + tools), no
114
- > solo la salida de una tool. Por eso los patrones de baja confianza y PII están fuera
115
- > por defecto: un email o una URI de redis en el código serían falsos positivos caros.
150
+ **`minConfidence`** decides how many detectors are active:
116
151
 
117
- ## Tests
152
+ - `medium` (the default) skips the `low` ones: `cohere-key`, `redis-connection-string`,
153
+ and, when their bundles are enabled, `datadog-api-key`, `pii-us-phone` and `pii-ipv4`.
154
+ With the default bundles, 96 detectors are active.
155
+ - `low` enables all 98 detectors of the default bundles.
156
+ - `high` keeps only the unambiguous ones (78).
157
+
158
+ > **Why so conservative?** apex redacts the **whole** context (system prompt, history
159
+ > and tool definitions), not just one tool's output. An email address or a Redis URL in
160
+ > your source code would become a marker everywhere, which makes the code hard for the
161
+ > model to work with. Low-confidence and personal-data detectors are therefore off by
162
+ > default.
163
+
164
+ ## Redacting from outside: RPC `apex/redact.process`
165
+
166
+ The same engine is available over the OpenCode server's RPC endpoint. That endpoint and
167
+ its authentication are explained in [EVENTS.md](EVENTS.md).
168
+
169
+ ```
170
+ POST /api/rpc/apex/redact.process?location[directory]=<project>
171
+ {"input": {"text": "token ghp_…", "mode": "strict"}}
172
+ → {"output": {"redacted": "token [SECRET:github-pat:…]", "findings": [{"pattern": "github-pat"}]}}
173
+ ```
118
174
 
119
- `/tmp/opencode/apex-redact-test/test.ts` — cifrado/descifrado, estructura del marcador
120
- (incluido el nombre de patrón), round-trip, multi-patrón, valores anidados, allowlist,
121
- modo warn, marcador ajeno e idempotencia.
175
+ It uses the configured detectors, `allowlist`, key and marker format.