@johpaz/hive-agents 1.1.0 → 1.1.2

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.
Files changed (71) hide show
  1. package/README.md +15 -9
  2. package/dist/hive.js +2925 -1871
  3. package/dist/ui/assets/{A2UIPage-CS0VPY6a.js → A2UIPage-BOR7GzYi.js} +1 -1
  4. package/dist/ui/assets/{AgentCreateForm-DXkjtXaS.js → AgentCreateForm-Btza1Kiv.js} +1 -1
  5. package/dist/ui/assets/{AgentDetailPage-DUIX_cuQ.js → AgentDetailPage-D435IX8G.js} +1 -1
  6. package/dist/ui/assets/{AgentNewPage-SNXz2wik.js → AgentNewPage-DvP05Ap5.js} +1 -1
  7. package/dist/ui/assets/{AgentsPage-CGsdgx5F.js → AgentsPage-BT9CssIN.js} +1 -1
  8. package/dist/ui/assets/{ApiClientPage-MNMjfSDs.js → ApiClientPage-Cmo0XBwk.js} +1 -1
  9. package/dist/ui/assets/{ChannelsPage-BEwxWUcE.js → ChannelsPage-C53NCtXi.js} +1 -1
  10. package/dist/ui/assets/{DashboardPage-D6cRFKWW.js → DashboardPage-DpI54Ot0.js} +1 -1
  11. package/dist/ui/assets/{LoginPage-ByYmIa2p.js → LoginPage-CTc-MbtG.js} +1 -1
  12. package/dist/ui/assets/{LogsPage-Bmk9rohg.js → LogsPage-D-2DgTQh.js} +1 -1
  13. package/dist/ui/assets/{MeetingPage-Dm97Mbiw.js → MeetingPage-B8Xb1z_0.js} +1 -1
  14. package/dist/ui/assets/{ModelSelector-gubC8j_Q.js → ModelSelector-BcaASPWF.js} +1 -1
  15. package/dist/ui/assets/Office3DPage-6bDnybWI.js +727 -0
  16. package/dist/ui/assets/ProvidersPage-CVK-nKxE.js +1 -0
  17. package/dist/ui/assets/{RecoverPage-YY2QU-qh.js → RecoverPage-UL782VIG.js} +1 -1
  18. package/dist/ui/assets/SettingsPage-CHJfutPk.js +9 -0
  19. package/dist/ui/assets/{SetupPage-LXnd2XbV.js → SetupPage-B_fXVcuJ.js} +1 -1
  20. package/dist/ui/assets/{Vignette-BcPWkNhm.js → Vignette-bSrGVyRd.js} +1 -1
  21. package/dist/ui/assets/{VoicePage-uLWdtoD4.css → VoicePage-CADecxhn.css} +1 -1
  22. package/dist/ui/assets/VoicePage-CdBZrLAm.js +307 -0
  23. package/dist/ui/assets/{WebChatPage-B61ZDjQ8.js → WebChatPage-D8KsJqMf.js} +1 -1
  24. package/dist/ui/assets/{bia-BFcUpOu3.glb → bia-csMImkVQ.glb} +0 -0
  25. package/dist/ui/assets/{conversationsStore-BlwA3yd2.js → conversationsStore-8WwqUOpe.js} +1 -1
  26. package/dist/ui/assets/{dialog-B04KpdNt.js → dialog-DcgGvP2g.js} +1 -1
  27. package/dist/ui/assets/headworklet.min-Bi87kUoI.mjs +1 -0
  28. package/dist/ui/assets/{index-DKJFLL3a.js → index-C5Hhusqq.js} +2 -2
  29. package/dist/ui/assets/index-DmFPF9xQ.css +2 -0
  30. package/dist/ui/assets/model-en-mixed-CfUSaeKF.bin +0 -0
  31. package/dist/ui/assets/useAudioDevices-BO-kUbtK.js +41 -0
  32. package/dist/ui/assets/{useHiveAgentsModelLoad-B4EjHvj4.js → useHiveAgentsModelLoad-IOqfYcrC.js} +1 -1
  33. package/dist/ui/assets/{useProviders-B1NS24md.js → useProviders-DsFqfiyM.js} +1 -1
  34. package/dist/ui/index.html +2 -2
  35. package/package.json +2 -2
  36. package/packages/cli/src/commands/onboard.ts +1 -1
  37. package/packages/core/src/agent/acceptance-checks.ts +25 -0
  38. package/packages/core/src/agent/agent-catalog.ts +23 -3
  39. package/packages/core/src/agent/jev-decisions.ts +125 -31
  40. package/packages/core/src/agent/jev-planner.ts +3 -3
  41. package/packages/core/src/agent/tool-selector.ts +41 -0
  42. package/packages/core/src/gateway/routes/providers.ts +4 -4
  43. package/packages/core/src/storage/bootstrap.ts +1 -1
  44. package/packages/core/src/storage/crypto.ts +110 -28
  45. package/packages/core/src/storage/seed.ts +38 -0
  46. package/packages/core/src/tools/code-agent/adapters.ts +110 -0
  47. package/packages/core/src/tools/code-agent/index.ts +193 -0
  48. package/packages/core/src/tools/index.ts +8 -0
  49. package/packages/core/src/tools/web/browser-backend.ts +22 -2
  50. package/packages/core/src/tools/web/index.ts +4 -0
  51. package/packages/core/src/tools/web/obscura.ts +860 -0
  52. package/packages/core/src/tools/web/webview-backend.ts +28 -6
  53. package/packages/skills/src/bundled/cli/external_code_agent/SKILL.md +69 -0
  54. package/packages/skills/src/bundled/web/obscura_browser/SKILL.md +69 -0
  55. package/packages/skills/src/bundled-data.generated.ts +837 -819
  56. package/dist/ui/assets/Office3DPage-Bfi-S2kG.js +0 -727
  57. package/dist/ui/assets/ProvidersPage-CSo0MYxd.js +0 -1
  58. package/dist/ui/assets/SettingsPage-DrafhhKw.js +0 -9
  59. package/dist/ui/assets/VoicePage-p-hTMAq7.js +0 -307
  60. package/dist/ui/assets/index-ByTufXPh.css +0 -2
  61. package/dist/ui/assets/useAudioDevices-B2stUHvr.js +0 -41
  62. /package/dist/ui/assets/{agentCapabilities-PfTEVxG1.js → agentCapabilities-CDSfJWhw.js} +0 -0
  63. /package/dist/ui/assets/{pause-Cm9LzIZK.js → pause-BAMsNQkh.js} +0 -0
  64. /package/dist/ui/assets/{pencil-L3Li7_pz.js → pencil-CKritjT_.js} +0 -0
  65. /package/dist/ui/assets/{play-zqogwA2l.js → play-Cwpe4tp6.js} +0 -0
  66. /package/dist/ui/assets/{plus-Bm08ABhc.js → plus-RD44ce15.js} +0 -0
  67. /package/dist/ui/assets/{radio-Cii1BjMt.js → radio-lFPMHi6-.js} +0 -0
  68. /package/dist/ui/assets/{refresh-cw-DXv3XgEt.js → refresh-cw-DtJMHRHO.js} +0 -0
  69. /package/dist/ui/assets/{rotate-ccw-LoM1AuqK.js → rotate-ccw-b3E_4PoX.js} +0 -0
  70. /package/dist/ui/assets/{search-BMwCI-pX.js → search-z2oZt00P.js} +0 -0
  71. /package/dist/ui/assets/{send-D6fgWV7m.js → send-CpoY_2F-.js} +0 -0
