micro-models-agent 0.19.0 → 0.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/dist/main.js +179 -358
  2. package/package.json +1 -1
  3. package/dist/cli/commands.js +0 -237
  4. package/dist/cli/completer.js +0 -168
  5. package/dist/cli/index.js +0 -2
  6. package/dist/cli/main.js +0 -113
  7. package/dist/cli/repl.js +0 -1010
  8. package/dist/cli/security-commands.js +0 -166
  9. package/dist/cli/setup.js +0 -229
  10. package/dist/config/config.js +0 -186
  11. package/dist/config/defaults.js +0 -91
  12. package/dist/config/experts.js +0 -15
  13. package/dist/config/index.js +0 -3
  14. package/dist/config/security.js +0 -193
  15. package/dist/config/types.js +0 -1
  16. package/dist/core/agent-moe.js +0 -98
  17. package/dist/core/agent.js +0 -471
  18. package/dist/core/bootstrap.js +0 -314
  19. package/dist/core/index.js +0 -2
  20. package/dist/core/prompt-builder.js +0 -55
  21. package/dist/core/session-logger.js +0 -122
  22. package/dist/core/types.js +0 -1
  23. package/dist/i18n/en.json +0 -461
  24. package/dist/i18n/index.js +0 -43
  25. package/dist/i18n/ru.json +0 -461
  26. package/dist/index.js +0 -22
  27. package/dist/llm/image-utils.js +0 -144
  28. package/dist/llm/index.js +0 -4
  29. package/dist/llm/model-loader.js +0 -78
  30. package/dist/llm/openai-compat.js +0 -324
  31. package/dist/llm/orchestrator.js +0 -194
  32. package/dist/llm/provider.js +0 -10
  33. package/dist/llm/response.js +0 -39
  34. package/dist/llm/token-counter.js +0 -39
  35. package/dist/llm/types.js +0 -1
  36. package/dist/logger/app-logger.js +0 -76
  37. package/dist/logger/index.js +0 -1
  38. package/dist/migration/backup.js +0 -45
  39. package/dist/migration/detect.js +0 -50
  40. package/dist/migration/index.js +0 -2
  41. package/dist/modules/browser/actions.js +0 -46
  42. package/dist/modules/browser/cookie-store.js +0 -24
  43. package/dist/modules/browser/index.js +0 -5
  44. package/dist/modules/browser/module.js +0 -28
  45. package/dist/modules/browser/session.js +0 -287
  46. package/dist/modules/browser/snapshot.js +0 -114
  47. package/dist/modules/browser/types.js +0 -9
  48. package/dist/modules/context/index.js +0 -1
  49. package/dist/modules/context/manager.js +0 -240
  50. package/dist/modules/execution/auditor.js +0 -72
  51. package/dist/modules/execution/index.js +0 -6
  52. package/dist/modules/execution/module.js +0 -337
  53. package/dist/modules/execution/moe-executor.js +0 -209
  54. package/dist/modules/execution/plan-validator.js +0 -153
  55. package/dist/modules/execution/planner.js +0 -35
  56. package/dist/modules/execution/stuck-detector.js +0 -134
  57. package/dist/modules/execution/tracker.js +0 -53
  58. package/dist/modules/execution/types.js +0 -1
  59. package/dist/modules/execution/verifier.js +0 -149
  60. package/dist/modules/hallucination/confidence.js +0 -59
  61. package/dist/modules/hallucination/consistency.js +0 -66
  62. package/dist/modules/hallucination/detector.js +0 -33
  63. package/dist/modules/hallucination/factual.js +0 -561
  64. package/dist/modules/hallucination/index.js +0 -3
  65. package/dist/modules/index.js +0 -5
  66. package/dist/modules/indexer/cache.js +0 -38
  67. package/dist/modules/indexer/index.js +0 -3
  68. package/dist/modules/indexer/module.js +0 -192
  69. package/dist/modules/indexer/walker.js +0 -101
  70. package/dist/modules/mcp/client.js +0 -393
  71. package/dist/modules/mcp/index.js +0 -3
  72. package/dist/modules/mcp/module.js +0 -146
  73. package/dist/modules/mcp/registry.js +0 -15
  74. package/dist/modules/memory/index.js +0 -1
  75. package/dist/modules/memory/module.js +0 -48
  76. package/dist/modules/memory/search.js +0 -40
  77. package/dist/modules/memory/store.js +0 -65
  78. package/dist/modules/pipelines/engine.js +0 -60
  79. package/dist/modules/pipelines/index.js +0 -3
  80. package/dist/modules/pipelines/parser.js +0 -53
  81. package/dist/modules/pipelines/template.js +0 -14
  82. package/dist/modules/plugins/builtin/lint-on-write.js +0 -121
  83. package/dist/modules/plugins/builtin/notify.js +0 -8
  84. package/dist/modules/plugins/index.js +0 -1
  85. package/dist/modules/plugins/loader.js +0 -28
  86. package/dist/modules/plugins/manager.js +0 -161
  87. package/dist/modules/plugins/types.js +0 -1
  88. package/dist/modules/processes/detect.js +0 -34
  89. package/dist/modules/processes/index.js +0 -3
  90. package/dist/modules/processes/registry.js +0 -148
  91. package/dist/modules/processes/runner.js +0 -124
  92. package/dist/modules/registry.js +0 -45
  93. package/dist/modules/security/audit-log.js +0 -116
  94. package/dist/modules/security/audit-notifier.js +0 -292
  95. package/dist/modules/security/command-validator.js +0 -185
  96. package/dist/modules/security/content-scanner.js +0 -52
  97. package/dist/modules/security/data-sanitizer.js +0 -97
  98. package/dist/modules/security/encryption.js +0 -240
  99. package/dist/modules/security/index.js +0 -14
  100. package/dist/modules/security/network-validator.js +0 -79
  101. package/dist/modules/security/path-validator.js +0 -155
  102. package/dist/modules/security/rate-limiter.js +0 -119
  103. package/dist/modules/security/security-policies.js +0 -393
  104. package/dist/modules/security/session-encryption.js +0 -193
  105. package/dist/modules/security/session-isolation.js +0 -95
  106. package/dist/modules/session/index.js +0 -3
  107. package/dist/modules/session/manager.js +0 -167
  108. package/dist/modules/session/module.js +0 -24
  109. package/dist/modules/session/store.js +0 -174
  110. package/dist/modules/session/types.js +0 -1
  111. package/dist/modules/skills/index.js +0 -3
  112. package/dist/modules/skills/loader.js +0 -72
  113. package/dist/modules/skills/matcher.js +0 -27
  114. package/dist/modules/skills/module.js +0 -143
  115. package/dist/modules/types.js +0 -1
  116. package/dist/modules/updater/checker.js +0 -32
  117. package/dist/modules/updater/index.js +0 -1
  118. package/dist/modules/user-profile/compressor.js +0 -16
  119. package/dist/modules/user-profile/index.js +0 -1
  120. package/dist/modules/user-profile/profile.js +0 -68
  121. package/dist/skills/builtin/builtin/git.md +0 -36
  122. package/dist/skills/builtin/builtin/typescript.md +0 -35
  123. package/dist/tools/approve.js +0 -32
  124. package/dist/tools/attach-image.js +0 -89
  125. package/dist/tools/bash.js +0 -140
  126. package/dist/tools/browser.js +0 -97
  127. package/dist/tools/create-dir.js +0 -55
  128. package/dist/tools/delete-file.js +0 -62
  129. package/dist/tools/edit-file.js +0 -77
  130. package/dist/tools/executor.js +0 -95
  131. package/dist/tools/file-info.js +0 -45
  132. package/dist/tools/filter-tools.js +0 -10
  133. package/dist/tools/glob-tool.js +0 -26
  134. package/dist/tools/grep-tool.js +0 -64
  135. package/dist/tools/index.js +0 -52
  136. package/dist/tools/list-dir.js +0 -47
  137. package/dist/tools/load-skill.js +0 -48
  138. package/dist/tools/mcp-call.js +0 -68
  139. package/dist/tools/move-file.js +0 -84
  140. package/dist/tools/path-utils.js +0 -51
  141. package/dist/tools/pipeline-run.js +0 -144
  142. package/dist/tools/preview.js +0 -2
  143. package/dist/tools/process-kill.js +0 -29
  144. package/dist/tools/process-list.js +0 -38
  145. package/dist/tools/process-log.js +0 -41
  146. package/dist/tools/question.js +0 -142
  147. package/dist/tools/read-file.js +0 -70
  148. package/dist/tools/recall.js +0 -110
  149. package/dist/tools/registry.js +0 -36
  150. package/dist/tools/remember.js +0 -67
  151. package/dist/tools/scope-check.js +0 -30
  152. package/dist/tools/search-history.js +0 -64
  153. package/dist/tools/subagent.js +0 -142
  154. package/dist/tools/types.js +0 -1
  155. package/dist/tools/user-input.js +0 -123
  156. package/dist/tools/web-browse.js +0 -57
  157. package/dist/tools/web-fetch.js +0 -72
  158. package/dist/tools/web-search.js +0 -59
  159. package/dist/tools/write-file.js +0 -79
  160. package/dist/ui/box.js +0 -81
  161. package/dist/ui/colors.js +0 -4
  162. package/dist/ui/diff.js +0 -185
  163. package/dist/ui/index.js +0 -6
  164. package/dist/ui/md-formatter.js +0 -212
  165. package/dist/ui/output.js +0 -13
  166. package/dist/ui/renderer.js +0 -141
  167. package/dist/ui/spinner.js +0 -70
  168. package/dist/ui/table.js +0 -144
