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/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "opencode-apex",
3
+ "version": "0.1.0",
4
+ "description": "Modular monolithic plugin for OpenCode V2 — redaction, events, advisor permissions, guard meta-permissions, external browser over CDP",
5
+ "type": "module",
6
+ "main": "index.ts",
7
+ "engines": {
8
+ "opencode": ">=2.0.0 <3"
9
+ },
10
+ "files": [
11
+ "index.ts",
12
+ "redact.ts",
13
+ "events.ts",
14
+ "advisor.ts",
15
+ "guard.ts",
16
+ "browser.ts",
17
+ "browser",
18
+ "core",
19
+ "docs",
20
+ "opencode-apex.jsonc"
21
+ ],
22
+ "dependencies": {
23
+ "@opencode/plugin": "latest",
24
+ "@opencode/plugin-browser": "^2.0.21",
25
+ "effect": "4.0.0-rc.112",
26
+ "jsonc-parser": "^3.3.1",
27
+ "ws": "^8.22.0",
28
+ "zod": "^3.24.0"
29
+ },
30
+ "devDependencies": {
31
+ "typescript": "^5.5.0",
32
+ "bun-types": "^1.1.0"
33
+ }
34
+ }
package/redact.ts ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Apex Redact — módulo de redacción de secretos basada en cifrado.
3
+ *
4
+ * Flujo (crítico):
5
+ * ENTRADA al modelo → REDACTAR
6
+ * - session.hook("context") ← único punto: system prompt + mensajes + tools
7
+ *
8
+ * SALIDA hacia la herramienta → RESTAURAR
9
+ * - tool.hook("execute.before") ← único punto: argumentos de la tool
10
+ *
11
+ * El resto de salidas (respuesta del modelo, razonamiento) NO se restauran:
12
+ * el usuario ve marcadores legibles `[SECRET:patrón:cifrado]` en lugar del
13
+ * secreto. El store de sesión conserva el texto original (solo se redacta
14
+ * de cara al modelo).
15
+ *
16
+ * El marcador es `${prefix}${patternName}:${base64url(iv||tag||ciphertext)}${suffix}`:
17
+ * no hay mapping en memoria, la restauración descifra el propio marcador.
18
+ */
19
+
20
+ import { Effect } from "effect"
21
+ import type { Scope } from "effect"
22
+ import type { Plugin } from "@opencode/plugin/effect"
23
+ import { compilePatterns, DEFAULT_BUNDLES, type PatternDefinition } from "./core/patterns.js"
24
+ import { createRedactEngine, type RedactEngine } from "./core/redact.js"
25
+ import { resolveKey } from "./core/crypto.js"
26
+ import type { RedactConfig } from "./core/config.js"
27
+
28
+ export type { RedactConfig }
29
+
30
+ /** Findings del último proceso RPC (reutilizado para no asignar en cada llamada). */
31
+ const rpcFindings: Array<{ pattern: string }> = []
32
+
33
+ /** Handler del módulo, consumido por el RPC `redact.process` (set en register). */
34
+ export let redactHandler:
35
+ | ((input: { text: string; mode?: "strict" | "warn" }) => { redacted: string; findings: unknown[] })
36
+ | null = null
37
+
38
+ export function createDefaultRedactConfig(): RedactConfig & { enabled: boolean } {
39
+ return {
40
+ enabled: true,
41
+ mode: "strict",
42
+ patterns: [],
43
+ bundles: [...DEFAULT_BUNDLES],
44
+ minConfidence: "medium",
45
+ allowlist: [],
46
+ prefix: "[SECRET:",
47
+ suffix: "]",
48
+ key: "",
49
+ restore: { toolInput: true },
50
+ }
51
+ }
52
+
53
+ // ---------------------------------------------------------------------------
54
+ // Compilación de la configuración → motor
55
+ // ---------------------------------------------------------------------------
56
+
57
+ export interface CompiledRedact {
58
+ readonly engine: RedactEngine
59
+ readonly patterns: PatternDefinition[]
60
+ }
61
+
62
+ export function compileRedactConfig(config: RedactConfig): CompiledRedact {
63
+ const patterns = compilePatterns(config.bundles ?? [], config.patterns ?? [], config.minConfidence ?? "medium")
64
+ const allowlist = (config.allowlist ?? []).flatMap((source) => {
65
+ try {
66
+ return [new RegExp(source)]
67
+ } catch (error) {
68
+ console.warn(`[apex.redact] allowlist inválida (${source}): ${String(error)}`)
69
+ return []
70
+ }
71
+ })
72
+
73
+ const { key, source, fingerprint } = resolveKey(config.key)
74
+ console.info(`[apex.redact] Clave cargada (source=${source}, fp=${fingerprint}), ${patterns.length} patrones activos`)
75
+
76
+ const engine = createRedactEngine({
77
+ patterns,
78
+ allowlist,
79
+ prefix: config.prefix,
80
+ suffix: config.suffix,
81
+ key,
82
+ mode: config.mode,
83
+ onFinding: ({ pattern, stage }) => {
84
+ console.debug(`[apex.redact] secreto detectado (patrón=${pattern}, stage=${stage ?? "?"})`)
85
+ },
86
+ })
87
+
88
+ return { engine, patterns }
89
+ }
90
+
91
+ // ---------------------------------------------------------------------------
92
+ // Registro del módulo (Effect-native)
93
+ // ---------------------------------------------------------------------------
94
+
95
+ export function register(
96
+ ctx: Plugin.Context,
97
+ config: RedactConfig & { enabled?: boolean },
98
+ ): Effect.Effect<void, never, Scope.Scope> {
99
+ return Effect.gen(function* () {
100
+ if (!config.enabled) return
101
+
102
+ const { engine, patterns } = compileRedactConfig(config)
103
+ const key = resolveKey(config.key).key
104
+
105
+ // Motores precompilados para el RPC (evita recompilar y re-resolver la clave
106
+ // en cada llamada).
107
+ const rpcEngines = {
108
+ strict: createRedactEngine({
109
+ patterns, allowlist: [], prefix: config.prefix, suffix: config.suffix,
110
+ key, mode: "strict", onFinding: (f) => rpcFindings.push({ pattern: f.pattern }),
111
+ }),
112
+ warn: createRedactEngine({
113
+ patterns, allowlist: [], prefix: config.prefix, suffix: config.suffix,
114
+ key, mode: "warn", onFinding: (f) => rpcFindings.push({ pattern: f.pattern }),
115
+ }),
116
+ }
117
+ const restoreCfg = config.restore ?? { toolInput: true }
118
+
119
+ // Exponer la redacción por RPC (motores precompilados)
120
+ redactHandler = (input) => {
121
+ rpcFindings.length = 0
122
+ const probe = (input.mode ?? config.mode) === "warn" ? rpcEngines.warn : rpcEngines.strict
123
+ const redacted = probe.redactText(input.text, "rpc")
124
+ return { redacted, findings: [...rpcFindings] }
125
+ }
126
+
127
+ // ------------------------------------------------------------------
128
+ // ENTRADA al modelo → redactar
129
+ // ------------------------------------------------------------------
130
+ // Punto único: el hook `context` recibe system prompt + mensajes (incluye
131
+ // prompt del usuario y resultados de tools) + definiciones de tools, justo
132
+ // antes de enviarse al proveedor. Es transport-agnostic (HTTP, WS o ACP).
133
+ yield* ctx.session.hook("context", (event) =>
134
+ Effect.sync(() => {
135
+ event.system = engine.redactValue(event.system, "system") as typeof event.system
136
+ event.messages = engine.redactValue(event.messages, "messages") as typeof event.messages
137
+ event.tools = engine.redactValue(event.tools, "tools") as typeof event.tools
138
+ }),
139
+ )
140
+
141
+ // ------------------------------------------------------------------
142
+ // SALIDA hacia la herramienta → restaurar
143
+ // ------------------------------------------------------------------
144
+ // El modelo solo vio marcadores; al invocar una tool, sus argumentos deben
145
+ // volver a ser el secreto real para que la herramienta funcione.
146
+ if (restoreCfg.toolInput) {
147
+ yield* ctx.tool.hook("execute.before", (event) =>
148
+ Effect.sync(() => {
149
+ if (event.input !== undefined) {
150
+ event.input = engine.restoreValue(event.input)
151
+ }
152
+ }),
153
+ )
154
+ }
155
+ })
156
+ }