@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.
- package/README.md +15 -9
- package/dist/hive.js +2925 -1871
- package/dist/ui/assets/{A2UIPage-CS0VPY6a.js → A2UIPage-F1sUdZV7.js} +1 -1
- package/dist/ui/assets/{AgentCreateForm-DXkjtXaS.js → AgentCreateForm-CN5Gb9UN.js} +1 -1
- package/dist/ui/assets/{AgentDetailPage-DUIX_cuQ.js → AgentDetailPage-CzBnoKtH.js} +1 -1
- package/dist/ui/assets/{AgentNewPage-SNXz2wik.js → AgentNewPage-AGDjfAVf.js} +1 -1
- package/dist/ui/assets/{AgentsPage-CGsdgx5F.js → AgentsPage-BgKr7pAZ.js} +1 -1
- package/dist/ui/assets/{ApiClientPage-MNMjfSDs.js → ApiClientPage-Dq4nPse4.js} +1 -1
- package/dist/ui/assets/{ChannelsPage-BEwxWUcE.js → ChannelsPage-BuWItmp-.js} +1 -1
- package/dist/ui/assets/{DashboardPage-D6cRFKWW.js → DashboardPage-CB1aM87o.js} +1 -1
- package/dist/ui/assets/{LoginPage-ByYmIa2p.js → LoginPage-DBvwBCG6.js} +1 -1
- package/dist/ui/assets/{LogsPage-Bmk9rohg.js → LogsPage-Bc-oTBwY.js} +1 -1
- package/dist/ui/assets/{MeetingPage-Dm97Mbiw.js → MeetingPage-C2H5SxaQ.js} +1 -1
- package/dist/ui/assets/{ModelSelector-gubC8j_Q.js → ModelSelector-D0aJvoD9.js} +1 -1
- package/dist/ui/assets/{Office3DPage-Bfi-S2kG.js → Office3DPage-D5vwZkJa.js} +15 -15
- package/dist/ui/assets/ProvidersPage-BBBt4Hcz.js +1 -0
- package/dist/ui/assets/{RecoverPage-YY2QU-qh.js → RecoverPage-nq901JiE.js} +1 -1
- package/dist/ui/assets/{SettingsPage-DrafhhKw.js → SettingsPage-DQ5KZPAd.js} +1 -1
- package/dist/ui/assets/{SetupPage-LXnd2XbV.js → SetupPage-DeIGn-Uf.js} +1 -1
- package/dist/ui/assets/{VoicePage-p-hTMAq7.js → VoicePage-DJYsOsaU.js} +1 -1
- package/dist/ui/assets/{WebChatPage-B61ZDjQ8.js → WebChatPage-CRDN4OlP.js} +1 -1
- package/dist/ui/assets/{conversationsStore-BlwA3yd2.js → conversationsStore-BIs0iMhp.js} +1 -1
- package/dist/ui/assets/{dialog-B04KpdNt.js → dialog-DdbsUCv9.js} +1 -1
- package/dist/ui/assets/index-BD7hBA1d.css +2 -0
- package/dist/ui/assets/{index-DKJFLL3a.js → index-CpzwBwPg.js} +2 -2
- package/dist/ui/assets/{useAudioDevices-B2stUHvr.js → useAudioDevices-yU-wu-kt.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-B4EjHvj4.js → useHiveAgentsModelLoad-29pOYRd9.js} +1 -1
- package/dist/ui/assets/{useProviders-B1NS24md.js → useProviders-CiBi4Dt6.js} +1 -1
- package/dist/ui/index.html +2 -2
- package/package.json +2 -2
- package/packages/cli/src/commands/onboard.ts +1 -1
- package/packages/core/src/agent/acceptance-checks.ts +25 -0
- package/packages/core/src/agent/agent-catalog.ts +23 -3
- package/packages/core/src/agent/jev-decisions.ts +125 -31
- package/packages/core/src/agent/jev-planner.ts +3 -3
- package/packages/core/src/agent/tool-selector.ts +41 -0
- package/packages/core/src/gateway/routes/providers.ts +4 -4
- package/packages/core/src/storage/bootstrap.ts +1 -1
- package/packages/core/src/storage/crypto.ts +110 -28
- package/packages/core/src/storage/seed.ts +38 -0
- package/packages/core/src/tools/code-agent/adapters.ts +110 -0
- package/packages/core/src/tools/code-agent/index.ts +193 -0
- package/packages/core/src/tools/index.ts +8 -0
- package/packages/core/src/tools/web/browser-backend.ts +22 -2
- package/packages/core/src/tools/web/index.ts +4 -0
- package/packages/core/src/tools/web/obscura.ts +860 -0
- package/packages/core/src/tools/web/webview-backend.ts +28 -6
- package/packages/skills/src/bundled/cli/external_code_agent/SKILL.md +69 -0
- package/packages/skills/src/bundled/web/obscura_browser/SKILL.md +69 -0
- package/packages/skills/src/bundled-data.generated.ts +837 -819
- package/dist/ui/assets/ProvidersPage-CSo0MYxd.js +0 -1
- package/dist/ui/assets/index-ByTufXPh.css +0 -2
|
@@ -12,10 +12,20 @@ export const JEV_MODEL = "typesafe/jev-1.13"
|
|
|
12
12
|
const ENDPOINT = "https://openrouter.ai/api/alpha/decisions"
|
|
13
13
|
const TIMEOUT_MS = 3000
|
|
14
14
|
const COOLDOWN_MS = 60_000
|
|
15
|
+
/** Kev: same oracle served from the HiveAgents LLM host (llm.hiveagents.io), tried before Jev. */
|
|
16
|
+
export const KEV_MODEL = "Kev-9B-Q8_0.gguf"
|
|
17
|
+
const KEV_DEFAULT_BASE = "https://llm.hiveagents.io"
|
|
18
|
+
const KEV_READY_TTL_MS = 30_000
|
|
19
|
+
const KEV_STATUS_TIMEOUT_MS = 2000
|
|
20
|
+
export type DecisionBackend = "kev" | "jev"
|
|
15
21
|
let failures = 0
|
|
16
22
|
let cooldownUntil = 0
|
|
17
23
|
let lastError: string | null = null
|
|
18
24
|
let lastSuccessAt: number | null = null
|
|
25
|
+
let kevFailures = 0
|
|
26
|
+
let kevCooldownUntil = 0
|
|
27
|
+
let kevReadyCache: { at: number; ready: boolean } | null = null
|
|
28
|
+
let lastBackend: DecisionBackend | null = null
|
|
19
29
|
let decisionSequence = 0
|
|
20
30
|
/** Since gateway boot; the office shows them as the oracle's running contribution. */
|
|
21
31
|
const totals = { decisions: 0, savedTokens: 0, costUsd: 0 }
|
|
@@ -23,16 +33,19 @@ const totals = { decisions: 0, savedTokens: 0, costUsd: 0 }
|
|
|
23
33
|
export type JevQuestion =
|
|
24
34
|
| { type: "choice"; instructions: string; criteria: Record<string, string> }
|
|
25
35
|
| { type: "noul"; instructions: string; criteria?: { true: string; false: string } }
|
|
36
|
+
| { type: "score"; instructions: string; criteria?: Record<string, string> }
|
|
26
37
|
|
|
27
38
|
export type JevAnswer =
|
|
28
39
|
| { type: "choice"; choice: string; confidence: number; probabilities: Record<string, number> }
|
|
29
40
|
| { type: "noul"; noul: number }
|
|
41
|
+
| { type: "score"; score: number }
|
|
30
42
|
|
|
31
43
|
export interface JevResult {
|
|
32
44
|
answers: Record<string, JevAnswer>
|
|
33
45
|
inputTokens: number
|
|
34
46
|
costUsd: number
|
|
35
47
|
latencyMs: number
|
|
48
|
+
backend: DecisionBackend
|
|
36
49
|
}
|
|
37
50
|
|
|
38
51
|
export async function getJevKey(): Promise<string | null> {
|
|
@@ -41,8 +54,45 @@ export async function getJevKey(): Promise<string | null> {
|
|
|
41
54
|
return (await loadProviderApiKey("openrouter")) || process.env.OPENROUTER_API_KEY || null
|
|
42
55
|
}
|
|
43
56
|
|
|
57
|
+
/** Kev is available when the HiveAgents LLM provider is on and has a key; readiness is checked separately. */
|
|
58
|
+
async function getKevConfig(): Promise<{ key: string; base: string } | null> {
|
|
59
|
+
const provider = await (await col<ProviderDoc>("providers")).get("hiveagents")
|
|
60
|
+
if (!provider?.doc.enabled || !provider.doc.active) return null
|
|
61
|
+
const key = (await loadProviderApiKey("hiveagents")) || process.env.HIVEAGENTS_API_KEY || null
|
|
62
|
+
if (!key) return null
|
|
63
|
+
return { key, base: provider.doc.base_url?.replace(/\/v1\/?$/, "").replace(/\/$/, "") || KEV_DEFAULT_BASE }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** `kev-decision.service` is toggled with systemd on the lab PC, so ask the host; cached to spare every turn a request. */
|
|
67
|
+
async function isKevReady(cfg: { key: string; base: string }, fetcher: typeof fetch): Promise<boolean> {
|
|
68
|
+
if (Date.now() < kevCooldownUntil) return false
|
|
69
|
+
if (kevReadyCache && Date.now() - kevReadyCache.at < KEV_READY_TTL_MS) return kevReadyCache.ready
|
|
70
|
+
let ready = false
|
|
71
|
+
try {
|
|
72
|
+
const response = await fetcher(`${cfg.base}/api/decisions/status`, {
|
|
73
|
+
headers: { Authorization: `Bearer ${cfg.key}` },
|
|
74
|
+
signal: AbortSignal.timeout(KEV_STATUS_TIMEOUT_MS),
|
|
75
|
+
})
|
|
76
|
+
if (response.status === 401 || response.status === 403) kevCooldownUntil = Date.now() + COOLDOWN_MS
|
|
77
|
+
else if (response.ok) {
|
|
78
|
+
const data = await response.json().catch(() => null) as { ready?: unknown } | null
|
|
79
|
+
ready = data?.ready === true
|
|
80
|
+
}
|
|
81
|
+
} catch { /* host unreachable: Kev is simply off */ }
|
|
82
|
+
kevReadyCache = { at: Date.now(), ready }
|
|
83
|
+
return ready
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** True when any decision backend could answer; callers use it to skip building questions. */
|
|
87
|
+
export async function hasDecisionBackend(): Promise<boolean> {
|
|
88
|
+
if (await getJevKey().catch(() => null)) return true
|
|
89
|
+
const kev = await getKevConfig().catch(() => null)
|
|
90
|
+
return !!kev && Date.now() >= kevCooldownUntil
|
|
91
|
+
}
|
|
92
|
+
|
|
44
93
|
export interface JevStatus {
|
|
45
94
|
state: "off" | "ready" | "fallback"
|
|
95
|
+
backend: DecisionBackend | null
|
|
46
96
|
lastError: string | null
|
|
47
97
|
lastSuccessAt: number | null
|
|
48
98
|
totals: { decisions: number; savedTokens: number; costUsd: number }
|
|
@@ -50,10 +100,16 @@ export interface JevStatus {
|
|
|
50
100
|
|
|
51
101
|
export async function getJevStatus(): Promise<JevStatus> {
|
|
52
102
|
const key = await getJevKey().catch(() => null)
|
|
103
|
+
const kev = await getKevConfig().catch(() => null)
|
|
104
|
+
const jevOk = !!key && Date.now() >= cooldownUntil && !lastError
|
|
105
|
+
const kevOk = !!kev && Date.now() >= kevCooldownUntil && kevFailures === 0
|
|
106
|
+
// Before any decision has been served, report who would answer: Kev only when its host says ready.
|
|
107
|
+
const kevReady = kevOk && kev ? await isKevReady(kev, fetch).catch(() => false) : false
|
|
53
108
|
return {
|
|
54
|
-
state: !key ? "off" :
|
|
55
|
-
|
|
56
|
-
|
|
109
|
+
state: !key && !kev ? "off" : jevOk || kevReady ? "ready" : "fallback",
|
|
110
|
+
backend: kevReady ? "kev" : lastBackend ?? (jevOk ? "jev" : null),
|
|
111
|
+
lastError: key || kev ? lastError : null,
|
|
112
|
+
lastSuccessAt: key || kev ? lastSuccessAt : null,
|
|
57
113
|
totals: { ...totals },
|
|
58
114
|
}
|
|
59
115
|
}
|
|
@@ -85,63 +141,101 @@ export function resetJevStatus(): void {
|
|
|
85
141
|
cooldownUntil = 0
|
|
86
142
|
lastError = null
|
|
87
143
|
lastSuccessAt = null
|
|
144
|
+
kevFailures = 0
|
|
145
|
+
kevCooldownUntil = 0
|
|
146
|
+
kevReadyCache = null
|
|
147
|
+
lastBackend = null
|
|
88
148
|
broadcastStatus()
|
|
89
149
|
}
|
|
90
150
|
|
|
151
|
+
function validateAnswers(questions: Record<string, JevQuestion>, data: { answers?: Record<string, JevAnswer> }): Record<string, JevAnswer> {
|
|
152
|
+
const answers: Record<string, JevAnswer> = {}
|
|
153
|
+
const unit = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= 1
|
|
154
|
+
for (const [name, question] of Object.entries(questions)) {
|
|
155
|
+
const answer = data.answers?.[name]
|
|
156
|
+
if (question.type === "choice") {
|
|
157
|
+
if (answer?.type !== "choice" || !Object.hasOwn(question.criteria, answer.choice) || !unit(answer.confidence)) {
|
|
158
|
+
throw new Error(`Invalid choice answer: ${name}`)
|
|
159
|
+
}
|
|
160
|
+
} else if (question.type === "score") {
|
|
161
|
+
if (answer?.type !== "score" || !unit(answer.score)) throw new Error(`Invalid score answer: ${name}`)
|
|
162
|
+
} else if (answer?.type !== "noul" || !unit(answer.noul)) {
|
|
163
|
+
throw new Error(`Invalid noul answer: ${name}`)
|
|
164
|
+
}
|
|
165
|
+
answers[name] = answer
|
|
166
|
+
}
|
|
167
|
+
return answers
|
|
168
|
+
}
|
|
169
|
+
|
|
91
170
|
export async function askJev(
|
|
92
171
|
state: unknown,
|
|
93
172
|
questions: Record<string, JevQuestion>,
|
|
94
173
|
options: { fetcher?: typeof fetch; signal?: AbortSignal } = {},
|
|
95
174
|
): Promise<JevResult | null> {
|
|
175
|
+
if (Object.keys(questions).length === 0) return null
|
|
176
|
+
const fetcher = options.fetcher ?? fetch
|
|
177
|
+
const kev = await getKevConfig().catch(() => null)
|
|
178
|
+
if (kev && await isKevReady(kev, fetcher)) {
|
|
179
|
+
const result = await requestDecision("kev", `${kev.base}/v1/systemone`, kev.key, KEV_MODEL, state, questions, options)
|
|
180
|
+
if (result || options.signal?.aborted) return result
|
|
181
|
+
}
|
|
96
182
|
const key = await getJevKey().catch(() => null)
|
|
97
|
-
if (!key || Date.now() < cooldownUntil
|
|
183
|
+
if (!key || Date.now() < cooldownUntil) return null
|
|
184
|
+
return requestDecision("jev", ENDPOINT, key, JEV_MODEL, state, questions, options)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function requestDecision(
|
|
188
|
+
backend: DecisionBackend,
|
|
189
|
+
endpoint: string,
|
|
190
|
+
key: string,
|
|
191
|
+
model: string,
|
|
192
|
+
state: unknown,
|
|
193
|
+
questions: Record<string, JevQuestion>,
|
|
194
|
+
options: { fetcher?: typeof fetch; signal?: AbortSignal },
|
|
195
|
+
): Promise<JevResult | null> {
|
|
98
196
|
const started = performance.now()
|
|
197
|
+
const label = backend === "kev" ? "Kev" : "OpenRouter"
|
|
99
198
|
try {
|
|
100
|
-
const response = await (options.fetcher ?? fetch)(
|
|
199
|
+
const response = await (options.fetcher ?? fetch)(endpoint, {
|
|
101
200
|
method: "POST",
|
|
102
201
|
headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
|
|
103
|
-
body: JSON.stringify({ model
|
|
202
|
+
body: JSON.stringify({ model, state, questions }),
|
|
104
203
|
signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(TIMEOUT_MS)]) : AbortSignal.timeout(TIMEOUT_MS),
|
|
105
204
|
})
|
|
106
205
|
if (!response.ok) {
|
|
107
|
-
if (response.status === 401 || response.status === 403)
|
|
108
|
-
|
|
206
|
+
if (response.status === 401 || response.status === 403) {
|
|
207
|
+
if (backend === "kev") kevCooldownUntil = Date.now() + COOLDOWN_MS
|
|
208
|
+
else cooldownUntil = Date.now() + COOLDOWN_MS
|
|
209
|
+
}
|
|
210
|
+
throw new Error(`${label} HTTP ${response.status}`)
|
|
109
211
|
}
|
|
110
212
|
const data = await response.json() as {
|
|
111
213
|
answers?: Record<string, JevAnswer>
|
|
112
214
|
usage?: { input_tokens?: number; output_tokens?: number; cost?: number }
|
|
113
215
|
}
|
|
114
|
-
const answers
|
|
115
|
-
for (const [name, question] of Object.entries(questions)) {
|
|
116
|
-
const answer = data.answers?.[name]
|
|
117
|
-
if (question.type === "choice") {
|
|
118
|
-
if (answer?.type !== "choice" || !Object.hasOwn(question.criteria, answer.choice) ||
|
|
119
|
-
!Number.isFinite(answer.confidence) || answer.confidence < 0 || answer.confidence > 1) {
|
|
120
|
-
throw new Error(`Invalid choice answer: ${name}`)
|
|
121
|
-
}
|
|
122
|
-
} else if (answer?.type !== "noul" || !Number.isFinite(answer.noul) || answer.noul < 0 || answer.noul > 1) {
|
|
123
|
-
throw new Error(`Invalid noul answer: ${name}`)
|
|
124
|
-
}
|
|
125
|
-
answers[name] = answer
|
|
126
|
-
}
|
|
216
|
+
const answers = validateAnswers(questions, data)
|
|
127
217
|
const recovered = lastError !== null
|
|
128
|
-
|
|
218
|
+
if (backend === "kev") kevFailures = 0
|
|
219
|
+
else failures = 0
|
|
129
220
|
lastError = null
|
|
130
221
|
lastSuccessAt = Date.now()
|
|
131
|
-
if (recovered) broadcastStatus()
|
|
222
|
+
if (recovered || lastBackend !== backend) { lastBackend = backend; broadcastStatus() }
|
|
132
223
|
const inputTokens = data.usage?.input_tokens ?? 0
|
|
133
|
-
|
|
134
|
-
|
|
224
|
+
// Kev runs on our own hardware: no per-token cost.
|
|
225
|
+
const costUsd = backend === "kev" ? 0 : data.usage?.cost ?? inputTokens * 0.042 / 1_000_000
|
|
226
|
+
log.info(`Decision served: backend=${backend} questions=${Object.keys(questions).join(",")} latency_ms=${Math.round(performance.now() - started)} input_tokens=${inputTokens} cost_usd=${costUsd}`)
|
|
135
227
|
if (inputTokens > 0) {
|
|
136
|
-
|
|
228
|
+
const provider = backend === "kev" ? "hiveagents" : "openrouter"
|
|
229
|
+
recordUsage({ provider, model: catalogModelKey(provider, model), inputTokens, outputTokens: data.usage?.output_tokens ?? 0, latencyMs: Math.round(performance.now() - started) })
|
|
137
230
|
}
|
|
138
|
-
return { answers, inputTokens, costUsd, latencyMs: Math.round(performance.now() - started) }
|
|
231
|
+
return { answers, inputTokens, costUsd, latencyMs: Math.round(performance.now() - started), backend }
|
|
139
232
|
} catch (error) {
|
|
140
233
|
if (options.signal?.aborted) return null
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
234
|
+
lastError = error instanceof Error ? error.message : `${label} unavailable`
|
|
235
|
+
if (backend === "kev") {
|
|
236
|
+
if (++kevFailures >= 3) { kevCooldownUntil = Date.now() + COOLDOWN_MS; kevReadyCache = null }
|
|
237
|
+
} else if (++failures >= 3) cooldownUntil = Date.now() + COOLDOWN_MS
|
|
238
|
+
log.warn(`Decision fallback (${backend}): ${lastError}`)
|
|
145
239
|
broadcastStatus()
|
|
146
240
|
return null
|
|
147
241
|
}
|
|
@@ -5,7 +5,7 @@ import type { PlaybookRule } from "./playbook-selector"
|
|
|
5
5
|
import { MINIMAL_TOOLS } from "./minimal-loadout"
|
|
6
6
|
import { searchCapabilities } from "./capability-search"
|
|
7
7
|
import { mcpToolFullName } from "./tool-selector"
|
|
8
|
-
import { askJev,
|
|
8
|
+
import { askJev, hasDecisionBackend, type JevAnswer, type JevQuestion } from "./jev-decisions"
|
|
9
9
|
import { col } from "../storage/hive"
|
|
10
10
|
import type { AgentDoc, McpServerDoc, McpToolDoc } from "../storage/collections"
|
|
11
11
|
|
|
@@ -112,7 +112,7 @@ export async function planJevContext(input: {
|
|
|
112
112
|
/** From describeSwarmCapabilities; absent means "unknown", not "none". */
|
|
113
113
|
swarm?: { mcpServers: JevMcpServer[]; specialists: JevSpecialist[] }
|
|
114
114
|
}): Promise<JevContextPlan | null> {
|
|
115
|
-
if (!await
|
|
115
|
+
if (!await hasDecisionBackend().catch(() => false)) return null
|
|
116
116
|
const { objective, messages, tools, allTools, skills, isWorker } = input
|
|
117
117
|
const mandatoryMessages = new Set<number>()
|
|
118
118
|
// The last two exchanges carry the thread's immediate referents ("hazlo otra
|
|
@@ -218,7 +218,7 @@ export async function planJevContext(input: {
|
|
|
218
218
|
*/
|
|
219
219
|
export async function jevWantsParallel(calls: Array<{ function: { name: string; arguments: unknown } }>): Promise<{ parallel: boolean; decision?: JevDecisionMetrics } | null> {
|
|
220
220
|
if (calls.length < 2) return null
|
|
221
|
-
if (!await
|
|
221
|
+
if (!await hasDecisionBackend().catch(() => false)) return null
|
|
222
222
|
const names = calls.map(c => c.function.name)
|
|
223
223
|
const readOnly = names.every(n => /^(fs_read|fs_list|fs_glob|fs_exists|web_search|web_fetch|memory_read|memory_search|artifact_read|artifact_inspect|task_status|agent_find)$/.test(n))
|
|
224
224
|
const delegated = names.every(n => n === "task_delegate")
|
|
@@ -135,6 +135,8 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
|
|
|
135
135
|
// Code execution
|
|
136
136
|
{ name: "cli_exec", description: "Execute shell commands, run bash scripts and system commands. Spanish keywords: ejecutar comando, terminal, línea de comandos, bash, script, comando del sistema", category: "cli", abstractionLevel: "atomic" },
|
|
137
137
|
|
|
138
|
+
{ name: "code_agent_run", description: "Delegate a coding task to an external coding-agent CLI (Claude Code, Codex, OpenCode, Kimi) in an isolated git worktree; returns summary, changed files and diff. Spanish keywords: agente de código, delegar programación, codex, claude code, opencode, kimi, implementar con otro agente", category: "cli", abstractionLevel: "atomic" },
|
|
139
|
+
|
|
138
140
|
// Web tools
|
|
139
141
|
{ name: "web_search", description: "Search web for current information, find up-to-date news facts and research. Spanish keywords: buscar en internet, buscar web, información, noticias, investigación, buscar", category: "web", abstractionLevel: "atomic" },
|
|
140
142
|
{ name: "web_fetch", description: "Fetch content from URL, download and extract content from web pages. Spanish keywords: obtener página, descargar web, extraer contenido, obtener contenido, página web", category: "web", abstractionLevel: "atomic" },
|
|
@@ -168,6 +170,45 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
|
|
|
168
170
|
{ name: "browser_script", description: "Execute arbitrary JavaScript in the browser page context and get the result. Spanish keywords: ejecutar javascript, script, código, función, evaluar, js en página", category: "browser", abstractionLevel: "atomic" },
|
|
169
171
|
{ name: "browser_wait", description: "Wait for an element to appear or condition to be met on the page. Spanish keywords: esperar, wait, condición, elemento, selector, aguardar carga", category: "browser", abstractionLevel: "atomic" },
|
|
170
172
|
|
|
173
|
+
// Obscura (headless browser, live session, element refs)
|
|
174
|
+
{ name: "obscura_navigate", 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", category: "browser", abstractionLevel: "atomic" },
|
|
175
|
+
{ name: "obscura_back", 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", category: "browser", abstractionLevel: "atomic" },
|
|
176
|
+
{ name: "obscura_forward", description: "Navigate forward in the page history. Requires an active session from obscura_navigate. Spanish keywords: adelante, página siguiente, avanzar", category: "browser", abstractionLevel: "atomic" },
|
|
177
|
+
{ name: "obscura_reload", description: "Reload the current page. Requires an active session from obscura_navigate. Spanish keywords: recargar, refrescar página, actualizar página, f5", category: "browser", abstractionLevel: "atomic" },
|
|
178
|
+
{ name: "obscura_close", description: "Close the current browser page and reset the session state. Spanish keywords: cerrar navegador, cerrar página, terminar sesión", category: "browser", abstractionLevel: "atomic" },
|
|
179
|
+
{ name: "obscura_snapshot", 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", category: "browser", abstractionLevel: "atomic" },
|
|
180
|
+
{ name: "obscura_markdown", 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", category: "browser", abstractionLevel: "atomic" },
|
|
181
|
+
{ name: "obscura_links", 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", category: "browser", abstractionLevel: "atomic" },
|
|
182
|
+
{ name: "obscura_interactive_elements", 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", category: "browser", abstractionLevel: "atomic" },
|
|
183
|
+
{ name: "obscura_detect_forms", 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", category: "browser", abstractionLevel: "atomic" },
|
|
184
|
+
{ name: "obscura_extract", 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", category: "browser", abstractionLevel: "atomic" },
|
|
185
|
+
{ name: "obscura_get_attribute", 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", category: "browser", abstractionLevel: "atomic" },
|
|
186
|
+
{ name: "obscura_count", 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", category: "browser", abstractionLevel: "atomic" },
|
|
187
|
+
{ name: "obscura_search", 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", category: "browser", abstractionLevel: "atomic" },
|
|
188
|
+
{ name: "obscura_click", 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", category: "browser", abstractionLevel: "atomic" },
|
|
189
|
+
{ name: "obscura_fill", 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", category: "browser", abstractionLevel: "atomic" },
|
|
190
|
+
{ name: "obscura_type", 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", category: "browser", abstractionLevel: "atomic" },
|
|
191
|
+
{ name: "obscura_fill_form", 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", category: "browser", abstractionLevel: "atomic" },
|
|
192
|
+
{ name: "obscura_press_key", description: "Dispatch a keyboard event (Enter, Tab, Escape…) on an element or the document. Spanish keywords: presionar tecla, pulsar enter, teclado, keydown", category: "browser", abstractionLevel: "atomic" },
|
|
193
|
+
{ name: "obscura_select_option", 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", category: "browser", abstractionLevel: "atomic" },
|
|
194
|
+
{ name: "obscura_scroll", 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", category: "browser", abstractionLevel: "atomic" },
|
|
195
|
+
{ name: "obscura_wait_for", description: "Wait for a CSS selector to appear in the DOM (default 30s). Spanish keywords: esperar elemento, aguardar selector, wait selector, esperar carga", category: "browser", abstractionLevel: "atomic" },
|
|
196
|
+
{ name: "obscura_wait_for_text", 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", category: "browser", abstractionLevel: "atomic" },
|
|
197
|
+
{ name: "obscura_evaluate", 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", category: "browser", abstractionLevel: "atomic" },
|
|
198
|
+
{ name: "obscura_network_requests", 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", category: "browser", abstractionLevel: "atomic" },
|
|
199
|
+
{ name: "obscura_console_messages", 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", category: "browser", abstractionLevel: "atomic" },
|
|
200
|
+
{ name: "obscura_screenshot", 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", category: "browser", abstractionLevel: "atomic" },
|
|
201
|
+
{ name: "obscura_pdf", 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", category: "browser", abstractionLevel: "atomic" },
|
|
202
|
+
{ name: "obscura_get_cookies", 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", category: "browser", abstractionLevel: "atomic" },
|
|
203
|
+
{ name: "obscura_set_cookie", 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", category: "browser", abstractionLevel: "atomic" },
|
|
204
|
+
{ name: "obscura_clear_cookies", description: "Wipe every cookie from the jar. Spanish keywords: borrar cookies, limpiar cookies, eliminar cookies", category: "browser", abstractionLevel: "atomic" },
|
|
205
|
+
{ name: "obscura_storage_state", 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", category: "browser", abstractionLevel: "atomic" },
|
|
206
|
+
{ name: "obscura_set_storage_state", 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", category: "browser", abstractionLevel: "atomic" },
|
|
207
|
+
{ name: "obscura_tab_new", 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", category: "browser", abstractionLevel: "atomic" },
|
|
208
|
+
{ name: "obscura_tab_list", 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", category: "browser", abstractionLevel: "atomic" },
|
|
209
|
+
{ name: "obscura_tab_switch", description: "Switch the active tab — all subsequent tool calls target this tab. Spanish keywords: cambiar pestaña, cambiar tab, activar pestaña", category: "browser", abstractionLevel: "atomic" },
|
|
210
|
+
{ name: "obscura_tab_close", description: "Close a tab by ID (default: the active tab). Spanish keywords: cerrar pestaña, cerrar tab", category: "browser", abstractionLevel: "atomic" },
|
|
211
|
+
|
|
171
212
|
// A2UI v0.9 rich interactive surfaces
|
|
172
213
|
{ name: "a2ui_create_surface", description: "Create A2UI v0.9 surface for rich interactive UIs with forms, dashboards, and workflows. Spanish keywords: crear superficie A2UI, iniciar UI interactiva, crear formulario rico, interfaz A2UI, crear surface", category: "a2ui", abstractionLevel: "orchestration" },
|
|
173
214
|
{ name: "a2ui_update_components", description: "Send A2UI v0.9 components to an existing surface (Text, Button, TextField, Row, Column, Card, etc.). Spanish keywords: enviar componentes A2UI, actualizar UI, renderizar componentes, A2UI componentes, update components", category: "a2ui", abstractionLevel: "atomic" },
|
|
@@ -42,7 +42,7 @@ export async function handleGetProviders(req: Request, addCorsHeaders: (r: Respo
|
|
|
42
42
|
has_api_key: apiKey ? 1 : 0,
|
|
43
43
|
has_headers: Object.keys(headers).length > 0 ? 1 : 0,
|
|
44
44
|
masked_api_key: apiKey ? maskApiKey(apiKey) : null,
|
|
45
|
-
...(p.doc.id === "openrouter" ? { jev: jevStatus } : {}),
|
|
45
|
+
...(p.doc.id === "openrouter" || p.doc.id === "hiveagents" ? { jev: jevStatus } : {}),
|
|
46
46
|
models: providerModels,
|
|
47
47
|
}
|
|
48
48
|
}))
|
|
@@ -78,7 +78,7 @@ export async function handleToggleProvider(req: Request, addCorsHeaders: (r: Res
|
|
|
78
78
|
}
|
|
79
79
|
|
|
80
80
|
await updateDoc<ProviderDoc>("providers", providerId, { active: !!active, enabled: !!active })
|
|
81
|
-
if (providerId === "openrouter") resetJevStatus()
|
|
81
|
+
if (providerId === "openrouter" || providerId === "hiveagents") resetJevStatus()
|
|
82
82
|
|
|
83
83
|
// Cascade: activate/deactivate all models for this provider
|
|
84
84
|
await updateManyByIndex<ModelDoc>("models", "provider_id", providerId, { active: !!active, enabled: !!active })
|
|
@@ -113,7 +113,7 @@ export async function handleUpdateProvider(req: Request, addCorsHeaders: (r: Res
|
|
|
113
113
|
}
|
|
114
114
|
if (body.clearApiKey === true) {
|
|
115
115
|
await deleteProviderApiKey(id)
|
|
116
|
-
if (id === "openrouter") resetJevStatus()
|
|
116
|
+
if (id === "openrouter" || id === "hiveagents") resetJevStatus()
|
|
117
117
|
}
|
|
118
118
|
if (body.headers) {
|
|
119
119
|
await storeProviderHeaders(id, body.headers)
|
|
@@ -123,7 +123,7 @@ export async function handleUpdateProvider(req: Request, addCorsHeaders: (r: Res
|
|
|
123
123
|
|
|
124
124
|
if (Object.keys(patch).length > 0) {
|
|
125
125
|
await updateDoc<ProviderDoc>("providers", id, patch).catch(() => { /* provider not found */ })
|
|
126
|
-
if (id === "openrouter" && (patch.active !== undefined || patch.enabled !== undefined)) resetJevStatus()
|
|
126
|
+
if ((id === "openrouter" || id === "hiveagents") && (patch.active !== undefined || patch.enabled !== undefined)) resetJevStatus()
|
|
127
127
|
|
|
128
128
|
// Cascade active/enabled changes to models
|
|
129
129
|
if (patch.active !== undefined) {
|
|
@@ -160,7 +160,7 @@ export async function ensureHiveDb(): Promise<void> {
|
|
|
160
160
|
// Mint the master key before anything can save an API key, so a fresh
|
|
161
161
|
// install is durable from the first keystroke rather than after a restart
|
|
162
162
|
// has already dropped the secret.
|
|
163
|
-
ensureSecretsBackend();
|
|
163
|
+
await ensureSecretsBackend();
|
|
164
164
|
await ensureSeedData();
|
|
165
165
|
|
|
166
166
|
await ensureLegacyThreads();
|
|
@@ -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
|
|
19
|
-
//
|
|
20
|
-
//
|
|
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
|
-
*
|
|
147
|
-
* will be stored. Called once at boot so an operator sees the answer
|
|
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
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
309
|
-
*
|
|
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
|
|
316
|
-
|
|
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
|
-
|
|
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]
|
|
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
|
-
|
|
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`
|