@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
@@ -0,0 +1,860 @@
1
+ import { homedir } from "node:os"
2
+ /**
3
+ * Browser automation via Obscura (https://obscura.sh) — direct MCP 2.0 client.
4
+ *
5
+ * Architecture:
6
+ * - Spawns the Obscura CLI as an MCP server subprocess: `obscura mcp` (stdio).
7
+ * - Speaks MCP 2.0 (stateless revision 2026-07-28) FIRST: tries `server/discover`
8
+ * with the protocol version in `params._meta`. If the server does not know the
9
+ * RPC (e.g. Obscura 0.2.x negotiates 2024-11-05), it falls back automatically
10
+ * to the legacy `initialize` handshake. When Obscura ships MCP 2.0 support the
11
+ * client switches to the stateless flow with zero code changes.
12
+ * - The server keeps ONE live browser session: navigate first, then read/act.
13
+ * Element refs (e.g. "e3") come from browser_snapshot / browser_interactive_elements.
14
+ * - Auto-restart: if the subprocess dies, the next tool call respawns it.
15
+ * - Image/PDF content blocks are persisted to ~/.hive/screenshots/ and
16
+ * returned with both path and base64.
17
+ *
18
+ * Binary resolution order:
19
+ * 1. OBSCURA_PATH env var
20
+ * 2. `obscura` on PATH
21
+ * 3. ~/.hive/bin/obscura, then ~/.hivecode/bin/obscura (shared with hivecode)
22
+ *
23
+ * Tuning env vars: OBSCURA_STEALTH=1, OBSCURA_PROXY=<url>,
24
+ * OBSCURA_USER_AGENT=<ua>, OBSCURA_ALLOW_PRIVATE_NETWORK=1
25
+ */
26
+
27
+ import { existsSync, mkdirSync, writeFileSync, statSync } from "node:fs"
28
+ import { join } from "node:path"
29
+ import { logger } from "../../utils/logger.ts"
30
+ import type { Tool, ToolParameter } from "../types.ts"
31
+ import type { Subprocess } from "bun"
32
+
33
+ const log = logger.child("obscura")
34
+
35
+ // ── MCP 2.0 protocol constants ────────────────────────────────────────────────
36
+
37
+ /** MCP 2.0 — stateless revision of the Model Context Protocol. */
38
+ const MCP_PROTOCOL_2_0 = "2026-07-28"
39
+
40
+ /** Legacy fallback revision for servers that still use the initialize handshake. */
41
+ const MCP_LEGACY_FALLBACK = "2025-06-18"
42
+
43
+ const CLIENT_INFO = { name: "hive", version: "1.0" } as const
44
+
45
+ /**
46
+ * Per-request `_meta` prescribed by MCP 2.0 (2026-07-28): every request carries
47
+ * its protocol version, client identity and client capabilities.
48
+ */
49
+ function mcp2Meta(): Record<string, unknown> {
50
+ return {
51
+ "io.modelcontextprotocol/protocolVersion": MCP_PROTOCOL_2_0,
52
+ "io.modelcontextprotocol/clientInfo": CLIENT_INFO,
53
+ "io.modelcontextprotocol/clientCapabilities": {},
54
+ }
55
+ }
56
+
57
+ // ── Binary resolution ─────────────────────────────────────────────────────────
58
+
59
+ let cachedBin: string | null | undefined
60
+
61
+ export function resolveObscuraBin(): string | null {
62
+ if (cachedBin !== undefined) return cachedBin
63
+
64
+ // 1. OBSCURA_PATH (explicit override)
65
+ if (process.env.OBSCURA_PATH && existsSync(process.env.OBSCURA_PATH)) {
66
+ cachedBin = process.env.OBSCURA_PATH
67
+ return cachedBin
68
+ }
69
+
70
+ // 2. PATH (global install)
71
+ try {
72
+ const r = Bun.spawnSync(["which", "obscura"], {
73
+ stdout: "pipe", stderr: "ignore", stdin: "ignore",
74
+ })
75
+ if (r.exitCode === 0) {
76
+ const p = r.stdout.toString().trim()
77
+ if (p.length > 0) { cachedBin = p; return cachedBin }
78
+ }
79
+ } catch { /* ignore */ }
80
+
81
+ // 3. Instalación gestionada: ~/.hive/bin primero, ~/.hivecode/bin (hivecode) como respaldo
82
+ for (const dir of [join(homedir(), ".hive", "bin"), join(homedir(), ".hivecode", "bin")]) {
83
+ const managed = join(dir, process.platform === "win32" ? "obscura.exe" : "obscura")
84
+ if (existsSync(managed)) {
85
+ cachedBin = managed
86
+ return cachedBin
87
+ }
88
+ }
89
+
90
+ cachedBin = null
91
+ return null
92
+ }
93
+
94
+ /** True when the Obscura CLI is available (used for capability reporting). */
95
+ export function obscuraAvailable(): boolean {
96
+ return resolveObscuraBin() !== null
97
+ }
98
+
99
+ const INSTALL_ERROR =
100
+ "Obscura browser CLI not installed. See https://docs.obscura.sh/quickstart/installation " +
101
+ "and put the binary in PATH or ~/.hive/bin/obscura, or set OBSCURA_PATH. " +
102
+ "Use the browser_* tools (Chrome) meanwhile."
103
+
104
+ // ── MCP session (stdio JSON-RPC 2.0) ──────────────────────────────────────────
105
+
106
+ /** Bun.spawn stdin when piped is a FileSink (its type union also includes the fd number). */
107
+ interface StdinSink {
108
+ write(data: string | Uint8Array): number | Promise<number>
109
+ flush(): number | Promise<number>
110
+ end(): number | Promise<number>
111
+ }
112
+
113
+ function stdinSink(proc: Subprocess): StdinSink {
114
+ return proc.stdin as unknown as StdinSink
115
+ }
116
+
117
+ interface JsonRpcError { code: number; message: string; data?: unknown }
118
+
119
+ interface ContentBlock {
120
+ type: string
121
+ text?: string
122
+ data?: string // image block: base64 payload
123
+ mimeType?: string
124
+ resource?: { blob?: string; mimeType?: string; uri?: string; text?: string }
125
+ }
126
+
127
+ interface ToolCallResult {
128
+ content?: ContentBlock[]
129
+ isError?: boolean
130
+ structuredContent?: unknown
131
+ }
132
+
133
+ type PendingEntry = {
134
+ resolve: (value: unknown) => void
135
+ reject: (err: Error) => void
136
+ timer: ReturnType<typeof setTimeout>
137
+ }
138
+
139
+ class ObscuraMcpSession {
140
+ private proc: Subprocess | null = null
141
+ private nextId = 1
142
+ private pending = new Map<number, PendingEntry>()
143
+ private stdoutBuf = ""
144
+ private mode: "mcp2" | "legacy" = "legacy"
145
+ private negotiatedVersion: string | null = null
146
+ private serverName = "obscura-mcp"
147
+ private starting: Promise<void> | null = null
148
+
149
+ /** Ensure a live, negotiated MCP session (idempotent, concurrent-safe). */
150
+ ensure(): Promise<void> {
151
+ if (this.proc && this.proc.exitCode === null) return Promise.resolve()
152
+ this.starting ??= this.start().finally(() => { this.starting = null })
153
+ return this.starting
154
+ }
155
+
156
+ private async start(): Promise<void> {
157
+ const bin = resolveObscuraBin()
158
+ if (!bin) throw new Error(INSTALL_ERROR)
159
+
160
+ const args = ["mcp"]
161
+ if (process.env.OBSCURA_STEALTH === "1" || process.env.OBSCURA_STEALTH === "true") args.push("--stealth")
162
+ if (process.env.OBSCURA_PROXY) args.push("--proxy", process.env.OBSCURA_PROXY)
163
+ if (process.env.OBSCURA_USER_AGENT) args.push("--user-agent", process.env.OBSCURA_USER_AGENT)
164
+ if (process.env.OBSCURA_ALLOW_PRIVATE_NETWORK === "1" || process.env.OBSCURA_ALLOW_PRIVATE_NETWORK === "true") {
165
+ args.push("--allow-private-network")
166
+ }
167
+
168
+ log.info(`[obscura] starting MCP server: ${bin} ${args.join(" ")}`)
169
+ const proc = Bun.spawn([bin, ...args], {
170
+ stdin: "pipe",
171
+ stdout: "pipe",
172
+ stderr: "pipe",
173
+ })
174
+ this.proc = proc
175
+ this.stdoutBuf = ""
176
+
177
+ // Best-effort cleanup when the host process exits
178
+ try { process.once("exit", () => { try { proc.kill() } catch { /* ignore */ } }) } catch { /* ignore */ }
179
+
180
+ void this.readStdout(proc)
181
+ void this.readStderr(proc)
182
+
183
+ proc.exited.then((code) => {
184
+ if (this.proc === proc) this.proc = null
185
+ const err = new Error(`obscura mcp server exited (code ${code})`)
186
+ for (const [, entry] of this.pending) { clearTimeout(entry.timer); entry.reject(err) }
187
+ this.pending.clear()
188
+ if (code !== 0) log.warn(`[obscura] MCP server exited with code ${code}`)
189
+ }).catch(() => { /* killed */ })
190
+
191
+ await this.negotiate()
192
+ }
193
+
194
+ private async readStdout(proc: Subprocess): Promise<void> {
195
+ const reader = (proc.stdout as ReadableStream).getReader()
196
+ const decoder = new TextDecoder()
197
+ try {
198
+ while (true) {
199
+ const { done, value } = await reader.read()
200
+ if (done) break
201
+ this.stdoutBuf += decoder.decode(value, { stream: true })
202
+ let idx: number
203
+ while ((idx = this.stdoutBuf.indexOf("\n")) !== -1) {
204
+ const line = this.stdoutBuf.slice(0, idx).trim()
205
+ this.stdoutBuf = this.stdoutBuf.slice(idx + 1)
206
+ if (line) this.handleLine(line)
207
+ }
208
+ }
209
+ } catch { /* stream closed */ }
210
+ }
211
+
212
+ private async readStderr(proc: Subprocess): Promise<void> {
213
+ const reader = (proc.stderr as ReadableStream).getReader()
214
+ const decoder = new TextDecoder()
215
+ try {
216
+ while (true) {
217
+ const { done, value } = await reader.read()
218
+ if (done) break
219
+ const t = decoder.decode(value, { stream: true }).trim()
220
+ if (t) log.debug(`[obscura:mcp] ${t.slice(0, 300)}`)
221
+ }
222
+ } catch { /* stream closed */ }
223
+ }
224
+
225
+ private handleLine(line: string): void {
226
+ let msg: {
227
+ jsonrpc?: string
228
+ id?: number
229
+ method?: string
230
+ params?: unknown
231
+ result?: unknown
232
+ error?: JsonRpcError
233
+ }
234
+ try { msg = JSON.parse(line) } catch {
235
+ log.debug(`[obscura:mcp] non-JSON stdout: ${line.slice(0, 200)}`)
236
+ return
237
+ }
238
+
239
+ // Response to a pending request
240
+ if (typeof msg.id === "number") {
241
+ const entry = this.pending.get(msg.id)
242
+ if (!entry) return
243
+ this.pending.delete(msg.id)
244
+ clearTimeout(entry.timer)
245
+ if (msg.error) {
246
+ entry.reject(Object.assign(new Error(msg.error.message ?? "MCP error"), { code: msg.error.code }))
247
+ } else {
248
+ entry.resolve(msg.result)
249
+ }
250
+ return
251
+ }
252
+
253
+ // Notification from the server
254
+ if (msg.method) log.debug(`[obscura:mcp] notification: ${msg.method}`)
255
+ }
256
+
257
+ /** Low-level request — assumes the subprocess is alive. */
258
+ private rawRequest(method: string, params: unknown, timeoutMs: number): Promise<unknown> {
259
+ const proc = this.proc
260
+ if (!proc) return Promise.reject(new Error("obscura MCP server not running"))
261
+
262
+ const id = this.nextId++
263
+ return new Promise((resolve, reject) => {
264
+ const timer = setTimeout(() => {
265
+ this.pending.delete(id)
266
+ reject(new Error(`MCP ${method} timed out after ${timeoutMs}ms`))
267
+ }, timeoutMs)
268
+ this.pending.set(id, {
269
+ resolve,
270
+ reject,
271
+ timer,
272
+ })
273
+ try {
274
+ const sink = stdinSink(proc)
275
+ sink.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n")
276
+ sink.flush()
277
+ } catch (err) {
278
+ this.pending.delete(id)
279
+ clearTimeout(timer)
280
+ reject(err as Error)
281
+ }
282
+ })
283
+ }
284
+
285
+ /** Notification — fire and forget (no id). */
286
+ private notify(method: string): void {
287
+ const proc = this.proc
288
+ if (!proc) return
289
+ try {
290
+ const sink = stdinSink(proc)
291
+ sink.write(JSON.stringify({ jsonrpc: "2.0", method }) + "\n")
292
+ sink.flush()
293
+ } catch { /* ignore */ }
294
+ }
295
+
296
+ /**
297
+ * MCP 2.0-first negotiation:
298
+ * 1. `server/discover` with protocol version in `_meta` (2026-07-28 flow).
299
+ * 2. On unknown-method / error / timeout → legacy `initialize` handshake.
300
+ */
301
+ private async negotiate(): Promise<void> {
302
+ // 1. MCP 2.0 (stateless) — no handshake required
303
+ try {
304
+ const discovered = await this.rawRequest("server/discover", { _meta: mcp2Meta() }, 5_000) as
305
+ { serverInfo?: { name?: string; version?: string } } | null
306
+ this.mode = "mcp2"
307
+ this.negotiatedVersion = MCP_PROTOCOL_2_0
308
+ this.serverName = discovered?.serverInfo?.name ?? "obscura-mcp"
309
+ log.info(`[obscura] MCP 2.0 (${MCP_PROTOCOL_2_0}) stateless session — ${this.serverName}`)
310
+ return
311
+ } catch {
312
+ // fall through to the legacy handshake
313
+ }
314
+
315
+ // 2. Legacy handshake — request 2.0 first; if the server rejects the unknown
316
+ // version, retry with a known-good legacy revision.
317
+ let init: { protocolVersion?: string; serverInfo?: { name?: string; version?: string } } | null = null
318
+ for (const revision of [MCP_PROTOCOL_2_0, MCP_LEGACY_FALLBACK]) {
319
+ try {
320
+ init = await this.rawRequest("initialize", {
321
+ protocolVersion: revision,
322
+ capabilities: {},
323
+ clientInfo: CLIENT_INFO,
324
+ }, 5_000) as typeof init
325
+ break
326
+ } catch (err) {
327
+ log.debug(`[obscura] initialize(${revision}) failed: ${(err as Error).message}`)
328
+ }
329
+ }
330
+ if (!init) throw new Error("obscura MCP server did not complete the initialize handshake")
331
+
332
+ this.mode = "legacy"
333
+ this.negotiatedVersion = init.protocolVersion ?? "2024-11-05"
334
+ this.serverName = init.serverInfo?.name ?? "obscura-mcp"
335
+ this.notify("notifications/initialized")
336
+ log.info(
337
+ `[obscura] legacy MCP session (server ${this.serverName}, negotiated ${this.negotiatedVersion})`,
338
+ )
339
+ }
340
+
341
+ /** JSON-RPC request on the live session (auto-starts / auto-restarts). */
342
+ async rpc(method: string, params: unknown, timeoutMs = 60_000): Promise<unknown> {
343
+ await this.ensure()
344
+ const request = this.mode === "mcp2"
345
+ ? { ...(params as object ?? {}), _meta: mcp2Meta() }
346
+ : params
347
+ return this.rawRequest(method, request, timeoutMs)
348
+ }
349
+
350
+ /** tools/call with content-block unpacking. */
351
+ async callTool(name: string, args: Record<string, unknown>, timeoutMs = 60_000): Promise<object> {
352
+ const result = await this.rpc("tools/call", { name, arguments: args }, timeoutMs) as ToolCallResult
353
+ return unpackToolResult(name, result)
354
+ }
355
+
356
+ /** tools/list — for diagnostics and capability discovery. */
357
+ async listTools(): Promise<Array<{ name: string; description?: string; inputSchema?: unknown }>> {
358
+ const result = await this.rpc("tools/list", {}, 15_000) as
359
+ { tools?: Array<{ name: string; description?: string; inputSchema?: unknown }> } | null
360
+ return result?.tools ?? []
361
+ }
362
+
363
+ get protocolMode(): "mcp2" | "legacy" { return this.mode }
364
+ get protocolVersion(): string | null { return this.negotiatedVersion }
365
+
366
+ async close(): Promise<void> {
367
+ const proc = this.proc
368
+ this.proc = null
369
+ if (!proc) return
370
+ try { stdinSink(proc).end() } catch { /* ignore */ }
371
+ try { proc.kill() } catch { /* ignore */ }
372
+ }
373
+ }
374
+
375
+ let session: ObscuraMcpSession | null = null
376
+ function getSession(): ObscuraMcpSession {
377
+ session ??= new ObscuraMcpSession()
378
+ return session
379
+ }
380
+
381
+ /** Kill the Obscura MCP subprocess (used on shutdown). */
382
+ export async function closeObscura(): Promise<void> {
383
+ await session?.close()
384
+ }
385
+
386
+ // ── Content unpacking ─────────────────────────────────────────────────────────
387
+
388
+ const ASSET_DIR = () => join(homedir(), ".hive", "screenshots")
389
+
390
+ function saveAsset(toolName: string, base64: string, mimeType: string): { path: string; bytes: number } {
391
+ const dir = ASSET_DIR()
392
+ mkdirSync(dir, { recursive: true })
393
+ const ext = mimeType.includes("pdf") ? "pdf" : (mimeType.split("/")[1] ?? "bin").replace(/[^a-z0-9]/gi, "")
394
+ const file = join(dir, `${toolName}-${Date.now()}.${ext}`)
395
+ writeFileSync(file, Buffer.from(base64, "base64"))
396
+ return { path: file, bytes: statSync(file).size }
397
+ }
398
+
399
+ function unpackToolResult(toolName: string, result: ToolCallResult): object {
400
+ const blocks = result.content ?? []
401
+ const texts: string[] = []
402
+ const images: Array<{ path: string; bytes: number; mimeType: string }> = []
403
+
404
+ for (const block of blocks) {
405
+ if (block.type === "text" && block.text) {
406
+ texts.push(block.text)
407
+ } else if (block.type === "image" && block.data) {
408
+ const mimeType = block.mimeType ?? "image/png"
409
+ const saved = saveAsset(toolName, block.data, mimeType)
410
+ images.push({ ...saved, mimeType })
411
+ } else if (block.type === "resource" && block.resource?.blob) {
412
+ const mimeType = block.resource.mimeType ?? "application/octet-stream"
413
+ const saved = saveAsset(toolName, block.resource.blob, mimeType)
414
+ images.push({ ...saved, mimeType })
415
+ }
416
+ }
417
+
418
+ const text = texts.join("\n").trim()
419
+
420
+ if (result.isError) {
421
+ return { ok: false, error: text || `obscura tool ${toolName} failed`, tool: toolName }
422
+ }
423
+
424
+ if (images.length > 0) {
425
+ const [first] = images
426
+ return {
427
+ ok: true,
428
+ path: first.path,
429
+ mimeType: first.mimeType,
430
+ bytes: first.bytes,
431
+ ...(text ? { text } : {}),
432
+ ...(images.length > 1 ? { additional_assets: images.slice(1).map(i => i.path) } : {}),
433
+ }
434
+ }
435
+
436
+ return { ok: true, text }
437
+ }
438
+
439
+ // ── Tool factory ──────────────────────────────────────────────────────────────
440
+
441
+ /**
442
+ * Build a hivecode Tool backed by an Obscura MCP tool.
443
+ * Only the properties declared in `properties` are forwarded to the server
444
+ * (Obscura marks several schemas additionalProperties:false); `timeoutMs`
445
+ * is a client-side kill switch and never reaches the wire.
446
+ */
447
+ /** Hive-side name of an Obscura server tool: browser_snapshot → obscura_snapshot. */
448
+ function hiveName(serverName: string): string {
449
+ return serverName.replace(/^browser_/, "obscura_")
450
+ }
451
+
452
+ function obscuraTool(
453
+ name: string,
454
+ description: string,
455
+ properties: Record<string, ToolParameter>,
456
+ required: string[] = [],
457
+ opts: { timeoutMs?: number } = {},
458
+ ): Tool {
459
+ return {
460
+ // The Obscura server knows these as browser_*; Hive keeps its own Chrome-backed
461
+ // browser_* tools, so the Obscura ones are exposed as obscura_*.
462
+ name: hiveName(name),
463
+ description: description.replaceAll("browser_", "obscura_"),
464
+ parameters: {
465
+ type: "object",
466
+ properties,
467
+ ...(required.length > 0 ? { required } : {}),
468
+ },
469
+ async execute(args: Record<string, unknown>): Promise<string | object> {
470
+ if (!obscuraAvailable()) return { ok: false, error: INSTALL_ERROR }
471
+
472
+ // Forward only schema-declared keys
473
+ const serverArgs: Record<string, unknown> = {}
474
+ for (const key of Object.keys(properties)) {
475
+ if (args[key] !== undefined && args[key] !== null) serverArgs[key] = args[key]
476
+ }
477
+
478
+ const timeoutMs = args.timeoutMs !== undefined ? Number(args.timeoutMs) : opts.timeoutMs
479
+ log.info(`[obscura] ${name} ${summarizeArgs(serverArgs)}`)
480
+ try {
481
+ return await getSession().callTool(name, serverArgs, timeoutMs ?? 60_000)
482
+ } catch (err) {
483
+ const message = (err as Error).message
484
+ log.warn(`[obscura] ${name} failed: ${message}`)
485
+ return { ok: false, error: message, tool: name }
486
+ }
487
+ },
488
+ }
489
+ }
490
+
491
+ function summarizeArgs(args: Record<string, unknown>): string {
492
+ const keys = Object.keys(args)
493
+ if (keys.length === 0) return ""
494
+ const parts: string[] = []
495
+ for (const key of keys.slice(0, 3)) {
496
+ const value = String(args[key])
497
+ parts.push(`${key}=${value.length > 60 ? `${value.slice(0, 57)}…` : value}`)
498
+ }
499
+ if (keys.length > 3) parts.push(`+${keys.length - 3}`)
500
+ return parts.join(" ")
501
+ }
502
+
503
+ const urlParam: ToolParameter = { type: "string", description: "URL to navigate to (http/https)" }
504
+ const refParam: ToolParameter = { type: "string", description: "Element ref from a recent obscura_snapshot / obscura_interactive_elements (e.g. 'e3')" }
505
+ const selectorParam: ToolParameter = { type: "string", description: "CSS selector (fallback when no ref is available)" }
506
+ const maxCharsParam: ToolParameter = { type: "number", description: "Truncate returned text to this many characters (default 4000)" }
507
+ const timeoutParam: ToolParameter = { type: "number", description: "Client-side timeout in milliseconds (default 60000)" }
508
+
509
+ // ── The full Obscura browser toolset ──────────────────────────────────────────
510
+
511
+ export function createObscuraTools(): Tool[] {
512
+ return [
513
+ // ── Navigation and lifecycle ────────────────────────────────────────────
514
+ obscuraTool(
515
+ "browser_navigate",
516
+ "Navigate to a URL and wait for the page to load, keeping a live browser session for " +
517
+ "subsequent browser_* tools. Returns the final URL and title only: read the page next with " +
518
+ "browser_snapshot or browser_markdown. Spanish keywords: navegar, abrir página, ir a sitio web, cargar url, visitar",
519
+ {
520
+ url: urlParam,
521
+ waitUntil: { type: "string", enum: ["load", "domcontentloaded", "networkidle0"], description: "Navigation wait condition (default: load)" },
522
+ timeoutMs: timeoutParam,
523
+ },
524
+ ["url"],
525
+ { timeoutMs: 90_000 },
526
+ ),
527
+ obscuraTool(
528
+ "browser_back",
529
+ "Navigate back in the page history (browser back button). Requires an active session from browser_navigate. " +
530
+ "Spanish keywords: atrás, volver, página anterior, regresar",
531
+ {},
532
+ ),
533
+ obscuraTool(
534
+ "browser_forward",
535
+ "Navigate forward in the page history. Requires an active session from browser_navigate. " +
536
+ "Spanish keywords: adelante, página siguiente, avanzar",
537
+ {},
538
+ ),
539
+ obscuraTool(
540
+ "browser_reload",
541
+ "Reload the current page. Requires an active session from browser_navigate. " +
542
+ "Spanish keywords: recargar, refrescar página, actualizar página, f5",
543
+ {},
544
+ ),
545
+ obscuraTool(
546
+ "browser_close",
547
+ "Close the current browser page and reset the session state. Spanish keywords: cerrar navegador, cerrar página, terminar sesión",
548
+ {},
549
+ ),
550
+
551
+ // ── Read the page ───────────────────────────────────────────────────────
552
+ obscuraTool(
553
+ "browser_snapshot",
554
+ "Get the current page as text: URL, title, readable body text and interactive element refs. " +
555
+ "Preferred first read after navigating. Spanish keywords: snapshot página, contenido página, ver página, texto página, captura textual",
556
+ { max_chars: maxCharsParam },
557
+ ),
558
+ obscuraTool(
559
+ "browser_markdown",
560
+ "Extract the current page as Markdown (headings, paragraphs, lists, links, code blocks). " +
561
+ "Token-dense structured content instead of plain text. Spanish keywords: markdown, extraer markdown, contenido estructurado, página en markdown",
562
+ { max_chars: maxCharsParam },
563
+ ),
564
+ obscuraTool(
565
+ "browser_links",
566
+ "List every anchor link on the current page as one JSON object per line {text, href}. " +
567
+ "Spanish keywords: listar enlaces, ver links, urls página, hipervínculos, enlaces",
568
+ {
569
+ limit: { type: "number", description: "Max number of links to return (default 100)" },
570
+ internal_only: { type: "boolean", description: "Only return links on the same origin as the current page" },
571
+ },
572
+ ),
573
+ obscuraTool(
574
+ "browser_interactive_elements",
575
+ "List every clickable/typeable element with a stable ref ID and a brief description. " +
576
+ "Use BEFORE clicking or filling to act by ref instead of guessing CSS selectors. " +
577
+ "Spanish keywords: elementos interactivos, botones, campos, inputs, refs, elementos clicables",
578
+ { limit: { type: "number", description: "Max number of elements (default 100)" } },
579
+ ),
580
+ obscuraTool(
581
+ "browser_detect_forms",
582
+ "List every <form> on the page with its action URL, method and a description of each " +
583
+ "input/textarea/select. Understand a form before filling it. Spanish keywords: detectar formularios, ver formularios, campos formulario, estructura formulario",
584
+ {},
585
+ ),
586
+ obscuraTool(
587
+ "browser_extract",
588
+ "Extract a structured object from the page given a map of {field_name: css_selector}. " +
589
+ "Use 'selector@attr' for attributes (e.g. 'a@href') and 'field[]' suffix for arrays. " +
590
+ "Spanish keywords: extraer datos, scraping, extraer estructura, datos página, seleccionar campos",
591
+ {
592
+ schema: {
593
+ type: "object",
594
+ description: "Map of field_name to CSS selector. Suffix selector with '@attr' for attribute, suffix field name with '[]' for array.",
595
+ additionalProperties: { type: "string" },
596
+ },
597
+ },
598
+ ["schema"],
599
+ ),
600
+ obscuraTool(
601
+ "browser_get_attribute",
602
+ "Read an attribute of an element (href, src, value, class, data-*). Returns the raw value or empty string. " +
603
+ "Spanish keywords: leer atributo, obtener atributo, href, valor elemento, atributo html",
604
+ { attribute: { type: "string", description: "Attribute name (e.g. href, value, src)" }, ref: refParam, selector: selectorParam },
605
+ ["attribute"],
606
+ ),
607
+ obscuraTool(
608
+ "browser_count",
609
+ "Count how many elements on the page match a CSS selector. Cheap existence/pagination probe. " +
610
+ "Spanish keywords: contar elementos, cuántos, número de elementos, contar coincidencias",
611
+ { selector: selectorParam },
612
+ ["selector"],
613
+ ),
614
+ obscuraTool(
615
+ "browser_search",
616
+ "Find substring matches in the visible page text with surrounding context. " +
617
+ "Spanish keywords: buscar en página, encontrar texto, buscar contenido, texto en página",
618
+ {
619
+ query: { type: "string", description: "Substring to find in the visible page text" },
620
+ case_sensitive: { type: "boolean", description: "Case-sensitive match (default false)" },
621
+ limit: { type: "number", description: "Max matches to return (default 10)" },
622
+ context_chars: { type: "number", description: "Chars on each side of the match (default 80)" },
623
+ },
624
+ ["query"],
625
+ ),
626
+
627
+ // ── Interact ─────────────────────────────────────────────────────────────
628
+ obscuraTool(
629
+ "browser_click",
630
+ "Click an element by ref (preferred, from browser_snapshot/browser_interactive_elements) or CSS selector. " +
631
+ "Spanish keywords: hacer clic, presionar botón, clickear, pulsar, click",
632
+ { ref: refParam, selector: selectorParam },
633
+ ),
634
+ obscuraTool(
635
+ "browser_fill",
636
+ "Set the value of an input element (replaces existing value). Pass ref (preferred) or selector. " +
637
+ "Spanish keywords: llenar campo, rellenar input, establecer valor, completar campo",
638
+ { ref: refParam, selector: selectorParam, value: { type: "string", description: "Value to set" } },
639
+ ["value"],
640
+ ),
641
+ obscuraTool(
642
+ "browser_type",
643
+ "Type text into an input element (appends to existing value). Pass ref (preferred) or selector. " +
644
+ "Spanish keywords: escribir en campo, teclear texto, introducir texto, escribir input",
645
+ { ref: refParam, selector: selectorParam, text: { type: "string", description: "Text to type" } },
646
+ ["text"],
647
+ ),
648
+ obscuraTool(
649
+ "browser_fill_form",
650
+ "Fill multiple inputs in one call: fields is an array of {ref?, selector?, value, type?} where " +
651
+ "type is text (default), check, uncheck or select. Optional submit_ref/submit_selector clicks after filling. " +
652
+ "Spanish keywords: llenar formulario, completar formulario, rellenar form, enviar formulario",
653
+ {
654
+ fields: {
655
+ type: "array",
656
+ description: "Fields to fill: {ref?, selector?, value, type?}",
657
+ items: {
658
+ type: "object",
659
+ properties: {
660
+ ref: { type: "string" },
661
+ selector: { type: "string" },
662
+ value: { type: "string" },
663
+ type: { type: "string", enum: ["text", "check", "uncheck", "select"] },
664
+ },
665
+ },
666
+ },
667
+ submit_ref: { type: "string", description: "Optional element to click after filling (e.g. submit button ref)" },
668
+ submit_selector: { type: "string", description: "Optional CSS selector to click after filling" },
669
+ },
670
+ ["fields"],
671
+ ),
672
+ obscuraTool(
673
+ "browser_press_key",
674
+ "Dispatch a keyboard event (Enter, Tab, Escape…) on an element or the document. " +
675
+ "Spanish keywords: presionar tecla, pulsar enter, teclado, keydown",
676
+ { key: { type: "string", description: "Key name (e.g. Enter, Tab, Escape)" }, selector: selectorParam },
677
+ ["key"],
678
+ ),
679
+ obscuraTool(
680
+ "browser_select_option",
681
+ "Select an option from a <select> element by value or visible text. " +
682
+ "Spanish keywords: seleccionar opción, elegir opción, dropdown, lista desplegable, select",
683
+ { selector: selectorParam, value: { type: "string", description: "Value or text of the option to select" } },
684
+ ["selector", "value"],
685
+ ),
686
+ obscuraTool(
687
+ "browser_scroll",
688
+ "Scroll the page or an element: direction top/bottom/up/down/left/right, amount in pixels. " +
689
+ "Use 'bottom' to trigger infinite-scroll loaders. Spanish keywords: scroll, desplazar, bajar página, subir página, desplazamiento",
690
+ {
691
+ direction: { type: "string", enum: ["top", "bottom", "up", "down", "left", "right"], description: "Scroll direction (default 'down')" },
692
+ amount: { type: "number", description: "Pixels (default: one viewport)" },
693
+ ref: refParam,
694
+ selector: selectorParam,
695
+ },
696
+ ),
697
+
698
+ // ── Wait and run JS ──────────────────────────────────────────────────────
699
+ obscuraTool(
700
+ "browser_wait_for",
701
+ "Wait for a CSS selector to appear in the DOM (default 30s). Spanish keywords: esperar elemento, aguardar selector, wait selector, esperar carga",
702
+ {
703
+ selector: { type: "string", description: "CSS selector to wait for" },
704
+ timeout: { type: "number", description: "Server-side timeout in seconds (default 30)" },
705
+ timeoutMs: timeoutParam,
706
+ },
707
+ ["selector"],
708
+ { timeoutMs: 60_000 },
709
+ ),
710
+ obscuraTool(
711
+ "browser_wait_for_text",
712
+ "Wait until a substring appears anywhere in the rendered page text — for result messages and notifications. " +
713
+ "Spanish keywords: esperar texto, aguardar mensaje, esperar resultado, wait texto",
714
+ {
715
+ text: { type: "string", description: "Substring to wait for" },
716
+ timeout: { type: "number", description: "Server-side timeout in seconds (default 30)" },
717
+ timeoutMs: timeoutParam,
718
+ },
719
+ ["text"],
720
+ { timeoutMs: 60_000 },
721
+ ),
722
+ obscuraTool(
723
+ "browser_evaluate",
724
+ "Evaluate a JavaScript expression in the page context and return the result as JSON. " +
725
+ "Spanish keywords: ejecutar javascript, evaluar expresión, js en página, script navegador, eval",
726
+ { expression: { type: "string", description: "JavaScript expression to evaluate" }, timeoutMs: timeoutParam },
727
+ ["expression"],
728
+ { timeoutMs: 30_000 },
729
+ ),
730
+
731
+ // ── Diagnostics ──────────────────────────────────────────────────────────
732
+ obscuraTool(
733
+ "browser_network_requests",
734
+ "List the network requests made by the current page (URLs, statuses, timings). " +
735
+ "Spanish keywords: ver peticiones red, requests, tráfico red, llamadas http página, network",
736
+ {},
737
+ ),
738
+ obscuraTool(
739
+ "browser_console_messages",
740
+ "List the console messages logged by the current page (logs, warnings, errors). " +
741
+ "Spanish keywords: ver consola, logs página, mensajes consola, errores javascript, console",
742
+ {},
743
+ ),
744
+
745
+ // ── Visual output ────────────────────────────────────────────────────────
746
+ obscuraTool(
747
+ "browser_screenshot",
748
+ "Capture the current rendered viewport as a PNG (saved to ~/.hivecode/screenshots/, returned with path + base64). " +
749
+ "Use for canvas/visual verification; prefer browser_snapshot for text. Spanish keywords: captura de pantalla, screenshot, fotografiar página, imagen página, png",
750
+ {
751
+ width: { type: "number", description: "Optional CSS-pixel capture width" },
752
+ height: { type: "number", description: "Optional CSS-pixel capture height" },
753
+ timeoutMs: timeoutParam,
754
+ },
755
+ [],
756
+ { timeoutMs: 45_000 },
757
+ ),
758
+ obscuraTool(
759
+ "browser_pdf",
760
+ "Export the current rendered document as a paginated PDF (saved to ~/.hivecode/screenshots/). " +
761
+ "Spanish keywords: exportar pdf, guardar pdf, página a pdf, documento pdf",
762
+ {
763
+ landscape: { type: "boolean" },
764
+ print_background: { type: "boolean" },
765
+ scale: { type: "number", description: "0.1–2" },
766
+ paper_width: { type: "number", description: "Paper width in inches" },
767
+ paper_height: { type: "number", description: "Paper height in inches" },
768
+ margin_top: { type: "number", description: "Top margin in inches" },
769
+ margin_bottom: { type: "number", description: "Bottom margin in inches" },
770
+ margin_left: { type: "number", description: "Left margin in inches" },
771
+ margin_right: { type: "number", description: "Right margin in inches" },
772
+ timeoutMs: timeoutParam,
773
+ },
774
+ [],
775
+ { timeoutMs: 45_000 },
776
+ ),
777
+
778
+ // ── Cookies and storage ──────────────────────────────────────────────────
779
+ obscuraTool(
780
+ "browser_get_cookies",
781
+ "Return all cookies in the browser's cookie jar as one JSON object per line. " +
782
+ "Spanish keywords: ver cookies, obtener cookies, cookies sesión, leer cookies",
783
+ { domain: { type: "string", description: "Filter to cookies on this domain (default: all)" } },
784
+ ),
785
+ obscuraTool(
786
+ "browser_set_cookie",
787
+ "Add or replace a cookie in the jar — skip a login flow when you already have a session token. " +
788
+ "Spanish keywords: setear cookie, establecer cookie, inyectar cookie, cookie sesión",
789
+ {
790
+ name: { type: "string" },
791
+ value: { type: "string" },
792
+ domain: { type: "string", description: "e.g. example.com or .example.com" },
793
+ path: { type: "string", description: "default '/'" },
794
+ secure: { type: "boolean" },
795
+ http_only: { type: "boolean" },
796
+ },
797
+ ["name", "value", "domain"],
798
+ ),
799
+ obscuraTool(
800
+ "browser_clear_cookies",
801
+ "Wipe every cookie from the jar. Spanish keywords: borrar cookies, limpiar cookies, eliminar cookies",
802
+ {},
803
+ ),
804
+ obscuraTool(
805
+ "browser_storage_state",
806
+ "Export the full session state (cookies + localStorage + sessionStorage) as JSON — save it to skip a login on a later run. " +
807
+ "Spanish keywords: exportar sesión, estado sesión, guardar sesión, storage state",
808
+ {},
809
+ ),
810
+ obscuraTool(
811
+ "browser_set_storage_state",
812
+ "Restore a session state previously returned by browser_storage_state to bring an authenticated session back. " +
813
+ "Spanish keywords: restaurar sesión, importar sesión, cargar sesión guardada, login guardado",
814
+ { state: { type: "object", description: "{cookies: [...], origins: [{origin, localStorage: [...], sessionStorage: [...]}]}" } },
815
+ ["state"],
816
+ ),
817
+
818
+ // ── Tabs ──────────────────────────────────────────────────────────────────
819
+ obscuraTool(
820
+ "browser_tab_new",
821
+ "Open a new tab (isolated browser page); subsequent tool calls operate on the most recent tab. " +
822
+ "Spanish keywords: nueva pestaña, abrir pestaña, nuevo tab",
823
+ { url: { type: "string", description: "Optional URL to navigate the new tab to" } },
824
+ ),
825
+ obscuraTool(
826
+ "browser_tab_list",
827
+ "List all open tabs with their ID, URL, title and which one is active. " +
828
+ "Spanish keywords: listar pestañas, ver pestañas, tabs abiertos",
829
+ {},
830
+ ),
831
+ obscuraTool(
832
+ "browser_tab_switch",
833
+ "Switch the active tab — all subsequent tool calls target this tab. " +
834
+ "Spanish keywords: cambiar pestaña, cambiar tab, activar pestaña",
835
+ { tab_id: { type: "string", description: "Tab ID from browser_tab_list" } },
836
+ ["tab_id"],
837
+ ),
838
+ obscuraTool(
839
+ "browser_tab_close",
840
+ "Close a tab by ID (default: the active tab). Spanish keywords: cerrar pestaña, cerrar tab",
841
+ { tab_id: { type: "string", description: "Tab ID to close (default: active tab)" } },
842
+ ),
843
+ ]
844
+ }
845
+
846
+ /** Names of every Obscura-backed browser tool (single source of truth). */
847
+ export function obscuraToolNames(): string[] {
848
+ return createObscuraTools().map(t => t.name)
849
+ }
850
+
851
+ /** List the tools the Obscura MCP server actually exposes (diagnostics). */
852
+ export async function listObscuraTools() {
853
+ if (!obscuraAvailable()) return { ok: false as const, error: INSTALL_ERROR, tools: [] as Array<{ name: string; description?: string; inputSchema?: unknown }> }
854
+ try {
855
+ const tools = await getSession().listTools()
856
+ return { ok: true as const, tools, protocol: getSession().protocolVersion, mode: getSession().protocolMode }
857
+ } catch (err) {
858
+ return { ok: false as const, error: (err as Error).message, tools: [] as Array<{ name: string; description?: string; inputSchema?: unknown }> }
859
+ }
860
+ }