micro-models-agent 0.23.0 → 0.24.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.
Files changed (171) hide show
  1. package/README.md +312 -312
  2. package/bin/mma.mjs +8 -8
  3. package/dist/main.js +8777 -864
  4. package/package.json +4 -3
  5. package/dist/cli/commands.js +0 -220
  6. package/dist/cli/completer.js +0 -168
  7. package/dist/cli/index.js +0 -2
  8. package/dist/cli/main.js +0 -113
  9. package/dist/cli/repl.js +0 -987
  10. package/dist/cli/security-commands.js +0 -166
  11. package/dist/cli/setup.js +0 -229
  12. package/dist/config/config.js +0 -186
  13. package/dist/config/defaults.js +0 -91
  14. package/dist/config/experts.js +0 -15
  15. package/dist/config/index.js +0 -3
  16. package/dist/config/security.js +0 -193
  17. package/dist/config/types.js +0 -1
  18. package/dist/core/agent-moe.js +0 -98
  19. package/dist/core/agent.js +0 -461
  20. package/dist/core/bootstrap.js +0 -321
  21. package/dist/core/index.js +0 -2
  22. package/dist/core/prompt-builder.js +0 -55
  23. package/dist/core/session-logger.js +0 -122
  24. package/dist/core/types.js +0 -1
  25. package/dist/i18n/en.json +0 -461
  26. package/dist/i18n/index.js +0 -43
  27. package/dist/i18n/ru.json +0 -461
  28. package/dist/index.js +0 -22
  29. package/dist/llm/image-utils.js +0 -144
  30. package/dist/llm/index.js +0 -4
  31. package/dist/llm/model-loader.js +0 -78
  32. package/dist/llm/openai-compat.js +0 -324
  33. package/dist/llm/orchestrator.js +0 -194
  34. package/dist/llm/provider.js +0 -10
  35. package/dist/llm/response.js +0 -39
  36. package/dist/llm/token-counter.js +0 -39
  37. package/dist/llm/types.js +0 -1
  38. package/dist/logger/app-logger.js +0 -76
  39. package/dist/logger/index.js +0 -1
  40. package/dist/migration/backup.js +0 -45
  41. package/dist/migration/detect.js +0 -50
  42. package/dist/migration/index.js +0 -2
  43. package/dist/modules/browser/actions.js +0 -46
  44. package/dist/modules/browser/cookie-store.js +0 -24
  45. package/dist/modules/browser/index.js +0 -5
  46. package/dist/modules/browser/module.js +0 -28
  47. package/dist/modules/browser/session.js +0 -287
  48. package/dist/modules/browser/snapshot.js +0 -114
  49. package/dist/modules/browser/types.js +0 -9
  50. package/dist/modules/context/history.js +0 -15
  51. package/dist/modules/context/index.js +0 -1
  52. package/dist/modules/context/manager.js +0 -240
  53. package/dist/modules/execution/auditor.js +0 -72
  54. package/dist/modules/execution/index.js +0 -6
  55. package/dist/modules/execution/module.js +0 -337
  56. package/dist/modules/execution/moe-executor.js +0 -209
  57. package/dist/modules/execution/plan-validator.js +0 -153
  58. package/dist/modules/execution/planner.js +0 -35
  59. package/dist/modules/execution/stuck-detector.js +0 -134
  60. package/dist/modules/execution/tracker.js +0 -53
  61. package/dist/modules/execution/types.js +0 -1
  62. package/dist/modules/execution/verifier.js +0 -149
  63. package/dist/modules/hallucination/confidence.js +0 -54
  64. package/dist/modules/hallucination/consistency.js +0 -60
  65. package/dist/modules/hallucination/detector.js +0 -41
  66. package/dist/modules/hallucination/factual.js +0 -170
  67. package/dist/modules/hallucination/index.js +0 -4
  68. package/dist/modules/index.js +0 -5
  69. package/dist/modules/indexer/cache.js +0 -38
  70. package/dist/modules/indexer/index.js +0 -3
  71. package/dist/modules/indexer/module.js +0 -192
  72. package/dist/modules/indexer/walker.js +0 -101
  73. package/dist/modules/mcp/client.js +0 -393
  74. package/dist/modules/mcp/index.js +0 -3
  75. package/dist/modules/mcp/module.js +0 -146
  76. package/dist/modules/mcp/registry.js +0 -15
  77. package/dist/modules/memory/index.js +0 -1
  78. package/dist/modules/memory/module.js +0 -48
  79. package/dist/modules/memory/search.js +0 -40
  80. package/dist/modules/memory/store.js +0 -65
  81. package/dist/modules/pipelines/engine.js +0 -60
  82. package/dist/modules/pipelines/index.js +0 -3
  83. package/dist/modules/pipelines/parser.js +0 -53
  84. package/dist/modules/pipelines/template.js +0 -14
  85. package/dist/modules/plugins/builtin/lint-on-write.js +0 -121
  86. package/dist/modules/plugins/builtin/notify.js +0 -8
  87. package/dist/modules/plugins/index.js +0 -1
  88. package/dist/modules/plugins/loader.js +0 -28
  89. package/dist/modules/plugins/manager.js +0 -161
  90. package/dist/modules/plugins/types.js +0 -1
  91. package/dist/modules/processes/detect.js +0 -34
  92. package/dist/modules/processes/index.js +0 -3
  93. package/dist/modules/processes/registry.js +0 -148
  94. package/dist/modules/processes/runner.js +0 -124
  95. package/dist/modules/registry.js +0 -45
  96. package/dist/modules/security/audit-log.js +0 -116
  97. package/dist/modules/security/audit-notifier.js +0 -292
  98. package/dist/modules/security/command-validator.js +0 -185
  99. package/dist/modules/security/content-scanner.js +0 -52
  100. package/dist/modules/security/data-sanitizer.js +0 -97
  101. package/dist/modules/security/encryption.js +0 -240
  102. package/dist/modules/security/index.js +0 -14
  103. package/dist/modules/security/network-validator.js +0 -79
  104. package/dist/modules/security/path-validator.js +0 -155
  105. package/dist/modules/security/rate-limiter.js +0 -119
  106. package/dist/modules/security/security-policies.js +0 -393
  107. package/dist/modules/security/session-encryption.js +0 -193
  108. package/dist/modules/security/session-isolation.js +0 -95
  109. package/dist/modules/session/index.js +0 -3
  110. package/dist/modules/session/manager.js +0 -167
  111. package/dist/modules/session/module.js +0 -24
  112. package/dist/modules/session/store.js +0 -174
  113. package/dist/modules/session/types.js +0 -1
  114. package/dist/modules/skills/index.js +0 -3
  115. package/dist/modules/skills/loader.js +0 -72
  116. package/dist/modules/skills/matcher.js +0 -27
  117. package/dist/modules/skills/module.js +0 -143
  118. package/dist/modules/types.js +0 -1
  119. package/dist/modules/updater/checker.js +0 -32
  120. package/dist/modules/updater/index.js +0 -1
  121. package/dist/modules/user-profile/compressor.js +0 -16
  122. package/dist/modules/user-profile/index.js +0 -1
  123. package/dist/modules/user-profile/profile.js +0 -68
  124. package/dist/skills/builtin/builtin/git.md +0 -36
  125. package/dist/skills/builtin/builtin/typescript.md +0 -35
  126. package/dist/tools/approve.js +0 -32
  127. package/dist/tools/attach-image.js +0 -89
  128. package/dist/tools/bash.js +0 -140
  129. package/dist/tools/browser.js +0 -97
  130. package/dist/tools/create-dir.js +0 -56
  131. package/dist/tools/delete-file.js +0 -63
  132. package/dist/tools/edit-file.js +0 -77
  133. package/dist/tools/executor.js +0 -95
  134. package/dist/tools/file-info.js +0 -45
  135. package/dist/tools/filter-tools.js +0 -10
  136. package/dist/tools/glob-tool.js +0 -26
  137. package/dist/tools/grep-tool.js +0 -64
  138. package/dist/tools/index.js +0 -52
  139. package/dist/tools/list-dir.js +0 -47
  140. package/dist/tools/load-skill.js +0 -48
  141. package/dist/tools/mcp-call.js +0 -68
  142. package/dist/tools/move-file.js +0 -84
  143. package/dist/tools/path-utils.js +0 -51
  144. package/dist/tools/pipeline-run.js +0 -144
  145. package/dist/tools/preview.js +0 -2
  146. package/dist/tools/process-kill.js +0 -29
  147. package/dist/tools/process-list.js +0 -38
  148. package/dist/tools/process-log.js +0 -41
  149. package/dist/tools/question.js +0 -142
  150. package/dist/tools/read-file.js +0 -73
  151. package/dist/tools/recall.js +0 -110
  152. package/dist/tools/registry.js +0 -36
  153. package/dist/tools/remember.js +0 -67
  154. package/dist/tools/scope-check.js +0 -30
  155. package/dist/tools/search-history.js +0 -64
  156. package/dist/tools/subagent.js +0 -142
  157. package/dist/tools/types.js +0 -1
  158. package/dist/tools/user-input.js +0 -123
  159. package/dist/tools/web-browse.js +0 -57
  160. package/dist/tools/web-fetch.js +0 -72
  161. package/dist/tools/web-search.js +0 -59
  162. package/dist/tools/write-file.js +0 -80
  163. package/dist/ui/box.js +0 -81
  164. package/dist/ui/colors.js +0 -4
  165. package/dist/ui/diff.js +0 -185
  166. package/dist/ui/index.js +0 -6
  167. package/dist/ui/md-formatter.js +0 -212
  168. package/dist/ui/output.js +0 -13
  169. package/dist/ui/renderer.js +0 -141
  170. package/dist/ui/spinner.js +0 -70
  171. package/dist/ui/table.js +0 -144
@@ -1,461 +0,0 @@
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
- }