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/guard.ts
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Apex Guard — el módulo que aplica los meta-permisos y los reporta.
|
|
3
|
+
*
|
|
4
|
+
* Dos piezas:
|
|
5
|
+
* 1. `permission.hook("evaluate")` → reescribe el efecto según las reglas de
|
|
6
|
+
* `core/guard.ts` y anota la decisión.
|
|
7
|
+
* 2. la tool `apex_guard_report` → devuelve lo anotado, para auditar qué ha
|
|
8
|
+
* intentado cada agente y qué se le dejó hacer.
|
|
9
|
+
*
|
|
10
|
+
* ORDEN DE REGISTRO. Debe registrarse ANTES del advisor. `hooks.trigger` del host
|
|
11
|
+
* recorre los callbacks en orden de registro mutando el mismo evento, y el
|
|
12
|
+
* advisor solo interviene cuando el efecto sigue siendo `"ask"`. Registrando el
|
|
13
|
+
* guard primero, lo que el guard resuelve ya no llega al advisor, y lo que deja
|
|
14
|
+
* en `"ask"` es exactamente lo que el advisor debe juzgar. Invertir el orden
|
|
15
|
+
* haría que el advisor aprobara cosas que el guard iba a prohibir.
|
|
16
|
+
*
|
|
17
|
+
* EL CASO DEL PROPIO ADVISOR. El agente `apex-advisor` pasa por el guard como
|
|
18
|
+
* cualquier otro: su política por defecto le deja `execute` (imprescindible —
|
|
19
|
+
* opencode v2 invoca las herramientas desde el sandbox JS) y
|
|
20
|
+
* `apex_advisor_decide`, y le deniega el resto. Así, si su modelo intenta
|
|
21
|
+
* `write`, el guard lo corta sin consultarle a él mismo: el guard no llama a
|
|
22
|
+
* ningún modelo, de modo que no hay recursión posible.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { Effect } from "effect"
|
|
26
|
+
import type { Scope } from "effect"
|
|
27
|
+
import type { Plugin } from "@opencode/plugin/effect"
|
|
28
|
+
import { homedir } from "node:os"
|
|
29
|
+
import {
|
|
30
|
+
decide,
|
|
31
|
+
GuardReport,
|
|
32
|
+
ruleLabel,
|
|
33
|
+
type GuardConfigShape,
|
|
34
|
+
type GuardEffect,
|
|
35
|
+
type GuardEntry,
|
|
36
|
+
} from "./core/guard.js"
|
|
37
|
+
|
|
38
|
+
export type { GuardConfigShape }
|
|
39
|
+
|
|
40
|
+
const TOOL_NAME = "apex_guard_report"
|
|
41
|
+
const ADVISOR_AGENT = "apex-advisor"
|
|
42
|
+
const ADVISOR_TOOL = "apex_advisor_decide"
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Defaults: nada prohibido salvo lo del advisor, y en modo informe.
|
|
46
|
+
*
|
|
47
|
+
* Arrancar en `report` es deliberado: un guard recién configurado que empiece
|
|
48
|
+
* denegando rompe la sesión antes de que nadie haya visto una sola regla en
|
|
49
|
+
* acción. Se mira el informe, se ajustan las reglas y entonces se pasa a
|
|
50
|
+
* `enforce`.
|
|
51
|
+
*/
|
|
52
|
+
export function createDefaultGuardConfig(): GuardConfigShape & { enabled: boolean } {
|
|
53
|
+
return {
|
|
54
|
+
enabled: false,
|
|
55
|
+
mode: "report",
|
|
56
|
+
fallback: "keep",
|
|
57
|
+
keep: 500,
|
|
58
|
+
agents: {
|
|
59
|
+
[ADVISOR_AGENT]: [
|
|
60
|
+
{ action: "*", effect: "deny", reason: "el advisor solo decide; no toca el workspace" },
|
|
61
|
+
{ action: "execute", effect: "allow" },
|
|
62
|
+
{ action: ADVISOR_TOOL, effect: "allow" },
|
|
63
|
+
],
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Informe vivo, compartido por PROCESO.
|
|
70
|
+
*
|
|
71
|
+
* opencode instancia el plugin una vez por location (el propio advisor corre en
|
|
72
|
+
* `/tmp/opencode-apex-advisor`, que es otra), así que con el informe en ámbito de
|
|
73
|
+
* módulo el hook de una instancia anota donde la tool de otra no mira — y sale un
|
|
74
|
+
* informe vacío con el guard funcionando. `Symbol.for` es el único ámbito que
|
|
75
|
+
* coincide con el del recurso.
|
|
76
|
+
*/
|
|
77
|
+
const CELL = Symbol.for("apex.guard.report.v1")
|
|
78
|
+
|
|
79
|
+
function cell(keep: number): GuardReport {
|
|
80
|
+
const holder = globalThis as Record<symbol, GuardReport | undefined>
|
|
81
|
+
return (holder[CELL] ??= new GuardReport(keep))
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function guardReport(): GuardReport | null {
|
|
85
|
+
return (globalThis as Record<symbol, GuardReport | undefined>)[CELL] ?? null
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
interface PermissionEvaluationEvent {
|
|
89
|
+
readonly sessionID: string
|
|
90
|
+
readonly agent?: string
|
|
91
|
+
readonly action: string
|
|
92
|
+
readonly resources: readonly string[]
|
|
93
|
+
effect: GuardEffect
|
|
94
|
+
message?: string
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function register(
|
|
98
|
+
ctx: Plugin.Context,
|
|
99
|
+
config: GuardConfigShape & { enabled: boolean },
|
|
100
|
+
): Effect.Effect<void, never, Scope.Scope> {
|
|
101
|
+
return Effect.gen(function* () {
|
|
102
|
+
const projectDir = ctx.location?.directory ?? process.cwd()
|
|
103
|
+
const home = homedir()
|
|
104
|
+
const enforce = config.mode === "enforce"
|
|
105
|
+
const live = cell(config.keep)
|
|
106
|
+
|
|
107
|
+
yield* Effect.logInfo(
|
|
108
|
+
`[apex.guard] activo · modo=${config.mode} · fallback=${config.fallback} · agentes con reglas: ${
|
|
109
|
+
Object.keys(config.agents).join(", ") || "(ninguno)"
|
|
110
|
+
}`,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
// El cuerpo va envuelto porque `hooks.trigger` del host recorre los
|
|
114
|
+
// callbacks con `yield* result`: si este lanza, la cadena se corta y los
|
|
115
|
+
// hooks REGISTRADOS DESPUÉS no llegan a ejecutarse — el advisor, sin ir más
|
|
116
|
+
// lejos, dejaría de evaluar y nadie se enteraría. Un fallo del guard debe
|
|
117
|
+
// dejar el permiso como estaba, no desactivar lo que viene detrás.
|
|
118
|
+
yield* ctx.permission.hook("evaluate", (event) =>
|
|
119
|
+
Effect.sync(() => {
|
|
120
|
+
try {
|
|
121
|
+
aplicar(event as unknown as PermissionEvaluationEvent)
|
|
122
|
+
} catch (error) {
|
|
123
|
+
console.error(`[apex.guard] fallo evaluando un permiso, se deja como estaba: ${String(error)}`)
|
|
124
|
+
}
|
|
125
|
+
}),
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
function aplicar(e: PermissionEvaluationEvent): void {
|
|
129
|
+
{
|
|
130
|
+
const agent = e.agent ?? "(sin agente)"
|
|
131
|
+
const verdict = decide(
|
|
132
|
+
config,
|
|
133
|
+
{ agent: e.agent, action: e.action, resources: e.resources, incoming: e.effect },
|
|
134
|
+
{ projectDir, home },
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
// En modo informe se anota lo que HABRÍA pasado y no se toca el permiso.
|
|
138
|
+
const applied: GuardEffect = enforce ? verdict.effect : e.effect
|
|
139
|
+
|
|
140
|
+
const entry: GuardEntry = {
|
|
141
|
+
at: Date.now(),
|
|
142
|
+
agent,
|
|
143
|
+
action: e.action,
|
|
144
|
+
resources: e.resources,
|
|
145
|
+
incoming: verdict.incoming,
|
|
146
|
+
effect: verdict.effect,
|
|
147
|
+
applied,
|
|
148
|
+
reason: verdict.reason,
|
|
149
|
+
rule: ruleLabel(verdict.rule),
|
|
150
|
+
}
|
|
151
|
+
live.add(entry)
|
|
152
|
+
if (process.env.APEX_GUARD_TRACE)
|
|
153
|
+
console.log(`[apex.guard] ${agent} ${e.action} ${verdict.incoming}→${applied} ${verdict.reason ?? ""}`)
|
|
154
|
+
|
|
155
|
+
if (!enforce) return
|
|
156
|
+
// Solo se escribe cuando hay veredicto propio. Sin regla que coincida el
|
|
157
|
+
// permiso se deja intacto (`fallback: "keep"`), y eso es lo que permite
|
|
158
|
+
// que las reglas de `shell` de la config y el advisor sigan operando en
|
|
159
|
+
// los agentes para los que el guard no dice nada.
|
|
160
|
+
//
|
|
161
|
+
// Un `allow` SÍ eleva un `ask`, y es deliberado: es lo que deja a un
|
|
162
|
+
// subagente escribir en su propio directorio sin molestar al usuario. La
|
|
163
|
+
// elevación exige una regla explícita — nunca sale del fallback.
|
|
164
|
+
if (verdict.effect === e.effect) return
|
|
165
|
+
e.effect = verdict.effect
|
|
166
|
+
if (verdict.effect === "deny") {
|
|
167
|
+
const motivo = verdict.reason ?? "prohibido por los meta-permisos de apex"
|
|
168
|
+
e.message = `⛔ apex.guard: ${motivo}${verdict.rule ? ` [${ruleLabel(verdict.rule)}]` : ""}`
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// --- Tool de informe -------------------------------------------------
|
|
174
|
+
yield* ctx.tool.transform((editor) => {
|
|
175
|
+
editor.add({
|
|
176
|
+
name: TOOL_NAME,
|
|
177
|
+
description:
|
|
178
|
+
"Informe de los meta-permisos de apex: qué herramientas ha intentado cada agente y qué se decidió " +
|
|
179
|
+
"(allow/deny/ask), con la regla que lo decidió. Úsalo para auditar por qué se bloqueó una acción " +
|
|
180
|
+
"o para ajustar las reglas antes de pasar el guard a modo enforce.",
|
|
181
|
+
input: {
|
|
182
|
+
type: "object",
|
|
183
|
+
properties: {
|
|
184
|
+
limit: { type: "number", description: "Cuántas decisiones recientes devolver (por defecto 40)" },
|
|
185
|
+
agent: { type: "string", description: "Filtra por agente" },
|
|
186
|
+
effect: { type: "string", enum: ["allow", "deny", "ask"], description: "Filtra por efecto aplicado" },
|
|
187
|
+
},
|
|
188
|
+
additionalProperties: false,
|
|
189
|
+
},
|
|
190
|
+
// El informe sale como TEXTO, no como objeto: un `type: "object"` con
|
|
191
|
+
// claves dinámicas (el resumen va por agente) lo rechaza el validador de
|
|
192
|
+
// salida del host — «Tool returned a non-JSON value for its output
|
|
193
|
+
// schema» —, y además una tabla compacta cuesta bastantes menos tokens
|
|
194
|
+
// que el mismo contenido en JSON anidado.
|
|
195
|
+
output: {
|
|
196
|
+
type: "object",
|
|
197
|
+
properties: { report: { type: "string", description: "Informe en texto" } },
|
|
198
|
+
required: ["report"],
|
|
199
|
+
additionalProperties: false,
|
|
200
|
+
},
|
|
201
|
+
execute: (rawInput: unknown) =>
|
|
202
|
+
Effect.sync(() => {
|
|
203
|
+
const input = (rawInput ?? {}) as { limit?: number; agent?: string; effect?: GuardEffect }
|
|
204
|
+
const limit = Math.max(1, Math.min(input.limit ?? 40, config.keep))
|
|
205
|
+
let rows = live.recent(config.keep)
|
|
206
|
+
if (input.agent) rows = rows.filter((r) => r.agent === input.agent)
|
|
207
|
+
if (input.effect) rows = rows.filter((r) => r.applied === input.effect)
|
|
208
|
+
const shown = rows.slice(0, limit)
|
|
209
|
+
|
|
210
|
+
const lineas: string[] = [
|
|
211
|
+
`apex.guard · modo=${config.mode} · fallback=${config.fallback} · ${live.all().length} decisiones registradas`,
|
|
212
|
+
]
|
|
213
|
+
|
|
214
|
+
const resumen = live.summary()
|
|
215
|
+
const agentes = Object.keys(resumen).sort()
|
|
216
|
+
if (agentes.length > 0) {
|
|
217
|
+
lineas.push("", "resumen (allow/deny/ask por agente):")
|
|
218
|
+
for (const a of agentes) {
|
|
219
|
+
const r = resumen[a]!
|
|
220
|
+
lineas.push(` ${a.padEnd(20)} allow=${r.allow} deny=${r.deny} ask=${r.ask}`)
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if (shown.length === 0) {
|
|
225
|
+
lineas.push("", "sin decisiones que encajen con el filtro")
|
|
226
|
+
} else {
|
|
227
|
+
lineas.push("", `últimas ${shown.length} (más reciente primero):`)
|
|
228
|
+
for (const r of shown) {
|
|
229
|
+
const hora = new Date(r.at).toISOString().slice(11, 19)
|
|
230
|
+
const flecha = r.incoming === r.applied ? r.applied : `${r.incoming}→${r.applied}`
|
|
231
|
+
const recursos = r.resources.length > 0 ? ` ${r.resources.slice(0, 2).join(" ")}` : ""
|
|
232
|
+
const regla = r.rule ? ` · regla: ${r.rule}` : ""
|
|
233
|
+
const motivo = r.reason && r.applied === "deny" ? ` · ${r.reason}` : ""
|
|
234
|
+
lineas.push(` ${hora} ${r.agent} ${r.action}${recursos} → ${flecha}${regla}${motivo}`)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (config.mode === "report") {
|
|
239
|
+
lineas.push(
|
|
240
|
+
"",
|
|
241
|
+
'modo "report": la columna → muestra lo que se HABRÍA aplicado; el permiso no se ha tocado.',
|
|
242
|
+
)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return { output: { report: lineas.join("\n") } }
|
|
246
|
+
}),
|
|
247
|
+
})
|
|
248
|
+
})
|
|
249
|
+
})
|
|
250
|
+
}
|
package/index.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* opencode-apex — Modular monolithic plugin for OpenCode V2 (Effect-native API).
|
|
3
|
+
*
|
|
4
|
+
* Modules:
|
|
5
|
+
* - redact: Secret detection (regex), encryption-based redaction, restore on tool input
|
|
6
|
+
* - events: RPC + plaintext-listener event ingestion, subscriptions, delivery
|
|
7
|
+
* - advisor: allow/deny permission decisions via a dedicated agent + side session
|
|
8
|
+
* - guard: meta-permissions per agent/tool/path (opt-in)
|
|
9
|
+
* - browser: browser.* tools against an external Chromium over CDP (attach on request)
|
|
10
|
+
*
|
|
11
|
+
* Built on the official Effect plugin API: https://opencode.ai/v2/docs/build/plugins/effect/
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { Plugin } from "@opencode/plugin/effect"
|
|
15
|
+
import { Effect, Stream } from "effect"
|
|
16
|
+
import { homedir } from "node:os"
|
|
17
|
+
import { loadApexConfig, loadConfig, type ApexConfig } from "./core/config.js"
|
|
18
|
+
import { emit as busEmit } from "./core/bus.js"
|
|
19
|
+
import { register as registerRedact, createDefaultRedactConfig, type RedactConfig } from "./redact.js"
|
|
20
|
+
import { register as registerEvents, createDefaultEventsConfig, type EventsConfig } from "./events.js"
|
|
21
|
+
import { register as registerAdvisor, createDefaultAdvisorConfig, type AdvisorConfig } from "./advisor.js"
|
|
22
|
+
import { register as registerGuard, createDefaultGuardConfig, type GuardConfigShape } from "./guard.js"
|
|
23
|
+
import { register as registerBrowser, createDefaultBrowserConfig, type BrowserConfigShape } from "./browser.js"
|
|
24
|
+
import { registerCentralRpc } from "./core/rpc.js"
|
|
25
|
+
|
|
26
|
+
// Plugin version
|
|
27
|
+
const VERSION = "0.1.0"
|
|
28
|
+
|
|
29
|
+
interface ModuleConfigs {
|
|
30
|
+
redact: RedactConfig & { enabled: boolean }
|
|
31
|
+
events: EventsConfig & { enabled: boolean }
|
|
32
|
+
advisor: AdvisorConfig & { enabled: boolean }
|
|
33
|
+
guard: GuardConfigShape & { enabled: boolean }
|
|
34
|
+
browser: BrowserConfigShape
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Merge user config with defaults for each module.
|
|
39
|
+
*/
|
|
40
|
+
function getModuleConfigs(userConfig: ApexConfig): ModuleConfigs {
|
|
41
|
+
return {
|
|
42
|
+
redact: { ...createDefaultRedactConfig(), ...userConfig.redact, enabled: userConfig.modules?.redact ?? true },
|
|
43
|
+
events: { ...createDefaultEventsConfig(), ...userConfig.events, enabled: userConfig.modules?.events ?? true } as ModuleConfigs["events"],
|
|
44
|
+
advisor: { ...createDefaultAdvisorConfig(), ...userConfig.advisor, enabled: userConfig.modules?.advisor ?? true },
|
|
45
|
+
// Opt-in: sin reglas no hace nada útil, y con reglas mal puestas bloquea al
|
|
46
|
+
// agente, así que se activa a mano.
|
|
47
|
+
guard: { ...createDefaultGuardConfig(), ...userConfig.guard, enabled: userConfig.modules?.guard ?? false },
|
|
48
|
+
// Activado por defecto; en modo `external` puede abrir un popup de Chrome por conexión.
|
|
49
|
+
browser: {
|
|
50
|
+
...createDefaultBrowserConfig(),
|
|
51
|
+
...userConfig.browser,
|
|
52
|
+
enabled: userConfig.modules?.browser ?? true,
|
|
53
|
+
},
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Main plugin definition (Effect-native).
|
|
59
|
+
*/
|
|
60
|
+
export default Plugin.define({
|
|
61
|
+
id: "apex",
|
|
62
|
+
effect: (ctx) =>
|
|
63
|
+
Effect.gen(function* () {
|
|
64
|
+
// Track start time for uptime
|
|
65
|
+
;(globalThis as any).__apexStartTime = Date.now()
|
|
66
|
+
|
|
67
|
+
// Configuración con JERARQUÍA y dos canales.
|
|
68
|
+
// precedencia (menor → mayor): fichero global
|
|
69
|
+
// (<config>/opencode/opencode-apex.jsonc) → opciones inline del plugin
|
|
70
|
+
// (opencode.json, ya mergeadas local>global por el host) → fichero local
|
|
71
|
+
// (<proyecto>/.opencode/opencode-apex.jsonc). Ver docs/CONFIG.md.
|
|
72
|
+
const home = homedir()
|
|
73
|
+
const projectDir = ctx.location.directory
|
|
74
|
+
const loaded = yield* Effect.tryPromise(() =>
|
|
75
|
+
loadApexConfig({
|
|
76
|
+
projectDir,
|
|
77
|
+
home,
|
|
78
|
+
options: ctx.options as Record<string, unknown> | undefined,
|
|
79
|
+
}),
|
|
80
|
+
).pipe(
|
|
81
|
+
Effect.catch((error) =>
|
|
82
|
+
Effect.logWarning(`[apex] configuración inválida, usando defaults: ${String(error)}`).pipe(
|
|
83
|
+
Effect.andThen(
|
|
84
|
+
Effect.promise(() =>
|
|
85
|
+
loadApexConfig({ projectDir, home, options: undefined }).catch(() => ({
|
|
86
|
+
config: undefined as unknown as ApexConfig,
|
|
87
|
+
sources: { inline: false, global: false, local: false },
|
|
88
|
+
paths: { global: "", local: "" },
|
|
89
|
+
})),
|
|
90
|
+
),
|
|
91
|
+
),
|
|
92
|
+
),
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
const validatedConfig = loaded.config ?? (yield* Effect.promise(() => loadConfig(`${projectDir}/__apex_defaults__.jsonc`)))
|
|
96
|
+
yield* Effect.logInfo(
|
|
97
|
+
`[apex] config: inline=${loaded.sources.inline} global=${loaded.sources.global} local=${loaded.sources.local} · global=${loaded.paths.global} · local=${loaded.paths.local}`,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
// Get module configs with defaults
|
|
101
|
+
const moduleConfigs = getModuleConfigs(validatedConfig)
|
|
102
|
+
|
|
103
|
+
// --- Bus: feed OpenCode events into the apex event buffer ---
|
|
104
|
+
yield* ctx.event.subscribe().pipe(
|
|
105
|
+
Stream.tap((event) =>
|
|
106
|
+
Effect.sync(() => {
|
|
107
|
+
busEmit(event.type, (event.data ?? {}) as Record<string, unknown>, "opencode")
|
|
108
|
+
}),
|
|
109
|
+
),
|
|
110
|
+
Stream.runDrain,
|
|
111
|
+
Effect.forkScoped,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
// --- Feature modules (conditionally enabled) ---
|
|
115
|
+
if (moduleConfigs.redact.enabled) {
|
|
116
|
+
yield* registerRedact(ctx, moduleConfigs.redact)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (moduleConfigs.events.enabled) {
|
|
120
|
+
yield* registerEvents(ctx, validatedConfig)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ANTES del advisor, y el orden es funcional, no estético: el host recorre
|
|
124
|
+
// los hooks de `permission.evaluate` en orden de registro sobre el mismo
|
|
125
|
+
// evento, y el advisor solo juzga lo que siga en "ask". Con el guard
|
|
126
|
+
// delante, lo que él resuelve no llega al advisor; al revés, el advisor
|
|
127
|
+
// aprobaría cosas que el guard iba a prohibir.
|
|
128
|
+
if (moduleConfigs.guard.enabled) {
|
|
129
|
+
yield* registerGuard(ctx, moduleConfigs.guard)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (moduleConfigs.advisor.enabled) {
|
|
133
|
+
yield* registerAdvisor(ctx, moduleConfigs.advisor)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (moduleConfigs.browser.enabled) {
|
|
137
|
+
yield* registerBrowser(ctx, moduleConfigs.browser)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// --- Central RPC registration (the "apex" namespace) ---
|
|
141
|
+
yield* registerCentralRpc(ctx, moduleConfigs as unknown as Record<string, { enabled: boolean }>, VERSION)
|
|
142
|
+
|
|
143
|
+
}),
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
// Re-export types for external use
|
|
147
|
+
export type { ApexConfig }
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
{
|
|
2
|
+
// ==========================================================================
|
|
3
|
+
// opencode-apex — configuración de ejemplo completa
|
|
4
|
+
//
|
|
5
|
+
// JERARQUÍA Y CANALES (precedencia de menor a mayor):
|
|
6
|
+
// 1. fichero GLOBAL ~/.config/opencode/opencode-apex.jsonc
|
|
7
|
+
// 2. opciones inline del plugin en opencode.json { "plugins": [{ "package": "…", "options": {…} }] }
|
|
8
|
+
// 3. fichero LOCAL <proyecto>/.opencode/opencode-apex.jsonc ← este
|
|
9
|
+
// Reglas: el ámbito manda (local > global) y dentro de cada ámbito el
|
|
10
|
+
// fichero gana a las opciones inline ⇒ local-inline > global-file.
|
|
11
|
+
//
|
|
12
|
+
// COMENTARIOS: se aceptan #, // y /* */ (los # dentro de strings se respetan)
|
|
13
|
+
//
|
|
14
|
+
// PLANTILLAS (events.promptTemplateFile, advisor.promptTemplateFile):
|
|
15
|
+
// solo rutas relativas — al proyecto ("prompts/x.md") o al home ("~/x.md").
|
|
16
|
+
// Las absolutas se rechazan; si el fichero no existe se CREA con defaults.
|
|
17
|
+
//
|
|
18
|
+
// Todos los campos son opcionales: el plugin arranca con defaults si no hay
|
|
19
|
+
// ninguna fuente. Las variables de entorno se interpolan con ${VAR} o ${VAR:-default}.
|
|
20
|
+
// ==========================================================================
|
|
21
|
+
|
|
22
|
+
// --------------------------------------------------------------------------
|
|
23
|
+
// Módulos: activa/desactiva cada uno individualmente.
|
|
24
|
+
// FUENTE ÚNICA: el toggle vive SOLO aquí — no existe <modulo>.enabled.
|
|
25
|
+
// Si se omite una clave, el módulo queda activo por defecto.
|
|
26
|
+
// --------------------------------------------------------------------------
|
|
27
|
+
"modules": {
|
|
28
|
+
"redact": true,
|
|
29
|
+
"events": false,
|
|
30
|
+
"advisor": true,
|
|
31
|
+
"guard": false,
|
|
32
|
+
"browser": true
|
|
33
|
+
},
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
// --------------------------------------------------------------------------
|
|
37
|
+
// redact — redacción de secretos por cifrado (AES-256-GCM).
|
|
38
|
+
//
|
|
39
|
+
// Cada coincidencia se cifra y se sustituye por el marcador legible:
|
|
40
|
+
// ${prefix}${nombreDelPatron}:${base64url(iv||tag||ciphertext)}${suffix}
|
|
41
|
+
// p. ej. [SECRET:github-pat:AbC123...]
|
|
42
|
+
// La restauración descifra el propio marcador (no hay mapping en memoria).
|
|
43
|
+
// Se redacta solo de cara al modelo (hook context) y se restaura solo en los
|
|
44
|
+
// argumentos de tool (hook execute.before): la respuesta del modelo no se
|
|
45
|
+
// restaura, el usuario ve el marcador legible.
|
|
46
|
+
//
|
|
47
|
+
// patterns: regex propias (se suman a los bundles)
|
|
48
|
+
// bundles: conjuntos de patrones por nombre. Por defecto se activan TODOS
|
|
49
|
+
// menos los opt-in. Disponibles: aws, github, gitlab, slack, jwt,
|
|
50
|
+
// pem, bearer, env, openai, anthropic, google, stripe, npm, database,
|
|
51
|
+
// azure, terraform, vault, heroku, vercel, supabase, digitalocean,
|
|
52
|
+
// cloudflare, observability, pypi, rubygems, twilio, sendgrid,
|
|
53
|
+
// postman, mailgun, mailchimp, linear, shopify, square, docker,
|
|
54
|
+
// kubernetes, cohere, huggingface, discord.
|
|
55
|
+
// Opt-in (ruidosos/PII, NO activos por defecto): pii, network, datadog.
|
|
56
|
+
// minConfidence: low | medium | high — filtra patrones ruidosos (default medium)
|
|
57
|
+
// allowlist: regex que NUNCA se redactan
|
|
58
|
+
// key: material de clave -> literal | env:VAR | file:/ruta | hex:... | base64:...
|
|
59
|
+
// También se interpola ${VAR} / ${VAR:-default} en cualquier string.
|
|
60
|
+
// Si no se resuelve, se genera una clave aleatoria y se persiste en
|
|
61
|
+
// ~/.config/opencode/apex.key (0600) para que la restauración funcione.
|
|
62
|
+
// mode: "strict" (redacta) | "warn" (solo registra)
|
|
63
|
+
// restore: qué salidas se descifran (solo input de tool por ahora)
|
|
64
|
+
// --------------------------------------------------------------------------
|
|
65
|
+
"redact": {
|
|
66
|
+
"mode": "strict",
|
|
67
|
+
"patterns": ["\\bcustom-secret-[A-Za-z0-9]{16}\\b","private-password"],
|
|
68
|
+
"bundles": ["aws", "github", "gitlab", "slack", "jwt", "pem", "bearer", "env", "openai", "anthropic", "google", "stripe", "npm", "database", "azure", "terraform", "vault", "heroku", "vercel", "supabase", "digitalocean", "cloudflare", "observability", "pypi", "rubygems", "twilio", "sendgrid", "postman", "mailgun", "mailchimp", "linear", "shopify", "square", "docker", "kubernetes", "cohere", "huggingface", "discord"],
|
|
69
|
+
"minConfidence": "medium",
|
|
70
|
+
"allowlist": ["^sk-test-"],
|
|
71
|
+
"prefix": "[SECRET:",
|
|
72
|
+
"suffix": "]",
|
|
73
|
+
"key": "env:APEX_REDACT_KEY",
|
|
74
|
+
"restore": { "toolInput": true }
|
|
75
|
+
},
|
|
76
|
+
|
|
77
|
+
// --------------------------------------------------------------------------
|
|
78
|
+
// events — ingesta genérica de eventos, suscripciones y entrega.
|
|
79
|
+
// routing: "all" (fan-out a todas las suscripciones) | "first" (solo la de mayor prioridad)
|
|
80
|
+
// Cada suscripción filtra eventos y los entrega a una sesión. La plantilla
|
|
81
|
+
// puede ser inline (promptTemplate) o un fichero (promptTemplateFile, tiene
|
|
82
|
+
// prioridad). Placeholders: {{payload.campo}}, {{source}}, {{type}}, {{eventID}}.
|
|
83
|
+
// deliverAs: "prompt" (user prompt, por defecto) | "synthetic" (mensaje sintético).
|
|
84
|
+
// resume: SOLO con deliverAs="synthetic". true → despierta el bucle del agente
|
|
85
|
+
// (execution.wake) y el modelo procesa el mensaje; false → inyección
|
|
86
|
+
// pasiva, solo aparece en la sesión (default false).
|
|
87
|
+
// sessionID:
|
|
88
|
+
// - "" / null / ausente → AUTO-VINCULACIÓN a la sesión principal activa
|
|
89
|
+
// (la raíz que se crea al abrir opencode). NO se vincula a la sesión del
|
|
90
|
+
// advisor ni a sesiones de subagentes (parentID).
|
|
91
|
+
// Al cerrarse esa sesión, la suscripción se DESVINCULA automáticamente;
|
|
92
|
+
// una nueva sesión principal la vuelve a vincular.
|
|
93
|
+
// - "ses_xxx" → sesión explícita (si no existe, la entrega falla y se registra).
|
|
94
|
+
// Los ejemplos van con "enabled": false.
|
|
95
|
+
// operator: equals | contains | matches | gt | lt | in | notIn | exists | notExists
|
|
96
|
+
// delivery: "queue" (espera turno) | "steer" (inyecta en el turno actual)
|
|
97
|
+
// --------------------------------------------------------------------------
|
|
98
|
+
"events": {
|
|
99
|
+
"routing": "all",
|
|
100
|
+
// Listener HTTP plano: expone EL MISMO events.ingest para scripts sin
|
|
101
|
+
// credenciales (curl desde otra máquina, hook de arranque, túnel…).
|
|
102
|
+
// host: "127.0.0.1" (loopback) | "0.0.0.0" | una IP LAN. Fuera de loopback
|
|
103
|
+
// define token (quien pueda llamarlo puede inyectar prompts al agente).
|
|
104
|
+
"listener": {
|
|
105
|
+
// Activo por defecto en loopback (el agente puede montar callbacks,
|
|
106
|
+
// incluido un túnel, sin tocar la config). Ponlo a false para no abrir puerto.
|
|
107
|
+
"enabled": true,
|
|
108
|
+
"host": "127.0.0.1",
|
|
109
|
+
"port": 4599,
|
|
110
|
+
"token": "",
|
|
111
|
+
// Fallback de URL pública. Normalmente NO hace falta: el agente fija la
|
|
112
|
+
// URL del túnel en runtime con la tool apex_set_callback_url
|
|
113
|
+
// (precedencia: runtime > esta config).
|
|
114
|
+
"publicUrl": ""
|
|
115
|
+
},
|
|
116
|
+
"subscriptions": [
|
|
117
|
+
{
|
|
118
|
+
"sessionID": "",
|
|
119
|
+
"agent": "plan",
|
|
120
|
+
"filters": [
|
|
121
|
+
{ "field": "type", "operator": "equals", "value": "ci.failed" },
|
|
122
|
+
{ "field": "payload.branch", "operator": "in", "value": ["main", "release/*"] }
|
|
123
|
+
],
|
|
124
|
+
"promptTemplate": "CI failed on {{payload.branch}} ({{payload.commit}}). Investigate and propose a fix.",
|
|
125
|
+
"promptTemplateFile": "prompts/ci-failure.md",
|
|
126
|
+
"deliverAs": "prompt",
|
|
127
|
+
"delivery": "queue",
|
|
128
|
+
"priority": 10,
|
|
129
|
+
"enabled": false
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
"sessionID": "",
|
|
133
|
+
"filters": [{ "field": "type", "operator": "matches", "pattern": "^deploy\\." }],
|
|
134
|
+
"promptTemplate": "Deploy detectado: {{payload.env}}",
|
|
135
|
+
"deliverAs": "synthetic",
|
|
136
|
+
"resume": true,
|
|
137
|
+
"delivery": "steer",
|
|
138
|
+
"priority": 5,
|
|
139
|
+
"enabled": false
|
|
140
|
+
}
|
|
141
|
+
]
|
|
142
|
+
},
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
// --------------------------------------------------------------------------
|
|
147
|
+
// browser — las tools browser.* contra un Chromium EXTERNO por CDP.
|
|
148
|
+
//
|
|
149
|
+
// El plugin-browser del host ya registra esas tools, pero su attachment solo
|
|
150
|
+
// existe si alguien se engancha (en un servidor sin app de escritorio está
|
|
151
|
+
// vacío y todo falla con "browser is disconnected"). Este módulo se engancha
|
|
152
|
+
// y las sirve contra un navegador real.
|
|
153
|
+
//
|
|
154
|
+
// mode:
|
|
155
|
+
// "auto" (default) espera a que se lo pidan. Cero sorpresas.
|
|
156
|
+
// "external" se engancha en cuanto detecta una sesión activa.
|
|
157
|
+
// "in-app" no se engancha: deja servir a la app de escritorio.
|
|
158
|
+
//
|
|
159
|
+
// OJO con el conflicto: el protocolo admite UN attachment por sesión
|
|
160
|
+
// (connection.ts:59 reemplaza al anterior). El plugin y la app Electron nunca
|
|
161
|
+
// sirven la misma sesión a la vez; el que pierde ve "browser.disconnected".
|
|
162
|
+
// Se cambia en caliente con la tool browser.target o /browser-target.
|
|
163
|
+
//
|
|
164
|
+
// cdpUrl: "auto" (lee DevToolsActivePort de los perfiles conocidos)
|
|
165
|
+
// | "puerto" | "ws://host:puerto/ruta" | "wss://…" para remoto
|
|
166
|
+
// profile: perfil explícito. "" = deducir. Pisar esto sobre
|
|
167
|
+
// ai.opencode.desktop exige que la app Electron esté CERRADA: dos
|
|
168
|
+
// procesos sobre el mismo user-data-dir corrompen el SQLite de cookies.
|
|
169
|
+
// headers/caFile/insecureSkipVerify: para un wss:// remoto detrás de un proxy
|
|
170
|
+
// inverso. El CDP nativo de Chrome no habla TLS ni pide cabeceras, así
|
|
171
|
+
// que un navegador en otra máquina necesita túnel (ssh -L, tailscale,
|
|
172
|
+
// cloudflared, nginx) delante.
|
|
173
|
+
//
|
|
174
|
+
// ESTO ES EL DEFAULT, NO LO ÚNICO. browser.target y /browser-target aceptan
|
|
175
|
+
// un destino y mandan sobre la config, en caliente:
|
|
176
|
+
// browser.target({ mode: "external", cdpUrl: "9333" })
|
|
177
|
+
// browser.target({ mode: "external", profile: "~/.config/google-chrome" })
|
|
178
|
+
// /browser-target external 9333
|
|
179
|
+
// /browser-target external wss://tunnel.example/devtools
|
|
180
|
+
// Un destino que empieza por / o ~ es un perfil; el resto, URL o puerto.
|
|
181
|
+
// Omitirlo NO lo cambia. Cambiarlo cierra el socket y suelta los
|
|
182
|
+
// attachments; la sesión que lo cambió se reengancha en la misma llamada y
|
|
183
|
+
// las demás lo piden de nuevo con browser.target o /browser-target (el
|
|
184
|
+
// enganche es siempre a petición, nunca en cada tool call).
|
|
185
|
+
//
|
|
186
|
+
// MODOS DE CHROME QUE IMPORTAN:
|
|
187
|
+
// --remote-debugging-port → /json/version responde 200. INERTE sobre el
|
|
188
|
+
// user-data-dir por defecto desde Chrome 136, así que necesita perfil
|
|
189
|
+
// propio. Sin popup.
|
|
190
|
+
// chrome://inspect/#remote-debugging (toggle) → /json/version da 404 POR
|
|
191
|
+
// DISEÑO y la URL sale de DevToolsActivePort. Pide un popup "Allow remote
|
|
192
|
+
// debugging?" POR CONEXIÓN. El socket se mantiene abierto, pero recargar
|
|
193
|
+
// el plugin lo pide de nuevo.
|
|
194
|
+
//
|
|
195
|
+
// Varios perfiles pueden declarar el mismo puerto (los ficheros quedan stale
|
|
196
|
+
// al cerrar Chrome), así que se prueban en orden y gana el primero que
|
|
197
|
+
// responde de verdad. Por eso conectar puede tardar.
|
|
198
|
+
// --------------------------------------------------------------------------
|
|
199
|
+
"browser": {
|
|
200
|
+
"mode": "auto",
|
|
201
|
+
"cdpUrl": "auto",
|
|
202
|
+
"profile": "",
|
|
203
|
+
"connectTimeoutMs": 90000,
|
|
204
|
+
"reconnectSeconds": 15,
|
|
205
|
+
"headers": {},
|
|
206
|
+
"caFile": "",
|
|
207
|
+
"insecureSkipVerify": false
|
|
208
|
+
},
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
// --------------------------------------------------------------------------
|
|
212
|
+
// advisor — decisiones de permiso mediante una sesión advisor dedicada.
|
|
213
|
+
//
|
|
214
|
+
// El plugin define (upsert) el agente oculto "apex-advisor" con su propio
|
|
215
|
+
// modelo y permisos: SOLO puede usar la herramienta apex_advisor_decide.
|
|
216
|
+
// Existe UNA sesión advisor por ÁRBOL: la sesión agente-usuario (raíz) y todos
|
|
217
|
+
// sus subagentes comparten la misma sesión advisor, que queda registrada
|
|
218
|
+
// entera → auditoría completa de cada allow/deny.
|
|
219
|
+
//
|
|
220
|
+
// Vocabulario: aprobar = "allow"; denegar = "deny" + reason.
|
|
221
|
+
// model: modelo del agente advisor (rápido/barato; corre con contexto completo)
|
|
222
|
+
// decisive: true = su decisión se aplica al permiso · false = solo informa
|
|
223
|
+
// evaluate: "ask-only" (default) solo cuando tus reglas no resolvieron ·
|
|
224
|
+
// "all" consulta en CADA tool call
|
|
225
|
+
// timeoutMs: sin decisión a tiempo no se altera el permiso (no bloquea)
|
|
226
|
+
// location: directorio de la sesión advisor. Por defecto uno dedicado FUERA
|
|
227
|
+
// del proyecto: la discovery de instrucciones es por location, así
|
|
228
|
+
// no se le inyecta el AGENTS.md del repo. (El AGENTS.md global de
|
|
229
|
+
// ~/.config/opencode sí aplica siempre.)
|
|
230
|
+
// actions: filtro de nombres de tool (vacío = todas)
|
|
231
|
+
// system: system prompt del agente advisor (opcional)
|
|
232
|
+
// promptTemplate: plantilla de la petición ({{requestID}}, {{action}}, {{resources}}…)
|
|
233
|
+
// --------------------------------------------------------------------------
|
|
234
|
+
"advisor": {
|
|
235
|
+
"model": "opencode/big-pickle",
|
|
236
|
+
"decisive": true,
|
|
237
|
+
"evaluate": "ask-only",
|
|
238
|
+
"timeoutMs": 10000,
|
|
239
|
+
"location": "",
|
|
240
|
+
"actions": [],
|
|
241
|
+
"promptTemplate": "Solicitud {{requestID}}
|
|
242
|
+
Tool: {{action}}
|
|
243
|
+
Recursos: {{resources}}
|
|
244
|
+
Sesión: {{sessionID}} ({{agent}})
|
|
245
|
+
{{enforcement}}
|
|
246
|
+
Decidí con apex_advisor_decide."
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
}
|