@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
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* acceptance-checks — deterministic acceptance checking, no LLM.
|
|
3
|
+
*
|
|
4
|
+
* Replaces the independent acceptance_verifier agent loop (which ran a full
|
|
5
|
+
* agent-loop, up to 3 times, just to re-derive a verdict the worker's own
|
|
6
|
+
* structured output already implies). This runs whatever deterministic
|
|
7
|
+
* checkTool each criterion declares, inspects any artifact_id found in the
|
|
8
|
+
* evidence, and applies cheap delivery gates — zero LLM calls.
|
|
9
|
+
*
|
|
10
|
+
* When nothing deterministic applies to a criterion, the result is
|
|
11
|
+
* "unchecked", not a failure: that's exactly the case the coordinator's
|
|
12
|
+
* closing turn (already paid for, via the delegation-group fan-in) is meant
|
|
13
|
+
* to judge using this checks result plus the raw evidence.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { col } from "../storage/hive";
|
|
17
|
+
import type { AgentDoc } from "../storage/collections";
|
|
18
|
+
import type { AcceptanceCriterion } from "./run-store";
|
|
19
|
+
import { interpretCheckResult } from "./goal-runner";
|
|
20
|
+
import { inspectArtifact } from "../artifacts/store";
|
|
21
|
+
import { loadConfig } from "../config/loader";
|
|
22
|
+
import { logger } from "../utils/logger";
|
|
23
|
+
|
|
24
|
+
const log = logger.child("acceptance-checks");
|
|
25
|
+
|
|
26
|
+
export type CheckStatus = "passed" | "failed" | "unchecked";
|
|
27
|
+
|
|
28
|
+
export interface AcceptanceCheckResult {
|
|
29
|
+
criterion_id: string;
|
|
30
|
+
/** checkTool name, "artifact_inspect", "delivery_gate", or "none". */
|
|
31
|
+
check: string;
|
|
32
|
+
/** null when no deterministic check applied to this criterion. */
|
|
33
|
+
met: boolean | null;
|
|
34
|
+
detail: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface AcceptanceChecks {
|
|
38
|
+
status: CheckStatus;
|
|
39
|
+
results: AcceptanceCheckResult[];
|
|
40
|
+
summary: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function sanitizeDiagnostic(value: string, limit = 1000): string {
|
|
44
|
+
return value
|
|
45
|
+
.replace(
|
|
46
|
+
// El esquema de auth va aparte: sin el grupo opcional, "authorization:
|
|
47
|
+
// Bearer <token>" consumía sólo "Bearer" y dejaba el token en claro.
|
|
48
|
+
/(api[_-]?key|token|authorization|secret)(["'=:\s]+)(?:(bearer|basic)\s+)?[^\s,}"']+/gi,
|
|
49
|
+
(_match, key: string, separator: string, scheme?: string) =>
|
|
50
|
+
`${key}${separator}${scheme ? `${scheme} ` : ""}[REDACTED]`,
|
|
51
|
+
)
|
|
52
|
+
.slice(0, limit);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function runCheckTool(criterion: AcceptanceCriterion, objective: string): Promise<AcceptanceCheckResult | null> {
|
|
56
|
+
if (!criterion.checkTool) return null;
|
|
57
|
+
try {
|
|
58
|
+
const { executeToolBatch } = await import("../tool-runtime");
|
|
59
|
+
const { createAllTools } = await import("../tools/index");
|
|
60
|
+
const allTools = createAllTools(loadConfig());
|
|
61
|
+
const toolDef = allTools.find((t) => t.name === criterion.checkTool);
|
|
62
|
+
if (!toolDef) {
|
|
63
|
+
log.warn(`[acceptance-checks] Check tool "${criterion.checkTool}" not found in the tool registry`);
|
|
64
|
+
return { criterion_id: criterion.id, check: criterion.checkTool, met: null, detail: "Check tool not found in registry" };
|
|
65
|
+
}
|
|
66
|
+
const toolResults = await executeToolBatch({
|
|
67
|
+
toolCalls: [{
|
|
68
|
+
id: `check-${criterion.id}`,
|
|
69
|
+
function: { name: criterion.checkTool, arguments: JSON.stringify({ goal: criterion.description || objective }) },
|
|
70
|
+
}],
|
|
71
|
+
allTools,
|
|
72
|
+
toolConfig: {},
|
|
73
|
+
});
|
|
74
|
+
const result = toolResults[0];
|
|
75
|
+
if (!result?.ok) {
|
|
76
|
+
return { criterion_id: criterion.id, check: criterion.checkTool, met: false, detail: `Check tool failed: ${result?.error?.message ?? "unknown"}` };
|
|
77
|
+
}
|
|
78
|
+
const interpreted = interpretCheckResult(result.result);
|
|
79
|
+
return { criterion_id: criterion.id, check: criterion.checkTool, met: interpreted.met, detail: interpreted.reason };
|
|
80
|
+
} catch (err) {
|
|
81
|
+
log.warn(`[acceptance-checks] Check tool "${criterion.checkTool}" errored: ${(err as Error).message}`);
|
|
82
|
+
return { criterion_id: criterion.id, check: criterion.checkTool, met: false, detail: `Check tool error: ${(err as Error).message}` };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function artifactChecks(evidence: string[]): Promise<AcceptanceCheckResult[]> {
|
|
87
|
+
const artifactIds = new Set<string>();
|
|
88
|
+
for (const item of evidence) {
|
|
89
|
+
for (const match of String(item).matchAll(/artifact_id:\s*["']?([0-9a-f-]{36})["']?/gi)) {
|
|
90
|
+
if (match[1]) artifactIds.add(match[1]);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const results: AcceptanceCheckResult[] = [];
|
|
94
|
+
for (const artifactId of artifactIds) {
|
|
95
|
+
const inspection = await inspectArtifact(artifactId);
|
|
96
|
+
const ok = inspection.ok === true;
|
|
97
|
+
results.push({
|
|
98
|
+
criterion_id: "artifact",
|
|
99
|
+
check: "artifact_inspect",
|
|
100
|
+
met: ok,
|
|
101
|
+
detail: ok ? `Artifact ${artifactId} verified` : `Artifact ${artifactId} inspection failed: ${JSON.stringify(inspection)}`,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
return results;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Matches the worker's own documented output contract (agent-catalog.ts buildSystemPrompt): "status: completed|needs_input|partial|failed". */
|
|
108
|
+
function selfDeclaredFailure(delivery: string): AcceptanceCheckResult | null {
|
|
109
|
+
const match = delivery.match(/(?:^|\n)\s*-?\s*status\s*:\s*(completed|needs_input|partial|failed)/i);
|
|
110
|
+
if (!match || match[1].toLowerCase() !== "failed") return null;
|
|
111
|
+
return { criterion_id: "delivery", check: "delivery_gate", met: false, detail: "El worker declaró status: failed" };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function runAcceptanceChecks(input: {
|
|
115
|
+
objective: string;
|
|
116
|
+
acceptance?: AcceptanceCriterion[] | null;
|
|
117
|
+
delivery: string;
|
|
118
|
+
evidence?: string[];
|
|
119
|
+
}): Promise<AcceptanceChecks> {
|
|
120
|
+
const criteria = input.acceptance?.length ? input.acceptance : [];
|
|
121
|
+
const evidence = input.evidence ?? [];
|
|
122
|
+
const results: AcceptanceCheckResult[] = [];
|
|
123
|
+
|
|
124
|
+
if (!input.delivery || !input.delivery.trim()) {
|
|
125
|
+
results.push({ criterion_id: "delivery", check: "delivery_gate", met: false, detail: "Empty delivery" });
|
|
126
|
+
} else {
|
|
127
|
+
const declared = selfDeclaredFailure(input.delivery);
|
|
128
|
+
if (declared) results.push(declared);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
for (const criterion of criteria) {
|
|
132
|
+
const checked = await runCheckTool(criterion, input.objective);
|
|
133
|
+
if (checked) results.push(checked);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
results.push(...(await artifactChecks(evidence)));
|
|
137
|
+
|
|
138
|
+
const anyFailed = results.some((r) => r.met === false);
|
|
139
|
+
const anyPassed = results.some((r) => r.met === true);
|
|
140
|
+
const status: CheckStatus = anyFailed ? "failed" : anyPassed ? "passed" : "unchecked";
|
|
141
|
+
|
|
142
|
+
const summary = results.length
|
|
143
|
+
? results.map((r) => `${r.met === true ? "✅" : r.met === false ? "❌" : "◌"} ${r.check}: ${sanitizeDiagnostic(r.detail, 300)}`).join("\n")
|
|
144
|
+
: "Sin checks determinísticos aplicables — requiere juicio del coordinador.";
|
|
145
|
+
|
|
146
|
+
return { status, results, summary };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** ACE counters live directly on the executor's AgentDoc row. */
|
|
150
|
+
export async function recordAgentOutcome(
|
|
151
|
+
agentId: string | null | undefined,
|
|
152
|
+
outcome: "helpful" | "harmful",
|
|
153
|
+
): Promise<void> {
|
|
154
|
+
if (!agentId) return;
|
|
155
|
+
const agents = await col<AgentDoc>("agents");
|
|
156
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
157
|
+
const current = await agents.get(agentId);
|
|
158
|
+
if (!current) return;
|
|
159
|
+
try {
|
|
160
|
+
await agents.put(agentId, {
|
|
161
|
+
...current.doc,
|
|
162
|
+
helpful_count: (current.doc.helpful_count ?? 0) + (outcome === "helpful" ? 1 : 0),
|
|
163
|
+
harmful_count: (current.doc.harmful_count ?? 0) + (outcome === "harmful" ? 1 : 0),
|
|
164
|
+
updated_at: Date.now(),
|
|
165
|
+
}, { expectedVersion: current.version });
|
|
166
|
+
return;
|
|
167
|
+
} catch {
|
|
168
|
+
// Retry OCC conflicts; another outcome may have updated the same agent concurrently.
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
log.warn(`[acceptance-checks] Could not update ACE counters for ${agentId}`);
|
|
172
|
+
}
|
|
@@ -64,12 +64,6 @@ const CODE_MODEL: AgentModelOverride = {
|
|
|
64
64
|
fallback: "general",
|
|
65
65
|
};
|
|
66
66
|
|
|
67
|
-
const VERIFIER_MODEL: AgentModelOverride = {
|
|
68
|
-
required_capabilities: ["reasoning", "function_calling"],
|
|
69
|
-
fallback: "general",
|
|
70
|
-
prefer_different_family: true,
|
|
71
|
-
};
|
|
72
|
-
|
|
73
67
|
const CATALOG_PERSONAS: CatalogPersona[] = [
|
|
74
68
|
{
|
|
75
69
|
id: "web_researcher",
|
|
@@ -241,36 +235,6 @@ const CATALOG_PERSONAS: CatalogPersona[] = [
|
|
|
241
235
|
workspaceScope: { kind: "resource", resource_types: ["http_endpoint"] },
|
|
242
236
|
acceptance: [{ id: "http", description: "El status y el contrato de respuesta coinciden con lo esperado." }],
|
|
243
237
|
},
|
|
244
|
-
{
|
|
245
|
-
id: "acceptance_verifier",
|
|
246
|
-
name: "Verificador de cumplimiento",
|
|
247
|
-
description: "Verifica de forma independiente que una tarea cumplió todos sus criterios antes de autorizar que el principal reporte éxito.",
|
|
248
|
-
role: "Sos la puerta independiente de aceptación de Hive. Evaluás resultados; nunca ejecutás ni reparás la tarea original.",
|
|
249
|
-
receives: "Objetivo original, criterios, resultado del ejecutor, trazas, artefactos, checks determinísticos y epochs.",
|
|
250
|
-
workflow: [
|
|
251
|
-
"Evaluá cada criterio por separado y rechazá criterios sin evidencia suficiente.",
|
|
252
|
-
"Preferí checks determinísticos y readbacks seguros a afirmaciones del ejecutor.",
|
|
253
|
-
"Identificá evidencia contradictoria, efectos no comprobados y límites.",
|
|
254
|
-
"Emití verified solo si todos los criterios están demostrados; en otro caso emití rejected o needs_evidence.",
|
|
255
|
-
],
|
|
256
|
-
prohibitions: [
|
|
257
|
-
...COMMON_PROHIBITIONS,
|
|
258
|
-
"No modificás artefactos, no corregís el trabajo y no aceptás la autoafirmación del ejecutor como evidencia.",
|
|
259
|
-
"No usás tools mutantes, shell, clicks, formularios, creación, eliminación ni notificaciones.",
|
|
260
|
-
],
|
|
261
|
-
quality: "Todo veredicto es reproducible, criterio por criterio, y ningún éxito se autoriza con evidencia faltante.",
|
|
262
|
-
routingExamples: ["verificar una tarea delegada", "auditar criterios de aceptación", "autorizar proof packet"],
|
|
263
|
-
routingExclusions: ["responder una pregunta del usuario", "ejecutar o reparar la tarea"],
|
|
264
|
-
tools: [
|
|
265
|
-
"fs_read", "fs_exists", "fs_list", "web_fetch",
|
|
266
|
-
"browser_navigate", "browser_extract", "browser_screenshot", "artifact_inspect",
|
|
267
|
-
"office_leer_*", "cron.list", "cron.history", "task_status",
|
|
268
|
-
],
|
|
269
|
-
skills: ["acceptance_verification"],
|
|
270
|
-
workspaceScope: { kind: "resource", resource_types: ["verification_evidence", "workspace_readonly"] },
|
|
271
|
-
acceptance: [{ id: "all_criteria", description: "Cada criterio tiene evidencia independiente suficiente." }],
|
|
272
|
-
modelOverride: VERIFIER_MODEL,
|
|
273
|
-
},
|
|
274
238
|
];
|
|
275
239
|
|
|
276
240
|
/**
|
|
@@ -299,7 +263,7 @@ export function createSeedCatalogAgents(now = Date.now()): AgentDoc[] {
|
|
|
299
263
|
skills_json: JSON.stringify(s.skills),
|
|
300
264
|
active_mcp_json: null,
|
|
301
265
|
parent_id: toIndexable(null),
|
|
302
|
-
max_iterations:
|
|
266
|
+
max_iterations: 20,
|
|
303
267
|
workspace: null,
|
|
304
268
|
lastTraceAt: null,
|
|
305
269
|
created_at: now,
|
|
@@ -26,7 +26,6 @@ import { emitCanvas } from "../canvas/emitter"
|
|
|
26
26
|
import type { MCPClientManager } from "@johpaz/hive-agents-mcp"
|
|
27
27
|
import { compileContext } from "./context-compiler"
|
|
28
28
|
import { formatToolResult } from "../utils/toon"
|
|
29
|
-
import { getAverageTokenCost } from "../storage/usage"
|
|
30
29
|
import { resolveUserId, resolveAgentId } from "../storage/onboarding"
|
|
31
30
|
import type { ContentPart } from "../multimodal/types"
|
|
32
31
|
import { loadConfig } from "../config/loader"
|
|
@@ -47,6 +46,7 @@ import {
|
|
|
47
46
|
type RunCheckpointState,
|
|
48
47
|
} from "./run-store"
|
|
49
48
|
import { publishNarration } from "../events/narration"
|
|
49
|
+
import { getNarration } from "../events/tool-narration"
|
|
50
50
|
|
|
51
51
|
const log = logger.child("agent-loop")
|
|
52
52
|
|
|
@@ -523,6 +523,17 @@ export async function* runAgent(
|
|
|
523
523
|
await opts.onStep({ type: "text", message: response.content })
|
|
524
524
|
}
|
|
525
525
|
|
|
526
|
+
// ── Provider failure → surface it, but never let it enter the history ───
|
|
527
|
+
// callLLM returns errors as a normal response whose `content` is the error
|
|
528
|
+
// text. That text is for the user's screen only: persisting it would make
|
|
529
|
+
// the next turn replay a provider outage as something the agent "said".
|
|
530
|
+
if (response.stop_reason === "error") {
|
|
531
|
+
log.error(`[agent-loop] LLM call failed at iteration ${iterations}: ${response.error?.message ?? response.content}`)
|
|
532
|
+
finalContent = response.content?.trim() || ""
|
|
533
|
+
finalEmitted = true // already yielded above as the agent chunk
|
|
534
|
+
break
|
|
535
|
+
}
|
|
536
|
+
|
|
526
537
|
// ── No tool calls → final response ──────────────────────────────────
|
|
527
538
|
if (!response.tool_calls?.length || response.stop_reason !== "tool_calls") {
|
|
528
539
|
finalContent = response.content?.trim() || ""
|
|
@@ -576,7 +587,9 @@ export async function* runAgent(
|
|
|
576
587
|
agentName,
|
|
577
588
|
kind: "tool_call",
|
|
578
589
|
status: "running",
|
|
579
|
-
label
|
|
590
|
+
// Human-readable text, not the raw tool id — this label is what a
|
|
591
|
+
// WhatsApp/Telegram user reads.
|
|
592
|
+
label: `${agentName}: ${getNarration(toolName)}`,
|
|
580
593
|
dedupeKey: `tool_call:${iterations}:${tc.id}:${toolName}`,
|
|
581
594
|
})
|
|
582
595
|
}
|
|
@@ -1045,6 +1058,12 @@ export async function* runAgent(
|
|
|
1045
1058
|
totalInputTokens += synthesis.usage.input_tokens
|
|
1046
1059
|
totalOutputTokens += synthesis.usage.output_tokens
|
|
1047
1060
|
}
|
|
1061
|
+
// A provider failure comes back as non-empty `content`, which the
|
|
1062
|
+
// empty-content check above would happily accept as a valid synthesis and
|
|
1063
|
+
// persist. Raise instead so the retry/AgentSynthesisError path runs.
|
|
1064
|
+
if (synthesis.stop_reason === "error") {
|
|
1065
|
+
throw new Error(synthesis.error?.message ?? synthesis.content)
|
|
1066
|
+
}
|
|
1048
1067
|
return synthesis.content
|
|
1049
1068
|
})
|
|
1050
1069
|
if (!opts.isolated) {
|
|
@@ -90,7 +90,6 @@ export async function syncCatalogAgentsToIndex(): Promise<void> {
|
|
|
90
90
|
|
|
91
91
|
export function renderAgentRoutingCatalog(agents: AgentDoc[]): string {
|
|
92
92
|
return agents
|
|
93
|
-
.filter((a) => a.id !== "acceptance_verifier")
|
|
94
93
|
.map((a) => {
|
|
95
94
|
const exclusions = a.routing_exclusions_json
|
|
96
95
|
? JSON.parse(a.routing_exclusions_json) as string[]
|
|
@@ -59,7 +59,10 @@ export async function maybeCompact(
|
|
|
59
59
|
const modelId = fromIndexable(coordinators[0]?.doc.model_id ?? null)
|
|
60
60
|
if (modelId) {
|
|
61
61
|
const modelsCol = await col<ModelDoc>("models")
|
|
62
|
-
|
|
62
|
+
// El id se busca completo: recortar el primer segmento rompía cualquier
|
|
63
|
+
// modelo cuyo nombre lleve barra (meta/llama-3.3-70b-instruct buscaba
|
|
64
|
+
// "llama-3.3-70b-instruct", no encontraba nada y caía al default).
|
|
65
|
+
const modelEntry = await modelsCol.get(modelId)
|
|
63
66
|
if (modelEntry?.doc.context_window) {
|
|
64
67
|
effectiveThreshold = Math.floor(modelEntry.doc.context_window * 0.25)
|
|
65
68
|
}
|
|
@@ -161,6 +164,18 @@ async function compactThread(
|
|
|
161
164
|
],
|
|
162
165
|
})
|
|
163
166
|
|
|
167
|
+
// A failed provider call still returns a populated `content` (the error text),
|
|
168
|
+
// so this has to gate on stop_reason — otherwise the summary that permanently
|
|
169
|
+
// replaces N messages of history becomes "[LLM Error] ...". Skipping leaves the
|
|
170
|
+
// thread uncompacted, which is recoverable; saving is not.
|
|
171
|
+
if (summaryResponse.stop_reason === "error") {
|
|
172
|
+
log.warn(
|
|
173
|
+
`[compaction] Summarizer call failed (${summaryResponse.error?.message ?? "unknown error"}) — `
|
|
174
|
+
+ `keeping thread ${threadId} uncompacted rather than saving the error as its summary`
|
|
175
|
+
)
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
|
|
164
179
|
const summary = summaryResponse.content.trim()
|
|
165
180
|
if (!summary) return
|
|
166
181
|
|
|
@@ -214,7 +214,9 @@ export async function compileContext(opts: {
|
|
|
214
214
|
if (agent.model_id) {
|
|
215
215
|
try {
|
|
216
216
|
const modelsCol = await col<ModelDoc>("models")
|
|
217
|
-
|
|
217
|
+
// Id completo: el recorte del primer segmento fallaba para todo modelo
|
|
218
|
+
// con barra en el nombre y dejaba el context window en el default.
|
|
219
|
+
const modelEntry = await modelsCol.get(agent.model_id)
|
|
218
220
|
if (modelEntry?.doc.context_window) modelContextWindow = modelEntry.doc.context_window
|
|
219
221
|
} catch { /* use default */ }
|
|
220
222
|
}
|
|
@@ -53,7 +53,7 @@ export function isInternalSource(source: string | null | undefined): boolean {
|
|
|
53
53
|
|
|
54
54
|
export function formatInternalEvent(source: string, content: string): string {
|
|
55
55
|
return `<hive:internal_event source="${source}">\n` +
|
|
56
|
-
`Evento interno del sistema — NO es un mensaje del usuario. No lo cites literalmente, no expongas IDs internos (task_id, worker_id
|
|
56
|
+
`Evento interno del sistema — NO es un mensaje del usuario. No lo cites literalmente, no expongas IDs internos (task_id, worker_id) ni JSON crudo. Respondé al usuario de forma natural y breve.\n\n` +
|
|
57
57
|
`${content}\n` +
|
|
58
58
|
`</hive:internal_event>`
|
|
59
59
|
}
|
|
@@ -17,8 +17,6 @@ const MCP_IDLE_TTL_MS = 2 * 60_000;
|
|
|
17
17
|
|
|
18
18
|
export interface PrepareDelegationOptions {
|
|
19
19
|
workspace: string | null;
|
|
20
|
-
/** Internal-only transient scope used by the independent verifier for readback. */
|
|
21
|
-
taskScopedMcpServerIds?: string[];
|
|
22
20
|
/** Fallback provider/model when the target row has none of its own (catalog agents are seeded without one — inherits the parent/coordinator's). */
|
|
23
21
|
parentProviderId?: string | null;
|
|
24
22
|
parentModelId?: string | null;
|
|
@@ -190,12 +188,7 @@ export async function prepareDelegation(agentId: string, opts: PrepareDelegation
|
|
|
190
188
|
|
|
191
189
|
const skillIds = agentDoc.skills_json ? await validateSkillIds(JSON.parse(agentDoc.skills_json)) : [];
|
|
192
190
|
|
|
193
|
-
const
|
|
194
|
-
if (taskScopedMcpIds.length > 0 && agentId !== "acceptance_verifier") {
|
|
195
|
-
throw new Error(`Agent ${agentId} does not allow transient MCP servers`);
|
|
196
|
-
}
|
|
197
|
-
const fixedMcpIds: string[] = agentDoc.mcp_server_ids_json ? JSON.parse(agentDoc.mcp_server_ids_json) : [];
|
|
198
|
-
const requestedMcp = [...new Set([...fixedMcpIds, ...taskScopedMcpIds])];
|
|
191
|
+
const requestedMcp: string[] = agentDoc.mcp_server_ids_json ? JSON.parse(agentDoc.mcp_server_ids_json) : [];
|
|
199
192
|
if (requestedMcp.length > 0 && !opts.mcpManager) throw new Error("MCP servers requested but MCP manager is unavailable");
|
|
200
193
|
|
|
201
194
|
const acquired: string[] = [];
|
|
@@ -20,6 +20,7 @@ import { createRun, type AcceptanceCriterion } from "./run-store";
|
|
|
20
20
|
import { clearOldToolResults } from "./compaction";
|
|
21
21
|
import { loadConfig } from "../config/loader";
|
|
22
22
|
import { getDurableQueue } from "../gateway/durable-queue";
|
|
23
|
+
import { recordLLMUsage } from "./tracer";
|
|
23
24
|
|
|
24
25
|
export type { AcceptanceCriterion } from "./run-store";
|
|
25
26
|
|
|
@@ -122,14 +123,92 @@ export async function runGoal(opts: GoalRunOptions): Promise<GoalRunResult> {
|
|
|
122
123
|
};
|
|
123
124
|
}
|
|
124
125
|
|
|
126
|
+
/** Runs a deterministic goal_check_tool, no LLM involved. */
|
|
127
|
+
async function runDeterministicCheck(checkTool: string, goal: string): Promise<{ met: boolean; reason: string } | null> {
|
|
128
|
+
try {
|
|
129
|
+
const { executeToolBatch } = await import("../tool-runtime");
|
|
130
|
+
const { createAllTools } = await import("../tools/index");
|
|
131
|
+
const allTools = createAllTools(loadConfig());
|
|
132
|
+
const toolDef = allTools.find((t) => t.name === checkTool);
|
|
133
|
+
if (!toolDef) {
|
|
134
|
+
log.warn(`[verifyGoal] Check tool "${checkTool}" not found in the tool registry — falling back to LLM verifier`);
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
const toolResults = await executeToolBatch({
|
|
138
|
+
toolCalls: [{
|
|
139
|
+
id: "goal-check",
|
|
140
|
+
function: { name: checkTool, arguments: JSON.stringify({ goal }) },
|
|
141
|
+
}],
|
|
142
|
+
allTools,
|
|
143
|
+
toolConfig: {},
|
|
144
|
+
});
|
|
145
|
+
const result = toolResults[0];
|
|
146
|
+
if (result?.ok) return interpretCheckResult(result.result);
|
|
147
|
+
return { met: false, reason: `Check tool failed: ${result?.error?.message ?? "unknown"}` };
|
|
148
|
+
} catch (err) {
|
|
149
|
+
log.warn(`[verifyGoal] Check tool "${checkTool}" failed: ${(err as Error).message}`);
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Judges every criterion that has no deterministic checkTool with a SINGLE
|
|
156
|
+
* LLM call (not one call per criterion) — the model returns a verdict per
|
|
157
|
+
* criterion id in one structured response.
|
|
158
|
+
*/
|
|
159
|
+
async function judgeCriteriaWithLLM(
|
|
160
|
+
criteria: AcceptanceCriterion[],
|
|
161
|
+
messages: LLMMessage[],
|
|
162
|
+
providerCfg: any,
|
|
163
|
+
): Promise<AcceptanceResult[]> {
|
|
164
|
+
try {
|
|
165
|
+
const verificationMessages: LLMMessage[] = [
|
|
166
|
+
...clearOldToolResults(messages),
|
|
167
|
+
{
|
|
168
|
+
role: "user",
|
|
169
|
+
content: `Evaluá si cada uno de los siguientes criterios de aceptación se cumplió, basándote en la conversación anterior.\n\nCriterios:\n${criteria.map((c) => `- ${c.id}: ${c.description}`).join("\n")}\n\nRespondé en JSON estricto, un resultado por criterio:\n{"results":[{"id":"...","met":true/false,"reason":"explicación breve"}]}`,
|
|
170
|
+
},
|
|
171
|
+
];
|
|
172
|
+
|
|
173
|
+
const response = await callLLM({ ...providerCfg, messages: verificationMessages, tools: undefined });
|
|
174
|
+
if (providerCfg.provider && providerCfg.model && response.usage) {
|
|
175
|
+
recordLLMUsage({
|
|
176
|
+
provider: providerCfg.provider,
|
|
177
|
+
model: providerCfg.model,
|
|
178
|
+
inputTokens: response.usage.input_tokens ?? 0,
|
|
179
|
+
outputTokens: response.usage.output_tokens ?? 0,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Without this the error text falls through to JSON.parse and the catch below
|
|
184
|
+
// reports a bogus "Unexpected token" instead of the actual provider failure.
|
|
185
|
+
if (response.stop_reason === "error") {
|
|
186
|
+
throw new Error(response.error?.message ?? response.content);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const content = response.content?.trim() || "";
|
|
190
|
+
const candidate = content.slice(content.indexOf("{"), content.lastIndexOf("}") + 1);
|
|
191
|
+
const parsed = JSON.parse(candidate) as { results?: Array<{ id: string; met: boolean; reason?: string }> };
|
|
192
|
+
const byId = new Map((parsed.results ?? []).map((r) => [r.id, r]));
|
|
193
|
+
return criteria.map((c) => {
|
|
194
|
+
const r = byId.get(c.id);
|
|
195
|
+
return { id: c.id, description: c.description, met: r?.met === true, evidence: r?.reason || "El modelo no evaluó este criterio" };
|
|
196
|
+
});
|
|
197
|
+
} catch (err) {
|
|
198
|
+
log.warn(`[verifyGoal] LLM verification failed: ${(err as Error).message}`);
|
|
199
|
+
return criteria.map((c) => ({ id: c.id, description: c.description, met: false, evidence: `Verification error: ${(err as Error).message}` }));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
125
203
|
/**
|
|
126
204
|
* Verify whether a goal has been met using either:
|
|
127
205
|
* - A deterministic tool (goal_check_tool) — executes the tool and checks the result
|
|
128
206
|
* - An LLM verifier — asks the model to return JSON {met, reason}
|
|
129
207
|
*
|
|
130
|
-
* When `acceptance` criteria are supplied, each
|
|
131
|
-
*
|
|
132
|
-
*
|
|
208
|
+
* When `acceptance` criteria are supplied, each with its own checkTool is
|
|
209
|
+
* checked deterministically (no LLM), and every remaining criterion is
|
|
210
|
+
* judged together in a single LLM call — never one call per criterion. The
|
|
211
|
+
* overall verdict is the conjunction of all of them; the top-level
|
|
133
212
|
* `goal`/`checkTool` are ignored in that case.
|
|
134
213
|
*/
|
|
135
214
|
export async function verifyGoal(
|
|
@@ -141,10 +220,21 @@ export async function verifyGoal(
|
|
|
141
220
|
): Promise<{ met: boolean; reason: string; acceptanceResults?: AcceptanceResult[] }> {
|
|
142
221
|
if (acceptance && acceptance.length > 0) {
|
|
143
222
|
const results: AcceptanceResult[] = [];
|
|
223
|
+
const needsLLMJudgment: AcceptanceCriterion[] = [];
|
|
224
|
+
|
|
144
225
|
for (const criterion of acceptance) {
|
|
145
|
-
const
|
|
146
|
-
|
|
226
|
+
const deterministic = criterion.checkTool ? await runDeterministicCheck(criterion.checkTool, criterion.description) : null;
|
|
227
|
+
if (deterministic) {
|
|
228
|
+
results.push({ id: criterion.id, description: criterion.description, met: deterministic.met, evidence: deterministic.reason });
|
|
229
|
+
} else {
|
|
230
|
+
needsLLMJudgment.push(criterion);
|
|
231
|
+
}
|
|
147
232
|
}
|
|
233
|
+
|
|
234
|
+
if (needsLLMJudgment.length > 0) {
|
|
235
|
+
results.push(...(await judgeCriteriaWithLLM(needsLLMJudgment, messages, providerCfg)));
|
|
236
|
+
}
|
|
237
|
+
|
|
148
238
|
const met = results.every((r) => r.met);
|
|
149
239
|
const reason = results.map((r) => `${r.met ? "✅" : "❌"} ${r.description}: ${r.evidence}`).join("\n");
|
|
150
240
|
return { met, reason, acceptanceResults: results };
|
|
@@ -152,32 +242,9 @@ export async function verifyGoal(
|
|
|
152
242
|
|
|
153
243
|
// If we have a deterministic check tool, execute it
|
|
154
244
|
if (checkTool) {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
const allTools = createAllTools(loadConfig());
|
|
159
|
-
const toolDef = allTools.find((t) => t.name === checkTool);
|
|
160
|
-
if (!toolDef) {
|
|
161
|
-
log.warn(`[verifyGoal] Check tool "${checkTool}" not found in the tool registry — falling back to LLM verifier`);
|
|
162
|
-
} else {
|
|
163
|
-
const toolResults = await executeToolBatch({
|
|
164
|
-
toolCalls: [{
|
|
165
|
-
id: "goal-check",
|
|
166
|
-
function: { name: checkTool, arguments: JSON.stringify({ goal }) },
|
|
167
|
-
}],
|
|
168
|
-
allTools,
|
|
169
|
-
toolConfig: {},
|
|
170
|
-
});
|
|
171
|
-
const result = toolResults[0];
|
|
172
|
-
if (result?.ok) {
|
|
173
|
-
return interpretCheckResult(result.result);
|
|
174
|
-
}
|
|
175
|
-
return { met: false, reason: `Check tool failed: ${result?.error?.message ?? "unknown"}` };
|
|
176
|
-
}
|
|
177
|
-
} catch (err) {
|
|
178
|
-
log.warn(`[verifyGoal] Check tool "${checkTool}" failed: ${(err as Error).message}`);
|
|
179
|
-
// Fall through to LLM verifier
|
|
180
|
-
}
|
|
245
|
+
const deterministic = await runDeterministicCheck(checkTool, goal);
|
|
246
|
+
if (deterministic) return deterministic;
|
|
247
|
+
// Falls through to the LLM verifier when the tool is missing or errored.
|
|
181
248
|
}
|
|
182
249
|
|
|
183
250
|
// LLM verifier: ask the model to evaluate whether the goal is met
|
|
@@ -195,6 +262,18 @@ export async function verifyGoal(
|
|
|
195
262
|
messages: verificationMessages,
|
|
196
263
|
tools: undefined,
|
|
197
264
|
});
|
|
265
|
+
if (providerCfg.provider && providerCfg.model && response.usage) {
|
|
266
|
+
recordLLMUsage({
|
|
267
|
+
provider: providerCfg.provider,
|
|
268
|
+
model: providerCfg.model,
|
|
269
|
+
inputTokens: response.usage.input_tokens ?? 0,
|
|
270
|
+
outputTokens: response.usage.output_tokens ?? 0,
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (response.stop_reason === "error") {
|
|
275
|
+
throw new Error(response.error?.message ?? response.content);
|
|
276
|
+
}
|
|
198
277
|
|
|
199
278
|
const content = response.content?.trim() || "";
|
|
200
279
|
// Extract JSON from the response
|
|
@@ -217,7 +296,7 @@ export async function verifyGoal(
|
|
|
217
296
|
* Interpret a check tool's result strictly: an object with a boolean `met`,
|
|
218
297
|
* a bare boolean, or a JSON string with `met` — anything else is not met.
|
|
219
298
|
*/
|
|
220
|
-
function interpretCheckResult(raw: unknown): { met: boolean; reason: string } {
|
|
299
|
+
export function interpretCheckResult(raw: unknown): { met: boolean; reason: string } {
|
|
221
300
|
if (typeof raw === "boolean") {
|
|
222
301
|
return { met: raw, reason: raw ? "Check tool returned true" : "Check tool returned false" };
|
|
223
302
|
}
|
|
@@ -28,6 +28,8 @@ import { QwenProvider } from "./llm-providers/qwen"
|
|
|
28
28
|
import { MiniMaxProvider } from "./llm-providers/minimax"
|
|
29
29
|
import { OpenCodeGoProvider } from "./llm-providers/opencode-go"
|
|
30
30
|
import { HiveAgentsProvider } from "./llm-providers/hiveagents"
|
|
31
|
+
import { ZaiProvider } from "./llm-providers/z-ai"
|
|
32
|
+
import { ModelScopeProvider } from "./llm-providers/modelscope"
|
|
31
33
|
import type { LLMProvider } from "./llm-providers/interface"
|
|
32
34
|
|
|
33
35
|
const log = logger.child("llm-client")
|
|
@@ -108,6 +110,18 @@ export interface LLMResponse {
|
|
|
108
110
|
thinking_content?: string
|
|
109
111
|
/** Anthropic extended thinking raw blocks — must be round-tripped verbatim when tool calls follow. */
|
|
110
112
|
thinking_blocks?: ThinkingBlock[]
|
|
113
|
+
/**
|
|
114
|
+
* Set only when stop_reason === "error". `content` carries a human-readable
|
|
115
|
+
* version of the same failure for display, but it is NOT model output —
|
|
116
|
+
* callers must check this field before persisting `content` anywhere durable
|
|
117
|
+
* (conversation history, summaries, task results).
|
|
118
|
+
*/
|
|
119
|
+
error?: {
|
|
120
|
+
message: string
|
|
121
|
+
status?: number
|
|
122
|
+
/** The model id no longer resolves at the provider (HTTP 404/410) — the config needs to change, retrying won't help. */
|
|
123
|
+
modelUnavailable?: boolean
|
|
124
|
+
}
|
|
111
125
|
}
|
|
112
126
|
|
|
113
127
|
// ─── Provider factory ─────────────────────────────────────────────────────────
|
|
@@ -129,6 +143,8 @@ function getProvider(provider: string): LLMProvider {
|
|
|
129
143
|
case "minimax": return new MiniMaxProvider()
|
|
130
144
|
case "opencode-go": return new OpenCodeGoProvider()
|
|
131
145
|
case "hiveagents": return new HiveAgentsProvider()
|
|
146
|
+
case "z-ai": return new ZaiProvider()
|
|
147
|
+
case "modelscope": return new ModelScopeProvider()
|
|
132
148
|
default:
|
|
133
149
|
log.warn(`[llm-client] Unknown provider "${provider}" — falling back to OpenAI-compatible endpoint`)
|
|
134
150
|
return new OpenAIProvider()
|
|
@@ -163,13 +179,29 @@ export async function callLLM(options: LLMCallOptions): Promise<LLMResponse> {
|
|
|
163
179
|
(err) => !options.signal?.aborted && isRetryableError(err)
|
|
164
180
|
)
|
|
165
181
|
} catch (err) {
|
|
166
|
-
const msg = (err as Error).message
|
|
167
182
|
const cleanModel = options.model.replace(new RegExp(`^${options.provider}\\/`), "")
|
|
183
|
+
const status = extractErrorStatus(err)
|
|
184
|
+
const modelUnavailable = status === 404 || status === 410
|
|
185
|
+
const msg = modelUnavailable
|
|
186
|
+
? `El modelo "${cleanModel}" ya no existe en ${options.provider} (HTTP ${status}). `
|
|
187
|
+
+ `El proveedor lo retiró de su catálogo; reintentar no sirve. `
|
|
188
|
+
+ `Elegí otro modelo en Ajustes → Proveedores.`
|
|
189
|
+
: (err as Error).message
|
|
168
190
|
log.error(`[llm-client] Error calling ${options.provider}/${cleanModel}: ${msg}`, err)
|
|
169
|
-
return {
|
|
191
|
+
return {
|
|
192
|
+
content: `[LLM Error] ${msg}`,
|
|
193
|
+
stop_reason: "error",
|
|
194
|
+
error: { message: msg, status, modelUnavailable },
|
|
195
|
+
}
|
|
170
196
|
}
|
|
171
197
|
}
|
|
172
198
|
|
|
199
|
+
/** Provider SDKs disagree on where the HTTP status lands; check every shape we've seen. */
|
|
200
|
+
function extractErrorStatus(err: unknown): number | undefined {
|
|
201
|
+
const e = err as { status?: number; statusCode?: number; response?: { status?: number } }
|
|
202
|
+
return e?.status ?? e?.statusCode ?? e?.response?.status
|
|
203
|
+
}
|
|
204
|
+
|
|
173
205
|
/**
|
|
174
206
|
* Default provider/model resolved from the DB, used when an agent has none configured:
|
|
175
207
|
* 1. the coordinator agent's config, 2. the first active LLM model of an active provider.
|