@johpaz/hive-agents 1.0.1 → 1.0.3

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 (120) hide show
  1. package/README.md +3 -3
  2. package/dist/hive.js +1286 -764
  3. package/dist/ui/assets/A2UIPage-DExwevBV.js +8 -0
  4. package/dist/ui/assets/{AgentCreateForm-M2RhjeA1.js → AgentCreateForm-7PPShsUn.js} +1 -1
  5. package/dist/ui/assets/{AgentDetailPage-DkFRtj8g.js → AgentDetailPage-CiV4tz4P.js} +1 -1
  6. package/dist/ui/assets/AgentNewPage-D3TtVwQf.js +1 -0
  7. package/dist/ui/assets/{AgentsPage-Ctzq2LWx.js → AgentsPage-C2DThet7.js} +1 -1
  8. package/dist/ui/assets/{ApiClientPage-DKbGO1QW.js → ApiClientPage-Cowdq-0f.js} +1 -1
  9. package/dist/ui/assets/{ChannelsPage-H6rgr8DQ.js → ChannelsPage-D4IgglwJ.js} +1 -1
  10. package/dist/ui/assets/{DashboardPage-BIjYGf4m.js → DashboardPage-DAgVB7Iy.js} +1 -1
  11. package/dist/ui/assets/{LoginPage-DazoxtBJ.js → LoginPage-CpU61b3u.js} +1 -1
  12. package/dist/ui/assets/{LogsPage-DMZ6KtQ3.js → LogsPage-DyJOGQNy.js} +1 -1
  13. package/dist/ui/assets/{MeetingPage-CSLFvHL7.js → MeetingPage-DLmqHmm2.js} +1 -1
  14. package/dist/ui/assets/{ModelSelector-BCfvugHB.js → ModelSelector-D4OaICwN.js} +1 -1
  15. package/dist/ui/assets/{Office3DPage-BE6Epe0d.js → Office3DPage-BvO66B0h.js} +1 -1
  16. package/dist/ui/assets/{ProvidersPage-D0cApfM1.js → ProvidersPage-Bhb6Qr87.js} +1 -1
  17. package/dist/ui/assets/{RecoverPage-BVUPHG9z.js → RecoverPage-DaZrCpdB.js} +1 -1
  18. package/dist/ui/assets/SettingsPage-BRD2F7up.js +9 -0
  19. package/dist/ui/assets/{SetupPage-In19p30M.js → SetupPage-DKppgTja.js} +1 -1
  20. package/dist/ui/assets/WebChatPage-CPtETNL5.js +29 -0
  21. package/dist/ui/assets/{activity-BIIli7ET.js → activity-BSosMryb.js} +1 -1
  22. package/dist/ui/assets/{agentCapabilities-D1PD9yFH.js → agentCapabilities-VqxLmrF6.js} +1 -1
  23. package/dist/ui/assets/arrow-left-C9Y6p4Jt.js +1 -0
  24. package/dist/ui/assets/arrow-right-BYfOLnTB.js +1 -0
  25. package/dist/ui/assets/arrow-up-right-D2trA3Ob.js +1 -0
  26. package/dist/ui/assets/{calendar-S9-_Q6QR.js → calendar-rdd4nvY1.js} +1 -1
  27. package/dist/ui/assets/check-DUq9uoNQ.js +1 -0
  28. package/dist/ui/assets/chevron-down-rPF4Pr1n.js +1 -0
  29. package/dist/ui/assets/chevron-left-Crzzf2sY.js +1 -0
  30. package/dist/ui/assets/chevron-right-DtMIvG9A.js +1 -0
  31. package/dist/ui/assets/chevron-up-CG0_KGBy.js +1 -0
  32. package/dist/ui/assets/{circle-alert-DTVW4R94.js → circle-alert-CYt6gsDA.js} +1 -1
  33. package/dist/ui/assets/circle-check-Zl32-jCa.js +1 -0
  34. package/dist/ui/assets/{circle-x-CJXbXzRh.js → circle-x-BJXzKGmx.js} +1 -1
  35. package/dist/ui/assets/{copy-X_TPpA-A.js → copy-BmtJXmDe.js} +1 -1
  36. package/dist/ui/assets/{dialog-uUBz_NIB.js → dialog-Dn9hGPYl.js} +1 -1
  37. package/dist/ui/assets/{download-C-fXu08w.js → download-D3mYhuuL.js} +1 -1
  38. package/dist/ui/assets/{earth-CTsVjCmp.js → earth-BZzdDXFC.js} +1 -1
  39. package/dist/ui/assets/{ellipsis-vertical-5zBh5yzc.js → ellipsis-vertical-BF705XvB.js} +1 -1
  40. package/dist/ui/assets/{external-link-CvpRhwC_.js → external-link-gdpMTHUV.js} +1 -1
  41. package/dist/ui/assets/{eye-CM-HQEWU.js → eye-lSG04hI7.js} +1 -1
  42. package/dist/ui/assets/{file-text-lwkvYGtA.js → file-text-CjQxcJvN.js} +1 -1
  43. package/dist/ui/assets/gauge-DBryKhDK.js +1 -0
  44. package/dist/ui/assets/{history-eSHspWRr.js → history-BC6ir9qU.js} +1 -1
  45. package/dist/ui/assets/{index-ZjAc-KQS.js → index-DyxoAvTq.js} +2 -2
  46. package/dist/ui/assets/index-wML8DaUo.css +2 -0
  47. package/dist/ui/assets/{info-DTgFQ_jA.js → info-BGBaIyKc.js} +1 -1
  48. package/dist/ui/assets/{key-CeM9JJkq.js → key-D_CNJTY2.js} +1 -1
  49. package/dist/ui/assets/loader-circle-RXdrfPsH.js +1 -0
  50. package/dist/ui/assets/{lock-open-B089GUAJ.js → lock-open-UB61lorP.js} +1 -1
  51. package/dist/ui/assets/{mail--gNFIe4M.js → mail-C5bJ_dBt.js} +1 -1
  52. package/dist/ui/assets/{pause-DjT1nwQM.js → pause-BSTJvxDu.js} +1 -1
  53. package/dist/ui/assets/{pencil-6PRgdjiU.js → pencil-C2B1Q7y2.js} +1 -1
  54. package/dist/ui/assets/play-tcMbj-0p.js +1 -0
  55. package/dist/ui/assets/plus-BSZvyMND.js +1 -0
  56. package/dist/ui/assets/{radio-D-joO9J0.js → radio-D9CrjAar.js} +1 -1
  57. package/dist/ui/assets/{refresh-cw-BRrzoHQW.js → refresh-cw-D7EB_fVv.js} +1 -1
  58. package/dist/ui/assets/search-5S6LY69I.js +1 -0
  59. package/dist/ui/assets/{select-BOR8MsSL.js → select-ot0a6art.js} +1 -1
  60. package/dist/ui/assets/{send-DIlj81PT.js → send-Dax1tJ5b.js} +1 -1
  61. package/dist/ui/assets/{settings-CkBjgAEm.js → settings-97CL32lC.js} +1 -1
  62. package/dist/ui/assets/{shield-U0hIjGzm.js → shield-DwbCEZbF.js} +1 -1
  63. package/dist/ui/assets/{sparkles-VXHGDbNh.js → sparkles-CWMAzkpD.js} +1 -1
  64. package/dist/ui/assets/{square-OHeetvN3.js → square-B4dgTXI3.js} +1 -1
  65. package/dist/ui/assets/terminal-DoLedTPM.js +1 -0
  66. package/dist/ui/assets/{trash-2-DQxm7DUM.js → trash-2-DxnVYOz8.js} +1 -1
  67. package/dist/ui/assets/{triangle-alert-Dj8ZhmWj.js → triangle-alert-Cka-BeIE.js} +1 -1
  68. package/dist/ui/assets/{useHiveAgentsModelLoad-COLvs-Ho.js → useHiveAgentsModelLoad-BjnIsQKR.js} +1 -1
  69. package/dist/ui/assets/{useProviders-q6iROeWE.js → useProviders-CueMz_mL.js} +1 -1
  70. package/dist/ui/assets/{volume-x-Bm735CXN.js → volume-x-DLsli9cf.js} +1 -1
  71. package/dist/ui/assets/{wifi-DklBfOZ6.js → wifi-BQRJGfLZ.js} +1 -1
  72. package/dist/ui/assets/{zap-BEZNJ0i0.js → zap-DSR3CEce.js} +1 -1
  73. package/dist/ui/index.html +2 -2
  74. package/package.json +1 -1
  75. package/packages/cli/src/index.ts +23 -17
  76. package/packages/core/src/agent/agent-loop.ts +29 -3
  77. package/packages/core/src/agent/context-compiler.ts +13 -2
  78. package/packages/core/src/agent/mcp-result-normalizer.ts +150 -0
  79. package/packages/core/src/agent/providers/index.ts +8 -0
  80. package/packages/core/src/artifacts/store.ts +16 -0
  81. package/packages/core/src/canvas/canvas-manager.ts +36 -7
  82. package/packages/core/src/channels/base.ts +33 -0
  83. package/packages/core/src/channels/discord.ts +20 -1
  84. package/packages/core/src/channels/slack.ts +21 -2
  85. package/packages/core/src/channels/telegram.ts +16 -1
  86. package/packages/core/src/channels/whatsapp.ts +16 -3
  87. package/packages/core/src/gateway/durable-queue.ts +2 -1
  88. package/packages/core/src/gateway/failure-notify.ts +78 -0
  89. package/packages/core/src/gateway/job-executors.ts +1 -0
  90. package/packages/core/src/gateway/job-store.ts +6 -0
  91. package/packages/core/src/gateway/process-safety.ts +40 -0
  92. package/packages/core/src/gateway/routes/a2ui.ts +43 -0
  93. package/packages/core/src/gateway/routes/artifacts.ts +60 -0
  94. package/packages/core/src/gateway/routes/runtime.ts +58 -0
  95. package/packages/core/src/gateway/routes/setup.ts +127 -108
  96. package/packages/core/src/gateway/server.ts +52 -5
  97. package/packages/core/src/gateway/webchat-turn.ts +40 -1
  98. package/packages/core/src/storage/onboarding.ts +23 -7
  99. package/packages/core/src/storage/seed.ts +31 -2
  100. package/packages/core/src/utils/redact-binary.ts +17 -0
  101. package/dist/ui/assets/A2UIPage-D4nzp5NV.js +0 -8
  102. package/dist/ui/assets/AgentNewPage-CfBU7puz.js +0 -1
  103. package/dist/ui/assets/SettingsPage-DCZ4nql4.js +0 -9
  104. package/dist/ui/assets/WebChatPage-ByVBSzxL.js +0 -29
  105. package/dist/ui/assets/arrow-left-BfcnX8Er.js +0 -1
  106. package/dist/ui/assets/arrow-right-Q-dzAn8k.js +0 -1
  107. package/dist/ui/assets/arrow-up-right-Bf-8wrUQ.js +0 -1
  108. package/dist/ui/assets/check-CryV78SQ.js +0 -1
  109. package/dist/ui/assets/chevron-down-QCtMs-Af.js +0 -1
  110. package/dist/ui/assets/chevron-left-dTGbyl5G.js +0 -1
  111. package/dist/ui/assets/chevron-right-D0GjXbnO.js +0 -1
  112. package/dist/ui/assets/chevron-up-Cg0jO8uT.js +0 -1
  113. package/dist/ui/assets/circle-check-BAolxswA.js +0 -1
  114. package/dist/ui/assets/gauge-CB-cas-h.js +0 -1
  115. package/dist/ui/assets/index-D489S18g.css +0 -2
  116. package/dist/ui/assets/loader-circle-Dtfz4FWw.js +0 -1
  117. package/dist/ui/assets/play-tOrP0xUJ.js +0 -1
  118. package/dist/ui/assets/plus-Cnom3j47.js +0 -1
  119. package/dist/ui/assets/search-D277MUP0.js +0 -1
  120. package/dist/ui/assets/terminal-C6YPcJl_.js +0 -1
