opencode-apex 0.1.0
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/README.md +155 -0
- package/advisor.ts +290 -0
- package/browser/actions.ts +811 -0
- package/browser/cdp.ts +603 -0
- package/browser/endpoint.ts +243 -0
- package/browser.ts +556 -0
- package/core/advisor-agent.ts +93 -0
- package/core/advisor-session.ts +292 -0
- package/core/advisor-tool.ts +76 -0
- package/core/bus.ts +192 -0
- package/core/conditions.ts +66 -0
- package/core/config.ts +533 -0
- package/core/crypto.ts +193 -0
- package/core/guard.ts +248 -0
- package/core/ingest-listener.ts +193 -0
- package/core/patterns.ts +385 -0
- package/core/redact.ts +256 -0
- package/core/rpc.ts +117 -0
- package/core/templates.ts +100 -0
- package/docs/ADVISOR.md +91 -0
- package/docs/BROWSER.md +226 -0
- package/docs/CONFIG.md +97 -0
- package/docs/EVENTS.md +102 -0
- package/docs/GUARD.md +165 -0
- package/docs/REDACT.md +121 -0
- package/docs/TROUBLESHOOTING.md +203 -0
- package/events.ts +934 -0
- package/guard.ts +250 -0
- package/index.ts +147 -0
- package/opencode-apex.jsonc +249 -0
- package/package.json +34 -0
- package/redact.ts +156 -0
package/README.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# opencode-apex
|
|
2
|
+
|
|
3
|
+
**Plugin modular para OpenCode V2** — redacción de secretos por cifrado, eventos con
|
|
4
|
+
suscripciones, decisiones de permiso mediante una sesión advisor dedicada, meta-permisos
|
|
5
|
+
(guard) y tools `browser.*` contra un Chromium externo por CDP.
|
|
6
|
+
|
|
7
|
+
API **Effect-native** (`Plugin.define({ id, effect })` de `@opencode/plugin/effect`).
|
|
8
|
+
|
|
9
|
+
## Módulos
|
|
10
|
+
|
|
11
|
+
| Módulo | Qué hace | Doc |
|
|
12
|
+
| ----------- | ----------------------------------------------------------------------------------------- | ------------------------- |
|
|
13
|
+
| **Redact** | Detecta secretos por regex, los cifra (AES-256-GCM) y los sustituye por un marcador legible. Restaura en el input de las tools | [docs/REDACT.md](docs/REDACT.md) |
|
|
14
|
+
| **Events** | Ingesta de eventos por RPC o por listener HTTP plano, filtros por suscripción y entrega como prompt o mensaje sintético | [docs/EVENTS.md](docs/EVENTS.md) |
|
|
15
|
+
| **Advisor** | Decide `allow`/`deny` sobre el uso de herramientas usando un agente y una sesión laterales | [docs/ADVISOR.md](docs/ADVISOR.md) |
|
|
16
|
+
| **Guard** | Meta-permisos por agente, herramienta y ruta, con informe. El `deny` que la config no puede declarar sin romper el toolset | [docs/GUARD.md](docs/GUARD.md) |
|
|
17
|
+
| **Browser** | Sirve las tools `browser.*` contra un Chromium **externo** por CDP, local o remoto. Elige entre navegador externo y el de la app de escritorio | [docs/BROWSER.md](docs/BROWSER.md) |
|
|
18
|
+
|
|
19
|
+
Activación por módulo en `modules` (fuente única, no existe `<modulo>.enabled`):
|
|
20
|
+
|
|
21
|
+
```jsonc
|
|
22
|
+
"modules": { "redact": true, "events": true, "advisor": false, "guard": false, "browser": true }
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Instalación
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
cd .opencode/plugins/apex
|
|
29
|
+
bun install
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Configuración
|
|
33
|
+
|
|
34
|
+
Dos canales y jerarquía (ver [docs/CONFIG.md](docs/CONFIG.md)):
|
|
35
|
+
|
|
36
|
+
| # | Fuente | Nivel |
|
|
37
|
+
| - | ----------------------------------------------------- | ----------- |
|
|
38
|
+
| 1 | Fichero global `~/.config/opencode/opencode-apex.jsonc` | global-file |
|
|
39
|
+
| 2 | `options` del plugin en `opencode.json` | inline |
|
|
40
|
+
| 3 | Fichero local `<proyecto>/.opencode/opencode-apex.jsonc` | local-file |
|
|
41
|
+
|
|
42
|
+
- Precedencia: **el ámbito manda** (local > global) y **dentro de cada ámbito el fichero gana al inline** ⇒ `local-inline > global-file`.
|
|
43
|
+
- Comentarios: `#`, `//` y `/* */`.
|
|
44
|
+
- Plantillas de prompt: **solo rutas relativas** (al proyecto o `~/home`); si el fichero no existe **se crea con defaults**.
|
|
45
|
+
|
|
46
|
+
```jsonc
|
|
47
|
+
{
|
|
48
|
+
"modules": { "redact": true, "events": true, "advisor": false },
|
|
49
|
+
"redact": {
|
|
50
|
+
"mode": "strict",
|
|
51
|
+
"bundles": ["aws", "github", "jwt", "env"],
|
|
52
|
+
"minConfidence": "medium",
|
|
53
|
+
"prefix": "[SECRET:",
|
|
54
|
+
"suffix": "]",
|
|
55
|
+
"key": "env:APEX_REDACT_KEY",
|
|
56
|
+
"restore": { "toolInput": true }
|
|
57
|
+
},
|
|
58
|
+
"events": {
|
|
59
|
+
"routing": "all",
|
|
60
|
+
"subscriptions": [
|
|
61
|
+
{ "sessionID": "", "filters": [{ "field": "type", "operator": "equals", "value": "ci.failed" }] }
|
|
62
|
+
]
|
|
63
|
+
},
|
|
64
|
+
"advisor": { "model": "opencode/big-pickle", "decisive": true, "evaluate": "ask-only" }
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Callbacks (notificar al agente desde fuera)
|
|
69
|
+
|
|
70
|
+
Patrón: el agente se **suscribe** → un proceso externo dispara **`apex.events.ingest`**
|
|
71
|
+
→ el agente recibe un prompt. Dos vías de disparo: RPC autenticado
|
|
72
|
+
(`POST /api/rpc/apex/events.ingest`) o el **listener HTTP plano** (sin credenciales
|
|
73
|
+
del servidor, con host/puerto/token configurables).
|
|
74
|
+
|
|
75
|
+
Skill con los patrones completos (fire-and-forget, LAN, túneles, hooks de arranque,
|
|
76
|
+
entrega fiable): **`.opencode/skills/apex-callbacks/SKILL.md`**.
|
|
77
|
+
|
|
78
|
+
## Herramientas expuestas
|
|
79
|
+
|
|
80
|
+
| Tool | Módulo | Qué hace |
|
|
81
|
+
| ------------------------- | ------- | ----------------------------------------------------------- |
|
|
82
|
+
| `apex_subscribe` | events | Crea una suscripción para la sesión que llama |
|
|
83
|
+
| `apex_unsubscribe` | events | Elimina una suscripción dinámica por id |
|
|
84
|
+
| `apex_list_subscriptions` | events | Lista suscripciones (marca las estáticas de config) |
|
|
85
|
+
| `apex_callback_endpoint` | events | Devuelve DÓNDE recibe el agente los eventos (URLs, túnel, token, RPC) |
|
|
86
|
+
| `apex_set_callback_url` | events | Anuncia/limpia la URL pública (túnel) en runtime; el agente monta el túnel él mismo |
|
|
87
|
+
| `apex_advisor_decide` | advisor | Única tool del agente advisor: `allow` / `deny` + `reason` |
|
|
88
|
+
| `apex_guard_report` | guard | Informe de meta-permisos: qué intentó cada agente y qué se decidió |
|
|
89
|
+
| `browser_target` | browser | Elige qué navegador sirve `browser.*`: `external` (CDP), `in-app` (app de escritorio) o `auto` |
|
|
90
|
+
|
|
91
|
+
## RPC (namespace `apex`)
|
|
92
|
+
|
|
93
|
+
| Método | Entrada | Salida |
|
|
94
|
+
| ---------------- | ---------------------------------------------- | ------------------------------------- |
|
|
95
|
+
| `apex.ping` | `{ payload? }` | `{ pong, timestamp }` |
|
|
96
|
+
| `apex.status` | `{}` | `{ modules, version, uptimeMs, callback }` |
|
|
97
|
+
| `apex.redact.process` | `{ text, mode? }` | `{ redacted, findings }` |
|
|
98
|
+
| `apex.events.ingest` | `{ source, type?, payload, eventID? }` | `{ accepted, eventID, delivered }` |
|
|
99
|
+
|
|
100
|
+
## Estructura
|
|
101
|
+
|
|
102
|
+
```
|
|
103
|
+
.opencode/plugins/apex/
|
|
104
|
+
├── index.ts # Entrada: Plugin.define + carga de config + registro de módulos
|
|
105
|
+
├── redact.ts # Módulo redact: hooks context / execute.before
|
|
106
|
+
├── events.ts # Módulo events: tools, ingest, routing, auto-vinculación
|
|
107
|
+
├── advisor.ts # Módulo advisor: agente + hook de permisos
|
|
108
|
+
├── guard.ts # Módulo guard: meta-permisos + informe
|
|
109
|
+
├── browser.ts # Módulo browser: attachment CDP, tool browser.target, comando
|
|
110
|
+
├── browser/
|
|
111
|
+
│ ├── cdp.ts # Cliente CDP: WebSocket, TabRegistry, colectores
|
|
112
|
+
│ ├── endpoint.ts # DevToolsActivePort vs /json/version, ws/wss remoto
|
|
113
|
+
│ └── actions.ts # Las 45 Browser.Action → CDP
|
|
114
|
+
├── core/
|
|
115
|
+
│ ├── config.ts # Jerarquía, merge, comentarios, schema Zod
|
|
116
|
+
│ ├── templates.ts # Resolución/creación de plantillas (relativas)
|
|
117
|
+
│ ├── crypto.ts # AES-256-GCM, resolución de clave
|
|
118
|
+
│ ├── patterns.ts # 41 bundles / 104 patrones (secret-redactor + warden)
|
|
119
|
+
│ ├── redact.ts # Motor de redacción/restauración
|
|
120
|
+
│ ├── conditions.ts # Evaluación de condiciones de filtros
|
|
121
|
+
│ ├── bus.ts # Bus interno
|
|
122
|
+
│ ├── rpc.ts # Registro del namespace RPC "apex"
|
|
123
|
+
│ ├── guard.ts # Motor de meta-permisos
|
|
124
|
+
│ ├── ingest-listener.ts # Listener HTTP plano de events
|
|
125
|
+
│ ├── advisor-agent.ts # Definición del agente apex-advisor
|
|
126
|
+
│ ├── advisor-tool.ts # Tool apex_advisor_decide
|
|
127
|
+
│ └── advisor-session.ts # Sesión advisor por árbol + round-trip
|
|
128
|
+
├── test/
|
|
129
|
+
│ ├── browser.test.ts # Suite del módulo browser (Chromium en TEST_CDP_URL)
|
|
130
|
+
│ └── guard.test.ts # Suite del módulo guard
|
|
131
|
+
└── docs/ # CONFIG · REDACT · EVENTS · ADVISOR · GUARD · BROWSER · TROUBLESHOOTING
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## Desarrollo
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
./node_modules/.bin/tsc --noEmit # typecheck
|
|
138
|
+
./node_modules/.bin/tsc --noEmit --noUnusedLocals --noUnusedParameters # código muerto
|
|
139
|
+
bun -e "await import('./index.ts'); console.log('OK')" # smoke de carga
|
|
140
|
+
bun test test/guard.test.ts # guard (56)
|
|
141
|
+
TEST_CDP_URL=<puerto> bun test test/browser.test.ts # browser (10; p.ej. 9333)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Para la suite de browser hace falta un Chromium headless con CDP en ese puerto:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
google-chrome --headless=new --remote-debugging-port=9333 \
|
|
148
|
+
--user-data-dir=/tmp/opencode/cdp-probe about:blank
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Troubleshooting
|
|
152
|
+
|
|
153
|
+
Ver [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) — matriz v1/v2, errores
|
|
154
|
+
conocidos (`ast._tag`, ENOENT de config, versiones de `effect`), y checklist para
|
|
155
|
+
módulos nuevos.
|
package/advisor.ts
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Apex Advisor — decisiones de permiso mediante una sesión advisor dedicada.
|
|
3
|
+
*
|
|
4
|
+
* Arquitectura:
|
|
5
|
+
* - El plugin define (upsert) el agente oculto `apex-advisor`, con su propio
|
|
6
|
+
* `model` (barato/rápido) y un ruleset que le permite SOLO la herramienta
|
|
7
|
+
* de decisión.
|
|
8
|
+
* - Existe UNA sesión advisor por ÁRBOL de sesiones: la raíz (sesión
|
|
9
|
+
* agente-usuario) y todos sus subagentes comparten la misma sesión advisor.
|
|
10
|
+
* - Ante cada tool call se pide decisión al advisor; el agente responde
|
|
11
|
+
* llamando a `apex_advisor_decide` con allow o deny+reason.
|
|
12
|
+
* - La sesión advisor queda registrada entera → auditoría completa.
|
|
13
|
+
*
|
|
14
|
+
* Vocabulario: aprobar = "allow"; denegar = "deny" + reason. No hay "consejo":
|
|
15
|
+
* si `decisive` es false, la decisión simplemente no se aplica al permiso.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { createHash } from "node:crypto"
|
|
19
|
+
import { Effect } from "effect"
|
|
20
|
+
import type { Scope } from "effect"
|
|
21
|
+
import type { Plugin } from "@opencode/plugin/effect"
|
|
22
|
+
import { homedir } from "node:os"
|
|
23
|
+
import { ADVISOR_AGENT_ID, ensureAdvisorAgent } from "./core/advisor-agent.js"
|
|
24
|
+
import { readOrCreateTemplate } from "./core/templates.js"
|
|
25
|
+
import { registerAdvisorTool } from "./core/advisor-tool.js"
|
|
26
|
+
import {
|
|
27
|
+
DEFAULT_ADVISOR_REQUEST_TEMPLATE,
|
|
28
|
+
isAdvisorSession,
|
|
29
|
+
requestAdvisorDecision,
|
|
30
|
+
} from "./core/advisor-session.js"
|
|
31
|
+
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
// Configuración
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
export interface AdvisorConfig {
|
|
37
|
+
/** Enable advisor module */
|
|
38
|
+
enabled: boolean
|
|
39
|
+
/** true = la decisión del advisor se aplica al permiso; false = solo se informa */
|
|
40
|
+
decisive: boolean
|
|
41
|
+
/**
|
|
42
|
+
* Modelo del agente advisor, formato "providerID/modelID". Recomendado uno
|
|
43
|
+
* rápido y barato: el advisor corre en su propia sesión con contexto completo.
|
|
44
|
+
*/
|
|
45
|
+
model?: string
|
|
46
|
+
/** System prompt del agente advisor (por defecto el protocolo allow/deny) */
|
|
47
|
+
system?: string
|
|
48
|
+
/** Plantilla de la PETICIÓN al advisor ({{requestID}}, {{action}}, {{resources}}, …) */
|
|
49
|
+
promptTemplate?: string
|
|
50
|
+
/** Fichero con la plantilla (relativo al proyecto o `~/home`; tiene prioridad).
|
|
51
|
+
* Si no existe se crea con la plantilla por defecto. */
|
|
52
|
+
promptTemplateFile?: string
|
|
53
|
+
/** Timeout de espera de la decisión (ms). Al agotarse no se altera el permiso. */
|
|
54
|
+
timeoutMs?: number
|
|
55
|
+
/** "ask-only" (default): solo cuando el efecto es "ask" · "all": en cada tool call */
|
|
56
|
+
evaluate?: "ask-only" | "all"
|
|
57
|
+
/** Filtro de acciones (nombres de tool). Vacío/ausente = todas. */
|
|
58
|
+
actions?: string[]
|
|
59
|
+
/**
|
|
60
|
+
* Directorio de la sesión advisor. Por defecto uno dedicado fuera del
|
|
61
|
+
* proyecto, para que NO se le inyecte el AGENTS.md del repo (la discovery de
|
|
62
|
+
* instrucciones es por location). Fuera de $HOME evita también la cadena de
|
|
63
|
+
* ancestros del home; el AGENTS.md global de ~/.config/opencode sigue aplicando.
|
|
64
|
+
*/
|
|
65
|
+
location?: string
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
// Estado persistido (caché de veredictos + auditoría)
|
|
70
|
+
// ---------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
interface CacheEntry {
|
|
73
|
+
verdict: "allow" | "deny"
|
|
74
|
+
reason: string
|
|
75
|
+
timestamp: number
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
interface AuditEntry {
|
|
79
|
+
timestamp: number
|
|
80
|
+
action: string
|
|
81
|
+
resources: readonly string[]
|
|
82
|
+
verdict: "allow" | "deny" | "ask"
|
|
83
|
+
reason: string
|
|
84
|
+
latencyMs: number
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const ADVISOR_CACHE_KEY = "apex:advisor:cache"
|
|
88
|
+
const ADVISOR_AUDIT_KEY = "apex:auditlog"
|
|
89
|
+
const CACHE_TTL_MS = 10 * 60 * 1000 // 10 minutes
|
|
90
|
+
const MAX_AUDIT_ENTRIES = 100
|
|
91
|
+
const DEFAULT_TIMEOUT_MS = 10_000
|
|
92
|
+
|
|
93
|
+
/** Evento del hook de permisos (forma real del hook `permission.evaluate`). */
|
|
94
|
+
interface PermissionEvaluationEvent {
|
|
95
|
+
sessionID: string
|
|
96
|
+
agent?: string
|
|
97
|
+
action: string
|
|
98
|
+
resources: readonly string[]
|
|
99
|
+
metadata?: Record<string, unknown>
|
|
100
|
+
source?: unknown
|
|
101
|
+
effect: "allow" | "deny" | "ask"
|
|
102
|
+
message?: string
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function generateCacheKey(action: string, resources: readonly string[]): string {
|
|
106
|
+
const sorted = [...resources].sort()
|
|
107
|
+
const input = action + JSON.stringify(sorted)
|
|
108
|
+
return createHash("sha256").update(input).digest("hex").slice(0, 32)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function loadCache(storage: Plugin.Context["storage"]): Promise<Map<string, CacheEntry>> {
|
|
112
|
+
const stored = await Effect.runPromise(storage.get(ADVISOR_CACHE_KEY))
|
|
113
|
+
if (!stored) return new Map()
|
|
114
|
+
try {
|
|
115
|
+
return new Map(JSON.parse(stored as string) as [string, CacheEntry][])
|
|
116
|
+
} catch {
|
|
117
|
+
return new Map()
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function saveCache(storage: Plugin.Context["storage"], cache: Map<string, CacheEntry>): Promise<void> {
|
|
122
|
+
await Effect.runPromise(storage.set(ADVISOR_CACHE_KEY, JSON.stringify(Array.from(cache.entries())) as never))
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function loadAuditLog(storage: Plugin.Context["storage"]): Promise<AuditEntry[]> {
|
|
126
|
+
const stored = await Effect.runPromise(storage.get(ADVISOR_AUDIT_KEY))
|
|
127
|
+
if (!stored) return []
|
|
128
|
+
try {
|
|
129
|
+
return JSON.parse(stored as string) as AuditEntry[]
|
|
130
|
+
} catch {
|
|
131
|
+
return []
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function saveAuditLog(storage: Plugin.Context["storage"], log: AuditEntry[]): Promise<void> {
|
|
136
|
+
await Effect.runPromise(storage.set(ADVISOR_AUDIT_KEY, JSON.stringify(log) as never))
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function addAuditEntry(
|
|
140
|
+
storage: Plugin.Context["storage"],
|
|
141
|
+
entry: Omit<AuditEntry, "timestamp">,
|
|
142
|
+
): Promise<void> {
|
|
143
|
+
const log = await loadAuditLog(storage)
|
|
144
|
+
log.push({ ...entry, timestamp: Date.now() })
|
|
145
|
+
if (log.length > MAX_AUDIT_ENTRIES) log.splice(0, log.length - MAX_AUDIT_ENTRIES)
|
|
146
|
+
await saveAuditLog(storage, log)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// ---------------------------------------------------------------------------
|
|
150
|
+
// Registro del módulo
|
|
151
|
+
// ---------------------------------------------------------------------------
|
|
152
|
+
|
|
153
|
+
export function register(
|
|
154
|
+
ctx: Plugin.Context,
|
|
155
|
+
config: AdvisorConfig,
|
|
156
|
+
): Effect.Effect<void, never, Scope.Scope> {
|
|
157
|
+
return Effect.gen(function* () {
|
|
158
|
+
if (!config.enabled) return
|
|
159
|
+
|
|
160
|
+
const decisive = config.decisive ?? false
|
|
161
|
+
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
162
|
+
// Plantilla: fichero (relativo, con creación por defecto) > inline > default
|
|
163
|
+
const templateFile = readOrCreateTemplate(
|
|
164
|
+
config.promptTemplateFile,
|
|
165
|
+
{ projectDir: ctx.location?.directory ?? process.cwd(), home: homedir() },
|
|
166
|
+
config.promptTemplate ?? DEFAULT_ADVISOR_REQUEST_TEMPLATE,
|
|
167
|
+
)
|
|
168
|
+
const template = templateFile.content ?? config.promptTemplate ?? DEFAULT_ADVISOR_REQUEST_TEMPLATE
|
|
169
|
+
const evaluateAll = config.evaluate === "all"
|
|
170
|
+
const actionFilter = new Set(config.actions ?? [])
|
|
171
|
+
|
|
172
|
+
// 1. Agente advisor dedicado (upsert)
|
|
173
|
+
yield* ensureAdvisorAgent(ctx, { model: config.model, system: config.system, decisive })
|
|
174
|
+
|
|
175
|
+
// 2. Única herramienta del advisor
|
|
176
|
+
yield* registerAdvisorTool(ctx)
|
|
177
|
+
|
|
178
|
+
// 3. Caché de veredictos
|
|
179
|
+
const cache = yield* Effect.promise(() => loadCache(ctx.storage))
|
|
180
|
+
|
|
181
|
+
// 4. Hook de permisos → sesión advisor
|
|
182
|
+
yield* ctx.permission.hook("evaluate", (event) =>
|
|
183
|
+
Effect.promise(async () => {
|
|
184
|
+
const e = event as unknown as PermissionEvaluationEvent
|
|
185
|
+
|
|
186
|
+
// Guardas: nunca evaluar la propia sesión advisor (por id de sesión o por
|
|
187
|
+
// agente — robusto ante recargas, cuando el registro de sesiones se pierde);
|
|
188
|
+
// filtro de acciones; por defecto solo cuando el usuario no resolvió ("ask").
|
|
189
|
+
if (isAdvisorSession(e.sessionID)) return
|
|
190
|
+
if (e.agent === ADVISOR_AGENT_ID) return
|
|
191
|
+
if (actionFilter.size > 0 && !actionFilter.has(e.action)) return
|
|
192
|
+
if (!evaluateAll && e.effect !== "ask") return
|
|
193
|
+
|
|
194
|
+
const startedAt = Date.now()
|
|
195
|
+
const cacheKey = generateCacheKey(e.action, e.resources)
|
|
196
|
+
|
|
197
|
+
// Camino rápido: veredicto cacheado
|
|
198
|
+
const cached = cache.get(cacheKey)
|
|
199
|
+
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
|
|
200
|
+
applyDecision(e, cached.verdict, cached.reason, decisive)
|
|
201
|
+
await addAuditEntry(ctx.storage, {
|
|
202
|
+
action: e.action,
|
|
203
|
+
resources: e.resources,
|
|
204
|
+
verdict: cached.verdict,
|
|
205
|
+
reason: `${cached.reason} (cached)`,
|
|
206
|
+
latencyMs: Date.now() - startedAt,
|
|
207
|
+
})
|
|
208
|
+
return
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Consultar a la sesión advisor del árbol
|
|
212
|
+
const decision = await requestAdvisorDecision(ctx, {
|
|
213
|
+
sessionID: e.sessionID,
|
|
214
|
+
action: e.action,
|
|
215
|
+
resources: e.resources,
|
|
216
|
+
agent: e.agent,
|
|
217
|
+
metadata: e.metadata,
|
|
218
|
+
decisive,
|
|
219
|
+
timeoutMs,
|
|
220
|
+
template,
|
|
221
|
+
location: config.location,
|
|
222
|
+
})
|
|
223
|
+
|
|
224
|
+
if (!decision) {
|
|
225
|
+
// Degradación: sin decisión no se altera el permiso original.
|
|
226
|
+
console.warn(`[apex.advisor] sin decisión para "${e.action}"; se mantiene el efecto original`)
|
|
227
|
+
await addAuditEntry(ctx.storage, {
|
|
228
|
+
action: e.action,
|
|
229
|
+
resources: e.resources,
|
|
230
|
+
verdict: "ask",
|
|
231
|
+
reason: "sin decisión del advisor (timeout/error)",
|
|
232
|
+
latencyMs: Date.now() - startedAt,
|
|
233
|
+
})
|
|
234
|
+
return
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
applyDecision(e, decision.decision, decision.reason ?? "", decisive)
|
|
238
|
+
|
|
239
|
+
cache.set(cacheKey, {
|
|
240
|
+
verdict: decision.decision,
|
|
241
|
+
reason: decision.reason ?? "",
|
|
242
|
+
timestamp: Date.now(),
|
|
243
|
+
})
|
|
244
|
+
await saveCache(ctx.storage, cache)
|
|
245
|
+
|
|
246
|
+
await addAuditEntry(ctx.storage, {
|
|
247
|
+
action: e.action,
|
|
248
|
+
resources: e.resources,
|
|
249
|
+
verdict: decision.decision,
|
|
250
|
+
reason: decision.reason ?? "",
|
|
251
|
+
latencyMs: Date.now() - startedAt,
|
|
252
|
+
})
|
|
253
|
+
}),
|
|
254
|
+
)
|
|
255
|
+
})
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Aplica la decisión al evento de permiso.
|
|
260
|
+
* - decisive=true → allow/deny sustituyen el efecto (deny deja el motivo).
|
|
261
|
+
* - decisive=false → no se toca el efecto; la decisión se anota en el mensaje.
|
|
262
|
+
*/
|
|
263
|
+
function applyDecision(
|
|
264
|
+
event: PermissionEvaluationEvent,
|
|
265
|
+
decision: "allow" | "deny",
|
|
266
|
+
reason: string,
|
|
267
|
+
decisive: boolean,
|
|
268
|
+
): void {
|
|
269
|
+
if (decisive) {
|
|
270
|
+
event.effect = decision
|
|
271
|
+
if (decision === "deny") {
|
|
272
|
+
event.message = reason.length > 0 ? reason : "denegado por apex.advisor"
|
|
273
|
+
}
|
|
274
|
+
return
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const note = `⚖ apex.advisor: ${decision}${reason ? ` — ${reason}` : ""}`
|
|
278
|
+
event.message = event.message ? `${event.message}\n${note}` : note
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export function createDefaultAdvisorConfig(): AdvisorConfig {
|
|
282
|
+
return {
|
|
283
|
+
enabled: true,
|
|
284
|
+
decisive: false,
|
|
285
|
+
evaluate: "ask-only",
|
|
286
|
+
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
287
|
+
actions: [],
|
|
288
|
+
promptTemplate: DEFAULT_ADVISOR_REQUEST_TEMPLATE,
|
|
289
|
+
}
|
|
290
|
+
}
|