@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.
- package/README.md +4 -4
- package/dist/hive.js +46386 -45716
- package/dist/ui/assets/A2UIPage-7Ry5rHh9.js +8 -0
- package/dist/ui/assets/AgentCreateForm-Dh5W0q_t.js +1 -0
- package/dist/ui/assets/AgentDetailPage-CIoPjtsS.js +1 -0
- package/dist/ui/assets/AgentNewPage-BNsZcJQf.js +1 -0
- package/dist/ui/assets/AgentsPage-YZrDmgNI.js +10 -0
- package/dist/ui/assets/ApiClientPage-6a6KFwsQ.js +3 -0
- package/dist/ui/assets/ChannelsPage-Dice4dkJ.js +8 -0
- package/dist/ui/assets/DashboardPage-B9r0sc0F.js +6 -0
- package/dist/ui/assets/LoginPage-BkAAX_tu.js +1 -0
- package/dist/ui/assets/{LogsPage-6Po7_T2u.js → LogsPage-8-H1OJs3.js} +1 -1
- package/dist/ui/assets/MeetingPage-14JoQo71.js +1 -0
- package/dist/ui/assets/ModelSelector-CrgJQ7DG.js +1 -0
- package/dist/ui/assets/{NotFound-Bpr12V51.js → NotFound-B06kVW7N.js} +1 -1
- package/dist/ui/assets/{Office3DPage-BYwLMTCl.js → Office3DPage-BMUZWkFS.js} +2 -2
- package/dist/ui/assets/ProvidersPage-BiL3QxCs.js +1 -0
- package/dist/ui/assets/RecoverPage-D1o8yxNz.js +1 -0
- package/dist/ui/assets/SettingsPage-GP8UwQIL.js +9 -0
- package/dist/ui/assets/SetupPage-B_gU1YQU.js +1 -0
- package/dist/ui/assets/WebChatPage-Yahufnth.js +29 -0
- package/dist/ui/assets/activity-C_GS5wrG.js +1 -0
- package/dist/ui/assets/agentCapabilities-Dg72UAFj.js +1 -0
- package/dist/ui/assets/{alert-CQlRq6sv.js → alert-DChoEVJw.js} +1 -1
- package/dist/ui/assets/arrow-left-WyDPYZXU.js +1 -0
- package/dist/ui/assets/arrow-right-BuNjN-bk.js +1 -0
- package/dist/ui/assets/arrow-up-right-DWzTsCXj.js +1 -0
- package/dist/ui/assets/{badge-DKGZbVZJ.js → badge-uRjRSt86.js} +1 -1
- package/dist/ui/assets/calendar-B6x9cw-q.js +1 -0
- package/dist/ui/assets/{card-D3Nw3kh3.js → card-DwQizslL.js} +1 -1
- package/dist/ui/assets/check-C8pw-7Fx.js +1 -0
- package/dist/ui/assets/chevron-down-8GjmTjLR.js +1 -0
- package/dist/ui/assets/chevron-left-GK4EQOyZ.js +1 -0
- package/dist/ui/assets/chevron-right-BupZqrxu.js +1 -0
- package/dist/ui/assets/chevron-up-DZrzJIW8.js +1 -0
- package/dist/ui/assets/circle-alert-CtDbK2nl.js +1 -0
- package/dist/ui/assets/circle-check-BKNT2_q6.js +1 -0
- package/dist/ui/assets/circle-x-DfBjbztU.js +1 -0
- package/dist/ui/assets/copy-wR7o7Ly8.js +1 -0
- package/dist/ui/assets/core-Sjunb8Z1.js +1 -0
- package/dist/ui/assets/createLucideIcon-BRaPSYgN.js +1 -0
- package/dist/ui/assets/{dialog-CO1WrPJc.js → dialog--mljnfAi.js} +1 -1
- package/dist/ui/assets/dist-js-B0s_TDau.js +1 -0
- package/dist/ui/assets/dist-js-CLxM1g2B.js +1 -0
- package/dist/ui/assets/download-D0aDV8Y_.js +1 -0
- package/dist/ui/assets/earth-BJRGJbVn.js +1 -0
- package/dist/ui/assets/ellipsis-vertical-BOW_iEOO.js +1 -0
- package/dist/ui/assets/external-link-5cujQzfV.js +1 -0
- package/dist/ui/assets/eye-sRPY5qOa.js +1 -0
- package/dist/ui/assets/file-text-DNSyNLUh.js +1 -0
- package/dist/ui/assets/gauge-C__zxC3_.js +1 -0
- package/dist/ui/assets/history-BHQWfE-7.js +1 -0
- package/dist/ui/assets/index-BHHUQZJd.js +116 -0
- package/dist/ui/assets/index-CEFhf4dF.css +2 -0
- package/dist/ui/assets/info-CG1VohyH.js +1 -0
- package/dist/ui/assets/key-BC28VCjO.js +1 -0
- package/dist/ui/assets/{label-k0jYxoWW.js → label-BceoUB2w.js} +1 -1
- package/dist/ui/assets/lock-open-Bhp0UJlL.js +1 -0
- package/dist/ui/assets/mail-Biwn8WrV.js +1 -0
- package/dist/ui/assets/pause-C2l5G2Py.js +1 -0
- package/dist/ui/assets/pencil-CUbpCfeG.js +1 -0
- package/dist/ui/assets/play-CMAscR3a.js +1 -0
- package/dist/ui/assets/plus-DzvRxH4U.js +1 -0
- package/dist/ui/assets/radio-DfGzov4y.js +1 -0
- package/dist/ui/assets/refresh-cw-DZXu5FrG.js +1 -0
- package/dist/ui/assets/scroll-area-DMEaZZUp.js +1 -0
- package/dist/ui/assets/search-ykSx-zZU.js +1 -0
- package/dist/ui/assets/{select-BfRyBbi9.js → select-BBEBtcLm.js} +1 -1
- package/dist/ui/assets/send-DAhlz2i9.js +1 -0
- package/dist/ui/assets/settings-DL0REysC.js +1 -0
- package/dist/ui/assets/shield-BPZZhjCT.js +1 -0
- package/dist/ui/assets/slider-DcmBdvYD.js +1 -0
- package/dist/ui/assets/sparkles-BViXTAh7.js +1 -0
- package/dist/ui/assets/square-psq7k_CB.js +1 -0
- package/dist/ui/assets/{switch-DXcELPsM.js → switch-CgiDezVR.js} +1 -1
- package/dist/ui/assets/tabs-gUXIjjZv.js +1 -0
- package/dist/ui/assets/terminal-CzxPKG-h.js +1 -0
- package/dist/ui/assets/{textarea-rp6vsOZl.js → textarea-DedxQYBx.js} +1 -1
- package/dist/ui/assets/trash-2-SgYCWiVk.js +1 -0
- package/dist/ui/assets/{useHiveAgentsModelLoad-D3s2U82M.js → useHiveAgentsModelLoad-C7bhWPDG.js} +1 -1
- package/dist/ui/assets/useProviders-CiLSc05q.js +1 -0
- package/dist/ui/assets/vendor-radix-DUug7irY.js +63 -0
- package/dist/ui/assets/{vendor-react-CPJEWbIG.js → vendor-react-DYyYpuMy.js} +1 -1
- package/dist/ui/assets/volume-x-BDlMCDYT.js +1 -0
- package/dist/ui/assets/wifi-CyPHteEm.js +1 -0
- package/dist/ui/assets/zap-OVVrfEHr.js +1 -0
- package/dist/ui/index.html +8 -7
- package/package.json +1 -1
- package/packages/core/src/agent/agent-loop.ts +77 -3
- package/packages/core/src/agent/context-compiler.ts +13 -2
- package/packages/core/src/agent/llm-client.ts +41 -6
- package/packages/core/src/agent/llm-providers/nvidia.ts +39 -0
- package/packages/core/src/agent/llm-providers/openai-compat-base.ts +38 -2
- package/packages/core/src/agent/mcp-result-normalizer.ts +192 -0
- package/packages/core/src/agent/providers/index.ts +8 -0
- package/packages/core/src/agent/tool-selector.ts +1 -0
- package/packages/core/src/artifacts/store.ts +81 -0
- package/packages/core/src/channels/base.ts +33 -0
- package/packages/core/src/channels/discord.ts +20 -1
- package/packages/core/src/channels/slack.ts +21 -2
- package/packages/core/src/channels/telegram.ts +16 -1
- package/packages/core/src/channels/whatsapp.ts +16 -3
- package/packages/core/src/events/tool-narration.ts +3 -0
- package/packages/core/src/gateway/durable-queue.ts +2 -1
- package/packages/core/src/gateway/failure-notify.ts +78 -0
- package/packages/core/src/gateway/job-executors.ts +1 -0
- package/packages/core/src/gateway/job-store.ts +6 -0
- package/packages/core/src/gateway/process-safety.ts +40 -0
- package/packages/core/src/gateway/routes/artifacts.ts +60 -0
- package/packages/core/src/gateway/routes/system.ts +9 -4
- package/packages/core/src/gateway/server.ts +36 -5
- package/packages/core/src/gateway/webchat-turn.ts +74 -2
- package/packages/core/src/storage/seed.ts +1 -0
- package/packages/core/src/tool-runtime/embedded-worker.generated.ts +20 -0
- package/packages/core/src/tool-runtime/index.ts +56 -14
- package/packages/core/src/tools/index.ts +3 -2
- package/packages/core/src/tools/web/artifact-read.ts +162 -0
- package/packages/core/src/tools/web/index.ts +3 -0
- package/packages/core/src/utils/redact-binary.ts +17 -0
- package/packages/skills/src/bundled-data.generated.ts +752 -752
- package/dist/ui/assets/A2UIPage-BRpjnMss.js +0 -8
- package/dist/ui/assets/AgentCreateForm-ASjKD7Js.js +0 -1
- package/dist/ui/assets/AgentDetailPage-bqJ-MS40.js +0 -1
- package/dist/ui/assets/AgentNewPage-CPaf2C3u.js +0 -1
- package/dist/ui/assets/AgentsPage-BIpLG0V6.js +0 -10
- package/dist/ui/assets/ApiClientPage-dRckcgrN.js +0 -3
- package/dist/ui/assets/ChannelsPage-BX_hPtiN.js +0 -8
- package/dist/ui/assets/DashboardPage-KMaMaFf4.js +0 -6
- package/dist/ui/assets/LoginPage-Zchu-f16.js +0 -1
- package/dist/ui/assets/MeetingPage-qrpYGVD-.js +0 -1
- package/dist/ui/assets/ModelSelector-C8ny_pxu.js +0 -1
- package/dist/ui/assets/ProvidersPage-DP9v_1ko.js +0 -1
- package/dist/ui/assets/RecoverPage-BXwjLfap.js +0 -1
- package/dist/ui/assets/SettingsPage-DD7GKtS6.js +0 -9
- package/dist/ui/assets/SetupPage-D7YX2io-.js +0 -1
- package/dist/ui/assets/WebChatPage-C3cgimxd.js +0 -29
- package/dist/ui/assets/activity-DZKL7dg4.js +0 -1
- package/dist/ui/assets/agentCapabilities-DuGs07XP.js +0 -1
- package/dist/ui/assets/arrow-left-12JaXVoH.js +0 -1
- package/dist/ui/assets/arrow-right-Dbui5p0d.js +0 -1
- package/dist/ui/assets/arrow-up-right-CJBtXRrp.js +0 -1
- package/dist/ui/assets/calendar-CkDsc4OJ.js +0 -1
- package/dist/ui/assets/check-DxOMIDcl.js +0 -1
- package/dist/ui/assets/chevron-down-CObv-xyx.js +0 -1
- package/dist/ui/assets/chevron-left-C0mqwhLU.js +0 -1
- package/dist/ui/assets/chevron-right-jCt1h8Kw.js +0 -1
- package/dist/ui/assets/chevron-up-DX_5iw7O.js +0 -1
- package/dist/ui/assets/circle-alert-BkP6x0zQ.js +0 -1
- package/dist/ui/assets/circle-check-CXC2AiMS.js +0 -1
- package/dist/ui/assets/circle-x-h4OJiHV3.js +0 -1
- package/dist/ui/assets/copy-BtpYEEvV.js +0 -1
- package/dist/ui/assets/download-aPuVaZik.js +0 -1
- package/dist/ui/assets/earth-sc8YJMc0.js +0 -1
- package/dist/ui/assets/ellipsis-vertical-DEBZJGzY.js +0 -1
- package/dist/ui/assets/external-link-D_C_678M.js +0 -1
- package/dist/ui/assets/eye-BfN613fx.js +0 -1
- package/dist/ui/assets/file-text-Bth5pPZX.js +0 -1
- package/dist/ui/assets/gauge-DypSzSOE.js +0 -1
- package/dist/ui/assets/history-njH_sPSo.js +0 -1
- package/dist/ui/assets/index-D-9yCvjP.js +0 -116
- package/dist/ui/assets/index-wML8DaUo.css +0 -2
- package/dist/ui/assets/info-Def2ZFeP.js +0 -1
- package/dist/ui/assets/key-D8bkDl83.js +0 -1
- package/dist/ui/assets/loader-circle-wLVzSdML.js +0 -1
- package/dist/ui/assets/lock-open-Cdopbw1b.js +0 -1
- package/dist/ui/assets/mail-BQ_YA9_b.js +0 -1
- package/dist/ui/assets/pause-CvS_LzKx.js +0 -1
- package/dist/ui/assets/pencil-C3tPvnCk.js +0 -1
- package/dist/ui/assets/play-C-oR-PMH.js +0 -1
- package/dist/ui/assets/plus-CF9No2td.js +0 -1
- package/dist/ui/assets/progress-DrI2UDu-.js +0 -1
- package/dist/ui/assets/radio-dsaiFxuT.js +0 -1
- package/dist/ui/assets/refresh-cw-BmYQwOhh.js +0 -1
- package/dist/ui/assets/scroll-area-CfHn94Vb.js +0 -1
- package/dist/ui/assets/search-CTONpTyl.js +0 -1
- package/dist/ui/assets/send-C3o2wpLi.js +0 -1
- package/dist/ui/assets/settings-DEpdBuf2.js +0 -1
- package/dist/ui/assets/shield-gbUkSqfi.js +0 -1
- package/dist/ui/assets/slider-CmE_z1Ii.js +0 -1
- package/dist/ui/assets/sparkles-Ccd1JZ3s.js +0 -1
- package/dist/ui/assets/square-BrwQ6Mun.js +0 -1
- package/dist/ui/assets/tabs-CxiybXcw.js +0 -1
- package/dist/ui/assets/terminal-DP9j3HjM.js +0 -1
- package/dist/ui/assets/trash-2-CfCs7RhJ.js +0 -1
- package/dist/ui/assets/triangle-alert-C3lWSnRr.js +0 -1
- package/dist/ui/assets/useProviders-B3rT_xU9.js +0 -1
- package/dist/ui/assets/vendor-radix-D0s_k6Gp.js +0 -63
- package/dist/ui/assets/volume-x-D2h9cyml.js +0 -1
- package/dist/ui/assets/wifi-CGQECzu2.js +0 -1
- package/dist/ui/assets/zap-B1azpiE7.js +0 -1
- /package/dist/ui/assets/{gateway-url-BlnabM5e.js → gateway-url-BZj_2-jf.js} +0 -0
- /package/dist/ui/assets/{useOfficeModel-Cy7cAyEn.js → useOfficeModel-BAFasrg8.js} +0 -0
- /package/dist/ui/assets/{utils-Dyb7SC2_.js → utils-SGUggNJc.js} +0 -0
- /package/dist/ui/assets/{vendor-router-zpB-76nT.js → vendor-router-Dsg8fxNQ.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-S-ySWqyJ.js";import{At as t}from"./vendor-radix-
|
|
1
|
+
import{t as e}from"./rolldown-runtime-S-ySWqyJ.js";import{At as t}from"./vendor-radix-DUug7irY.js";var n=e((e=>{var n=t();e.createRoot=n.createRoot,e.hydrateRoot=n.hydrateRoot}));export{n as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./createLucideIcon-BRaPSYgN.js";var t=e(`Volume2`,[[`path`,{d:`M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z`,key:`uqj9uw`}],[`path`,{d:`M16 9a5 5 0 0 1 0 6`,key:`1q6k2b`}],[`path`,{d:`M19.364 18.364a9 9 0 0 0 0-12.728`,key:`ijwkga`}]]),n=e(`VolumeX`,[[`path`,{d:`M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z`,key:`uqj9uw`}],[`line`,{x1:`22`,x2:`16`,y1:`9`,y2:`15`,key:`1ewh16`}],[`line`,{x1:`16`,x2:`22`,y1:`9`,y2:`15`,key:`5ykzw1`}]]);export{t as n,n as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./createLucideIcon-BRaPSYgN.js";var t=e(`WifiOff`,[[`path`,{d:`M12 20h.01`,key:`zekei9`}],[`path`,{d:`M8.5 16.429a5 5 0 0 1 7 0`,key:`1bycff`}],[`path`,{d:`M5 12.859a10 10 0 0 1 5.17-2.69`,key:`1dl1wf`}],[`path`,{d:`M19 12.859a10 10 0 0 0-2.007-1.523`,key:`4k23kn`}],[`path`,{d:`M2 8.82a15 15 0 0 1 4.177-2.643`,key:`1grhjp`}],[`path`,{d:`M22 8.82a15 15 0 0 0-11.288-3.764`,key:`z3jwby`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]),n=e(`Wifi`,[[`path`,{d:`M12 20h.01`,key:`zekei9`}],[`path`,{d:`M2 8.82a15 15 0 0 1 20 0`,key:`dnpr2z`}],[`path`,{d:`M5 12.859a10 10 0 0 1 14 0`,key:`1x1e6c`}],[`path`,{d:`M8.5 16.429a5 5 0 0 1 7 0`,key:`1bycff`}]]);export{t as n,n as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./createLucideIcon-BRaPSYgN.js";var t=e(`Zap`,[[`path`,{d:`M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z`,key:`1xq2db`}]]);export{t};
|
package/dist/ui/index.html
CHANGED
|
@@ -23,17 +23,18 @@
|
|
|
23
23
|
<meta name="twitter:title" content="Hive">
|
|
24
24
|
<meta property="og:description" content="Hive Agents">
|
|
25
25
|
<meta name="twitter:description" content="Hive Agents">
|
|
26
|
-
<script type="module" crossorigin src="/assets/index-
|
|
26
|
+
<script type="module" crossorigin src="/assets/index-BHHUQZJd.js"></script>
|
|
27
27
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-S-ySWqyJ.js">
|
|
28
28
|
<link rel="modulepreload" crossorigin href="/assets/vendor-charts-K3xcRl0X.js">
|
|
29
|
-
<link rel="modulepreload" crossorigin href="/assets/vendor-router-
|
|
29
|
+
<link rel="modulepreload" crossorigin href="/assets/vendor-router-Dsg8fxNQ.js">
|
|
30
30
|
<link rel="modulepreload" crossorigin href="/assets/vendor-query-Dj8xYhQD.js">
|
|
31
|
-
<link rel="modulepreload" crossorigin href="/assets/vendor-radix-
|
|
31
|
+
<link rel="modulepreload" crossorigin href="/assets/vendor-radix-DUug7irY.js">
|
|
32
32
|
<link rel="modulepreload" crossorigin href="/assets/dist-CD_qfA30.js">
|
|
33
|
-
<link rel="modulepreload" crossorigin href="/assets/
|
|
34
|
-
<link rel="modulepreload" crossorigin href="/assets/
|
|
35
|
-
<link rel="modulepreload" crossorigin href="/assets/
|
|
36
|
-
<link rel="
|
|
33
|
+
<link rel="modulepreload" crossorigin href="/assets/createLucideIcon-BRaPSYgN.js">
|
|
34
|
+
<link rel="modulepreload" crossorigin href="/assets/vendor-react-DYyYpuMy.js">
|
|
35
|
+
<link rel="modulepreload" crossorigin href="/assets/utils-SGUggNJc.js">
|
|
36
|
+
<link rel="modulepreload" crossorigin href="/assets/gateway-url-BZj_2-jf.js">
|
|
37
|
+
<link rel="stylesheet" crossorigin href="/assets/index-CEFhf4dF.css">
|
|
37
38
|
</head>
|
|
38
39
|
|
|
39
40
|
<body>
|
package/package.json
CHANGED
|
@@ -26,6 +26,7 @@ import { emitCanvas } from "../canvas/emitter"
|
|
|
26
26
|
import type { MCPClientManager } from "@johpaz/hive-agents-mcp"
|
|
27
27
|
import { compileContext } from "./context-compiler"
|
|
28
28
|
import { formatToolResult } from "../utils/toon"
|
|
29
|
+
import { redactBinaryStrings } from "../utils/redact-binary"
|
|
29
30
|
import { resolveUserId, resolveAgentId } from "../storage/onboarding"
|
|
30
31
|
import type { ContentPart } from "../multimodal/types"
|
|
31
32
|
import { loadConfig } from "../config/loader"
|
|
@@ -94,6 +95,50 @@ export async function synthesizeFinalResponse(
|
|
|
94
95
|
)
|
|
95
96
|
}
|
|
96
97
|
|
|
98
|
+
type LoadoutContext = {
|
|
99
|
+
tools: Array<{ type: string; function?: { name?: string } }>
|
|
100
|
+
allTools: Array<{ name: string }>
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Adds artifact_read to the loadout the moment a tool result hands the model an
|
|
105
|
+
* `artifact_ref` it will need to open.
|
|
106
|
+
*
|
|
107
|
+
* mcp-result-normalizer.ts moves oversized MCP text results out of the context
|
|
108
|
+
* window and leaves a reference behind. Discovery (search_knowledge) can find
|
|
109
|
+
* the reader, but that costs an iteration and assumes the model thinks to look:
|
|
110
|
+
* in the incident this comes from, it reached for artifact_inspect instead, got
|
|
111
|
+
* metadata, and burned the rest of its budget on `find` and `env` before the
|
|
112
|
+
* turn died on an empty synthesis. Image refs are excluded — those are carried
|
|
113
|
+
* to the UI, not read back by the model.
|
|
114
|
+
*
|
|
115
|
+
* Returns true when the loadout changed.
|
|
116
|
+
*/
|
|
117
|
+
export function injectArtifactReadIfNeeded(toolResult: unknown, ctx: LoadoutContext): boolean {
|
|
118
|
+
if (!Array.isArray(toolResult)) return false
|
|
119
|
+
|
|
120
|
+
const needsReader = toolResult.some((block) =>
|
|
121
|
+
!!block && typeof block === "object" &&
|
|
122
|
+
(block as { type?: unknown }).type === "artifact_ref" &&
|
|
123
|
+
!String((block as { mime_type?: unknown }).mime_type ?? "").startsWith("image/")
|
|
124
|
+
)
|
|
125
|
+
if (!needsReader) return false
|
|
126
|
+
if (ctx.tools.some((t) => t.function?.name === "artifact_read")) return false
|
|
127
|
+
|
|
128
|
+
const reader = ctx.allTools.find((t) => t.name === "artifact_read")
|
|
129
|
+
if (!reader) return false
|
|
130
|
+
|
|
131
|
+
ctx.tools.push({
|
|
132
|
+
type: "function",
|
|
133
|
+
function: {
|
|
134
|
+
name: reader.name,
|
|
135
|
+
description: (reader as any).description ?? "",
|
|
136
|
+
parameters: (reader as any).parameters ?? { type: "object", properties: {} },
|
|
137
|
+
},
|
|
138
|
+
} as LoadoutContext["tools"][number])
|
|
139
|
+
return true
|
|
140
|
+
}
|
|
141
|
+
|
|
97
142
|
/** Bounds a single async operation to its own timeout window, independent of any caller. */
|
|
98
143
|
export async function withTimeout<T>(op: () => Promise<T>, timeoutMs: number): Promise<T> {
|
|
99
144
|
let timer: ReturnType<typeof setTimeout>
|
|
@@ -215,6 +260,8 @@ export interface StreamChunk {
|
|
|
215
260
|
agent?: { messages: any[]; streamed?: boolean }
|
|
216
261
|
tools?: { messages: any[] }
|
|
217
262
|
usage?: { input_tokens: number; output_tokens: number }
|
|
263
|
+
/** Image artifacts (mcp-result-normalizer.ts) produced by tools this turn. */
|
|
264
|
+
artifacts?: { images: Array<{ artifactId: string; mimeType: string }> }
|
|
218
265
|
}
|
|
219
266
|
|
|
220
267
|
// ─── Main agent loop ──────────────────────────────────────────────────────────
|
|
@@ -360,6 +407,10 @@ export async function* runAgent(
|
|
|
360
407
|
let iterations = 0
|
|
361
408
|
let totalInputTokens = 0
|
|
362
409
|
let totalOutputTokens = 0
|
|
410
|
+
// Image artifacts produced by tool results this turn (post mcp-result-normalizer.ts) —
|
|
411
|
+
// surfaced in the final chunk so callers (webchat-turn.ts) can attach them to the
|
|
412
|
+
// outbound message instead of the model having to describe them in text.
|
|
413
|
+
const turnImageArtifacts: Array<{ artifactId: string; mimeType: string }> = []
|
|
363
414
|
let lastToolSignature = ""
|
|
364
415
|
let consecutiveRepeat = 0
|
|
365
416
|
let idleIterations = 0
|
|
@@ -648,6 +699,27 @@ export async function* runAgent(
|
|
|
648
699
|
const toolResultJS = batchResult.result
|
|
649
700
|
const toolMs = batchResult.durationMs
|
|
650
701
|
|
|
702
|
+
// Surface image artifacts (see mcp-result-normalizer.ts) so the final
|
|
703
|
+
// response can carry them to the UI/channel — before TOON-encoding,
|
|
704
|
+
// while toolResultJS is still structured.
|
|
705
|
+
if (Array.isArray(toolResultJS)) {
|
|
706
|
+
for (const block of toolResultJS) {
|
|
707
|
+
if (
|
|
708
|
+
block && typeof block === "object" &&
|
|
709
|
+
(block as { type?: unknown }).type === "artifact_ref" &&
|
|
710
|
+
typeof (block as { mime_type?: unknown }).mime_type === "string" &&
|
|
711
|
+
(block as { mime_type: string }).mime_type.startsWith("image/")
|
|
712
|
+
) {
|
|
713
|
+
const ref = block as { artifact_id: string; mime_type: string }
|
|
714
|
+
turnImageArtifacts.push({ artifactId: ref.artifact_id, mimeType: ref.mime_type })
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
if (injectArtifactReadIfNeeded(toolResultJS, ctx)) {
|
|
720
|
+
log.info("[agent-loop] Tool result carries an artifact_ref — injected artifact_read into loadout")
|
|
721
|
+
}
|
|
722
|
+
|
|
651
723
|
// Encode TOON only for LLM consumption (with cost calculation)
|
|
652
724
|
const toolResultLLM = formatToolResult(toolResultJS, cleanModel)
|
|
653
725
|
|
|
@@ -1085,6 +1157,10 @@ export async function* runAgent(
|
|
|
1085
1157
|
yield { usage: { input_tokens: totalInputTokens, output_tokens: totalOutputTokens } }
|
|
1086
1158
|
}
|
|
1087
1159
|
|
|
1160
|
+
if (turnImageArtifacts.length > 0) {
|
|
1161
|
+
yield { artifacts: { images: turnImageArtifacts } }
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1088
1164
|
// ── Post-loop ────────────────────────────────────────────────────────────
|
|
1089
1165
|
const durationMs = Math.round(performance.now() - t0)
|
|
1090
1166
|
|
|
@@ -1232,9 +1308,7 @@ export async function runAgentIsolatedDetailed(
|
|
|
1232
1308
|
}
|
|
1233
1309
|
for (const message of chunk.tools?.messages ?? []) {
|
|
1234
1310
|
const raw = typeof message.content === "string" ? message.content : JSON.stringify(message.content)
|
|
1235
|
-
const safe = raw
|
|
1236
|
-
.replace(/data:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[a-z0-9+/=\s]+/gi, "[REDACTED_BINARY]")
|
|
1237
|
-
.replace(/[A-Za-z0-9+/]{1000,}={0,2}/g, "[REDACTED_BINARY]")
|
|
1311
|
+
const safe = redactBinaryStrings(raw)
|
|
1238
1312
|
toolEvidence.push(`${message.name ?? "tool"}: ${safe.slice(0, 4000)}`)
|
|
1239
1313
|
if (toolEvidence.length > 8) toolEvidence.shift()
|
|
1240
1314
|
}
|
|
@@ -36,6 +36,7 @@ import { createAllTools } from "../tools/index.ts"
|
|
|
36
36
|
import { resolveUserId } from "../storage/onboarding"
|
|
37
37
|
import { getMCPManager as getSingletonMCPManager } from "../mcp/singleton"
|
|
38
38
|
import { syncMCPToolsToDB, syncMCPToolsToIndex } from "../mcp/tool-sync"
|
|
39
|
+
import { normalizeMcpResult } from "./mcp-result-normalizer"
|
|
39
40
|
import { getUserDate, getUserTime } from "../utils/date"
|
|
40
41
|
import { loadConfig } from "../config/loader"
|
|
41
42
|
import { getHiveDb } from "../storage/hivedb"
|
|
@@ -293,10 +294,20 @@ export async function compileContext(opts: {
|
|
|
293
294
|
name: fullName,
|
|
294
295
|
description: mcpTool.description || `Tool from ${server.name}`,
|
|
295
296
|
parameters: mcpTool.inputSchema || { type: "object", properties: {} },
|
|
296
|
-
execute: async (params: Record<string, unknown>) => {
|
|
297
|
+
execute: async (params: Record<string, unknown>, config?: { configurable?: Record<string, unknown> }) => {
|
|
297
298
|
// Return raw JS value — agent-loop will TOON-encode via formatToolResult.
|
|
298
299
|
// Never pre-stringify here: formatToolResult(string) double-encodes.
|
|
299
|
-
|
|
300
|
+
const raw = await effectiveMcpManager.callTool(resolvedServerKey, mcpTool.name, params)
|
|
301
|
+
// MCP results can carry base64 image/audio/blob content blocks —
|
|
302
|
+
// normalize those into artifact_ref pointers so a large binary
|
|
303
|
+
// result never gets serialized whole into the LLM context (see
|
|
304
|
+
// mcp-result-normalizer.ts for the incident this prevents).
|
|
305
|
+
const configurable = config?.configurable ?? {}
|
|
306
|
+
return await normalizeMcpResult(raw, {
|
|
307
|
+
userId: configurable.user_id ? String(configurable.user_id) : undefined,
|
|
308
|
+
runId: configurable.run_id ? String(configurable.run_id) : null,
|
|
309
|
+
taskId: configurable.task_id ? String(configurable.task_id) : null,
|
|
310
|
+
})
|
|
300
311
|
},
|
|
301
312
|
})
|
|
302
313
|
|
|
@@ -182,20 +182,55 @@ export async function callLLM(options: LLMCallOptions): Promise<LLMResponse> {
|
|
|
182
182
|
const cleanModel = options.model.replace(new RegExp(`^${options.provider}\\/`), "")
|
|
183
183
|
const status = extractErrorStatus(err)
|
|
184
184
|
const modelUnavailable = status === 404 || status === 410
|
|
185
|
-
const msg =
|
|
186
|
-
? `El modelo "${cleanModel}" ya no existe en ${options.provider} (HTTP ${status}). `
|
|
187
|
-
+ `El proveedor lo retiró de su catálogo; reintentar no sirve. `
|
|
188
|
-
+ `Elegí otro modelo en Ajustes → Proveedores.`
|
|
189
|
-
: (err as Error).message
|
|
185
|
+
const msg = describeProviderFailure(err, status, options.provider, cleanModel)
|
|
190
186
|
log.error(`[llm-client] Error calling ${options.provider}/${cleanModel}: ${msg}`, err)
|
|
191
187
|
return {
|
|
192
|
-
content:
|
|
188
|
+
content: `${LLM_ERROR_PREFIX} ${msg}`,
|
|
193
189
|
stop_reason: "error",
|
|
194
190
|
error: { message: msg, status, modelUnavailable },
|
|
195
191
|
}
|
|
196
192
|
}
|
|
197
193
|
}
|
|
198
194
|
|
|
195
|
+
/**
|
|
196
|
+
* Marks content that is a provider failure rather than something the agent
|
|
197
|
+
* said. webchat-turn.ts keys the failed-turn UI off this prefix, and
|
|
198
|
+
* agent-loop.ts keeps such content out of the conversation history.
|
|
199
|
+
*/
|
|
200
|
+
export const LLM_ERROR_PREFIX = "[LLM Error]"
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Turns a provider failure into something the user can act on.
|
|
204
|
+
*
|
|
205
|
+
* The raw SDK text is written for whoever is reading a stack trace: "429 status
|
|
206
|
+
* code (no body)" showed up verbatim in the chat and says nothing about what
|
|
207
|
+
* happened (the account hit its rate limit) or what to do about it. Statuses
|
|
208
|
+
* without a specific mapping keep the original message — a wrong explanation is
|
|
209
|
+
* worse than a technical one.
|
|
210
|
+
*/
|
|
211
|
+
export function describeProviderFailure(
|
|
212
|
+
err: unknown,
|
|
213
|
+
status: number | undefined,
|
|
214
|
+
provider: string,
|
|
215
|
+
cleanModel: string,
|
|
216
|
+
): string {
|
|
217
|
+
if (status === 404 || status === 410) {
|
|
218
|
+
return `El modelo "${cleanModel}" ya no existe en ${provider} (HTTP ${status}). `
|
|
219
|
+
+ `El proveedor lo retiró de su catálogo; reintentar no sirve. `
|
|
220
|
+
+ `Elegí otro modelo en Ajustes → Proveedores.`
|
|
221
|
+
}
|
|
222
|
+
if (status === 429) {
|
|
223
|
+
return `${provider} está limitando las peticiones (HTTP 429) y los reintentos tampoco pasaron. `
|
|
224
|
+
+ `Es el límite de uso de tu cuenta, no un problema del modelo: esperá unos minutos, `
|
|
225
|
+
+ `revisá tu cuota con el proveedor, o cambiá de modelo en Ajustes → Proveedores.`
|
|
226
|
+
}
|
|
227
|
+
if (status === 401 || status === 403) {
|
|
228
|
+
return `${provider} rechazó la API key (HTTP ${status}). `
|
|
229
|
+
+ `Revisá que siga siendo válida y tenga acceso a "${cleanModel}" en Ajustes → Proveedores.`
|
|
230
|
+
}
|
|
231
|
+
return (err as Error).message
|
|
232
|
+
}
|
|
233
|
+
|
|
199
234
|
/** Provider SDKs disagree on where the HTTP status lands; check every shape we've seen. */
|
|
200
235
|
function extractErrorStatus(err: unknown): number | undefined {
|
|
201
236
|
const e = err as { status?: number; statusCode?: number; response?: { status?: number } }
|
|
@@ -1,5 +1,44 @@
|
|
|
1
1
|
import { OpenAICompatBase } from "./openai-compat-base"
|
|
2
|
+
import type { LLMCallOptions } from "../llm-client"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* NIM mantiene el razonamiento APAGADO por defecto en su endpoint compatible
|
|
6
|
+
* con OpenAI, y el interruptor no es el `reasoning_effort` de OpenAI sino
|
|
7
|
+
* `chat_template_kwargs`, con una clave distinta por familia de modelo.
|
|
8
|
+
*
|
|
9
|
+
* Verificado en vivo contra integrate.api.nvidia.com (2026-08-15):
|
|
10
|
+
* `z-ai/glm-5.2` no emite un solo `reasoning_content` sin esto — el delta trae
|
|
11
|
+
* únicamente `role` y `content` — y sí lo emite con `enable_thinking`. Por eso
|
|
12
|
+
* la app no mostraba razonamiento con los modelos de NVIDIA: no llegaba.
|
|
13
|
+
*
|
|
14
|
+
* Las familias que no están acá se dejan en paz a propósito. Nemotron 3 ya
|
|
15
|
+
* emite `reasoning_content` sin ningún kwarg (también verificado), y mandarle
|
|
16
|
+
* una clave que su plantilla no acepta es justamente lo que rompe la llamada.
|
|
17
|
+
*/
|
|
18
|
+
const THINKING_KWARGS: Array<{ pattern: RegExp; kwargs: Record<string, unknown> }> = [
|
|
19
|
+
// Verificado con z-ai/glm-5.2.
|
|
20
|
+
{ pattern: /glm/i, kwargs: { enable_thinking: true, clear_thinking: false } },
|
|
21
|
+
// Verificado con minimaxai/minimax-m3.
|
|
22
|
+
{ pattern: /minimax/i, kwargs: { thinking_mode: "enabled" } },
|
|
23
|
+
// Documentado por NVIDIA, sin verificar: moonshotai/kimi-k2.6 responde 404
|
|
24
|
+
// en la cuenta con la que se probó. Si la plantilla lo rechaza, el reintento
|
|
25
|
+
// de openai-compat-base repite la llamada sin kwargs.
|
|
26
|
+
{ pattern: /kimi|deepseek/i, kwargs: { thinking: true } },
|
|
27
|
+
{ pattern: /qwen|qwq/i, kwargs: { enable_thinking: true } },
|
|
28
|
+
]
|
|
2
29
|
|
|
3
30
|
export class NvidiaProvider extends OpenAICompatBase {
|
|
4
31
|
constructor() { super("nvidia") }
|
|
32
|
+
|
|
33
|
+
protected modifyRequestBody(body: any, options: LLMCallOptions): any {
|
|
34
|
+
if (!options.thinking?.enabled) return body
|
|
35
|
+
|
|
36
|
+
const match = THINKING_KWARGS.find(({ pattern }) => pattern.test(options.model))
|
|
37
|
+
if (!match) return body
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
...body,
|
|
41
|
+
chat_template_kwargs: { ...(body.chat_template_kwargs ?? {}), ...match.kwargs },
|
|
42
|
+
}
|
|
43
|
+
}
|
|
5
44
|
}
|
|
@@ -9,6 +9,32 @@ import type { ContentPart, LLMMessage } from "../llm-client"
|
|
|
9
9
|
|
|
10
10
|
const log = logger.child("llm-client")
|
|
11
11
|
|
|
12
|
+
/**
|
|
13
|
+
* Statuses that mean "this body is malformed or unsupported" — the only ones
|
|
14
|
+
* where dropping the provider extras can possibly help.
|
|
15
|
+
*
|
|
16
|
+
* Deliberately narrow. A first version retried on any status and immediately
|
|
17
|
+
* misfired in production against a 429: a rate limit is not a body problem, so
|
|
18
|
+
* the retry spent a second request against the very limit that rejected the
|
|
19
|
+
* first, and turned thinking off for nothing. Same for 401/403 (auth) and 404
|
|
20
|
+
* (unknown model).
|
|
21
|
+
*/
|
|
22
|
+
const EXTRAS_REJECTED_CODES = [400, 422]
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Drops the non-standard fields a provider added on top of an OpenAI-shaped
|
|
26
|
+
* body, for use on a retry after the body itself was rejected. Right now that
|
|
27
|
+
* is only NIM's `chat_template_kwargs` (nvidia.ts): it enables the model's
|
|
28
|
+
* thinking, so losing it costs the reasoning display and nothing else — a far
|
|
29
|
+
* better outcome than a turn that dies because one model's chat template did
|
|
30
|
+
* not recognize the switch.
|
|
31
|
+
*/
|
|
32
|
+
function stripProviderExtras(body: any): any {
|
|
33
|
+
if (!body?.chat_template_kwargs) return body
|
|
34
|
+
const { chat_template_kwargs: _dropped, ...rest } = body
|
|
35
|
+
return rest
|
|
36
|
+
}
|
|
37
|
+
|
|
12
38
|
/** Matches both generic "context length exceeded" phrasing and llama.cpp's exceed_context_size_error shape. */
|
|
13
39
|
function isContextOverflowError(err: any, errMsg: string): boolean {
|
|
14
40
|
const status = err?.status ?? err?.response?.status
|
|
@@ -183,7 +209,14 @@ export abstract class OpenAICompatBase implements LLMProvider {
|
|
|
183
209
|
delete bodyNoTools.tools
|
|
184
210
|
delete bodyNoTools.tool_choice
|
|
185
211
|
delete bodyNoTools.parallel_tool_calls
|
|
186
|
-
response = await client.chat.completions.create(this.modifyRequestBody(bodyNoTools, options), { signal: options.signal })
|
|
212
|
+
response = await client.chat.completions.create(stripProviderExtras(this.modifyRequestBody(bodyNoTools, options)), { signal: options.signal })
|
|
213
|
+
}
|
|
214
|
+
// Retry 3: the provider-specific extras are the only other thing we added
|
|
215
|
+
// to an otherwise standard body (NIM's chat_template_kwargs — see
|
|
216
|
+
// nvidia.ts). Losing the reasoning display beats failing the turn.
|
|
217
|
+
else if (EXTRAS_REJECTED_CODES.includes(status) && this.modifyRequestBody(body, options).chat_template_kwargs) {
|
|
218
|
+
log.warn(`[llm-client] ${this.providerName}: request rejected (HTTP ${status}) — retrying without chat_template_kwargs`)
|
|
219
|
+
response = await client.chat.completions.create(stripProviderExtras(this.modifyRequestBody(body, options)), { signal: options.signal })
|
|
187
220
|
}
|
|
188
221
|
else {
|
|
189
222
|
throw err
|
|
@@ -254,7 +287,10 @@ export abstract class OpenAICompatBase implements LLMProvider {
|
|
|
254
287
|
delete bodyNoTools.tools
|
|
255
288
|
delete bodyNoTools.tool_choice
|
|
256
289
|
delete bodyNoTools.parallel_tool_calls
|
|
257
|
-
stream = await client.chat.completions.create({ ...this.modifyRequestBody(bodyNoTools, options), stream: true }, { signal: options.signal })
|
|
290
|
+
stream = await client.chat.completions.create({ ...stripProviderExtras(this.modifyRequestBody(bodyNoTools, options)), stream: true }, { signal: options.signal })
|
|
291
|
+
} else if (EXTRAS_REJECTED_CODES.includes(status) && this.modifyRequestBody(body, options).chat_template_kwargs) {
|
|
292
|
+
log.warn(`[llm-client] ${this.providerName}: request rejected (HTTP ${status}) — retrying stream without chat_template_kwargs`)
|
|
293
|
+
stream = await client.chat.completions.create({ ...stripProviderExtras(this.modifyRequestBody(body, options)), stream: true }, { signal: options.signal })
|
|
258
294
|
} else {
|
|
259
295
|
throw err
|
|
260
296
|
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mcp-result-normalizer — keeps large/binary MCP tool results out of the LLM
|
|
3
|
+
* context window.
|
|
4
|
+
*
|
|
5
|
+
* `MCPClientManager.callTool()` (packages/mcp/src/manager.ts) returns the raw
|
|
6
|
+
* `content` array from the MCP SDK's CallToolResult. Per the MCP spec that
|
|
7
|
+
* array can contain `image`/`audio` blocks (base64 `data`) or `resource`
|
|
8
|
+
* blocks (base64 `blob`) alongside plain `text` blocks. Nothing downstream
|
|
9
|
+
* (agent-loop.ts's formatToolResult) inspects those blocks — a base64 image
|
|
10
|
+
* would be serialized whole into a `role:"tool"` message and sent to the
|
|
11
|
+
* model, which is exactly what filled the context window and hung the agent
|
|
12
|
+
* in the incident this module fixes.
|
|
13
|
+
*
|
|
14
|
+
* This mirrors the pattern already used by browser-screenshot.ts: binary
|
|
15
|
+
* content gets persisted via createArtifact() (artifacts/store.ts) and the
|
|
16
|
+
* model only ever sees a lightweight { type: "artifact_ref", ... } reference.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { createArtifact } from "../artifacts/store";
|
|
20
|
+
import { logger } from "../utils/logger";
|
|
21
|
+
|
|
22
|
+
const log = logger.child("mcp-result-normalizer");
|
|
23
|
+
|
|
24
|
+
/** Blocks longer than this (in chars) get materialized as a text artifact instead of inlined. Override via HIVE_MCP_INLINE_MAX_CHARS. */
|
|
25
|
+
const MCP_INLINE_MAX_CHARS = Number(process.env.HIVE_MCP_INLINE_MAX_CHARS) || 20_000;
|
|
26
|
+
|
|
27
|
+
export interface McpNormalizeContext {
|
|
28
|
+
userId?: string;
|
|
29
|
+
runId?: string | null;
|
|
30
|
+
taskId?: string | null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type McpContentBlock = Record<string, unknown> & { type?: unknown };
|
|
34
|
+
|
|
35
|
+
function isBinaryBlock(block: McpContentBlock): block is McpContentBlock & { type: "image" | "audio"; data: string; mimeType: string } {
|
|
36
|
+
return (block.type === "image" || block.type === "audio") && typeof block.data === "string";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isBlobResourceBlock(block: McpContentBlock): block is McpContentBlock & { type: "resource"; resource: { blob: string; mimeType?: string; uri?: string } } {
|
|
40
|
+
if (block.type !== "resource") return false;
|
|
41
|
+
const resource = block.resource as Record<string, unknown> | undefined;
|
|
42
|
+
return !!resource && typeof resource.blob === "string";
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function isOversizedTextBlock(block: McpContentBlock): block is McpContentBlock & { type: "text"; text: string } {
|
|
46
|
+
return block.type === "text" && typeof block.text === "string" && block.text.length > MCP_INLINE_MAX_CHARS;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function materializeBinary(
|
|
50
|
+
bytesBase64: string,
|
|
51
|
+
mimeType: string,
|
|
52
|
+
kind: string,
|
|
53
|
+
ctx: McpNormalizeContext,
|
|
54
|
+
): Promise<Record<string, unknown>> {
|
|
55
|
+
if (!ctx.userId) {
|
|
56
|
+
// Without a user_id we can't set ownership on the artifact (inspectArtifact
|
|
57
|
+
// would reject any read against it later) — never let raw base64 through,
|
|
58
|
+
// just describe what was omitted.
|
|
59
|
+
const approxBytes = Math.floor((bytesBase64.length * 3) / 4);
|
|
60
|
+
log.warn(`[materializeBinary] No user_id in tool context — omitting ${mimeType} block (${approxBytes} bytes) instead of creating an artifact`);
|
|
61
|
+
return { type: "artifact_omitted", mime_type: mimeType, approx_size: approxBytes, reason: "no user_id in tool context" };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const bytes = Buffer.from(bytesBase64, "base64");
|
|
65
|
+
const artifact = await createArtifact({
|
|
66
|
+
bytes,
|
|
67
|
+
mimeType,
|
|
68
|
+
kind,
|
|
69
|
+
userId: ctx.userId,
|
|
70
|
+
runId: ctx.runId ?? null,
|
|
71
|
+
taskId: ctx.taskId ?? null,
|
|
72
|
+
});
|
|
73
|
+
log.info(`[materializeBinary] Stored ${kind} as artifact ${artifact.id} (${artifact.size} bytes, ${artifact.mime_type})`);
|
|
74
|
+
return {
|
|
75
|
+
type: "artifact_ref",
|
|
76
|
+
artifact_id: artifact.id,
|
|
77
|
+
mime_type: artifact.mime_type,
|
|
78
|
+
size: artifact.size,
|
|
79
|
+
sha256: artifact.sha256,
|
|
80
|
+
expires_at: artifact.expires_at,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Above this, parsing the text just to describe it costs more than it explains. */
|
|
85
|
+
const MAX_SHAPE_PROBE_CHARS = 5_000_000;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Describes the shape of a JSON payload so the model can aim `artifact_read`
|
|
89
|
+
* instead of paging blind.
|
|
90
|
+
*
|
|
91
|
+
* The 500-char preview alone is close to useless on the payload this was
|
|
92
|
+
* written for — a Gmail MCP result where the first message's `received`
|
|
93
|
+
* headers eat the whole window before a single subject line appears. Knowing
|
|
94
|
+
* "12 items, keyed id/threadId/labelIds/headers" is what turns a search into
|
|
95
|
+
* one call.
|
|
96
|
+
*/
|
|
97
|
+
function describeJsonShape(text: string): Record<string, unknown> {
|
|
98
|
+
if (text.length > MAX_SHAPE_PROBE_CHARS) return {};
|
|
99
|
+
const trimmed = text.trimStart();
|
|
100
|
+
if (!trimmed.startsWith("[") && !trimmed.startsWith("{")) return {};
|
|
101
|
+
|
|
102
|
+
try {
|
|
103
|
+
const parsed = JSON.parse(text);
|
|
104
|
+
if (Array.isArray(parsed)) {
|
|
105
|
+
const first = parsed.find((item) => item && typeof item === "object" && !Array.isArray(item));
|
|
106
|
+
return {
|
|
107
|
+
json_items: parsed.length,
|
|
108
|
+
...(first ? { json_item_keys: Object.keys(first as Record<string, unknown>).slice(0, 25) } : {}),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
if (parsed && typeof parsed === "object") {
|
|
112
|
+
return { json_keys: Object.keys(parsed as Record<string, unknown>).slice(0, 25) };
|
|
113
|
+
}
|
|
114
|
+
} catch {
|
|
115
|
+
// Not JSON, or truncated JSON — the plain preview still stands.
|
|
116
|
+
}
|
|
117
|
+
return {};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function materializeText(text: string, ctx: McpNormalizeContext): Promise<Record<string, unknown>> {
|
|
121
|
+
if (!ctx.userId) {
|
|
122
|
+
log.warn(`[materializeText] No user_id in tool context — truncating oversized text block (${text.length} chars) instead of creating an artifact`);
|
|
123
|
+
return { type: "text", text: `${text.slice(0, 500)}… [truncated: ${text.length} chars total, no user_id to persist full text as artifact]` };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const artifact = await createArtifact({
|
|
127
|
+
bytes: Buffer.from(text, "utf-8"),
|
|
128
|
+
mimeType: "text/plain",
|
|
129
|
+
kind: "mcp_text_result",
|
|
130
|
+
userId: ctx.userId,
|
|
131
|
+
runId: ctx.runId ?? null,
|
|
132
|
+
taskId: ctx.taskId ?? null,
|
|
133
|
+
});
|
|
134
|
+
log.info(`[materializeText] Stored oversized text result as artifact ${artifact.id} (${artifact.size} bytes)`);
|
|
135
|
+
return {
|
|
136
|
+
type: "artifact_ref",
|
|
137
|
+
artifact_id: artifact.id,
|
|
138
|
+
mime_type: "text/plain",
|
|
139
|
+
size: artifact.size,
|
|
140
|
+
chars: text.length,
|
|
141
|
+
preview: text.length > 500 ? `${text.slice(0, 500)}…` : text,
|
|
142
|
+
...describeJsonShape(text),
|
|
143
|
+
// Without this the model only knows the data exists somewhere. It used to
|
|
144
|
+
// reach for artifact_inspect (metadata only), find nothing usable, and
|
|
145
|
+
// spend its remaining iterations guessing.
|
|
146
|
+
hint: "Full content is available via artifact_read (artifactId + offset/limit, or search).",
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Normalizes a raw MCP CallToolResult.content array: binary blocks (image,
|
|
152
|
+
* audio, resource-with-blob) become { type: "artifact_ref", ... }, oversized
|
|
153
|
+
* text blocks are persisted the same way with a short preview kept inline,
|
|
154
|
+
* everything else (text, resource_link) passes through unchanged.
|
|
155
|
+
*
|
|
156
|
+
* Never pre-stringifies — returns JS values so formatToolResult (toon.ts)
|
|
157
|
+
* keeps doing the actual TOON/JSON encoding, same contract context-compiler.ts
|
|
158
|
+
* already documents for MCP tool executors.
|
|
159
|
+
*/
|
|
160
|
+
export async function normalizeMcpResult(content: unknown, ctx: McpNormalizeContext): Promise<unknown> {
|
|
161
|
+
if (!Array.isArray(content)) return content;
|
|
162
|
+
|
|
163
|
+
const out: unknown[] = [];
|
|
164
|
+
for (const raw of content) {
|
|
165
|
+
if (!raw || typeof raw !== "object") {
|
|
166
|
+
out.push(raw);
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
const block = raw as McpContentBlock;
|
|
170
|
+
try {
|
|
171
|
+
if (isBinaryBlock(block)) {
|
|
172
|
+
out.push(await materializeBinary(block.data, block.mimeType, "mcp_result", ctx));
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
if (isBlobResourceBlock(block)) {
|
|
176
|
+
const mimeType = block.resource.mimeType || "application/octet-stream";
|
|
177
|
+
out.push(await materializeBinary(block.resource.blob, mimeType, "mcp_result", ctx));
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (isOversizedTextBlock(block)) {
|
|
181
|
+
out.push(await materializeText(block.text, ctx));
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
} catch (err) {
|
|
185
|
+
log.error(`[normalizeMcpResult] Failed to materialize block (type=${String(block.type)}): ${(err as Error).message}`);
|
|
186
|
+
out.push({ type: "artifact_error", mime_type: (block as { mimeType?: string }).mimeType, error: (err as Error).message });
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
out.push(block);
|
|
190
|
+
}
|
|
191
|
+
return out;
|
|
192
|
+
}
|
|
@@ -62,6 +62,8 @@ export interface ModelResponse {
|
|
|
62
62
|
totalTokens: number
|
|
63
63
|
}
|
|
64
64
|
finishReason?: string
|
|
65
|
+
/** Image artifacts (mcp-result-normalizer.ts, agent-loop.ts's turnImageArtifacts) produced by tools this turn. */
|
|
66
|
+
imageArtifacts?: Array<{ artifactId: string; mimeType: string }>
|
|
65
67
|
}
|
|
66
68
|
|
|
67
69
|
export class AgentRunner {
|
|
@@ -92,6 +94,7 @@ export class AgentRunner {
|
|
|
92
94
|
let toolCalls: ModelResponse["toolCalls"] = []
|
|
93
95
|
let totalInputTokens = 0
|
|
94
96
|
let totalOutputTokens = 0
|
|
97
|
+
let imageArtifacts: ModelResponse["imageArtifacts"]
|
|
95
98
|
|
|
96
99
|
try {
|
|
97
100
|
const stream = agentLoop.stream(
|
|
@@ -190,6 +193,10 @@ export class AgentRunner {
|
|
|
190
193
|
totalInputTokens += chunk.usage.input_tokens
|
|
191
194
|
totalOutputTokens += chunk.usage.output_tokens
|
|
192
195
|
}
|
|
196
|
+
|
|
197
|
+
if (chunk.artifacts?.images?.length) {
|
|
198
|
+
imageArtifacts = [...(imageArtifacts ?? []), ...chunk.artifacts.images]
|
|
199
|
+
}
|
|
193
200
|
}
|
|
194
201
|
|
|
195
202
|
logger.debug(`[STREAM] done. totalChunks=${chunkCount} lastAgentContent length=${lastAgentContent.length}, accumulated length=${accumulatedAgentContent.length}`)
|
|
@@ -208,6 +215,7 @@ export class AgentRunner {
|
|
|
208
215
|
totalTokens: totalInputTokens + totalOutputTokens,
|
|
209
216
|
},
|
|
210
217
|
finishReason: "stop",
|
|
218
|
+
imageArtifacts,
|
|
211
219
|
}
|
|
212
220
|
} catch (error) {
|
|
213
221
|
logger.error("AgentRunner error:", error)
|
|
@@ -201,6 +201,7 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
|
|
|
201
201
|
|
|
202
202
|
// Artifacts
|
|
203
203
|
{ name: "artifact_inspect", description: "Inspect a managed artifact's integrity and metadata without modifying it. Spanish keywords: inspeccionar artefacto, verificar archivo generado, metadatos artefacto, comprobar entrega", category: "web", abstractionLevel: "atomic" },
|
|
204
|
+
{ name: "artifact_read", description: "Read a managed artifact's text content in slices, or search inside it — the way to open any artifact_ref a tool returned. Spanish keywords: leer artefacto, ver contenido del artefacto, abrir resultado grande, buscar dentro del artefacto", category: "web", abstractionLevel: "atomic" },
|
|
204
205
|
|
|
205
206
|
// Office documents — read
|
|
206
207
|
{ name: "office_leer_pdf", description: "Read and extract text from a PDF document. Spanish keywords: leer pdf, extraer texto pdf, abrir pdf, contenido pdf", category: "office", abstractionLevel: "atomic" },
|