@@ -1,471 +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", {
309
- count: consecutiveToolFailures,
310
- });
311
- logger.warn(`Consecutive tool failures: ${consecutiveToolFailures}`);
312
- const taskSnippet = input.length > 200 ? input.slice(0, 200) + "..." : input;
313
- const taskReminder = t("exec.task_reminder", { task: taskSnippet });
314
- contextManager.addMessage({
315
- role: "user",
316
- content: `<system-summary>${recoveryMsg}\n${taskReminder}</system-summary>`,
317
- });
318
- }
319
- contextManager.addMessage({
320
- role: "user",
321
- content: `<system-summary>${summaries.join("\n")}</system-summary>`,
322
- });
323
- const ctxTokens = contextManager.getEstimatedTokens();
324
- const ctxBudget = contextManager.getBudget();
325
- const ctxPct = Math.min(100, Math.round((ctxTokens / ctxBudget.history) * 100));
326
- const barLen = 10;
327
- const filled = Math.round((ctxPct / 100) * barLen);
328
- const ctxBar = pc.green("█".repeat(filled)) + pc.dim("░".repeat(barLen - filled));
329
- const pctColor = ctxPct >= 75 ? pc.yellow : pc.dim;
330
- onMeta?.(`\n ${ctxBar} ${pctColor(`${ctxPct}%`)} ${pc.dim(`ctx: ${ctxTokens}/${ctxBudget.history}`)}\n`);
331
- continue;
332
- }
333
- const hallucinationResult = hallucinationDetector.validate(textContent);
334
- if (hallucinationResult.status === "block") {
335
- logger.warn(`Response blocked: ${hallucinationResult.reason}`);
336
- return {
337
- success: false,
338
- text: lastText,
339
- error: t("error.response_blocked", {
340
- reason: hallucinationResult.reason || "",
341
- }),
342
- iterationCount: iteration,
343
- };
344
- }
345
- if (hallucinationResult.status === "warn") {
346
- logger.warn(`Hallucination warning: ${hallucinationResult.reason}`);
347
- const warnPrefix = t("hall.uncertainty_prefix");
348
- if (onChunk) {
349
- onChunk(warnPrefix);
350
- }
351
- lastText = warnPrefix + lastText;
352
- }
353
- if (hallucinationResult.status === "retry") {
354
- if (this.deps.exitOnComplete) {
355
- logger.debug("Exit-on-complete: stopping on first response");
356
- break;
357
- }
358
- if (hallucinationRetries >= MAX_HALLUCINATION_RETRIES) {
359
- logger.warn(`Hallucination retries exhausted (${MAX_HALLUCINATION_RETRIES}), returning error`);
360
- return {
361
- success: false,
362
- text: lastText,
363
- error: t("error.response_blocked", {
364
- reason: t("hall.max_retries_exhausted"),
365
- }),
366
- iterationCount: iteration,
367
- };
368
- }
369
- hallucinationRetries++;
370
- logger.warn(`Hallucination retry (${hallucinationRetries}/${MAX_HALLUCINATION_RETRIES}): ${hallucinationResult.reason}`);
371
- if (textContent) {
372
- contextManager.addMessage({
373
- role: "assistant",
374
- content: textContent,
375
- });
376
- }
377
- contextManager.addMessage({
378
- role: "user",
379
- 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>`,
380
- });
381
- continue;
382
- }
383
- if (textContent) {
384
- contextManager.addMessage({ role: "assistant", content: textContent });
385
- slog.saveAssistantMessage(textContent);
386
- slog.logAssistant(textContent, reasoningContent, undefined, iteration);
387
- }
388
- lastText = textContent;
389
- if (!sawToolCall) {
390
- if (this.deps.finalAudit) {
391
- const audit = await this.deps.finalAudit();
392
- if (audit && !audit.passed) {
393
- logger.warn(`Final audit incomplete: ${audit.summary}`);
394
- const steps = audit.pendingSteps.slice(0, 5).join("; ") || "—";
395
- contextManager.addMessage({
396
- role: "user",
397
- content: `<system-summary>${t("exec.audit_incomplete", {
398
- summary: audit.summary,
399
- steps,
400
- })}</system-summary>`,
401
- });
402
- slog.logAudit(audit.summary, iteration);
403
- if (iteration >= config.maxToolIterations - 1) {
404
- break;
405
- }
406
- continue;
407
- }
408
- }
409
- break;
410
- }
411
- }
412
- const tokensUsed = contextManager.getEstimatedTokens();
413
- const budget = contextManager.getBudget();
414
- if (iteration >= config.maxToolIterations) {
415
- return {
416
- success: false,
417
- text: lastText,
418
- error: t("error.max_iters", { max: config.maxToolIterations }),
419
- iterationCount: iteration,
420
- contextUsed: tokensUsed,
421
- contextLimit: budget.history,
422
- promptTokens: apiPromptTokens,
423
- completionTokens: apiCompletionTokens,
424
- totalTokens: apiPromptTokens + apiCompletionTokens,
425
- };
426
- }
427
- return {
428
- success: true,
429
- text: lastText,
430
- iterationCount: iteration,
431
- contextUsed: tokensUsed,
432
- contextLimit: budget.history,
433
- promptTokens: apiPromptTokens,
434
- completionTokens: apiCompletionTokens,
435
- totalTokens: apiPromptTokens + apiCompletionTokens,
436
- };
437
- }
438
- clearContext() {
439
- this.deps.contextManager.clear();
440
- this.systemPromptAdded = false;
441
- }
442
- setContext(messages) {
443
- const { contextManager } = this.deps;
444
- contextManager.clear();
445
- const { prompt: systemPrompt } = this.buildSystemPrompt();
446
- contextManager.addMessage({ role: "system", content: systemPrompt });
447
- this.systemPromptAdded = true;
448
- for (const msg of messages) {
449
- if (msg.role === "system")
450
- continue;
451
- contextManager.addMessage({
452
- role: msg.role,
453
- content: msg.content,
454
- name: msg.name,
455
- });
456
- }
457
- }
458
- shutdown() {
459
- this.shutdownRequested = true;
460
- const { pluginManager, logger, sessionManager, contextManager } = this.deps;
461
- contextManager.onCompact = null;
462
- const killed = processRegistry.killAll();
463
- if (killed > 0) {
464
- logger.info(`Killed ${killed} background process(es) on shutdown`);
465
- }
466
- pluginManager.runOnSessionEnd({
467
- logger,
468
- sessionManager: sessionManager?.getActiveMeta(),
469
- });
470
- }
471
- }