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/core/config.ts ADDED
@@ -0,0 +1,533 @@
1
+ /**
2
+ * opencode-apex — Configuración central con validación Zod, resolución de variables de entorno
3
+ * y patrón last-good para fallback seguro.
4
+ */
5
+ import { z } from "zod"
6
+ import type { GuardConfigShape } from "./guard.js"
7
+ import { DEFAULT_BUNDLES } from "./patterns.js"
8
+ import { readFile } from "fs/promises"
9
+ import { parse as parseJsonc } from "jsonc-parser"
10
+ import { join } from "node:path"
11
+
12
+ // ============================================================================
13
+ // Tipos de configuración
14
+ // ============================================================================
15
+
16
+ export interface RedactConfig {
17
+ mode: "strict" | "warn"
18
+ /** Fuentes regex propias (se suman a los bundles) */
19
+ patterns: string[]
20
+ /** Bundles de patrones por nombre */
21
+ bundles: string[]
22
+ /** Confianza mínima para activar un patrón: low | medium | high */
23
+ minConfidence: "low" | "medium" | "high"
24
+ /** Regex de cadenas que nunca se redactan */
25
+ allowlist: string[]
26
+ /** Prefijo del marcador */
27
+ prefix: string
28
+ /** Sufijo del marcador */
29
+ suffix: string
30
+ /** Material de clave: literal | env:VAR | file:/ruta | hex:... | base64:... */
31
+ key: string
32
+ /** Salidas que se restauran (solo la entrada de tool por ahora) */
33
+ restore: {
34
+ toolInput: boolean
35
+ }
36
+ }
37
+
38
+ export interface RuleCondition {
39
+ field: string
40
+ operator: "equals" | "contains" | "matches" | "gt" | "lt" | "in" | "notIn" | "exists" | "notExists"
41
+ value?: unknown
42
+ pattern?: string
43
+ }
44
+
45
+ export interface EventSubscription {
46
+ id: string
47
+ /** Sesión destino. Vacío/null/ausente → se vincula automáticamente a la
48
+ * sesión principal activa (la raíz creada al abrir opencode). */
49
+ sessionID?: string | null
50
+ agent?: string
51
+ filters: RuleCondition[]
52
+ promptTemplate?: string
53
+ /** Fichero de plantilla (relativo al proyecto o `~/home`); prioridad sobre promptTemplate */
54
+ promptTemplateFile?: string
55
+ /** "prompt" (user prompt) | "synthetic" (mensaje sintético) */
56
+ deliverAs?: "synthetic" | "prompt"
57
+ /** Solo synthetic: despierta el bucle del agente (default false) */
58
+ resume?: boolean
59
+ delivery: "queue" | "steer"
60
+ priority: number
61
+ enabled: boolean
62
+ readonly?: boolean
63
+ }
64
+
65
+ export interface EventsConfig {
66
+ /** El toggle del módulo vive SOLO en `modules.events`. */
67
+ routing: "first" | "all"
68
+ subscriptions: Omit<EventSubscription, "id" | "readonly">[]
69
+ /** Listener HTTP plano que expone el MISMO events.ingest para scripts sin credenciales. */
70
+ listener: IngestListenerConfig
71
+ }
72
+
73
+ export interface IngestListenerConfig {
74
+ /** Desactivado por defecto. */
75
+ enabled: boolean
76
+ /** Interfaz de escucha: 127.0.0.1 (loopback) | 0.0.0.0 | una IP LAN. */
77
+ host: string
78
+ /** Puerto de escucha. */
79
+ port: number
80
+ /** Token opcional; si se define, obligatorio en cada petición. */
81
+ token?: string
82
+ /**
83
+ * URL pública por DEFECTO (p. ej. un túnel fijo). Normalmente no hace falta:
84
+ * el agente fija la URL en runtime con la tool `apex_set_callback_url`
85
+ * (precedencia: runtime > esta config).
86
+ */
87
+ publicUrl?: string
88
+ }
89
+
90
+ export interface AdvisorConfig {
91
+ model?: string
92
+ actions: string[]
93
+ decisive: boolean
94
+ }
95
+
96
+ export interface ApexConfig {
97
+ redact: RedactConfig
98
+ events: EventsConfig
99
+ advisor: AdvisorConfig
100
+ guard: GuardConfigShape
101
+ browser: z.infer<typeof browserConfigSchema>
102
+ modules: Record<string, boolean>
103
+ }
104
+
105
+ // ============================================================================
106
+ // Esquema Zod (Standard Schema compatible)
107
+ // ============================================================================
108
+
109
+ const redactConfigSchema = z.object({
110
+ mode: z.enum(["strict", "warn"]).default("strict"),
111
+ patterns: z.array(z.string()).default(() => []),
112
+ bundles: z.array(z.string()).default(() => [...DEFAULT_BUNDLES]),
113
+ minConfidence: z.enum(["low", "medium", "high"]).default("medium"),
114
+ allowlist: z.array(z.string()).default(() => []),
115
+ prefix: z.string().default("[SECRET:"),
116
+ suffix: z.string().default("]"),
117
+ key: z.string().default(""),
118
+ restore: z
119
+ .object({
120
+ toolInput: z.boolean().default(true),
121
+ })
122
+ .default(() => ({ toolInput: true })),
123
+ })
124
+
125
+ const ruleConditionSchema = z.object({
126
+ field: z.string(),
127
+ operator: z.enum(["equals", "contains", "matches", "gt", "lt", "in", "notIn", "exists", "notExists"]),
128
+ value: z.unknown().optional(),
129
+ pattern: z.string().optional(),
130
+ })
131
+
132
+ const eventSubscriptionSchema = z.object({
133
+ // Vacío/null → auto-vinculación a la sesión principal activa.
134
+ sessionID: z.string().nullable().optional(),
135
+ agent: z.string().optional(),
136
+ filters: z.array(ruleConditionSchema).default([]),
137
+ promptTemplate: z.string().optional(),
138
+ promptTemplateFile: z.string().optional(),
139
+ deliverAs: z.enum(["synthetic", "prompt"]).default("prompt"),
140
+ resume: z.boolean().default(false),
141
+ delivery: z.enum(["queue", "steer"]).default("queue"),
142
+ priority: z.number().default(0),
143
+ enabled: z.boolean().default(true),
144
+ })
145
+
146
+ const ingestListenerSchema = z.object({
147
+ // Activo por defecto en loopback: el agente puede montar callbacks (incluido
148
+ // un túnel) sin tocar la config. Cámbialo a false para no abrir el puerto.
149
+ enabled: z.boolean().default(true),
150
+ host: z.string().default("127.0.0.1"),
151
+ port: z.number().int().positive().default(4599),
152
+ token: z.string().optional(),
153
+ publicUrl: z.string().optional(),
154
+ })
155
+
156
+ const eventsConfigSchema = z.object({
157
+ // El toggle del módulo vive SOLO en `modules.events` (evita duplicidad).
158
+ routing: z.enum(["first", "all"]).default("all"),
159
+ subscriptions: z.array(eventSubscriptionSchema).default([]),
160
+ listener: ingestListenerSchema.default(() => ({ enabled: true, host: "127.0.0.1", port: 4599 })),
161
+ })
162
+
163
+ const advisorConfigSchema = z.object({
164
+ model: z.string().optional(),
165
+ system: z.string().optional(),
166
+ promptTemplate: z.string().optional(),
167
+ promptTemplateFile: z.string().optional(),
168
+ actions: z.array(z.string()).default(() => []),
169
+ decisive: z.boolean().default(false),
170
+ evaluate: z.enum(["ask-only", "all"]).default("ask-only"),
171
+ timeoutMs: z.number().int().positive().default(10000),
172
+ location: z.string().optional(),
173
+ })
174
+
175
+ const guardRuleSchema = z.object({
176
+ action: z.string(),
177
+ resource: z.string().optional(),
178
+ effect: z.enum(["allow", "deny", "ask"]),
179
+ reason: z.string().optional(),
180
+ })
181
+
182
+ const guardConfigSchema = z.object({
183
+ // Arranca en "report": un guard que empieza denegando rompe la sesión antes
184
+ // de que nadie haya visto una regla en acción.
185
+ mode: z.enum(["enforce", "report"]).default("report"),
186
+ // "keep" = no tocar lo que decidió el host. Ver GuardFallback.
187
+ fallback: z.enum(["allow", "deny", "ask", "keep"]).default("keep"),
188
+ keep: z.number().int().positive().default(500),
189
+ agents: z.record(z.string(), z.array(guardRuleSchema)).default(() => ({})),
190
+ })
191
+
192
+ const browserConfigSchema = z.object({
193
+ // in-app: no hacemos attach, sirve la app Electron (y soltamos el que haya).
194
+ // external y auto: engancha el Chromium externo, pero solo cuando alguien lo
195
+ // pide (browser.target o /browser-target), nunca en cada tool call.
196
+ mode: z.enum(["in-app", "external", "auto"]).default("auto"),
197
+ // "auto" = deducir del DevToolsActivePort. Un path explícito lo fuerza.
198
+ cdpUrl: z.string().default("auto"),
199
+ profile: z.string().default(""),
200
+ connectTimeoutMs: z.number().int().positive().default(90000),
201
+ // Segundos entre reintentos al conectar. El modo toggle de Chrome exige
202
+ // aprobar un popup POR CONEXIÓN, así que no conviene reintentar rápido.
203
+ reconnectSeconds: z.number().int().nonnegative().default(15),
204
+ // Cabeceras y CA para un wss:// remoto detrás de un proxy inverso.
205
+ headers: z.record(z.string(), z.string()).default(() => ({})),
206
+ caFile: z.string().default(""),
207
+ insecureSkipVerify: z.boolean().default(false),
208
+ })
209
+
210
+ export const apexConfigSchema = z.object({
211
+ redact: redactConfigSchema.default(() => ({ mode: "strict" as const, patterns: [], bundles: [...DEFAULT_BUNDLES], minConfidence: "medium" as const, allowlist: [], prefix: "[SECRET:", suffix: "]", key: "", restore: { toolInput: true } })),
212
+ events: eventsConfigSchema.default(() => ({ routing: "all" as const, subscriptions: [], listener: { enabled: true, host: "127.0.0.1", port: 4599 } })),
213
+ advisor: advisorConfigSchema.default(() => ({ actions: [], decisive: false, evaluate: "ask-only" as const, timeoutMs: 10000 })),
214
+ guard: guardConfigSchema.default(() => ({
215
+ mode: "report" as const,
216
+ fallback: "keep" as const,
217
+ keep: 500,
218
+ agents: {},
219
+ })),
220
+ browser: browserConfigSchema.default(() => ({
221
+ mode: "auto" as const,
222
+ cdpUrl: "auto",
223
+ profile: "",
224
+ connectTimeoutMs: 90000,
225
+ reconnectSeconds: 15,
226
+ headers: {},
227
+ caFile: "",
228
+ insecureSkipVerify: false,
229
+ })),
230
+ modules: z
231
+ .object({
232
+ redact: z.boolean().optional(),
233
+ events: z.boolean().optional(),
234
+ advisor: z.boolean().optional(),
235
+ guard: z.boolean().optional(),
236
+ // Activado por defecto; en modo external puede abrir un popup de Chrome.
237
+ browser: z.boolean().optional(),
238
+ })
239
+ .default(() => ({})),
240
+ })
241
+
242
+ const ENV_VAR_REGEX = /\$\{([^}:]+)(?::-([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)/g
243
+
244
+ /** Sustituye ${VAR} / ${VAR:-default} / $VAR por su valor de entorno. */
245
+ function resolveValue(value: string): string {
246
+ return value.replace(ENV_VAR_REGEX, (_match, braceVar, defaultValue, simpleVar) => {
247
+ const varName = braceVar ?? simpleVar
248
+ const envValue = process.env[varName]
249
+
250
+ if (envValue !== undefined) return envValue
251
+ if (braceVar && defaultValue !== undefined) return defaultValue
252
+ if (braceVar) throw new Error(`Variable de entorno requerida no encontrada: ${varName}`)
253
+ return _match // $VAR sin valor y sin default -> mantener original
254
+ })
255
+ }
256
+
257
+ function resolveEnvInObject(obj: unknown): unknown {
258
+ if (typeof obj === "string") return resolveValue(obj)
259
+ if (Array.isArray(obj)) return obj.map(resolveEnvInObject)
260
+ if (obj && typeof obj === "object") {
261
+ const result: Record<string, unknown> = {}
262
+ for (const [key, value] of Object.entries(obj)) {
263
+ result[key] = resolveEnvInObject(value)
264
+ }
265
+ return result
266
+ }
267
+ return obj
268
+ }
269
+
270
+ export function resolveEnvVariables(config: ApexConfig): ApexConfig {
271
+ return resolveEnvInObject(config) as ApexConfig
272
+ }
273
+
274
+ // ============================================================================
275
+ // Carga y validación de configuración
276
+ // ============================================================================
277
+
278
+ // ============================================================================
279
+ // Parseo: comentarios #, // y /* */
280
+ // ============================================================================
281
+
282
+ /**
283
+ * Elimina comentarios de línea con `#` respetando las cadenas Y los otros
284
+ * comentarios: un `#` dentro de una cadena o de un bloque `/* ... *​/` NO es
285
+ * un comentario (rompería el parseo sí se cortara ahí).
286
+ * `//` y `/* *​/` los cubre jsonc-parser.
287
+ */
288
+ export function stripHashComments(text: string): string {
289
+ let out = ""
290
+ let inString = false
291
+ let inLineComment = false
292
+ let inBlockComment = false
293
+ let quote = ""
294
+ let escaped = false
295
+
296
+ for (let i = 0; i < text.length; i++) {
297
+ const ch = text[i]!
298
+ const next = i + 1 < text.length ? text[i + 1] : ""
299
+
300
+ if (inString) {
301
+ out += ch
302
+ if (escaped) { escaped = false; continue }
303
+ if (ch === "\\") { escaped = true; continue }
304
+ if (ch === quote) inString = false
305
+ continue
306
+ }
307
+
308
+ if (inLineComment) {
309
+ if (ch === "\n") { inLineComment = false; out += ch }
310
+ continue
311
+ }
312
+
313
+ if (inBlockComment) {
314
+ out += ch
315
+ if (ch === "*" && next === "/") { inBlockComment = false; i++; out += "/" }
316
+ continue
317
+ }
318
+
319
+ if (ch === '"' || ch === "'") { inString = true; quote = ch; out += ch; continue }
320
+ if (ch === "/" && next === "/") { inLineComment = true; i++; out += "//"; continue }
321
+ if (ch === "/" && next === "*") { inBlockComment = true; i++; out += "/*"; continue }
322
+ if (ch === "#") {
323
+ while (i < text.length && text[i] !== "\n") i++
324
+ out += "\n"
325
+ continue
326
+ }
327
+ out += ch
328
+ }
329
+ return out
330
+ }
331
+
332
+ /** Parsea un texto de configuración (JSONC + comentarios `#`). */
333
+ export function parseConfigText(text: string, path: string): Record<string, unknown> {
334
+ const parsed = parseJsonc(stripHashComments(text), [], { disallowComments: false, allowTrailingComma: true })
335
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
336
+ throw new Error(`Configuración inválida en ${path}: se esperaba un objeto`)
337
+ }
338
+ return parsed as Record<string, unknown>
339
+ }
340
+
341
+ // ============================================================================
342
+ // Merge profundo y jerarquía de fuentes
343
+ // ============================================================================
344
+
345
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
346
+ return typeof value === "object" && value !== null && !Array.isArray(value)
347
+ }
348
+
349
+ /**
350
+ * Merge profundo: los objetos se combinan, los arrays se SUSTITUYEN y
351
+ * `undefined` no pisa. (Los arrays se reemplazan para que una lista de
352
+ * bundles/patrones se pueda sobrescribir por completo desde la config local.)
353
+ */
354
+ export function deepMerge<T>(base: T, override: unknown): T {
355
+ if (override === undefined) return base
356
+ if (isPlainObject(base) && isPlainObject(override)) {
357
+ const out: Record<string, unknown> = { ...base }
358
+ for (const [key, value] of Object.entries(override)) {
359
+ out[key] = key in out ? deepMerge(out[key], value) : value
360
+ }
361
+ return out as T
362
+ }
363
+ return override as T
364
+ }
365
+
366
+ /** Rutas de los ficheros de configuración de apex. */
367
+ export function apexConfigPaths(input: {
368
+ projectDir: string
369
+ home: string
370
+ configDir?: string
371
+ }): { global: string; local: string } {
372
+ const base = input.configDir ?? process.env.XDG_CONFIG_HOME ?? join(input.home, ".config")
373
+ return {
374
+ // Global: junto a la config global de opencode.
375
+ global: join(base, "opencode", "opencode-apex.jsonc"),
376
+ // Local: dentro de .opencode/ del proyecto (convención de opencode).
377
+ local: join(input.projectDir, ".opencode", "opencode-apex.jsonc"),
378
+ }
379
+ }
380
+
381
+ /** Lee una fuente de configuración. Ausente → {}. Sintaxis inválida → throw. */
382
+ async function loadConfigSource(path: string): Promise<Record<string, unknown>> {
383
+ let content: string
384
+ try {
385
+ content = await readFile(path, "utf-8")
386
+ } catch (error) {
387
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return {}
388
+ throw error
389
+ }
390
+ return parseConfigText(content, path)
391
+ }
392
+
393
+ export interface ApexConfigLoadResult {
394
+ readonly config: ApexConfig
395
+ readonly sources: { readonly inline: boolean; readonly global: boolean; readonly local: boolean }
396
+ readonly paths: { readonly global: string; readonly local: string }
397
+ }
398
+
399
+ /**
400
+ * Carga la configuración con JERARQUÍA y dos canales.
401
+ *
402
+ * Precedencia (menor → mayor):
403
+ * 1. Fichero GLOBAL → <config>/opencode/opencode-apex.jsonc
404
+ * 2. Opciones inline en la definición del plugin (opencode.json) → ctx.options
405
+ * (el host ya mergea su config global y local, ganando la local)
406
+ * 3. Fichero LOCAL → <proyecto>/.opencode/opencode-apex.jsonc
407
+ *
408
+ * Es decir: el ámbito manda (local > global) y, dentro de cada ámbito, el
409
+ * fichero gana a las opciones inline. El inline ocupa el nivel "local" porque
410
+ * el host entrega ya mergeadas las opciones inline global+local.
411
+ */
412
+ export async function loadApexConfig(input: {
413
+ projectDir: string
414
+ home: string
415
+ options?: Record<string, unknown>
416
+ configDir?: string
417
+ }): Promise<ApexConfigLoadResult> {
418
+ const paths = apexConfigPaths(input)
419
+ const inline = input.options ?? {}
420
+
421
+ const readSource = async (path: string, label: string): Promise<Record<string, unknown>> => {
422
+ try {
423
+ return await loadConfigSource(path)
424
+ } catch (error) {
425
+ console.warn(`[apex] config ${label} inválida (${path}): ${String(error)} — se ignora`)
426
+ return {}
427
+ }
428
+ }
429
+
430
+ const globalRaw = await readSource(paths.global, "global")
431
+ const localRaw = await readSource(paths.local, "local")
432
+
433
+ // global-file < inline < local-file
434
+ const merged = deepMerge(deepMerge(deepMerge({}, globalRaw), inline), localRaw)
435
+
436
+ // Aviso de claves obsoletas: el toggle es `modules.<nombre>`.
437
+ const legacy = (merged as Record<string, unknown>).events
438
+ const legacyEnabled = (legacy as Record<string, unknown> | undefined)?.enabled
439
+ if (legacyEnabled !== undefined) {
440
+ console.warn(
441
+ `[apex] "events.enabled" está obsoleto y se ignora; usa "modules.events" (valor indicado: ${String(legacyEnabled)})`,
442
+ )
443
+ }
444
+
445
+ const result = apexConfigSchema.safeParse(merged)
446
+ if (!result.success) {
447
+ const issues = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")
448
+ throw new Error(`Configuración inválida (merge inline+global+local): ${issues}`)
449
+ }
450
+
451
+ return {
452
+ config: resolveEnvVariables(result.data),
453
+ sources: {
454
+ inline: Object.keys(inline).length > 0,
455
+ global: Object.keys(globalRaw).length > 0,
456
+ local: Object.keys(localRaw).length > 0,
457
+ },
458
+ paths,
459
+ }
460
+ }
461
+
462
+ /** Carga un único fichero (compatibilidad y tests). Ausente → defaults. */
463
+ export async function loadConfig(path: string): Promise<ApexConfig> {
464
+ const raw = await loadConfigSource(path)
465
+ const result = apexConfigSchema.safeParse(raw)
466
+ if (!result.success) {
467
+ const issues = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")
468
+ throw new Error(`Configuración inválida en ${path}: ${issues}`)
469
+ }
470
+ return resolveEnvVariables(result.data)
471
+ }
472
+
473
+ // ============================================================================
474
+ // Gestor de configuración con patrón last-good
475
+ // ============================================================================
476
+
477
+ class ApexConfigManager {
478
+ private currentConfig: ApexConfig | null = null
479
+ private lastGoodConfig: ApexConfig | null = null
480
+
481
+ get config(): ApexConfig | null {
482
+ return this.currentConfig
483
+ }
484
+
485
+ get lastGood(): ApexConfig | null {
486
+ return this.lastGoodConfig
487
+ }
488
+
489
+ async load(path: string): Promise<ApexConfig> {
490
+ const config = await loadConfig(path)
491
+ this.currentConfig = config
492
+ this.lastGoodConfig = config
493
+ return config
494
+ }
495
+
496
+ apply(config: ApexConfig): void {
497
+ this.currentConfig = config
498
+ this.lastGoodConfig = config
499
+ // Los flags de módulos se aplican en el plugin principal (index.ts)
500
+ // Aquí solo actualizamos el estado interno
501
+ }
502
+
503
+ dispose(): void {
504
+ this.currentConfig = null
505
+ this.lastGoodConfig = null
506
+ }
507
+
508
+ }
509
+
510
+ // Singleton exportado
511
+ export const configManager = new ApexConfigManager()
512
+
513
+ // ============================================================================
514
+ // Helpers de conveniencia
515
+ // ============================================================================
516
+
517
+ export function getConfig(): ApexConfig | null {
518
+ return configManager.config
519
+ }
520
+
521
+ export function getLastGoodConfig(): ApexConfig | null {
522
+ return configManager.lastGood
523
+ }
524
+
525
+ export async function loadAndApplyConfig(path: string): Promise<ApexConfig> {
526
+ const config = await configManager.load(path)
527
+ configManager.apply(config)
528
+ return config
529
+ }
530
+
531
+ export function disposeConfig(): void {
532
+ configManager.dispose()
533
+ }