@johpaz/hive-agents 1.0.3 → 1.0.5
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 +49133 -48182
- package/dist/tool-worker.js +2 -1
- package/dist/ui/assets/A2UIPage-DTW79pyL.js +8 -0
- package/dist/ui/assets/AgentCreateForm-Bcp3HN8D.js +1 -0
- package/dist/ui/assets/AgentDetailPage-10XptMde.js +1 -0
- package/dist/ui/assets/AgentNewPage-CUt49rVS.js +1 -0
- package/dist/ui/assets/AgentsPage-1_e1a9xa.js +10 -0
- package/dist/ui/assets/ApiClientPage-DHfIlSAg.js +3 -0
- package/dist/ui/assets/ChannelsPage-BnCQAGZL.js +8 -0
- package/dist/ui/assets/DashboardPage-BsCCKHgg.js +6 -0
- package/dist/ui/assets/LoginPage-BaX6cAPa.js +1 -0
- package/dist/ui/assets/{LogsPage-DyJOGQNy.js → LogsPage-DiFBQt7o.js} +1 -1
- package/dist/ui/assets/MeetingPage-Bpv5zVXf.js +1 -0
- package/dist/ui/assets/ModelSelector-DfExlPzx.js +1 -0
- package/dist/ui/assets/{NotFound-Bpr12V51.js → NotFound-C8HBdF73.js} +1 -1
- package/dist/ui/assets/Office3DPage-ChsGMapf.js +319 -0
- package/dist/ui/assets/ProvidersPage-B39pfWHf.js +1 -0
- package/dist/ui/assets/RecoverPage-C_Id9WM-.js +1 -0
- package/dist/ui/assets/SettingsPage-BgFqasyg.js +9 -0
- package/dist/ui/assets/SetupPage-YeJFfgbt.js +1 -0
- package/dist/ui/assets/Vignette-Cyi27LQH.js +4302 -0
- package/dist/ui/assets/VoicePage-Cp63Abj4.js +307 -0
- package/dist/ui/assets/VoicePage-uLWdtoD4.css +1 -0
- package/dist/ui/assets/WebChatPage-DxFLWgtM.js +29 -0
- package/dist/ui/assets/activity-C_GS5wrG.js +1 -0
- package/dist/ui/assets/agentCapabilities-DOeepCty.js +1 -0
- package/dist/ui/assets/{alert-CQlRq6sv.js → alert-Cj4DpKv6.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-DKpeVCpY.js} +1 -1
- package/dist/ui/assets/bia-4LFKOyxR.webp +0 -0
- package/dist/ui/assets/bia-BFcUpOu3.glb +0 -0
- package/dist/ui/assets/calendar-B6x9cw-q.js +1 -0
- package/dist/ui/assets/{card-D3Nw3kh3.js → card-Cag15G4h.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-Dz04EE_8.js +1 -0
- package/dist/ui/assets/createLucideIcon-BRaPSYgN.js +1 -0
- package/dist/ui/assets/{dialog-Dn9hGPYl.js → dialog-7E3EoEt3.js} +1 -1
- package/dist/ui/assets/dist-js-Bg0g3vPS.js +1 -0
- package/dist/ui/assets/dist-js-DwLn9F4C.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-Bi8qEmrK.js +116 -0
- package/dist/ui/assets/index-D2UhaSb0.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-C6atPuIh.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/mic-Rq4BxU1R.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/rotate-ccw-Dx92orJM.js +1 -0
- package/dist/ui/assets/scroll-area-CSoG2z53.js +1 -0
- package/dist/ui/assets/search-DB4w9YHW.js +1 -0
- package/dist/ui/assets/{select-ot0a6art.js → select-DlCT21_r.js} +1 -1
- package/dist/ui/assets/send-xi8HzUdc.js +1 -0
- package/dist/ui/assets/settings-pV0cF8Kf.js +1 -0
- package/dist/ui/assets/shield-nLNsomh_.js +1 -0
- package/dist/ui/assets/slider-Bb_PHFJT.js +1 -0
- package/dist/ui/assets/sparkles-CerRDYxk.js +1 -0
- package/dist/ui/assets/square-CcWzRWyG.js +1 -0
- package/dist/ui/assets/{switch-DXcELPsM.js → switch-CUsGuBNi.js} +1 -1
- package/dist/ui/assets/tabs-Ckfc7DGG.js +1 -0
- package/dist/ui/assets/terminal-C2SUZUAD.js +1 -0
- package/dist/ui/assets/{textarea-rp6vsOZl.js → textarea-BH6pI9Ax.js} +1 -1
- package/dist/ui/assets/trash-2-BZsMCfso.js +1 -0
- package/dist/ui/assets/useAudioDevices-Dpr_hn6i.js +41 -0
- package/dist/ui/assets/useHiveAgentsModelLoad-CHmtvNp4.js +1 -0
- package/dist/ui/assets/useProviders-C7FA6z4M.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-2-CBMYsuF3.js +1 -0
- package/dist/ui/assets/volume-x-vNFf2e4-.js +1 -0
- package/dist/ui/assets/wifi-DNv53AfN.js +1 -0
- package/dist/ui/assets/zap-Yed86Sh8.js +1 -0
- package/dist/ui/index.html +8 -7
- package/package.json +1 -1
- package/packages/cli/src/commands/doctor.ts +99 -44
- package/packages/cli/src/commands/onboard.ts +4 -2
- package/packages/core/src/agent/agent-catalog.ts +23 -23
- package/packages/core/src/agent/agent-loop.ts +48 -0
- package/packages/core/src/agent/context-compiler.ts +1 -1
- package/packages/core/src/agent/conversation-store.ts +14 -1
- 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 +42 -0
- package/packages/core/src/agent/prompt-builder.ts +1 -1
- package/packages/core/src/agent/realtime-providers/gemini-live.ts +230 -0
- package/packages/core/src/agent/realtime-providers/index.ts +29 -0
- package/packages/core/src/agent/realtime-providers/interface.ts +108 -0
- package/packages/core/src/agent/skill-selector.ts +1 -1
- package/packages/core/src/agent/tool-selector.ts +2 -0
- package/packages/core/src/artifacts/store.ts +65 -0
- package/packages/core/src/canvas/canvas-manager.ts +128 -26
- package/packages/core/src/config/loader.ts +6 -4
- package/packages/core/src/events/tool-narration.ts +4 -0
- package/packages/core/src/gateway/delegation-groups.ts +4 -4
- package/packages/core/src/gateway/initializer.ts +17 -10
- package/packages/core/src/gateway/realtime/bridge-tools.ts +392 -0
- package/packages/core/src/gateway/realtime/index.ts +249 -0
- package/packages/core/src/gateway/realtime/prompt.ts +137 -0
- package/packages/core/src/gateway/realtime/protocol.ts +60 -0
- package/packages/core/src/gateway/realtime/voice-session.ts +441 -0
- package/packages/core/src/gateway/routes/providers.ts +1 -1
- package/packages/core/src/gateway/routes/setup.ts +3 -3
- package/packages/core/src/gateway/routes/system.ts +9 -4
- package/packages/core/src/gateway/server.ts +86 -1
- package/packages/core/src/gateway/slash-commands.ts +3 -1
- package/packages/core/src/gateway/webchat-turn.ts +34 -1
- package/packages/core/src/storage/collections.ts +10 -1
- package/packages/core/src/storage/onboarding.ts +39 -39
- package/packages/core/src/storage/seed.ts +21 -2
- 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 +4 -2
- package/packages/core/src/tools/web/artifact-read.ts +162 -0
- package/packages/core/src/tools/web/browser-backend.ts +141 -44
- package/packages/core/src/tools/web/browser-click.ts +2 -2
- package/packages/core/src/tools/web/browser-extract.ts +2 -2
- package/packages/core/src/tools/web/browser-navigate.ts +2 -2
- package/packages/core/src/tools/web/browser-screenshot.ts +12 -5
- package/packages/core/src/tools/web/browser-script.ts +2 -2
- package/packages/core/src/tools/web/browser-service.ts +63 -384
- package/packages/core/src/tools/web/browser-session.ts +125 -0
- package/packages/core/src/tools/web/browser-type.ts +2 -2
- package/packages/core/src/tools/web/browser-wait.ts +2 -2
- package/packages/core/src/tools/web/computer-use.ts +553 -0
- package/packages/core/src/tools/web/index.ts +8 -1
- package/packages/core/src/tools/web/webview-backend.ts +439 -21
- package/packages/skills/src/bundled-data.generated.ts +752 -752
- package/dist/ui/assets/A2UIPage-DExwevBV.js +0 -8
- package/dist/ui/assets/AgentCreateForm-7PPShsUn.js +0 -1
- package/dist/ui/assets/AgentDetailPage-CiV4tz4P.js +0 -1
- package/dist/ui/assets/AgentNewPage-D3TtVwQf.js +0 -1
- package/dist/ui/assets/AgentsPage-C2DThet7.js +0 -10
- package/dist/ui/assets/ApiClientPage-Cowdq-0f.js +0 -3
- package/dist/ui/assets/ChannelsPage-D4IgglwJ.js +0 -8
- package/dist/ui/assets/DashboardPage-DAgVB7Iy.js +0 -6
- package/dist/ui/assets/LoginPage-CpU61b3u.js +0 -1
- package/dist/ui/assets/MeetingPage-DLmqHmm2.js +0 -1
- package/dist/ui/assets/ModelSelector-D4OaICwN.js +0 -1
- package/dist/ui/assets/Office3DPage-BvO66B0h.js +0 -4614
- package/dist/ui/assets/ProvidersPage-Bhb6Qr87.js +0 -1
- package/dist/ui/assets/RecoverPage-DaZrCpdB.js +0 -1
- package/dist/ui/assets/SettingsPage-BRD2F7up.js +0 -9
- package/dist/ui/assets/SetupPage-DKppgTja.js +0 -1
- package/dist/ui/assets/WebChatPage-CPtETNL5.js +0 -29
- package/dist/ui/assets/activity-BSosMryb.js +0 -1
- package/dist/ui/assets/agentCapabilities-VqxLmrF6.js +0 -1
- package/dist/ui/assets/arrow-left-C9Y6p4Jt.js +0 -1
- package/dist/ui/assets/arrow-right-BYfOLnTB.js +0 -1
- package/dist/ui/assets/arrow-up-right-D2trA3Ob.js +0 -1
- package/dist/ui/assets/calendar-rdd4nvY1.js +0 -1
- package/dist/ui/assets/check-DUq9uoNQ.js +0 -1
- package/dist/ui/assets/chevron-down-rPF4Pr1n.js +0 -1
- package/dist/ui/assets/chevron-left-Crzzf2sY.js +0 -1
- package/dist/ui/assets/chevron-right-DtMIvG9A.js +0 -1
- package/dist/ui/assets/chevron-up-CG0_KGBy.js +0 -1
- package/dist/ui/assets/circle-alert-CYt6gsDA.js +0 -1
- package/dist/ui/assets/circle-check-Zl32-jCa.js +0 -1
- package/dist/ui/assets/circle-x-BJXzKGmx.js +0 -1
- package/dist/ui/assets/copy-BmtJXmDe.js +0 -1
- package/dist/ui/assets/download-D3mYhuuL.js +0 -1
- package/dist/ui/assets/earth-BZzdDXFC.js +0 -1
- package/dist/ui/assets/ellipsis-vertical-BF705XvB.js +0 -1
- package/dist/ui/assets/external-link-gdpMTHUV.js +0 -1
- package/dist/ui/assets/eye-lSG04hI7.js +0 -1
- package/dist/ui/assets/file-text-CjQxcJvN.js +0 -1
- package/dist/ui/assets/gauge-DBryKhDK.js +0 -1
- package/dist/ui/assets/history-BC6ir9qU.js +0 -1
- package/dist/ui/assets/index-DyxoAvTq.js +0 -116
- package/dist/ui/assets/index-wML8DaUo.css +0 -2
- package/dist/ui/assets/info-BGBaIyKc.js +0 -1
- package/dist/ui/assets/key-D_CNJTY2.js +0 -1
- package/dist/ui/assets/loader-circle-RXdrfPsH.js +0 -1
- package/dist/ui/assets/lock-open-UB61lorP.js +0 -1
- package/dist/ui/assets/mail-C5bJ_dBt.js +0 -1
- package/dist/ui/assets/pause-BSTJvxDu.js +0 -1
- package/dist/ui/assets/pencil-C2B1Q7y2.js +0 -1
- package/dist/ui/assets/play-tcMbj-0p.js +0 -1
- package/dist/ui/assets/plus-BSZvyMND.js +0 -1
- package/dist/ui/assets/progress-DrI2UDu-.js +0 -1
- package/dist/ui/assets/radio-D9CrjAar.js +0 -1
- package/dist/ui/assets/refresh-cw-D7EB_fVv.js +0 -1
- package/dist/ui/assets/scroll-area-CfHn94Vb.js +0 -1
- package/dist/ui/assets/search-5S6LY69I.js +0 -1
- package/dist/ui/assets/send-Dax1tJ5b.js +0 -1
- package/dist/ui/assets/settings-97CL32lC.js +0 -1
- package/dist/ui/assets/shield-DwbCEZbF.js +0 -1
- package/dist/ui/assets/slider-CmE_z1Ii.js +0 -1
- package/dist/ui/assets/sparkles-CWMAzkpD.js +0 -1
- package/dist/ui/assets/square-B4dgTXI3.js +0 -1
- package/dist/ui/assets/tabs-CxiybXcw.js +0 -1
- package/dist/ui/assets/terminal-DoLedTPM.js +0 -1
- package/dist/ui/assets/trash-2-DxnVYOz8.js +0 -1
- package/dist/ui/assets/triangle-alert-Cka-BeIE.js +0 -1
- package/dist/ui/assets/useHiveAgentsModelLoad-BjnIsQKR.js +0 -1
- package/dist/ui/assets/useProviders-CueMz_mL.js +0 -1
- package/dist/ui/assets/vendor-radix-D0s_k6Gp.js +0 -63
- package/dist/ui/assets/volume-x-DLsli9cf.js +0 -1
- package/dist/ui/assets/wifi-BQRJGfLZ.js +0 -1
- package/dist/ui/assets/zap-DSR3CEce.js +0 -1
- /package/dist/ui/assets/{gateway-url-BlnabM5e.js → gateway-url-BzQV75Ig.js} +0 -0
- /package/dist/ui/assets/{useOfficeModel-Cy7cAyEn.js → useOfficeModel-Cc5VkReZ.js} +0 -0
- /package/dist/ui/assets/{utils-Dyb7SC2_.js → utils-lc8H6VGT.js} +0 -0
- /package/dist/ui/assets/{vendor-router-zpB-76nT.js → vendor-router-DCsSv_I7.js} +0 -0
|
@@ -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
|
}
|
|
@@ -81,6 +81,42 @@ async function materializeBinary(
|
|
|
81
81
|
};
|
|
82
82
|
}
|
|
83
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
|
+
|
|
84
120
|
async function materializeText(text: string, ctx: McpNormalizeContext): Promise<Record<string, unknown>> {
|
|
85
121
|
if (!ctx.userId) {
|
|
86
122
|
log.warn(`[materializeText] No user_id in tool context — truncating oversized text block (${text.length} chars) instead of creating an artifact`);
|
|
@@ -101,7 +137,13 @@ async function materializeText(text: string, ctx: McpNormalizeContext): Promise<
|
|
|
101
137
|
artifact_id: artifact.id,
|
|
102
138
|
mime_type: "text/plain",
|
|
103
139
|
size: artifact.size,
|
|
140
|
+
chars: text.length,
|
|
104
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).",
|
|
105
147
|
};
|
|
106
148
|
}
|
|
107
149
|
|
|
@@ -136,7 +136,7 @@ export async function buildSystemPrompt(opts: BuildSystemPromptOpts): Promise<st
|
|
|
136
136
|
if (Object.keys(userData).length > 0) {
|
|
137
137
|
userSection += formatContext(userData) + "\n\n"
|
|
138
138
|
if (agent.role === "coordinator" && user.email) {
|
|
139
|
-
userSection += `Cuando el usuario diga "envíame", "mándame" o "a mi correo" sin indicar otro destinatario,
|
|
139
|
+
userSection += `Cuando el usuario diga "envíame", "mándame" o "a mi correo" sin indicar otro destinatario, usa CorreoPropio. Para terceras personas, resuelve su dirección por separado.\n\n`
|
|
140
140
|
}
|
|
141
141
|
} else {
|
|
142
142
|
userSection += `Usuario ID: ${userId}\n\n`
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adaptador de la Live API de Gemini (`bidiGenerateContent`).
|
|
3
|
+
*
|
|
4
|
+
* Sobre `ai.live.connect()` de @google/genai. El import es dinámico igual que en
|
|
5
|
+
* ../llm-providers/gemini.ts: el SDK arrastra dependencias de Vertex que no hacen
|
|
6
|
+
* falta con API key, y cargarlo perezosamente evita pagarlas en el arranque.
|
|
7
|
+
*
|
|
8
|
+
* Verificado contra gemini-3.1-flash-live-preview (2026-08): la inyección de
|
|
9
|
+
* texto va por `sendRealtimeInput({text})`; `sendClientContent` quedó restringido
|
|
10
|
+
* al contexto inicial en 3.x, así que no se usa acá.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { logger } from "../../utils/logger";
|
|
14
|
+
import { ensureArrayItems } from "../llm-providers/interface";
|
|
15
|
+
import type {
|
|
16
|
+
RealtimeProvider,
|
|
17
|
+
RealtimeSession,
|
|
18
|
+
RealtimeSessionOptions,
|
|
19
|
+
RealtimeToolCall,
|
|
20
|
+
} from "./interface";
|
|
21
|
+
|
|
22
|
+
const log = logger.child("realtime:gemini");
|
|
23
|
+
|
|
24
|
+
/** Modelos con `bidiGenerateContent`. El id vive en la BD; esto es sólo el fallback. */
|
|
25
|
+
export const DEFAULT_GEMINI_LIVE_MODEL = "gemini-3.1-flash-live-preview";
|
|
26
|
+
|
|
27
|
+
class GeminiLiveSession implements RealtimeSession {
|
|
28
|
+
closed = false;
|
|
29
|
+
|
|
30
|
+
constructor(
|
|
31
|
+
readonly model: string,
|
|
32
|
+
private readonly session: any,
|
|
33
|
+
private readonly callbacks: RealtimeSessionOptions["callbacks"],
|
|
34
|
+
) {}
|
|
35
|
+
|
|
36
|
+
sendAudio(pcm: ArrayBufferLike): void {
|
|
37
|
+
if (this.closed) return;
|
|
38
|
+
try {
|
|
39
|
+
this.session.sendRealtimeInput({
|
|
40
|
+
audio: {
|
|
41
|
+
data: Buffer.from(pcm as ArrayBuffer).toString("base64"),
|
|
42
|
+
mimeType: "audio/pcm;rate=16000",
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
} catch (error) {
|
|
46
|
+
this.fail(error, "sendAudio");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
sendVideoFrame(base64: string, mimeType: string): void {
|
|
51
|
+
if (this.closed) return;
|
|
52
|
+
try {
|
|
53
|
+
this.session.sendRealtimeInput({ video: { data: base64, mimeType } });
|
|
54
|
+
} catch (error) {
|
|
55
|
+
this.fail(error, "sendVideoFrame");
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
sendText(text: string): void {
|
|
60
|
+
if (this.closed || !text.trim()) return;
|
|
61
|
+
try {
|
|
62
|
+
this.session.sendRealtimeInput({ text });
|
|
63
|
+
} catch (error) {
|
|
64
|
+
this.fail(error, "sendText");
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
sendToolResult(id: string, name: string, result: Record<string, unknown>): void {
|
|
69
|
+
if (this.closed) return;
|
|
70
|
+
try {
|
|
71
|
+
this.session.sendToolResponse({ functionResponses: [{ id, name, response: result }] });
|
|
72
|
+
} catch (error) {
|
|
73
|
+
this.fail(error, "sendToolResult");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
close(): void {
|
|
78
|
+
if (this.closed) return;
|
|
79
|
+
this.closed = true;
|
|
80
|
+
try {
|
|
81
|
+
this.session.close();
|
|
82
|
+
} catch {
|
|
83
|
+
/* el socket ya estaba cerrado */
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Marca la sesión como muerta: seguir escribiendo en un socket roto sólo genera ruido. */
|
|
88
|
+
private fail(error: unknown, op: string): void {
|
|
89
|
+
this.closed = true;
|
|
90
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
91
|
+
log.warn(`${op} falló: ${err.message}`);
|
|
92
|
+
this.callbacks.onError?.(err);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export class GeminiLiveProvider implements RealtimeProvider {
|
|
97
|
+
readonly id = "gemini";
|
|
98
|
+
|
|
99
|
+
async connect(options: RealtimeSessionOptions): Promise<RealtimeSession> {
|
|
100
|
+
const { GoogleGenAI } = await import("@google/genai");
|
|
101
|
+
const ai = new GoogleGenAI({ apiKey: options.apiKey });
|
|
102
|
+
const cb = options.callbacks;
|
|
103
|
+
|
|
104
|
+
const config: Record<string, unknown> = {
|
|
105
|
+
responseModalities: ["AUDIO"],
|
|
106
|
+
systemInstruction: options.systemInstruction,
|
|
107
|
+
// Necesarias para persistir el hilo y pintarlo en el chat: sin esto sólo
|
|
108
|
+
// llegan bytes de audio y la conversación hablada no deja rastro escrito.
|
|
109
|
+
inputAudioTranscription: {},
|
|
110
|
+
outputAudioTranscription: {},
|
|
111
|
+
// Sin compresión la sesión muere a los 15 min de audio.
|
|
112
|
+
contextWindowCompression: { slidingWindow: {} },
|
|
113
|
+
// Handle para reanudar tras un goAway sin perder el hilo.
|
|
114
|
+
sessionResumption: options.resumptionHandle ? { handle: options.resumptionHandle } : {},
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
if (options.voice || options.language) {
|
|
118
|
+
const speechConfig: Record<string, unknown> = {};
|
|
119
|
+
if (options.voice) {
|
|
120
|
+
speechConfig.voiceConfig = { prebuiltVoiceConfig: { voiceName: options.voice } };
|
|
121
|
+
}
|
|
122
|
+
if (options.language) speechConfig.languageCode = options.language;
|
|
123
|
+
config.speechConfig = speechConfig;
|
|
124
|
+
}
|
|
125
|
+
if (options.silenceDurationMs || options.startOfSpeechSensitivity) {
|
|
126
|
+
const deteccion: Record<string, unknown> = {};
|
|
127
|
+
if (options.silenceDurationMs) deteccion.silenceDurationMs = options.silenceDurationMs;
|
|
128
|
+
if (options.startOfSpeechSensitivity) {
|
|
129
|
+
deteccion.startOfSpeechSensitivity = options.startOfSpeechSensitivity;
|
|
130
|
+
}
|
|
131
|
+
config.realtimeInputConfig = { automaticActivityDetection: deteccion };
|
|
132
|
+
}
|
|
133
|
+
if (options.tools?.length) {
|
|
134
|
+
config.tools = [
|
|
135
|
+
{
|
|
136
|
+
functionDeclarations: options.tools.map((t) => ({
|
|
137
|
+
name: t.function.name,
|
|
138
|
+
description: t.function.description,
|
|
139
|
+
parameters: ensureArrayItems(t.function.parameters),
|
|
140
|
+
})),
|
|
141
|
+
},
|
|
142
|
+
];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
let wrapper: GeminiLiveSession | null = null;
|
|
146
|
+
|
|
147
|
+
const session = await ai.live.connect({
|
|
148
|
+
model: options.model,
|
|
149
|
+
config: config as any,
|
|
150
|
+
callbacks: {
|
|
151
|
+
onopen: () => log.info(`sesión abierta (${options.model})`),
|
|
152
|
+
onmessage: (msg: any) => {
|
|
153
|
+
try {
|
|
154
|
+
handleMessage(msg, cb);
|
|
155
|
+
} catch (error) {
|
|
156
|
+
cb.onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
onerror: (e: any) => {
|
|
160
|
+
cb.onError?.(new Error(e?.message ?? String(e)));
|
|
161
|
+
},
|
|
162
|
+
onclose: (e: any) => {
|
|
163
|
+
if (wrapper) wrapper.closed = true;
|
|
164
|
+
cb.onClose?.(e?.reason || "");
|
|
165
|
+
},
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
wrapper = new GeminiLiveSession(options.model, session, cb);
|
|
170
|
+
return wrapper;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function handleMessage(msg: any, cb: RealtimeSessionOptions["callbacks"]): void {
|
|
175
|
+
const content = msg.serverContent;
|
|
176
|
+
if (content) {
|
|
177
|
+
for (const part of content.modelTurn?.parts ?? []) {
|
|
178
|
+
const data = part.inlineData?.data;
|
|
179
|
+
if (data) cb.onAudio?.(Buffer.from(data, "base64"));
|
|
180
|
+
}
|
|
181
|
+
if (content.inputTranscription?.text) cb.onInputTranscript?.(content.inputTranscription.text);
|
|
182
|
+
if (content.outputTranscription?.text) cb.onOutputTranscript?.(content.outputTranscription.text);
|
|
183
|
+
if (content.interrupted) cb.onInterrupted?.();
|
|
184
|
+
if (content.turnComplete) cb.onTurnComplete?.();
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (msg.toolCall?.functionCalls?.length) {
|
|
188
|
+
const calls: RealtimeToolCall[] = msg.toolCall.functionCalls.map((fc: any) => ({
|
|
189
|
+
id: fc.id ?? "",
|
|
190
|
+
name: fc.name ?? "",
|
|
191
|
+
args: (fc.args ?? {}) as Record<string, unknown>,
|
|
192
|
+
}));
|
|
193
|
+
cb.onToolCall?.(calls);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (msg.toolCallCancellation?.ids?.length) {
|
|
197
|
+
cb.onToolCallCancellation?.(msg.toolCallCancellation.ids);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (msg.usageMetadata) {
|
|
201
|
+
const u = msg.usageMetadata;
|
|
202
|
+
cb.onUsage?.({
|
|
203
|
+
inputTokens: Number(u.promptTokenCount ?? 0),
|
|
204
|
+
outputTokens: Number(u.responseTokenCount ?? 0),
|
|
205
|
+
totalTokens: Number(u.totalTokenCount ?? 0),
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (msg.sessionResumptionUpdate?.newHandle) {
|
|
210
|
+
cb.onResumptionHandle?.(msg.sessionResumptionUpdate.newHandle);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (msg.goAway) {
|
|
214
|
+
cb.onGoAway?.(parseDuration(msg.goAway.timeLeft));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** `timeLeft` llega como duración protobuf ("9.5s") o como objeto {seconds,nanos}. */
|
|
219
|
+
function parseDuration(value: unknown): number {
|
|
220
|
+
if (typeof value === "string") {
|
|
221
|
+
const seconds = parseFloat(value.replace(/s$/, ""));
|
|
222
|
+
return Number.isFinite(seconds) ? Math.round(seconds * 1000) : 0;
|
|
223
|
+
}
|
|
224
|
+
if (value && typeof value === "object") {
|
|
225
|
+
const v = value as { seconds?: number | string; nanos?: number };
|
|
226
|
+
const seconds = Number(v.seconds ?? 0);
|
|
227
|
+
return Math.round(seconds * 1000 + (v.nanos ?? 0) / 1e6);
|
|
228
|
+
}
|
|
229
|
+
return 0;
|
|
230
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Registro de proveedores de voz en tiempo real.
|
|
3
|
+
*
|
|
4
|
+
* Hoy sólo Gemini Live. La interfaz existe desacoplada para que añadir OpenAI
|
|
5
|
+
* Realtime o Nova Sonic no obligue a tocar el gateway ni el cliente: cambia el
|
|
6
|
+
* adaptador, no el transporte.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { GeminiLiveProvider } from "./gemini-live";
|
|
10
|
+
import type { RealtimeProvider } from "./interface";
|
|
11
|
+
|
|
12
|
+
export * from "./interface";
|
|
13
|
+
export { DEFAULT_GEMINI_LIVE_MODEL } from "./gemini-live";
|
|
14
|
+
|
|
15
|
+
const providers = new Map<string, RealtimeProvider>([["gemini", new GeminiLiveProvider()]]);
|
|
16
|
+
|
|
17
|
+
export function getRealtimeProvider(providerId: string): RealtimeProvider {
|
|
18
|
+
const provider = providers.get(providerId);
|
|
19
|
+
if (!provider) {
|
|
20
|
+
throw new Error(
|
|
21
|
+
`El proveedor "${providerId}" no soporta voz en tiempo real. Disponibles: ${[...providers.keys()].join(", ")}`,
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
return provider;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function isRealtimeProvider(providerId: string): boolean {
|
|
28
|
+
return providers.has(providerId);
|
|
29
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* realtime-providers — sesiones de voz full-duplex (speech-to-speech).
|
|
3
|
+
*
|
|
4
|
+
* `LLMProvider` (../llm-providers/interface.ts) es one-shot: `call()` recibe un
|
|
5
|
+
* historial y devuelve una respuesta. Una sesión Live no encaja ahí — es un
|
|
6
|
+
* socket que vive minutos, recibe audio continuo y emite audio continuo. De ahí
|
|
7
|
+
* esta interfaz hermana en vez de una subclase.
|
|
8
|
+
*
|
|
9
|
+
* El modelo realtime NO es el cerebro de Hive: sólo oye, habla e interrumpe. El
|
|
10
|
+
* trabajo real lo hace el agent-loop de siempre (Bee → especialistas → tools).
|
|
11
|
+
* Por eso las herramientas que se declaran acá son un puñado fijo de funciones
|
|
12
|
+
* puente (gateway/realtime/bridge-tools.ts) y no el catálogo del agente: la Live
|
|
13
|
+
* API congela las tools en el `setup` y no admite cambiarlas a mitad de sesión.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { LLMToolDef } from "../llm-client";
|
|
17
|
+
|
|
18
|
+
/** Lo que el micrófono debe entregar: PCM16 mono little-endian. */
|
|
19
|
+
export const REALTIME_INPUT_SAMPLE_RATE = 16_000;
|
|
20
|
+
/** Lo que el modelo devuelve: PCM16 mono. */
|
|
21
|
+
export const REALTIME_OUTPUT_SAMPLE_RATE = 24_000;
|
|
22
|
+
|
|
23
|
+
export interface RealtimeToolCall {
|
|
24
|
+
id: string;
|
|
25
|
+
name: string;
|
|
26
|
+
args: Record<string, unknown>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface RealtimeCallbacks {
|
|
30
|
+
/** Audio del modelo, PCM16 mono a REALTIME_OUTPUT_SAMPLE_RATE. */
|
|
31
|
+
onAudio?: (pcm: Buffer) => void;
|
|
32
|
+
/** Transcripción de lo que dijo el usuario (fragmentos incrementales). */
|
|
33
|
+
onInputTranscript?: (text: string) => void;
|
|
34
|
+
/** Transcripción de lo que dijo el modelo (fragmentos incrementales). */
|
|
35
|
+
onOutputTranscript?: (text: string) => void;
|
|
36
|
+
onToolCall?: (calls: RealtimeToolCall[]) => void;
|
|
37
|
+
/** El modelo canceló tool calls ya emitidas (el usuario cambió de tema). */
|
|
38
|
+
onToolCallCancellation?: (ids: string[]) => void;
|
|
39
|
+
/** Barge-in: el usuario habló encima. Hay que vaciar la cola de reproducción YA. */
|
|
40
|
+
onInterrupted?: () => void;
|
|
41
|
+
onTurnComplete?: () => void;
|
|
42
|
+
/** Consumo acumulado que reporta el proveedor. */
|
|
43
|
+
onUsage?: (usage: { inputTokens: number; outputTokens: number; totalTokens: number }) => void;
|
|
44
|
+
/** Handle para reanudar la sesión tras un corte (válido ~2 h). */
|
|
45
|
+
onResumptionHandle?: (handle: string) => void;
|
|
46
|
+
/** El servidor va a cerrar la conexión; hay que reconectar con el handle. */
|
|
47
|
+
onGoAway?: (timeLeftMs: number) => void;
|
|
48
|
+
onError?: (error: Error) => void;
|
|
49
|
+
onClose?: (reason: string) => void;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface RealtimeSessionOptions {
|
|
53
|
+
model: string;
|
|
54
|
+
apiKey: string;
|
|
55
|
+
/** Prompt de la sesión de voz (no es el system prompt del agent-loop). */
|
|
56
|
+
systemInstruction: string;
|
|
57
|
+
/** Funciones puente. Congeladas: la Live API no permite cambiarlas después. */
|
|
58
|
+
tools?: LLMToolDef[];
|
|
59
|
+
/** Voz del proveedor (ej. "Kore"). Ver voiceService.getGeminiVoices(). */
|
|
60
|
+
voice?: string;
|
|
61
|
+
/**
|
|
62
|
+
* Idioma con acento regional, en BCP-47 (es-CO, es-MX, en-US…).
|
|
63
|
+
*
|
|
64
|
+
* Los modelos de audio nativo cambian de idioma solos siguiendo al usuario,
|
|
65
|
+
* pero sin esto eligen el acento por su cuenta: un usuario colombiano puede
|
|
66
|
+
* terminar escuchando español rioplatense.
|
|
67
|
+
*/
|
|
68
|
+
language?: string;
|
|
69
|
+
/** Silencio en ms que cierra el turno del usuario (VAD automático). */
|
|
70
|
+
silenceDurationMs?: number;
|
|
71
|
+
/**
|
|
72
|
+
* Cuánto cuesta que el modelo dé por empezada una intervención del usuario.
|
|
73
|
+
* `START_SENSITIVITY_LOW` sube el listón: hace falta voz clara para
|
|
74
|
+
* interrumpirle, en vez de cualquier ruido. Es lo que salva las manos libres,
|
|
75
|
+
* donde lo que entra por el micrófono incluye su propia voz rebotando.
|
|
76
|
+
*/
|
|
77
|
+
startOfSpeechSensitivity?: "START_SENSITIVITY_LOW" | "START_SENSITIVITY_HIGH";
|
|
78
|
+
/** Handle devuelto por una sesión anterior, para retomar el hilo. */
|
|
79
|
+
resumptionHandle?: string;
|
|
80
|
+
callbacks: RealtimeCallbacks;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface RealtimeSession {
|
|
84
|
+
readonly model: string;
|
|
85
|
+
/** PCM16 mono a REALTIME_INPUT_SAMPLE_RATE. */
|
|
86
|
+
sendAudio(pcm: ArrayBufferLike): void;
|
|
87
|
+
/**
|
|
88
|
+
* Un fotograma de la cámara, ya codificado (JPEG en base64).
|
|
89
|
+
*
|
|
90
|
+
* Va a baja cadencia a propósito: con vídeo, la Live API recorta la sesión de
|
|
91
|
+
* 15 minutos a unos 2 y cada imagen cuesta cientos de tokens frente a los 25
|
|
92
|
+
* por segundo del audio.
|
|
93
|
+
*/
|
|
94
|
+
sendVideoFrame(base64: string, mimeType: string): void;
|
|
95
|
+
/** Inyecta texto en la conversación (narración de la colmena, avisos). */
|
|
96
|
+
sendText(text: string): void;
|
|
97
|
+
sendToolResult(id: string, name: string, result: Record<string, unknown>): void;
|
|
98
|
+
close(): void;
|
|
99
|
+
readonly closed: boolean;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface RealtimeProvider {
|
|
103
|
+
readonly id: string;
|
|
104
|
+
connect(options: RealtimeSessionOptions): Promise<RealtimeSession>;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Toolset fijo de una sesión de voz, en el formato canónico de Hive. */
|
|
108
|
+
export type RealtimeToolset = LLMToolDef[];
|
|
@@ -109,7 +109,7 @@ const STOPWORDS = new Set([
|
|
|
109
109
|
"más", "mas", "ya", "yo", "tu", "te", "ti", "mi", "me",
|
|
110
110
|
"hola", "hi", "hello", "hey", "gracias", "thank", "please",
|
|
111
111
|
"ok", "okay", "yes", "si", "no", "bien", "good", "great",
|
|
112
|
-
"puedes", "necesito", "quiero", "
|
|
112
|
+
"puedes", "necesito", "quiero", "puedes", "necesitás", "quieres",
|
|
113
113
|
])
|
|
114
114
|
|
|
115
115
|
/** Conversational patterns that should return empty skill list */
|
|
@@ -161,6 +161,7 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
|
|
|
161
161
|
// Browser automation
|
|
162
162
|
{ name: "browser_navigate", description: "Navigate to URL and get content, open web pages and extract information. Spanish keywords: navegar web, abrir página, ir a sitio, navegar, ir a página", category: "browser", abstractionLevel: "atomic" },
|
|
163
163
|
{ name: "browser_screenshot", description: "Take webpage screenshot, capture visual snapshot of web page. Spanish keywords: captura de pantalla, screenshot, fotografiar página, imagen de página", category: "browser", abstractionLevel: "atomic" },
|
|
164
|
+
{ name: "computer_use_task", description: "Operate the browser by looking at the screen: click by coordinates, type and navigate when no stable CSS selector exists (canvas, generated UIs, embedded viewers). Acts on Hive's own browser, never on the user screen. Spanish keywords: usar el navegador, hacer clic donde veas, operar una página, rellenar formulario, computer use, mirar la pantalla", category: "browser", abstractionLevel: "orchestration" },
|
|
164
165
|
{ name: "browser_click", description: "Click element on page, interact with buttons and links in browser. Spanish keywords: hacer clic, presionar botón, clickear, pulsar, botón", category: "browser", abstractionLevel: "atomic" },
|
|
165
166
|
{ name: "browser_type", description: "Type into input field, fill forms and text inputs in browser. Spanish keywords: escribir en página, llenar formulario, introducir texto, completar formulario", category: "browser", abstractionLevel: "atomic" },
|
|
166
167
|
{ name: "browser_extract", description: "Extract text, links, or structured data from page using CSS selectors or XPath. Spanish keywords: extraer datos, obtener información, scraping, selectores, xpath", category: "browser", abstractionLevel: "atomic" },
|
|
@@ -201,6 +202,7 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
|
|
|
201
202
|
|
|
202
203
|
// Artifacts
|
|
203
204
|
{ 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" },
|
|
205
|
+
{ 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
206
|
|
|
205
207
|
// Office documents — read
|
|
206
208
|
{ 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" },
|
|
@@ -107,6 +107,71 @@ export async function readArtifactBytes(
|
|
|
107
107
|
return { bytes: readFileSync(entry.doc.path), mimeType: entry.doc.mime_type };
|
|
108
108
|
}
|
|
109
109
|
|
|
110
|
+
/** Beyond this an artifact stops being something an agent can read into a context window. */
|
|
111
|
+
const MAX_TEXT_ARTIFACT_BYTES = 25 * 1024 * 1024;
|
|
112
|
+
|
|
113
|
+
function looksBinary(mimeType: string, bytes: Buffer): boolean {
|
|
114
|
+
if (/^(image|audio|video)\//.test(mimeType)) return true;
|
|
115
|
+
if (mimeType === "application/octet-stream") return true;
|
|
116
|
+
// A NUL byte in the first KB is the classic "this is not text" tell — a
|
|
117
|
+
// mislabelled text/plain artifact would otherwise decode to garbage.
|
|
118
|
+
return bytes.subarray(0, 1024).includes(0x00);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export type ArtifactTextResult = {
|
|
122
|
+
ok: boolean;
|
|
123
|
+
text?: string;
|
|
124
|
+
artifact?: ArtifactDoc;
|
|
125
|
+
error?: string;
|
|
126
|
+
status?: string;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Decodes a text artifact for in-process consumers that need its *content*,
|
|
131
|
+
* not just its metadata (inspectArtifact) or its raw bytes (readArtifactBytes).
|
|
132
|
+
*
|
|
133
|
+
* This exists because mcp-result-normalizer.ts moves oversized MCP text results
|
|
134
|
+
* out of the context window and hands the model an `artifact_ref` instead. Until
|
|
135
|
+
* this, nothing could read that reference back: the agent held a receipt it
|
|
136
|
+
* could not cash, burned its iterations guessing, and the turn died on an empty
|
|
137
|
+
* synthesis. Ownership and status checks mirror inspectArtifact's.
|
|
138
|
+
*/
|
|
139
|
+
export async function readArtifactText(
|
|
140
|
+
artifactId: string,
|
|
141
|
+
options: { userId?: string } = {},
|
|
142
|
+
): Promise<ArtifactTextResult> {
|
|
143
|
+
const artifacts = await col<ArtifactDoc>("artifacts");
|
|
144
|
+
const entry = await artifacts.get(artifactId);
|
|
145
|
+
if (!entry) return { ok: false, error: "Artifact not found" };
|
|
146
|
+
const artifact = entry.doc;
|
|
147
|
+
|
|
148
|
+
if (options.userId && artifact.user_id && artifact.user_id !== options.userId) {
|
|
149
|
+
return { ok: false, error: "Artifact not accessible" };
|
|
150
|
+
}
|
|
151
|
+
if (artifact.status !== "active") {
|
|
152
|
+
return { ok: false, error: "Artifact binary has expired", status: artifact.status };
|
|
153
|
+
}
|
|
154
|
+
if (!existsSync(artifact.path)) {
|
|
155
|
+
return { ok: false, error: "Artifact binary is missing", status: "missing" };
|
|
156
|
+
}
|
|
157
|
+
if (artifact.size > MAX_TEXT_ARTIFACT_BYTES) {
|
|
158
|
+
return {
|
|
159
|
+
ok: false,
|
|
160
|
+
error: `Artifact is too large to read as text (${artifact.size} bytes, limit ${MAX_TEXT_ARTIFACT_BYTES})`,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const bytes = readFileSync(artifact.path);
|
|
165
|
+
if (looksBinary(detectedMime(bytes, artifact.mime_type), bytes)) {
|
|
166
|
+
return {
|
|
167
|
+
ok: false,
|
|
168
|
+
error: `Artifact is binary (${detectedMime(bytes, artifact.mime_type)}) — use artifact_inspect for its metadata`,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return { ok: true, text: bytes.toString("utf-8"), artifact };
|
|
173
|
+
}
|
|
174
|
+
|
|
110
175
|
export async function inspectArtifact(
|
|
111
176
|
artifactId: string,
|
|
112
177
|
options: { userId?: string } = {},
|