@johpaz/hive-agents 1.1.0 → 1.1.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.
Files changed (52) hide show
  1. package/README.md +15 -9
  2. package/dist/hive.js +2925 -1871
  3. package/dist/ui/assets/{A2UIPage-CS0VPY6a.js → A2UIPage-F1sUdZV7.js} +1 -1
  4. package/dist/ui/assets/{AgentCreateForm-DXkjtXaS.js → AgentCreateForm-CN5Gb9UN.js} +1 -1
  5. package/dist/ui/assets/{AgentDetailPage-DUIX_cuQ.js → AgentDetailPage-CzBnoKtH.js} +1 -1
  6. package/dist/ui/assets/{AgentNewPage-SNXz2wik.js → AgentNewPage-AGDjfAVf.js} +1 -1
  7. package/dist/ui/assets/{AgentsPage-CGsdgx5F.js → AgentsPage-BgKr7pAZ.js} +1 -1
  8. package/dist/ui/assets/{ApiClientPage-MNMjfSDs.js → ApiClientPage-Dq4nPse4.js} +1 -1
  9. package/dist/ui/assets/{ChannelsPage-BEwxWUcE.js → ChannelsPage-BuWItmp-.js} +1 -1
  10. package/dist/ui/assets/{DashboardPage-D6cRFKWW.js → DashboardPage-CB1aM87o.js} +1 -1
  11. package/dist/ui/assets/{LoginPage-ByYmIa2p.js → LoginPage-DBvwBCG6.js} +1 -1
  12. package/dist/ui/assets/{LogsPage-Bmk9rohg.js → LogsPage-Bc-oTBwY.js} +1 -1
  13. package/dist/ui/assets/{MeetingPage-Dm97Mbiw.js → MeetingPage-C2H5SxaQ.js} +1 -1
  14. package/dist/ui/assets/{ModelSelector-gubC8j_Q.js → ModelSelector-D0aJvoD9.js} +1 -1
  15. package/dist/ui/assets/{Office3DPage-Bfi-S2kG.js → Office3DPage-D5vwZkJa.js} +15 -15
  16. package/dist/ui/assets/ProvidersPage-BBBt4Hcz.js +1 -0
  17. package/dist/ui/assets/{RecoverPage-YY2QU-qh.js → RecoverPage-nq901JiE.js} +1 -1
  18. package/dist/ui/assets/{SettingsPage-DrafhhKw.js → SettingsPage-DQ5KZPAd.js} +1 -1
  19. package/dist/ui/assets/{SetupPage-LXnd2XbV.js → SetupPage-DeIGn-Uf.js} +1 -1
  20. package/dist/ui/assets/{VoicePage-p-hTMAq7.js → VoicePage-DJYsOsaU.js} +1 -1
  21. package/dist/ui/assets/{WebChatPage-B61ZDjQ8.js → WebChatPage-CRDN4OlP.js} +1 -1
  22. package/dist/ui/assets/{conversationsStore-BlwA3yd2.js → conversationsStore-BIs0iMhp.js} +1 -1
  23. package/dist/ui/assets/{dialog-B04KpdNt.js → dialog-DdbsUCv9.js} +1 -1
  24. package/dist/ui/assets/index-BD7hBA1d.css +2 -0
  25. package/dist/ui/assets/{index-DKJFLL3a.js → index-CpzwBwPg.js} +2 -2
  26. package/dist/ui/assets/{useAudioDevices-B2stUHvr.js → useAudioDevices-yU-wu-kt.js} +1 -1
  27. package/dist/ui/assets/{useHiveAgentsModelLoad-B4EjHvj4.js → useHiveAgentsModelLoad-29pOYRd9.js} +1 -1
  28. package/dist/ui/assets/{useProviders-B1NS24md.js → useProviders-CiBi4Dt6.js} +1 -1
  29. package/dist/ui/index.html +2 -2
  30. package/package.json +2 -2
  31. package/packages/cli/src/commands/onboard.ts +1 -1
  32. package/packages/core/src/agent/acceptance-checks.ts +25 -0
  33. package/packages/core/src/agent/agent-catalog.ts +23 -3
  34. package/packages/core/src/agent/jev-decisions.ts +125 -31
  35. package/packages/core/src/agent/jev-planner.ts +3 -3
  36. package/packages/core/src/agent/tool-selector.ts +41 -0
  37. package/packages/core/src/gateway/routes/providers.ts +4 -4
  38. package/packages/core/src/storage/bootstrap.ts +1 -1
  39. package/packages/core/src/storage/crypto.ts +110 -28
  40. package/packages/core/src/storage/seed.ts +38 -0
  41. package/packages/core/src/tools/code-agent/adapters.ts +110 -0
  42. package/packages/core/src/tools/code-agent/index.ts +193 -0
  43. package/packages/core/src/tools/index.ts +8 -0
  44. package/packages/core/src/tools/web/browser-backend.ts +22 -2
  45. package/packages/core/src/tools/web/index.ts +4 -0
  46. package/packages/core/src/tools/web/obscura.ts +860 -0
  47. package/packages/core/src/tools/web/webview-backend.ts +28 -6
  48. package/packages/skills/src/bundled/cli/external_code_agent/SKILL.md +69 -0
  49. package/packages/skills/src/bundled/web/obscura_browser/SKILL.md +69 -0
  50. package/packages/skills/src/bundled-data.generated.ts +837 -819
  51. package/dist/ui/assets/ProvidersPage-CSo0MYxd.js +0 -1
  52. package/dist/ui/assets/index-ByTufXPh.css +0 -2
@@ -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
 
@@ -16,6 +16,7 @@ import { browserTypeTool } from "./browser-type.ts";
16
16
  import { browserExtractTool } from "./browser-extract.ts";
17
17
  import { browserScriptTool } from "./browser-script.ts";
18
18
  import { browserWaitTool } from "./browser-wait.ts";
19
+ import { createObscuraTools } from "./obscura.ts";
19
20
  import { artifactInspectTool } from "./artifact-inspect.ts";
20
21
  import { artifactReadTool } from "./artifact-read.ts";
21
22
 
@@ -31,6 +32,8 @@ export function createTools(): Tool[] {
31
32
  browserExtractTool,
32
33
  browserScriptTool,
33
34
  browserWaitTool,
35
+ // Obscura: navegador headless sin Chromium, sesión viva y refs de elementos.
36
+ ...createObscuraTools(),
34
37
  artifactInspectTool,
35
38
  artifactReadTool,
36
39
  ];
@@ -47,5 +50,6 @@ export * from "./browser-extract.ts";
47
50
  export * from "./browser-script.ts";
48
51
  export * from "./browser-wait.ts";
49
52
  export * from "./browser-service.ts";
53
+ export * from "./obscura.ts";
50
54
  export * from "./artifact-inspect.ts";
51
55
  export * from "./artifact-read.ts";