@johpaz/hive-agents 1.0.0 → 1.0.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 (165) hide show
  1. package/README.md +25 -11
  2. package/dist/hive.js +22498 -6889
  3. package/dist/tool-worker.js +6 -2
  4. package/dist/ui/assets/A2UIPage-BRpjnMss.js +8 -0
  5. package/dist/ui/assets/{AgentCreateForm-g1mQnIoJ.js → AgentCreateForm-ASjKD7Js.js} +1 -1
  6. package/dist/ui/assets/{AgentDetailPage-C3XkU4Ll.js → AgentDetailPage-bqJ-MS40.js} +1 -1
  7. package/dist/ui/assets/AgentNewPage-CPaf2C3u.js +1 -0
  8. package/dist/ui/assets/{AgentsPage-CNA778Eo.js → AgentsPage-BIpLG0V6.js} +1 -1
  9. package/dist/ui/assets/{ApiClientPage-t5DpKhmA.js → ApiClientPage-dRckcgrN.js} +1 -1
  10. package/dist/ui/assets/{ChannelsPage-yY6t0YTU.js → ChannelsPage-BX_hPtiN.js} +2 -2
  11. package/dist/ui/assets/{DashboardPage-BSeNSYg5.js → DashboardPage-KMaMaFf4.js} +2 -2
  12. package/dist/ui/assets/{LoginPage-eT5zDRDa.js → LoginPage-Zchu-f16.js} +1 -1
  13. package/dist/ui/assets/{LogsPage-Gczzzsdh.js → LogsPage-6Po7_T2u.js} +1 -1
  14. package/dist/ui/assets/{MeetingPage-Bu4aMMNR.js → MeetingPage-qrpYGVD-.js} +1 -1
  15. package/dist/ui/assets/{ModelSelector-nNOrW3te.js → ModelSelector-C8ny_pxu.js} +1 -1
  16. package/dist/ui/assets/{Office3DPage-B_iXEbyv.js → Office3DPage-BYwLMTCl.js} +2 -2
  17. package/dist/ui/assets/ProvidersPage-DP9v_1ko.js +1 -0
  18. package/dist/ui/assets/{RecoverPage-DMqSasKk.js → RecoverPage-BXwjLfap.js} +1 -1
  19. package/dist/ui/assets/SettingsPage-DD7GKtS6.js +9 -0
  20. package/dist/ui/assets/{SetupPage-DhcRbGgg.js → SetupPage-D7YX2io-.js} +1 -1
  21. package/dist/ui/assets/{WebChatPage-CWXjW4Hn.js → WebChatPage-C3cgimxd.js} +1 -1
  22. package/dist/ui/assets/{activity-CQuPevhB.js → activity-DZKL7dg4.js} +1 -1
  23. package/dist/ui/assets/{agentCapabilities-CDC6y91E.js → agentCapabilities-DuGs07XP.js} +1 -1
  24. package/dist/ui/assets/arrow-left-12JaXVoH.js +1 -0
  25. package/dist/ui/assets/arrow-right-Dbui5p0d.js +1 -0
  26. package/dist/ui/assets/arrow-up-right-CJBtXRrp.js +1 -0
  27. package/dist/ui/assets/{calendar-Be23hQGc.js → calendar-CkDsc4OJ.js} +1 -1
  28. package/dist/ui/assets/check-DxOMIDcl.js +1 -0
  29. package/dist/ui/assets/chevron-down-CObv-xyx.js +1 -0
  30. package/dist/ui/assets/chevron-left-C0mqwhLU.js +1 -0
  31. package/dist/ui/assets/chevron-right-jCt1h8Kw.js +1 -0
  32. package/dist/ui/assets/chevron-up-DX_5iw7O.js +1 -0
  33. package/dist/ui/assets/{circle-alert-BDVHxmAz.js → circle-alert-BkP6x0zQ.js} +1 -1
  34. package/dist/ui/assets/circle-check-CXC2AiMS.js +1 -0
  35. package/dist/ui/assets/{circle-x-Cb2Yer4s.js → circle-x-h4OJiHV3.js} +1 -1
  36. package/dist/ui/assets/{copy-33tZrzc9.js → copy-BtpYEEvV.js} +1 -1
  37. package/dist/ui/assets/{dialog-KOZKWbib.js → dialog-CO1WrPJc.js} +1 -1
  38. package/dist/ui/assets/{download-CiQqqXyz.js → download-aPuVaZik.js} +1 -1
  39. package/dist/ui/assets/{earth-DCvN7ynm.js → earth-sc8YJMc0.js} +1 -1
  40. package/dist/ui/assets/{ellipsis-vertical-BybFZDk2.js → ellipsis-vertical-DEBZJGzY.js} +1 -1
  41. package/dist/ui/assets/{external-link-0iNNBvZm.js → external-link-D_C_678M.js} +1 -1
  42. package/dist/ui/assets/{eye-C8sKSSkg.js → eye-BfN613fx.js} +1 -1
  43. package/dist/ui/assets/{file-text-DO8jqiJK.js → file-text-Bth5pPZX.js} +1 -1
  44. package/dist/ui/assets/gauge-DypSzSOE.js +1 -0
  45. package/dist/ui/assets/{history-BtTD1kDo.js → history-njH_sPSo.js} +1 -1
  46. package/dist/ui/assets/{index-Bejlp-R1.js → index-D-9yCvjP.js} +4 -4
  47. package/dist/ui/assets/index-wML8DaUo.css +2 -0
  48. package/dist/ui/assets/{info-mpk1tsNC.js → info-Def2ZFeP.js} +1 -1
  49. package/dist/ui/assets/{key-CoQ0qtXt.js → key-D8bkDl83.js} +1 -1
  50. package/dist/ui/assets/loader-circle-wLVzSdML.js +1 -0
  51. package/dist/ui/assets/{lock-open-Cd2aqwOd.js → lock-open-Cdopbw1b.js} +1 -1
  52. package/dist/ui/assets/{mail-BG0RYSkL.js → mail-BQ_YA9_b.js} +1 -1
  53. package/dist/ui/assets/{pause-Cme88_9s.js → pause-CvS_LzKx.js} +1 -1
  54. package/dist/ui/assets/{pencil-f1nJ1xhs.js → pencil-C3tPvnCk.js} +1 -1
  55. package/dist/ui/assets/play-C-oR-PMH.js +1 -0
  56. package/dist/ui/assets/plus-CF9No2td.js +1 -0
  57. package/dist/ui/assets/{radio-B5SpKJ-J.js → radio-dsaiFxuT.js} +1 -1
  58. package/dist/ui/assets/{refresh-cw-CroGQY62.js → refresh-cw-BmYQwOhh.js} +1 -1
  59. package/dist/ui/assets/search-CTONpTyl.js +1 -0
  60. package/dist/ui/assets/{select-BhbW0stK.js → select-BfRyBbi9.js} +1 -1
  61. package/dist/ui/assets/{send-D6whYpw-.js → send-C3o2wpLi.js} +1 -1
  62. package/dist/ui/assets/{settings-BX6q3MGB.js → settings-DEpdBuf2.js} +1 -1
  63. package/dist/ui/assets/{shield-BnGyu1xf.js → shield-gbUkSqfi.js} +1 -1
  64. package/dist/ui/assets/{sparkles-BcaOs_Jk.js → sparkles-Ccd1JZ3s.js} +1 -1
  65. package/dist/ui/assets/{square-ju5H8nrT.js → square-BrwQ6Mun.js} +1 -1
  66. package/dist/ui/assets/terminal-DP9j3HjM.js +1 -0
  67. package/dist/ui/assets/{trash-2-DjQXac_0.js → trash-2-CfCs7RhJ.js} +1 -1
  68. package/dist/ui/assets/{triangle-alert-B04mgMcg.js → triangle-alert-C3lWSnRr.js} +1 -1
  69. package/dist/ui/assets/{useHiveAgentsModelLoad-DT5-4CCj.js → useHiveAgentsModelLoad-D3s2U82M.js} +1 -1
  70. package/dist/ui/assets/{useProviders-DSX7eVsz.js → useProviders-B3rT_xU9.js} +1 -1
  71. package/dist/ui/assets/{volume-x-qnVxkRSM.js → volume-x-D2h9cyml.js} +1 -1
  72. package/dist/ui/assets/{wifi-BA1m2dGO.js → wifi-CGQECzu2.js} +1 -1
  73. package/dist/ui/assets/{zap-DT7cM7YS.js → zap-B1azpiE7.js} +1 -1
  74. package/dist/ui/index.html +8 -6
  75. package/dist/ui/logoblack.png +0 -0
  76. package/dist/ui/logocolor-dark.png +0 -0
  77. package/dist/ui/logocolorbg.png +0 -0
  78. package/dist/ui/logodoradobg.png +0 -0
  79. package/package.json +12 -8
  80. package/packages/cli/src/commands/doctor.ts +111 -0
  81. package/packages/cli/src/commands/onboard.ts +126 -59
  82. package/packages/cli/src/index.ts +23 -17
  83. package/packages/cli/src/ui-bundle.generated.ts +9 -92
  84. package/packages/core/src/agent/acceptance-checks.ts +172 -0
  85. package/packages/core/src/agent/agent-catalog.ts +1 -37
  86. package/packages/core/src/agent/agent-loop.ts +21 -2
  87. package/packages/core/src/agent/catalog-selector.ts +0 -1
  88. package/packages/core/src/agent/compaction.ts +16 -1
  89. package/packages/core/src/agent/context-compiler.ts +3 -1
  90. package/packages/core/src/agent/conversation-store.ts +1 -1
  91. package/packages/core/src/agent/delegation-runtime.ts +1 -8
  92. package/packages/core/src/agent/goal-runner.ts +111 -32
  93. package/packages/core/src/agent/index.ts +1 -1
  94. package/packages/core/src/agent/llm-client.ts +34 -2
  95. package/packages/core/src/agent/llm-providers/anthropic.ts +10 -7
  96. package/packages/core/src/agent/llm-providers/interface.ts +13 -2
  97. package/packages/core/src/agent/llm-providers/modelscope.ts +5 -0
  98. package/packages/core/src/agent/llm-providers/z-ai.ts +5 -0
  99. package/packages/core/src/agent/minimal-loadout.ts +1 -0
  100. package/packages/core/src/agent/proof-packet.ts +2 -11
  101. package/packages/core/src/agent/providers/index.ts +1 -1
  102. package/packages/core/src/agent/tool-selector.ts +25 -1
  103. package/packages/core/src/canvas/canvas-manager.ts +36 -7
  104. package/packages/core/src/canvas/emitter.ts +0 -44
  105. package/packages/core/src/channels/manager.ts +117 -25
  106. package/packages/core/src/channels/whatsapp.ts +6 -1
  107. package/packages/core/src/config/loader.ts +13 -1
  108. package/packages/core/src/events/channel-narration.ts +150 -0
  109. package/packages/core/src/events/tool-narration.ts +62 -0
  110. package/packages/core/src/gateway/channel-notify.ts +11 -7
  111. package/packages/core/src/gateway/delegation-groups.ts +24 -11
  112. package/packages/core/src/gateway/helpers/narration.ts +4 -62
  113. package/packages/core/src/gateway/helpers/ui-source.ts +67 -0
  114. package/packages/core/src/gateway/job-executors.ts +29 -67
  115. package/packages/core/src/gateway/resolver.ts +10 -2
  116. package/packages/core/src/gateway/routes/a2ui.ts +43 -0
  117. package/packages/core/src/gateway/routes/agents.ts +6 -6
  118. package/packages/core/src/gateway/routes/channels.ts +15 -1
  119. package/packages/core/src/gateway/routes/models.ts +69 -12
  120. package/packages/core/src/gateway/routes/providers.ts +110 -28
  121. package/packages/core/src/gateway/routes/runtime.ts +58 -0
  122. package/packages/core/src/gateway/routes/setup.ts +161 -90
  123. package/packages/core/src/gateway/routes/system.ts +8 -5
  124. package/packages/core/src/gateway/routes/voice.ts +3 -0
  125. package/packages/core/src/gateway/server.ts +74 -28
  126. package/packages/core/src/gateway/webchat-turn.ts +29 -5
  127. package/packages/core/src/index.ts +1 -1
  128. package/packages/core/src/storage/bootstrap.ts +13 -9
  129. package/packages/core/src/storage/collections.ts +12 -46
  130. package/packages/core/src/storage/crypto.ts +147 -58
  131. package/packages/core/src/storage/hivedb.ts +9 -0
  132. package/packages/core/src/storage/model-id.ts +53 -0
  133. package/packages/core/src/storage/onboarding.ts +36 -9
  134. package/packages/core/src/storage/seed.ts +283 -138
  135. package/packages/core/src/storage/usage.ts +61 -123
  136. package/packages/core/src/tools/agents/index.ts +199 -27
  137. package/packages/core/src/tools/index.ts +2 -1
  138. package/packages/core/src/tools/web/browser-backend.ts +129 -0
  139. package/packages/core/src/tools/web/browser-service.ts +75 -35
  140. package/packages/core/src/tools/web/webview-backend.ts +412 -0
  141. package/packages/core/src/voice/index.ts +108 -17
  142. package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +2 -1
  143. package/packages/skills/src/bundled-data.generated.ts +2 -23
  144. package/dist/ui/assets/A2UIPage-D4nUFe5q.js +0 -8
  145. package/dist/ui/assets/AgentNewPage-CEkLeA79.js +0 -1
  146. package/dist/ui/assets/ProvidersPage-BupHs5yO.js +0 -1
  147. package/dist/ui/assets/SettingsPage-B6FTSkOn.js +0 -9
  148. package/dist/ui/assets/arrow-left-0EBE7nsF.js +0 -1
  149. package/dist/ui/assets/arrow-right-5QIaph-z.js +0 -1
  150. package/dist/ui/assets/arrow-up-right-DQQCY007.js +0 -1
  151. package/dist/ui/assets/check-Dp6tzwax.js +0 -1
  152. package/dist/ui/assets/chevron-down-33N886NY.js +0 -1
  153. package/dist/ui/assets/chevron-left-C6itJXh3.js +0 -1
  154. package/dist/ui/assets/chevron-right-CFodBS-b.js +0 -1
  155. package/dist/ui/assets/chevron-up-BvSmyBEs.js +0 -1
  156. package/dist/ui/assets/circle-check-BJWNbLuF.js +0 -1
  157. package/dist/ui/assets/gauge-BRGwuN8G.js +0 -1
  158. package/dist/ui/assets/index-XoTT41Hr.css +0 -2
  159. package/dist/ui/assets/loader-circle-BhqRN2nO.js +0 -1
  160. package/dist/ui/assets/play-CfYDHD6h.js +0 -1
  161. package/dist/ui/assets/plus-C5BxJeOX.js +0 -1
  162. package/dist/ui/assets/search-rfBcmohK.js +0 -1
  163. package/dist/ui/assets/terminal-Bjfu-TkS.js +0 -1
  164. package/packages/core/src/agent/acceptance-verifier.ts +0 -300
  165. package/packages/skills/src/bundled/agents/acceptance_verification/SKILL.md +0 -26
