micro-models-agent 0.63.3 → 1.1.0
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/CHANGELOG.md +148 -1
- package/dist/cli/cache-line.js +30 -0
- package/dist/cli/command-suggest.js +38 -0
- package/dist/cli/commands.js +285 -60
- package/dist/cli/completer.js +16 -16
- package/dist/cli/json-payload.js +32 -0
- package/dist/cli/main.js +165 -77
- package/dist/cli/plugin-commands.js +5 -4
- package/dist/cli/relaunch.js +37 -0
- package/dist/cli/repl-commands.js +441 -307
- package/dist/cli/repl.js +360 -83
- package/dist/cli/run-result.js +12 -6
- package/dist/cli/security-commands.js +64 -60
- package/dist/cli/setup-order.js +57 -0
- package/dist/cli/setup-prompt.js +49 -0
- package/dist/cli/setup.js +52 -48
- package/dist/config/budget.js +48 -0
- package/dist/config/config.js +132 -70
- package/dist/config/defaults.js +37 -11
- package/dist/config/domains.js +9 -50
- package/dist/config/utils.js +56 -0
- package/dist/core/agent/audit-gate.js +49 -0
- package/dist/core/agent/compaction.js +89 -0
- package/dist/core/agent/constants.js +61 -0
- package/dist/core/agent/context-renderer.js +40 -0
- package/dist/core/agent/hallucination-gate.js +87 -0
- package/dist/core/agent/loop-state.js +53 -0
- package/dist/core/agent/prefix-monitor.js +101 -0
- package/dist/core/agent/reasoning-resolver.js +56 -0
- package/dist/core/agent/token-tracker.js +96 -0
- package/dist/core/agent/tool-batch.js +237 -0
- package/dist/core/agent/tool-output.js +62 -0
- package/dist/core/agent-moe.js +214 -69
- package/dist/core/agent.js +506 -546
- package/dist/core/bootstrap.js +297 -98
- package/dist/core/crash-handler.js +2 -1
- package/dist/core/prompt-builder.js +3 -0
- package/dist/core/prompt-overflow.js +307 -0
- package/dist/core/session-logger.js +34 -2
- package/dist/i18n/en.json +7 -4
- package/dist/i18n/ru.json +7 -4
- package/dist/index.js +5 -1
- package/dist/llm/cache-usage.js +76 -0
- package/dist/llm/image-utils.js +20 -16
- package/dist/llm/llm-errors.js +41 -0
- package/dist/llm/model-loader.js +30 -0
- package/dist/llm/openai-compat.js +287 -101
- package/dist/llm/orchestrator.js +140 -68
- package/dist/llm/provider-budget.js +68 -0
- package/dist/llm/provider.js +0 -1
- package/dist/llm/stream-state.js +26 -0
- package/dist/llm/token-counter.js +28 -0
- package/dist/logger/app-logger.js +12 -15
- package/dist/main.js +1606 -800
- package/dist/migration/detect.js +3 -1
- package/dist/modules/browser/actions.js +0 -3
- package/dist/modules/browser/bridge-client.js +2 -0
- package/dist/modules/browser/driver.js +46 -4
- package/dist/modules/certification/cli.js +85 -42
- package/dist/modules/certification/loader.js +15 -1
- package/dist/modules/certification/manifest.js +126 -15
- package/dist/modules/certification/runner.js +4 -26
- package/dist/modules/certification/scenarios.js +184 -5
- package/dist/modules/certification/syntax-scenarios.js +51 -0
- package/dist/modules/context/chunk-query.js +25 -5
- package/dist/modules/context/fact-extractor.js +6 -2
- package/dist/modules/context/manager.js +23 -7
- package/dist/modules/execution/audit-runners.js +7 -1
- package/dist/modules/execution/auditor.js +3 -3
- package/dist/modules/execution/execution-plugin.js +22 -15
- package/dist/modules/execution/input-from.js +46 -0
- package/dist/modules/execution/module.js +107 -18
- package/dist/modules/execution/moe-executor.js +166 -54
- package/dist/modules/execution/plan-actions.js +524 -0
- package/dist/modules/execution/plan-steps.js +23 -0
- package/dist/modules/execution/plan-store.js +15 -3
- package/dist/modules/execution/plan-tool.js +6 -488
- package/dist/modules/execution/plan-validator.js +24 -0
- package/dist/modules/execution/stuck-detector.js +3 -18
- package/dist/modules/execution/tracker.js +14 -5
- package/dist/modules/execution/transient-error.js +30 -0
- package/dist/modules/execution/verifier.js +94 -7
- package/dist/modules/execution/windows-commands.js +11 -0
- package/dist/modules/hallucination/confidence.js +36 -23
- package/dist/modules/hallucination/consistency.js +3 -0
- package/dist/modules/hallucination/detector.js +8 -3
- package/dist/modules/hallucination/factual.js +26 -7
- package/dist/modules/hallucination/llm-judge.js +12 -2
- package/dist/modules/indexer/map-command.js +35 -0
- package/dist/modules/indexer/map-select.js +87 -0
- package/dist/modules/indexer/module.js +34 -22
- package/dist/modules/indexer/symbols.js +189 -0
- package/dist/modules/indexer/walker.js +96 -42
- package/dist/modules/lsp/check-tool.js +2 -1
- package/dist/modules/lsp/client.js +49 -32
- package/dist/modules/lsp/config.js +55 -2
- package/dist/modules/lsp/module.js +38 -5
- package/dist/modules/lsp/probe.js +4 -3
- package/dist/modules/lsp/project-root.js +41 -1
- package/dist/modules/lsp/startup-check.js +12 -4
- package/dist/modules/mcp/client.js +153 -104
- package/dist/modules/mcp/module.js +165 -41
- package/dist/modules/memory/module.js +4 -3
- package/dist/modules/plugins/builtin/lint-on-write.js +36 -6
- package/dist/modules/plugins/manager.js +47 -84
- package/dist/modules/pricing/index.js +17 -7
- package/dist/modules/pricing/prices.js +30 -12
- package/dist/modules/processes/index.js +1 -0
- package/dist/modules/processes/kill-tree.js +56 -0
- package/dist/modules/processes/registry.js +2 -54
- package/dist/modules/providers/cache.js +23 -0
- package/dist/modules/providers/factory.js +28 -0
- package/dist/modules/providers/fallback.js +7 -5
- package/dist/modules/providers/health.js +2 -1
- package/dist/modules/providers/index.js +1 -0
- package/dist/modules/providers/manager.js +17 -2
- package/dist/modules/providers/presets.js +79 -6
- package/dist/modules/reasoning/policy.js +40 -0
- package/dist/modules/reasoning/probe.js +111 -0
- package/dist/modules/security/audit-notifier.js +42 -27
- package/dist/modules/security/command-validator.js +25 -20
- package/dist/modules/security/encryption.js +6 -12
- package/dist/modules/security/network-validator.js +76 -5
- package/dist/modules/security/path-validator.js +77 -34
- package/dist/modules/security/rate-limiter.js +11 -0
- package/dist/modules/security/security-policies.js +1 -1
- package/dist/modules/security/session-encryption.js +13 -2
- package/dist/modules/security/session-isolation.js +2 -9
- package/dist/modules/session/manager.js +11 -0
- package/dist/modules/session/module.js +11 -3
- package/dist/modules/session/store.js +41 -5
- package/dist/modules/skills/loader.js +7 -1
- package/dist/modules/skills/module.js +2 -1
- package/dist/modules/updater/changelog-reader.js +94 -0
- package/dist/modules/updater/dev-detect.js +17 -0
- package/dist/modules/updater/index.js +1 -0
- package/dist/modules/updater/module.js +14 -3
- package/dist/output/bus.js +32 -0
- package/dist/output/channel.js +233 -0
- package/dist/output/format.js +14 -0
- package/dist/output/index.js +7 -0
- package/dist/output/json-sink.js +22 -0
- package/dist/output/machine.js +8 -0
- package/dist/output/session-sink.js +27 -0
- package/dist/output/types.js +1 -0
- package/dist/tools/approve.js +6 -2
- package/dist/tools/attach-image.js +11 -11
- package/dist/tools/auto-fixer.js +198 -0
- package/dist/tools/bash.js +142 -89
- package/dist/tools/chunk-query.js +10 -6
- package/dist/tools/download-file.js +1 -1
- package/dist/tools/edit-file.js +20 -2
- package/dist/tools/executor.js +54 -9
- package/dist/tools/glob-tool.js +7 -0
- package/dist/tools/grep-tool.js +15 -1
- package/dist/tools/index.js +3 -1
- package/dist/tools/list-dir.js +3 -1
- package/dist/tools/load-skill.js +2 -1
- package/dist/tools/mcp-call.js +1 -1
- package/dist/tools/move-file.js +5 -4
- package/dist/tools/path-utils.js +7 -0
- package/dist/tools/pipeline-run.js +1 -1
- package/dist/tools/prompt-io.js +28 -0
- package/dist/tools/question.js +12 -12
- package/dist/tools/scope-request.js +91 -0
- package/dist/tools/session-info.js +44 -0
- package/dist/tools/set-thinking.js +71 -0
- package/dist/tools/subagent.js +50 -9
- package/dist/tools/syntax-validator.js +177 -0
- package/dist/tools/user-input.js +16 -9
- package/dist/tools/write-file.js +17 -1
- package/dist/ui/diff.js +10 -0
- package/dist/ui/line-editor.js +179 -26
- package/dist/ui/line-math.js +20 -3
- package/dist/ui/md-formatter.js +100 -10
- package/dist/ui/output.js +5 -4
- package/dist/ui/plan-view.js +2 -7
- package/dist/ui/renderer.js +89 -85
- package/dist/ui/spinner.js +14 -4
- package/dist/utils/error.js +4 -0
- package/dist/utils/index.js +4 -0
- package/dist/utils/retry.js +17 -0
- package/dist/utils/sleep.js +23 -0
- package/dist/utils/truncate.js +9 -0
- package/package.json +1 -1
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { pc } from "../../ui/colors";
|
|
2
|
+
import { t } from "../../i18n/index";
|
|
3
|
+
import { summarizeToolArgs, truncateToolOutput, compactToolError } from "./tool-output";
|
|
4
|
+
import { errMsg } from "../../utils";
|
|
5
|
+
import { MAX_CONSECUTIVE_TOOL_FAILURES, MIN_REPEATED_TOOL_FAILURES, } from "./constants";
|
|
6
|
+
/**
|
|
7
|
+
* Выполнение пакета тулов, полученных от модели за одну итерацию.
|
|
8
|
+
*
|
|
9
|
+
* Отвечает за весь жизненный цикл тула:
|
|
10
|
+
* - запись assistant-сообщения с tool_calls в контекст и session log;
|
|
11
|
+
* - plugin-хуки (onToolCall, onToolStart, onToolEnd, onMeta);
|
|
12
|
+
* - событий UI (onTool start/end), вывод display/diff;
|
|
13
|
+
* - усечение результата под бюджет и запись role:"tool" сообщения;
|
|
14
|
+
* - синтез "[interrupted]" результатов для тулов без ответа (иначе
|
|
15
|
+
* OpenAI-совместимые бэкенды отклоняют историю HTTP 400);
|
|
16
|
+
* - учёт неудач (последовательные + общие по тулам) и запись правил в память;
|
|
17
|
+
* - инъекцию <system-summary> с результатами и статусом плана.
|
|
18
|
+
*
|
|
19
|
+
* Не знает о структуре цикла — возвращает флаг `interrupted`, решение о
|
|
20
|
+
* `break`/`continue` принимает вызывающий цикл.
|
|
21
|
+
*/
|
|
22
|
+
export class ToolBatchExecutor {
|
|
23
|
+
deps;
|
|
24
|
+
constructor(deps) {
|
|
25
|
+
this.deps = deps;
|
|
26
|
+
}
|
|
27
|
+
async execute(state, toolCalls, boundedToolNames, textContent, reasoningContent, input, onTool, onMeta, slog) {
|
|
28
|
+
const { config, pluginManager, contextManager, logger } = this.deps;
|
|
29
|
+
const iteration = state.iteration;
|
|
30
|
+
slog?.logAssistant(textContent || "", reasoningContent, toolCalls, iteration);
|
|
31
|
+
contextManager.addMessage({
|
|
32
|
+
role: "assistant",
|
|
33
|
+
content: textContent || "",
|
|
34
|
+
tool_calls: toolCalls.map((tc) => ({
|
|
35
|
+
id: tc.id,
|
|
36
|
+
type: "function",
|
|
37
|
+
function: {
|
|
38
|
+
name: tc.name,
|
|
39
|
+
arguments: JSON.stringify(tc.arguments),
|
|
40
|
+
},
|
|
41
|
+
})),
|
|
42
|
+
});
|
|
43
|
+
const answeredToolCallIds = new Set();
|
|
44
|
+
// OpenAI-совместимые бэкенды (Jinja-шаблоны llama.cpp) отклоняют HTTP 400
|
|
45
|
+
// любую историю, где assistant(tool_calls) не завершён role:"tool"
|
|
46
|
+
// результатами для каждого call id — прерывание на середине пакета не
|
|
47
|
+
// должно оставлять висящую пару.
|
|
48
|
+
const synthesizePendingToolResults = () => {
|
|
49
|
+
for (const call of toolCalls) {
|
|
50
|
+
if (answeredToolCallIds.has(call.id))
|
|
51
|
+
continue;
|
|
52
|
+
logger.debug(`Interrupted before tool ${call.name} (${call.id}) returned a result — synthesizing tool message`);
|
|
53
|
+
contextManager.addMessage({
|
|
54
|
+
role: "tool",
|
|
55
|
+
content: "[interrupted]",
|
|
56
|
+
name: call.name,
|
|
57
|
+
tool_call_id: call.id,
|
|
58
|
+
success: false,
|
|
59
|
+
arguments: call.arguments,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const summaries = [];
|
|
64
|
+
let anyToolFailed = false;
|
|
65
|
+
// Информационные read-only тулы, чей "фейл" — ожидаемое поведение
|
|
66
|
+
// (file_info "Not found" после delete_file) — исключены из учёта неудач.
|
|
67
|
+
const infoTools = new Set(["file_info"]);
|
|
68
|
+
for (const call of toolCalls) {
|
|
69
|
+
this.deps.setScope();
|
|
70
|
+
const startTime = Date.now();
|
|
71
|
+
pluginManager.runOnToolCall({
|
|
72
|
+
toolName: call.name,
|
|
73
|
+
args: call.arguments,
|
|
74
|
+
});
|
|
75
|
+
pluginManager.runOnToolStart({ iteration, logger, contextManager }, { id: call.id, name: call.name, arguments: call.arguments });
|
|
76
|
+
const toolIcon = this.deps.toolExecutor.getRegistry().get(call.name)?.icon;
|
|
77
|
+
onTool?.({ type: "start", tool: call.name, args: call.arguments, icon: toolIcon });
|
|
78
|
+
slog?.logToolCall(call, iteration);
|
|
79
|
+
const tokensBeforeTool = contextManager.getEstimatedTokens();
|
|
80
|
+
let result;
|
|
81
|
+
try {
|
|
82
|
+
result = await this.deps.toolExecutor.execute(call, this.deps.getAbortSignal());
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
// Abort во время тула должен распространяться, чтобы сессия завершилась
|
|
86
|
+
// чисто. Любой ДРУГОЙ throw (баг тула/плагина, сбежавший из executor)
|
|
87
|
+
// не должен убивать сессию — деградируем до failed-результата.
|
|
88
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
89
|
+
synthesizePendingToolResults();
|
|
90
|
+
throw err;
|
|
91
|
+
}
|
|
92
|
+
logger.warn(`Tool ${call.name} threw: ${errMsg(err)}`);
|
|
93
|
+
result = {
|
|
94
|
+
success: false,
|
|
95
|
+
output: `${t("error.prefix")}${errMsg(err)}`,
|
|
96
|
+
toolCallId: call.id,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
// Прерывание во время тула: сессия уже завершается, останавливаемся
|
|
100
|
+
// сразу — без рендера, логов и обновления контекста для результата,
|
|
101
|
+
// который никто не увидит.
|
|
102
|
+
if (this.deps.isShutdownRequested())
|
|
103
|
+
break;
|
|
104
|
+
const duration = Date.now() - startTime;
|
|
105
|
+
if (!result.success && !result.blocked && !infoTools.has(call.name))
|
|
106
|
+
anyToolFailed = true;
|
|
107
|
+
if (result.success && call.name === "plan") {
|
|
108
|
+
const action = String(call.arguments.action ?? "");
|
|
109
|
+
if (action === "create" || action === "re-plan")
|
|
110
|
+
state.iterPlanCreated = true;
|
|
111
|
+
}
|
|
112
|
+
if (result.success && call.arguments.path) {
|
|
113
|
+
const filePath = String(call.arguments.path);
|
|
114
|
+
if (call.name === "write_file" || call.name === "edit_file") {
|
|
115
|
+
this.deps.hallucinationDetector.getConsistencyCheck().trackCreatedFile(filePath);
|
|
116
|
+
}
|
|
117
|
+
else if (call.name === "delete_file") {
|
|
118
|
+
this.deps.hallucinationDetector.getConsistencyCheck().trackDeletedFile(filePath);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
pluginManager.runOnToolEnd({ iteration, logger, contextManager }, { id: call.id, name: call.name, arguments: call.arguments }, result, duration);
|
|
122
|
+
// Проверка наличия, а не истинности: read_file возвращает display ""
|
|
123
|
+
// на полном чтении (заголовок уже показывает путь) — фолбэк на пустую
|
|
124
|
+
// строку вывалил бы всё содержимое файла в REPL.
|
|
125
|
+
if (result.display !== undefined) {
|
|
126
|
+
if (result.display.length > 0) {
|
|
127
|
+
onMeta?.("\n" + result.display + "\n");
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
else if (result.success) {
|
|
131
|
+
const metaOut = pluginManager.runOnMeta({ iteration, logger, contextManager }, result.output);
|
|
132
|
+
onMeta?.("\n" + pc.dim(metaOut) + "\n");
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
// Failed tool: its `output` is model-facing (Hints, recovery
|
|
136
|
+
// directives, "Do NOT …"). The user only needs the gist — the first
|
|
137
|
+
// line — not the instructions written for the agent.
|
|
138
|
+
const line = compactToolError(result.output);
|
|
139
|
+
const metaOut = line
|
|
140
|
+
? pluginManager.runOnMeta({ iteration, logger, contextManager }, line)
|
|
141
|
+
: "";
|
|
142
|
+
if (metaOut)
|
|
143
|
+
onMeta?.("\n" + pc.red(metaOut) + "\n");
|
|
144
|
+
}
|
|
145
|
+
if (result.diff) {
|
|
146
|
+
onMeta?.("\n" + result.diff + "\n");
|
|
147
|
+
}
|
|
148
|
+
const currentTokens = contextManager.getEstimatedTokens();
|
|
149
|
+
const budget = contextManager.getBudget();
|
|
150
|
+
const truncatedOutput = truncateToolOutput(result.output, budget, currentTokens, boundedToolNames.has(call.name));
|
|
151
|
+
contextManager.addMessage({
|
|
152
|
+
role: "tool",
|
|
153
|
+
content: truncatedOutput,
|
|
154
|
+
name: call.name,
|
|
155
|
+
tool_call_id: call.id,
|
|
156
|
+
success: result.success,
|
|
157
|
+
blocked: result.blocked,
|
|
158
|
+
arguments: call.arguments,
|
|
159
|
+
});
|
|
160
|
+
answeredToolCallIds.add(call.id);
|
|
161
|
+
const tokensAfterTool = contextManager.getEstimatedTokens();
|
|
162
|
+
onTool?.({
|
|
163
|
+
type: "end",
|
|
164
|
+
tool: call.name,
|
|
165
|
+
args: call.arguments,
|
|
166
|
+
duration,
|
|
167
|
+
error: !result.success,
|
|
168
|
+
ctxDelta: tokensAfterTool - tokensBeforeTool,
|
|
169
|
+
costUsd: this.deps.costTracker.total,
|
|
170
|
+
});
|
|
171
|
+
summaries.push(`[Tool: ${call.name}${summarizeToolArgs(call.arguments)} → ${truncatedOutput.slice(0, 200)}]`);
|
|
172
|
+
if (config.session.autoSave) {
|
|
173
|
+
slog?.logToolResult(call, result, duration, iteration);
|
|
174
|
+
}
|
|
175
|
+
this.deps.compactionService.compactAfterTool(state);
|
|
176
|
+
// Учёт общих неудач (НЕ только подряд идущих): тул, который стабильно
|
|
177
|
+
// падает между успехами других тулов, всё равно учится (наблюдалось:
|
|
178
|
+
// LSP spawn npx ENOENT упал 8x за сессию, ни разу подряд — и не дошёл
|
|
179
|
+
// до памяти по пути "5 подряд неудач").
|
|
180
|
+
if (!result.success && !result.blocked && !infoTools.has(call.name)) {
|
|
181
|
+
const key = call.name;
|
|
182
|
+
const prev = state.toolFailureCounts.get(key) ?? { count: 0, error: "" };
|
|
183
|
+
prev.count++;
|
|
184
|
+
prev.error = String(result.output ?? "").slice(0, 200);
|
|
185
|
+
state.toolFailureCounts.set(key, prev);
|
|
186
|
+
if (prev.count >= MIN_REPEATED_TOOL_FAILURES && !state.memoryRuleRecorded.has(key)) {
|
|
187
|
+
state.memoryRuleRecorded.add(key);
|
|
188
|
+
const memStore = this.deps.memoryStore;
|
|
189
|
+
if (memStore) {
|
|
190
|
+
memStore.appendRule("errors", `Tool ${key} failed ${prev.count}x (${prev.error})`, `Repeated ${key} failures suggest a systemic problem (config, environment, or a broken tool), not a one-off`, "Check the error message, verify the tool's dependencies are installed/configured, and consider a different tool");
|
|
191
|
+
logger.warn(`Recorded repeated ${key} failures to memory (${prev.count}x)`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (this.deps.isShutdownRequested()) {
|
|
197
|
+
synthesizePendingToolResults();
|
|
198
|
+
return { interrupted: true };
|
|
199
|
+
}
|
|
200
|
+
// Последовательные неудачи: recovery-сообщение + правило в память.
|
|
201
|
+
if (anyToolFailed) {
|
|
202
|
+
state.consecutiveToolFailures++;
|
|
203
|
+
state.consecutiveToolSuccesses = 0;
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
state.consecutiveToolFailures = 0;
|
|
207
|
+
state.consecutiveToolSuccesses++;
|
|
208
|
+
}
|
|
209
|
+
if (state.consecutiveToolFailures >= MAX_CONSECUTIVE_TOOL_FAILURES) {
|
|
210
|
+
const recoveryMsg = t("exec.consecutive_failures_recovery", {
|
|
211
|
+
count: state.consecutiveToolFailures,
|
|
212
|
+
});
|
|
213
|
+
logger.warn(`Consecutive tool failures: ${state.consecutiveToolFailures}`);
|
|
214
|
+
const taskSnippet = input.length > 200 ? input.slice(0, 200) + "..." : input;
|
|
215
|
+
const taskReminder = t("exec.task_reminder", { task: taskSnippet });
|
|
216
|
+
contextManager.addMessage({
|
|
217
|
+
role: "user",
|
|
218
|
+
content: `<system-summary>${recoveryMsg}\n${taskReminder}</system-summary>`,
|
|
219
|
+
});
|
|
220
|
+
const memStore = this.deps.memoryStore;
|
|
221
|
+
if (memStore) {
|
|
222
|
+
memStore.appendRule("errors", `${state.consecutiveToolFailures} consecutive tool failures`, "Multiple tools failing suggests environment or configuration issue", "Check dependencies, verify file paths, try write_file directly instead of shell commands");
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
// Статусная строка плана после каждого пакета тулов. Заменяет динамический
|
|
226
|
+
// plan-блок, который жил в system prompt (удалён ради KV-cache — план
|
|
227
|
+
// меняется каждую итерацию).
|
|
228
|
+
const planLine = this.deps.planSummary?.();
|
|
229
|
+
if (planLine)
|
|
230
|
+
summaries.push(planLine);
|
|
231
|
+
contextManager.addMessage({
|
|
232
|
+
role: "user",
|
|
233
|
+
content: `<system-summary>${summaries.join("\n")}</system-summary>`,
|
|
234
|
+
});
|
|
235
|
+
return { interrupted: false };
|
|
236
|
+
}
|
|
237
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { t } from "../../i18n/index";
|
|
2
|
+
import { TOOL_RESULT_MAX_TOKENS_RATIO, TOOL_RESULT_ABSOLUTE_MAX_CHARS, TOOL_ARGS_SUMMARY_MAX_CHARS, } from "./constants";
|
|
3
|
+
/**
|
|
4
|
+
* Макс. число символов результата тула при заданном остатке бюджета и
|
|
5
|
+
* признаке того, что тул сам ограничивает свой вывод.
|
|
6
|
+
*
|
|
7
|
+
* Тулы с `boundedOutput` (например, read_file с лимитом строк) НИКОГДА не
|
|
8
|
+
* усекаются бюджетом — почти полный контекст раньше резал их до ~2K символов,
|
|
9
|
+
* и модель верила, что файлы обрезаны, перечитывая их бесконечно.
|
|
10
|
+
*/
|
|
11
|
+
export function toolOutputCharLimit(remainingBudget, historyBudget, bounded) {
|
|
12
|
+
if (bounded)
|
|
13
|
+
return Number.MAX_SAFE_INTEGER;
|
|
14
|
+
const maxCharsByRatio = Math.floor(historyBudget * TOOL_RESULT_MAX_TOKENS_RATIO * 2);
|
|
15
|
+
return Math.min(remainingBudget, maxCharsByRatio, TOOL_RESULT_ABSOLUTE_MAX_CHARS);
|
|
16
|
+
}
|
|
17
|
+
/** Усечение вывода тула под бюджет с честной пометкой о потере. */
|
|
18
|
+
export function truncateToolOutput(output, budget, currentTokens, bounded) {
|
|
19
|
+
const remainingBudget = Math.max(0, budget.history - currentTokens);
|
|
20
|
+
const maxChars = toolOutputCharLimit(remainingBudget, budget.history, bounded);
|
|
21
|
+
if (output.length <= maxChars)
|
|
22
|
+
return output;
|
|
23
|
+
const truncated = output.slice(0, maxChars);
|
|
24
|
+
const removedChars = output.length - maxChars;
|
|
25
|
+
return truncated + `\n\n${t("tool.truncated", { tokens: Math.ceil(removedChars / 2) })}`;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* JSON-сериализация аргументов тула для <system-summary>, ограниченная по
|
|
29
|
+
* размеру. Большой аргумент (content у write_file) не должен дублироваться в
|
|
30
|
+
* сводке поверх role:"tool" сообщения, которое уже несёт результат.
|
|
31
|
+
*/
|
|
32
|
+
export function summarizeToolArgs(args) {
|
|
33
|
+
let s;
|
|
34
|
+
try {
|
|
35
|
+
s = JSON.stringify(args);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
s = String(args);
|
|
39
|
+
}
|
|
40
|
+
if (!s || s === "{}")
|
|
41
|
+
return "";
|
|
42
|
+
if (s.length <= TOOL_ARGS_SUMMARY_MAX_CHARS)
|
|
43
|
+
return ` (${s})`;
|
|
44
|
+
return ` (${s.slice(0, TOOL_ARGS_SUMMARY_MAX_CHARS)}…(${s.length} chars total))`;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Компактная пользовательская строка для упавшего тула.
|
|
48
|
+
*
|
|
49
|
+
* Полный `result.output` — это model-facing текст: хвост с Hint / recovery /
|
|
50
|
+
* "Do NOT …" инструкциями. В чат он попадать не должен: пользователю нужна
|
|
51
|
+
* суть ошибки (первая непустая строка), обрезанная по длине.
|
|
52
|
+
*/
|
|
53
|
+
export function compactToolError(output, max = 200) {
|
|
54
|
+
const text = String(output ?? "");
|
|
55
|
+
for (const line of text.split("\n")) {
|
|
56
|
+
const trimmed = line.trim();
|
|
57
|
+
if (!trimmed)
|
|
58
|
+
continue;
|
|
59
|
+
return trimmed.length > max ? `${trimmed.slice(0, max - 1)}…` : trimmed;
|
|
60
|
+
}
|
|
61
|
+
return "";
|
|
62
|
+
}
|
package/dist/core/agent-moe.js
CHANGED
|
@@ -2,101 +2,246 @@ import { OrchestratorClient } from "../llm/orchestrator";
|
|
|
2
2
|
import { validatePlan, applyAutoFixes } from "../modules/execution/plan-validator";
|
|
3
3
|
import { MoEExecutor } from "../modules/execution/moe-executor";
|
|
4
4
|
import { StepVerifier } from "../modules/execution/verifier";
|
|
5
|
+
import { newAbortError } from "../modules/execution/moe-executor";
|
|
6
|
+
import { t } from "../i18n/index";
|
|
7
|
+
export const DEFAULT_MOE_MAX_REPLAN_CYCLES = 3;
|
|
5
8
|
/**
|
|
6
|
-
* Execute the MoE (Mixture of Experts) path: plan → validate → execute → verify
|
|
9
|
+
* Execute the MoE (Mixture of Experts) path: plan → validate → execute → verify,
|
|
10
|
+
* with a re-plan loop driven by the orchestrator's verifyAndMerge decision.
|
|
7
11
|
* Returns a fallback signal when MoE cannot proceed so the caller can fall
|
|
8
12
|
* back to the single-agent loop.
|
|
9
13
|
*/
|
|
10
14
|
export async function runWithMoE(deps, input, fallback, opts = {}) {
|
|
11
15
|
const { config, llmProvider, logger, toolExecutor, baseDir } = deps;
|
|
12
|
-
const { onMeta, onPhase } = opts;
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
const { onMeta, onPhase, onTool, signal, onEvent, sessionId } = opts;
|
|
17
|
+
const emit = (type, data) => onEvent?.({ type, data });
|
|
18
|
+
const ensureNotAborted = () => {
|
|
19
|
+
if (signal?.aborted)
|
|
20
|
+
throw newAbortError();
|
|
21
|
+
};
|
|
22
|
+
// Orchestration one-liners are machine-facing: emit them to the chat only
|
|
23
|
+
// when the user opted into verbose UI (config.ui.verbose).
|
|
24
|
+
const verbose = config.ui?.verbose === true;
|
|
25
|
+
const status = (message) => {
|
|
26
|
+
if (verbose)
|
|
27
|
+
onMeta?.(message);
|
|
28
|
+
};
|
|
29
|
+
ensureNotAborted();
|
|
30
|
+
let orchestrator = deps.orchestratorOverride;
|
|
31
|
+
if (!orchestrator) {
|
|
32
|
+
orchestrator = new OrchestratorClient({
|
|
33
|
+
model: config.orchestrator.model,
|
|
34
|
+
provider: config.orchestrator.provider,
|
|
35
|
+
contextWindow: config.orchestrator.contextWindow,
|
|
36
|
+
retry: config.retry,
|
|
37
|
+
rateLimits: config.security?.rateLimits,
|
|
38
|
+
logger,
|
|
39
|
+
experts: config.experts,
|
|
40
|
+
}, llmProvider, { getSessionId: () => sessionId });
|
|
41
|
+
}
|
|
17
42
|
if (!orchestrator.isEnabled()) {
|
|
18
|
-
|
|
43
|
+
// Visible at default log level: a user who enabled moe.enabled must be
|
|
44
|
+
// able to tell why MoE never kicked in (missing orchestrator.model).
|
|
45
|
+
logger.warn("MoE enabled but no orchestrator model configured — falling back to single-agent. Set orchestrator.model to activate MoE.");
|
|
19
46
|
return fallback();
|
|
20
47
|
}
|
|
21
|
-
|
|
48
|
+
status("🤖 Planning with MoE mode...\n");
|
|
22
49
|
onPhase?.("thinking");
|
|
23
|
-
const planResult = await orchestrator.plan(input);
|
|
50
|
+
const planResult = await orchestrator.plan(input, undefined, signal);
|
|
24
51
|
onPhase?.("done");
|
|
25
52
|
if ("error" in planResult) {
|
|
26
53
|
logger.warn(`MoE plan failed: ${planResult.error} — falling back to single-agent`);
|
|
54
|
+
emit("moe_plan", { status: "error", error: planResult.error });
|
|
27
55
|
return fallback();
|
|
28
56
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
57
|
+
emit("moe_plan", {
|
|
58
|
+
status: "ok",
|
|
59
|
+
title: planResult.plan.title,
|
|
60
|
+
subtaskIds: planResult.plan.subtasks.map((s) => s.id),
|
|
61
|
+
});
|
|
62
|
+
const maxCycles = Math.max(1, config.moe?.maxReplanCycles ?? DEFAULT_MOE_MAX_REPLAN_CYCLES);
|
|
63
|
+
const mergedResults = new Map();
|
|
64
|
+
let currentPlan = planResult.plan;
|
|
65
|
+
const usageByTag = {};
|
|
66
|
+
for (let cycle = 1; cycle <= maxCycles; cycle++) {
|
|
67
|
+
ensureNotAborted();
|
|
68
|
+
if (cycle > 1) {
|
|
69
|
+
status(t("moe.replan_started", { cycle, max: maxCycles }) + "\n");
|
|
70
|
+
emit("moe_replan", {
|
|
71
|
+
cycle,
|
|
72
|
+
title: currentPlan.title,
|
|
73
|
+
subtaskIds: currentPlan.subtasks.map((s) => s.id),
|
|
74
|
+
});
|
|
39
75
|
}
|
|
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
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
76
|
+
// Validate every plan before executing it — never trust an LLM-produced
|
|
77
|
+
// plan, including re-plans produced by verifyAndMerge.
|
|
78
|
+
const validation = validatePlan(currentPlan, config);
|
|
79
|
+
if (!validation.valid) {
|
|
80
|
+
const applied = applyAutoFixes(currentPlan, validation.autoFixes);
|
|
81
|
+
const retry = validatePlan(applied, config);
|
|
82
|
+
if (!retry.valid) {
|
|
83
|
+
logger.warn(`MoE plan validation failed: ${retry.errors.join("; ")}`);
|
|
84
|
+
if (cycle === 1) {
|
|
85
|
+
status(`⚠️ Plan validation failed. Falling back to single-agent mode.\n`);
|
|
86
|
+
return fallback();
|
|
87
|
+
}
|
|
88
|
+
return partialFailure(mergedResults, retry.errors.join("; "));
|
|
89
|
+
}
|
|
90
|
+
currentPlan = applied;
|
|
91
|
+
if (validation.autoFixes.length > 0) {
|
|
92
|
+
status(`🔧 Auto-fixed ${validation.autoFixes.length} plan issues.\n`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const executor = deps.executorOverride ??
|
|
96
|
+
new MoEExecutor({
|
|
97
|
+
config,
|
|
98
|
+
toolRegistry: toolExecutor.getRegistry(),
|
|
99
|
+
toolExecutor,
|
|
100
|
+
llmProvider,
|
|
101
|
+
logger,
|
|
102
|
+
baseDir,
|
|
103
|
+
onTool,
|
|
104
|
+
sessionId,
|
|
105
|
+
onEvent: (e) => emit(e.type, e.data),
|
|
106
|
+
onScopeRequest: async (subtaskId, req) => {
|
|
107
|
+
const decision = await orchestrator.resolveScopeRequest(subtaskId, req, signal);
|
|
108
|
+
if (decision.action === "approve") {
|
|
109
|
+
status(t("moe.scope_approved", {
|
|
110
|
+
subtask: subtaskId,
|
|
111
|
+
files: [...decision.write, ...decision.read].join(", "),
|
|
112
|
+
}) + "\n");
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
status(t("moe.scope_rejected", { subtask: subtaskId }) + "\n");
|
|
116
|
+
}
|
|
117
|
+
return decision;
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
status(t("moe.executing", { count: String(currentPlan.subtasks.length), cycle: String(cycle) }) + "\n");
|
|
121
|
+
// Selective re-plan (Plan 5.1): subtasks already successfully executed in
|
|
122
|
+
// an earlier cycle are carried over — only failed/new ones re-execute.
|
|
123
|
+
const skipIds = new Set();
|
|
124
|
+
const carriedResults = [];
|
|
125
|
+
for (const s of currentPlan.subtasks) {
|
|
126
|
+
const prev = mergedResults.get(s.id);
|
|
127
|
+
if (prev?.success) {
|
|
128
|
+
skipIds.add(s.id);
|
|
129
|
+
carriedResults.push(prev);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
for (const id of skipIds) {
|
|
133
|
+
emit("moe_subtask", { subtaskId: id, status: "carried", cycle });
|
|
134
|
+
}
|
|
135
|
+
const planResults = await executor.executePlan(currentPlan, { skipIds, carriedResults });
|
|
136
|
+
ensureNotAborted();
|
|
137
|
+
const cycleUsage = executor.getUsageByTag?.();
|
|
138
|
+
if (cycleUsage) {
|
|
139
|
+
for (const [tag, usage] of Object.entries(cycleUsage)) {
|
|
140
|
+
const agg = usageByTag[tag] ?? {
|
|
141
|
+
promptTokens: 0,
|
|
142
|
+
completionTokens: 0,
|
|
143
|
+
totalTokens: 0,
|
|
144
|
+
subtasks: 0,
|
|
145
|
+
};
|
|
146
|
+
agg.promptTokens += usage.promptTokens;
|
|
147
|
+
agg.completionTokens += usage.completionTokens;
|
|
148
|
+
agg.totalTokens += usage.totalTokens;
|
|
149
|
+
agg.subtasks += usage.subtasks;
|
|
150
|
+
usageByTag[tag] = agg;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
for (const r of planResults.results) {
|
|
154
|
+
mergedResults.set(r.subtaskId, r);
|
|
155
|
+
}
|
|
156
|
+
const succeeded = [...mergedResults.values()].filter((r) => r.success).length;
|
|
157
|
+
status(`✅ ${t("moe.execution_complete", { succeeded: String(succeeded), total: String(mergedResults.size) })}\n`);
|
|
158
|
+
const verifier = deps.verifierOverride ??
|
|
159
|
+
new StepVerifier(baseDir);
|
|
160
|
+
const knownTags = collectKnownToolTags(toolExecutor);
|
|
161
|
+
const verification = await verifier.verifyMoEManifest(currentPlan, config, knownTags);
|
|
162
|
+
onPhase?.("thinking");
|
|
163
|
+
ensureNotAborted();
|
|
164
|
+
let verifyResult;
|
|
165
|
+
try {
|
|
166
|
+
verifyResult = await orchestrator.verifyAndMerge({
|
|
167
|
+
plan: currentPlan,
|
|
168
|
+
results: [...mergedResults.values()].map((r) => ({
|
|
169
|
+
subtaskId: r.subtaskId,
|
|
170
|
+
success: r.success,
|
|
171
|
+
summary: r.summary,
|
|
172
|
+
result: r.result,
|
|
173
|
+
error: r.error,
|
|
174
|
+
})),
|
|
175
|
+
verifierErrors: verification.errors,
|
|
176
|
+
verifierWarnings: verification.warnings,
|
|
177
|
+
}, signal);
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
onPhase?.("done");
|
|
181
|
+
if (err?.name === "AbortError")
|
|
182
|
+
throw err;
|
|
183
|
+
emit("moe_verify", { status: "error", error: err.message });
|
|
184
|
+
return {
|
|
185
|
+
success: false,
|
|
186
|
+
text: `MoE verifyAndMerge crashed: ${err.message}`,
|
|
187
|
+
error: err.message,
|
|
188
|
+
iterationCount: mergedResults.size,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
onPhase?.("done");
|
|
192
|
+
emit("moe_verify", {
|
|
193
|
+
decision: verifyResult.type,
|
|
194
|
+
explanation: verifyResult.explanation,
|
|
195
|
+
usageByTag: Object.keys(usageByTag).length > 0 ? usageByTag : undefined,
|
|
72
196
|
});
|
|
197
|
+
if (verifyResult.type === "final") {
|
|
198
|
+
return buildFinalResult(mergedResults, verification.success, verifyResult);
|
|
199
|
+
}
|
|
200
|
+
if (!verifyResult.plan || !Array.isArray(verifyResult.plan.subtasks)) {
|
|
201
|
+
// Verifier asked for a re-plan but produced none usable — stop honestly.
|
|
202
|
+
return partialFailure(mergedResults, verifyResult.explanation || "re-plan requested but no plan returned");
|
|
203
|
+
}
|
|
204
|
+
currentPlan = verifyResult.plan;
|
|
73
205
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
};
|
|
206
|
+
return partialFailure(mergedResults, t("moe.cycles_exhausted", { max: String(maxCycles) }));
|
|
207
|
+
}
|
|
208
|
+
function collectKnownToolTags(toolExecutor) {
|
|
209
|
+
const tags = new Set();
|
|
210
|
+
for (const tool of toolExecutor.getRegistry().getAll()) {
|
|
211
|
+
for (const tag of tool.tags || [])
|
|
212
|
+
tags.add(tag);
|
|
82
213
|
}
|
|
83
|
-
|
|
214
|
+
return Array.from(tags);
|
|
215
|
+
}
|
|
216
|
+
function buildFinalResult(mergedResults, verificationSuccess, verifyResult) {
|
|
84
217
|
const outputLines = [`## MoE Execution Results\n`];
|
|
85
|
-
for (const r of
|
|
218
|
+
for (const r of mergedResults.values()) {
|
|
86
219
|
const icon = r.success ? "✅" : "❌";
|
|
87
220
|
outputLines.push(`${icon} **${r.subtaskId}**: ${r.summary} (${r.durationMs}ms)`);
|
|
88
221
|
}
|
|
89
222
|
outputLines.push("");
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
outputLines.
|
|
223
|
+
outputLines.push(`**Result:** ${verifyResult.finalAnswer || "Complete"}`);
|
|
224
|
+
const failedCount = [...mergedResults.values()].filter((r) => !r.success).length;
|
|
225
|
+
return {
|
|
226
|
+
success: failedCount === 0 && verificationSuccess,
|
|
227
|
+
text: outputLines.join("\n"),
|
|
228
|
+
iterationCount: mergedResults.size,
|
|
229
|
+
moeHandled: true,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
function partialFailure(mergedResults, reason) {
|
|
233
|
+
const outputLines = [`## MoE Execution Results\n`];
|
|
234
|
+
for (const r of mergedResults.values()) {
|
|
235
|
+
const icon = r.success ? "✅" : "❌";
|
|
236
|
+
outputLines.push(`${icon} **${r.subtaskId}**: ${r.summary} (${r.durationMs}ms)`);
|
|
95
237
|
}
|
|
96
|
-
|
|
238
|
+
outputLines.push("");
|
|
239
|
+
outputLines.push(`**${t("moe.partial_result")}:** ${reason}`);
|
|
97
240
|
return {
|
|
98
|
-
success:
|
|
241
|
+
success: false,
|
|
99
242
|
text: outputLines.join("\n"),
|
|
100
|
-
|
|
243
|
+
error: reason,
|
|
244
|
+
iterationCount: mergedResults.size,
|
|
245
|
+
moeHandled: true,
|
|
101
246
|
};
|
|
102
247
|
}
|