opencode-apex 0.6.0 → 0.8.1

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