@@ -11,9 +11,10 @@
11
11
  * instead of `DELETE`+`INSERT`.
12
12
  */
13
13
 
14
- import { getHiveDb } from "./hivedb";
14
+ import { getHiveDb, getOpenHiveDb } from "./hivedb";
15
15
  import { col } from "./hive";
16
16
  import { seedAllData } from "./seed";
17
+ import { ensureSecretsBackend } from "./crypto";
17
18
 
18
19
  interface IndexSpec {
19
20
  collection: string;
@@ -80,10 +81,6 @@ const INDEXES: IndexSpec[] = [
80
81
  { collection: "artifacts", field: "task_id" },
81
82
  { collection: "artifacts", field: "user_id" },
82
83
  { collection: "artifacts", field: "status" },
83
- { collection: "verifications", field: "run_id" },
84
- { collection: "verifications", field: "task_id" },
85
- { collection: "verifications", field: "executor_agent_id" },
86
- { collection: "verifications", field: "status" },
87
84
  { collection: "agentProposals", field: "agent_id" },
88
85
  { collection: "agentProposals", field: "status" },
89
86
  { collection: "agentProposals", field: "type" },
@@ -126,7 +123,10 @@ async function ensureSeedData(): Promise<void> {
126
123
  await seedAllData();
127
124
  }
128
125
 
129
- let bootstrapped = false;
126
+ // Bootstrap state belongs to a specific database instance. A boolean that
127
+ // survives closeHiveDb() can report a closed/replaced database as ready when
128
+ // tests or long-running processes open a fresh instance in the same runtime.
129
+ let bootstrappedDb: Awaited<ReturnType<typeof getHiveDb>> | null = null;
130
130
 
131
131
  /**
132
132
  * Idempotent entry point: opens the database, ensures indexes, reseeds the
@@ -134,17 +134,21 @@ let bootstrapped = false;
134
134
  * gateway boot.
135
135
  */
136
136
  export async function ensureHiveDb(): Promise<void> {
137
- await getHiveDb();
137
+ const db = await getHiveDb();
138
138
  await ensureIndexes();
139
+ // Mint the master key before anything can save an API key, so a fresh
140
+ // install is durable from the first keystroke rather than after a restart
141
+ // has already dropped the secret.
142
+ ensureSecretsBackend();
139
143
  await ensureSeedData();
140
144
 
141
145
  const meta = await col<{ value: number }>("meta");
142
146
  const existing = await meta.get("schemaVersion");
143
147
  if (!existing) await meta.put("schemaVersion", { value: 1 }, { expectedVersion: 0 });
144
148
 
145
- bootstrapped = true;
149
+ bootstrappedDb = db;
146
150
  }
147
151
 
148
152
  export function isBootstrapped(): boolean {
149
- return bootstrapped;
153
+ return bootstrappedDb !== null && bootstrappedDb === getOpenHiveDb();
150
154
  }
@@ -53,6 +53,14 @@ export interface ModelDoc {
53
53
  * agent pointing at it. Legacy rows (undefined) are treated as discovered.
54
54
  */
55
55
  source?: "catalog" | "discovered"
56
+ /**
57
+ * Precio en USD por millón de tokens. Única fuente de verdad para el costo
58
+ * del dashboard: `calculateCost` (storage/usage.ts) lee de acá, no de una
59
+ * tabla aparte. `null` = precio desconocido (modelo agregado a mano o
60
+ * descubierto en runtime), que se reporta como $0 con un warning.
61
+ */
62
+ input_per_1m?: number | null
63
+ output_per_1m?: number | null
56
64
  }
57
65
 
58
66
  export interface AgentDoc {
@@ -95,7 +103,7 @@ export interface AgentDoc {
95
103
  workspace_scope_json?: string | null
96
104
  model_override_json?: string | null
97
105
  default_acceptance_json?: string | null
98
- /** ACE learning counters — updated by independent verifier verdicts (acceptance-verifier.ts), not by loop completion. */
106
+ /** ACE learning counters — updated by deterministic acceptance checks and the coordinator's own accept/revise judgment (acceptance-checks.ts), not by loop completion. */
99
107
  helpful_count?: number
100
108
  harmful_count?: number
101
109
  seed_version?: number
@@ -217,6 +225,8 @@ export interface UserIdentityDoc {
217
225
  user_id: string
218
226
  channel: string
219
227
  channel_user_id: string
228
+ /** Account that owns this session — replies must go back out through it. Absent on legacy rows. */
229
+ account_id?: string
220
230
  linked_at: number
221
231
  }
222
232
 
@@ -459,8 +469,6 @@ export interface ProofPacketDoc {
459
469
  known_limits: string | null
460
470
  /** Fixed-worker epoch this run executed under — copied from AgentRunDoc.epoch_json. */
461
471
  epoch_json: string | null
462
- /** Required when met=true. Points at an independent verified verdict. */
463
- verification_id: string
464
472
  /** `toIndexable`-encoded catalog agent id, or `NO_PARENT`. */
465
473
  catalog_agent_id: string
466
474
  met: boolean
@@ -486,48 +494,6 @@ export interface ArtifactDoc {
486
494
  expired_at: number | null
487
495
  }
488
496
 
489
- export interface VerificationCriterionResult {
490
- criterion_id: string
491
- met: boolean
492
- evidence: string[]
493
- check_used: string
494
- confidence: number
495
- }
496
-
497
- export interface VerificationVerdict {
498
- status: "verified" | "rejected" | "needs_evidence"
499
- criterion_results: VerificationCriterionResult[]
500
- summary: string
501
- retry_guidance: string | null
502
- risks: string[]
503
- }
504
-
505
- /** Independent acceptance-gate record. Executors cannot write a verified proof packet without one. */
506
- export interface VerificationDoc {
507
- id: string
508
- run_id: string
509
- task_id: string
510
- /** Any AgentDoc id (catalog-seeded or not). */
511
- executor_agent_id: string
512
- verifier_agent_id: "acceptance_verifier"
513
- objective: string
514
- acceptance_json: string
515
- verdict_json: string
516
- status: VerificationVerdict["status"]
517
- attempt: number
518
- executor_epoch_json: string
519
- verifier_epoch_json: string
520
- /** Diagnostic classification when the verifier could not produce a usable verdict. */
521
- failure_code?: "invalid_output" | "verifier_error" | null
522
- /** Sanitized diagnostic detail; never used to authorize success. */
523
- failure_detail?: string | null
524
- /** Bounded and sanitized preview of the verifier output. */
525
- raw_output_preview?: string | null
526
- verifier_provider?: string | null
527
- verifier_model?: string | null
528
- created_at: number
529
- }
530
-
531
497
  export interface AgentProposalDoc {
532
498
  id: string
533
499
  type: "move_tool" | "create_agent" | "disable_agent"
@@ -639,7 +605,7 @@ export interface NarrationEventDoc {
639
605
  session_id: string
640
606
  agent_id: string
641
607
  agent_name: string
642
- kind: "delegated" | "worker_started" | "tool_call" | "tool_result" | "verifying" | "verified" | "failed" | "group_ready"
608
+ kind: "delegated" | "worker_started" | "tool_call" | "tool_result" | "verified" | "failed" | "group_ready"
643
609
  status: "queued" | "running" | "done" | "error"
644
610
  label: string
645
611
  detail: string | null
@@ -1,3 +1,7 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
3
+ import * as path from "node:path"
4
+ import { getHiveDir } from "../config/loader.ts"
1
5
  import { logger } from "../utils/logger"
2
6
  import { col } from "./hive"
3
7
 
@@ -9,49 +13,70 @@ interface SecretDoc {
9
13
  iv: string
10
14
  }
11
15
 
12
- // ─── Keychain with in-memory fallback ────────────────────────────────────────
13
- // On Linux headless (no GNOME Keyring / libsecret) Bun.secrets throws.
14
- // Fall back to in-memory storage so the server stays functional, but log a
15
- // warning so operators know secrets won't survive a restart in that mode.
16
+ // ─── Durable secret store ────────────────────────────────────────────────────
17
+ // The `secrets` collection is the source of truth: AES-256-GCM ciphertext in
18
+ // the database, keyed by <HIVE_HOME>/.master.key. It lives inside the data
19
+ // directory, so whatever persists the database (a Docker volume, a backup)
20
+ // persists the secrets with it.
21
+ //
22
+ // The OS keychain (Bun.secrets) is only a best-effort mirror. It throws on
23
+ // headless Linux/Docker (no libsecret/D-Bus), and on desktops it can be a
24
+ // session keyring that is discarded when the session ends — so a secret
25
+ // written *only* there does not survive a server restart. That is exactly
26
+ // what was wiping every provider API key, channel token and MCP header on
27
+ // restart in production.
16
28
 
17
29
  const _mem = new Map<string, string>()
18
30
  let _keychainOk: boolean | null = null // null = untested
31
+ let _keychainApi: unknown = undefined
19
32
 
20
- async function _get(name: string): Promise<string | null> {
21
- if (_keychainOk === false) {
22
- return _mem.get(name) ?? (await _readCollectionSecret(name))
23
- }
24
- try {
25
- const val = await (Bun as any).secrets.get({ service: SERVICE, name })
26
- _keychainOk = true
27
- return val ?? _mem.get(name) ?? (await _readCollectionSecret(name))
28
- } catch {
29
- _keychainOk = false
30
- return _mem.get(name) ?? (await _readCollectionSecret(name))
33
+ /**
34
+ * A test double or a recovered runtime may replace Bun.secrets. Reset the
35
+ * cached availability result when that API object changes so a previous
36
+ * headless failure cannot poison the replacement backend forever.
37
+ */
38
+ function _getKeychainApi(): any {
39
+ const api = (Bun as any).secrets
40
+ if (api !== _keychainApi) {
41
+ _keychainApi = api
42
+ _keychainOk = null
31
43
  }
44
+ return api
32
45
  }
33
46
 
47
+ async function _get(name: string): Promise<string | null> {
48
+ const cached = _mem.get(name)
49
+ if (cached !== undefined) return cached
50
+
51
+ // Durable store first — it is the one every write goes to.
52
+ const stored = await _readCollectionSecret(name)
53
+ if (stored) return stored
54
+
55
+ // Legacy/desktop installs may only have the value in the OS keychain.
56
+ const fromKeychain = await _keychainGet(name)
57
+ if (fromKeychain) _mem.set(name, fromKeychain)
58
+ return fromKeychain
59
+ }
60
+
61
+ /**
62
+ * Persist a secret. Always writes the durable store; the keychain is
63
+ * mirrored on top when available. Returns false only when the value ended up
64
+ * nowhere but this process's memory — callers can use that to warn instead of
65
+ * silently accepting a secret that dies with the process.
66
+ */
34
67
  async function _set(name: string, value: string): Promise<boolean> {
35
- if (_keychainOk === false) {
36
- _mem.set(name, value)
37
- return persistSecretToCollection(name, value)
38
- }
39
- try {
40
- await (Bun as any).secrets.set({ service: SERVICE, name, value })
41
- _keychainOk = true
42
- return true
43
- } catch {
44
- _keychainOk = false
45
- _mem.set(name, value)
46
- return persistSecretToCollection(name, value)
68
+ _mem.set(name, value)
69
+ const durable = await persistSecretToCollection(name, value)
70
+ const mirrored = await _keychainSet(name, value)
71
+ if (!durable && !mirrored) {
72
+ log.error(`[secrets] ${name} could not be persisted — it will be lost on restart`)
47
73
  }
74
+ return durable || mirrored
48
75
  }
49
76
 
50
77
  /**
51
- * Read a secret from the `secrets` HiveDB collection as a last-resort
52
- * fallback when the keychain and in-memory map are both empty. Used to
53
- * survive process restarts when the OS keychain is unavailable (Docker,
54
- * headless).
78
+ * Read a secret from the `secrets` HiveDB collection — the durable store.
79
+ * Decrypted values are cached in memory for the rest of the process.
55
80
  */
56
81
  async function _readCollectionSecret(name: string): Promise<string | null> {
57
82
  try {
@@ -69,6 +94,32 @@ async function _readCollectionSecret(name: string): Promise<string | null> {
69
94
  }
70
95
  }
71
96
 
97
+ async function _keychainGet(name: string): Promise<string | null> {
98
+ const keychain = _getKeychainApi()
99
+ if (_keychainOk === false) return null
100
+ try {
101
+ const val = await keychain.get({ service: SERVICE, name })
102
+ _keychainOk = true
103
+ return val ?? null
104
+ } catch {
105
+ _keychainOk = false
106
+ return null
107
+ }
108
+ }
109
+
110
+ async function _keychainSet(name: string, value: string): Promise<boolean> {
111
+ const keychain = _getKeychainApi()
112
+ if (_keychainOk === false) return false
113
+ try {
114
+ await keychain.set({ service: SERVICE, name, value })
115
+ _keychainOk = true
116
+ return true
117
+ } catch {
118
+ _keychainOk = false
119
+ return false
120
+ }
121
+ }
122
+
72
123
  async function _del(name: string): Promise<void> {
73
124
  _mem.delete(name)
74
125
  try {
@@ -84,6 +135,22 @@ async function _del(name: string): Promise<void> {
84
135
  }
85
136
  }
86
137
 
138
+ /**
139
+ * Mint the master key (if this is a fresh install) and report where secrets
140
+ * will be stored. Called once at boot so an operator sees the answer before
141
+ * typing an API key, not after a restart lost it.
142
+ */
143
+ export function ensureSecretsBackend(): { durable: boolean } {
144
+ const durable = getMasterKey() !== null
145
+ if (!durable) {
146
+ log.error(
147
+ `[secrets] No master key available — API keys and channel tokens will NOT survive a restart. ` +
148
+ `Set HIVE_MASTER_KEY or make ${getHiveDir()} writable.`
149
+ )
150
+ }
151
+ return { durable }
152
+ }
153
+
87
154
  // ─── Primitive API ────────────────────────────────────────────────────────────
88
155
 
89
156
  export async function storeSecret(name: string, value: string): Promise<void> {
@@ -209,13 +276,12 @@ export function verifyPassword(password: string, hash: string): boolean {
209
276
  // ─── AES-256-GCM for the collection-backed secret fallback ──────────────────
210
277
 
211
278
  export function decryptSecret(encrypted: string, iv: string): string {
212
- const nodeCrypto = require("node:crypto")
213
279
  const key = getMasterKey()
214
280
  if (!key) return ""
215
281
  try {
216
282
  const ivBuf = Buffer.from(iv, "hex")
217
283
  const [encData, authTag] = encrypted.split(":")
218
- const decipher = nodeCrypto.createDecipheriv("aes-256-gcm", key, ivBuf)
284
+ const decipher = createDecipheriv("aes-256-gcm", key, ivBuf)
219
285
  decipher.setAuthTag(Buffer.from(authTag, "hex"))
220
286
  return decipher.update(encData, "hex", "utf8") + decipher.final("utf8")
221
287
  } catch {
@@ -223,38 +289,63 @@ export function decryptSecret(encrypted: string, iv: string): string {
223
289
  }
224
290
  }
225
291
 
292
+ let _masterKey: Buffer | null = null
293
+
294
+ /**
295
+ * The AES key protecting the `secrets` collection.
296
+ *
297
+ * `HIVE_MASTER_KEY` wins when set (the recommended way to run in production:
298
+ * the key never touches the data volume). Otherwise the key is minted on
299
+ * first use and written 0600 to `<HIVE_HOME>/.master.key`, next to the
300
+ * database — a fresh install becomes durable without the user configuring
301
+ * anything, and restoring the data directory restores the ability to read
302
+ * the secrets inside it.
303
+ */
226
304
  function getMasterKey(): Buffer | null {
227
- const nodeCrypto = require("node:crypto")
228
- const nodeFs = require("node:fs")
229
- const nodePath = require("node:path")
230
- const nodeOs = require("node:os")
231
-
232
- const masterKey = process.env.HIVE_MASTER_KEY
233
- if (masterKey) {
234
- return Buffer.from(masterKey.slice(0, 32).padEnd(32, "0"), "utf8")
305
+ if (_masterKey) return _masterKey
306
+
307
+ const fromEnv = process.env.HIVE_MASTER_KEY
308
+ if (fromEnv) {
309
+ _masterKey = Buffer.from(fromEnv.slice(0, 32).padEnd(32, "0"), "utf8")
310
+ return _masterKey
235
311
  }
236
- const hiveDir = process.env.HIVE_HOME || nodePath.join(nodeOs.homedir(), ".hive")
237
- const keyPath = nodePath.join(hiveDir, ".master.key")
238
- if (!nodeFs.existsSync(keyPath)) return null
312
+
313
+ const keyPath = path.join(getHiveDir(), ".master.key")
239
314
  try {
240
- return Buffer.from(nodeFs.readFileSync(keyPath, "utf8").trim(), "hex")
241
- } catch {
315
+ if (!existsSync(keyPath)) {
316
+ mkdirSync(path.dirname(keyPath), { recursive: true })
317
+ try {
318
+ // "wx" so two processes starting at once can't overwrite each other's key
319
+ writeFileSync(keyPath, randomBytes(32).toString("hex"), { mode: 0o600, flag: "wx" })
320
+ log.info(`[secrets] Master key generated at ${keyPath}`)
321
+ } catch (err) {
322
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err
323
+ }
324
+ }
325
+ const key = Buffer.from(readFileSync(keyPath, "utf8").trim(), "hex")
326
+ if (key.length !== 32) {
327
+ log.error(`[secrets] ${keyPath} is not a 32-byte hex key — secrets cannot be read or written`)
328
+ return null
329
+ }
330
+ _masterKey = key
331
+ return _masterKey
332
+ } catch (err) {
333
+ log.error(`[secrets] Could not read or create ${keyPath}: ${(err as Error).message}`)
242
334
  return null
243
335
  }
244
336
  }
245
337
 
246
338
  /**
247
339
  * Encrypt a plaintext string with AES-256-GCM. Format:
248
- * `<encDataHex>:<authTagHex>`. Used as the `secrets` collection fallback
249
- * when the OS keychain is unavailable (headless Linux, Docker, etc.).
340
+ * `<encDataHex>:<authTagHex>`. Used for every document in the `secrets`
341
+ * collection.
250
342
  */
251
343
  export function encryptSecret(plain: string, ivHex: string): string {
252
- const nodeCrypto = require("node:crypto")
253
344
  const key = getMasterKey()
254
345
  if (!key) return ""
255
346
  try {
256
347
  const iv = Buffer.from(ivHex, "hex")
257
- const cipher = nodeCrypto.createCipheriv("aes-256-gcm", key, iv)
348
+ const cipher = createCipheriv("aes-256-gcm", key, iv)
258
349
  const encData = cipher.update(plain, "utf8", "hex") + cipher.final("hex")
259
350
  const authTag = cipher.getAuthTag().toString("hex")
260
351
  return `${encData}:${authTag}`
@@ -264,20 +355,18 @@ export function encryptSecret(plain: string, ivHex: string): string {
264
355
  }
265
356
 
266
357
  /**
267
- * Persist a secret to the `secrets` collection as a last-resort fallback
268
- * (keyed directly by the canonical secret name, e.g.
269
- * `provider:openai:api_key`). Returns true if the document was written.
358
+ * Persist a secret to the `secrets` collection — the durable store — keyed by
359
+ * the canonical secret name (e.g. `provider:openai:api_key`). Returns true if
360
+ * the document was written.
270
361
  */
271
362
  async function persistSecretToCollection(name: string, value: string): Promise<boolean> {
272
- const nodeCrypto = require("node:crypto")
273
-
274
363
  const key = getMasterKey()
275
364
  if (!key) {
276
- log.warn(`[secrets] No master key in ${process.env.HIVE_HOME || "~/.hive"}/.master.key — cannot persist ${name} to collection fallback`)
365
+ log.warn(`[secrets] No master key — cannot persist ${name} durably`)
277
366
  return false
278
367
  }
279
368
 
280
- const iv = nodeCrypto.randomBytes(12).toString("hex")
369
+ const iv = randomBytes(12).toString("hex")
281
370
  const ciphertext = encryptSecret(value, iv)
282
371
  if (!ciphertext) return false
283
372
 
@@ -286,7 +375,7 @@ async function persistSecretToCollection(name: string, value: string): Promise<b
286
375
  await secrets.put(name, { ciphertext, iv })
287
376
  return true
288
377
  } catch (err) {
289
- log.warn(`[secrets] Collection fallback failed for ${name}: ${(err as Error).message}`)
378
+ log.warn(`[secrets] Durable write failed for ${name}: ${(err as Error).message}`)
290
379
  return false
291
380
  }
292
381
  }
@@ -48,6 +48,15 @@ export async function getHiveDb(): Promise<HiveDB> {
48
48
  return opening;
49
49
  }
50
50
 
51
+ /**
52
+ * Return the currently open database without opening one.
53
+ * Used by lifecycle-aware consumers that need to invalidate state after a
54
+ * close/reopen cycle.
55
+ */
56
+ export function getOpenHiveDb(): HiveDB | null {
57
+ return db;
58
+ }
59
+
51
60
  export function closeHiveDb(): void {
52
61
  if (db) {
53
62
  try {
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Claves de la colección `models`.
3
+ *
4
+ * La colección se indexa sólo por el id del modelo, así que dos providers que
5
+ * sirvan el mismo modelo colisionan y uno pisa al otro (pasó de verdad con
6
+ * `z-ai/glm-5.2`, presente a la vez en NVIDIA NIM y en OpenRouter).
7
+ *
8
+ * Regla: el id conserva el nombre que le da el propietario del modelo, y los
9
+ * servicios revendedores lo prefijan con su propio id de provider.
10
+ *
11
+ * nvidia + z-ai/glm-5.2 → nvidia/z-ai/glm-5.2
12
+ * openrouter + z-ai/glm-5.2 → openrouter/z-ai/glm-5.2
13
+ * anthropic + claude-opus-5 → claude-opus-5
14
+ *
15
+ * El prefijo no llega al cable: `OpenAICompatBase.call()` quita
16
+ * `^<providerName>/` antes de armar el request, así que el provider recibe el
17
+ * nombre del propietario tal cual. Por eso todos los revendedores de esta lista
18
+ * deben ser OpenAI-compatibles.
19
+ */
20
+
21
+ const RESELLER_PROVIDERS = new Set(["nvidia", "openrouter", "opencode-go", "groq", "modelscope"])
22
+
23
+ /**
24
+ * Id de fila en `models` para el modelo `wireId` servido por `providerId`.
25
+ *
26
+ * `wireId` es siempre el nombre del cable, nunca una clave ya prefijada. No hay
27
+ * atajo de idempotencia a propósito: "ya lleva el prefijo" es indistinguible de
28
+ * "el namespace del propietario coincide con el id del provider". NVIDIA sirve
29
+ * `nvidia/nemotron-3-super-120b-a12b` y Groq sirve `groq/compound`, así que
30
+ * saltarse el prefijo por un `startsWith` recortaba de más al volver al cable y
31
+ * mandaba `nemotron-…` / `compound`.
32
+ */
33
+ export function catalogModelKey(providerId: string, wireId: string): string {
34
+ return RESELLER_PROVIDERS.has(providerId) ? `${providerId}/${wireId}` : wireId
35
+ }
36
+
37
+ /**
38
+ * Inversa de `catalogModelKey`: el nombre que el provider espera en el cable.
39
+ *
40
+ * Los adapters OpenAI-compatibles ya hacen este strip solos al armar el request,
41
+ * así que esto es para los caminos que mandan el modelo a mano — por ejemplo la
42
+ * verificación de API key en `gateway/routes/setup.ts`, que arma su propio fetch.
43
+ */
44
+ export function wireModelId(providerId: string, key: string): string {
45
+ const prefix = `${providerId}/`
46
+ if (!RESELLER_PROVIDERS.has(providerId) || !key.startsWith(prefix)) return key
47
+ return key.slice(prefix.length)
48
+ }
49
+
50
+ /** True cuando el provider revende modelos de terceros y por eso prefija sus ids. */
51
+ export function isResellerProvider(providerId: string): boolean {
52
+ return RESELLER_PROVIDERS.has(providerId)
53
+ }
@@ -37,7 +37,23 @@ Leé el pedido completo y mirá lo que ya sabés: la sección SCRATCHPAD trae tu
37
37
 
38
38
  **Si es un saludo, una charla o una pregunta que respondés de memoria: respondé y terminá.** Eso no se delega nunca ni necesita herramientas.
39
39
 
40
- ## 2. DESCOMPONER
40
+ ## 2. MAPA RÁPIDO DE ESPECIALISTAS
41
+
42
+ Para cualquier pedido operativo, comparalo primero con este mapa y delegá al especialista más cercano:
43
+
44
+ - \`web_researcher\`: investiga información actual en la web y entrega fuentes.
45
+ - \`browser_operator\`: navega sitios, completa formularios y verifica el resultado.
46
+ - \`workspace_file_operator\`: crea, lee, edita y organiza archivos del workspace.
47
+ - \`software_engineer\`: implementa, depura y prueba software en un repositorio.
48
+ - \`office_document_agent\`: lee y genera PDF, Word, Excel y PowerPoint.
49
+ - \`a2ui_builder\`: construye formularios, dashboards y flujos interactivos A2UI.
50
+ - \`schedule_automation_agent\`: crea y administra jobs, recordatorios y automatizaciones de Hive.
51
+ - \`api_operator\`: ejecuta y verifica operaciones contra APIs REST autorizadas.
52
+ - Especialistas MCP del usuario: workers con integraciones específicas; encontralos con \`agent_find\` antes de usar una tool MCP.
53
+
54
+ **Regla de prioridad:** primero elegí un agente de este mapa y usá \`task_delegate\`, pero verificá antes que aparezca activo en la COLMENA; el mapa describe roles y no garantiza disponibilidad. Si no está activo o ninguno encaja, buscá otro worker con \`agent_find\`; solo después descubrí herramientas y resolvé directamente. No delegues a un ID asumido ni elijas herramientas directas antes de hacer esta comprobación, salvo saludos, charla o preguntas que respondés de memoria.
55
+
56
+ ## 3. DESCOMPONER
41
57
 
42
58
  Separá el pedido en partes y clasificá cada una:
43
59
 
@@ -47,7 +63,7 @@ Separá el pedido en partes y clasificá cada una:
47
63
  | Una necesita el resultado de otra | Va en una fase posterior |
48
64
  | Trivial o conversacional | La resolvés vos, sin herramientas |
49
65
 
50
- ## 3. POR CADA PARTE: ¿HAY UN AGENTE QUE LA HAGA?
66
+ ## 4. POR CADA PARTE: ¿HAY UN AGENTE QUE LA HAGA?
51
67
 
52
68
  **Esta es la pregunta central de tu rol, y contestarla es gratis:** el roster está en la sección COLMENA DE AGENTES de este mismo prompt, no hace falta ninguna llamada para consultarlo.
53
69
 
@@ -71,7 +87,7 @@ Separá el pedido en partes y clasificá cada una:
71
87
 
72
88
  Si \`search_knowledge\` no devuelve nada y el pedido es corto o ambiguo, **preguntale al usuario** en vez de adivinar y encadenar más búsquedas. Una pregunta cuesta un turno; adivinar mal cuesta varios.
73
89
 
74
- ## 4. DELEGAR EN PARALELO
90
+ ## 5. DELEGAR EN PARALELO
75
91
 
76
92
  Las partes independientes se lanzan **todas en el mismo turno**: una \`task_delegate\` por parte, con \`mode="async"\`. Hive las agrupa por turno y los workers corren simultáneamente.
77
93
 
@@ -79,7 +95,9 @@ Si el usuario pide tres cosas que no dependen entre sí, son tres \`task_delegat
79
95
 
80
96
  Cada delegación lleva: \`worker_id\`, una subtarea acotada, contexto mínimo y \`acceptance\` verificable. Antes de delegar, si el worker va a necesitar herramientas puntuales, buscalas con \`search_knowledge\` e incluilas en la instrucción. Reservá \`mode="sync"\` solo para un lookup cuyo resultado esperás en segundos.
81
97
 
82
- ## 5. ESPERAR: NO ESPERÁS
98
+ Si más adelante una entrega no cumple sus criterios, \`task_revise\` reencola al mismo worker sobre el mismo hilo (ver sección 7) — no crees una delegación nueva para corregir algo ya delegado.
99
+
100
+ ## 6. ESPERAR: NO ESPERÁS
83
101
 
84
102
  Después de delegar, contale al usuario en una línea qué pusiste a correr y **terminá tu turno**.
85
103
 
@@ -89,9 +107,17 @@ Cuando todas las tareas del turno alcanzan estado terminal, Hive te reinvoca aut
89
107
  - No anuncies resultados que todavía no tenés ni declares éxito antes del \`[Sistema]\`.
90
108
  - No re-delegues una tarea porque "no contestó": ya está encolada.
91
109
 
92
- ## 6. CERRAR
110
+ ## 7. CERRAR
111
+
112
+ Al recibir el \`[Sistema]\`, cada entrega trae sus \`acceptance\` (criterios) y sus \`checks\` (resultado determinístico, sin LLM, ya calculado):
113
+
114
+ - \`checks.status="passed"\` → un check automático ya lo confirmó. Aceptalo.
115
+ - \`checks.status="failed"\` (implica \`ok=false\`) → no cumplió. Nunca lo reportes como éxito.
116
+ - \`checks.status="unchecked"\` o ausente → no hay check automático para ese criterio: **vos sos quien juzga**, con el contenido y la evidencia que trae la entrega.
117
+
118
+ Si una entrega no cumple sus criterios: usá \`task_revise\` con el \`task_id\` y un feedback concreto y accionable — el worker retoma con su contexto, no hace falta repetirle todo el pedido. Si el problema es trivial y tenés las tools, corregilo vos directamente en vez de re-delegar. No inventes trabajo ni evidencia.
93
119
 
94
- Al recibir el \`[Sistema]\`, escribí **una sola** respuesta final integrando todo. Las entradas con \`ok=false\` se reportan con su motivo real, nunca como éxito.
120
+ Cuando todo lo delegado en esta ronda cumple, escribí **una sola** respuesta final integrando todo. Las entradas con \`ok=false\` se reportan con su motivo real, nunca como éxito.
95
121
 
96
122
  Guardá lo que vaya a servir después: \`save_note\` para esta conversación, \`memory_write\` para lo que deba sobrevivir a ella. Confirmá con el usuario antes de persistir datos suyos.
97
123
 
@@ -99,7 +125,7 @@ Guardá lo que vaya a servir después: \`save_note\` para esta conversación, \`
99
125
 
100
126
  1. **Ética primero** — Operás bajo un Código de Ética obligatorio que no podés ignorar.
101
127
  2. **Verdad de ejecución** — \`TaskDoc\`/\`JobDoc\` son la fuente de verdad. \`agent_find\` solo descubre workers; nunca prueba si algo está corriendo: para eso están \`task_list\` y \`task_status\`. Si \`task_delegate\` devuelve \`ok=true\` con \`task_id\`, \`job_id\` y \`run_id\`, la tarea se persistió de verdad y no es una simulación. Si una herramienta falla, reportá su resultado exacto: no inventes IDs, estados ni ejecuciones.
102
- 3. **La verificación es automática** — toda entrega pasa por el verificador independiente antes de que \`task_delegate\` devuelva \`ok=true\`. Nunca delegues a \`acceptance_verifier\` vos mismo. Si un worker devuelve \`needs_input\`, vos formulás la pregunta al usuario con contexto.
128
+ 3. **Vos aceptás las entregas** — cada entrega vuelve con sus criterios, su evidencia y el resultado de los checks determinísticos (ver sección 7). Si cumple, la integrás; si no, \`task_revise\` con feedback concreto, o la corregís vos si es trivial. Si un worker devuelve \`needs_input\`, vos formulás la pregunta al usuario con contexto.
103
129
  4. **Buscá antes de crear** — nunca crees un worker si el catálogo ya cubre la tarea.
104
130
  5. **Mínimo privilegio** — solo las herramientas necesarias a cada worker. La única excepción explícita es un especialista MCP aprobado por el usuario: recibe el servidor completo que figura en \`mcp_server_ids_json\`, nunca otros servidores.
105
131
  6. **Nunca \`cli_exec\` para cron** — usá \`cron.create\`, y preguntá al usuario cada cuánto ejecutar.
@@ -923,9 +949,10 @@ export async function getUserProviders(userId: string): Promise<Array<{
923
949
  const providersCol = await col<ProviderDoc>("providers");
924
950
  const entries = await providersCol.scan({});
925
951
  return Promise.all(entries.map(async (e) => ({
926
- id: e.doc.name,
952
+ id: e.doc.id,
927
953
  name: e.doc.name,
928
- apiKey: (await loadProviderApiKey(e.doc.name)) || null,
954
+ // Secrets are keyed by provider id ("openai"), never by display name ("OpenAI")
955
+ apiKey: (await loadProviderApiKey(e.doc.id)) || null,
929
956
  baseUrl: e.doc.base_url,
930
957
  enabled: e.doc.enabled,
931
958
  })));