@johpaz/hive-agents 1.0.2 → 1.0.4

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 (194) hide show
  1. package/README.md +4 -4
  2. package/dist/hive.js +46386 -45716
  3. package/dist/ui/assets/A2UIPage-7Ry5rHh9.js +8 -0
  4. package/dist/ui/assets/AgentCreateForm-Dh5W0q_t.js +1 -0
  5. package/dist/ui/assets/AgentDetailPage-CIoPjtsS.js +1 -0
  6. package/dist/ui/assets/AgentNewPage-BNsZcJQf.js +1 -0
  7. package/dist/ui/assets/AgentsPage-YZrDmgNI.js +10 -0
  8. package/dist/ui/assets/ApiClientPage-6a6KFwsQ.js +3 -0
  9. package/dist/ui/assets/ChannelsPage-Dice4dkJ.js +8 -0
  10. package/dist/ui/assets/DashboardPage-B9r0sc0F.js +6 -0
  11. package/dist/ui/assets/LoginPage-BkAAX_tu.js +1 -0
  12. package/dist/ui/assets/{LogsPage-6Po7_T2u.js → LogsPage-8-H1OJs3.js} +1 -1
  13. package/dist/ui/assets/MeetingPage-14JoQo71.js +1 -0
  14. package/dist/ui/assets/ModelSelector-CrgJQ7DG.js +1 -0
  15. package/dist/ui/assets/{NotFound-Bpr12V51.js → NotFound-B06kVW7N.js} +1 -1
  16. package/dist/ui/assets/{Office3DPage-BYwLMTCl.js → Office3DPage-BMUZWkFS.js} +2 -2
  17. package/dist/ui/assets/ProvidersPage-BiL3QxCs.js +1 -0
  18. package/dist/ui/assets/RecoverPage-D1o8yxNz.js +1 -0
  19. package/dist/ui/assets/SettingsPage-GP8UwQIL.js +9 -0
  20. package/dist/ui/assets/SetupPage-B_gU1YQU.js +1 -0
  21. package/dist/ui/assets/WebChatPage-Yahufnth.js +29 -0
  22. package/dist/ui/assets/activity-C_GS5wrG.js +1 -0
  23. package/dist/ui/assets/agentCapabilities-Dg72UAFj.js +1 -0
  24. package/dist/ui/assets/{alert-CQlRq6sv.js → alert-DChoEVJw.js} +1 -1
  25. package/dist/ui/assets/arrow-left-WyDPYZXU.js +1 -0
  26. package/dist/ui/assets/arrow-right-BuNjN-bk.js +1 -0
  27. package/dist/ui/assets/arrow-up-right-DWzTsCXj.js +1 -0
  28. package/dist/ui/assets/{badge-DKGZbVZJ.js → badge-uRjRSt86.js} +1 -1
  29. package/dist/ui/assets/calendar-B6x9cw-q.js +1 -0
  30. package/dist/ui/assets/{card-D3Nw3kh3.js → card-DwQizslL.js} +1 -1
  31. package/dist/ui/assets/check-C8pw-7Fx.js +1 -0
  32. package/dist/ui/assets/chevron-down-8GjmTjLR.js +1 -0
  33. package/dist/ui/assets/chevron-left-GK4EQOyZ.js +1 -0
  34. package/dist/ui/assets/chevron-right-BupZqrxu.js +1 -0
  35. package/dist/ui/assets/chevron-up-DZrzJIW8.js +1 -0
  36. package/dist/ui/assets/circle-alert-CtDbK2nl.js +1 -0
  37. package/dist/ui/assets/circle-check-BKNT2_q6.js +1 -0
  38. package/dist/ui/assets/circle-x-DfBjbztU.js +1 -0
  39. package/dist/ui/assets/copy-wR7o7Ly8.js +1 -0
  40. package/dist/ui/assets/core-Sjunb8Z1.js +1 -0
  41. package/dist/ui/assets/createLucideIcon-BRaPSYgN.js +1 -0
  42. package/dist/ui/assets/{dialog-CO1WrPJc.js → dialog--mljnfAi.js} +1 -1
  43. package/dist/ui/assets/dist-js-B0s_TDau.js +1 -0
  44. package/dist/ui/assets/dist-js-CLxM1g2B.js +1 -0
  45. package/dist/ui/assets/download-D0aDV8Y_.js +1 -0
  46. package/dist/ui/assets/earth-BJRGJbVn.js +1 -0
  47. package/dist/ui/assets/ellipsis-vertical-BOW_iEOO.js +1 -0
  48. package/dist/ui/assets/external-link-5cujQzfV.js +1 -0
  49. package/dist/ui/assets/eye-sRPY5qOa.js +1 -0
  50. package/dist/ui/assets/file-text-DNSyNLUh.js +1 -0
  51. package/dist/ui/assets/gauge-C__zxC3_.js +1 -0
  52. package/dist/ui/assets/history-BHQWfE-7.js +1 -0
  53. package/dist/ui/assets/index-BHHUQZJd.js +116 -0
  54. package/dist/ui/assets/index-CEFhf4dF.css +2 -0
  55. package/dist/ui/assets/info-CG1VohyH.js +1 -0
  56. package/dist/ui/assets/key-BC28VCjO.js +1 -0
  57. package/dist/ui/assets/{label-k0jYxoWW.js → label-BceoUB2w.js} +1 -1
  58. package/dist/ui/assets/lock-open-Bhp0UJlL.js +1 -0
  59. package/dist/ui/assets/mail-Biwn8WrV.js +1 -0
  60. package/dist/ui/assets/pause-C2l5G2Py.js +1 -0
  61. package/dist/ui/assets/pencil-CUbpCfeG.js +1 -0
  62. package/dist/ui/assets/play-CMAscR3a.js +1 -0
  63. package/dist/ui/assets/plus-DzvRxH4U.js +1 -0
  64. package/dist/ui/assets/radio-DfGzov4y.js +1 -0
  65. package/dist/ui/assets/refresh-cw-DZXu5FrG.js +1 -0
  66. package/dist/ui/assets/scroll-area-DMEaZZUp.js +1 -0
  67. package/dist/ui/assets/search-ykSx-zZU.js +1 -0
  68. package/dist/ui/assets/{select-BfRyBbi9.js → select-BBEBtcLm.js} +1 -1
  69. package/dist/ui/assets/send-DAhlz2i9.js +1 -0
  70. package/dist/ui/assets/settings-DL0REysC.js +1 -0
  71. package/dist/ui/assets/shield-BPZZhjCT.js +1 -0
  72. package/dist/ui/assets/slider-DcmBdvYD.js +1 -0
  73. package/dist/ui/assets/sparkles-BViXTAh7.js +1 -0
  74. package/dist/ui/assets/square-psq7k_CB.js +1 -0
  75. package/dist/ui/assets/{switch-DXcELPsM.js → switch-CgiDezVR.js} +1 -1
  76. package/dist/ui/assets/tabs-gUXIjjZv.js +1 -0
  77. package/dist/ui/assets/terminal-CzxPKG-h.js +1 -0
  78. package/dist/ui/assets/{textarea-rp6vsOZl.js → textarea-DedxQYBx.js} +1 -1
  79. package/dist/ui/assets/trash-2-SgYCWiVk.js +1 -0
  80. package/dist/ui/assets/{useHiveAgentsModelLoad-D3s2U82M.js → useHiveAgentsModelLoad-C7bhWPDG.js} +1 -1
  81. package/dist/ui/assets/useProviders-CiLSc05q.js +1 -0
  82. package/dist/ui/assets/vendor-radix-DUug7irY.js +63 -0
  83. package/dist/ui/assets/{vendor-react-CPJEWbIG.js → vendor-react-DYyYpuMy.js} +1 -1
  84. package/dist/ui/assets/volume-x-BDlMCDYT.js +1 -0
  85. package/dist/ui/assets/wifi-CyPHteEm.js +1 -0
  86. package/dist/ui/assets/zap-OVVrfEHr.js +1 -0
  87. package/dist/ui/index.html +8 -7
  88. package/package.json +1 -1
  89. package/packages/core/src/agent/agent-loop.ts +77 -3
  90. package/packages/core/src/agent/context-compiler.ts +13 -2
  91. package/packages/core/src/agent/llm-client.ts +41 -6
  92. package/packages/core/src/agent/llm-providers/nvidia.ts +39 -0
  93. package/packages/core/src/agent/llm-providers/openai-compat-base.ts +38 -2
  94. package/packages/core/src/agent/mcp-result-normalizer.ts +192 -0
  95. package/packages/core/src/agent/providers/index.ts +8 -0
  96. package/packages/core/src/agent/tool-selector.ts +1 -0
  97. package/packages/core/src/artifacts/store.ts +81 -0
  98. package/packages/core/src/channels/base.ts +33 -0
  99. package/packages/core/src/channels/discord.ts +20 -1
  100. package/packages/core/src/channels/slack.ts +21 -2
  101. package/packages/core/src/channels/telegram.ts +16 -1
  102. package/packages/core/src/channels/whatsapp.ts +16 -3
  103. package/packages/core/src/events/tool-narration.ts +3 -0
  104. package/packages/core/src/gateway/durable-queue.ts +2 -1
  105. package/packages/core/src/gateway/failure-notify.ts +78 -0
  106. package/packages/core/src/gateway/job-executors.ts +1 -0
  107. package/packages/core/src/gateway/job-store.ts +6 -0
  108. package/packages/core/src/gateway/process-safety.ts +40 -0
  109. package/packages/core/src/gateway/routes/artifacts.ts +60 -0
  110. package/packages/core/src/gateway/routes/system.ts +9 -4
  111. package/packages/core/src/gateway/server.ts +36 -5
  112. package/packages/core/src/gateway/webchat-turn.ts +74 -2
  113. package/packages/core/src/storage/seed.ts +1 -0
  114. package/packages/core/src/tool-runtime/embedded-worker.generated.ts +20 -0
  115. package/packages/core/src/tool-runtime/index.ts +56 -14
  116. package/packages/core/src/tools/index.ts +3 -2
  117. package/packages/core/src/tools/web/artifact-read.ts +162 -0
  118. package/packages/core/src/tools/web/index.ts +3 -0
  119. package/packages/core/src/utils/redact-binary.ts +17 -0
  120. package/packages/skills/src/bundled-data.generated.ts +752 -752
  121. package/dist/ui/assets/A2UIPage-BRpjnMss.js +0 -8
  122. package/dist/ui/assets/AgentCreateForm-ASjKD7Js.js +0 -1
  123. package/dist/ui/assets/AgentDetailPage-bqJ-MS40.js +0 -1
  124. package/dist/ui/assets/AgentNewPage-CPaf2C3u.js +0 -1
  125. package/dist/ui/assets/AgentsPage-BIpLG0V6.js +0 -10
  126. package/dist/ui/assets/ApiClientPage-dRckcgrN.js +0 -3
  127. package/dist/ui/assets/ChannelsPage-BX_hPtiN.js +0 -8
  128. package/dist/ui/assets/DashboardPage-KMaMaFf4.js +0 -6
  129. package/dist/ui/assets/LoginPage-Zchu-f16.js +0 -1
  130. package/dist/ui/assets/MeetingPage-qrpYGVD-.js +0 -1
  131. package/dist/ui/assets/ModelSelector-C8ny_pxu.js +0 -1
  132. package/dist/ui/assets/ProvidersPage-DP9v_1ko.js +0 -1
  133. package/dist/ui/assets/RecoverPage-BXwjLfap.js +0 -1
  134. package/dist/ui/assets/SettingsPage-DD7GKtS6.js +0 -9
  135. package/dist/ui/assets/SetupPage-D7YX2io-.js +0 -1
  136. package/dist/ui/assets/WebChatPage-C3cgimxd.js +0 -29
  137. package/dist/ui/assets/activity-DZKL7dg4.js +0 -1
  138. package/dist/ui/assets/agentCapabilities-DuGs07XP.js +0 -1
  139. package/dist/ui/assets/arrow-left-12JaXVoH.js +0 -1
  140. package/dist/ui/assets/arrow-right-Dbui5p0d.js +0 -1
  141. package/dist/ui/assets/arrow-up-right-CJBtXRrp.js +0 -1
  142. package/dist/ui/assets/calendar-CkDsc4OJ.js +0 -1
  143. package/dist/ui/assets/check-DxOMIDcl.js +0 -1
  144. package/dist/ui/assets/chevron-down-CObv-xyx.js +0 -1
  145. package/dist/ui/assets/chevron-left-C0mqwhLU.js +0 -1
  146. package/dist/ui/assets/chevron-right-jCt1h8Kw.js +0 -1
  147. package/dist/ui/assets/chevron-up-DX_5iw7O.js +0 -1
  148. package/dist/ui/assets/circle-alert-BkP6x0zQ.js +0 -1
  149. package/dist/ui/assets/circle-check-CXC2AiMS.js +0 -1
  150. package/dist/ui/assets/circle-x-h4OJiHV3.js +0 -1
  151. package/dist/ui/assets/copy-BtpYEEvV.js +0 -1
  152. package/dist/ui/assets/download-aPuVaZik.js +0 -1
  153. package/dist/ui/assets/earth-sc8YJMc0.js +0 -1
  154. package/dist/ui/assets/ellipsis-vertical-DEBZJGzY.js +0 -1
  155. package/dist/ui/assets/external-link-D_C_678M.js +0 -1
  156. package/dist/ui/assets/eye-BfN613fx.js +0 -1
  157. package/dist/ui/assets/file-text-Bth5pPZX.js +0 -1
  158. package/dist/ui/assets/gauge-DypSzSOE.js +0 -1
  159. package/dist/ui/assets/history-njH_sPSo.js +0 -1
  160. package/dist/ui/assets/index-D-9yCvjP.js +0 -116
  161. package/dist/ui/assets/index-wML8DaUo.css +0 -2
  162. package/dist/ui/assets/info-Def2ZFeP.js +0 -1
  163. package/dist/ui/assets/key-D8bkDl83.js +0 -1
  164. package/dist/ui/assets/loader-circle-wLVzSdML.js +0 -1
  165. package/dist/ui/assets/lock-open-Cdopbw1b.js +0 -1
  166. package/dist/ui/assets/mail-BQ_YA9_b.js +0 -1
  167. package/dist/ui/assets/pause-CvS_LzKx.js +0 -1
  168. package/dist/ui/assets/pencil-C3tPvnCk.js +0 -1
  169. package/dist/ui/assets/play-C-oR-PMH.js +0 -1
  170. package/dist/ui/assets/plus-CF9No2td.js +0 -1
  171. package/dist/ui/assets/progress-DrI2UDu-.js +0 -1
  172. package/dist/ui/assets/radio-dsaiFxuT.js +0 -1
  173. package/dist/ui/assets/refresh-cw-BmYQwOhh.js +0 -1
  174. package/dist/ui/assets/scroll-area-CfHn94Vb.js +0 -1
  175. package/dist/ui/assets/search-CTONpTyl.js +0 -1
  176. package/dist/ui/assets/send-C3o2wpLi.js +0 -1
  177. package/dist/ui/assets/settings-DEpdBuf2.js +0 -1
  178. package/dist/ui/assets/shield-gbUkSqfi.js +0 -1
  179. package/dist/ui/assets/slider-CmE_z1Ii.js +0 -1
  180. package/dist/ui/assets/sparkles-Ccd1JZ3s.js +0 -1
  181. package/dist/ui/assets/square-BrwQ6Mun.js +0 -1
  182. package/dist/ui/assets/tabs-CxiybXcw.js +0 -1
  183. package/dist/ui/assets/terminal-DP9j3HjM.js +0 -1
  184. package/dist/ui/assets/trash-2-CfCs7RhJ.js +0 -1
  185. package/dist/ui/assets/triangle-alert-C3lWSnRr.js +0 -1
  186. package/dist/ui/assets/useProviders-B3rT_xU9.js +0 -1
  187. package/dist/ui/assets/vendor-radix-D0s_k6Gp.js +0 -63
  188. package/dist/ui/assets/volume-x-D2h9cyml.js +0 -1
  189. package/dist/ui/assets/wifi-CGQECzu2.js +0 -1
  190. package/dist/ui/assets/zap-B1azpiE7.js +0 -1
  191. /package/dist/ui/assets/{gateway-url-BlnabM5e.js → gateway-url-BZj_2-jf.js} +0 -0
  192. /package/dist/ui/assets/{useOfficeModel-Cy7cAyEn.js → useOfficeModel-BAFasrg8.js} +0 -0
  193. /package/dist/ui/assets/{utils-Dyb7SC2_.js → utils-SGUggNJc.js} +0 -0
  194. /package/dist/ui/assets/{vendor-router-zpB-76nT.js → vendor-router-Dsg8fxNQ.js} +0 -0