@@ -1,5 +1,5 @@
1
1
  import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
2
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"
3
3
  import * as path from "node:path"
4
4
  import { getHiveDir } from "../config/loader.ts"
5
5
  import { logger } from "../utils/logger"
@@ -15,9 +15,10 @@ interface SecretDoc {
15
15
 
16
16
  // ─── Durable secret store ────────────────────────────────────────────────────
17
17
  // The `secrets` collection is the source of truth: AES-256-GCM ciphertext in
18
- // the database, keyed by <HIVE_HOME>/.master.key. It lives inside the data
19
- // directory, so whatever persists the database (a Docker volume, a backup)
20
- // persists the secrets with it.
18
+ // the database. The AES key lives in the OS keychain (libsecret / macOS
19
+ // Keychain / Credential Manager); only where no keychain exists (headless
20
+ // Linux, Docker) does it fall back to <HIVE_HOME>/.master.key, next to the
21
+ // database, so a fresh install is still durable without configuration.
21
22
  //
22
23
  // The OS keychain (Bun.secrets) is only a best-effort mirror. It throws on
23
24
  // headless Linux/Docker (no libsecret/D-Bus), and on desktops it can be a
@@ -49,6 +50,7 @@ function _getKeychainApi(): any {
49
50
  }
50
51
 
51
52
  async function _get(name: string): Promise<string | null> {
53
+ await initMasterKey()
52
54
  const cached = _mem.get(name)
53
55
  if (cached !== undefined) return cached
54
56
  const epoch = _epoch.get(name) ?? 0
@@ -74,6 +76,7 @@ async function _get(name: string): Promise<string | null> {
74
76
  * silently accepting a secret that dies with the process.
75
77
  */
76
78
  async function _set(name: string, value: string): Promise<boolean> {
79
+ await initMasterKey()
77
80
  _epoch.set(name, (_epoch.get(name) ?? 0) + 1)
78
81
  _mem.set(name, value)
79
82
  const durable = await persistSecretToCollection(name, value)
@@ -143,19 +146,20 @@ async function _del(name: string): Promise<void> {
143
146
  }
144
147
 
145
148
  /**
146
- * Mint the master key (if this is a fresh install) and report where secrets
147
- * will be stored. Called once at boot so an operator sees the answer before
148
- * typing an API key, not after a restart lost it.
149
+ * Resolve the master key (minting it on a fresh install) and report where
150
+ * secrets will be stored. Called once at boot so an operator sees the answer
151
+ * before typing an API key, not after a restart lost it.
149
152
  */
150
- export function ensureSecretsBackend(): { durable: boolean } {
151
- const durable = getMasterKey() !== null
153
+ export async function ensureSecretsBackend(): Promise<{ durable: boolean; keySource: MasterKeySource }> {
154
+ await initMasterKey()
155
+ const durable = _masterKey !== null
152
156
  if (!durable) {
153
157
  log.error(
154
158
  `[secrets] No master key available — API keys and channel tokens will NOT survive a restart. ` +
155
159
  `Set HIVE_MASTER_KEY or make ${getHiveDir()} writable.`
156
160
  )
157
161
  }
158
- return { durable }
162
+ return { durable, keySource: _keySource }
159
163
  }
160
164
 
161
165
  // ─── Primitive API ────────────────────────────────────────────────────────────
@@ -300,52 +304,130 @@ export function decryptSecret(encrypted: string, iv: string): string {
300
304
  }
301
305
  }
302
306
 
307
+ type MasterKeySource = "env" | "keychain" | "file" | "none"
308
+
309
+ // One entry per data directory: the keychain is per-user, HIVE_HOME is not, and
310
+ // a second instance (tests, another profile) must never adopt this one's key.
311
+ const masterKeyEntry = () =>
312
+ `master-key:${new Bun.CryptoHasher("sha256").update(path.resolve(getHiveDir())).digest("hex").slice(0, 16)}`
313
+
303
314
  let _masterKey: Buffer | null = null
315
+ let _keySource: MasterKeySource = "none"
316
+ let _initPromise: Promise<void> | null = null
304
317
 
305
318
  /**
306
- * The AES key protecting the `secrets` collection.
319
+ * Resolve the AES key protecting the `secrets` collection, in order:
320
+ *
321
+ * 1. `HIVE_MASTER_KEY` — the key never touches the machine's disk.
322
+ * 2. The OS keychain. A key left in `<HIVE_HOME>/.master.key` by an earlier
323
+ * version is moved there, and the file is removed only after the keychain
324
+ * returns the same key.
325
+ * 3. `<HIVE_HOME>/.master.key` (0600) where no keychain exists.
307
326
  *
308
- * `HIVE_MASTER_KEY` wins when set (the recommended way to run in production:
309
- * the key never touches the data volume). Otherwise the key is minted on
310
- * first use and written 0600 to `<HIVE_HOME>/.master.key`, next to the
311
- * database — a fresh install becomes durable without the user configuring
312
- * anything, and restoring the data directory restores the ability to read
313
- * the secrets inside it.
327
+ * Memoized: every secret read/write awaits it, so the sync primitives below
328
+ * can rely on `_masterKey`.
314
329
  */
315
- function getMasterKey(): Buffer | null {
316
- if (_masterKey) return _masterKey
330
+ export function initMasterKey(): Promise<void> {
331
+ return (_initPromise ??= resolveMasterKey())
332
+ }
317
333
 
334
+ async function resolveMasterKey(): Promise<void> {
318
335
  const fromEnv = process.env.HIVE_MASTER_KEY
319
336
  if (fromEnv) {
320
337
  _masterKey = Buffer.from(fromEnv.slice(0, 32).padEnd(32, "0"), "utf8")
321
- return _masterKey
338
+ _keySource = "env"
339
+ return
322
340
  }
323
341
 
324
342
  const keyPath = path.join(getHiveDir(), ".master.key")
343
+ const fromKeychain = await _keychainGetKey()
344
+ if (fromKeychain) {
345
+ _masterKey = fromKeychain
346
+ _keySource = "keychain"
347
+ // An earlier version's file must not outlive the key it duplicates.
348
+ if (existsSync(keyPath) && readFileKey(keyPath)?.equals(fromKeychain)) removeKeyFile(keyPath)
349
+ return
350
+ }
351
+
352
+ // No key in the keychain: reuse the file's key (migration) or mint a new one.
353
+ const key = (existsSync(keyPath) ? readFileKey(keyPath) : null) ?? randomBytes(32)
354
+ if (await _keychainSetKey(key)) {
355
+ _masterKey = key
356
+ _keySource = "keychain"
357
+ if (existsSync(keyPath)) removeKeyFile(keyPath)
358
+ else log.info("[secrets] Master key generated in the OS keychain")
359
+ return
360
+ }
361
+
362
+ // Headless Linux / Docker: no keychain to hold it.
363
+ _masterKey = loadOrMintKeyFile(keyPath)
364
+ _keySource = _masterKey ? "file" : "none"
365
+ }
366
+
367
+ /** Read the key from the keychain; null when absent, malformed or no keychain. */
368
+ async function _keychainGetKey(): Promise<Buffer | null> {
369
+ try {
370
+ const hex = await (Bun as any).secrets.get({ service: SERVICE, name: masterKeyEntry() })
371
+ const key = hex ? Buffer.from(String(hex).trim(), "hex") : null
372
+ return key?.length === 32 ? key : null
373
+ } catch {
374
+ return null
375
+ }
376
+ }
377
+
378
+ /** Store the key and confirm the keychain gives it back — a write that does not persist is no write. */
379
+ async function _keychainSetKey(key: Buffer): Promise<boolean> {
380
+ try {
381
+ await (Bun as any).secrets.set({ service: SERVICE, name: masterKeyEntry(), value: key.toString("hex") })
382
+ } catch {
383
+ return false
384
+ }
385
+ return (await _keychainGetKey())?.equals(key) ?? false
386
+ }
387
+
388
+ function readFileKey(keyPath: string): Buffer | null {
389
+ try {
390
+ const key = Buffer.from(readFileSync(keyPath, "utf8").trim(), "hex")
391
+ if (key.length === 32) return key
392
+ log.error(`[secrets] ${keyPath} is not a 32-byte hex key — secrets cannot be read or written`)
393
+ } catch (err) {
394
+ log.error(`[secrets] Could not read ${keyPath}: ${(err as Error).message}`)
395
+ }
396
+ return null
397
+ }
398
+
399
+ function removeKeyFile(keyPath: string): void {
400
+ try {
401
+ unlinkSync(keyPath)
402
+ log.info(`[secrets] Master key moved to the OS keychain; removed ${keyPath}`)
403
+ } catch (err) {
404
+ log.warn(`[secrets] Master key is in the OS keychain but ${keyPath} could not be removed: ${(err as Error).message}`)
405
+ }
406
+ }
407
+
408
+ function loadOrMintKeyFile(keyPath: string): Buffer | null {
325
409
  try {
326
410
  if (!existsSync(keyPath)) {
327
411
  mkdirSync(path.dirname(keyPath), { recursive: true })
328
412
  try {
329
413
  // "wx" so two processes starting at once can't overwrite each other's key
330
414
  writeFileSync(keyPath, randomBytes(32).toString("hex"), { mode: 0o600, flag: "wx" })
331
- log.info(`[secrets] Master key generated at ${keyPath}`)
415
+ log.info(`[secrets] No OS keychain; master key generated at ${keyPath}`)
332
416
  } catch (err) {
333
417
  if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err
334
418
  }
335
419
  }
336
- const key = Buffer.from(readFileSync(keyPath, "utf8").trim(), "hex")
337
- if (key.length !== 32) {
338
- log.error(`[secrets] ${keyPath} is not a 32-byte hex key — secrets cannot be read or written`)
339
- return null
340
- }
341
- _masterKey = key
342
- return _masterKey
420
+ return readFileKey(keyPath)
343
421
  } catch (err) {
344
422
  log.error(`[secrets] Could not read or create ${keyPath}: ${(err as Error).message}`)
345
423
  return null
346
424
  }
347
425
  }
348
426
 
427
+ function getMasterKey(): Buffer | null {
428
+ return _masterKey
429
+ }
430
+
349
431
  /**
350
432
  * Encrypt a plaintext string with AES-256-GCM. Format:
351
433
  * `<encDataHex>:<authTagHex>`. Used for every document in the `secrets`
@@ -62,6 +62,43 @@ export const SEED_DATA: SeedData = {
62
62
  { id: "browser_extract", name: "browser_extract", category: "web", description: "Extraer texto, enlaces o datos estructurados usando selectores CSS o XPath. Sinónimos: obtener datos, scraping, selectores, extraer información" },
63
63
  { id: "browser_script", name: "browser_script", category: "web", description: "Ejecutar JavaScript arbitrario en el navegador y obtener resultado. Sinónimos: ejecutar javascript, script, código, función, evaluar" },
64
64
  { id: "browser_wait", name: "browser_wait", category: "web", description: "Esperar a que aparezca un elemento o se cumpla una condición. Sinónimos: esperar, condición, elemento, selector, pausa" },
65
+ { id: "obscura_navigate", name: "obscura_navigate", category: "web", description: "Navigate to a URL and wait for the page to load, keeping a live browser session for subsequent obscura_* tools. Returns the final URL and title only: read the page next with obscura_snapshot or obscura_markdown. Spanish keywords: navegar, abrir página, ir a sitio web, cargar url, visitar" },
66
+ { id: "obscura_back", name: "obscura_back", category: "web", description: "Navigate back in the page history (browser back button). Requires an active session from obscura_navigate. Spanish keywords: atrás, volver, página anterior, regresar" },
67
+ { id: "obscura_forward", name: "obscura_forward", category: "web", description: "Navigate forward in the page history. Requires an active session from obscura_navigate. Spanish keywords: adelante, página siguiente, avanzar" },
68
+ { id: "obscura_reload", name: "obscura_reload", category: "web", description: "Reload the current page. Requires an active session from obscura_navigate. Spanish keywords: recargar, refrescar página, actualizar página, f5" },
69
+ { id: "obscura_close", name: "obscura_close", category: "web", description: "Close the current browser page and reset the session state. Spanish keywords: cerrar navegador, cerrar página, terminar sesión" },
70
+ { id: "obscura_snapshot", name: "obscura_snapshot", category: "web", description: "Get the current page as text: URL, title, readable body text and interactive element refs. Preferred first read after navigating. Spanish keywords: snapshot página, contenido página, ver página, texto página, captura textual" },
71
+ { id: "obscura_markdown", name: "obscura_markdown", category: "web", description: "Extract the current page as Markdown (headings, paragraphs, lists, links, code blocks). Token-dense structured content instead of plain text. Spanish keywords: markdown, extraer markdown, contenido estructurado, página en markdown" },
72
+ { id: "obscura_links", name: "obscura_links", category: "web", description: "List every anchor link on the current page as one JSON object per line {text, href}. Spanish keywords: listar enlaces, ver links, urls página, hipervínculos, enlaces" },
73
+ { id: "obscura_interactive_elements", name: "obscura_interactive_elements", category: "web", description: "List every clickable/typeable element with a stable ref ID and a brief description. Use BEFORE clicking or filling to act by ref instead of guessing CSS selectors. Spanish keywords: elementos interactivos, botones, campos, inputs, refs, elementos clicables" },
74
+ { id: "obscura_detect_forms", name: "obscura_detect_forms", category: "web", description: "List every <form> on the page with its action URL, method and a description of each input/textarea/select. Understand a form before filling it. Spanish keywords: detectar formularios, ver formularios, campos formulario, estructura formulario" },
75
+ { id: "obscura_extract", name: "obscura_extract", category: "web", description: "Extract a structured object from the page given a map of {field_name: css_selector}. Use 'selector@attr' for attributes (e.g. 'a@href') and 'field[]' suffix for arrays. Spanish keywords: extraer datos, scraping, extraer estructura, datos página, seleccionar campos" },
76
+ { id: "obscura_get_attribute", name: "obscura_get_attribute", category: "web", description: "Read an attribute of an element (href, src, value, class, data-*). Returns the raw value or empty string. Spanish keywords: leer atributo, obtener atributo, href, valor elemento, atributo html" },
77
+ { id: "obscura_count", name: "obscura_count", category: "web", description: "Count how many elements on the page match a CSS selector. Cheap existence/pagination probe. Spanish keywords: contar elementos, cuántos, número de elementos, contar coincidencias" },
78
+ { id: "obscura_search", name: "obscura_search", category: "web", description: "Find substring matches in the visible page text with surrounding context. Spanish keywords: buscar en página, encontrar texto, buscar contenido, texto en página" },
79
+ { id: "obscura_click", name: "obscura_click", category: "web", description: "Click an element by ref (preferred, from obscura_snapshot/obscura_interactive_elements) or CSS selector. Spanish keywords: hacer clic, presionar botón, clickear, pulsar, click" },
80
+ { id: "obscura_fill", name: "obscura_fill", category: "web", description: "Set the value of an input element (replaces existing value). Pass ref (preferred) or selector. Spanish keywords: llenar campo, rellenar input, establecer valor, completar campo" },
81
+ { id: "obscura_type", name: "obscura_type", category: "web", description: "Type text into an input element (appends to existing value). Pass ref (preferred) or selector. Spanish keywords: escribir en campo, teclear texto, introducir texto, escribir input" },
82
+ { id: "obscura_fill_form", name: "obscura_fill_form", category: "web", description: "Fill multiple inputs in one call: fields is an array of {ref?, selector?, value, type?} where type is text (default), check, uncheck or select. Optional submit_ref/submit_selector clicks after filling. Spanish keywords: llenar formulario, completar formulario, rellenar form, enviar formulario" },
83
+ { id: "obscura_press_key", name: "obscura_press_key", category: "web", description: "Dispatch a keyboard event (Enter, Tab, Escape…) on an element or the document. Spanish keywords: presionar tecla, pulsar enter, teclado, keydown" },
84
+ { id: "obscura_select_option", name: "obscura_select_option", category: "web", description: "Select an option from a <select> element by value or visible text. Spanish keywords: seleccionar opción, elegir opción, dropdown, lista desplegable, select" },
85
+ { id: "obscura_scroll", name: "obscura_scroll", category: "web", description: "Scroll the page or an element: direction top/bottom/up/down/left/right, amount in pixels. Use 'bottom' to trigger infinite-scroll loaders. Spanish keywords: scroll, desplazar, bajar página, subir página, desplazamiento" },
86
+ { id: "obscura_wait_for", name: "obscura_wait_for", category: "web", description: "Wait for a CSS selector to appear in the DOM (default 30s). Spanish keywords: esperar elemento, aguardar selector, wait selector, esperar carga" },
87
+ { id: "obscura_wait_for_text", name: "obscura_wait_for_text", category: "web", description: "Wait until a substring appears anywhere in the rendered page text — for result messages and notifications. Spanish keywords: esperar texto, aguardar mensaje, esperar resultado, wait texto" },
88
+ { id: "obscura_evaluate", name: "obscura_evaluate", category: "web", description: "Evaluate a JavaScript expression in the page context and return the result as JSON. Spanish keywords: ejecutar javascript, evaluar expresión, js en página, script navegador, eval" },
89
+ { id: "obscura_network_requests", name: "obscura_network_requests", category: "web", description: "List the network requests made by the current page (URLs, statuses, timings). Spanish keywords: ver peticiones red, requests, tráfico red, llamadas http página, network" },
90
+ { id: "obscura_console_messages", name: "obscura_console_messages", category: "web", description: "List the console messages logged by the current page (logs, warnings, errors). Spanish keywords: ver consola, logs página, mensajes consola, errores javascript, console" },
91
+ { id: "obscura_screenshot", name: "obscura_screenshot", category: "web", description: "Capture the current rendered viewport as a PNG (saved to ~/.hivecode/screenshots/, returned with path + base64). Use for canvas/visual verification; prefer obscura_snapshot for text. Spanish keywords: captura de pantalla, screenshot, fotografiar página, imagen página, png" },
92
+ { id: "obscura_pdf", name: "obscura_pdf", category: "web", description: "Export the current rendered document as a paginated PDF (saved to ~/.hivecode/screenshots/). Spanish keywords: exportar pdf, guardar pdf, página a pdf, documento pdf" },
93
+ { id: "obscura_get_cookies", name: "obscura_get_cookies", category: "web", description: "Return all cookies in the browser's cookie jar as one JSON object per line. Spanish keywords: ver cookies, obtener cookies, cookies sesión, leer cookies" },
94
+ { id: "obscura_set_cookie", name: "obscura_set_cookie", category: "web", description: "Add or replace a cookie in the jar — skip a login flow when you already have a session token. Spanish keywords: setear cookie, establecer cookie, inyectar cookie, cookie sesión" },
95
+ { id: "obscura_clear_cookies", name: "obscura_clear_cookies", category: "web", description: "Wipe every cookie from the jar. Spanish keywords: borrar cookies, limpiar cookies, eliminar cookies" },
96
+ { id: "obscura_storage_state", name: "obscura_storage_state", category: "web", description: "Export the full session state (cookies + localStorage + sessionStorage) as JSON — save it to skip a login on a later run. Spanish keywords: exportar sesión, estado sesión, guardar sesión, storage state" },
97
+ { id: "obscura_set_storage_state", name: "obscura_set_storage_state", category: "web", description: "Restore a session state previously returned by obscura_storage_state to bring an authenticated session back. Spanish keywords: restaurar sesión, importar sesión, cargar sesión guardada, login guardado" },
98
+ { id: "obscura_tab_new", name: "obscura_tab_new", category: "web", description: "Open a new tab (isolated browser page); subsequent tool calls operate on the most recent tab. Spanish keywords: nueva pestaña, abrir pestaña, nuevo tab" },
99
+ { id: "obscura_tab_list", name: "obscura_tab_list", category: "web", description: "List all open tabs with their ID, URL, title and which one is active. Spanish keywords: listar pestañas, ver pestañas, tabs abiertos" },
100
+ { id: "obscura_tab_switch", name: "obscura_tab_switch", category: "web", description: "Switch the active tab — all subsequent tool calls target this tab. Spanish keywords: cambiar pestaña, cambiar tab, activar pestaña" },
101
+ { id: "obscura_tab_close", name: "obscura_tab_close", category: "web", description: "Close a tab by ID (default: the active tab). Spanish keywords: cerrar pestaña, cerrar tab" },
65
102
 
66
103
  // ─────────────────────────────────────────
67
104
  // 3. CRON — Tareas programadas
@@ -79,6 +116,7 @@ export const SEED_DATA: SeedData = {
79
116
  // 4. CLI — Ejecución de comandos
80
117
  // ─────────────────────────────────────────
81
118
  { id: "cli_exec", name: "cli_exec", category: "cli", description: "Ejecutar comandos shell/bash en el entorno del agente. NOTA: NO usar para tareas programadas, usar cron.create. Sinónimos: ejecutar comando, terminal, bash, script, consola" },
119
+ { id: "code_agent_run", name: "code_agent_run", category: "cli", description: "Delegar una tarea de programación a un agente de código externo (claude, codex, opencode, kimi) en un git worktree aislado; devuelve resumen, archivos y diff. Sinónimos: agente de código, delegar programación" },
82
120
 
83
121
  // ─────────────────────────────────────────
84
122
  // 5. AGENTS — Memoria, workers y delegación
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Adapters for external coding-agent CLIs. Each one knows how to run its CLI
3
+ * non-interactively and how to pull a human-readable summary out of the output.
4
+ */
5
+
6
+ export type CodeAgentId = "claude" | "codex" | "opencode" | "kimi";
7
+
8
+ export interface AdapterInvocation {
9
+ argv: string[];
10
+ /** Files the CLI writes its final message to (codex), read after exit. */
11
+ lastMessageFile?: string;
12
+ }
13
+
14
+ export interface AdapterInput {
15
+ prompt: string;
16
+ cwd: string;
17
+ model?: string;
18
+ /** True when cwd is a throwaway worktree, so full auto-approval is safe. */
19
+ isolated: boolean;
20
+ tmpDir: string;
21
+ }
22
+
23
+ export interface CodeAgentAdapter {
24
+ id: CodeAgentId;
25
+ binary: string;
26
+ build(input: AdapterInput): AdapterInvocation;
27
+ summarize(stdout: string, lastMessage?: string): { summary: string; sessionId?: string; costUsd?: number };
28
+ }
29
+
30
+ function tail(text: string, max = 4000): string {
31
+ const t = text.trim();
32
+ return t.length > max ? `…${t.slice(-max)}` : t;
33
+ }
34
+
35
+ const claude: CodeAgentAdapter = {
36
+ id: "claude",
37
+ binary: "claude",
38
+ build({ prompt, model, isolated }) {
39
+ const argv = [
40
+ "claude", "-p", prompt,
41
+ "--output-format", "json",
42
+ "--permission-mode", isolated ? "bypassPermissions" : "acceptEdits",
43
+ ];
44
+ if (model) argv.push("--model", model);
45
+ return { argv };
46
+ },
47
+ summarize(stdout) {
48
+ try {
49
+ const parsed = JSON.parse(stdout.trim());
50
+ return {
51
+ summary: String(parsed.result ?? ""),
52
+ sessionId: parsed.session_id,
53
+ costUsd: typeof parsed.total_cost_usd === "number" ? parsed.total_cost_usd : undefined,
54
+ };
55
+ } catch {
56
+ return { summary: tail(stdout) };
57
+ }
58
+ },
59
+ };
60
+
61
+ const codex: CodeAgentAdapter = {
62
+ id: "codex",
63
+ binary: "codex",
64
+ build({ prompt, cwd, model, tmpDir }) {
65
+ const lastMessageFile = `${tmpDir}/codex-last-message.txt`;
66
+ const argv = [
67
+ "codex", "exec",
68
+ "-s", "workspace-write",
69
+ "-C", cwd,
70
+ "--skip-git-repo-check",
71
+ "-o", lastMessageFile,
72
+ ];
73
+ if (model) argv.push("-m", model);
74
+ argv.push(prompt);
75
+ return { argv, lastMessageFile };
76
+ },
77
+ summarize(stdout, lastMessage) {
78
+ return { summary: lastMessage?.trim() || tail(stdout) };
79
+ },
80
+ };
81
+
82
+ const opencode: CodeAgentAdapter = {
83
+ id: "opencode",
84
+ binary: "opencode",
85
+ build({ prompt, model }) {
86
+ const argv = ["opencode", "run", "--auto"];
87
+ if (model) argv.push("-m", model);
88
+ argv.push(prompt);
89
+ return { argv };
90
+ },
91
+ summarize(stdout) {
92
+ return { summary: tail(stdout) };
93
+ },
94
+ };
95
+
96
+ const kimi: CodeAgentAdapter = {
97
+ id: "kimi",
98
+ binary: "kimi",
99
+ // --prompt cannot be combined with --auto/--yolo: prompt mode runs unattended on its own.
100
+ build({ prompt, model }) {
101
+ const argv = ["kimi", "-p", prompt];
102
+ if (model) argv.push("-m", model);
103
+ return { argv };
104
+ },
105
+ summarize(stdout) {
106
+ return { summary: tail(stdout) };
107
+ },
108
+ };
109
+
110
+ export const ADAPTERS: Record<CodeAgentId, CodeAgentAdapter> = { claude, codex, opencode, kimi };
@@ -0,0 +1,193 @@
1
+ /**
2
+ * code_agent_run - Delegate a coding task to an external coding-agent CLI
3
+ * (Claude Code, Codex, OpenCode, Kimi).
4
+ *
5
+ * The CLI runs inside a throwaway git worktree when the workspace is a git
6
+ * repo, so it can be auto-approved safely. Nothing is merged: the result
7
+ * carries the diff and a patch file for the caller to review and apply.
8
+ *
9
+ * @category cli
10
+ * @seedId code_agent_run
11
+ * @spanish agente de código, delegar código, codex, claude code, opencode, kimi
12
+ */
13
+
14
+ import * as fs from "node:fs";
15
+ import * as os from "node:os";
16
+ import * as path from "node:path";
17
+ import type { Tool } from "../types.ts";
18
+ import { logger } from "../../utils/logger.ts";
19
+ import { resolveInWorkspace, getWorkspace, expandPath } from "../filesystem/workspace-guard.ts";
20
+ import { ADAPTERS, type CodeAgentId } from "./adapters.ts";
21
+
22
+ const log = logger.child("code-agent");
23
+
24
+ const DEFAULT_TIMEOUT_SECS = 600;
25
+ const MAX_TIMEOUT_SECS = 3600;
26
+ const MAX_DIFF_CHARS = 20000;
27
+
28
+ /** Env vars that must never reach an external CLI. */
29
+ const SECRET_ENV = /(^|_)(TOKEN|SECRET|PASSWORD|KEY)(_|$)/i;
30
+ const KEEP_ENV = new Set(["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "MOONSHOT_API_KEY", "KIMI_API_KEY", "OPENROUTER_API_KEY"]);
31
+
32
+ function cleanEnv(): Record<string, string> {
33
+ const env: Record<string, string> = {};
34
+ for (const [k, v] of Object.entries(process.env)) {
35
+ if (v === undefined) continue;
36
+ if (SECRET_ENV.test(k) && !KEEP_ENV.has(k)) continue;
37
+ env[k] = v;
38
+ }
39
+ return env;
40
+ }
41
+
42
+ async function run(argv: string[], cwd: string, opts: { signal?: AbortSignal; env?: Record<string, string> } = {}) {
43
+ const proc = Bun.spawn(argv, { cwd, stdout: "pipe", stderr: "pipe", signal: opts.signal, env: opts.env });
44
+ const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);
45
+ const exitCode = await proc.exited;
46
+ return { stdout, stderr, exitCode };
47
+ }
48
+
49
+ async function gitRoot(cwd: string): Promise<string | null> {
50
+ try {
51
+ const r = await run(["git", "rev-parse", "--show-toplevel"], cwd);
52
+ return r.exitCode === 0 ? r.stdout.trim() : null;
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ export const codeAgentRunTool: Tool = {
59
+ name: "code_agent_run",
60
+ // Coding agents are slow; the harness ceiling must exceed the per-call timeout.
61
+ timeoutMs: (MAX_TIMEOUT_SECS + 60) * 1000,
62
+ description:
63
+ "Delegate a coding task to an external coding-agent CLI (claude, codex, opencode, kimi). " +
64
+ "Runs in an isolated git worktree when possible and returns the summary, changed files and diff; " +
65
+ "it never merges into the workspace. Spanish: agente de código externo, delegar programación",
66
+ parameters: {
67
+ type: "object",
68
+ properties: {
69
+ agent: { type: "string", enum: ["claude", "codex", "opencode", "kimi"], description: "Which coding-agent CLI to use" },
70
+ prompt: { type: "string", description: "Complete, self-contained task instructions for the coding agent" },
71
+ cwd: { type: "string", description: "Repository directory (default: agent workspace)" },
72
+ model: { type: "string", description: "Optional model override understood by that CLI" },
73
+ timeout: { type: "number", description: `Timeout in seconds (default ${DEFAULT_TIMEOUT_SECS}, max ${MAX_TIMEOUT_SECS})` },
74
+ },
75
+ required: ["agent", "prompt"],
76
+ },
77
+ execute: async (params, config) => {
78
+ const agentId = params.agent as CodeAgentId;
79
+ const adapter = ADAPTERS[agentId];
80
+ if (!adapter) return { ok: false, error: `Unknown agent '${String(params.agent)}'. Use: ${Object.keys(ADAPTERS).join(", ")}` };
81
+ const prompt = String(params.prompt ?? "").trim();
82
+ if (!prompt) return { ok: false, error: "prompt is required" };
83
+
84
+ // Bun.which looks at the PATH the process started with; pass the live one so
85
+ // a PATH changed at runtime (a user shell hook, a test double) is honoured.
86
+ if (!Bun.which(adapter.binary, { PATH: process.env.PATH })) {
87
+ return { ok: false, error: `'${adapter.binary}' is not installed or not in PATH`, hint: "Install that CLI or choose another agent." };
88
+ }
89
+
90
+ const workspace = getWorkspace(config);
91
+ let cwd: string;
92
+ try {
93
+ const raw = (params.cwd as string) ?? (workspace ? expandPath(workspace) : process.cwd());
94
+ cwd = resolveInWorkspace(raw, workspace);
95
+ } catch (e) {
96
+ return { ok: false, error: (e as Error).message };
97
+ }
98
+ if (!fs.existsSync(cwd)) return { ok: false, error: `Working directory not found: ${cwd}` };
99
+
100
+ const timeoutSecs = Math.min(Math.max((params.timeout as number) ?? DEFAULT_TIMEOUT_SECS, 10), MAX_TIMEOUT_SECS);
101
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "hive-code-agent-"));
102
+ const root = await gitRoot(cwd);
103
+ let runDir = cwd;
104
+ let worktree: string | null = null;
105
+
106
+ if (root) {
107
+ const wt = path.join(tmpDir, "worktree");
108
+ const add = await run(["git", "worktree", "add", "--detach", wt, "HEAD"], root);
109
+ if (add.exitCode === 0) {
110
+ worktree = wt;
111
+ runDir = path.join(wt, path.relative(root, cwd));
112
+ } else {
113
+ log.warn(`worktree failed, running in place with reduced permissions: ${add.stderr.trim()}`);
114
+ }
115
+ }
116
+
117
+ const invocation = adapter.build({
118
+ prompt,
119
+ cwd: runDir,
120
+ model: params.model as string | undefined,
121
+ isolated: worktree !== null,
122
+ tmpDir,
123
+ });
124
+
125
+ log.info(`code_agent_run ${agentId} (cwd=${runDir}, isolated=${worktree !== null})`);
126
+ const t0 = performance.now();
127
+ const controller = new AbortController();
128
+ const timer = setTimeout(() => controller.abort(), timeoutSecs * 1000);
129
+ let result: { stdout: string; stderr: string; exitCode: number } | null = null;
130
+ let timedOut = false;
131
+
132
+ try {
133
+ result = await run(invocation.argv, runDir, { signal: controller.signal, env: cleanEnv() });
134
+ } catch {
135
+ timedOut = controller.signal.aborted;
136
+ } finally {
137
+ clearTimeout(timer);
138
+ }
139
+
140
+ let diff = "";
141
+ let files: string[] = [];
142
+ let patchPath: string | undefined;
143
+ if (worktree) {
144
+ await run(["git", "add", "-A"], worktree);
145
+ diff = (await run(["git", "diff", "--cached", "HEAD"], worktree)).stdout;
146
+ files = (await run(["git", "diff", "--cached", "--name-only", "HEAD"], worktree)).stdout.split("\n").filter(Boolean);
147
+ if (diff) {
148
+ patchPath = path.join(os.tmpdir(), `hive-code-agent-${Date.now()}.patch`);
149
+ fs.writeFileSync(patchPath, diff);
150
+ }
151
+ await run(["git", "worktree", "remove", "--force", worktree], root!);
152
+ }
153
+
154
+ let lastMessage: string | undefined;
155
+ if (invocation.lastMessageFile && fs.existsSync(invocation.lastMessageFile)) {
156
+ lastMessage = fs.readFileSync(invocation.lastMessageFile, "utf8");
157
+ }
158
+ fs.rmSync(tmpDir, { recursive: true, force: true });
159
+
160
+ const elapsedMs = Math.round(performance.now() - t0);
161
+ if (!result) {
162
+ return {
163
+ ok: false,
164
+ agent: agentId,
165
+ error: timedOut ? `${agentId} killed after ${timeoutSecs}s timeout` : `${agentId} failed to run`,
166
+ files_changed: files,
167
+ patch_path: patchPath,
168
+ executionTimeMs: elapsedMs,
169
+ };
170
+ }
171
+
172
+ const parsed = adapter.summarize(result.stdout, lastMessage);
173
+ return {
174
+ ok: result.exitCode === 0,
175
+ agent: agentId,
176
+ exitCode: result.exitCode,
177
+ isolated: worktree !== null,
178
+ summary: parsed.summary,
179
+ session_id: parsed.sessionId,
180
+ cost_usd: parsed.costUsd,
181
+ files_changed: files,
182
+ diff: diff.length > MAX_DIFF_CHARS ? `${diff.slice(0, MAX_DIFF_CHARS)}\n…(truncated, see patch_path)` : diff,
183
+ patch_path: patchPath,
184
+ stderr: result.exitCode === 0 ? undefined : result.stderr.trim().slice(-2000),
185
+ executionTimeMs: elapsedMs,
186
+ apply_hint: patchPath ? `git apply ${patchPath}` : undefined,
187
+ };
188
+ },
189
+ };
190
+
191
+ export function createTools(): Tool[] {
192
+ return [codeAgentRunTool];
193
+ }
@@ -20,6 +20,9 @@ import * as cron from "./cron/index.ts";
20
20
  // CLI (1)
21
21
  import * as cli from "./cli/index.ts";
22
22
 
23
+ // Code agents (1) - external coding-agent CLIs
24
+ import * as codeAgent from "./code-agent/index.ts";
25
+
23
26
  // Agents (15)
24
27
  import * as agents from "./agents/index.ts";
25
28
 
@@ -52,6 +55,9 @@ export function createAllTools(config: Config): Tool[] {
52
55
  // CLI (1)
53
56
  ...cli.createTools(),
54
57
 
58
+ // CODE AGENTS (1)
59
+ ...codeAgent.createTools(),
60
+
55
61
  // AGENTS (14)
56
62
  ...agents.createTools(),
57
63
 
@@ -83,6 +89,8 @@ export function createToolsByCategory(category: string, config: Config): Tool[]
83
89
  return cron.createTools();
84
90
  case "cli":
85
91
  return cli.createTools();
92
+ case "code-agent":
93
+ return codeAgent.createTools();
86
94
  case "agents":
87
95
  return agents.createTools();
88
96
  case "a2ui":
@@ -106,6 +106,20 @@ const CHROME_BINARIES = [
106
106
  "opera",
107
107
  ];
108
108
 
109
+ /** Chromium que Playwright deja en `~/.cache/ms-playwright/chromium-<rev>`, el más nuevo primero. */
110
+ function playwrightChromiumPaths(home: string): string[] {
111
+ const { readdirSync } = require("node:fs") as typeof import("node:fs");
112
+ const root = process.env.PLAYWRIGHT_BROWSERS_PATH ?? `${home}/.cache/ms-playwright`;
113
+ try {
114
+ return readdirSync(root)
115
+ .filter((name) => /^chromium-\d+$/.test(name))
116
+ .sort((a, b) => Number(b.split("-")[1]) - Number(a.split("-")[1]))
117
+ .map((name) => `${root}/${name}/chrome-linux/chrome`);
118
+ } catch {
119
+ return [];
120
+ }
121
+ }
122
+
109
123
  /** Rutas conocidas por plataforma, en orden de preferencia. */
110
124
  function chromePathsForPlatform(): string[] {
111
125
  const home = process.env.HOME ?? "";
@@ -137,8 +151,12 @@ function chromePathsForPlatform(): string[] {
137
151
 
138
152
  // Linux: paquetes del sistema, snap y los wrappers que exporta flatpak —que
139
153
  // en la práctica son el único Chrome de muchas máquinas.
154
+ // Chrome y Chromium de flatpak arrancan bien con Bun; el de Brave no ("Failed
155
+ // to spawn Chrome": su sandbox no hereda los pipes de depuración). Por eso se
156
+ // recorre por app y no por directorio —si no, el Brave del directorio de
157
+ // sistema ganaría al Chrome del directorio de usuario— y Brave va al final.
140
158
  const flatpakDirs = ["/var/lib/flatpak/exports/bin", `${home}/.local/share/flatpak/exports/bin`];
141
- const flatpakApps = ["com.google.Chrome", "org.chromium.Chromium", "com.brave.Browser", "com.microsoft.Edge"];
159
+ const flatpakPaths = (apps: string[]) => apps.flatMap((app) => flatpakDirs.map((dir) => `${dir}/${app}`));
142
160
  return [
143
161
  "/usr/bin/google-chrome",
144
162
  "/usr/bin/google-chrome-stable",
@@ -151,7 +169,9 @@ function chromePathsForPlatform(): string[] {
151
169
  "/usr/bin/opera",
152
170
  "/snap/bin/chromium",
153
171
  "/snap/bin/brave",
154
- ...flatpakDirs.flatMap((dir) => flatpakApps.map((app) => `${dir}/${app}`)),
172
+ ...flatpakPaths(["com.google.Chrome", "org.chromium.Chromium"]),
173
+ ...playwrightChromiumPaths(home),
174
+ ...flatpakPaths(["com.microsoft.Edge", "com.brave.Browser"]),
155
175
  ];
156
176
  }
157
177