@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,10 +11,12 @@ export interface ResolveContextResult {
11
11
  export interface ResolveContextOptions {
12
12
  channel: string
13
13
  channelUserId: string
14
+ /** Channel account the message arrived on — persisted so replies can be routed back to it. */
15
+ accountId?: string
14
16
  }
15
17
 
16
18
  export async function resolveContext(options: ResolveContextOptions): Promise<ResolveContextResult> {
17
- const { channel, channelUserId } = options
19
+ const { channel, channelUserId, accountId } = options
18
20
 
19
21
  const identitiesCol = await col<UserIdentityDoc>("userIdentities")
20
22
  const usersCol = await col<UserDoc>("users")
@@ -28,6 +30,11 @@ export async function resolveContext(options: ResolveContextOptions): Promise<Re
28
30
 
29
31
  if (identity) {
30
32
  userId = identity.doc.user_id
33
+ // Backfill/refresh the owning account so replies survive a restart, when
34
+ // the in-memory session→account map in ChannelManager is empty.
35
+ if (accountId && identity.doc.account_id !== accountId) {
36
+ await identitiesCol.put(identity.id, { ...identity.doc, account_id: accountId })
37
+ }
31
38
  } else {
32
39
  // Sistema mono-usuario: reutilizar el usuario del onboarding
33
40
  const allUsers = await usersCol.scan({})
@@ -43,7 +50,8 @@ export async function resolveContext(options: ResolveContextOptions): Promise<Re
43
50
  // put(): si ya existe una fila (user_id, channel), actualiza channel_user_id
44
51
  // con el valor real del canal (e.g. chat ID numérico de Telegram).
45
52
  await identitiesCol.put(`${userId}:${channel}`, {
46
- user_id: userId, channel, channel_user_id: channelUserId, linked_at: Date.now(),
53
+ user_id: userId, channel, channel_user_id: channelUserId,
54
+ account_id: accountId, linked_at: Date.now(),
47
55
  })
48
56
  }
49
57
 
@@ -0,0 +1,43 @@
1
+ import { canvasManager } from "../../canvas/canvas-manager.ts";
2
+ import { resolveUserId } from "../../storage/onboarding.ts";
3
+
4
+ /**
5
+ * Returns the durable-in-process A2UI surfaces for the authenticated user.
6
+ * The client should use these IDs for cleanup instead of guessing a surface
7
+ * name such as "main" or "saludo".
8
+ */
9
+ export async function handleGetA2UISurfaces(
10
+ req: Request,
11
+ addCorsHeaders: (response: Response, request: Request) => Response,
12
+ ): Promise<Response> {
13
+ const userId = await resolveUserId({});
14
+ if (!userId) {
15
+ return addCorsHeaders(Response.json({ surfaces: [], sessionId: null }), req);
16
+ }
17
+
18
+ const sessionId = `canvas:${userId}`;
19
+ return addCorsHeaders(Response.json({
20
+ sessionId,
21
+ surfaces: canvasManager.getA2UISurfaces(sessionId),
22
+ }), req);
23
+ }
24
+
25
+ export async function handleDeleteA2UISurface(
26
+ req: Request,
27
+ addCorsHeaders: (response: Response, request: Request) => Response,
28
+ ): Promise<Response> {
29
+ const userId = await resolveUserId({});
30
+ const surfaceId = decodeURIComponent(new URL(req.url).pathname.split("/").pop() ?? "");
31
+ if (!userId || !surfaceId) {
32
+ return addCorsHeaders(Response.json({ success: false, error: "surfaceId required" }, { status: 400 }), req);
33
+ }
34
+
35
+ const sessionId = `canvas:${userId}`;
36
+ const known = canvasManager.getA2UISurfaces(sessionId).some((surface) => surface.surfaceId === surfaceId);
37
+ if (!known) {
38
+ return addCorsHeaders(Response.json({ success: false, error: "Surface not found", surfaceId }, { status: 404 }), req);
39
+ }
40
+
41
+ await canvasManager.sendA2UIMessage(sessionId, "a2ui:deleteSurface", { surfaceId });
42
+ return addCorsHeaders(Response.json({ success: true, sessionId, surfaceId }), req);
43
+ }
@@ -1,5 +1,5 @@
1
1
  import { col, updateDoc, toIndexable, fromIndexable } from "../../storage/hive"
2
- import type { AgentDoc, AgentProposalDoc, McpServerDoc, SkillDoc, UserDoc, VerificationDoc } from "../../storage/collections"
2
+ import type { AgentDoc, AgentProposalDoc, McpServerDoc, SkillDoc, TaskDoc, UserDoc } from "../../storage/collections"
3
3
  import { emitCanvas } from "../../canvas/emitter"
4
4
  import { storeAgentHeaders, deleteAgentSecrets } from "../../storage/crypto"
5
5
  import { getDefaultLLM } from "../../agent/llm-client"
@@ -11,7 +11,7 @@ export async function handleGetAgents(req: Request, addCorsHeaders: (r: Response
11
11
 
12
12
  const agentsCol = await col<AgentDoc>("agents")
13
13
  const usersCol = await col<UserDoc>("users")
14
- const verificationsCol = await col<VerificationDoc>("verifications")
14
+ const tasksCol = await col<TaskDoc>("tasks")
15
15
  const skillsCol = await col<SkillDoc>("skills")
16
16
  const mcpServersCol = await col<McpServerDoc>("mcpServers")
17
17
  const mcpServers = new Map(
@@ -49,11 +49,11 @@ export async function handleGetAgents(req: Request, addCorsHeaders: (r: Response
49
49
 
50
50
  let lastVerification: { status: string; taskId: string; createdAt: number } | null = null
51
51
  if (isCatalog) {
52
- const verificationRows = await verificationsCol.findBy("executor_agent_id", row.doc.id)
53
- const latest = verificationRows.length
54
- ? verificationRows.map(e => e.doc).sort((a, b) => b.created_at - a.created_at)[0]
52
+ const taskRows = await tasksCol.findBy("agent_id", row.doc.id)
53
+ const latest = taskRows.length
54
+ ? taskRows.map(e => e.doc).sort((a, b) => b.updated_at - a.updated_at)[0]
55
55
  : null
56
- lastVerification = latest ? { status: latest.status, taskId: latest.task_id, createdAt: latest.created_at } : null
56
+ lastVerification = latest ? { status: latest.status, taskId: latest.id, createdAt: latest.updated_at } : null
57
57
  }
58
58
 
59
59
  return {
@@ -1,6 +1,7 @@
1
1
  import { col, updateDoc, toIndexable } from "../../storage/hive"
2
2
  import type { ChannelDoc } from "../../storage/collections"
3
3
  import { storeChannelConfig, loadChannelConfig, deleteChannelSecrets } from "../../storage/crypto"
4
+ import { invalidateNarrationModeCache, DEFAULT_NARRATION_MODE } from "../../events/channel-narration"
4
5
 
5
6
  export async function handleGetChannels(
6
7
  req: Request,
@@ -162,7 +163,7 @@ export async function handleCreateChannel(
162
163
  await channelsCol.put(id, {
163
164
  id, user_id: toIndexable(null), type, enabled: true, active: true, status: "connecting",
164
165
  last_active: null, voice_enabled: false, tts_enabled: false, stt_provider: null, tts_provider: null,
165
- tts_voice_id: null, step_delivery_mode: "new_messages", vision_enabled: false,
166
+ tts_voice_id: null, step_delivery_mode: DEFAULT_NARRATION_MODE, vision_enabled: false,
166
167
  ocr_provider: null, vision_provider: null, vision_model_id: null,
167
168
  }, { expectedVersion: 0 });
168
169
  }
@@ -340,6 +341,16 @@ export async function handleUpdateChannelSettings(
340
341
  }
341
342
  }
342
343
 
344
+ if ("step_delivery_mode" in patch) {
345
+ const mode = patch.step_delivery_mode;
346
+ if (mode !== "off" && mode !== "milestones" && mode !== "all") {
347
+ return addCorsHeaders(Response.json(
348
+ { error: "step_delivery_mode must be one of: off, milestones, all" },
349
+ { status: 400 }
350
+ ), req);
351
+ }
352
+ }
353
+
343
354
  // Merge type-specific config into the secrets store if body.config is provided
344
355
  const newConfig = body.config as Record<string, unknown> | undefined;
345
356
  if (newConfig && typeof newConfig === "object" && Object.keys(newConfig).length > 0) {
@@ -355,6 +366,9 @@ export async function handleUpdateChannelSettings(
355
366
 
356
367
  if (entry) {
357
368
  await channelsCol.put(channelId, { ...entry.doc, ...patch }, { expectedVersion: entry.version });
369
+ // Narration delivery caches the mode per channel type — drop it so the new
370
+ // setting applies to the next turn instead of after the TTL.
371
+ if ("step_delivery_mode" in patch) invalidateNarrationModeCache(entry.doc.type);
358
372
  }
359
373
 
360
374
  return addCorsHeaders(Response.json({ success: true }), req);
@@ -1,6 +1,8 @@
1
1
  import { col, updateDoc } from "../../storage/hive.ts"
2
2
  import { getHiveDb } from "../../storage/hivedb.ts"
3
- import type { ModelDoc, AgentDoc } from "../../storage/collections.ts"
3
+ import type { ModelDoc, AgentDoc, ProviderDoc } from "../../storage/collections.ts"
4
+ import { catalogModelKey, wireModelId } from "../../storage/model-id.ts"
5
+ import { invalidateModelPricingCache } from "../../storage/usage.ts"
4
6
  import type { Config } from "../../config/loader.ts"
5
7
 
6
8
  export async function handleGetModels(req: Request, addCorsHeaders: (r: Response, req: Request) => Response): Promise<Response> {
@@ -12,24 +14,47 @@ export async function handleGetModels(req: Request, addCorsHeaders: (r: Response
12
14
  ? await modelsCol.findBy("provider_id", providerId)
13
15
  : await modelsCol.scan({})
14
16
 
15
- const models = entries.map(e => e.doc).sort((a, b) => a.name.localeCompare(b.name))
17
+ // `wire_id` = el nombre que el provider espera, derivado acá y no en el front:
18
+ // la lista de providers revendedores vive en storage/model-id.ts y no debe
19
+ // duplicarse en la UI.
20
+ const models = entries
21
+ .map(e => ({ ...e.doc, wire_id: wireModelId(e.doc.provider_id, e.doc.id) }))
22
+ .sort((a, b) => a.name.localeCompare(b.name))
16
23
 
17
24
  return addCorsHeaders(Response.json({ models }), req)
18
25
  }
19
26
 
27
+ /** Precio opcional: sólo se acepta un número finito >= 0; cualquier otra cosa queda como "sin tarifa". */
28
+ function parsePrice(value: unknown): number | null {
29
+ if (value === null || value === undefined || value === "") return null
30
+ const n = typeof value === "number" ? value : Number(value)
31
+ return Number.isFinite(n) && n >= 0 ? n : null
32
+ }
33
+
34
+ /** `["chat","vision"]` → string JSON; acepta ya-un-string o un array. */
35
+ function parseCapabilities(value: unknown): string | null {
36
+ if (!value) return null
37
+ if (typeof value === "string") return value.trim() || null
38
+ if (Array.isArray(value)) return value.length ? JSON.stringify(value) : null
39
+ return null
40
+ }
41
+
20
42
  export async function handleCreateModel(req: Request, addCorsHeaders: (r: Response, req: Request) => Response): Promise<Response> {
21
43
  const body = await req.json().catch(() => ({}))
22
44
 
23
45
  const providerId = body.provider_id || body.providerId
24
46
  const name = body.name
25
47
  const modelType = body.model_type || body.modelType || "llm"
26
- const contextWindow = body.context_window || body.contextWindow || 50000
48
+ const contextWindow = Number(body.context_window ?? body.contextWindow) || 50000
27
49
 
28
50
  if (!name || !providerId) {
29
51
  return addCorsHeaders(Response.json({ ok: false, error: "name and provider_id are required" }, { status: 400 }), req)
30
52
  }
31
53
 
32
- const id = body.id || name
54
+ // El id del request es el nombre que el provider espera en el cable; la clave
55
+ // de la BD lleva el prefijo del revendedor (igual que el catálogo sembrado).
56
+ const wireId = body.id || name
57
+ const id = catalogModelKey(providerId, wireId)
33
58
  const modelsCol = await col<ModelDoc>("models")
34
59
  const existing = await modelsCol.get(id)
35
60
  if (existing) {
@@ -38,9 +63,17 @@ export async function handleCreateModel(req: Request, addCorsHeaders: (r: Respon
38
63
 
39
64
  const model: ModelDoc = {
40
65
  id, name, provider_id: providerId, model_type: modelType,
41
- context_window: contextWindow, capabilities: null, enabled: true, active: true,
66
+ context_window: contextWindow,
67
+ capabilities: parseCapabilities(body.capabilities),
68
+ enabled: true, active: true,
69
+ // "discovered" y no "catalog": un modelo agregado a mano no se puede recrear
70
+ // desde SEED_DATA, así que el wipe del re-seed no debe borrarlo.
71
+ source: "discovered",
72
+ input_per_1m: parsePrice(body.input_per_1m ?? body.inputPer1M),
73
+ output_per_1m: parsePrice(body.output_per_1m ?? body.outputPer1M),
42
74
  }
43
75
  await modelsCol.put(id, model, { expectedVersion: 0 })
76
+ invalidateModelPricingCache()
44
77
 
45
78
  return addCorsHeaders(Response.json({ ok: true, id, model }, { status: 201 }), req)
46
79
  }
@@ -67,9 +100,18 @@ export async function handleGetModelsConfig(
67
100
  addCorsHeaders: (r: Response, req: Request) => Response,
68
101
  config: Config
69
102
  ): Promise<Response> {
103
+ // Los providers salen de la BD, no de una lista fija: la que estaba acá se
104
+ // quedó sin nvidia, groq, minimax, qwen, z-ai ni opencode-go, y cada provider
105
+ // nuevo del catálogo habría que acordarse de agregarlo también acá.
106
+ const providersCol = await col<ProviderDoc>("providers")
107
+ const availableProviders = (await providersCol.scan({}))
108
+ .filter(p => (p.doc.category ?? "llm") === "llm")
109
+ .map(p => p.doc.id)
110
+ .sort()
111
+
70
112
  return addCorsHeaders(Response.json({
71
113
  config: config.models || {},
72
- availableProviders: ["openai", "anthropic", "gemini", "kimi", "ollama", "openrouter", "deepseek"],
114
+ availableProviders,
73
115
  }), req);
74
116
  }
75
117
 
@@ -96,6 +138,7 @@ export async function handleDeleteModel(req: Request, addCorsHeaders: (r: Respon
96
138
  }
97
139
 
98
140
  await modelsCol.delete(modelId)
141
+ invalidateModelPricingCache()
99
142
  return addCorsHeaders(Response.json({ ok: true }), req)
100
143
  }
101
144
 
@@ -115,13 +158,26 @@ export async function handleUpdateModel(req: Request, addCorsHeaders: (r: Respon
115
158
  }
116
159
 
117
160
  const body = await req.json().catch(() => ({}))
118
- const newId: string | undefined = body.id
119
161
  const newName: string | undefined = body.name
162
+ // El id que llega es el nombre de cable; la clave lleva el prefijo del revendedor.
163
+ const newId: string | undefined = body.id
164
+ ? catalogModelKey(existing.doc.provider_id, body.id)
165
+ : undefined
166
+
167
+ // Campos de catálogo editables. `undefined` = "no lo mandaron, no lo toques";
168
+ // null en un precio sí es un cambio explícito a "sin tarifa".
169
+ const patch: Partial<ModelDoc> = {}
170
+ if (newName) patch.name = newName
171
+ if (body.model_type ?? body.modelType) patch.model_type = (body.model_type ?? body.modelType) as ModelDoc["model_type"]
172
+ const ctx = Number(body.context_window ?? body.contextWindow)
173
+ if (Number.isFinite(ctx) && ctx > 0) patch.context_window = ctx
174
+ if ("capabilities" in body) patch.capabilities = parseCapabilities(body.capabilities)
175
+ if ("input_per_1m" in body || "inputPer1M" in body) patch.input_per_1m = parsePrice(body.input_per_1m ?? body.inputPer1M)
176
+ if ("output_per_1m" in body || "outputPer1M" in body) patch.output_per_1m = parsePrice(body.output_per_1m ?? body.outputPer1M)
120
177
 
121
178
  if (!newId || newId === oldId) {
122
- // Only name change
123
- const name = newName || existing.doc.name
124
- await modelsCol.put(oldId, { ...existing.doc, name }, { expectedVersion: existing.version })
179
+ await modelsCol.put(oldId, { ...existing.doc, ...patch }, { expectedVersion: existing.version })
180
+ invalidateModelPricingCache()
125
181
  const model = (await modelsCol.get(oldId))?.doc
126
182
  return addCorsHeaders(Response.json({ ok: true, model }), req)
127
183
  }
@@ -133,8 +189,8 @@ export async function handleUpdateModel(req: Request, addCorsHeaders: (r: Respon
133
189
  return addCorsHeaders(Response.json({ ok: false, error: "Ya existe un modelo con ese ID" }, { status: 409 }), req)
134
190
  }
135
191
 
136
- const name = newName || existing.doc.name
137
- const newModel: ModelDoc = { ...existing.doc, id: newId, name }
192
+ // El rename arrastra también el resto de campos editados en el mismo submit.
193
+ const newModel: ModelDoc = { ...existing.doc, ...patch, id: newId }
138
194
 
139
195
  const agentsCol = await col<AgentDoc>("agents")
140
196
  const affectedAgents = await agentsCol.findBy("model_id", oldId)
@@ -148,6 +204,7 @@ export async function handleUpdateModel(req: Request, addCorsHeaders: (r: Respon
148
204
  doc: { ...a.doc, model_id: newId }, expectedVersion: a.version,
149
205
  })),
150
206
  ])
207
+ invalidateModelPricingCache()
151
208
 
152
209
  return addCorsHeaders(Response.json({ ok: true, model: newModel }), req)
153
210
  }
@@ -1,5 +1,6 @@
1
1
  import { col, updateDoc, updateManyByIndex } from "../../storage/hive"
2
2
  import type { ProviderDoc, ModelDoc, AgentDoc } from "../../storage/collections"
3
+ import { catalogModelKey, wireModelId } from "../../storage/model-id"
3
4
  import {
4
5
  maskApiKey,
5
6
  loadProviderApiKey, storeProviderApiKey,
@@ -20,7 +21,7 @@ export async function handleGetProviders(req: Request, addCorsHeaders: (r: Respo
20
21
  for (const m of modelsRows) {
21
22
  const pid = m.doc.provider_id
22
23
  if (!modelsByProvider[pid]) modelsByProvider[pid] = []
23
- modelsByProvider[pid].push({ ...m.doc, provider_id: pid })
24
+ modelsByProvider[pid].push({ ...m.doc, provider_id: pid, wire_id: wireModelId(pid, m.doc.id) })
24
25
  }
25
26
 
26
27
  const providers = await Promise.all(rawProviders.map(async (p) => {
@@ -120,6 +121,96 @@ export async function handleUpdateProvider(req: Request, addCorsHeaders: (r: Res
120
121
  return addCorsHeaders(Response.json({ ok: true }), req)
121
122
  }
122
123
 
124
+ /**
125
+ * Pregunta al provider qué modelos sirve hoy. NO escribe en la BD: la usan tanto
126
+ * el sync como el explorador del formulario de alta.
127
+ *
128
+ * El `base_url` guardado ya incluye el segmento de versión
129
+ * (`.../v1`, `.../api/paas/v4`), así que sólo se le cuelga `/models`. La versión
130
+ * anterior recortaba `/v1` para volver a agregarlo, lo que funcionaba de casualidad
131
+ * en los `/v1` y armaba `/api/paas/v4/v1/models` en los demás.
132
+ */
133
+ // Una sola forma en vez de una unión discriminada: el proyecto compila sin
134
+ // `strictNullChecks`, y sin él TS no estrecha `if (!result.ok)`.
135
+ interface DiscoveryResult {
136
+ names: string[]
137
+ error?: string
138
+ /** Código HTTP a devolver cuando `error` está presente. */
139
+ status?: number
140
+ }
141
+
142
+ export async function fetchProviderModelNames(
143
+ providerId: string,
144
+ baseUrl: string | null
145
+ ): Promise<DiscoveryResult> {
146
+ if (providerId === "ollama") {
147
+ const host = (baseUrl || "http://localhost:11434").replace(/\/+$/, "").replace(/\/(v1|api)$/, "")
148
+ const res = await fetch(`${host}/api/tags`, { signal: AbortSignal.timeout(10000) })
149
+ if (!res.ok) return { names: [], error: `Ollama responded ${res.status}`, status: 502 }
150
+ const data = await res.json() as { models: Array<{ name: string }> }
151
+ return { names: (data.models || []).map(m => m.name) }
152
+ }
153
+
154
+ if (!baseUrl) {
155
+ return { names: [], error: `El provider "${providerId}" no tiene base_url configurada.`, status: 400 }
156
+ }
157
+
158
+ // Se manda la key si el provider tiene una: hay endpoints cuyo listado es
159
+ // público (ModelScope, NVIDIA) y otros que devuelven 401 sin autenticar
160
+ // (DashScope), donde sin esto el explorador de modelos no servía.
161
+ const apiKey = await loadProviderApiKey(providerId).catch(() => null)
162
+ const headers: Record<string, string> = apiKey ? { Authorization: `Bearer ${apiKey}` } : {}
163
+
164
+ const res = await fetch(`${baseUrl.replace(/\/+$/, "")}/models`, {
165
+ headers,
166
+ signal: AbortSignal.timeout(10000),
167
+ })
168
+ if (!res.ok) return { names: [], error: `${providerId} responded ${res.status}`, status: 502 }
169
+ const data = await res.json() as { data: Array<{ id: string }> }
170
+ return { names: (data.data || []).map(m => m.id) }
171
+ }
172
+
173
+ /**
174
+ * GET /api/providers/:id/available-models — sólo lectura.
175
+ * El sync persiste TODO lo que devuelve el provider (102 modelos en NVIDIA), que
176
+ * no es lo que querés al explorar para agregar uno: acá se devuelve la lista y el
177
+ * usuario elige.
178
+ */
179
+ export async function handleGetProviderAvailableModels(
180
+ req: Request,
181
+ addCorsHeaders: (r: Response, req: Request) => Response,
182
+ providerId: string
183
+ ): Promise<Response> {
184
+ const providersCol = await col<ProviderDoc>("providers")
185
+ const providerEntry = await providersCol.get(providerId)
186
+ if (!providerEntry) {
187
+ return addCorsHeaders(Response.json({ error: "Provider not found" }, { status: 404 }), req)
188
+ }
189
+
190
+ try {
191
+ const result = await fetchProviderModelNames(providerId, providerEntry.doc.base_url)
192
+ if (result.error) {
193
+ return addCorsHeaders(Response.json({ error: result.error }, { status: result.status }), req)
194
+ }
195
+
196
+ // Qué ya está agregado, para que la UI lo marque en vez de duplicarlo.
197
+ const modelsCol = await col<ModelDoc>("models")
198
+ const existing = new Set((await modelsCol.findBy("provider_id", providerId)).map(m => m.id))
199
+
200
+ const models = result.names.map(name => ({
201
+ wire_id: name,
202
+ id: catalogModelKey(providerId, name),
203
+ already_added: existing.has(catalogModelKey(providerId, name)),
204
+ })).sort((a, b) => a.wire_id.localeCompare(b.wire_id))
205
+
206
+ return addCorsHeaders(Response.json({ models }), req)
207
+ } catch (err) {
208
+ return addCorsHeaders(Response.json({
209
+ error: `No se pudo consultar ${providerId}: ${(err as Error).message}`,
210
+ }, { status: 502 }), req)
211
+ }
212
+ }
213
+
123
214
  export async function handleSyncProviderModels(
124
215
  req: Request,
125
216
  addCorsHeaders: (r: Response, req: Request) => Response,
@@ -133,56 +224,47 @@ export async function handleSyncProviderModels(
133
224
  return addCorsHeaders(new Response("Provider not found", { status: 404 }), req)
134
225
  }
135
226
 
136
- const baseUrl = (providerEntry.doc.base_url || "http://localhost:11434").replace(/\/(v1|api)\/?$/, "")
137
-
138
227
  try {
139
- let modelNames: string[] = []
140
-
141
- // Ollama uses /api/tags, OpenAI-compatible providers use /v1/models
142
- if (providerId === "ollama") {
143
- const res = await fetch(`${baseUrl}/api/tags`, { signal: AbortSignal.timeout(10000) })
144
- if (!res.ok) {
145
- return addCorsHeaders(Response.json({ error: `Ollama responded ${res.status}` }, { status: 502 }), req)
146
- }
147
- const data = await res.json() as { models: Array<{ name: string }> }
148
- modelNames = (data.models || []).map(m => m.name)
149
- } else {
150
- // OpenAI-compatible: groq, mistral, etc.
151
- const res = await fetch(`${baseUrl}/v1/models`, { signal: AbortSignal.timeout(10000) })
152
- if (!res.ok) {
153
- return addCorsHeaders(Response.json({ error: `${providerId} responded ${res.status}` }, { status: 502 }), req)
154
- }
155
- const data = await res.json() as { data: Array<{ id: string }> }
156
- modelNames = (data.data || []).map(m => m.id)
228
+ const discovered = await fetchProviderModelNames(providerId, providerEntry.doc.base_url)
229
+ if (discovered.error) {
230
+ return addCorsHeaders(Response.json({ error: discovered.error }, { status: discovered.status }), req)
157
231
  }
232
+ const modelNames = discovered.names
158
233
 
159
234
  if (modelNames.length === 0) {
160
235
  return addCorsHeaders(Response.json({ error: "No models found from provider" }, { status: 400 }), req)
161
236
  }
162
237
 
238
+ // Los ids se guardan con la clave de catálogo (prefijada en los providers
239
+ // revendedores) para que dos servicios que sirvan el mismo modelo no se
240
+ // pisen la fila.
241
+ const discoveredKeys = new Set(modelNames.map(n => catalogModelKey(providerId, n)))
163
242
  for (const name of modelNames) {
164
- const existing = await modelsCol.get(name)
165
- await modelsCol.put(name, {
166
- id: name, provider_id: providerId, name,
243
+ const key = catalogModelKey(providerId, name)
244
+ const existing = await modelsCol.get(key)
245
+ await modelsCol.put(key, {
246
+ id: key, provider_id: providerId, name,
167
247
  model_type: existing?.doc.model_type ?? "llm",
168
248
  context_window: existing?.doc.context_window ?? 32768,
169
249
  capabilities: existing?.doc.capabilities ?? null,
170
250
  enabled: true, active: true,
171
251
  source: existing?.doc.source ?? "discovered",
252
+ input_per_1m: existing?.doc.input_per_1m ?? null,
253
+ output_per_1m: existing?.doc.output_per_1m ?? null,
172
254
  }, existing ? { expectedVersion: existing.version } : undefined)
173
255
  }
174
256
 
175
257
  // Disable models that are no longer present
176
258
  const existingModels = await modelsCol.findBy("provider_id", providerId)
177
259
  for (const row of existingModels) {
178
- if (!modelNames.includes(row.id)) {
260
+ if (!discoveredKeys.has(row.id)) {
179
261
  await modelsCol.put(row.id, { ...row.doc, active: false, enabled: false }, { expectedVersion: row.version })
180
262
  }
181
263
  }
182
264
 
183
- const models = (await modelsCol.findBy("provider_id", providerId)).map(m => ({
184
- id: m.doc.id, name: m.doc.name, provider_id: m.doc.provider_id, enabled: m.doc.enabled, active: m.doc.active,
185
- }))
265
+ // Se devuelve el doc completo: recortar los campos dejaba a la UI sin
266
+ // context_window ni precio justo después de sincronizar.
267
+ const models = (await modelsCol.findBy("provider_id", providerId)).map(m => m.doc)
186
268
 
187
269
  return addCorsHeaders(Response.json({
188
270
  success: true,
@@ -0,0 +1,58 @@
1
+ import { col } from "../../storage/hive.ts";
2
+ import type { AgentDoc, SkillDoc } from "../../storage/collections.ts";
3
+ import { getHiveDir } from "../../config/loader.ts";
4
+ import pkg from "../../../../../package.json";
5
+
6
+ const REQUIRED_CATALOG_SKILLS = ["a2ui_form", "a2ui_dashboard", "a2ui_interactive"];
7
+
8
+ function parseSkillIds(value: string | null | undefined): string[] {
9
+ try {
10
+ const parsed = value ? JSON.parse(value) : [];
11
+ return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === "string") : [];
12
+ } catch {
13
+ return [];
14
+ }
15
+ }
16
+
17
+ /**
18
+ * Runtime facts used by the desktop UI to distinguish an empty database from
19
+ * an old/incomplete gateway sidecar. This endpoint deliberately reports
20
+ * catalog metadata only; skill bodies and secrets are never included.
21
+ */
22
+ export async function handleGetRuntimeStatus(
23
+ req: Request,
24
+ addCorsHeaders: (response: Response, request: Request) => Response,
25
+ ): Promise<Response> {
26
+ const skills = (await (await col<SkillDoc>("skills")).scan({})).map((entry) => entry.doc);
27
+ const agents = (await (await col<AgentDoc>("agents")).scan({})).map((entry) => entry.doc);
28
+ const byName = new Map(skills.map((skill) => [skill.name, skill]));
29
+ const a2uiBuilder = agents.find((agent) => agent.id === "a2ui_builder");
30
+ const required = REQUIRED_CATALOG_SKILLS.map((name) => ({
31
+ name,
32
+ present: byName.has(name),
33
+ active: byName.get(name)?.active === true,
34
+ }));
35
+
36
+ return addCorsHeaders(Response.json({
37
+ version: pkg.version,
38
+ process: {
39
+ execPath: process.execPath,
40
+ nodeEnv: process.env.NODE_ENV ?? null,
41
+ },
42
+ hiveHome: process.env.HIVE_HOME ?? getHiveDir(),
43
+ skills: {
44
+ total: skills.length,
45
+ active: skills.filter((skill) => skill.active).length,
46
+ required,
47
+ },
48
+ agents: {
49
+ a2ui_builder: a2uiBuilder
50
+ ? {
51
+ enabled: a2uiBuilder.enabled,
52
+ skills: parseSkillIds(a2uiBuilder.skills_json),
53
+ }
54
+ : null,
55
+ },
56
+ healthy: required.every((skill) => skill.present && skill.active),
57
+ }), req);
58
+ }