@johpaz/hive-agents 1.0.0 → 1.0.1
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 +25 -11
- package/dist/hive.js +22245 -6788
- package/dist/tool-worker.js +6 -2
- package/dist/ui/assets/{A2UIPage-D4nUFe5q.js → A2UIPage-D4nzp5NV.js} +1 -1
- package/dist/ui/assets/{AgentCreateForm-g1mQnIoJ.js → AgentCreateForm-M2RhjeA1.js} +1 -1
- package/dist/ui/assets/{AgentDetailPage-C3XkU4Ll.js → AgentDetailPage-DkFRtj8g.js} +1 -1
- package/dist/ui/assets/AgentNewPage-CfBU7puz.js +1 -0
- package/dist/ui/assets/{AgentsPage-CNA778Eo.js → AgentsPage-Ctzq2LWx.js} +1 -1
- package/dist/ui/assets/{ApiClientPage-t5DpKhmA.js → ApiClientPage-DKbGO1QW.js} +1 -1
- package/dist/ui/assets/{ChannelsPage-yY6t0YTU.js → ChannelsPage-H6rgr8DQ.js} +2 -2
- package/dist/ui/assets/{DashboardPage-BSeNSYg5.js → DashboardPage-BIjYGf4m.js} +2 -2
- package/dist/ui/assets/{LoginPage-eT5zDRDa.js → LoginPage-DazoxtBJ.js} +1 -1
- package/dist/ui/assets/{LogsPage-Gczzzsdh.js → LogsPage-DMZ6KtQ3.js} +1 -1
- package/dist/ui/assets/{MeetingPage-Bu4aMMNR.js → MeetingPage-CSLFvHL7.js} +1 -1
- package/dist/ui/assets/{ModelSelector-nNOrW3te.js → ModelSelector-BCfvugHB.js} +1 -1
- package/dist/ui/assets/{Office3DPage-B_iXEbyv.js → Office3DPage-BE6Epe0d.js} +2 -2
- package/dist/ui/assets/ProvidersPage-D0cApfM1.js +1 -0
- package/dist/ui/assets/{RecoverPage-DMqSasKk.js → RecoverPage-BVUPHG9z.js} +1 -1
- package/dist/ui/assets/{SettingsPage-B6FTSkOn.js → SettingsPage-DCZ4nql4.js} +1 -1
- package/dist/ui/assets/{SetupPage-DhcRbGgg.js → SetupPage-In19p30M.js} +1 -1
- package/dist/ui/assets/{WebChatPage-CWXjW4Hn.js → WebChatPage-ByVBSzxL.js} +1 -1
- package/dist/ui/assets/{activity-CQuPevhB.js → activity-BIIli7ET.js} +1 -1
- package/dist/ui/assets/{agentCapabilities-CDC6y91E.js → agentCapabilities-D1PD9yFH.js} +1 -1
- package/dist/ui/assets/arrow-left-BfcnX8Er.js +1 -0
- package/dist/ui/assets/arrow-right-Q-dzAn8k.js +1 -0
- package/dist/ui/assets/arrow-up-right-Bf-8wrUQ.js +1 -0
- package/dist/ui/assets/{calendar-Be23hQGc.js → calendar-S9-_Q6QR.js} +1 -1
- package/dist/ui/assets/check-CryV78SQ.js +1 -0
- package/dist/ui/assets/chevron-down-QCtMs-Af.js +1 -0
- package/dist/ui/assets/chevron-left-dTGbyl5G.js +1 -0
- package/dist/ui/assets/chevron-right-D0GjXbnO.js +1 -0
- package/dist/ui/assets/chevron-up-Cg0jO8uT.js +1 -0
- package/dist/ui/assets/{circle-alert-BDVHxmAz.js → circle-alert-DTVW4R94.js} +1 -1
- package/dist/ui/assets/circle-check-BAolxswA.js +1 -0
- package/dist/ui/assets/{circle-x-Cb2Yer4s.js → circle-x-CJXbXzRh.js} +1 -1
- package/dist/ui/assets/{copy-33tZrzc9.js → copy-X_TPpA-A.js} +1 -1
- package/dist/ui/assets/{dialog-KOZKWbib.js → dialog-uUBz_NIB.js} +1 -1
- package/dist/ui/assets/{download-CiQqqXyz.js → download-C-fXu08w.js} +1 -1
- package/dist/ui/assets/{earth-DCvN7ynm.js → earth-CTsVjCmp.js} +1 -1
- package/dist/ui/assets/{ellipsis-vertical-BybFZDk2.js → ellipsis-vertical-5zBh5yzc.js} +1 -1
- package/dist/ui/assets/{external-link-0iNNBvZm.js → external-link-CvpRhwC_.js} +1 -1
- package/dist/ui/assets/{eye-C8sKSSkg.js → eye-CM-HQEWU.js} +1 -1
- package/dist/ui/assets/{file-text-DO8jqiJK.js → file-text-lwkvYGtA.js} +1 -1
- package/dist/ui/assets/gauge-CB-cas-h.js +1 -0
- package/dist/ui/assets/{history-BtTD1kDo.js → history-eSHspWRr.js} +1 -1
- package/dist/ui/assets/index-D489S18g.css +2 -0
- package/dist/ui/assets/{index-Bejlp-R1.js → index-ZjAc-KQS.js} +4 -4
- package/dist/ui/assets/{info-mpk1tsNC.js → info-DTgFQ_jA.js} +1 -1
- package/dist/ui/assets/{key-CoQ0qtXt.js → key-CeM9JJkq.js} +1 -1
- package/dist/ui/assets/loader-circle-Dtfz4FWw.js +1 -0
- package/dist/ui/assets/{lock-open-Cd2aqwOd.js → lock-open-B089GUAJ.js} +1 -1
- package/dist/ui/assets/{mail-BG0RYSkL.js → mail--gNFIe4M.js} +1 -1
- package/dist/ui/assets/{pause-Cme88_9s.js → pause-DjT1nwQM.js} +1 -1
- package/dist/ui/assets/{pencil-f1nJ1xhs.js → pencil-6PRgdjiU.js} +1 -1
- package/dist/ui/assets/play-tOrP0xUJ.js +1 -0
- package/dist/ui/assets/plus-Cnom3j47.js +1 -0
- package/dist/ui/assets/{radio-B5SpKJ-J.js → radio-D-joO9J0.js} +1 -1
- package/dist/ui/assets/{refresh-cw-CroGQY62.js → refresh-cw-BRrzoHQW.js} +1 -1
- package/dist/ui/assets/search-D277MUP0.js +1 -0
- package/dist/ui/assets/{select-BhbW0stK.js → select-BOR8MsSL.js} +1 -1
- package/dist/ui/assets/{send-D6whYpw-.js → send-DIlj81PT.js} +1 -1
- package/dist/ui/assets/{settings-BX6q3MGB.js → settings-CkBjgAEm.js} +1 -1
- package/dist/ui/assets/{shield-BnGyu1xf.js → shield-U0hIjGzm.js} +1 -1
- package/dist/ui/assets/{sparkles-BcaOs_Jk.js → sparkles-VXHGDbNh.js} +1 -1
- package/dist/ui/assets/{square-ju5H8nrT.js → square-OHeetvN3.js} +1 -1
- package/dist/ui/assets/terminal-C6YPcJl_.js +1 -0
- package/dist/ui/assets/{trash-2-DjQXac_0.js → trash-2-DQxm7DUM.js} +1 -1
- package/dist/ui/assets/{triangle-alert-B04mgMcg.js → triangle-alert-Dj8ZhmWj.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-DT5-4CCj.js → useHiveAgentsModelLoad-COLvs-Ho.js} +1 -1
- package/dist/ui/assets/{useProviders-DSX7eVsz.js → useProviders-q6iROeWE.js} +1 -1
- package/dist/ui/assets/{volume-x-qnVxkRSM.js → volume-x-Bm735CXN.js} +1 -1
- package/dist/ui/assets/{wifi-BA1m2dGO.js → wifi-DklBfOZ6.js} +1 -1
- package/dist/ui/assets/{zap-DT7cM7YS.js → zap-BEZNJ0i0.js} +1 -1
- package/dist/ui/index.html +8 -6
- package/dist/ui/logoblack.png +0 -0
- package/dist/ui/logocolor-dark.png +0 -0
- package/dist/ui/logocolorbg.png +0 -0
- package/dist/ui/logodoradobg.png +0 -0
- package/package.json +12 -8
- package/packages/cli/src/commands/doctor.ts +111 -0
- package/packages/cli/src/commands/onboard.ts +126 -59
- package/packages/cli/src/ui-bundle.generated.ts +9 -92
- package/packages/core/src/agent/acceptance-checks.ts +172 -0
- package/packages/core/src/agent/agent-catalog.ts +1 -37
- package/packages/core/src/agent/agent-loop.ts +21 -2
- package/packages/core/src/agent/catalog-selector.ts +0 -1
- package/packages/core/src/agent/compaction.ts +16 -1
- package/packages/core/src/agent/context-compiler.ts +3 -1
- package/packages/core/src/agent/conversation-store.ts +1 -1
- package/packages/core/src/agent/delegation-runtime.ts +1 -8
- package/packages/core/src/agent/goal-runner.ts +111 -32
- package/packages/core/src/agent/index.ts +1 -1
- package/packages/core/src/agent/llm-client.ts +34 -2
- package/packages/core/src/agent/llm-providers/anthropic.ts +10 -7
- package/packages/core/src/agent/llm-providers/interface.ts +13 -2
- package/packages/core/src/agent/llm-providers/modelscope.ts +5 -0
- package/packages/core/src/agent/llm-providers/z-ai.ts +5 -0
- package/packages/core/src/agent/minimal-loadout.ts +1 -0
- package/packages/core/src/agent/proof-packet.ts +2 -11
- package/packages/core/src/agent/providers/index.ts +1 -1
- package/packages/core/src/agent/tool-selector.ts +25 -1
- package/packages/core/src/canvas/emitter.ts +0 -44
- package/packages/core/src/channels/manager.ts +117 -25
- package/packages/core/src/channels/whatsapp.ts +6 -1
- package/packages/core/src/config/loader.ts +13 -1
- package/packages/core/src/events/channel-narration.ts +150 -0
- package/packages/core/src/events/tool-narration.ts +62 -0
- package/packages/core/src/gateway/channel-notify.ts +11 -7
- package/packages/core/src/gateway/delegation-groups.ts +24 -11
- package/packages/core/src/gateway/helpers/narration.ts +4 -62
- package/packages/core/src/gateway/helpers/ui-source.ts +67 -0
- package/packages/core/src/gateway/job-executors.ts +29 -67
- package/packages/core/src/gateway/resolver.ts +10 -2
- package/packages/core/src/gateway/routes/agents.ts +6 -6
- package/packages/core/src/gateway/routes/channels.ts +15 -1
- package/packages/core/src/gateway/routes/models.ts +69 -12
- package/packages/core/src/gateway/routes/providers.ts +110 -28
- package/packages/core/src/gateway/routes/setup.ts +63 -11
- package/packages/core/src/gateway/routes/system.ts +8 -5
- package/packages/core/src/gateway/routes/voice.ts +3 -0
- package/packages/core/src/gateway/server.ts +58 -28
- package/packages/core/src/gateway/webchat-turn.ts +29 -5
- package/packages/core/src/index.ts +1 -1
- package/packages/core/src/storage/bootstrap.ts +13 -9
- package/packages/core/src/storage/collections.ts +12 -46
- package/packages/core/src/storage/crypto.ts +147 -58
- package/packages/core/src/storage/hivedb.ts +9 -0
- package/packages/core/src/storage/model-id.ts +53 -0
- package/packages/core/src/storage/onboarding.ts +15 -4
- package/packages/core/src/storage/seed.ts +254 -138
- package/packages/core/src/storage/usage.ts +61 -123
- package/packages/core/src/tools/agents/index.ts +199 -27
- package/packages/core/src/tools/index.ts +2 -1
- package/packages/core/src/tools/web/browser-backend.ts +129 -0
- package/packages/core/src/tools/web/browser-service.ts +75 -35
- package/packages/core/src/tools/web/webview-backend.ts +412 -0
- package/packages/core/src/voice/index.ts +108 -17
- package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +2 -1
- package/packages/skills/src/bundled-data.generated.ts +2 -23
- package/dist/ui/assets/AgentNewPage-CEkLeA79.js +0 -1
- package/dist/ui/assets/ProvidersPage-BupHs5yO.js +0 -1
- package/dist/ui/assets/arrow-left-0EBE7nsF.js +0 -1
- package/dist/ui/assets/arrow-right-5QIaph-z.js +0 -1
- package/dist/ui/assets/arrow-up-right-DQQCY007.js +0 -1
- package/dist/ui/assets/check-Dp6tzwax.js +0 -1
- package/dist/ui/assets/chevron-down-33N886NY.js +0 -1
- package/dist/ui/assets/chevron-left-C6itJXh3.js +0 -1
- package/dist/ui/assets/chevron-right-CFodBS-b.js +0 -1
- package/dist/ui/assets/chevron-up-BvSmyBEs.js +0 -1
- package/dist/ui/assets/circle-check-BJWNbLuF.js +0 -1
- package/dist/ui/assets/gauge-BRGwuN8G.js +0 -1
- package/dist/ui/assets/index-XoTT41Hr.css +0 -2
- package/dist/ui/assets/loader-circle-BhqRN2nO.js +0 -1
- package/dist/ui/assets/play-CfYDHD6h.js +0 -1
- package/dist/ui/assets/plus-C5BxJeOX.js +0 -1
- package/dist/ui/assets/search-rfBcmohK.js +0 -1
- package/dist/ui/assets/terminal-Bjfu-TkS.js +0 -1
- package/packages/core/src/agent/acceptance-verifier.ts +0 -300
- package/packages/skills/src/bundled/agents/acceptance_verification/SKILL.md +0 -26
|
@@ -5,22 +5,25 @@ import type { ContentPart, LLMMessage } from "../llm-client"
|
|
|
5
5
|
|
|
6
6
|
const log = logger.child("llm-client")
|
|
7
7
|
|
|
8
|
-
// Models that
|
|
8
|
+
// Models that accept the explicit `thinking: { type: "enabled" }` parameter, per
|
|
9
|
+
// the "Extended thinking" row of platform.claude.com/docs/en/about-claude/models/overview.
|
|
10
|
+
// This is an allowlist on purpose: from Opus 4.7 onward Anthropic replaced extended
|
|
11
|
+
// thinking with *adaptive* thinking, which is server-side and always on — those models
|
|
12
|
+
// reject the parameter, so being absent here is the correct behavior, not an omission.
|
|
9
13
|
const THINKING_CAPABLE_MODELS = new Set([
|
|
10
14
|
"claude-3-7-sonnet-20250219",
|
|
11
15
|
"claude-sonnet-4-5",
|
|
12
|
-
"claude-sonnet-4-
|
|
16
|
+
"claude-sonnet-4-5-20250929",
|
|
17
|
+
"claude-sonnet-4-6", // deprecated but still accepted
|
|
13
18
|
"claude-opus-4-5",
|
|
14
|
-
"claude-opus-4-
|
|
15
|
-
"claude-opus-4-
|
|
19
|
+
"claude-opus-4-5-20251101",
|
|
20
|
+
"claude-opus-4-6", // deprecated but still accepted
|
|
16
21
|
"claude-haiku-4-5",
|
|
17
22
|
"claude-haiku-4-5-20251001",
|
|
18
23
|
])
|
|
19
24
|
|
|
20
25
|
function supportsThinking(model: string): boolean {
|
|
21
|
-
|
|
22
|
-
// Also match any claude-4.x or claude-3-7+ by prefix
|
|
23
|
-
return /^claude-(4|3-7)/.test(model)
|
|
26
|
+
return THINKING_CAPABLE_MODELS.has(model)
|
|
24
27
|
}
|
|
25
28
|
|
|
26
29
|
/** Anthropic's documented shape for context-length errors: 400 + invalid_request_error + a "too long"/"maximum" message. */
|
|
@@ -30,6 +30,11 @@ export const OPENAI_COMPAT_BASE_URLS: Record<string, string> = {
|
|
|
30
30
|
minimax: "https://api.minimaxi.com/v1",
|
|
31
31
|
"opencode-go": "https://opencode.ai/zen/go/v1",
|
|
32
32
|
hiveagents: "https://llm.hiveagents.io/v1",
|
|
33
|
+
"z-ai": "https://api.z.ai/api/paas/v4",
|
|
34
|
+
// OJO: `.ai`, no `.cn`. Son dos plataformas con cuentas y tokens distintos, y
|
|
35
|
+
// un token de la internacional da 401 contra el endpoint chino aunque el
|
|
36
|
+
// listado de modelos responda 200 en ambos (ese listado es público).
|
|
37
|
+
modelscope: "https://api-inference.modelscope.ai/v1",
|
|
33
38
|
}
|
|
34
39
|
|
|
35
40
|
// ─── Provider profiles ────────────────────────────────────────────────────────
|
|
@@ -63,9 +68,15 @@ const PROVIDER_PROFILES: Record<string, ProviderProfile> = {
|
|
|
63
68
|
kimi: { ...DEFAULT_PROFILE, normalizeToolNames: true, disableParallelToolCalls: true, retryWithoutToolsOnCodes: [422] },
|
|
64
69
|
deepseek: { ...DEFAULT_PROFILE, normalizeToolNames: true },
|
|
65
70
|
groq: { ...DEFAULT_PROFILE, normalizeToolNames: true, retryWithoutToolsOnCodes: [400, 422] },
|
|
66
|
-
|
|
71
|
+
// tool_choice "any" *forces* a tool call on every request per docs.mistral.ai —
|
|
72
|
+
// it is not Mistral's spelling of "auto", which Mistral supports and defaults to.
|
|
73
|
+
// With "any" the agent could never answer in plain text: every turn had to end
|
|
74
|
+
// in a tool call, so the loop only stopped when it hit max iterations.
|
|
75
|
+
mistral: { ...DEFAULT_PROFILE, normalizeToolNames: true, stripAdditionalProperties: true },
|
|
67
76
|
openrouter: { ...DEFAULT_PROFILE, normalizeToolNames: true, retryWithoutToolsOnCodes: [400, 422] },
|
|
68
|
-
nvidia: { ...DEFAULT_PROFILE, normalizeToolNames: true },
|
|
77
|
+
nvidia: { ...DEFAULT_PROFILE, normalizeToolNames: true, retryWithoutToolsOnCodes: [400, 422] },
|
|
78
|
+
"z-ai": { ...DEFAULT_PROFILE, normalizeToolNames: true, retryWithoutToolsOnCodes: [400, 422] },
|
|
79
|
+
modelscope: { ...DEFAULT_PROFILE, normalizeToolNames: true, retryWithoutToolsOnCodes: [400, 422] },
|
|
69
80
|
qwen: { ...DEFAULT_PROFILE, normalizeToolNames: true, retryWithoutToolsOnCodes: [400, 422] },
|
|
70
81
|
minimax: { ...DEFAULT_PROFILE, normalizeToolNames: true, retryWithoutToolsOnCodes: [400, 422] },
|
|
71
82
|
"opencode-go": { ...DEFAULT_PROFILE, normalizeToolNames: true, retryWithoutToolsOnCodes: [400, 422] },
|
|
@@ -25,20 +25,12 @@ export interface BuildProofPacketInput {
|
|
|
25
25
|
evidence: string[];
|
|
26
26
|
knownLimits?: string | null;
|
|
27
27
|
epoch?: RunEpoch | null;
|
|
28
|
-
/** Mandatory for met=true: independent acceptance_verifier verdict id. */
|
|
29
|
-
verificationId?: string | null;
|
|
30
28
|
catalogAgentId?: string | null;
|
|
31
29
|
}
|
|
32
30
|
|
|
33
31
|
export async function buildProofPacket(input: BuildProofPacketInput): Promise<ProofPacketDoc> {
|
|
34
|
-
if (input.met) {
|
|
35
|
-
|
|
36
|
-
throw new Error("A successful proof packet requires an independent verification_id");
|
|
37
|
-
}
|
|
38
|
-
const { getVerifiedVerification } = await import("./acceptance-verifier");
|
|
39
|
-
if (!(await getVerifiedVerification(input.verificationId, input.runId))) {
|
|
40
|
-
throw new Error(`Verification ${input.verificationId} is missing, rejected, or belongs to another run`);
|
|
41
|
-
}
|
|
32
|
+
if (input.met && (input.checksRun.length === 0 || input.evidence.length === 0)) {
|
|
33
|
+
throw new Error("A successful proof packet requires at least one check run and non-empty evidence");
|
|
42
34
|
}
|
|
43
35
|
const id = await nextId("proofPackets");
|
|
44
36
|
const acceptanceResults: AcceptanceResult[] =
|
|
@@ -54,7 +46,6 @@ export async function buildProofPacket(input: BuildProofPacketInput): Promise<Pr
|
|
|
54
46
|
evidence_json: JSON.stringify(input.evidence),
|
|
55
47
|
known_limits: input.knownLimits ?? null,
|
|
56
48
|
epoch_json: input.epoch ? JSON.stringify(input.epoch) : null,
|
|
57
|
-
verification_id: toIndexable(input.verificationId),
|
|
58
49
|
catalog_agent_id: toIndexable(input.catalogAgentId),
|
|
59
50
|
met: input.met,
|
|
60
51
|
created_at: Date.now(),
|
|
@@ -12,7 +12,7 @@ import { resolveUserId, resolveAgentId } from "../../storage/onboarding"
|
|
|
12
12
|
import type { ContentPart } from "../../multimodal/types"
|
|
13
13
|
import type { TurnSource } from "../../storage/collections"
|
|
14
14
|
|
|
15
|
-
export type Provider = "openai" | "anthropic" | "gemini" | "mistral" | "kimi" | "ollama" | "openrouter" | "deepseek" | "nvidia" | "hiveagents"
|
|
15
|
+
export type Provider = "openai" | "anthropic" | "gemini" | "mistral" | "kimi" | "ollama" | "openrouter" | "deepseek" | "nvidia" | "hiveagents" | "z-ai" | "modelscope" | "minimax" | "qwen" | "groq" | "opencode-go"
|
|
16
16
|
|
|
17
17
|
export interface StepEvent {
|
|
18
18
|
type: "text" | "plan" | "tool_call" | "tool_result"
|
|
@@ -184,6 +184,7 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
|
|
|
184
184
|
|
|
185
185
|
// Agent delegation and communication
|
|
186
186
|
{ name: "task_delegate", description: "Delegate general task to worker agent. Spanish keywords: delegar tarea, asignar worker, ejecutar por agente, encomendar tarea", category: "agents", abstractionLevel: "orchestration" },
|
|
187
|
+
{ name: "task_revise", description: "Send a delegated task back to its worker with feedback when it does not meet its acceptance criteria. Spanish keywords: corregir tarea, devolver al worker, pedir correccion, reencolar tarea", category: "agents", abstractionLevel: "orchestration" },
|
|
187
188
|
{ name: "task_list", description: "List real delegated task executions for the current user from persisted tasks and jobs. Spanish keywords: listar tareas activas, subagentes trabajando, ejecuciones reales", category: "agents", abstractionLevel: "atomic" },
|
|
188
189
|
{ name: "task_status", description: "Get execution status of delegated tasks. Spanish keywords: estado tarea delegada, verificar progreso, consultar tarea, progreso delegado", category: "agents", abstractionLevel: "atomic" },
|
|
189
190
|
{ name: "bus_publish", description: "Publish message to Agent Bus for worker-to-worker communication. Spanish keywords: publicar mensaje, comunicar workers, enviar bus, mensaje bus", category: "agents", abstractionLevel: "atomic" },
|
|
@@ -320,8 +321,31 @@ export async function selectTools(
|
|
|
320
321
|
return []
|
|
321
322
|
}
|
|
322
323
|
|
|
323
|
-
// Step 4: Map to tool descriptors with additional metadata
|
|
324
|
+
// Step 4: Map to tool descriptors with additional metadata.
|
|
325
|
+
//
|
|
326
|
+
// El mapa tiene que cubrir lo mismo que se indexó, o el hit se descarta en
|
|
327
|
+
// silencio. `syncToolCatalogToIndex` indexa CORE_TOOL_CATALOG **más** las
|
|
328
|
+
// filas de la colección `tools`; resolver sólo contra `fullToolList` (que
|
|
329
|
+
// por defecto es CORE_TOOL_CATALOG) hace que una tool registrada en runtime
|
|
330
|
+
// puntúe primera en BM25 y aun así nunca se le ofrezca al modelo. Acá no se
|
|
331
|
+
// nota porque todas las tools de hive están en el catálogo estático, pero
|
|
332
|
+
// cualquier tool que llegue sólo por la colección cae en el mismo pozo.
|
|
324
333
|
const toolMap = new Map(fullToolList.map(t => [t.name, t]))
|
|
334
|
+
const unresolved = relevantHits.filter(h => !toolMap.has(h.rawId))
|
|
335
|
+
if (unresolved.length > 0) {
|
|
336
|
+
const toolsCol = await col<ToolDoc>("tools")
|
|
337
|
+
for (const hit of unresolved) {
|
|
338
|
+
const entry = await toolsCol.get(hit.rawId)
|
|
339
|
+
if (!entry?.doc.enabled || !entry.doc.active) continue
|
|
340
|
+
toolMap.set(entry.doc.name, {
|
|
341
|
+
name: entry.doc.name,
|
|
342
|
+
description: entry.doc.description ?? entry.doc.name,
|
|
343
|
+
category: (entry.doc.category ?? "core") as any,
|
|
344
|
+
abstractionLevel: "atomic",
|
|
345
|
+
})
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
325
349
|
const calendarOperation = isCalendarOperation(userMessage)
|
|
326
350
|
|
|
327
351
|
const scoredTools: SelectedTool[] = []
|
|
@@ -19,7 +19,6 @@ export type CanvasEventType =
|
|
|
19
19
|
|
|
20
20
|
export type CanvasWorkPhase =
|
|
21
21
|
| "delegated"
|
|
22
|
-
| "review_started"
|
|
23
22
|
| "review_passed"
|
|
24
23
|
| "review_failed"
|
|
25
24
|
| "completed"
|
|
@@ -149,49 +148,6 @@ export function emitDelegationFinished(opts: { workerId: string; taskRef: string
|
|
|
149
148
|
emitCanvas("canvas:edge_remove", { id: `deleg_${opts.taskRef}` })
|
|
150
149
|
}
|
|
151
150
|
|
|
152
|
-
/**
|
|
153
|
-
* Fase de verificación del loop: el verificador independiente revisa la
|
|
154
|
-
* entrega del worker. Se visualiza como un eslabón worker → verificador.
|
|
155
|
-
*/
|
|
156
|
-
export function emitVerificationStarted(opts: {
|
|
157
|
-
verifierId: string
|
|
158
|
-
workerId: string
|
|
159
|
-
taskRef: string
|
|
160
|
-
taskName: string
|
|
161
|
-
}) {
|
|
162
|
-
emitWorkEvent({
|
|
163
|
-
phase: "review_started",
|
|
164
|
-
taskRef: opts.taskRef,
|
|
165
|
-
taskName: opts.taskName,
|
|
166
|
-
actorId: opts.workerId,
|
|
167
|
-
targetId: opts.verifierId,
|
|
168
|
-
})
|
|
169
|
-
emitCanvas("canvas:node_update", {
|
|
170
|
-
nodeId: opts.verifierId,
|
|
171
|
-
changes: {
|
|
172
|
-
status: "thinking",
|
|
173
|
-
currentTask: `Verificar: ${opts.taskName}`,
|
|
174
|
-
taskId: opts.taskRef,
|
|
175
|
-
delegatedBy: opts.workerId,
|
|
176
|
-
},
|
|
177
|
-
})
|
|
178
|
-
emitCanvas("canvas:edge_add", {
|
|
179
|
-
id: `review_${opts.taskRef}`,
|
|
180
|
-
source: opts.workerId,
|
|
181
|
-
target: opts.verifierId,
|
|
182
|
-
edgeType: "reviews",
|
|
183
|
-
data: { taskId: opts.taskRef, taskName: opts.taskName },
|
|
184
|
-
})
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
export function emitVerificationFinished(opts: { verifierId: string; taskRef: string }) {
|
|
188
|
-
emitCanvas("canvas:node_update", {
|
|
189
|
-
nodeId: opts.verifierId,
|
|
190
|
-
changes: { status: "idle", currentTool: null, currentTask: null, taskId: null, delegatedBy: null },
|
|
191
|
-
})
|
|
192
|
-
emitCanvas("canvas:edge_remove", { id: `review_${opts.taskRef}` })
|
|
193
|
-
}
|
|
194
|
-
|
|
195
151
|
export async function getCanvasSnapshot() {
|
|
196
152
|
const agentsCol = await col<AgentDoc>("agents")
|
|
197
153
|
const agentNodes = (await agentsCol.scan({}))
|
|
@@ -7,7 +7,7 @@ import { createWebChatChannel, type WebChatConfig } from "./webchat.ts";
|
|
|
7
7
|
import { createWhatsAppChannel, WhatsAppChannel, type WhatsAppConfig } from "./whatsapp.ts";
|
|
8
8
|
import { createSlackChannel, type SlackConfig } from "./slack.ts";
|
|
9
9
|
import { col } from "../storage/hive.ts";
|
|
10
|
-
import type { ChannelDoc, AgentDoc } from "../storage/collections.ts";
|
|
10
|
+
import type { ChannelDoc, AgentDoc, UserIdentityDoc } from "../storage/collections.ts";
|
|
11
11
|
import { loadChannelConfig } from "../storage/crypto.ts";
|
|
12
12
|
|
|
13
13
|
export class ChannelManager {
|
|
@@ -15,11 +15,44 @@ export class ChannelManager {
|
|
|
15
15
|
private channels: Map<string, IChannel> = new Map();
|
|
16
16
|
private messageHandler?: MessageHandler;
|
|
17
17
|
private log = logger.child("channels");
|
|
18
|
+
/**
|
|
19
|
+
* `channel:sessionId` → accountId of the account that received the message.
|
|
20
|
+
*
|
|
21
|
+
* Outbound calls (agent reply, narration, notify tools, scheduler) only carry
|
|
22
|
+
* a channel name and a routing session id. With two accounts of the same type
|
|
23
|
+
* connected — two WhatsApp numbers — picking a channel by name alone sends the
|
|
24
|
+
* reply out through whichever account happens to be first, to a peer that may
|
|
25
|
+
* not even exist there. Every inbound message records its account here so the
|
|
26
|
+
* reply goes back out the way it came in.
|
|
27
|
+
*
|
|
28
|
+
* Known limit: if the same peer id talks to two accounts of one type, the
|
|
29
|
+
* routing session id is identical for both and the most recent inbound
|
|
30
|
+
* message wins. Distinguishing them would require the account in the session
|
|
31
|
+
* id itself.
|
|
32
|
+
*/
|
|
33
|
+
private sessionAccounts: Map<string, string> = new Map();
|
|
18
34
|
|
|
19
35
|
constructor(config: Config) {
|
|
20
36
|
this.config = config;
|
|
21
37
|
}
|
|
22
38
|
|
|
39
|
+
private sessionKey(channelName: string, sessionId: string): string {
|
|
40
|
+
return `${channelName}:${sessionId}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Resolves which account owns an outbound session: an explicit account wins,
|
|
45
|
+
* then the account that last received a message on it.
|
|
46
|
+
*/
|
|
47
|
+
private resolveAccountId(
|
|
48
|
+
channelName: string,
|
|
49
|
+
sessionId: string,
|
|
50
|
+
explicit?: string
|
|
51
|
+
): string | undefined {
|
|
52
|
+
if (explicit) return explicit;
|
|
53
|
+
return this.sessionAccounts.get(this.sessionKey(channelName, sessionId));
|
|
54
|
+
}
|
|
55
|
+
|
|
23
56
|
onMessage(handler: MessageHandler): void {
|
|
24
57
|
this.messageHandler = handler;
|
|
25
58
|
}
|
|
@@ -33,9 +66,31 @@ export class ChannelManager {
|
|
|
33
66
|
await this.initializeFromConfig();
|
|
34
67
|
}
|
|
35
68
|
|
|
69
|
+
await this.seedSessionAccounts();
|
|
70
|
+
|
|
36
71
|
this.log.info(`Initialized ${this.channels.size} channel(s)`);
|
|
37
72
|
}
|
|
38
73
|
|
|
74
|
+
/**
|
|
75
|
+
* Restores session→account routing from persisted identities. Without this, a
|
|
76
|
+
* durable worker that finishes after a restart would have no record of which
|
|
77
|
+
* account its conversation came in on.
|
|
78
|
+
*/
|
|
79
|
+
private async seedSessionAccounts(): Promise<void> {
|
|
80
|
+
try {
|
|
81
|
+
const identitiesCol = await col<UserIdentityDoc>("userIdentities");
|
|
82
|
+
for (const { doc } of await identitiesCol.scan({})) {
|
|
83
|
+
if (!doc.account_id || !doc.channel_user_id) continue;
|
|
84
|
+
// Skip identities whose account is gone (disconnected and replaced by
|
|
85
|
+
// another one) — pinning a session to it would only fail every send.
|
|
86
|
+
if (!this.channels.has(`${doc.channel}:${doc.account_id}`)) continue;
|
|
87
|
+
this.sessionAccounts.set(this.sessionKey(doc.channel, doc.channel_user_id), doc.account_id);
|
|
88
|
+
}
|
|
89
|
+
} catch (error) {
|
|
90
|
+
this.log.debug(`Could not seed session accounts: ${(error as Error).message}`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
39
94
|
private async initializeFromDB(): Promise<void> {
|
|
40
95
|
try {
|
|
41
96
|
const channelsCol = await col<ChannelDoc>("channels");
|
|
@@ -84,6 +139,26 @@ export class ChannelManager {
|
|
|
84
139
|
}
|
|
85
140
|
}
|
|
86
141
|
|
|
142
|
+
/**
|
|
143
|
+
* Wires a channel into the manager: inbound messages record which account
|
|
144
|
+
* received them before reaching the handler, so replies can be routed back.
|
|
145
|
+
*/
|
|
146
|
+
private registerChannel(key: string, channel: IChannel): void {
|
|
147
|
+
channel.onMessage(async (message: IncomingMessage) => {
|
|
148
|
+
if (message.accountId && message.sessionId) {
|
|
149
|
+
this.sessionAccounts.set(
|
|
150
|
+
this.sessionKey(message.channel, message.sessionId),
|
|
151
|
+
message.accountId
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
if (this.messageHandler) {
|
|
155
|
+
await this.messageHandler(message);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
this.channels.set(key, channel);
|
|
160
|
+
}
|
|
161
|
+
|
|
87
162
|
private async createChannel(
|
|
88
163
|
channelName: string,
|
|
89
164
|
accountId: string,
|
|
@@ -158,14 +233,8 @@ export class ChannelManager {
|
|
|
158
233
|
return;
|
|
159
234
|
}
|
|
160
235
|
|
|
161
|
-
channel.onMessage(async (message: IncomingMessage) => {
|
|
162
|
-
if (this.messageHandler) {
|
|
163
|
-
await this.messageHandler(message);
|
|
164
|
-
}
|
|
165
|
-
});
|
|
166
|
-
|
|
167
236
|
const key = `${channelName}:${accountId}`;
|
|
168
|
-
this.
|
|
237
|
+
this.registerChannel(key, channel);
|
|
169
238
|
|
|
170
239
|
this.log.info(`Created channel: ${key}`);
|
|
171
240
|
} catch (error) {
|
|
@@ -217,22 +286,35 @@ export class ChannelManager {
|
|
|
217
286
|
|
|
218
287
|
getChannel(channelName: string, accountId?: string): IChannel | undefined {
|
|
219
288
|
if (accountId) {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
return channel;
|
|
289
|
+
const exact = this.channels.get(`${channelName}:${accountId}`);
|
|
290
|
+
// Deliberately no fallback: delivering through a different account would
|
|
291
|
+
// send someone else's conversation out of the wrong number.
|
|
292
|
+
if (!exact) {
|
|
293
|
+
this.log.warn(`Channel ${channelName}:${accountId} is not instantiated — refusing to fall back to another account`);
|
|
226
294
|
}
|
|
295
|
+
return exact;
|
|
227
296
|
}
|
|
228
297
|
|
|
229
|
-
|
|
298
|
+
const matches = [...this.channels.entries()].filter(([key]) => key.startsWith(`${channelName}:`));
|
|
299
|
+
if (matches.length > 1) {
|
|
300
|
+
this.log.warn(
|
|
301
|
+
`${matches.length} "${channelName}" accounts are connected and no account was given — routing through ${matches[0]![0]}`
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
return matches[0]?.[1];
|
|
230
305
|
}
|
|
231
306
|
|
|
232
307
|
async removeChannel(channelName: string, accountId: string): Promise<void> {
|
|
233
308
|
const key = `${channelName}:${accountId}`;
|
|
234
309
|
await this.stopChannel(channelName, accountId);
|
|
235
310
|
this.channels.delete(key);
|
|
311
|
+
// Drop sessions pinned to this account, otherwise every later send to them
|
|
312
|
+
// resolves to a channel that no longer exists.
|
|
313
|
+
for (const [sessionKey, account] of this.sessionAccounts) {
|
|
314
|
+
if (account === accountId && sessionKey.startsWith(`${channelName}:`)) {
|
|
315
|
+
this.sessionAccounts.delete(sessionKey);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
236
318
|
this.log.info(`Removed channel: ${key}`);
|
|
237
319
|
}
|
|
238
320
|
|
|
@@ -398,12 +480,22 @@ export class ChannelManager {
|
|
|
398
480
|
});
|
|
399
481
|
}
|
|
400
482
|
|
|
483
|
+
/** Resolves the account that owns this session (see `sessionAccounts`). */
|
|
484
|
+
private channelForSession(
|
|
485
|
+
channelName: string,
|
|
486
|
+
sessionId: string,
|
|
487
|
+
accountId?: string
|
|
488
|
+
): IChannel | undefined {
|
|
489
|
+
return this.getChannel(channelName, this.resolveAccountId(channelName, sessionId, accountId));
|
|
490
|
+
}
|
|
491
|
+
|
|
401
492
|
async send(
|
|
402
493
|
channelName: string,
|
|
403
494
|
sessionId: string,
|
|
404
|
-
message: unknown
|
|
495
|
+
message: unknown,
|
|
496
|
+
accountId?: string
|
|
405
497
|
): Promise<void> {
|
|
406
|
-
const channel = this.
|
|
498
|
+
const channel = this.channelForSession(channelName, sessionId, accountId);
|
|
407
499
|
|
|
408
500
|
if (!channel) {
|
|
409
501
|
throw new Error(`Channel not found: ${channelName}`);
|
|
@@ -412,29 +504,29 @@ export class ChannelManager {
|
|
|
412
504
|
await channel.send(sessionId, message as any);
|
|
413
505
|
}
|
|
414
506
|
|
|
415
|
-
async startTyping(channelName: string, sessionId: string): Promise<void> {
|
|
416
|
-
const channel = this.
|
|
507
|
+
async startTyping(channelName: string, sessionId: string, accountId?: string): Promise<void> {
|
|
508
|
+
const channel = this.channelForSession(channelName, sessionId, accountId);
|
|
417
509
|
if (channel?.startTyping) {
|
|
418
510
|
await channel.startTyping(sessionId);
|
|
419
511
|
}
|
|
420
512
|
}
|
|
421
513
|
|
|
422
|
-
async stopTyping(channelName: string, sessionId: string): Promise<void> {
|
|
423
|
-
const channel = this.
|
|
514
|
+
async stopTyping(channelName: string, sessionId: string, accountId?: string): Promise<void> {
|
|
515
|
+
const channel = this.channelForSession(channelName, sessionId, accountId);
|
|
424
516
|
if (channel?.stopTyping) {
|
|
425
517
|
await channel.stopTyping(sessionId);
|
|
426
518
|
}
|
|
427
519
|
}
|
|
428
520
|
|
|
429
|
-
async markAsRead(channelName: string, sessionId: string, messageId?: string): Promise<void> {
|
|
430
|
-
const channel = this.
|
|
521
|
+
async markAsRead(channelName: string, sessionId: string, messageId?: string, accountId?: string): Promise<void> {
|
|
522
|
+
const channel = this.channelForSession(channelName, sessionId, accountId);
|
|
431
523
|
if (channel?.markAsRead) {
|
|
432
524
|
await channel.markAsRead(sessionId, messageId);
|
|
433
525
|
}
|
|
434
526
|
}
|
|
435
527
|
|
|
436
|
-
async sendAudio(channelName: string, sessionId: string, audio: Buffer, mimeType: string): Promise<void> {
|
|
437
|
-
const channel = this.
|
|
528
|
+
async sendAudio(channelName: string, sessionId: string, audio: Buffer, mimeType: string, accountId?: string): Promise<void> {
|
|
529
|
+
const channel = this.channelForSession(channelName, sessionId, accountId);
|
|
438
530
|
if (!channel) {
|
|
439
531
|
throw new Error(`Channel not found: ${channelName}`);
|
|
440
532
|
}
|
|
@@ -482,7 +482,11 @@ export class WhatsAppChannel extends BaseChannel {
|
|
|
482
482
|
throw new Error("WhatsApp not connected");
|
|
483
483
|
}
|
|
484
484
|
|
|
485
|
-
|
|
485
|
+
// Progress narration arrives mid-turn. Clearing "typing…" on it would leave
|
|
486
|
+
// the user watching interim messages with no sign the agent is still
|
|
487
|
+
// working — only a final message ends the indicator.
|
|
488
|
+
const isInterim = message.type === "progress";
|
|
489
|
+
if (!isInterim) await this.stopTyping(sessionId);
|
|
486
490
|
|
|
487
491
|
const text = message.content ?? message.chunk ?? "";
|
|
488
492
|
if (!text) return;
|
|
@@ -490,6 +494,7 @@ export class WhatsAppChannel extends BaseChannel {
|
|
|
490
494
|
const jid = this.getJid(sessionId);
|
|
491
495
|
|
|
492
496
|
await this.socket.sendMessage(jid, { text });
|
|
497
|
+
if (isInterim) await this.startTyping(sessionId);
|
|
493
498
|
this.log.debug(`Sent message to ${jid}`);
|
|
494
499
|
}
|
|
495
500
|
|
|
@@ -19,8 +19,15 @@ export function loadEnv(hiveDir: string): void {
|
|
|
19
19
|
|
|
20
20
|
const [key, ...valueParts] = trimmed.split("=");
|
|
21
21
|
if (key && valueParts.length > 0) {
|
|
22
|
+
const normalizedKey = key.trim();
|
|
22
23
|
const value = valueParts.join("=").trim().replace(/^['"]|['"]$/g, "");
|
|
23
|
-
process
|
|
24
|
+
// Explicit process environment values (for example the random
|
|
25
|
+
// port assigned by the desktop shell) must take precedence over the
|
|
26
|
+
// persisted .env file. This follows dotenv conventions and prevents
|
|
27
|
+
// a previous CLI port from breaking desktop startup.
|
|
28
|
+
if (process.env[normalizedKey] === undefined) {
|
|
29
|
+
process.env[normalizedKey] = value;
|
|
30
|
+
}
|
|
24
31
|
}
|
|
25
32
|
}
|
|
26
33
|
} catch (e) {
|
|
@@ -120,6 +127,11 @@ const BrowserConfigSchema = z.object({
|
|
|
120
127
|
headless: z.boolean().optional(),
|
|
121
128
|
timeoutMs: z.number().optional(),
|
|
122
129
|
sessionName: z.string().optional(),
|
|
130
|
+
// "agent-browser" (default) usa Chrome via CLI y sirve headless/Docker.
|
|
131
|
+
// "webview" usa Bun.WebView in-process — mucho más rápido y sin instalación,
|
|
132
|
+
// pero requiere entorno gráfico. "auto" toma webview sólo si hay display.
|
|
133
|
+
// Lo pisa HIVE_BROWSER_BACKEND.
|
|
134
|
+
backend: z.enum(["agent-browser", "webview", "auto"]).optional(),
|
|
123
135
|
});
|
|
124
136
|
|
|
125
137
|
const CanvasConfigSchema = z.object({
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// ─── Narration delivery policy for messaging channels ─────────────────────────
|
|
2
|
+
// WebChat renders narration as ephemeral, collapsible "process" widgets. A
|
|
3
|
+
// messaging channel (WhatsApp, Telegram, Slack, Discord) has no such surface:
|
|
4
|
+
// every narration event becomes a permanent chat message. Without a filter a
|
|
5
|
+
// single turn with a few tools and two delegated workers produces dozens of
|
|
6
|
+
// messages before the actual answer — noise for the user and a rate-limit /
|
|
7
|
+
// ban risk on WhatsApp. This module decides what reaches those channels.
|
|
8
|
+
|
|
9
|
+
import { col } from "../storage/hive";
|
|
10
|
+
import type { ChannelDoc, NarrationEventDoc } from "../storage/collections";
|
|
11
|
+
import { logger } from "../utils/logger";
|
|
12
|
+
|
|
13
|
+
const log = logger.child("narration:channel");
|
|
14
|
+
|
|
15
|
+
/** `off` = silent, `milestones` = delegation lifecycle only, `all` = + per-tool steps. */
|
|
16
|
+
export type NarrationMode = "off" | "milestones" | "all";
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_NARRATION_MODE: NarrationMode = "milestones";
|
|
19
|
+
|
|
20
|
+
/** Legacy `step_delivery_mode` values predate this feature — map them forward. */
|
|
21
|
+
function coerceMode(raw: string | null | undefined): NarrationMode {
|
|
22
|
+
switch (raw) {
|
|
23
|
+
case "off":
|
|
24
|
+
case "milestones":
|
|
25
|
+
case "all":
|
|
26
|
+
return raw;
|
|
27
|
+
// "new_messages" was the original (never-read) default.
|
|
28
|
+
case "new_messages":
|
|
29
|
+
return DEFAULT_NARRATION_MODE;
|
|
30
|
+
default:
|
|
31
|
+
return DEFAULT_NARRATION_MODE;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** High-level events: what the user actually cares about seeing in a chat. */
|
|
36
|
+
const MILESTONE_KINDS = new Set<NarrationEventDoc["kind"]>([
|
|
37
|
+
"delegated",
|
|
38
|
+
"worker_started",
|
|
39
|
+
"verified",
|
|
40
|
+
"failed",
|
|
41
|
+
"group_ready",
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
const KIND_PREFIX: Record<NarrationEventDoc["kind"], string> = {
|
|
45
|
+
delegated: "📋",
|
|
46
|
+
worker_started: "▶️",
|
|
47
|
+
tool_call: "⚙️",
|
|
48
|
+
tool_result: "⚠️",
|
|
49
|
+
verified: "✅",
|
|
50
|
+
failed: "❌",
|
|
51
|
+
group_ready: "📝",
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const DETAIL_MAX_CHARS = 200;
|
|
55
|
+
|
|
56
|
+
// ─── Mode lookup (cached) ─────────────────────────────────────────────────────
|
|
57
|
+
// Resolved per channel *type* because narration events only carry the type, not
|
|
58
|
+
// the account id. Short TTL so a settings change takes effect without a restart.
|
|
59
|
+
|
|
60
|
+
const MODE_CACHE_TTL_MS = 30_000;
|
|
61
|
+
const modeCache = new Map<string, { mode: NarrationMode; expiresAt: number }>();
|
|
62
|
+
|
|
63
|
+
export function invalidateNarrationModeCache(channelType?: string): void {
|
|
64
|
+
if (channelType) modeCache.delete(channelType);
|
|
65
|
+
else modeCache.clear();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function resolveNarrationMode(channelType: string): Promise<NarrationMode> {
|
|
69
|
+
const cached = modeCache.get(channelType);
|
|
70
|
+
if (cached && cached.expiresAt > Date.now()) return cached.mode;
|
|
71
|
+
|
|
72
|
+
let mode = DEFAULT_NARRATION_MODE;
|
|
73
|
+
try {
|
|
74
|
+
const channels = await col<ChannelDoc>("channels");
|
|
75
|
+
const row = (await channels.scan({})).find((e) => e.doc.type === channelType);
|
|
76
|
+
mode = coerceMode(row?.doc.step_delivery_mode);
|
|
77
|
+
} catch (error) {
|
|
78
|
+
log.debug(`Could not resolve narration mode for ${channelType}: ${(error as Error).message}`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
modeCache.set(channelType, { mode, expiresAt: Date.now() + MODE_CACHE_TTL_MS });
|
|
82
|
+
return mode;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ─── Filtering ────────────────────────────────────────────────────────────────
|
|
86
|
+
|
|
87
|
+
export function shouldDeliverToChannel(event: NarrationEventDoc, mode: NarrationMode): boolean {
|
|
88
|
+
if (mode === "off") return false;
|
|
89
|
+
if (MILESTONE_KINDS.has(event.kind)) return true;
|
|
90
|
+
if (mode !== "all") return false;
|
|
91
|
+
// Even in `all`, a successful tool_result only restates the tool_call that
|
|
92
|
+
// preceded it. Errors are the part worth surfacing.
|
|
93
|
+
if (event.kind === "tool_result") return event.status === "error";
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ─── Formatting ───────────────────────────────────────────────────────────────
|
|
98
|
+
|
|
99
|
+
/** Collapses whitespace and trims — raw error details carry stacks and paths. */
|
|
100
|
+
function compactDetail(detail: string): string {
|
|
101
|
+
const flat = detail.replace(/\s+/g, " ").trim();
|
|
102
|
+
if (flat.length <= DETAIL_MAX_CHARS) return flat;
|
|
103
|
+
return `${flat.slice(0, DETAIL_MAX_CHARS - 1)}…`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function formatNarrationForChannel(event: NarrationEventDoc): string {
|
|
107
|
+
const prefix = KIND_PREFIX[event.kind] ?? "•";
|
|
108
|
+
const detail = event.detail ? compactDetail(event.detail) : "";
|
|
109
|
+
return detail ? `${prefix} ${event.label}\n${detail}` : `${prefix} ${event.label}`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ─── Ordered, off-critical-path delivery ──────────────────────────────────────
|
|
113
|
+
// `publishNarration` awaits the delivery adapter, so sending inline would put a
|
|
114
|
+
// round-trip to the channel's servers inside the agent loop for every event.
|
|
115
|
+
// Each conversation gets its own promise chain: the agent loop is never blocked,
|
|
116
|
+
// and messages still arrive in the order they were produced.
|
|
117
|
+
|
|
118
|
+
const sendQueues = new Map<string, Promise<void>>();
|
|
119
|
+
|
|
120
|
+
export function enqueueChannelNarration(
|
|
121
|
+
key: string,
|
|
122
|
+
send: () => Promise<void>,
|
|
123
|
+
): void {
|
|
124
|
+
const previous = sendQueues.get(key) ?? Promise.resolve();
|
|
125
|
+
const next = previous
|
|
126
|
+
.then(send)
|
|
127
|
+
.catch((error: Error) => {
|
|
128
|
+
log.warn(`Narration delivery failed for ${key}: ${error.message}`);
|
|
129
|
+
})
|
|
130
|
+
.finally(() => {
|
|
131
|
+
// Drop the entry once this send is the last one queued, so the map does
|
|
132
|
+
// not grow with one retained promise per conversation seen.
|
|
133
|
+
if (sendQueues.get(key) === next) sendQueues.delete(key);
|
|
134
|
+
});
|
|
135
|
+
sendQueues.set(key, next);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Resolves once the narration queued for one conversation has been sent. Call
|
|
140
|
+
* before sending a turn's final answer so it cannot overtake pending progress
|
|
141
|
+
* messages, which would show the user the outcome before the steps.
|
|
142
|
+
*/
|
|
143
|
+
export async function awaitChannelNarration(key: string): Promise<void> {
|
|
144
|
+
await (sendQueues.get(key) ?? Promise.resolve());
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Test/shutdown helper: resolves once every queued narration has been sent. */
|
|
148
|
+
export async function flushChannelNarration(): Promise<void> {
|
|
149
|
+
await Promise.allSettled([...sendQueues.values()]);
|
|
150
|
+
}
|