@@ -22,6 +22,8 @@ import { getNarration } from "./helpers";
22
22
  import { createRun, getRun } from "../agent/run-store";
23
23
  import { getDurableQueue } from "./durable-queue";
24
24
  import { sessionManager } from "./session";
25
+ import { publishNarration } from "../events/narration";
26
+ import { LLM_ERROR_PREFIX } from "../agent/llm-client";
25
27
  import type { JobDoc, TurnSource } from "../storage/collections";
26
28
 
27
29
  const log = logger.child("webchat-turn");
@@ -54,7 +56,12 @@ export interface WebchatTurnLive {
54
56
  }
55
57
 
56
58
  export interface WebchatTurnDeps {
57
- runner: { generate: (opts: any) => Promise<{ content?: string }> };
59
+ runner: {
60
+ generate: (opts: any) => Promise<{
61
+ content?: string;
62
+ imageArtifacts?: Array<{ artifactId: string; mimeType: string }>;
63
+ }>;
64
+ };
58
65
  getProvider: () => string;
59
66
  getModel: () => string;
60
67
  }
@@ -454,7 +461,47 @@ export async function runWebchatTurn(
454
461
  }
455
462
  }
456
463
 
457
- if (delegationGroup) {
464
+ // ── Image artifacts (e.g. an MCP image-generation tool's result) ─────────
465
+ // Sent as a trailing frame regardless of which content/audio branch above
466
+ // ran — decouples the (already-branchy) text/TTS delivery logic from
467
+ // whether this turn happened to also produce an image. Points at the
468
+ // artifacts download endpoint (routes/artifacts.ts) rather than
469
+ // re-inflating base64 into the WS payload — the whole point of
470
+ // materializing it as an artifact in the first place (see
471
+ // mcp-result-normalizer.ts) was to keep it out of large payloads.
472
+ if (response.imageArtifacts?.length) {
473
+ const img = response.imageArtifacts[response.imageArtifacts.length - 1];
474
+ const imageFrame = JSON.stringify({
475
+ type: "message",
476
+ id: messageId,
477
+ sessionId,
478
+ content: "",
479
+ image: `/api/artifacts/${img.artifactId}/download`,
480
+ imageMimeType: img.mimeType,
481
+ isStep: false,
482
+ });
483
+ if (hasLive) {
484
+ sendRaw(imageFrame);
485
+ } else {
486
+ const liveSession = channel === "webchat" ? sessionManager.get(sessionId) : undefined;
487
+ const liveWs = liveSession?.ws?.readyState === 1 ? liveSession.ws : null;
488
+ if (liveWs) {
489
+ try { liveWs.send(imageFrame); } catch { /* socket gone, best effort */ }
490
+ }
491
+ // No live socket at all (crash recovery / async notification path):
492
+ // image delivery there is out of scope for now — sendToUserChannel
493
+ // only carries plain text. The artifact itself is still safely
494
+ // persisted and inspectable (artifact_inspect) either way.
495
+ }
496
+ }
497
+
498
+ if (content.startsWith(LLM_ERROR_PREFIX)) {
499
+ // El turno terminó sin excepción pero lo que devuelve es una falla del
500
+ // proveedor (callLLM la entrega como contenido, no como throw). Cerrar la
501
+ // burbuja con "Listo" encima de un mensaje de error es decirle al usuario
502
+ // que salió bien algo que no salió.
503
+ processReporter?.error("El proveedor del modelo rechazó la petición");
504
+ } else if (delegationGroup) {
458
505
  processReporter?.pending();
459
506
  } else {
460
507
  processReporter?.done("Listo");
@@ -462,6 +509,31 @@ export async function runWebchatTurn(
462
509
  return content;
463
510
  } catch (error) {
464
511
  processReporter?.error("No se pudo completar la respuesta");
512
+ // La narración vive en su propia burbuja del chat (server.ts la entrega con
513
+ // messageId = turn_id, distinto del messageId de este turno) y solo se
514
+ // cierra cuando llega el tool_result de cada tool_call. Si el turno muere
515
+ // entre medio — como pasaba con "Tool worker entry not found" — ese
516
+ // tool_result nunca se publica y la burbuja queda en "Pensando" para
517
+ // siempre, aunque el processReporter ya haya marcado error. Este evento
518
+ // terminal la cierra, y a diferencia del processReporter no depende del
519
+ // socket del job: se entrega por sessionManager, así que también alcanza a
520
+ // los turnos rehidratados.
521
+ if (payload.turnId) {
522
+ await publishNarration({
523
+ turnId: payload.turnId,
524
+ threadId,
525
+ channel,
526
+ userId,
527
+ sessionId,
528
+ kind: "failed",
529
+ status: "error",
530
+ label: "No se pudo completar la respuesta",
531
+ detail: (error as Error).message,
532
+ dedupeKey: `turn_failed:${payload.turnId}`,
533
+ }).catch((err) =>
534
+ log.warn(`[runWebchatTurn] Could not publish the turn's failure narration: ${(err as Error).message}`)
535
+ );
536
+ }
465
537
  // Detener typing aunque falle — nunca dejar el spinner infinito
466
538
  send({ type: "typing", isTyping: false, sessionId });
467
539
  send({ type: "error", sessionId, error: (error as Error).message });
@@ -55,6 +55,7 @@ export const SEED_DATA: SeedData = {
55
55
  { id: "browser_navigate", name: "browser_navigate", category: "web", description: "Navegar a una URL y obtener contenido renderizado (soporta JS). Sinónimos: abrir página, sitio web, navegar url, cargar página" },
56
56
  { id: "browser_screenshot", name: "browser_screenshot", category: "web", description: "Tomar captura de pantalla de la página actual. Sinónimos: screenshot, imagen de página, capturar pantalla, foto página" },
57
57
  { id: "artifact_inspect", name: "artifact_inspect", category: "web", description: "Inspeccionar integridad y metadatos de un artefacto administrado sin modificarlo. Sinónimos: inspeccionar artefacto, verificar archivo generado, metadatos artefacto, comprobar entrega" },
58
+ { id: "artifact_read", name: "artifact_read", category: "web", description: "Leer por partes el contenido de texto de un artefacto administrado, o buscar dentro de él. Sinónimos: leer artefacto, ver contenido del artefacto, abrir resultado grande, buscar dentro del artefacto, leer artifact_ref" },
58
59
  { id: "browser_click", name: "browser_click", category: "web", description: "Hacer clic en un elemento de la página web. Sinónimos: botón, enlace, interactuar, presionar, seleccionar" },
59
60
  { id: "browser_type", name: "browser_type", category: "web", description: "Escribir texto en un campo de formulario. Sinónimos: escribir formulario, tipear, campo de texto, input, llenar campo" },
60
61
  { id: "browser_extract", name: "browser_extract", category: "web", description: "Extraer texto, enlaces o datos estructurados usando selectores CSS o XPath. Sinónimos: obtener datos, scraping, selectores, extraer información" },
@@ -0,0 +1,20 @@
1
+ // Auto-generado — NO EDITAR.
2
+ //
3
+ // Lo que se commitea es SIEMPRE este stub. `scripts/build-gateway.ts` lo
4
+ // reescribe justo antes de compilar el binario standalone con:
5
+ //
6
+ // import workerFile from "./tool-worker.generated.js" with { type: "file" }
7
+ // export const embeddedToolWorkerPath: string | null = workerFile
8
+ //
9
+ // y lo restaura al terminar. Ese `with { type: "file" }` es lo que hace que
10
+ // `bun build --compile` meta el bundle del tool worker dentro del ejecutable
11
+ // (queda en /$bunfs/root/...), porque `new Worker(new URL("./tool-worker.ts",
12
+ // import.meta.url))` NO se embebe solo: el path se resuelve en runtime y el
13
+ // bundler no lo ve. Sin esto, la app de escritorio se instala sin worker y
14
+ // cualquier turno con más de una tool call moría con "Tool worker entry not
15
+ // found" (v1.0.3 y anteriores).
16
+ //
17
+ // En dev y en el paquete npm este valor es null y no hace falta: el worker se
18
+ // resuelve desde disco (tool-worker.ts al lado de este archivo, o
19
+ // dist/tool-worker.js junto al bundle).
20
+ export const embeddedToolWorkerPath: string | null = null
@@ -4,6 +4,8 @@ import { dirname, join } from "node:path"
4
4
  import { availableParallelism } from "node:os"
5
5
  import type { Config } from "../config/loader.ts"
6
6
  import { loadConfig } from "../config/loader.ts"
7
+ import { logger } from "../utils/logger.ts"
8
+ import { embeddedToolWorkerPath } from "./embedded-worker.generated.ts"
7
9
 
8
10
  export type ToolCallLike = {
9
11
  id: string
@@ -105,7 +107,19 @@ type WorkerSlot = {
105
107
  job?: QueuedJob
106
108
  }
107
109
 
108
- function resolveWorkerEntry(): string {
110
+ let cachedWorkerEntry: string | null | undefined
111
+
112
+ /**
113
+ * Locate the tool worker entry, or null when this build ships without one.
114
+ *
115
+ * Returning null instead of throwing is deliberate: workers are an
116
+ * optimization, and a packaging gap must never take a whole turn down with it
117
+ * (it did until v1.0.3 — every desktop install failed each multi-tool turn
118
+ * with "Tool worker entry not found"). The caller degrades to the main thread.
119
+ */
120
+ function resolveWorkerEntry(): string | null {
121
+ if (cachedWorkerEntry !== undefined) return cachedWorkerEntry
122
+
109
123
  const candidates = [
110
124
  new URL("./tool-worker.js", import.meta.url),
111
125
  new URL("./tool-worker.ts", import.meta.url),
@@ -115,7 +129,8 @@ function resolveWorkerEntry(): string {
115
129
 
116
130
  for (const candidate of candidates) {
117
131
  if (existsSync(fileURLToPath(candidate))) {
118
- return candidate.href
132
+ cachedWorkerEntry = candidate.href
133
+ return cachedWorkerEntry
119
134
  }
120
135
  }
121
136
 
@@ -135,13 +150,25 @@ function resolveWorkerEntry(): string {
135
150
 
136
151
  for (const filePath of fallbacks) {
137
152
  if (existsSync(filePath)) {
138
- return filePath
153
+ cachedWorkerEntry = filePath
154
+ return cachedWorkerEntry
139
155
  }
140
156
  }
141
157
 
142
- throw new Error(
143
- `Tool worker entry not found. Tried: ${[...candidates.map((candidate) => fileURLToPath(candidate)), ...fallbacks].join(", ")}`
158
+ // Standalone executable: the worker was embedded at compile time and lives in
159
+ // the virtual bunfs, where existsSync() reports false — so it is taken on
160
+ // trust. It is only ever set by scripts/build-gateway.ts.
161
+ if (embeddedToolWorkerPath) {
162
+ cachedWorkerEntry = embeddedToolWorkerPath
163
+ return cachedWorkerEntry
164
+ }
165
+
166
+ logger.warn(
167
+ "[tool-runtime] No tool worker entry found — running tool batches on the main thread (sequentially)",
168
+ { tried: [...candidates.map((candidate) => fileURLToPath(candidate)), ...fallbacks] }
144
169
  )
170
+ cachedWorkerEntry = null
171
+ return null
145
172
  }
146
173
 
147
174
  function serializeError(error: unknown): SerializedError {
@@ -187,6 +214,7 @@ const DEFAULT_MAIN_THREAD_TOOL_NAMES = new Set([
187
214
  "browser_navigate",
188
215
  "browser_screenshot",
189
216
  "artifact_inspect",
217
+ "artifact_read",
190
218
  "browser_click",
191
219
  "browser_type",
192
220
  "browser_extract",
@@ -255,10 +283,12 @@ class ToolWorkerPool {
255
283
  private workers: WorkerSlot[] = []
256
284
  private queue: QueuedJob[] = []
257
285
  private readonly maxWorkers: number
286
+ private readonly workerEntry: string
258
287
  private disposed = false
259
288
 
260
- constructor(maxWorkers: number) {
289
+ constructor(maxWorkers: number, workerEntry: string) {
261
290
  this.maxWorkers = Math.max(1, maxWorkers)
291
+ this.workerEntry = workerEntry
262
292
  }
263
293
 
264
294
  execute(job: Omit<QueuedJob, "resolve" | "settled" | "startedAt">): Promise<ToolBatchResult> {
@@ -385,7 +415,7 @@ class ToolWorkerPool {
385
415
  }
386
416
 
387
417
  private createSlot(): WorkerSlot {
388
- const worker = new Worker(resolveWorkerEntry(), { type: "module" })
418
+ const worker = new Worker(this.workerEntry, { type: "module" })
389
419
  const slot: WorkerSlot = { worker, busy: false }
390
420
 
391
421
  worker.onmessage = (event: MessageEvent<WorkerMessage>) => {
@@ -500,11 +530,15 @@ class ToolWorkerPool {
500
530
  job.resolve(result)
501
531
 
502
532
  if (restart) {
533
+ // Un worker que abortó o murió se descarta, y el reemplazo lo crea
534
+ // `drain()` solo si queda trabajo. Antes se levantaba uno nuevo en el
535
+ // acto: sobre un aborto —el caso típico al terminar un turno o una
536
+ // suite— eso deja un worker recién arrancado que nadie va a usar y que
537
+ // hay que terminar a mitad del arranque. Bun se cae con SIGSEGV al
538
+ // cerrar el proceso en ese estado (CI: workers_spawned 13, terminated 11).
503
539
  slot.worker.terminate()
504
540
  const index = this.workers.indexOf(slot)
505
- if (index >= 0) {
506
- this.workers[index] = this.createSlot()
507
- }
541
+ if (index >= 0) this.workers.splice(index, 1)
508
542
  } else {
509
543
  slot.busy = false
510
544
  slot.job = undefined
@@ -550,9 +584,12 @@ function resolveToolTimeout(
550
584
  return baseTimeoutMs
551
585
  }
552
586
 
553
- function getPool(maxWorkers: number): ToolWorkerPool {
587
+ function getPool(maxWorkers: number): ToolWorkerPool | null {
588
+ const workerEntry = resolveWorkerEntry()
589
+ if (!workerEntry) return null
590
+
554
591
  if (!sharedPool || sharedPoolSize !== maxWorkers) {
555
- sharedPool = new ToolWorkerPool(maxWorkers)
592
+ sharedPool = new ToolWorkerPool(maxWorkers, workerEntry)
556
593
  sharedPoolSize = maxWorkers
557
594
  }
558
595
  return sharedPool
@@ -578,7 +615,13 @@ export async function executeToolBatch(options: ExecuteToolBatchOptions): Promis
578
615
  }))
579
616
  }
580
617
 
581
- if (!runtimeConfig.enabled || !runtimeConfig.parallelToolCalls || options.toolCalls.length <= 1) {
618
+ // A null pool means workers are disabled, unnecessary (single call), or
619
+ // unavailable in this build — all three degrade to the main thread.
620
+ const pool = runtimeConfig.enabled && runtimeConfig.parallelToolCalls && options.toolCalls.length > 1
621
+ ? getPool(runtimeConfig.maxWorkers)
622
+ : null
623
+
624
+ if (!pool) {
582
625
  const results: ToolBatchResult[] = []
583
626
  for (const toolCall of options.toolCalls) {
584
627
  const startedAt = performance.now()
@@ -605,7 +648,6 @@ export async function executeToolBatch(options: ExecuteToolBatchOptions): Promis
605
648
  return results
606
649
  }
607
650
 
608
- const pool = getPool(runtimeConfig.maxWorkers)
609
651
  const batchId = crypto.randomUUID()
610
652
  const abortHandler = () => pool.abortBatch(batchId, "Tool execution aborted")
611
653
  options.signal?.addEventListener("abort", abortHandler, { once: true })
@@ -11,7 +11,7 @@ import type { Config } from "../config/loader.ts";
11
11
  // Filesystem (7)
12
12
  import * as filesystem from "./filesystem/index.ts";
13
13
 
14
- // Web (10)
14
+ // Web (11)
15
15
  import * as web from "./web/index.ts";
16
16
 
17
17
  // Cron (8) - Croner-based scheduler tools
@@ -43,7 +43,7 @@ export function createAllTools(config: Config): Tool[] {
43
43
  // FILESYSTEM (7)
44
44
  ...filesystem.createTools(),
45
45
 
46
- // WEB (10)
46
+ // WEB (11)
47
47
  ...web.createTools(),
48
48
 
49
49
  // CRON (8)
@@ -124,6 +124,7 @@ export {
124
124
  browserScriptTool,
125
125
  browserWaitTool,
126
126
  artifactInspectTool,
127
+ artifactReadTool,
127
128
  } from "./web/index.ts";
128
129
 
129
130
  export {
@@ -0,0 +1,162 @@
1
+ /**
2
+ * artifact_read — reads back the content an artifact_ref points at.
3
+ *
4
+ * mcp-result-normalizer.ts keeps oversized MCP text results out of the context
5
+ * window: the model gets `{ type: "artifact_ref", artifact_id, size, preview }`
6
+ * with a blind 500-char preview. That is the right call for the context, but
7
+ * without a way to read the artifact back it left the agent stuck — it would
8
+ * call artifact_inspect (metadata only), find no content, and burn its
9
+ * iterations until the turn died on an empty synthesis. This is the way back in.
10
+ *
11
+ * Slicing is by characters, not lines: the case this was built for is a single
12
+ * 245 KB JSON line from a Gmail MCP server, where line-based paging returns
13
+ * everything or nothing. `search` exists for the same reason — jumping straight
14
+ * to the three relevant messages beats paging through 245 KB in 20 KB chunks.
15
+ */
16
+
17
+ import type { Tool } from "../types";
18
+ import { readArtifactText } from "../../artifacts/store";
19
+
20
+ const DEFAULT_LIMIT = 20_000;
21
+ const MAX_LIMIT = 50_000;
22
+ const MAX_MATCHES = 10;
23
+ const DEFAULT_MATCH_CONTEXT = 600;
24
+ const MAX_MATCH_CONTEXT = 8_000;
25
+ /**
26
+ * What a search may return in total. Capping the per-match window alone would
27
+ * be the wrong knob: a record whose fields are 2 KB of mail headers needs a
28
+ * wide window to show its id, while ten such windows would put back into the
29
+ * context exactly what the artifact was created to keep out.
30
+ */
31
+ const MAX_SEARCH_CHARS = 40_000;
32
+
33
+ function clampNumber(value: unknown, fallback: number, min: number, max: number): number {
34
+ const parsed = typeof value === "number" ? value : Number(value);
35
+ if (!Number.isFinite(parsed)) return fallback;
36
+ return Math.min(max, Math.max(min, Math.floor(parsed)));
37
+ }
38
+
39
+ function findMatches(text: string, query: string, context: number): Array<{ offset: number; excerpt: string }> {
40
+ const haystack = text.toLowerCase();
41
+ const needle = query.toLowerCase();
42
+ const matches: Array<{ offset: number; excerpt: string }> = [];
43
+ const half = Math.floor(context / 2);
44
+ let from = 0;
45
+
46
+ let used = 0;
47
+
48
+ while (matches.length < MAX_MATCHES) {
49
+ const at = haystack.indexOf(needle, from);
50
+ if (at === -1) break;
51
+ const start = Math.max(0, at - half);
52
+ const end = Math.min(text.length, at + needle.length + half);
53
+ const excerpt = text.slice(start, end);
54
+ // The first match always comes back, however wide it is — returning zero
55
+ // results for a query that did match would be the worst possible answer.
56
+ if (matches.length > 0 && used + excerpt.length > MAX_SEARCH_CHARS) break;
57
+ matches.push({ offset: at, excerpt });
58
+ used += excerpt.length;
59
+ from = at + needle.length;
60
+ }
61
+
62
+ return matches;
63
+ }
64
+
65
+ function countMatches(text: string, query: string): number {
66
+ const haystack = text.toLowerCase();
67
+ const needle = query.toLowerCase();
68
+ let total = 0;
69
+ let from = 0;
70
+ for (;;) {
71
+ const at = haystack.indexOf(needle, from);
72
+ if (at === -1) return total;
73
+ total++;
74
+ from = at + needle.length;
75
+ }
76
+ }
77
+
78
+ export const artifactReadTool: Tool = {
79
+ name: "artifact_read",
80
+ description:
81
+ "Read the text content of a managed artifact in slices, or search inside it. Use this on any artifact_ref a tool returned instead of guessing from its preview. Spanish: leer artefacto, ver contenido del artefacto, abrir resultado grande, buscar dentro del artefacto",
82
+ parameters: {
83
+ type: "object",
84
+ properties: {
85
+ artifactId: {
86
+ type: "string",
87
+ description: "Managed artifact identifier (the artifact_id of an artifact_ref).",
88
+ },
89
+ offset: {
90
+ type: "number",
91
+ description: "Character position to start reading from (default: 0). Use next_offset from the previous call to continue.",
92
+ },
93
+ limit: {
94
+ type: "number",
95
+ description: `Characters to return (default: ${DEFAULT_LIMIT}, max: ${MAX_LIMIT}).`,
96
+ },
97
+ search: {
98
+ type: "string",
99
+ description: "Return excerpts around each case-insensitive match instead of a contiguous slice. Far cheaper than paging a large artifact.",
100
+ },
101
+ context: {
102
+ type: "number",
103
+ description: `Characters of surrounding text per match (default: ${DEFAULT_MATCH_CONTEXT}, max: ${MAX_MATCH_CONTEXT}). Widen it when records carry long fields and the excerpt cuts off the data you need.`,
104
+ },
105
+ },
106
+ required: ["artifactId"],
107
+ },
108
+ execute: async (params, config) => {
109
+ const artifactId = String(params.artifactId ?? "").trim();
110
+ if (!artifactId) return { ok: false, error: "artifactId is required" };
111
+
112
+ const userId = config?.configurable?.user_id as string | undefined;
113
+ const result = await readArtifactText(artifactId, { userId });
114
+ if (!result.ok || !result.artifact) {
115
+ return { ok: false, artifact_id: artifactId, error: result.error, status: result.status };
116
+ }
117
+
118
+ const artifact = result.artifact;
119
+ const text = result.text ?? "";
120
+ const search = typeof params.search === "string" ? params.search.trim() : "";
121
+
122
+ if (search) {
123
+ const context = clampNumber(params.context, DEFAULT_MATCH_CONTEXT, 40, MAX_MATCH_CONTEXT);
124
+ const matches = findMatches(text, search, context);
125
+ // Always the real count, never the number returned: collection stops at
126
+ // MAX_MATCHES or at the character budget, and an agent told "4 matches"
127
+ // when there are 8 stops looking.
128
+ const total = countMatches(text, search);
129
+ return {
130
+ ok: true,
131
+ artifact_id: artifact.id,
132
+ mime_type: artifact.mime_type,
133
+ total_chars: text.length,
134
+ query: search,
135
+ total_matches: total,
136
+ returned_matches: matches.length,
137
+ truncated: total > matches.length,
138
+ context,
139
+ matches,
140
+ };
141
+ }
142
+
143
+ const offset = clampNumber(params.offset, 0, 0, Math.max(0, text.length));
144
+ const limit = clampNumber(params.limit, DEFAULT_LIMIT, 1, MAX_LIMIT);
145
+ const content = text.slice(offset, offset + limit);
146
+ const nextOffset = offset + content.length;
147
+ const eof = nextOffset >= text.length;
148
+
149
+ return {
150
+ ok: true,
151
+ artifact_id: artifact.id,
152
+ mime_type: artifact.mime_type,
153
+ kind: artifact.kind,
154
+ total_chars: text.length,
155
+ offset,
156
+ returned_chars: content.length,
157
+ next_offset: eof ? null : nextOffset,
158
+ eof,
159
+ content,
160
+ };
161
+ },
162
+ };
@@ -15,6 +15,7 @@ import { browserExtractTool } from "./browser-extract.ts";
15
15
  import { browserScriptTool } from "./browser-script.ts";
16
16
  import { browserWaitTool } from "./browser-wait.ts";
17
17
  import { artifactInspectTool } from "./artifact-inspect.ts";
18
+ import { artifactReadTool } from "./artifact-read.ts";
18
19
 
19
20
  export function createTools(): Tool[] {
20
21
  return [
@@ -28,6 +29,7 @@ export function createTools(): Tool[] {
28
29
  browserScriptTool,
29
30
  browserWaitTool,
30
31
  artifactInspectTool,
32
+ artifactReadTool,
31
33
  ];
32
34
  }
33
35
 
@@ -42,3 +44,4 @@ export * from "./browser-script.ts";
42
44
  export * from "./browser-wait.ts";
43
45
  export * from "./browser-service.ts";
44
46
  export * from "./artifact-inspect.ts";
47
+ export * from "./artifact-read.ts";
@@ -0,0 +1,17 @@
1
+ /**
2
+ * redact-binary — last-line-of-defense redaction for stray base64 blobs.
3
+ *
4
+ * mcp-result-normalizer.ts (agent/mcp-result-normalizer.ts) is the real fix:
5
+ * it intercepts MCP image/audio/resource content blocks before they ever
6
+ * reach a string. This utility is the safety net for whatever slips past
7
+ * that — a producer that isn't MCP, a content shape normalizeMcpResult
8
+ * doesn't recognize, etc. Never rely on this alone to keep binaries out of
9
+ * the LLM context.
10
+ */
11
+
12
+ const DATA_URI_RE = /data:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[a-z0-9+/=\s]+/gi;
13
+ const LONG_BASE64_RE = /[A-Za-z0-9+/]{1000,}={0,2}/g;
14
+
15
+ export function redactBinaryStrings(text: string): string {
16
+ return text.replace(DATA_URI_RE, "[REDACTED_BINARY]").replace(LONG_BASE64_RE, "[REDACTED_BINARY]");
17
+ }