@@ -7,7 +7,7 @@ import {
7
7
  type DMChannel,
8
8
  type NewsChannel,
9
9
  } from "discord.js";
10
- import { BaseChannel, type ChannelConfig, type IncomingMessage, type OutboundMessage } from "./base.ts";
10
+ import { BaseChannel, type ChannelConfig, type IncomingMessage, type OutboundMessage, readOutboundImageBytes } from "./base.ts";
11
11
  import { logger } from "../utils/logger.ts";
12
12
  import { updateDoc } from "../storage/hive.ts";
13
13
  import type { ChannelDoc } from "../storage/collections.ts";
@@ -207,9 +207,28 @@ export class DiscordChannel extends BaseChannel {
207
207
  throw new Error(`Channel not found for session: ${sessionId}`);
208
208
  }
209
209
 
210
+ if (message.image) {
211
+ try {
212
+ const bytes = await readOutboundImageBytes(message.image);
213
+ if (bytes) {
214
+ const ext = message.image.mimeType === "image/jpeg" ? "jpg" : message.image.mimeType === "image/webp" ? "webp" : "png";
215
+ await channel.send({
216
+ content: message.image.caption,
217
+ files: [{ attachment: bytes, name: `image.${ext}` }],
218
+ });
219
+ } else {
220
+ this.log.warn(`Image artifact unavailable, skipping photo send`, { sessionId });
221
+ }
222
+ } catch (error) {
223
+ this.log.error(`Failed to send Discord image: ${(error as Error).message}`);
224
+ }
225
+ }
226
+
210
227
  const content = message.content ?? "";
