micro-models-agent 0.28.9 → 0.29.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/dist/cli/commands.js +220 -0
- package/dist/cli/completer.js +168 -0
- package/dist/cli/index.js +2 -0
- package/dist/cli/main.js +113 -0
- package/dist/cli/repl.js +987 -0
- package/dist/cli/security-commands.js +166 -0
- package/dist/cli/setup.js +229 -0
- package/dist/config/config.js +186 -0
- package/dist/config/defaults.js +91 -0
- package/dist/config/experts.js +15 -0
- package/dist/config/index.js +3 -0
- package/dist/config/security.js +193 -0
- package/dist/config/types.js +1 -0
- package/dist/core/agent-moe.js +98 -0
- package/dist/core/agent.js +461 -0
- package/dist/core/bootstrap.js +321 -0
- package/dist/core/index.js +2 -0
- package/dist/core/prompt-builder.js +55 -0
- package/dist/core/session-logger.js +122 -0
- package/dist/core/types.js +1 -0
- package/dist/i18n/en.json +461 -0
- package/dist/i18n/index.js +43 -0
- package/dist/i18n/ru.json +461 -0
- package/dist/index.js +22 -0
- package/dist/llm/image-utils.js +144 -0
- package/dist/llm/index.js +4 -0
- package/dist/llm/model-loader.js +78 -0
- package/dist/llm/openai-compat.js +324 -0
- package/dist/llm/orchestrator.js +194 -0
- package/dist/llm/provider.js +10 -0
- package/dist/llm/response.js +39 -0
- package/dist/llm/token-counter.js +39 -0
- package/dist/llm/types.js +1 -0
- package/dist/logger/app-logger.js +76 -0
- package/dist/logger/index.js +1 -0
- package/dist/main.js +2251 -724
- package/dist/migration/backup.js +45 -0
- package/dist/migration/detect.js +50 -0
- package/dist/migration/index.js +2 -0
- package/dist/modules/browser/actions.js +46 -0
- package/dist/modules/browser/cookie-store.js +24 -0
- package/dist/modules/browser/index.js +5 -0
- package/dist/modules/browser/module.js +28 -0
- package/dist/modules/browser/session.js +287 -0
- package/dist/modules/browser/snapshot.js +114 -0
- package/dist/modules/browser/types.js +9 -0
- package/dist/modules/context/history.js +15 -0
- package/dist/modules/context/index.js +1 -0
- package/dist/modules/context/manager.js +240 -0
- package/dist/modules/execution/auditor.js +72 -0
- package/dist/modules/execution/index.js +6 -0
- package/dist/modules/execution/module.js +337 -0
- package/dist/modules/execution/moe-executor.js +209 -0
- package/dist/modules/execution/plan-validator.js +153 -0
- package/dist/modules/execution/planner.js +35 -0
- package/dist/modules/execution/stuck-detector.js +134 -0
- package/dist/modules/execution/tracker.js +53 -0
- package/dist/modules/execution/types.js +1 -0
- package/dist/modules/execution/verifier.js +149 -0
- package/dist/modules/hallucination/confidence.js +54 -0
- package/dist/modules/hallucination/consistency.js +60 -0
- package/dist/modules/hallucination/detector.js +41 -0
- package/dist/modules/hallucination/factual.js +170 -0
- package/dist/modules/hallucination/index.js +4 -0
- package/dist/modules/index.js +5 -0
- package/dist/modules/indexer/cache.js +38 -0
- package/dist/modules/indexer/index.js +3 -0
- package/dist/modules/indexer/module.js +192 -0
- package/dist/modules/indexer/walker.js +101 -0
- package/dist/modules/mcp/client.js +393 -0
- package/dist/modules/mcp/index.js +3 -0
- package/dist/modules/mcp/module.js +146 -0
- package/dist/modules/mcp/registry.js +15 -0
- package/dist/modules/memory/index.js +1 -0
- package/dist/modules/memory/module.js +48 -0
- package/dist/modules/memory/search.js +40 -0
- package/dist/modules/memory/store.js +65 -0
- package/dist/modules/pipelines/engine.js +60 -0
- package/dist/modules/pipelines/index.js +3 -0
- package/dist/modules/pipelines/parser.js +53 -0
- package/dist/modules/pipelines/template.js +14 -0
- package/dist/modules/plugins/builtin/lint-on-write.js +121 -0
- package/dist/modules/plugins/builtin/notify.js +8 -0
- package/dist/modules/plugins/index.js +1 -0
- package/dist/modules/plugins/loader.js +28 -0
- package/dist/modules/plugins/manager.js +161 -0
- package/dist/modules/plugins/types.js +1 -0
- package/dist/modules/processes/detect.js +34 -0
- package/dist/modules/processes/index.js +3 -0
- package/dist/modules/processes/registry.js +148 -0
- package/dist/modules/processes/runner.js +124 -0
- package/dist/modules/registry.js +45 -0
- package/dist/modules/security/audit-log.js +116 -0
- package/dist/modules/security/audit-notifier.js +292 -0
- package/dist/modules/security/command-validator.js +185 -0
- package/dist/modules/security/content-scanner.js +52 -0
- package/dist/modules/security/data-sanitizer.js +97 -0
- package/dist/modules/security/encryption.js +240 -0
- package/dist/modules/security/index.js +14 -0
- package/dist/modules/security/network-validator.js +79 -0
- package/dist/modules/security/path-validator.js +155 -0
- package/dist/modules/security/rate-limiter.js +119 -0
- package/dist/modules/security/security-policies.js +393 -0
- package/dist/modules/security/session-encryption.js +193 -0
- package/dist/modules/security/session-isolation.js +95 -0
- package/dist/modules/session/index.js +3 -0
- package/dist/modules/session/manager.js +167 -0
- package/dist/modules/session/module.js +24 -0
- package/dist/modules/session/store.js +174 -0
- package/dist/modules/session/types.js +1 -0
- package/dist/modules/skills/index.js +3 -0
- package/dist/modules/skills/loader.js +72 -0
- package/dist/modules/skills/matcher.js +27 -0
- package/dist/modules/skills/module.js +143 -0
- package/dist/modules/types.js +1 -0
- package/dist/modules/updater/checker.js +32 -0
- package/dist/modules/updater/index.js +1 -0
- package/dist/modules/user-profile/compressor.js +16 -0
- package/dist/modules/user-profile/index.js +1 -0
- package/dist/modules/user-profile/profile.js +68 -0
- package/dist/tools/approve.js +32 -0
- package/dist/tools/attach-image.js +89 -0
- package/dist/tools/bash.js +140 -0
- package/dist/tools/browser.js +97 -0
- package/dist/tools/create-dir.js +56 -0
- package/dist/tools/delete-file.js +63 -0
- package/dist/tools/edit-file.js +77 -0
- package/dist/tools/executor.js +95 -0
- package/dist/tools/file-info.js +45 -0
- package/dist/tools/filter-tools.js +10 -0
- package/dist/tools/glob-tool.js +26 -0
- package/dist/tools/grep-tool.js +64 -0
- package/dist/tools/index.js +52 -0
- package/dist/tools/list-dir.js +47 -0
- package/dist/tools/load-skill.js +48 -0
- package/dist/tools/mcp-call.js +68 -0
- package/dist/tools/move-file.js +84 -0
- package/dist/tools/path-utils.js +51 -0
- package/dist/tools/pipeline-run.js +144 -0
- package/dist/tools/preview.js +2 -0
- package/dist/tools/process-kill.js +29 -0
- package/dist/tools/process-list.js +38 -0
- package/dist/tools/process-log.js +41 -0
- package/dist/tools/question.js +142 -0
- package/dist/tools/read-file.js +73 -0
- package/dist/tools/recall.js +110 -0
- package/dist/tools/registry.js +36 -0
- package/dist/tools/remember.js +67 -0
- package/dist/tools/scope-check.js +30 -0
- package/dist/tools/search-history.js +64 -0
- package/dist/tools/subagent.js +142 -0
- package/dist/tools/types.js +1 -0
- package/dist/tools/user-input.js +123 -0
- package/dist/tools/web-browse.js +57 -0
- package/dist/tools/web-fetch.js +72 -0
- package/dist/tools/web-search.js +59 -0
- package/dist/tools/write-file.js +80 -0
- package/dist/ui/box.js +81 -0
- package/dist/ui/colors.js +4 -0
- package/dist/ui/diff.js +185 -0
- package/dist/ui/index.js +6 -0
- package/dist/ui/md-formatter.js +212 -0
- package/dist/ui/output.js +13 -0
- package/dist/ui/renderer.js +141 -0
- package/dist/ui/spinner.js +70 -0
- package/dist/ui/table.js +144 -0
- package/package.json +4 -4
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
import { t } from "../i18n/index";
|
|
2
|
+
import { pc } from "../ui/colors";
|
|
3
|
+
import { PromptBuilder } from "./prompt-builder";
|
|
4
|
+
import { processRegistry } from "../modules/processes";
|
|
5
|
+
import { SessionLogger } from "./session-logger";
|
|
6
|
+
import { runWithMoE } from "./agent-moe";
|
|
7
|
+
const TOOL_RESULT_MAX_TOKENS_RATIO = 0.3;
|
|
8
|
+
const TOOL_RESULT_ABSOLUTE_MAX_CHARS = 15000;
|
|
9
|
+
export class Agent {
|
|
10
|
+
deps;
|
|
11
|
+
systemPromptAdded = false;
|
|
12
|
+
shutdownRequested = false;
|
|
13
|
+
constructor(deps) {
|
|
14
|
+
this.deps = deps;
|
|
15
|
+
}
|
|
16
|
+
/** Expose context manager for REPL image attachment and other direct access. */
|
|
17
|
+
get contextManager() {
|
|
18
|
+
return this.deps.contextManager;
|
|
19
|
+
}
|
|
20
|
+
setScope() {
|
|
21
|
+
if (this.deps.scope) {
|
|
22
|
+
this.deps.toolExecutor.setScope(this.deps.scope);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
buildSystemPrompt() {
|
|
26
|
+
const systemBudget = Math.floor(this.deps.config.contextWindow *
|
|
27
|
+
this.deps.config.contextBudget.systemPrompt);
|
|
28
|
+
const builder = new PromptBuilder(systemBudget);
|
|
29
|
+
builder.addBlocks(this.deps.promptBlocks);
|
|
30
|
+
const dynamic = this.deps.getDynamicPromptBlocks?.() ?? [];
|
|
31
|
+
if (dynamic.length > 0) {
|
|
32
|
+
builder.addBlocks(dynamic);
|
|
33
|
+
}
|
|
34
|
+
const pluginBlocks = (this.deps.pluginManager.runOnBuildPrompt?.() ?? [])
|
|
35
|
+
.filter((s) => Boolean(s && s.trim() !== ""))
|
|
36
|
+
.map((content) => ({
|
|
37
|
+
content,
|
|
38
|
+
priority: "low",
|
|
39
|
+
essential: false,
|
|
40
|
+
estimatedTokens: this.deps.llmProvider.countTokens(content),
|
|
41
|
+
}));
|
|
42
|
+
if (pluginBlocks.length > 0) {
|
|
43
|
+
builder.addBlocks(pluginBlocks);
|
|
44
|
+
}
|
|
45
|
+
return builder.build();
|
|
46
|
+
}
|
|
47
|
+
refreshSystemPrompt() {
|
|
48
|
+
const { prompt } = this.buildSystemPrompt();
|
|
49
|
+
const current = this.deps.contextManager
|
|
50
|
+
.getActiveHistory()
|
|
51
|
+
.find((m) => m.role === "system");
|
|
52
|
+
if (!current || current.content !== prompt) {
|
|
53
|
+
this.deps.contextManager.updateSystemPrompt?.(prompt);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
truncateToolOutput(output, budget, currentTokens) {
|
|
57
|
+
const remainingBudget = budget.history - currentTokens;
|
|
58
|
+
const maxCharsByBudget = Math.floor(remainingBudget * 0.5 * 2);
|
|
59
|
+
const maxCharsByRatio = Math.floor(budget.history * TOOL_RESULT_MAX_TOKENS_RATIO * 2);
|
|
60
|
+
const maxChars = Math.min(maxCharsByBudget, maxCharsByRatio, TOOL_RESULT_ABSOLUTE_MAX_CHARS);
|
|
61
|
+
if (output.length <= maxChars)
|
|
62
|
+
return output;
|
|
63
|
+
const truncated = output.slice(0, maxChars);
|
|
64
|
+
const removedChars = output.length - maxChars;
|
|
65
|
+
return (truncated +
|
|
66
|
+
`\n\n${t("tool.truncated", { tokens: Math.ceil(removedChars / 2) })}`);
|
|
67
|
+
}
|
|
68
|
+
emitPhase(iteration, phase, onPhase) {
|
|
69
|
+
this.deps.pluginManager.runOnPhase?.({ iteration, logger: this.deps.logger }, phase);
|
|
70
|
+
onPhase?.(phase);
|
|
71
|
+
}
|
|
72
|
+
async run(input, onChunk, onMeta, onTool, onPhase) {
|
|
73
|
+
this.setScope();
|
|
74
|
+
const { config, llmProvider, toolExecutor, pluginManager, contextManager, logger, sessionManager, } = this.deps;
|
|
75
|
+
const slog = new SessionLogger(sessionManager);
|
|
76
|
+
if (sessionManager && !sessionManager.getActive()) {
|
|
77
|
+
sessionManager.create();
|
|
78
|
+
logger.debug(`Session started: ${sessionManager.getActive()}`);
|
|
79
|
+
}
|
|
80
|
+
if (!this.systemPromptAdded &&
|
|
81
|
+
!contextManager.getActiveHistory().some((m) => m.role === "system")) {
|
|
82
|
+
const { prompt: systemPrompt, excluded } = this.buildSystemPrompt();
|
|
83
|
+
contextManager.addMessage({ role: "system", content: systemPrompt });
|
|
84
|
+
this.systemPromptAdded = true;
|
|
85
|
+
slog.logSystem(systemPrompt.slice(0, 2000));
|
|
86
|
+
if (excluded.length > 0) {
|
|
87
|
+
slog.logSystem(`[Excluded prompt blocks: ${excluded.length}]`);
|
|
88
|
+
}
|
|
89
|
+
pluginManager.runOnSessionStart({
|
|
90
|
+
logger,
|
|
91
|
+
sessionManager: sessionManager?.getActiveMeta(),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
contextManager.addMessage({ role: "user", content: input });
|
|
95
|
+
slog.logUser(input);
|
|
96
|
+
if (config.moe?.enabled) {
|
|
97
|
+
return runWithMoE({
|
|
98
|
+
config,
|
|
99
|
+
llmProvider,
|
|
100
|
+
toolExecutor,
|
|
101
|
+
logger,
|
|
102
|
+
baseDir: this.deps.baseDir,
|
|
103
|
+
}, input, () => this.executeSingleAgentLoop(input, onChunk, onMeta, onTool, onPhase), { onMeta, onTool, onPhase });
|
|
104
|
+
}
|
|
105
|
+
return this.executeSingleAgentLoop(input, onChunk, onMeta, onTool, onPhase);
|
|
106
|
+
}
|
|
107
|
+
async executeSingleAgentLoop(input, onChunk, onMeta, onTool, onPhase) {
|
|
108
|
+
const { config, llmProvider, toolExecutor, pluginManager, contextManager, hallucinationDetector, logger, sessionManager, } = this.deps;
|
|
109
|
+
const slog = new SessionLogger(sessionManager);
|
|
110
|
+
let iteration = 0;
|
|
111
|
+
let lastText = "";
|
|
112
|
+
let hallucinationRetries = 0;
|
|
113
|
+
let lastToolSignature = "";
|
|
114
|
+
let apiPromptTokens = 0;
|
|
115
|
+
let apiCompletionTokens = 0;
|
|
116
|
+
const MAX_HALLUCINATION_RETRIES = 3;
|
|
117
|
+
let consecutiveToolFailures = 0;
|
|
118
|
+
const MAX_CONSECUTIVE_TOOL_FAILURES = 5;
|
|
119
|
+
while (iteration < config.maxToolIterations && !this.shutdownRequested) {
|
|
120
|
+
iteration++;
|
|
121
|
+
pluginManager.runOnBeforeThink({
|
|
122
|
+
iteration,
|
|
123
|
+
logger,
|
|
124
|
+
lastUserMessage: input,
|
|
125
|
+
contextManager,
|
|
126
|
+
onMeta,
|
|
127
|
+
});
|
|
128
|
+
if (contextManager.needsCompaction()) {
|
|
129
|
+
contextManager.compact();
|
|
130
|
+
logger.debug("Context compacted");
|
|
131
|
+
slog.logCompaction(`regular compaction, iteration ${iteration}`, iteration);
|
|
132
|
+
}
|
|
133
|
+
const currentTokens = contextManager.getEstimatedTokens();
|
|
134
|
+
const budget = contextManager.getBudget();
|
|
135
|
+
if (currentTokens > budget.history) {
|
|
136
|
+
contextManager.compact();
|
|
137
|
+
logger.warn(`Context overflow (${currentTokens} > ${budget.history}), forced compaction`);
|
|
138
|
+
slog.logCompaction(`forced compaction (${currentTokens} > ${budget.history}), iteration ${iteration}`, iteration, currentTokens, budget.history);
|
|
139
|
+
}
|
|
140
|
+
this.refreshSystemPrompt();
|
|
141
|
+
const history = contextManager.getActiveHistory();
|
|
142
|
+
const allTools = toolExecutor.getToolDefinitions(this.deps.toolTags);
|
|
143
|
+
slog.logToolDefs(allTools.length, allTools.map((t) => t.name), iteration);
|
|
144
|
+
let textContent = "";
|
|
145
|
+
let reasoningContent = "";
|
|
146
|
+
const toolCalls = [];
|
|
147
|
+
let sawToolCall = false;
|
|
148
|
+
let emittedReasoning = false;
|
|
149
|
+
const textChunks = [];
|
|
150
|
+
this.emitPhase(iteration, "thinking", onPhase);
|
|
151
|
+
try {
|
|
152
|
+
for await (const chunk of llmProvider.chat(history, allTools)) {
|
|
153
|
+
if (chunk.type === "text" && chunk.content) {
|
|
154
|
+
if (emittedReasoning && !textContent) {
|
|
155
|
+
onMeta?.("\n\n");
|
|
156
|
+
}
|
|
157
|
+
textContent += chunk.content;
|
|
158
|
+
textChunks.push(chunk.content);
|
|
159
|
+
}
|
|
160
|
+
if (chunk.type === "reasoning" && chunk.content) {
|
|
161
|
+
reasoningContent += chunk.content;
|
|
162
|
+
if (config.showReasoning) {
|
|
163
|
+
const metaOut = pluginManager.runOnMeta({ iteration, logger }, chunk.content);
|
|
164
|
+
if (metaOut) {
|
|
165
|
+
onMeta?.(pc.dim(metaOut));
|
|
166
|
+
}
|
|
167
|
+
emittedReasoning = true;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (chunk.type === "tool_call" && chunk.toolCall) {
|
|
171
|
+
sawToolCall = true;
|
|
172
|
+
let parsedArgs;
|
|
173
|
+
try {
|
|
174
|
+
parsedArgs = JSON.parse(chunk.toolCall.arguments);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
parsedArgs = {};
|
|
178
|
+
}
|
|
179
|
+
toolCalls.push({
|
|
180
|
+
id: chunk.toolCall.id,
|
|
181
|
+
name: chunk.toolCall.name,
|
|
182
|
+
arguments: parsedArgs,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
if (chunk.type === "done" && chunk.usage) {
|
|
186
|
+
apiPromptTokens += chunk.usage.promptTokens;
|
|
187
|
+
apiCompletionTokens += chunk.usage.completionTokens;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
catch (err) {
|
|
192
|
+
logger.error(`LLM call failed: ${err.message}`);
|
|
193
|
+
slog.logError(err.message);
|
|
194
|
+
pluginManager.runOnError({ iteration, logger }, err);
|
|
195
|
+
return {
|
|
196
|
+
success: false,
|
|
197
|
+
text: lastText,
|
|
198
|
+
error: t("error.llm", { message: err.message }),
|
|
199
|
+
iterationCount: iteration,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
this.emitPhase(iteration, "done", onPhase);
|
|
204
|
+
}
|
|
205
|
+
// Display buffered text only if no tool call in this response.
|
|
206
|
+
// When a tool call is present, text is just the model describing
|
|
207
|
+
// its tool call (e.g. raw JSON args) — suppress it.
|
|
208
|
+
if (!sawToolCall && textChunks.length > 0) {
|
|
209
|
+
for (const chunk of textChunks) {
|
|
210
|
+
const textOut = pluginManager.runOnText({ iteration, logger }, chunk);
|
|
211
|
+
onChunk?.(textOut);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
let llmResponse = null;
|
|
215
|
+
if (sawToolCall) {
|
|
216
|
+
llmResponse = { type: "tool_call", calls: toolCalls };
|
|
217
|
+
}
|
|
218
|
+
else if (textContent) {
|
|
219
|
+
llmResponse = { type: "text", content: textContent };
|
|
220
|
+
}
|
|
221
|
+
else if (reasoningContent) {
|
|
222
|
+
llmResponse = { type: "reasoning", content: reasoningContent };
|
|
223
|
+
}
|
|
224
|
+
pluginManager.runOnAfterThink({ iteration, logger }, llmResponse);
|
|
225
|
+
if (this.deps.exitOnComplete && sawToolCall) {
|
|
226
|
+
const signature = toolCalls
|
|
227
|
+
.map((tc) => `${tc.name}:${JSON.stringify(tc.arguments)}`)
|
|
228
|
+
.join("|");
|
|
229
|
+
if (signature && signature === lastToolSignature) {
|
|
230
|
+
logger.debug("Exit-on-complete: repeated identical tool call, stopping");
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
lastToolSignature = signature;
|
|
234
|
+
}
|
|
235
|
+
if (sawToolCall) {
|
|
236
|
+
slog.logAssistant(textContent || "", reasoningContent, toolCalls, iteration);
|
|
237
|
+
}
|
|
238
|
+
if (sawToolCall) {
|
|
239
|
+
contextManager.addMessage({
|
|
240
|
+
role: "assistant",
|
|
241
|
+
content: textContent || "",
|
|
242
|
+
tool_calls: toolCalls.map((tc) => ({
|
|
243
|
+
id: tc.id,
|
|
244
|
+
type: "function",
|
|
245
|
+
function: {
|
|
246
|
+
name: tc.name,
|
|
247
|
+
arguments: JSON.stringify(tc.arguments),
|
|
248
|
+
},
|
|
249
|
+
})),
|
|
250
|
+
});
|
|
251
|
+
const summaries = [];
|
|
252
|
+
let anyToolFailed = false;
|
|
253
|
+
for (const call of toolCalls) {
|
|
254
|
+
this.setScope();
|
|
255
|
+
const startTime = Date.now();
|
|
256
|
+
pluginManager.runOnToolCall({
|
|
257
|
+
toolName: call.name,
|
|
258
|
+
args: call.arguments,
|
|
259
|
+
});
|
|
260
|
+
pluginManager.runOnToolStart({ iteration, logger }, { id: call.id, name: call.name, arguments: call.arguments });
|
|
261
|
+
onTool?.({ type: "start", tool: call.name, args: call.arguments });
|
|
262
|
+
slog.logToolCall(call, iteration);
|
|
263
|
+
const result = await toolExecutor.execute(call);
|
|
264
|
+
const duration = Date.now() - startTime;
|
|
265
|
+
if (!result.success)
|
|
266
|
+
anyToolFailed = true;
|
|
267
|
+
pluginManager.runOnToolEnd({ iteration, logger }, { id: call.id, name: call.name, arguments: call.arguments }, result, duration);
|
|
268
|
+
if (result.display) {
|
|
269
|
+
onMeta?.("\n" + result.display + "\n");
|
|
270
|
+
}
|
|
271
|
+
const metaOut = pluginManager.runOnMeta({ iteration, logger }, result.output);
|
|
272
|
+
onMeta?.("\n" + pc.dim(metaOut) + "\n");
|
|
273
|
+
if (result.diff) {
|
|
274
|
+
onMeta?.("\n" + result.diff + "\n");
|
|
275
|
+
}
|
|
276
|
+
onTool?.({
|
|
277
|
+
type: "end",
|
|
278
|
+
tool: call.name,
|
|
279
|
+
args: call.arguments,
|
|
280
|
+
duration,
|
|
281
|
+
error: !result.success,
|
|
282
|
+
});
|
|
283
|
+
const currentTokens = contextManager.getEstimatedTokens();
|
|
284
|
+
const budget = contextManager.getBudget();
|
|
285
|
+
const truncatedOutput = this.truncateToolOutput(result.output, budget, currentTokens);
|
|
286
|
+
contextManager.addMessage({
|
|
287
|
+
role: "tool",
|
|
288
|
+
content: truncatedOutput,
|
|
289
|
+
name: call.name,
|
|
290
|
+
tool_call_id: call.id,
|
|
291
|
+
});
|
|
292
|
+
summaries.push(`[Tool: ${call.name} (${JSON.stringify(call.arguments)}) → ${truncatedOutput.slice(0, 200)}]`);
|
|
293
|
+
if (config.session.autoSave) {
|
|
294
|
+
slog.logToolResult(call, result, duration, iteration);
|
|
295
|
+
}
|
|
296
|
+
if (contextManager.needsCompaction()) {
|
|
297
|
+
contextManager.compact();
|
|
298
|
+
logger.debug("Context compacted after tool result");
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (anyToolFailed) {
|
|
302
|
+
consecutiveToolFailures++;
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
consecutiveToolFailures = 0;
|
|
306
|
+
}
|
|
307
|
+
if (consecutiveToolFailures >= MAX_CONSECUTIVE_TOOL_FAILURES) {
|
|
308
|
+
const recoveryMsg = t("exec.consecutive_failures_recovery", { count: consecutiveToolFailures });
|
|
309
|
+
logger.warn(`Consecutive tool failures: ${consecutiveToolFailures}`);
|
|
310
|
+
const taskSnippet = input.length > 200 ? input.slice(0, 200) + "..." : input;
|
|
311
|
+
const taskReminder = t("exec.task_reminder", { task: taskSnippet });
|
|
312
|
+
contextManager.addMessage({
|
|
313
|
+
role: "user",
|
|
314
|
+
content: `<system-summary>${recoveryMsg}\n${taskReminder}</system-summary>`,
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
contextManager.addMessage({
|
|
318
|
+
role: "user",
|
|
319
|
+
content: `<system-summary>${summaries.join("\n")}</system-summary>`,
|
|
320
|
+
});
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
const hallucinationResult = hallucinationDetector.validate(textContent);
|
|
324
|
+
if (hallucinationResult.status === "block") {
|
|
325
|
+
logger.warn(`Response blocked: ${hallucinationResult.reason}`);
|
|
326
|
+
return {
|
|
327
|
+
success: false,
|
|
328
|
+
text: lastText,
|
|
329
|
+
error: t("error.response_blocked", {
|
|
330
|
+
reason: hallucinationResult.reason || "",
|
|
331
|
+
}),
|
|
332
|
+
iterationCount: iteration,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
if (hallucinationResult.status === "warn") {
|
|
336
|
+
logger.warn(`Hallucination warning: ${hallucinationResult.reason}`);
|
|
337
|
+
const warnPrefix = t("hall.uncertainty_prefix");
|
|
338
|
+
if (onChunk) {
|
|
339
|
+
onChunk(warnPrefix);
|
|
340
|
+
}
|
|
341
|
+
lastText = warnPrefix + lastText;
|
|
342
|
+
}
|
|
343
|
+
if (hallucinationResult.status === "retry") {
|
|
344
|
+
if (this.deps.exitOnComplete) {
|
|
345
|
+
logger.debug("Exit-on-complete: stopping on first response");
|
|
346
|
+
break;
|
|
347
|
+
}
|
|
348
|
+
if (hallucinationRetries >= MAX_HALLUCINATION_RETRIES) {
|
|
349
|
+
logger.warn(`Hallucination retries exhausted (${MAX_HALLUCINATION_RETRIES}), returning error`);
|
|
350
|
+
return {
|
|
351
|
+
success: false,
|
|
352
|
+
text: lastText,
|
|
353
|
+
error: t("error.response_blocked", {
|
|
354
|
+
reason: t("hall.max_retries_exhausted"),
|
|
355
|
+
}),
|
|
356
|
+
iterationCount: iteration,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
hallucinationRetries++;
|
|
360
|
+
logger.warn(`Hallucination retry (${hallucinationRetries}/${MAX_HALLUCINATION_RETRIES}): ${hallucinationResult.reason}`);
|
|
361
|
+
if (textContent) {
|
|
362
|
+
contextManager.addMessage({
|
|
363
|
+
role: "assistant",
|
|
364
|
+
content: textContent,
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
contextManager.addMessage({
|
|
368
|
+
role: "user",
|
|
369
|
+
content: `<system-summary>[Retry context: ${hallucinationResult.reason}. Original task: "${input}". You must either call a needed tool or provide a substantive response. Empty replies are not allowed.]</system-summary>`,
|
|
370
|
+
});
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
if (textContent) {
|
|
374
|
+
contextManager.addMessage({ role: "assistant", content: textContent });
|
|
375
|
+
slog.saveAssistantMessage(textContent);
|
|
376
|
+
slog.logAssistant(textContent, reasoningContent, undefined, iteration);
|
|
377
|
+
}
|
|
378
|
+
lastText = textContent;
|
|
379
|
+
if (!sawToolCall) {
|
|
380
|
+
if (this.deps.finalAudit) {
|
|
381
|
+
const audit = await this.deps.finalAudit();
|
|
382
|
+
if (audit && !audit.passed) {
|
|
383
|
+
logger.warn(`Final audit incomplete: ${audit.summary}`);
|
|
384
|
+
const steps = audit.pendingSteps.slice(0, 5).join("; ") || "—";
|
|
385
|
+
contextManager.addMessage({
|
|
386
|
+
role: "user",
|
|
387
|
+
content: `<system-summary>${t("exec.audit_incomplete", {
|
|
388
|
+
summary: audit.summary,
|
|
389
|
+
steps,
|
|
390
|
+
})}</system-summary>`,
|
|
391
|
+
});
|
|
392
|
+
slog.logAudit(audit.summary, iteration);
|
|
393
|
+
if (iteration >= config.maxToolIterations - 1) {
|
|
394
|
+
break;
|
|
395
|
+
}
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
break;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const tokensUsed = contextManager.getEstimatedTokens();
|
|
403
|
+
const budget = contextManager.getBudget();
|
|
404
|
+
if (iteration >= config.maxToolIterations) {
|
|
405
|
+
return {
|
|
406
|
+
success: false,
|
|
407
|
+
text: lastText,
|
|
408
|
+
error: t("error.max_iters", { max: config.maxToolIterations }),
|
|
409
|
+
iterationCount: iteration,
|
|
410
|
+
contextUsed: tokensUsed,
|
|
411
|
+
contextLimit: budget.history,
|
|
412
|
+
promptTokens: apiPromptTokens,
|
|
413
|
+
completionTokens: apiCompletionTokens,
|
|
414
|
+
totalTokens: apiPromptTokens + apiCompletionTokens,
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
return {
|
|
418
|
+
success: true,
|
|
419
|
+
text: lastText,
|
|
420
|
+
iterationCount: iteration,
|
|
421
|
+
contextUsed: tokensUsed,
|
|
422
|
+
contextLimit: budget.history,
|
|
423
|
+
promptTokens: apiPromptTokens,
|
|
424
|
+
completionTokens: apiCompletionTokens,
|
|
425
|
+
totalTokens: apiPromptTokens + apiCompletionTokens,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
clearContext() {
|
|
429
|
+
this.deps.contextManager.clear();
|
|
430
|
+
this.systemPromptAdded = false;
|
|
431
|
+
}
|
|
432
|
+
setContext(messages) {
|
|
433
|
+
const { contextManager } = this.deps;
|
|
434
|
+
contextManager.clear();
|
|
435
|
+
const { prompt: systemPrompt } = this.buildSystemPrompt();
|
|
436
|
+
contextManager.addMessage({ role: "system", content: systemPrompt });
|
|
437
|
+
this.systemPromptAdded = true;
|
|
438
|
+
for (const msg of messages) {
|
|
439
|
+
if (msg.role === "system")
|
|
440
|
+
continue;
|
|
441
|
+
contextManager.addMessage({
|
|
442
|
+
role: msg.role,
|
|
443
|
+
content: msg.content,
|
|
444
|
+
name: msg.name,
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
shutdown() {
|
|
449
|
+
this.shutdownRequested = true;
|
|
450
|
+
const { pluginManager, logger, sessionManager, contextManager } = this.deps;
|
|
451
|
+
contextManager.onCompact = null;
|
|
452
|
+
const killed = processRegistry.killAll();
|
|
453
|
+
if (killed > 0) {
|
|
454
|
+
logger.info(`Killed ${killed} background process(es) on shutdown`);
|
|
455
|
+
}
|
|
456
|
+
pluginManager.runOnSessionEnd({
|
|
457
|
+
logger,
|
|
458
|
+
sessionManager: sessionManager?.getActiveMeta(),
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
}
|