@johpaz/hive-agents 1.0.0 → 1.0.2
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 +22498 -6889
- package/dist/tool-worker.js +6 -2
- package/dist/ui/assets/A2UIPage-BRpjnMss.js +8 -0
- package/dist/ui/assets/{AgentCreateForm-g1mQnIoJ.js → AgentCreateForm-ASjKD7Js.js} +1 -1
- package/dist/ui/assets/{AgentDetailPage-C3XkU4Ll.js → AgentDetailPage-bqJ-MS40.js} +1 -1
- package/dist/ui/assets/AgentNewPage-CPaf2C3u.js +1 -0
- package/dist/ui/assets/{AgentsPage-CNA778Eo.js → AgentsPage-BIpLG0V6.js} +1 -1
- package/dist/ui/assets/{ApiClientPage-t5DpKhmA.js → ApiClientPage-dRckcgrN.js} +1 -1
- package/dist/ui/assets/{ChannelsPage-yY6t0YTU.js → ChannelsPage-BX_hPtiN.js} +2 -2
- package/dist/ui/assets/{DashboardPage-BSeNSYg5.js → DashboardPage-KMaMaFf4.js} +2 -2
- package/dist/ui/assets/{LoginPage-eT5zDRDa.js → LoginPage-Zchu-f16.js} +1 -1
- package/dist/ui/assets/{LogsPage-Gczzzsdh.js → LogsPage-6Po7_T2u.js} +1 -1
- package/dist/ui/assets/{MeetingPage-Bu4aMMNR.js → MeetingPage-qrpYGVD-.js} +1 -1
- package/dist/ui/assets/{ModelSelector-nNOrW3te.js → ModelSelector-C8ny_pxu.js} +1 -1
- package/dist/ui/assets/{Office3DPage-B_iXEbyv.js → Office3DPage-BYwLMTCl.js} +2 -2
- package/dist/ui/assets/ProvidersPage-DP9v_1ko.js +1 -0
- package/dist/ui/assets/{RecoverPage-DMqSasKk.js → RecoverPage-BXwjLfap.js} +1 -1
- package/dist/ui/assets/SettingsPage-DD7GKtS6.js +9 -0
- package/dist/ui/assets/{SetupPage-DhcRbGgg.js → SetupPage-D7YX2io-.js} +1 -1
- package/dist/ui/assets/{WebChatPage-CWXjW4Hn.js → WebChatPage-C3cgimxd.js} +1 -1
- package/dist/ui/assets/{activity-CQuPevhB.js → activity-DZKL7dg4.js} +1 -1
- package/dist/ui/assets/{agentCapabilities-CDC6y91E.js → agentCapabilities-DuGs07XP.js} +1 -1
- package/dist/ui/assets/arrow-left-12JaXVoH.js +1 -0
- package/dist/ui/assets/arrow-right-Dbui5p0d.js +1 -0
- package/dist/ui/assets/arrow-up-right-CJBtXRrp.js +1 -0
- package/dist/ui/assets/{calendar-Be23hQGc.js → calendar-CkDsc4OJ.js} +1 -1
- package/dist/ui/assets/check-DxOMIDcl.js +1 -0
- package/dist/ui/assets/chevron-down-CObv-xyx.js +1 -0
- package/dist/ui/assets/chevron-left-C0mqwhLU.js +1 -0
- package/dist/ui/assets/chevron-right-jCt1h8Kw.js +1 -0
- package/dist/ui/assets/chevron-up-DX_5iw7O.js +1 -0
- package/dist/ui/assets/{circle-alert-BDVHxmAz.js → circle-alert-BkP6x0zQ.js} +1 -1
- package/dist/ui/assets/circle-check-CXC2AiMS.js +1 -0
- package/dist/ui/assets/{circle-x-Cb2Yer4s.js → circle-x-h4OJiHV3.js} +1 -1
- package/dist/ui/assets/{copy-33tZrzc9.js → copy-BtpYEEvV.js} +1 -1
- package/dist/ui/assets/{dialog-KOZKWbib.js → dialog-CO1WrPJc.js} +1 -1
- package/dist/ui/assets/{download-CiQqqXyz.js → download-aPuVaZik.js} +1 -1
- package/dist/ui/assets/{earth-DCvN7ynm.js → earth-sc8YJMc0.js} +1 -1
- package/dist/ui/assets/{ellipsis-vertical-BybFZDk2.js → ellipsis-vertical-DEBZJGzY.js} +1 -1
- package/dist/ui/assets/{external-link-0iNNBvZm.js → external-link-D_C_678M.js} +1 -1
- package/dist/ui/assets/{eye-C8sKSSkg.js → eye-BfN613fx.js} +1 -1
- package/dist/ui/assets/{file-text-DO8jqiJK.js → file-text-Bth5pPZX.js} +1 -1
- package/dist/ui/assets/gauge-DypSzSOE.js +1 -0
- package/dist/ui/assets/{history-BtTD1kDo.js → history-njH_sPSo.js} +1 -1
- package/dist/ui/assets/{index-Bejlp-R1.js → index-D-9yCvjP.js} +4 -4
- package/dist/ui/assets/index-wML8DaUo.css +2 -0
- package/dist/ui/assets/{info-mpk1tsNC.js → info-Def2ZFeP.js} +1 -1
- package/dist/ui/assets/{key-CoQ0qtXt.js → key-D8bkDl83.js} +1 -1
- package/dist/ui/assets/loader-circle-wLVzSdML.js +1 -0
- package/dist/ui/assets/{lock-open-Cd2aqwOd.js → lock-open-Cdopbw1b.js} +1 -1
- package/dist/ui/assets/{mail-BG0RYSkL.js → mail-BQ_YA9_b.js} +1 -1
- package/dist/ui/assets/{pause-Cme88_9s.js → pause-CvS_LzKx.js} +1 -1
- package/dist/ui/assets/{pencil-f1nJ1xhs.js → pencil-C3tPvnCk.js} +1 -1
- package/dist/ui/assets/play-C-oR-PMH.js +1 -0
- package/dist/ui/assets/plus-CF9No2td.js +1 -0
- package/dist/ui/assets/{radio-B5SpKJ-J.js → radio-dsaiFxuT.js} +1 -1
- package/dist/ui/assets/{refresh-cw-CroGQY62.js → refresh-cw-BmYQwOhh.js} +1 -1
- package/dist/ui/assets/search-CTONpTyl.js +1 -0
- package/dist/ui/assets/{select-BhbW0stK.js → select-BfRyBbi9.js} +1 -1
- package/dist/ui/assets/{send-D6whYpw-.js → send-C3o2wpLi.js} +1 -1
- package/dist/ui/assets/{settings-BX6q3MGB.js → settings-DEpdBuf2.js} +1 -1
- package/dist/ui/assets/{shield-BnGyu1xf.js → shield-gbUkSqfi.js} +1 -1
- package/dist/ui/assets/{sparkles-BcaOs_Jk.js → sparkles-Ccd1JZ3s.js} +1 -1
- package/dist/ui/assets/{square-ju5H8nrT.js → square-BrwQ6Mun.js} +1 -1
- package/dist/ui/assets/terminal-DP9j3HjM.js +1 -0
- package/dist/ui/assets/{trash-2-DjQXac_0.js → trash-2-CfCs7RhJ.js} +1 -1
- package/dist/ui/assets/{triangle-alert-B04mgMcg.js → triangle-alert-C3lWSnRr.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-DT5-4CCj.js → useHiveAgentsModelLoad-D3s2U82M.js} +1 -1
- package/dist/ui/assets/{useProviders-DSX7eVsz.js → useProviders-B3rT_xU9.js} +1 -1
- package/dist/ui/assets/{volume-x-qnVxkRSM.js → volume-x-D2h9cyml.js} +1 -1
- package/dist/ui/assets/{wifi-BA1m2dGO.js → wifi-CGQECzu2.js} +1 -1
- package/dist/ui/assets/{zap-DT7cM7YS.js → zap-B1azpiE7.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/index.ts +23 -17
- 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/canvas-manager.ts +36 -7
- 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/a2ui.ts +43 -0
- 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/runtime.ts +58 -0
- package/packages/core/src/gateway/routes/setup.ts +161 -90
- 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 +74 -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 +36 -9
- package/packages/core/src/storage/seed.ts +283 -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/A2UIPage-D4nUFe5q.js +0 -8
- package/dist/ui/assets/AgentNewPage-CEkLeA79.js +0 -1
- package/dist/ui/assets/ProvidersPage-BupHs5yO.js +0 -1
- package/dist/ui/assets/SettingsPage-B6FTSkOn.js +0 -9
- 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
|
@@ -1,100 +1,68 @@
|
|
|
1
1
|
import { col, nextId, bumpRollup } from "./hive";
|
|
2
|
-
import type { UsageRecordDoc, UsageRollupDoc } from "./collections";
|
|
2
|
+
import type { ModelDoc, UsageRecordDoc, UsageRollupDoc } from "./collections";
|
|
3
3
|
import { logger } from "../utils/logger";
|
|
4
4
|
|
|
5
5
|
const log = logger.child("usage");
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
"moonshot-v1-128k": { inputPer1M: 8.33, outputPer1M: 8.33 },
|
|
67
|
-
"moonshotai/kimi-k2.5": { inputPer1M: 0.45, outputPer1M: 2.2 },
|
|
68
|
-
"moonshotai/kimi-k2-instruct-0905": { inputPer1M: 0.45, outputPer1M: 2.2 },
|
|
69
|
-
|
|
70
|
-
// ── Meta Llama (vía OpenRouter) ──
|
|
71
|
-
"meta-llama/llama-3.3-70b-instruct": { inputPer1M: 0.88, outputPer1M: 0.88 },
|
|
72
|
-
"meta-llama/llama-4-maverick": { inputPer1M: 0.2, outputPer1M: 0.8 },
|
|
73
|
-
|
|
74
|
-
// ── Qwen (vía OpenRouter) ──
|
|
75
|
-
"qwen/qwen3.5-plus-02-15": { inputPer1M: 0.26, outputPer1M: 1.56 },
|
|
76
|
-
"qwen/qwen3.5-flash-02-23": { inputPer1M: 0.1, outputPer1M: 0.4 },
|
|
77
|
-
"qwen/qwen3-32b": { inputPer1M: 0, outputPer1M: 0 },
|
|
78
|
-
|
|
79
|
-
// ── Groq (fuente: console.groq.com/docs/models) ──
|
|
80
|
-
"llama-3.3-70b-versatile": { inputPer1M: 0.59, outputPer1M: 0.79 },
|
|
81
|
-
"llama-3.1-8b-instant": { inputPer1M: 0.05, outputPer1M: 0.08 },
|
|
82
|
-
"groq/compound": { inputPer1M: 0, outputPer1M: 0 },
|
|
83
|
-
"groq/compound-mini": { inputPer1M: 0, outputPer1M: 0 },
|
|
84
|
-
|
|
85
|
-
// ── Ollama local = siempre free ──
|
|
86
|
-
"qwen3:4b": { inputPer1M: 0, outputPer1M: 0 },
|
|
87
|
-
"qwen3:8b": { inputPer1M: 0, outputPer1M: 0 },
|
|
88
|
-
"qwen3:14b": { inputPer1M: 0, outputPer1M: 0 },
|
|
89
|
-
"llama3.2:3b": { inputPer1M: 0, outputPer1M: 0 },
|
|
90
|
-
"gemma3:9b": { inputPer1M: 0, outputPer1M: 0 },
|
|
91
|
-
};
|
|
92
|
-
|
|
93
|
-
function calculateCost(model: string, inputTokens: number, outputTokens: number): number {
|
|
94
|
-
const pricing = MODEL_PRICING[model] || { inputPer1M: 0, outputPer1M: 0 };
|
|
95
|
-
const inputCost = (inputTokens / 1_000_000) * pricing.inputPer1M;
|
|
96
|
-
const outputCost = (outputTokens / 1_000_000) * pricing.outputPer1M;
|
|
97
|
-
return inputCost + outputCost;
|
|
7
|
+
/**
|
|
8
|
+
* Costo de una llamada, en USD.
|
|
9
|
+
*
|
|
10
|
+
* El precio vive en la propia fila del modelo (`ModelDoc.input_per_1m` /
|
|
11
|
+
* `output_per_1m`), sembrada desde SEED_DATA.models. Antes había acá un mapa
|
|
12
|
+
* `MODEL_PRICING` hardcodeado en paralelo al catálogo: mantener dos listas en
|
|
13
|
+
* sincronía fallaba en silencio — un modelo sembrado sin entrada en el mapa
|
|
14
|
+
* costaba $0 sin avisar.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** Precio por id de modelo. Se llena bajo demanda y lo invalida el re-seed. */
|
|
18
|
+
let pricingCache: Map<string, { input: number; output: number } | null> | null = null;
|
|
19
|
+
|
|
20
|
+
/** Llamar cuando el catálogo cambie, para que el próximo costo relea de la BD. */
|
|
21
|
+
export function invalidateModelPricingCache(): void {
|
|
22
|
+
pricingCache = null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function loadPricing(): Promise<Map<string, { input: number; output: number } | null>> {
|
|
26
|
+
if (pricingCache) return pricingCache;
|
|
27
|
+
const cache = new Map<string, { input: number; output: number } | null>();
|
|
28
|
+
try {
|
|
29
|
+
const modelsCol = await col<ModelDoc>("models");
|
|
30
|
+
for (const row of await modelsCol.scan({})) {
|
|
31
|
+
const { input_per_1m: i, output_per_1m: o } = row.doc;
|
|
32
|
+
cache.set(row.id, i == null && o == null ? null : { input: i ?? 0, output: o ?? 0 });
|
|
33
|
+
}
|
|
34
|
+
pricingCache = cache;
|
|
35
|
+
} catch {
|
|
36
|
+
// La BD puede no estar lista todavía (arranque temprano): no cachear el
|
|
37
|
+
// resultado vacío o el costo quedaría en 0 para toda la vida del proceso.
|
|
38
|
+
return cache;
|
|
39
|
+
}
|
|
40
|
+
return cache;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Modelos ya avisados, para no repetir el warning en cada llamada. */
|
|
44
|
+
const unpricedModels = new Set<string>();
|
|
45
|
+
|
|
46
|
+
export async function calculateCost(
|
|
47
|
+
provider: string,
|
|
48
|
+
model: string,
|
|
49
|
+
inputTokens: number,
|
|
50
|
+
outputTokens: number
|
|
51
|
+
): Promise<number> {
|
|
52
|
+
const pricing = (await loadPricing()).get(model);
|
|
53
|
+
|
|
54
|
+
if (!pricing) {
|
|
55
|
+
// Sin esto un modelo sin tarifa aparece como $0.00 en el dashboard, que es
|
|
56
|
+
// indistinguible de un modelo realmente gratuito.
|
|
57
|
+
const key = `${provider}/${model}`;
|
|
58
|
+
if (!unpricedModels.has(key)) {
|
|
59
|
+
unpricedModels.add(key);
|
|
60
|
+
log.warn(`[usage] Sin tarifa para ${key} — su costo se contará como $0. Agregá inputPer1M/outputPer1M en SEED_DATA.models (storage/seed.ts).`);
|
|
61
|
+
}
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return (inputTokens / 1_000_000) * pricing.input + (outputTokens / 1_000_000) * pricing.output;
|
|
98
66
|
}
|
|
99
67
|
|
|
100
68
|
/** Hourly bucket key ("2026-07-09T14") — lexicographic order matches chronological order. */
|
|
@@ -213,7 +181,7 @@ export function recordUsage(options: {
|
|
|
213
181
|
// Fire-and-forget to avoid blocking the LLM call path.
|
|
214
182
|
Promise.resolve().then(async () => {
|
|
215
183
|
try {
|
|
216
|
-
const costUsd = calculateCost(options.model, options.inputTokens, options.outputTokens);
|
|
184
|
+
const costUsd = await calculateCost(options.provider, options.model, options.inputTokens, options.outputTokens);
|
|
217
185
|
const now = Date.now();
|
|
218
186
|
|
|
219
187
|
const id = await nextId("usageRecords");
|
|
@@ -337,36 +305,6 @@ export async function getUsageStats(hours: number = 24): Promise<UsageSummary> {
|
|
|
337
305
|
};
|
|
338
306
|
}
|
|
339
307
|
|
|
340
|
-
/**
|
|
341
|
-
* Get average cost per token for a model (input + output average)
|
|
342
|
-
*/
|
|
343
|
-
export function getAverageTokenCost(model: string): number {
|
|
344
|
-
// 1. Exact match
|
|
345
|
-
let pricing = MODEL_PRICING[model];
|
|
346
|
-
|
|
347
|
-
// 2. Try stripping a single provider prefix (e.g. "openrouter/moonshotai/kimi" → "moonshotai/kimi")
|
|
348
|
-
if (!pricing) {
|
|
349
|
-
const slashIdx = model.indexOf('/');
|
|
350
|
-
if (slashIdx !== -1) {
|
|
351
|
-
pricing = MODEL_PRICING[model.slice(slashIdx + 1)];
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
// 3. Partial match — find any key whose name is contained in the model string
|
|
356
|
-
if (!pricing) {
|
|
357
|
-
for (const [key, p] of Object.entries(MODEL_PRICING)) {
|
|
358
|
-
if (model.includes(key) || key.includes(model)) {
|
|
359
|
-
pricing = p;
|
|
360
|
-
break;
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
if (!pricing) return 0;
|
|
366
|
-
// Average of input and output cost per token
|
|
367
|
-
return (pricing.inputPer1M + pricing.outputPer1M) / 2 / 1_000_000;
|
|
368
|
-
}
|
|
369
|
-
|
|
370
308
|
/**
|
|
371
309
|
* Record TOON savings for metrics tracking
|
|
372
310
|
* This updates the usage_records table with complete TOON compression metrics
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Agents Tools -
|
|
3
|
-
*
|
|
2
|
+
* Agents Tools - 15 tools
|
|
3
|
+
*
|
|
4
4
|
* @category agents
|
|
5
5
|
*/
|
|
6
6
|
|
|
@@ -14,11 +14,8 @@ import { agentBus } from "../../events/agent-bus.ts";
|
|
|
14
14
|
import {
|
|
15
15
|
emitDelegationStarted,
|
|
16
16
|
emitDelegationFinished,
|
|
17
|
-
emitVerificationStarted,
|
|
18
|
-
emitVerificationFinished,
|
|
19
17
|
emitWorkEvent,
|
|
20
18
|
} from "../../canvas/emitter.ts";
|
|
21
|
-
import { VERIFIER_AGENT_ID } from "../../agent/acceptance-verifier.ts";
|
|
22
19
|
|
|
23
20
|
const log = logger.child("agents");
|
|
24
21
|
|
|
@@ -493,7 +490,7 @@ export const agentArchiveTool: Tool = {
|
|
|
493
490
|
|
|
494
491
|
export const taskDelegateTool: Tool = {
|
|
495
492
|
name: "task_delegate",
|
|
496
|
-
description: "Delegate a bounded task to an existing worker_id (any `agents` row: catalog-seeded or agent_create-made). The delivery
|
|
493
|
+
description: "Delegate a bounded task to an existing worker_id (any `agents` row: catalog-seeded or agent_create-made). The delivery goes through deterministic acceptance checks (no LLM); you judge anything they don't cover in your closing turn, and use task_revise to send it back with feedback if it doesn't meet its criteria. mode=sync blocks the conversation until done; mode=async enqueues and frees the conversation immediately — the user is notified automatically in this same chat when the worker finishes. Prefer async unless you expect the result in a few seconds.",
|
|
497
494
|
parameters: {
|
|
498
495
|
type: "object",
|
|
499
496
|
properties: {
|
|
@@ -721,43 +718,39 @@ export const taskDelegateTool: Tool = {
|
|
|
721
718
|
|
|
722
719
|
agentBus.notifyTaskCompleted(agentId, worker.name, 0, taskName, "", result);
|
|
723
720
|
|
|
724
|
-
//
|
|
725
|
-
// worker_id delegation (agent_create) skipped
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
const
|
|
729
|
-
|
|
730
|
-
executorAgentId: agentId,
|
|
721
|
+
// Deterministic acceptance checks now always run, closing the old gap
|
|
722
|
+
// where a plain worker_id delegation (agent_create) skipped them
|
|
723
|
+
// entirely in sync mode. No LLM call: the calling agent (usually the
|
|
724
|
+
// coordinator) judges the delivery itself in this same tool response.
|
|
725
|
+
const { runAcceptanceChecks, recordAgentOutcome } = await import("../../agent/acceptance-checks.ts");
|
|
726
|
+
const checks = await runAcceptanceChecks({
|
|
731
727
|
objective: taskDescription,
|
|
732
728
|
acceptance,
|
|
733
729
|
delivery: result,
|
|
734
|
-
|
|
735
|
-
mcpManager,
|
|
730
|
+
evidence: [result],
|
|
736
731
|
});
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
if (verification.status !== "verified") {
|
|
732
|
+
if (checks.status === "failed") {
|
|
733
|
+
await recordAgentOutcome(agentId, "harmful");
|
|
740
734
|
emitWorkEvent({
|
|
741
735
|
phase: "review_failed",
|
|
742
736
|
taskRef: syncDelegationRef,
|
|
743
737
|
taskName,
|
|
744
|
-
actorId:
|
|
738
|
+
actorId: parentAgentId || agentId,
|
|
745
739
|
targetId: agentId,
|
|
746
|
-
detail:
|
|
740
|
+
detail: checks.summary,
|
|
747
741
|
});
|
|
748
742
|
return {
|
|
749
743
|
ok: false,
|
|
750
|
-
status:
|
|
751
|
-
|
|
752
|
-
error: verdict.summary || "Independent verification did not authorize success.",
|
|
753
|
-
retry_guidance: verdict.retry_guidance,
|
|
744
|
+
status: checks.status,
|
|
745
|
+
error: checks.summary,
|
|
754
746
|
};
|
|
755
747
|
}
|
|
748
|
+
await recordAgentOutcome(agentId, "helpful");
|
|
756
749
|
emitWorkEvent({
|
|
757
750
|
phase: "review_passed",
|
|
758
751
|
taskRef: syncDelegationRef,
|
|
759
752
|
taskName,
|
|
760
|
-
actorId:
|
|
753
|
+
actorId: parentAgentId || agentId,
|
|
761
754
|
targetId: agentId,
|
|
762
755
|
});
|
|
763
756
|
emitWorkEvent({
|
|
@@ -771,7 +764,8 @@ export const taskDelegateTool: Tool = {
|
|
|
771
764
|
ok: true,
|
|
772
765
|
worker_id: agentId,
|
|
773
766
|
worker_name: worker.name,
|
|
774
|
-
|
|
767
|
+
acceptance,
|
|
768
|
+
checks,
|
|
775
769
|
result,
|
|
776
770
|
};
|
|
777
771
|
} catch (err) {
|
|
@@ -793,13 +787,190 @@ export const taskDelegateTool: Tool = {
|
|
|
793
787
|
error: errorMessage,
|
|
794
788
|
};
|
|
795
789
|
} finally {
|
|
796
|
-
emitVerificationFinished({ verifierId: VERIFIER_AGENT_ID, taskRef: syncDelegationRef });
|
|
797
790
|
emitDelegationFinished({ workerId: agentId, taskRef: syncDelegationRef });
|
|
798
791
|
await prepared.release();
|
|
799
792
|
}
|
|
800
793
|
},
|
|
801
794
|
};
|
|
802
795
|
|
|
796
|
+
// ─── task_revise ─────────────────────────────────────────────────────────────
|
|
797
|
+
|
|
798
|
+
const MAX_TASK_REVISIONS = 2;
|
|
799
|
+
|
|
800
|
+
export const taskReviseTool: Tool = {
|
|
801
|
+
name: "task_revise",
|
|
802
|
+
description: "Send a completed or blocked delegated task back to its worker with concrete feedback, instead of reporting it as done. The worker resumes on the SAME thread — it keeps its prior context, so the feedback only needs to describe what's missing. Use this when a delivery doesn't meet its acceptance criteria and you can't fix it yourself.",
|
|
803
|
+
parameters: {
|
|
804
|
+
type: "object",
|
|
805
|
+
properties: {
|
|
806
|
+
task_id: { type: "string", description: "The task_id from task_delegate's result." },
|
|
807
|
+
feedback: { type: "string", description: "Concrete, actionable feedback: what's wrong and what the worker still needs to do." },
|
|
808
|
+
acceptance: {
|
|
809
|
+
type: "array",
|
|
810
|
+
description: "Updated acceptance criteria, if they need to change. Defaults to the original task's criteria.",
|
|
811
|
+
items: {
|
|
812
|
+
type: "object",
|
|
813
|
+
properties: {
|
|
814
|
+
id: { type: "string" },
|
|
815
|
+
description: { type: "string" },
|
|
816
|
+
checkTool: { type: "string" },
|
|
817
|
+
},
|
|
818
|
+
required: ["id", "description"],
|
|
819
|
+
},
|
|
820
|
+
},
|
|
821
|
+
},
|
|
822
|
+
required: ["task_id", "feedback"],
|
|
823
|
+
},
|
|
824
|
+
execute: async (params: Record<string, unknown>, config?: any) => {
|
|
825
|
+
const taskId = params.task_id as string | undefined;
|
|
826
|
+
const feedback = params.feedback as string | undefined;
|
|
827
|
+
if (!taskId) return { ok: false, error: "Provide task_id." };
|
|
828
|
+
if (!feedback || !feedback.trim()) return { ok: false, error: "Provide feedback describing what's missing." };
|
|
829
|
+
|
|
830
|
+
const parentAgentId = config?.configurable?.agent_id ?? "";
|
|
831
|
+
if (!parentAgentId) {
|
|
832
|
+
return { ok: false, error: "Caller identity is missing (config.configurable.agent_id)." };
|
|
833
|
+
}
|
|
834
|
+
const agentsCol = await col<AgentDoc>("agents");
|
|
835
|
+
const parentEntry = await agentsCol.get(parentAgentId);
|
|
836
|
+
if (!parentEntry) return { ok: false, error: `Caller agent not found: ${parentAgentId}` };
|
|
837
|
+
const parentProviderId = fromIndexable(parentEntry.doc.provider_id);
|
|
838
|
+
const parentModelId = fromIndexable(parentEntry.doc.model_id);
|
|
839
|
+
|
|
840
|
+
const tasksCol = await col<TaskDoc>("tasks");
|
|
841
|
+
const taskEntry = await tasksCol.get(taskId);
|
|
842
|
+
if (!taskEntry) return { ok: false, error: `Task not found: ${taskId}` };
|
|
843
|
+
const task = taskEntry.doc;
|
|
844
|
+
if (task.status !== "completed" && task.status !== "blocked") {
|
|
845
|
+
return { ok: false, error: `Task ${taskId} is "${task.status}" — only completed or blocked tasks can be revised.` };
|
|
846
|
+
}
|
|
847
|
+
if ((task.attempts ?? 0) >= MAX_TASK_REVISIONS) {
|
|
848
|
+
return { ok: false, error: `Task ${taskId} already used its ${MAX_TASK_REVISIONS} revision attempt(s). Fix it yourself or report the limit to the user.` };
|
|
849
|
+
}
|
|
850
|
+
if (!task.thread_id) {
|
|
851
|
+
return { ok: false, error: `Task ${taskId} has no thread_id — cannot resume its worker.` };
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
const agentId = fromIndexable(task.agent_id);
|
|
855
|
+
const workerEntry = agentId ? await agentsCol.get(agentId) : null;
|
|
856
|
+
if (!workerEntry) return { ok: false, error: `Worker not found for task ${taskId}: ${agentId}` };
|
|
857
|
+
const worker = workerEntry.doc;
|
|
858
|
+
if (!worker.enabled) return { ok: false, error: `Worker is disabled: ${worker.name}` };
|
|
859
|
+
|
|
860
|
+
const { createRun, getRun, deserializeAcceptance } = await import("../../agent/run-store.ts");
|
|
861
|
+
const { getDurableQueue } = await import("../../gateway/durable-queue.ts");
|
|
862
|
+
const { updateDoc } = await import("../../storage/hive.ts");
|
|
863
|
+
|
|
864
|
+
const previousRun = task.run_id ? await getRun(task.run_id) : null;
|
|
865
|
+
const previousAcceptance = previousRun ? deserializeAcceptance(previousRun) : null;
|
|
866
|
+
const acceptance = (params.acceptance as AcceptanceCriterion[] | undefined) ?? previousAcceptance ?? [{ id: "objective", description: task.description ?? feedback }];
|
|
867
|
+
|
|
868
|
+
try {
|
|
869
|
+
const run = await createRun({
|
|
870
|
+
thread_id: task.thread_id,
|
|
871
|
+
agent_id: agentId!,
|
|
872
|
+
user_id: config?.configurable?.user_id ?? "",
|
|
873
|
+
channel: config?.configurable?.channel ?? null,
|
|
874
|
+
kind: "worker",
|
|
875
|
+
max_iterations: worker.max_iterations || 10,
|
|
876
|
+
resume_policy: "resume",
|
|
877
|
+
acceptance,
|
|
878
|
+
catalog_agent_id: worker.source === "catalog" ? agentId! : undefined,
|
|
879
|
+
});
|
|
880
|
+
|
|
881
|
+
const turnId = config?.configurable?.turn_id as string | undefined;
|
|
882
|
+
if (turnId) {
|
|
883
|
+
const { registerDelegatedTask } = await import("../../gateway/delegation-groups.ts");
|
|
884
|
+
await registerDelegatedTask({
|
|
885
|
+
turnId,
|
|
886
|
+
taskId,
|
|
887
|
+
threadId: config?.configurable?.thread_id ?? "",
|
|
888
|
+
channel: config?.configurable?.channel,
|
|
889
|
+
userId: config?.configurable?.user_id,
|
|
890
|
+
sessionId: config?.configurable?.session_id,
|
|
891
|
+
coordinatorAgentId: parentAgentId,
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
const queue = getDurableQueue();
|
|
896
|
+
const job = await queue.enqueue({
|
|
897
|
+
lane: `task:${taskId}`,
|
|
898
|
+
type: "worker_task",
|
|
899
|
+
run_id: run.id,
|
|
900
|
+
payload: {
|
|
901
|
+
workerId: agentId,
|
|
902
|
+
taskDescription: `${task.description ?? ""}\n\nCORRECCIÓN SOLICITADA: ${feedback}`,
|
|
903
|
+
taskName: task.name,
|
|
904
|
+
taskId,
|
|
905
|
+
acceptance,
|
|
906
|
+
parentAgentId,
|
|
907
|
+
parentProviderId,
|
|
908
|
+
parentModelId,
|
|
909
|
+
userId: config?.configurable?.user_id ?? "",
|
|
910
|
+
workspace: config?.configurable?.workspace ?? null,
|
|
911
|
+
originThreadId: config?.configurable?.thread_id ?? null,
|
|
912
|
+
originChannel: config?.configurable?.channel ?? null,
|
|
913
|
+
originSessionId: config?.configurable?.session_id ?? null,
|
|
914
|
+
turnId: turnId ?? null,
|
|
915
|
+
revision: true,
|
|
916
|
+
},
|
|
917
|
+
});
|
|
918
|
+
|
|
919
|
+
await updateDoc<TaskDoc>("tasks", taskId, {
|
|
920
|
+
status: "pending",
|
|
921
|
+
error: null,
|
|
922
|
+
job_id: job.id,
|
|
923
|
+
run_id: run.id,
|
|
924
|
+
attempts: (task.attempts ?? 0) + 1,
|
|
925
|
+
delegation_group_id: turnId ?? task.delegation_group_id ?? null,
|
|
926
|
+
updated_at: Date.now(),
|
|
927
|
+
} as Partial<TaskDoc>);
|
|
928
|
+
|
|
929
|
+
const { recordAgentOutcome } = await import("../../agent/acceptance-checks.ts");
|
|
930
|
+
await recordAgentOutcome(agentId, "harmful");
|
|
931
|
+
|
|
932
|
+
emitWorkEvent({
|
|
933
|
+
phase: "review_failed",
|
|
934
|
+
taskRef: taskId,
|
|
935
|
+
taskName: task.name,
|
|
936
|
+
actorId: parentAgentId,
|
|
937
|
+
targetId: agentId!,
|
|
938
|
+
detail: feedback,
|
|
939
|
+
});
|
|
940
|
+
|
|
941
|
+
if (turnId) {
|
|
942
|
+
const { publishNarration } = await import("../../events/narration.ts");
|
|
943
|
+
await publishNarration({
|
|
944
|
+
turnId,
|
|
945
|
+
threadId: config?.configurable?.thread_id ?? "",
|
|
946
|
+
channel: config?.configurable?.channel,
|
|
947
|
+
userId: config?.configurable?.user_id,
|
|
948
|
+
sessionId: config?.configurable?.session_id,
|
|
949
|
+
agentId: agentId!,
|
|
950
|
+
agentName: worker.name,
|
|
951
|
+
kind: "delegated",
|
|
952
|
+
status: "queued",
|
|
953
|
+
label: `Devolví “${task.name}” a ${worker.name} con correcciones`,
|
|
954
|
+
dedupeKey: `revised:${taskId}:${(task.attempts ?? 0) + 1}`,
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
return {
|
|
959
|
+
ok: true,
|
|
960
|
+
task_id: taskId,
|
|
961
|
+
job_id: job.id,
|
|
962
|
+
run_id: run.id,
|
|
963
|
+
worker_id: agentId,
|
|
964
|
+
attempts: (task.attempts ?? 0) + 1,
|
|
965
|
+
status: "queued",
|
|
966
|
+
message: `Revision enqueued (async). Use task_status with task_id="${taskId}" to check it.`,
|
|
967
|
+
};
|
|
968
|
+
} catch (err) {
|
|
969
|
+
return { ok: false, error: `Task revision failed: ${(err as Error).message}` };
|
|
970
|
+
}
|
|
971
|
+
},
|
|
972
|
+
};
|
|
973
|
+
|
|
803
974
|
// ─── task_list ──────────────────────────────────────────────────────────────
|
|
804
975
|
|
|
805
976
|
export const taskListTool: Tool = {
|
|
@@ -1044,6 +1215,7 @@ export function createTools(): Tool[] {
|
|
|
1044
1215
|
agentFindTool,
|
|
1045
1216
|
agentArchiveTool,
|
|
1046
1217
|
taskDelegateTool,
|
|
1218
|
+
taskReviseTool,
|
|
1047
1219
|
taskListTool,
|
|
1048
1220
|
taskStatusTool,
|
|
1049
1221
|
busPublishTool,
|
|
@@ -20,7 +20,7 @@ import * as cron from "./cron/index.ts";
|
|
|
20
20
|
// CLI (1)
|
|
21
21
|
import * as cli from "./cli/index.ts";
|
|
22
22
|
|
|
23
|
-
// Agents (
|
|
23
|
+
// Agents (15)
|
|
24
24
|
import * as agents from "./agents/index.ts";
|
|
25
25
|
|
|
26
26
|
// A2UI (4)
|
|
@@ -151,6 +151,7 @@ export {
|
|
|
151
151
|
agentFindTool,
|
|
152
152
|
agentArchiveTool,
|
|
153
153
|
taskDelegateTool,
|
|
154
|
+
taskReviseTool,
|
|
154
155
|
taskListTool,
|
|
155
156
|
taskStatusTool,
|
|
156
157
|
busPublishTool,
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BrowserBackend — el contrato que consumen las browser tools.
|
|
3
|
+
*
|
|
4
|
+
* Hay dos implementaciones con perfiles opuestos:
|
|
5
|
+
*
|
|
6
|
+
* - `AgentBrowserBackend` (browser-service.ts): habla con el CLI de
|
|
7
|
+
* agent-browser por subproceso. Maneja Chrome de verdad, corre headless y
|
|
8
|
+
* por lo tanto sirve en Docker y en un servidor sin display. El costo es
|
|
9
|
+
* un `Bun.spawn` por operación —medido en ~68 ms de piso— más una
|
|
10
|
+
* instalación diferida de ~75 MB y la descarga de Chrome.
|
|
11
|
+
*
|
|
12
|
+
* - `WebViewBackend` (webview-backend.ts): usa `Bun.WebView`, in-process.
|
|
13
|
+
* Sin instalación, sin subprocesos, ~0.25 ms por `evaluate`. Necesita un
|
|
14
|
+
* entorno gráfico (WebKitGTK en Linux, WebKit del sistema en macOS), así
|
|
15
|
+
* que no sirve headless.
|
|
16
|
+
*
|
|
17
|
+
* El default sigue siendo agent-browser: es el único de los dos que funciona
|
|
18
|
+
* donde suele correr el gateway. WebView se elige explícitamente.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export interface ScreenshotOptions {
|
|
22
|
+
encoding?: "blob" | "buffer" | "base64" | "shmem";
|
|
23
|
+
format?: "png" | "jpeg" | "webp";
|
|
24
|
+
quality?: number;
|
|
25
|
+
clip?: { x: number; y: number; width: number; height: number; scale: number };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface SnapshotOptions {
|
|
29
|
+
/** Colapsa nodos sin nombre accesible y recorta el texto largo. Default: true. */
|
|
30
|
+
compact?: boolean;
|
|
31
|
+
/** Profundidad máxima del árbol. */
|
|
32
|
+
depth?: number;
|
|
33
|
+
/** Sólo elementos accionables (links, botones, inputs...). */
|
|
34
|
+
interactiveOnly?: boolean;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* La superficie que las tools de `tools/web/` realmente usan. Se mantuvo
|
|
39
|
+
* deliberadamente chica: cualquier método que se agregue acá hay que
|
|
40
|
+
* implementarlo en los dos backends.
|
|
41
|
+
*/
|
|
42
|
+
export interface BrowserBackend {
|
|
43
|
+
readonly url: string;
|
|
44
|
+
readonly title: string;
|
|
45
|
+
readonly loading: boolean;
|
|
46
|
+
|
|
47
|
+
navigate(url: string): Promise<void>;
|
|
48
|
+
evaluate<T = unknown>(script: string): Promise<T>;
|
|
49
|
+
screenshot(options?: ScreenshotOptions): Promise<string>;
|
|
50
|
+
/** Árbol de accesibilidad en texto — lo que ve el modelo en vez del HTML crudo. */
|
|
51
|
+
snapshot(options?: SnapshotOptions): Promise<string>;
|
|
52
|
+
click(selector: string, options?: Record<string, unknown>): Promise<void>;
|
|
53
|
+
type(text: string): Promise<void>;
|
|
54
|
+
typeIn(selector: string, text: string): Promise<void>;
|
|
55
|
+
fill(selector: string, text: string): Promise<void>;
|
|
56
|
+
press(key: string, options?: { modifiers?: string[] }): Promise<void>;
|
|
57
|
+
scroll(dx: number, dy: number): Promise<void>;
|
|
58
|
+
scrollTo(selector: string, options?: { behavior?: "smooth" | "instant" }): Promise<void>;
|
|
59
|
+
back(): Promise<void>;
|
|
60
|
+
forward(): Promise<void>;
|
|
61
|
+
reload(): Promise<void>;
|
|
62
|
+
resize(width: number, height: number): Promise<void>;
|
|
63
|
+
/** Captura de un elemento puntual; el backend puede recortar sobre el viewport. */
|
|
64
|
+
screenshotElement(selector: string): Promise<string>;
|
|
65
|
+
close(): void;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type BrowserBackendKind = "agent-browser" | "webview";
|
|
69
|
+
|
|
70
|
+
/** `auto` resuelve a webview si el runtime lo soporta; si no, agent-browser. */
|
|
71
|
+
export type BrowserBackendPreference = BrowserBackendKind | "auto";
|
|
72
|
+
|
|
73
|
+
/** Motor que usa `Bun.WebView` por debajo. */
|
|
74
|
+
export type WebViewEngine = "webkit" | "chrome";
|
|
75
|
+
|
|
76
|
+
const CHROME_PATHS = [
|
|
77
|
+
"/usr/bin/google-chrome",
|
|
78
|
+
"/usr/bin/google-chrome-stable",
|
|
79
|
+
"/usr/bin/chromium",
|
|
80
|
+
"/usr/bin/chromium-browser",
|
|
81
|
+
"/snap/bin/chromium",
|
|
82
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
83
|
+
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
84
|
+
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
|
85
|
+
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
|
86
|
+
];
|
|
87
|
+
|
|
88
|
+
/** Chrome instalado en el sistema — `Bun.WebView` con motor chrome lo necesita. */
|
|
89
|
+
export function findChrome(): string | null {
|
|
90
|
+
if (process.env.BUN_CHROME_PATH) return process.env.BUN_CHROME_PATH;
|
|
91
|
+
const { existsSync } = require("node:fs") as typeof import("node:fs");
|
|
92
|
+
for (const candidate of CHROME_PATHS) {
|
|
93
|
+
if (existsSync(candidate)) return candidate;
|
|
94
|
+
}
|
|
95
|
+
// Último recurso: lo que esté en el PATH del usuario.
|
|
96
|
+
const home = process.env.HOME;
|
|
97
|
+
if (home) {
|
|
98
|
+
for (const name of ["google-chrome", "chromium"]) {
|
|
99
|
+
const local = `${home}/.local/bin/${name}`;
|
|
100
|
+
if (existsSync(local)) return local;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Motor a usar. WebKit no tiene dependencias externas pero sólo existe en macOS;
|
|
108
|
+
* Chrome corre headless en cualquier lado —incluido Docker— siempre que el
|
|
109
|
+
* binario esté instalado.
|
|
110
|
+
*/
|
|
111
|
+
export function resolveWebViewEngine(): WebViewEngine | null {
|
|
112
|
+
if (process.platform === "darwin") return "webkit";
|
|
113
|
+
return findChrome() ? "chrome" : null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** `Bun.WebView` existe desde Bun 1.3; además hace falta un motor utilizable. */
|
|
117
|
+
export function isWebViewSupported(): boolean {
|
|
118
|
+
if (typeof (globalThis as { Bun?: { WebView?: unknown } }).Bun?.WebView !== "function") return false;
|
|
119
|
+
return resolveWebViewEngine() !== null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function resolveBackendKind(
|
|
123
|
+
preference: BrowserBackendPreference | undefined,
|
|
124
|
+
): BrowserBackendKind {
|
|
125
|
+
const wanted = process.env.HIVE_BROWSER_BACKEND ?? preference ?? "agent-browser";
|
|
126
|
+
if (wanted === "webview") return "webview";
|
|
127
|
+
if (wanted === "auto") return isWebViewSupported() ? "webview" : "agent-browser";
|
|
128
|
+
return "agent-browser";
|
|
129
|
+
}
|