211
228
  const maxLength = 2000;
212
229
 
230
+ if (!content) return;
231
+
213
232
  try {
214
233
  if (content.length <= maxLength) {
215
234
  await channel.send(content);
@@ -1,6 +1,6 @@
1
1
  import { App, ExpressReceiver, type SlashCommand } from "@slack/bolt";
2
2
  import type { ChannelConfig, IncomingMessage, OutboundMessage } from "./base.ts";
3
- import { BaseChannel } from "./base.ts";
3
+ import { BaseChannel, readOutboundImageBytes } from "./base.ts";
4
4
  import { logger } from "../utils/logger.ts";
5
5
  import { updateDoc } from "../storage/hive.ts";
6
6
  import type { ChannelDoc } from "../storage/collections.ts";
@@ -260,10 +260,29 @@ await this.handleMessage(incoming);
260
260
  throw new Error("Slack not connected");
261
261
  }
262
262
 
263
+ const peerId = this.extractPeerId(sessionId);
264
+
265
+ if (message.image) {
266
+ try {
267
+ const bytes = await readOutboundImageBytes(message.image);
268
+ if (bytes) {
269
+ await this.app.client.files.uploadV2({
270
+ channel_id: peerId,
271
+ file: bytes,
272
+ filename: `image.${message.image.mimeType === "image/jpeg" ? "jpg" : message.image.mimeType === "image/webp" ? "webp" : "png"}`,
273
+ title: message.image.caption ?? "Image response",
274
+ });
275
+ } else {
276
+ this.log.warn(`Image artifact unavailable, skipping photo send`, { sessionId });
277
+ }
278
+ } catch (error) {
279
+ this.log.error(`Failed to send Slack image: ${(error as Error).message}`);
280
+ }
281
+ }
282
+
263
283
  const text = message.content ?? message.chunk ?? "";
264
284
  if (!text) return;
265
285
 
266
- const peerId = this.extractPeerId(sessionId);
267
286
  const pending = this.pendingMessages.get(sessionId);
268
287
 
269
288
  try {
@@ -1,5 +1,5 @@
1
1
  import { Bot, GrammyError, InputFile, type Context } from "grammy";
2
- import { BaseChannel, type ChannelConfig, type IncomingMessage, type OutboundMessage } from "./base.ts";
2
+ import { BaseChannel, type ChannelConfig, type IncomingMessage, type OutboundMessage, readOutboundImageBytes } from "./base.ts";
3
3
  import { logger } from "../utils/logger.ts";
4
4
  import { col, updateDoc } from "../storage/hive.ts";
5
5
  import type { ChannelDoc, UserIdentityDoc } from "../storage/collections.ts";
@@ -404,6 +404,21 @@ export class TelegramChannel extends BaseChannel {
404
404
  throw new Error(`Invalid chat ID from session: ${sessionId}`);
405
405
  }
406
406
 
407
+ if (message.image) {
408
+ try {
409
+ const bytes = await readOutboundImageBytes(message.image);
410
+ if (bytes) {
411
+ await this.bot.api.sendPhoto(chatId, new InputFile(bytes), {
412
+ caption: message.image.caption,
413
+ });
414
+ } else {
415
+ this.log.warn(`Image artifact unavailable, skipping photo send`, { sessionId });
416
+ }
417
+ } catch (error) {
418
+ this.log.error(`Telegram sendPhoto failed: ${(error as Error).message}`);
419
+ }
420
+ }
421
+
407
422
  const content = message.content ?? "";
408
423
 
409
424
  if (!content || content.trim().length === 0) {
@@ -8,7 +8,7 @@ import makeWASocket, {
8
8
  type WAMessage,
9
9
  } from "@whiskeysockets/baileys";
10
10
  import type { ChannelConfig, IncomingMessage, OutboundMessage } from "./base.ts";
11
- import { BaseChannel } from "./base.ts";
11
+ import { BaseChannel, readOutboundImageBytes } from "./base.ts";
12
12
  import { existsSync, mkdirSync, rmSync } from "node:fs";
13
13
  import * as path from "node:path";
14
14
  import { homedir } from "node:os";
@@ -488,11 +488,24 @@ export class WhatsAppChannel extends BaseChannel {
488
488
  const isInterim = message.type === "progress";
489
489
  if (!isInterim) await this.stopTyping(sessionId);
490
490
 
491
+ const jid = this.getJid(sessionId);
492
+
493
+ if (message.image) {
494
+ try {
495
+ const bytes = await readOutboundImageBytes(message.image);
496
+ if (bytes) {
497
+ await this.socket.sendMessage(jid, { image: bytes, caption: message.image.caption });
498
+ } else {
499
+ this.log.warn(`Image artifact unavailable, skipping photo send`, { sessionId });
500
+ }
501
+ } catch (error) {
502
+ this.log.error(`Failed to send WhatsApp image: ${(error as Error).message}`);
503
+ }
504
+ }
505
+
491
506
  const text = message.content ?? message.chunk ?? "";
492
507
  if (!text) return;
493
508
 
494
- const jid = this.getJid(sessionId);
495
-
496
509
  await this.socket.sendMessage(jid, { text });
497
510
  if (isInterim) await this.startTyping(sessionId);
498
511
  this.log.debug(`Sent message to ${jid}`);
@@ -92,7 +92,8 @@ export function registerTerminalHook(type: JobType, hook: JobTerminalHook): void
92
92
  terminalHooks.set(type, hook);
93
93
  }
94
94
 
95
- async function runTerminalHook(job: JobDoc, outcome: JobTerminalOutcome): Promise<void> {
95
+ /** Exported so job-store.ts's reclaimOrInterrupt can fire it too (dynamic import there — see its call site — avoids a static circular import since this module already imports reclaimOrInterrupt from job-store.ts). */
96
+ export async function runTerminalHook(job: JobDoc, outcome: JobTerminalOutcome): Promise<void> {
96
97
  const hook = terminalHooks.get(job.type);
97
98
  if (!hook) return;
98
99
  try {
@@ -0,0 +1,78 @@
1
+ /**
2
+ * failure-notify — closes the durable queue's silent-failure gap for the
3
+ * user's own turns (chat_turn, goal_run).
4
+ *
5
+ * durable-queue.ts's terminal-hook mechanism only had one consumer before
6
+ * this: delegation-notify.ts's worker_task hook, which relays a *delegated*
7
+ * task's outcome back to the coordinator's conversation. Nothing told the
8
+ * user when their OWN chat turn or goal run failed for good with no live
9
+ * socket attached (a rehydrated turn after a crash, a job that exhausted its
10
+ * lease via reclaimOrInterrupt, etc.) — the job/run just sat in HiveDB as
11
+ * "failed", logged, and otherwise silent. From the user's side that reads as
12
+ * the system not responding at all, not as an explained error.
13
+ *
14
+ * Unlike delegation-notify.ts, this sends directly via sendToUserChannel
15
+ * instead of enqueueing another synthetic chat turn: the failure already
16
+ * happened inside a turn/goal run, so routing it back through another LLM
17
+ * turn would just risk failing the same way again. A plain, immediate
18
+ * message is the safer default here.
19
+ */
20
+
21
+ import { logger } from "../utils/logger";
22
+ import { registerTerminalHook, type JobTerminalOutcome } from "./durable-queue";
23
+ import { sendToUserChannel } from "./channel-notify";
24
+ import { resolveContext } from "./resolver";
25
+ import { getRun } from "../agent/run-store";
26
+ import type { JobDoc } from "../storage/collections";
27
+ import type { WebchatTurnPayload } from "./webchat-turn";
28
+
29
+ const log = logger.child("failure-notify");
30
+
31
+ async function notifyChatTurnFailure(job: JobDoc, outcome: JobTerminalOutcome): Promise<void> {
32
+ if (outcome.ok) return; // success is delivered by runWebchatTurn itself
33
+
34
+ const payload = JSON.parse(job.payload_json) as WebchatTurnPayload;
35
+ const channel = payload.channel ?? "webchat";
36
+ let userId = payload.userId;
37
+
38
+ if (!userId) {
39
+ // Live webchat turns ("message"/"audio"/"a2ui") never carry userId in the
40
+ // payload — same resolution runWebchatTurn itself falls back to.
41
+ try {
42
+ const ctx = await resolveContext({ channel: "webchat", channelUserId: payload.sessionId });
43
+ userId = ctx.userId;
44
+ } catch (err) {
45
+ log.warn(`[notifyChatTurnFailure] Could not resolve a recipient for job ${job.id}: ${(err as Error).message}`);
46
+ return;
47
+ }
48
+ }
49
+
50
+ await sendToUserChannel(
51
+ channel,
52
+ userId,
53
+ "No pude completar tu solicitud por un error interno. Por favor intentá de nuevo."
54
+ ).catch((err) => log.warn(`[notifyChatTurnFailure] Delivery failed for job ${job.id}: ${(err as Error).message}`));
55
+ }
56
+
57
+ async function notifyGoalRunFailure(job: JobDoc, outcome: JobTerminalOutcome): Promise<void> {
58
+ if (outcome.ok) return; // goalRunExecutor already notifies success/budget-exhausted inline
59
+
60
+ const run = await getRun(job.run_id).catch(() => null);
61
+ if (!run?.channel || !run.user_id) return;
62
+
63
+ await sendToUserChannel(
64
+ run.channel,
65
+ run.user_id,
66
+ `No pude completar la tarea. Motivo: ${outcome.error ?? "error desconocido"}`
67
+ ).catch((err) => log.warn(`[notifyGoalRunFailure] Delivery failed for job ${job.id}: ${(err as Error).message}`));
68
+ }
69
+
70
+ let initialized = false;
71
+
72
+ export function initFailureNotify(): void {
73
+ if (initialized) return;
74
+ registerTerminalHook("chat_turn", notifyChatTurnFailure);
75
+ registerTerminalHook("goal_run", notifyGoalRunFailure);
76
+ initialized = true;
77
+ log.info("[initFailureNotify] Registered chat_turn/goal_run terminal hooks");
78
+ }
@@ -464,6 +464,7 @@ const goalRunExecutor: JobExecutor = async (job, signal) => {
464
464
  }
465
465
  } catch (err) {
466
466
  await failRun(goalRunId, (err as Error).message).catch(() => {});
467
+ await notify(`❌ No pude completar la meta: "${goal}". Error: ${(err as Error).message}`);
467
468
  return { ok: false, error: (err as Error).message, retryable: isRetryableError(err) };
468
469
  } finally {
469
470
  stopLeaseRenewal(goalRunId);
@@ -337,6 +337,12 @@ export async function reclaimOrInterrupt(jobId: string, opts?: { force?: boolean
337
337
  try {
338
338
  await c.put(jobId, updated, { expectedVersion: entry.version });
339
339
  log.warn(`[reclaimOrInterrupt] Job ${jobId} interrupted (attempts exhausted)`);
340
+ // Terminal via lease-expiry, not executeJob's normal fail path — that
341
+ // path already fires the hook, this one didn't before. Dynamic import
342
+ // avoids a static circular import (durable-queue.ts imports
343
+ // reclaimOrInterrupt from this module).
344
+ const { runTerminalHook } = await import("./durable-queue");
345
+ await runTerminalHook(updated, { ok: false, error: updated.error ?? "Job interrupted after lease expiry" }).catch(() => {});
340
346
  return updated;
341
347
  } catch {
342
348
  await occRetryDelay(attempt);
@@ -0,0 +1,40 @@
1
+ /**
2
+ * process-safety — last-resort net for exceptions nothing else caught.
3
+ *
4
+ * Confirmed by exhaustive grep: before this, packages/core/src had no
5
+ * process.on("uncaughtException"/"unhandledRejection") handler anywhere.
6
+ * Bun/Node's default behavior for a truly uncaught exception is to kill the
7
+ * process immediately with just a stack trace on stdout — no attempt to
8
+ * notify anyone, no clean shutdown.
9
+ *
10
+ * This does NOT try to keep the process alive after a fatal error — doing
11
+ * that would mask real bugs and can leave the process in an inconsistent
12
+ * state (leases not released, locks not freed). It only guarantees the crash
13
+ * is loud (max-severity log line) and the shutdown is a clean, fast exit
14
+ * instead of an undefined one. The rest of the story is handled by existing
15
+ * machinery: reconcileOnBoot (storage/reconcile.ts) already notifies the user
16
+ * for interrupted chat runs when the process comes back up, and the process
17
+ * supervisor (systemd/pm2/docker) is expected to restart it.
18
+ */
19
+
20
+ import { logger } from "../utils/logger";
21
+
22
+ const log = logger.child("process-safety");
23
+
24
+ let installed = false;
25
+
26
+ export function installProcessSafetyNet(): void {
27
+ if (installed) return;
28
+ installed = true;
29
+
30
+ const handleFatal = (err: unknown, origin: string) => {
31
+ const detail = err instanceof Error ? (err.stack ?? err.message) : String(err);
32
+ log.error(`[process-safety] FATAL ${origin} — process exiting: ${detail}`);
33
+ process.exit(1);
34
+ };
35
+
36
+ process.on("uncaughtException", (err) => handleFatal(err, "uncaughtException"));
37
+ process.on("unhandledRejection", (err) => handleFatal(err, "unhandledRejection"));
38
+
39
+ log.info("[process-safety] Installed uncaughtException/unhandledRejection safety net");
40
+ }
@@ -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
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * routes/artifacts — serves artifact binaries (images generated by MCP
3
+ * tools, screenshots, etc.) created by artifacts/store.ts's createArtifact().
4
+ *
5
+ * Follows the same shape as routes/meeting.ts's handleDownloadMeetingReport:
6
+ * resolve metadata, stream the file from disk with the right Content-Type.
7
+ * Hive is single-tenant behind one bearer token (see startGateway's
8
+ * HIVE_AUTH_TOKEN gate) — same as meeting downloads, no per-user ownership
9
+ * check is layered on top here; inspectArtifact still enforces expiry and
10
+ * that the file on disk matches its recorded hash/size.
11
+ */
12
+
13
+ import { logger } from "../../utils/logger";
14
+ import { col } from "../../storage/hive";
15
+ import type { ArtifactDoc } from "../../storage/collections";
16
+ import { inspectArtifact } from "../../artifacts/store";
17
+
18
+ const log = logger.child("routes/artifacts");
19
+
20
+ type CorsHelper = (r: Response, req: Request) => Response;
21
+
22
+ export async function handleDownloadArtifact(
23
+ req: Request,
24
+ addCorsHeaders: CorsHelper,
25
+ artifactId: string,
26
+ ): Promise<Response> {
27
+ try {
28
+ const meta = await inspectArtifact(artifactId);
29
+ if (!meta.ok) {
30
+ return addCorsHeaders(Response.json(meta, { status: 404 }), req);
31
+ }
32
+
33
+ const artifactsCol = await col<ArtifactDoc>("artifacts");
34
+ const entry = await artifactsCol.get(artifactId);
35
+ if (!entry) {
36
+ return addCorsHeaders(Response.json({ ok: false, error: "Artifact not found" }, { status: 404 }), req);
37
+ }
38
+
39
+ const file = Bun.file(entry.doc.path);
40
+ if (!(await file.exists())) {
41
+ return addCorsHeaders(Response.json({ ok: false, error: "Artifact binary is missing" }, { status: 404 }), req);
42
+ }
43
+
44
+ return addCorsHeaders(
45
+ new Response(file, {
46
+ headers: {
47
+ "Content-Type": entry.doc.mime_type,
48
+ "Cache-Control": "private, max-age=3600",
49
+ },
50
+ }),
51
+ req,
52
+ );
53
+ } catch (error) {
54
+ log.error(`handleDownloadArtifact: ${(error as Error).message}`);
55
+ return addCorsHeaders(
56
+ Response.json({ ok: false, error: (error as Error).message }, { status: 500 }),
57
+ req,
58
+ );
59
+ }
60
+ }
@@ -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
+ }