opencode-apex 0.5.1 → 0.8.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/cred.ts ADDED
@@ -0,0 +1,979 @@
1
+ /**
2
+ * Apex Cred — comando `/cred` + herramienta `apex_cred` para el agente.
3
+ *
4
+ * Almacén local de credenciales:
5
+ * - Declaración explícita: `/cred set ...` (sin modelo, siempre disponible).
6
+ * - Aprendizaje opcional: `/cred learn ...` con modelo local (off por defecto).
7
+ * - Backing KDBX opcional: interoperable con KeePassXC/KeePass/apps externas.
8
+ * - Redacción: todo valor secreto se inyecta en el motor de redact vía
9
+ * `core/cred.ts#getActiveCredStore().patterns()`.
10
+ * - Acceso del agente sin conocer el secreto: herramienta `apex_cred` que
11
+ * abre canales temporales (handles) y spawnea herramientas efímeras.
12
+ *
13
+ * Seguridad:
14
+ * - `list/get/describe` nunca devuelven valores secretos.
15
+ * - Las herramientas de canal usan el secreto internamente; la salida se
16
+ * redacta antes de devolverla al agente.
17
+ * - El TUI no enmascara `/cred set nombre=valor`; usar `--from-env` o
18
+ * `--from-file` para no dejar el secreto en historial.
19
+ */
20
+
21
+ import { Effect } from "effect"
22
+ import type { Scope } from "effect"
23
+ import type { Plugin } from "@opencode/plugin/effect"
24
+ import { randomBytes } from "node:crypto"
25
+ import { readFileSync, watch as fsWatch, type FSWatcher } from "node:fs"
26
+ import { homedir } from "node:os"
27
+ import { basename, dirname } from "node:path"
28
+ import { resolveKey } from "./core/crypto.js"
29
+ import {
30
+ createCredStore,
31
+ getActiveCredStore,
32
+ publicEntry,
33
+ secretValuesOf,
34
+ setActiveCredStore,
35
+ type CredEntry,
36
+ type CredStore,
37
+ } from "./core/cred.js"
38
+ import { openKdbxStore, parseCredentialUri, inferKind, type KdbxStore } from "./core/kdbx.js"
39
+ import { channelKind, channelUsage, isSupportedChannel, runChannelAction } from "./core/cred-channel.js"
40
+ import type { CredConfig } from "./core/config.js"
41
+
42
+ export type { CredConfig }
43
+
44
+ const STORAGE_KEY = "apex:cred"
45
+
46
+ export function createDefaultCredConfig(): CredConfig & { enabled: boolean } {
47
+ return {
48
+ enabled: true,
49
+ minLength: 6,
50
+ llm: {
51
+ enabled: false,
52
+ endpoint: "http://127.0.0.1:11434/v1",
53
+ model: "qwen2.5:3b",
54
+ timeoutMs: 4000,
55
+ allowRemote: false,
56
+ },
57
+ kdbx: {
58
+ enabled: false,
59
+ path: "~/.config/opencode/apex-creds.kdbx",
60
+ password: "env:APEX_CRED_KDBX_PASSWORD",
61
+ keyFile: "",
62
+ createIfMissing: true,
63
+ watch: true,
64
+ group: "apex",
65
+ },
66
+ }
67
+ }
68
+
69
+ // ---------------------------------------------------------------------------
70
+ // Helpers
71
+ // ---------------------------------------------------------------------------
72
+
73
+ function expandHome(p: string): string {
74
+ return p === "~" || p.startsWith("~/") ? p.replace(/^~/, homedir()) : p
75
+ }
76
+
77
+ function resolveSecretSpec(spec: string | undefined): string | undefined {
78
+ const raw = (spec ?? "").trim()
79
+ if (!raw) return undefined
80
+ if (raw.startsWith("env:")) {
81
+ const name = raw.slice(4).trim()
82
+ return process.env[name]
83
+ }
84
+ if (raw.startsWith("file:")) {
85
+ const p = expandHome(raw.slice(5).trim())
86
+ try {
87
+ return readFileSync(p, "utf8").trim()
88
+ } catch {
89
+ return undefined
90
+ }
91
+ }
92
+ return raw
93
+ }
94
+
95
+ /**
96
+ * Redacción defensiva de la salida de un canal: cualquier secreto del almacén
97
+ * (y las cadenas derivadas que se inyectaron, p. ej. el base64 de Basic) se
98
+ * sustituye antes de devolver nada al agente. El hook `context` de redact lo
99
+ * volvería a cazar, pero esta salida también va al log de la sesión.
100
+ */
101
+ export function scrubSecrets(value: unknown, store: CredStore, extra: readonly string[] = []): unknown {
102
+ const needles: Array<[string, string]> = []
103
+ for (const entry of store.entries()) {
104
+ for (const secret of secretValuesOf(entry)) {
105
+ if (secret.length >= 4) needles.push([secret, `[REDACTED:${entry.name}]`])
106
+ }
107
+ }
108
+ for (const s of extra) if (s && s.length >= 4) needles.push([s, "[REDACTED]"])
109
+ needles.sort((a, b) => b[0].length - a[0].length)
110
+ const scrub = (text: string): string => {
111
+ let out = text
112
+ for (const [needle, label] of needles) if (out.includes(needle)) out = out.split(needle).join(label)
113
+ return out
114
+ }
115
+ const walk = (v: unknown): unknown => {
116
+ if (typeof v === "string") return scrub(v)
117
+ if (Array.isArray(v)) return v.map(walk)
118
+ if (v && typeof v === "object") {
119
+ return Object.fromEntries(Object.entries(v as Record<string, unknown>).map(([k, x]) => [scrub(k), walk(x)]))
120
+ }
121
+ return v
122
+ }
123
+ return walk(value)
124
+ }
125
+
126
+ /**
127
+ * Marca de metadata para las respuestas de `/cred`: son para el USUARIO, nunca
128
+ * para el modelo. Un mensaje synthetic sí entraría al contexto; el hook
129
+ * `context`/`compaction`/`generate` de este módulo quita los que llevan la
130
+ * marca antes de cada petición (la metadata del mensaje guardado llega al hook
131
+ * y no se envía al modelo). Así el manual, los listados y los avisos se ven en
132
+ * la sesión pero no gastan contexto ni pueden filtrar nada al modelo.
133
+ */
134
+ export const UI_ONLY_KEY = "apexUiOnly"
135
+
136
+ function notify(ctx: Plugin.Context, sessionID: string, text: string): Effect.Effect<void> {
137
+ return ctx.session
138
+ .synthetic({
139
+ sessionID,
140
+ text,
141
+ description: "apex cred",
142
+ metadata: { [UI_ONLY_KEY]: true },
143
+ // steer + resume:false: queda en la bandeja (la app la muestra) y se
144
+ // entrega a la transcripción junto a la próxima llamada real al modelo,
145
+ // sin arrancar un turno propio. "queue" la entregaría como un input aparte
146
+ // al acabar el turno, lo que lanza una llamada al modelo para nada.
147
+ delivery: "steer",
148
+ resume: false,
149
+ } as never)
150
+ .pipe(Effect.asVoid, Effect.catch(() => Effect.void))
151
+ }
152
+
153
+ /** Quita del array de mensajes de una petición los marcados como solo-UI. */
154
+ export function dropUiOnlyMessages<T extends { readonly metadata?: Record<string, unknown> }>(messages: readonly T[]): T[] {
155
+ return messages.filter((m) => m?.metadata?.[UI_ONLY_KEY] !== true)
156
+ }
157
+
158
+ /** Manual de `/cred`, solo para el usuario (va con la marca UI-only). */
159
+ export const CRED_HELP = `apex cred — almacén local de credenciales
160
+
161
+ Qué hace
162
+ Guarda credenciales en tu máquina y las redacta del contexto del modelo: si
163
+ el valor aparece en un mensaje o en la salida de una herramienta, el modelo
164
+ ve [SECRET:…] en su lugar. El agente puede USAR una credencial (herramienta
165
+ apex_cred) sin llegar a ver el valor. Este manual no entra al contexto.
166
+
167
+ Guardar
168
+ /cred set NOMBRE=VALOR valor literal (queda en el historial del terminal)
169
+ /cred set NOMBRE --from-env VAR lee la variable de entorno del servidor
170
+ /cred set NOMBRE --from-file RUTA lee el fichero (sin salto final)
171
+ /cred set NOMBRE ssh://user:pass@host:22
172
+ URI: extrae usuario, contraseña, host y tipo
173
+ Opciones de set:
174
+ --url URL --username U --password P --notes TEXTO
175
+ --kind ssh|http-bearer|http-basic|api-key|database|generic
176
+ --secret.CAMPO VALOR campo secreto extra (se redacta)
177
+ --field.CAMPO VALOR campo público (no se redacta)
178
+ Secretos de menos de 6 caracteres se rechazan (redactarían texto normal).
179
+
180
+ Consultar y borrar (nunca muestran valores)
181
+ /cred list nombres, tipo, host y usuario
182
+ /cred get NOMBRE metadatos públicos de una entrada
183
+ /cred rm NOMBRE la borra (también del .kdbx si está activo)
184
+
185
+ KeePassXC / KeePass (.kdbx)
186
+ Con cred.kdbx.enabled=true el fichero .kdbx es la fuente de verdad: lo puedes
187
+ abrir y editar con KeePassXC y apex recarga solo.
188
+ /cred kdbx status ruta y nº de entradas
189
+ /cred kdbx reload recarga a mano
190
+ /cred kdbx save fuerza el guardado
191
+
192
+ Con modelo local (opcional, cred.llm.enabled=true)
193
+ /cred learn FRASE LIBRE "la contraseña de X es Y": propone nombre y valor
194
+ /cred confirm | /cred discard guarda o descarta la propuesta
195
+
196
+ Para el agente
197
+ El agente usa apex_cred: list/get (metadatos), open (canal a la URL de la
198
+ credencial: ssh exec o http request), use, close. El destino lo fija la
199
+ credencial; el agente no puede mandar el secreto a otro host.
200
+
201
+ Consejos
202
+ - Usa --from-env o --from-file para que el valor no quede en el historial.
203
+ - Para canales, guarda la URL: ssh://host:puerto o https://api.dominio.
204
+ - Más detalle: docs/CRED.md del plugin.`
205
+
206
+ function parseFlags(rest: string): { positional: string[]; flags: Record<string, string | boolean> } {
207
+ const tokens = rest.match(/(?:"[^"]*"|'[^']*'|\S+)/g) ?? []
208
+ const positional: string[] = []
209
+ const flags: Record<string, string | boolean> = {}
210
+ for (let i = 0; i < tokens.length; i++) {
211
+ const t = tokens[i]!
212
+ if (t.startsWith("--")) {
213
+ const key = t.slice(2)
214
+ const eq = key.indexOf("=")
215
+ if (eq >= 0) {
216
+ flags[key.slice(0, eq)] = key.slice(eq + 1).replace(/^['"]|['"]$/g, "")
217
+ continue
218
+ }
219
+ const next = tokens[i + 1]
220
+ if (next && !next.startsWith("--")) {
221
+ flags[key] = next.replace(/^['"]|['"]$/g, "")
222
+ i++
223
+ } else {
224
+ flags[key] = true
225
+ }
226
+ } else {
227
+ positional.push(t.replace(/^['"]|['"]$/g, ""))
228
+ }
229
+ }
230
+ return { positional, flags }
231
+ }
232
+
233
+ function parseSetArgs(rest: string):
234
+ | { name: string; value?: string; fromEnv?: string; fromFile?: string; uri?: string; fields: Record<string, string>; secretFields: Record<string, string>; flags: Record<string, string | boolean> }
235
+ | null {
236
+ const { positional, flags } = parseFlags(rest)
237
+ const first = positional[0]
238
+ if (!first) return null
239
+
240
+ let name = first
241
+ let value: string | undefined
242
+ const eq = first.indexOf("=")
243
+ if (eq > 0) {
244
+ name = first.slice(0, eq)
245
+ value = first.slice(eq + 1)
246
+ if (positional.length > 1 && !value) value = positional.slice(1).join(" ")
247
+ } else if (positional.length > 1 && !String(flags["from-env"] ?? flags["from-file"] ?? "")) {
248
+ // /cred set name <value-or-uri>
249
+ value = positional.slice(1).join(" ")
250
+ }
251
+
252
+ const fields: Record<string, string> = {}
253
+ const secretFields: Record<string, string> = {}
254
+ for (const [k, v] of Object.entries(flags)) {
255
+ if (k.startsWith("field.")) fields[k.slice(6)] = String(v)
256
+ if (k.startsWith("secret.") || k.startsWith("secret-field.")) {
257
+ const key = k.startsWith("secret-field.") ? k.slice(13) : k.slice(7)
258
+ secretFields[key] = String(v)
259
+ }
260
+ }
261
+
262
+ return {
263
+ name,
264
+ value,
265
+ fromEnv: typeof flags["from-env"] === "string" ? flags["from-env"] : undefined,
266
+ fromFile: typeof flags["from-file"] === "string" ? flags["from-file"] : undefined,
267
+ uri: typeof flags["uri"] === "string" ? flags["uri"] : typeof flags["url-cred"] === "string" ? flags["url-cred"] : undefined,
268
+ fields,
269
+ secretFields,
270
+ flags,
271
+ }
272
+ }
273
+
274
+ function looksLikeUri(value: string): boolean {
275
+ return /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/.+/.test(value)
276
+ }
277
+
278
+ function entryFromSet(
279
+ name: string,
280
+ value: string | undefined,
281
+ opts: {
282
+ uri?: string
283
+ username?: string
284
+ password?: string
285
+ url?: string
286
+ kind?: string
287
+ notes?: string
288
+ fields: Record<string, string>
289
+ secretFields: Record<string, string>
290
+ },
291
+ ): CredEntry {
292
+ let base: Partial<CredEntry> = {}
293
+ const uri = opts.uri ?? (value && looksLikeUri(value) ? value : undefined)
294
+ if (uri) base = parseCredentialUri(uri)
295
+
296
+ const password = opts.password ?? (uri ? base.password : value)
297
+ const username = opts.username ?? base.username
298
+ const url = opts.url ?? base.url ?? (uri && !looksLikeUri(uri) ? undefined : uri)
299
+ const kind = opts.kind ?? base.kind ?? inferKind({ url, password, username, fields: opts.fields, protectedFields: Object.keys(opts.secretFields) })
300
+
301
+ const fields: Record<string, string> = { ...(opts.fields ?? {}) }
302
+ const protectedFields = new Set<string>(Object.keys(opts.secretFields ?? {}))
303
+ for (const [k, v] of Object.entries(opts.secretFields ?? {})) fields[k] = v
304
+
305
+ return {
306
+ name,
307
+ value: password,
308
+ password,
309
+ username,
310
+ url,
311
+ notes: opts.notes,
312
+ kind,
313
+ fields,
314
+ protectedFields: [...protectedFields],
315
+ }
316
+ }
317
+
318
+ // ---------------------------------------------------------------------------
319
+ // LLM learn (opcional)
320
+ // ---------------------------------------------------------------------------
321
+
322
+ async function learnWithLocalModel(
323
+ config: CredConfig["llm"],
324
+ freeText: string,
325
+ ): Promise<{ name: string; value: string } | null> {
326
+ if (!config.enabled) return null
327
+ const isLocal = /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])/.test(config.endpoint)
328
+ if (!isLocal && !config.allowRemote) {
329
+ console.warn(`[apex.cred] endpoint "${config.endpoint}" no local y allowRemote=false: se ignora /cred learn`)
330
+ return null
331
+ }
332
+
333
+ const controller = new AbortController()
334
+ const timeout = setTimeout(() => controller.abort(), config.timeoutMs)
335
+ try {
336
+ const response = await fetch(`${config.endpoint.replace(/\/$/, "")}/chat/completions`, {
337
+ method: "POST",
338
+ headers: { "content-type": "application/json" },
339
+ signal: controller.signal,
340
+ body: JSON.stringify({
341
+ model: config.model,
342
+ temperature: 0,
343
+ messages: [
344
+ {
345
+ role: "system",
346
+ content:
347
+ "Extrae de la frase del usuario un nombre corto (sin espacios) y el valor literal de una " +
348
+ "credencial. Responde SOLO JSON: {\"name\":\"...\",\"value\":\"...\"}. Si no hay ninguna " +
349
+ "credencial clara, responde {\"name\":null,\"value\":null}.",
350
+ },
351
+ { role: "user", content: freeText },
352
+ ],
353
+ }),
354
+ })
355
+ if (!response.ok) return null
356
+ const data = (await response.json()) as { choices?: Array<{ message?: { content?: string } }> }
357
+ const content = data.choices?.[0]?.message?.content
358
+ if (!content) return null
359
+ const parsed = JSON.parse(content) as { name?: string | null; value?: string | null }
360
+ if (!parsed.name || !parsed.value) return null
361
+ return { name: parsed.name, value: parsed.value }
362
+ } catch {
363
+ return null
364
+ } finally {
365
+ clearTimeout(timeout)
366
+ }
367
+ }
368
+
369
+ // ---------------------------------------------------------------------------
370
+ // KDBX backing
371
+ // ---------------------------------------------------------------------------
372
+
373
+ async function openKdbxFromConfig(config: CredConfig["kdbx"]): Promise<KdbxStore | null> {
374
+ if (!config.enabled) return null
375
+ const path = expandHome(config.path)
376
+ const password = resolveSecretSpec(config.password)
377
+ const keyFile = config.keyFile ? expandHome(config.keyFile) : undefined
378
+ if (!password && !keyFile) {
379
+ console.warn("[apex.cred] KDBX habilitado pero sin password/keyFile resolubles; se usa almacén en memoria")
380
+ return null
381
+ }
382
+ try {
383
+ const store = await openKdbxStore({
384
+ path,
385
+ password,
386
+ keyFile,
387
+ createIfMissing: config.createIfMissing,
388
+ dbName: "apex-creds",
389
+ group: config.group,
390
+ })
391
+ console.info(`[apex.cred] KDBX cargado: ${path} (${store.entries().length} entradas)`)
392
+ return store
393
+ } catch (error) {
394
+ console.warn(`[apex.cred] No se pudo abrir KDBX ${path}: ${String(error)}`)
395
+ return null
396
+ }
397
+ }
398
+
399
+ function credEntryFromKdbx(rec: ReturnType<KdbxStore["entries"]>[number]): CredEntry {
400
+ return {
401
+ name: rec.name,
402
+ value: rec.password || undefined,
403
+ username: rec.username || undefined,
404
+ password: rec.password || undefined,
405
+ url: rec.url || undefined,
406
+ notes: rec.notes || undefined,
407
+ kind: rec.kind || inferKind(rec),
408
+ fields: { ...(rec.fields ?? {}) },
409
+ protectedFields: [...(rec.protectedFields ?? [])],
410
+ }
411
+ }
412
+
413
+ /**
414
+ * Vuelca el KDBX al índice en memoria. Todo secreto del fichero tiene que
415
+ * acabar en el índice (es lo que se redacta), así que dos entradas con el mismo
416
+ * título, o sin título, NO se pisan: reciben un nombre único.
417
+ */
418
+ export function syncKdbxToStore(kdbx: KdbxStore, store: CredStore): void {
419
+ for (const name of store.list()) store.remove(name)
420
+ const used = new Set<string>()
421
+ for (const rec of kdbx.entries()) {
422
+ const entry = credEntryFromKdbx(rec)
423
+ if (secretValuesOf(entry).length === 0) continue
424
+ const base = entry.name.trim() || `entry-${(rec.uuid ?? "").replace(/[^A-Za-z0-9]/g, "").slice(0, 8) || "untitled"}`
425
+ let name = base
426
+ for (let n = 2; used.has(name); n++) name = `${base}#${n}`
427
+ used.add(name)
428
+ try {
429
+ store.setEntry({ ...entry, name })
430
+ } catch {
431
+ // todos sus secretos son más cortos que minLength: no se indexa
432
+ }
433
+ }
434
+ }
435
+
436
+ async function persistEntryToKdbx(kdbx: KdbxStore, entry: CredEntry): Promise<void> {
437
+ kdbx.set({
438
+ name: entry.name,
439
+ username: entry.username ?? "",
440
+ password: entry.password ?? entry.value ?? "",
441
+ url: entry.url ?? "",
442
+ notes: entry.notes ?? "",
443
+ fields: { ...(entry.fields ?? {}) },
444
+ protectedFields: [...(entry.protectedFields ?? [])],
445
+ kind: entry.kind ?? inferKind(entry),
446
+ })
447
+ await kdbx.save()
448
+ }
449
+
450
+ async function removeEntryFromKdbx(kdbx: KdbxStore, name: string): Promise<boolean> {
451
+ const removed = kdbx.remove(name)
452
+ if (removed) await kdbx.save()
453
+ return removed
454
+ }
455
+
456
+ // ---------------------------------------------------------------------------
457
+ // Handles/canales temporales para el agente (sin exponer secretos)
458
+ // ---------------------------------------------------------------------------
459
+
460
+ interface CredHandle {
461
+ id: string
462
+ credentialName: string
463
+ kind: string
464
+ createdAt: number
465
+ lastUsedAt: number
466
+ uses: number
467
+ }
468
+
469
+ const MAX_HANDLES = 16
470
+ const HANDLE_TOOL_PREFIX = "apex_cred_use_"
471
+
472
+ function makeHandleId(): string {
473
+ return randomBytes(4).toString("hex")
474
+ }
475
+
476
+ function safeUrlForMeta(url: string | undefined): string | undefined {
477
+ if (!url) return undefined
478
+ try {
479
+ const u = new URL(url)
480
+ return `${u.protocol}//${u.host}${u.pathname}`
481
+ } catch {
482
+ return url.replace(/:\/\/[^@/\s]*@/, "://***@")
483
+ }
484
+ }
485
+
486
+ // ---------------------------------------------------------------------------
487
+ // Registro
488
+ // ---------------------------------------------------------------------------
489
+
490
+ export function register(
491
+ ctx: Plugin.Context,
492
+ config: CredConfig & { enabled?: boolean },
493
+ ): Effect.Effect<void, never, Scope.Scope> {
494
+ return Effect.gen(function* () {
495
+ if (!config.enabled) return
496
+
497
+ const key = resolveKey("").key
498
+ const store: CredStore = createCredStore({ key, minLength: config.minLength })
499
+ let kdbx: KdbxStore | null = null
500
+ let watcher: FSWatcher | null = null
501
+
502
+ // Cargar backing store
503
+ if (config.kdbx?.enabled) {
504
+ kdbx = yield* Effect.promise(() => openKdbxFromConfig(config.kdbx))
505
+ if (kdbx) {
506
+ syncKdbxToStore(kdbx, store)
507
+ // Migración suave: si KDBX está vacío y hay secretos en ctx.storage, importarlos.
508
+ if (kdbx.entries().length === 0) {
509
+ const persisted = yield* ctx.storage.get(STORAGE_KEY)
510
+ if (persisted && typeof persisted === "object") {
511
+ const legacy = createCredStore({ key, minLength: config.minLength })
512
+ legacy.load(persisted as Record<string, string>)
513
+ const toMigrate = legacy.entries()
514
+ if (toMigrate.length > 0) {
515
+ for (const entry of toMigrate) {
516
+ try {
517
+ store.setEntry(entry)
518
+ yield* Effect.promise(() => persistEntryToKdbx(kdbx!, entry)).pipe(Effect.catch(() => Effect.void))
519
+ } catch {}
520
+ }
521
+ console.info(`[apex.cred] migradas ${toMigrate.length} credencial(es) de ctx.storage a KDBX`)
522
+ }
523
+ }
524
+ }
525
+ if (config.kdbx.watch) {
526
+ const kdbxPath = expandHome(config.kdbx.path)
527
+ try {
528
+ let timer: ReturnType<typeof setTimeout> | null = null
529
+ const file = basename(kdbxPath)
530
+ // Se vigila el DIRECTORIO: KeePassXC (y apex) guardan escribiendo un
531
+ // temporal y renombrando, y un watcher sobre el fichero se queda
532
+ // mirando el inodo viejo tras el primer guardado.
533
+ watcher = fsWatch(dirname(kdbxPath), (_event, changed) => {
534
+ if (changed && String(changed) !== file) return
535
+ if (timer) clearTimeout(timer)
536
+ timer = setTimeout(() => {
537
+ void (async () => {
538
+ try {
539
+ if (!kdbx) return
540
+ await kdbx.reload()
541
+ if (kdbx) syncKdbxToStore(kdbx, store)
542
+ } catch (error) {
543
+ // Guardado a medias o contraseña cambiada: se conserva el último índice válido.
544
+ console.warn(`[apex.cred] KDBX reload failed, keeping the last good index: ${String(error)}`)
545
+ }
546
+ })()
547
+ }, 400)
548
+ })
549
+ watcher.on("error", (error) => console.warn(`[apex.cred] KDBX watcher error: ${String(error)}`))
550
+ } catch (error) {
551
+ console.warn(`[apex.cred] no se pudo vigilar KDBX: ${String(error)}`)
552
+ }
553
+ }
554
+ }
555
+ }
556
+
557
+ // Fallback: ctx.storage cuando no hay KDBX
558
+ if (!kdbx) {
559
+ const persisted = yield* ctx.storage.get(STORAGE_KEY)
560
+ if (persisted && typeof persisted === "object") {
561
+ store.load(persisted as Record<string, string>)
562
+ }
563
+ }
564
+
565
+ setActiveCredStore(store)
566
+ yield* Effect.addFinalizer(() =>
567
+ Effect.sync(() => {
568
+ if (watcher) try { watcher.close() } catch {}
569
+ watcher = null
570
+ if (getActiveCredStore() === store) setActiveCredStore(null)
571
+ kdbx?.close()
572
+ kdbx = null
573
+ }),
574
+ )
575
+
576
+ const persist = (): Effect.Effect<void> =>
577
+ kdbx
578
+ ? Effect.void // KDBX se guarda por operación
579
+ : ctx.storage.set(STORAGE_KEY, store.serialize())
580
+
581
+ const pending = new Map<string, { name: string; value: string }>()
582
+ const handles = new Map<string, CredHandle>()
583
+
584
+ // Respuestas de /cred (manual, listados, avisos): visibles en la sesión,
585
+ // fuera de toda petición al modelo — también de la compactación, para que
586
+ // el resumen no las arrastre al contexto.
587
+ for (const hookName of ["context", "compaction", "generate"] as const) {
588
+ yield* ctx.session.hook(hookName, (event) =>
589
+ Effect.suspend(() => {
590
+ const e = event as unknown as { messages?: Array<{ metadata?: Record<string, unknown> }> }
591
+ if (!Array.isArray(e.messages)) return Effect.void
592
+ const kept = dropUiOnlyMessages(e.messages)
593
+ const dropped = e.messages.length - kept.length
594
+ e.messages = kept
595
+ // Effect.log (no console.*): es lo único que llega al log del servidor.
596
+ return dropped > 0
597
+ ? Effect.logDebug(`[apex.cred] ${hookName}: ${dropped} respuesta(s) de /cred fuera de la petición`)
598
+ : Effect.void
599
+ }),
600
+ )
601
+ }
602
+
603
+ // ---------------------------------------------------------------------
604
+ // /cred command
605
+ // ---------------------------------------------------------------------
606
+ yield* ctx.command.transform((editor) => {
607
+ editor.add({
608
+ name: "cred",
609
+ description:
610
+ "Credenciales locales redactadas del contexto del modelo (set, list, get, rm, kdbx, learn). " +
611
+ "`/cred help` muestra el manual.",
612
+ execute: (input) =>
613
+ Effect.gen(function* () {
614
+ const text = String(input.prompt.text ?? "").trim()
615
+ const [sub, ...restParts] = text.split(/\s+/)
616
+ const rest = text.slice(sub?.length ?? 0).trim()
617
+
618
+ if (!sub || sub === "help" || sub === "--help" || sub === "-h" || sub === "ayuda") {
619
+ yield* notify(ctx, input.sessionID, CRED_HELP)
620
+ return
621
+ }
622
+
623
+ if (sub === "list") {
624
+ const names = store.list()
625
+ if (names.length === 0) {
626
+ yield* notify(ctx, input.sessionID, "apex cred: no hay secretos guardados")
627
+ return
628
+ }
629
+ const lines = names.map((n) => {
630
+ const e = store.get(n)
631
+ if (!e) return n
632
+ const kind = e.kind ?? inferKind(e)
633
+ const host = safeUrlForMeta(e.url)
634
+ return `${n}${kind ? ` [${kind}]` : ""}${host ? ` ${host}` : ""}${e.username ? ` user=${e.username}` : ""}`
635
+ })
636
+ yield* notify(ctx, input.sessionID, `apex cred: ${names.length} entrada(s)\n${lines.join("\n")}`)
637
+ return
638
+ }
639
+
640
+ if (sub === "get" || sub === "show" || sub === "describe") {
641
+ const name = restParts[0]
642
+ if (!name) { yield* notify(ctx, input.sessionID, "apex cred: uso: /cred get <nombre>"); return }
643
+ const entry = store.get(name)
644
+ if (!entry) { yield* notify(ctx, input.sessionID, `apex cred: "${name}" no existe`); return }
645
+ yield* notify(ctx, input.sessionID, `apex cred: ${JSON.stringify(publicEntry(entry), null, 2)}`)
646
+ return
647
+ }
648
+
649
+ if (sub === "rm" || sub === "remove" || sub === "del") {
650
+ const name = restParts[0]
651
+ if (!name) { yield* notify(ctx, input.sessionID, "apex cred: uso: /cred rm <nombre>"); return }
652
+ let removed = store.remove(name)
653
+ if (removed) {
654
+ if (kdbx) {
655
+ // El fichero manda: si allí no se pudo borrar (título duplicado o
656
+ // fallo al guardar), se resincroniza para no dejar de redactar.
657
+ const inFile = yield* Effect.promise(() => removeEntryFromKdbx(kdbx!, name).catch(() => false))
658
+ if (!inFile) {
659
+ syncKdbxToStore(kdbx, store)
660
+ removed = !store.has(name)
661
+ }
662
+ } else yield* persist()
663
+ }
664
+ yield* notify(ctx, input.sessionID, removed ? `apex cred: "${name}" eliminado` : `apex cred: "${name}" no existía`)
665
+ return
666
+ }
667
+
668
+ if (sub === "set" || sub === "add") {
669
+ const parsed = parseSetArgs(rest)
670
+ if (!parsed) {
671
+ yield* notify(ctx, input.sessionID, "apex cred: uso: /cred set <nombre>=<valor>|<uri> [--from-env VAR] [--from-file RUTA] [--username U] [--password P] [--url URL] [--kind K] [--secret.FIELD V]")
672
+ return
673
+ }
674
+
675
+ let value = parsed.value
676
+ if (parsed.fromEnv) value = process.env[parsed.fromEnv]
677
+ if (parsed.fromFile) {
678
+ try { value = readFileSync(expandHome(parsed.fromFile), "utf8").trim() }
679
+ catch (error) { yield* notify(ctx, input.sessionID, `apex cred: no se pudo leer fichero (${String(error)})`); return }
680
+ }
681
+
682
+ const entry = entryFromSet(parsed.name, value, {
683
+ uri: parsed.uri,
684
+ username: typeof parsed.flags.username === "string" ? parsed.flags.username : undefined,
685
+ password: typeof parsed.flags.password === "string" ? parsed.flags.password : undefined,
686
+ url: typeof parsed.flags.url === "string" ? parsed.flags.url : undefined,
687
+ kind: typeof parsed.flags.kind === "string" ? parsed.flags.kind : undefined,
688
+ notes: typeof parsed.flags.notes === "string" ? parsed.flags.notes : undefined,
689
+ fields: parsed.fields,
690
+ secretFields: parsed.secretFields,
691
+ })
692
+
693
+ const secrets = secretValuesOf(entry)
694
+ if (secrets.length === 0) {
695
+ yield* notify(ctx, input.sessionID, `apex cred: "${parsed.name}" no tiene ningún valor secreto`)
696
+ return
697
+ }
698
+ try {
699
+ store.setEntry(entry)
700
+ } catch (error) {
701
+ yield* notify(ctx, input.sessionID, `apex cred: ${(error as Error).message}`)
702
+ return
703
+ }
704
+ if (kdbx) {
705
+ const saveError = yield* Effect.promise(() =>
706
+ persistEntryToKdbx(kdbx!, entry).then(() => null, (e) => String((e as Error)?.message ?? e)),
707
+ )
708
+ if (saveError) {
709
+ yield* notify(ctx, input.sessionID, `apex cred: "${entry.name}" is redacted for this session but could NOT be saved to the KDBX file (${saveError})`)
710
+ return
711
+ }
712
+ } else {
713
+ yield* persist()
714
+ }
715
+ yield* notify(ctx, input.sessionID, `apex cred: "${entry.name}" guardado (${entry.kind ?? inferKind(entry)}) y redactado desde ahora`)
716
+ return
717
+ }
718
+
719
+ if (sub === "kdbx") {
720
+ const action = restParts[0]
721
+ if (action === "status") {
722
+ if (!kdbx) { yield* notify(ctx, input.sessionID, "apex cred: KDBX no habilitado"); return }
723
+ yield* notify(ctx, input.sessionID, `apex cred: KDBX activo en ${kdbx.path} (${kdbx.entries().length} entradas)`)
724
+ return
725
+ }
726
+ if (action === "reload") {
727
+ if (!kdbx) { yield* notify(ctx, input.sessionID, "apex cred: KDBX no habilitado"); return }
728
+ yield* Effect.promise(() => kdbx!.reload()).pipe(
729
+ Effect.tap(() => Effect.sync(() => syncKdbxToStore(kdbx!, store))),
730
+ Effect.tap(() => notify(ctx, input.sessionID, `apex cred: KDBX recargado (${kdbx!.entries().length} entradas)`)),
731
+ Effect.catch((e) => notify(ctx, input.sessionID, `apex cred: recarga KDBX falló (${String(e)})`)),
732
+ )
733
+ return
734
+ }
735
+ if (action === "save") {
736
+ if (!kdbx) { yield* notify(ctx, input.sessionID, "apex cred: KDBX no habilitado"); return }
737
+ yield* Effect.promise(() => kdbx!.save()).pipe(
738
+ Effect.tap(() => notify(ctx, input.sessionID, `apex cred: KDBX guardado en ${kdbx!.path}`)),
739
+ Effect.catch((e) => notify(ctx, input.sessionID, `apex cred: guardado KDBX falló (${String(e)})`)),
740
+ )
741
+ return
742
+ }
743
+ yield* notify(ctx, input.sessionID, "apex cred: uso: /cred kdbx status|reload|save")
744
+ return
745
+ }
746
+
747
+ if (sub === "learn") {
748
+ if (!config.llm.enabled) {
749
+ yield* notify(ctx, input.sessionID, "apex cred: /cred learn necesita cred.llm.enabled=true y modelo local. Usa /cred set.")
750
+ return
751
+ }
752
+ const guess = yield* Effect.promise(() => learnWithLocalModel(config.llm, rest))
753
+ if (!guess) { yield* notify(ctx, input.sessionID, "apex cred: no se identificó secreto. Usa /cred set."); return }
754
+ pending.set(input.sessionID, guess)
755
+ yield* notify(ctx, input.sessionID, `apex cred: detecté "${guess.name}" (${guess.value.length} caracteres). /cred confirm | /cred discard`)
756
+ return
757
+ }
758
+
759
+ if (sub === "confirm") {
760
+ const guess = pending.get(input.sessionID)
761
+ if (!guess) { yield* notify(ctx, input.sessionID, "apex cred: no hay candidato pendiente"); return }
762
+ pending.delete(input.sessionID)
763
+ try { store.set(guess.name, guess.value) }
764
+ catch (error) { yield* notify(ctx, input.sessionID, `apex cred: ${(error as Error).message}`); return }
765
+ if (kdbx) {
766
+ const entry = store.get(guess.name)
767
+ if (entry) yield* Effect.promise(() => persistEntryToKdbx(kdbx!, entry)).pipe(Effect.catch(() => Effect.void))
768
+ } else {
769
+ yield* persist()
770
+ }
771
+ yield* notify(ctx, input.sessionID, `apex cred: "${guess.name}" guardado y redactado desde ahora`)
772
+ return
773
+ }
774
+
775
+ if (sub === "discard") {
776
+ const had = pending.delete(input.sessionID)
777
+ yield* notify(ctx, input.sessionID, had ? "apex cred: candidato descartado" : "apex cred: no había nada pendiente")
778
+ return
779
+ }
780
+
781
+ yield* notify(ctx, input.sessionID, `apex cred: subcomando desconocido "${sub}".\n\n${CRED_HELP}`)
782
+ }),
783
+ })
784
+ })
785
+
786
+ // ---------------------------------------------------------------------
787
+ // Herramienta del agente: apex_cred (+ herramientas efímeras por canal)
788
+ // ---------------------------------------------------------------------
789
+ // Cada canal abierto publica su propia herramienta `apex_cred_use_<id>`:
790
+ // el transform se vuelve a ejecutar con `ctx.tool.reload()` al abrir/cerrar.
791
+ // `apex_cred action=use` hace lo mismo sin depender de que el host haya
792
+ // refrescado ya la lista de herramientas del turno en curso.
793
+ const reloadTools = (): Promise<void> =>
794
+ Effect.runPromise(ctx.tool.reload().pipe(Effect.catch(() => Effect.void))).catch(() => undefined)
795
+
796
+ const useHandle = async (
797
+ id: string,
798
+ action: string,
799
+ params: Record<string, unknown>,
800
+ ): Promise<{ ok: boolean; output: unknown }> => {
801
+ const handle = handles.get(id)
802
+ if (!handle) return { ok: false, output: "channel closed or unknown: open it again with apex_cred action=open" }
803
+ const entry = store.get(handle.credentialName)
804
+ if (!entry) {
805
+ handles.delete(id)
806
+ await reloadTools()
807
+ return { ok: false, output: `credential "${handle.credentialName}" no longer exists; channel closed` }
808
+ }
809
+ if (action === "describe") return { ok: true, output: { ...publicEntry(entry), channel: handle.kind } }
810
+ handle.lastUsedAt = Date.now()
811
+ handle.uses += 1
812
+ try {
813
+ const result = await runChannelAction(handle.kind, entry, action, params)
814
+ return { ok: result.ok, output: scrubSecrets(result.output, store, result.injected) }
815
+ } catch (error) {
816
+ return { ok: false, output: scrubSecrets(`channel error: ${String((error as Error)?.message ?? error)}`, store) }
817
+ }
818
+ }
819
+
820
+ const useParams = {
821
+ type: "object",
822
+ description:
823
+ "ssh exec: { command, stdin?, timeoutMs? }. http request: { method?, path? (or url on the same origin), headers?, body?, timeoutMs? }.",
824
+ additionalProperties: true,
825
+ } as const
826
+ const useOutput = {
827
+ type: "object",
828
+ properties: {
829
+ ok: { type: "boolean" },
830
+ output: { description: "Result with every known secret removed" },
831
+ },
832
+ required: ["ok"],
833
+ additionalProperties: true,
834
+ } as const
835
+
836
+ const handleTool = (handle: CredHandle) => ({
837
+ name: `${HANDLE_TOOL_PREFIX}${handle.id}`,
838
+ description:
839
+ `Temporary channel to the resource of credential "${handle.credentialName}" (${handle.kind}). apex injects the ` +
840
+ `secret; you never see it. ` +
841
+ (handle.kind === "ssh"
842
+ ? `action="exec" runs params.command on the credential's host.`
843
+ : `action="request" sends an HTTP request to the credential's own origin (params.path).`) +
844
+ ` action="describe" returns public metadata. Close with apex_cred action=close handle=${handle.id}.`,
845
+ input: {
846
+ type: "object",
847
+ properties: {
848
+ action: { type: "string", enum: ["describe", "exec", "request"] },
849
+ params: useParams,
850
+ },
851
+ required: ["action"],
852
+ additionalProperties: false,
853
+ },
854
+ output: useOutput,
855
+ execute: (rawInput: unknown) =>
856
+ Effect.promise(async () => {
857
+ const input = (rawInput ?? {}) as { action?: string; params?: Record<string, unknown> }
858
+ return { output: await useHandle(handle.id, String(input.action ?? ""), input.params ?? {}) }
859
+ }),
860
+ })
861
+
862
+ yield* Effect.addFinalizer(() => Effect.sync(() => handles.clear()))
863
+
864
+ yield* ctx.tool.transform((editor) => {
865
+ editor.add({
866
+ name: "apex_cred",
867
+ description:
868
+ "Use stored credentials without ever seeing the secret. list/get return public metadata only (name, kind, " +
869
+ "host, username). open creates a temporary channel bound to the credential's own host and returns a handle " +
870
+ "plus a dedicated tool apex_cred_use_<handle>; reuse it as many times as needed. use runs an action on an " +
871
+ "open channel (same as calling its dedicated tool). close ends it; handles lists open channels.",
872
+ input: {
873
+ type: "object",
874
+ properties: {
875
+ action: { type: "string", enum: ["list", "get", "open", "use", "close", "handles"] },
876
+ name: { type: "string", description: "Credential name (get, open)" },
877
+ handle: { type: "string", description: "Channel handle (use, close)" },
878
+ mode: {
879
+ type: "string",
880
+ enum: ["auto", "ssh", "http-bearer", "http-basic", "api-key"],
881
+ description: "open: how to present the secret. auto (default) follows the credential's kind/URL",
882
+ },
883
+ do: { type: "string", enum: ["describe", "exec", "request"], description: "use: channel action" },
884
+ params: useParams,
885
+ },
886
+ required: ["action"],
887
+ additionalProperties: false,
888
+ },
889
+ output: {
890
+ type: "object",
891
+ properties: {
892
+ ok: { type: "boolean" },
893
+ result: { description: "Public metadata, channel info or the scrubbed result" },
894
+ },
895
+ required: ["ok"],
896
+ additionalProperties: true,
897
+ },
898
+ execute: (rawInput: unknown) =>
899
+ Effect.promise(async () => {
900
+ const input = (rawInput ?? {}) as {
901
+ action?: string; name?: string; handle?: string; mode?: string; do?: string; params?: Record<string, unknown>
902
+ }
903
+ const reply = (ok: boolean, result: unknown) => ({ output: { ok, result } })
904
+
905
+ switch (input.action) {
906
+ case "list":
907
+ return reply(true, store.entries().map((e) => publicEntry(e)))
908
+
909
+ case "get": {
910
+ if (!input.name) return reply(false, "missing name")
911
+ const entry = store.get(input.name)
912
+ return entry ? reply(true, publicEntry(entry)) : reply(false, "credential not found")
913
+ }
914
+
915
+ case "handles":
916
+ return reply(
917
+ true,
918
+ [...handles.values()].map((h) => ({
919
+ handle: h.id, tool: `${HANDLE_TOOL_PREFIX}${h.id}`, credential: h.credentialName, kind: h.kind, uses: h.uses,
920
+ })),
921
+ )
922
+
923
+ case "open": {
924
+ if (!input.name) return reply(false, "missing name")
925
+ const entry = store.get(input.name)
926
+ if (!entry) return reply(false, "credential not found")
927
+ const kind = channelKind(entry, input.mode)
928
+ if (!isSupportedChannel(kind)) {
929
+ return reply(
930
+ false,
931
+ `no channel for kind "${kind}". Supported: ssh (URL ssh://host[:port]) and http(s) with mode ` +
932
+ `http-bearer | http-basic | api-key. Ask the user to add a URL to the credential.`,
933
+ )
934
+ }
935
+ if (!entry.url) return reply(false, "credential has no URL, so there is no host to bind the channel to")
936
+ // Reutiliza el canal ya abierto para la misma credencial y modo.
937
+ const existing = [...handles.values()].find((h) => h.credentialName === entry.name && h.kind === kind)
938
+ const handle: CredHandle = existing ?? {
939
+ id: makeHandleId(), credentialName: entry.name, kind, createdAt: Date.now(), lastUsedAt: Date.now(), uses: 0,
940
+ }
941
+ if (!existing) {
942
+ if (handles.size >= MAX_HANDLES) return reply(false, `too many open channels (${MAX_HANDLES}): close one first`)
943
+ handles.set(handle.id, handle)
944
+ await reloadTools()
945
+ }
946
+ return reply(true, {
947
+ handle: handle.id,
948
+ tool: `${HANDLE_TOOL_PREFIX}${handle.id}`,
949
+ credential: entry.name,
950
+ kind,
951
+ target: safeUrlForMeta(entry.url),
952
+ usage: channelUsage(kind),
953
+ fallback: `apex_cred { action: "use", handle: "${handle.id}", do, params } works too`,
954
+ })
955
+ }
956
+
957
+ case "use": {
958
+ if (!input.handle) return reply(false, "missing handle")
959
+ const r = await useHandle(input.handle, String(input.do ?? ""), input.params ?? {})
960
+ return reply(r.ok, r.output)
961
+ }
962
+
963
+ case "close": {
964
+ if (!input.handle) return reply(false, "missing handle")
965
+ const existed = handles.delete(input.handle)
966
+ if (existed) await reloadTools()
967
+ return reply(existed, existed ? "closed" : "handle not found")
968
+ }
969
+
970
+ default:
971
+ return reply(false, `unknown action: ${String(input.action)}`)
972
+ }
973
+ }),
974
+ })
975
+
976
+ for (const handle of handles.values()) editor.add(handleTool(handle) as never)
977
+ })
978
+ })
979
+ }