micro-models-agent 0.7.9 → 0.8.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 +173 -0
- package/dist/cli/completer.js +168 -0
- package/dist/cli/index.js +2 -0
- package/dist/cli/main.js +95 -0
- package/dist/cli/repl.js +762 -0
- package/dist/cli/security-commands.js +166 -0
- package/dist/cli/setup.js +214 -0
- package/dist/config/config.js +123 -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 +187 -0
- package/dist/config/types.js +1 -0
- package/dist/core/agent.js +626 -0
- package/dist/core/bootstrap.js +307 -0
- package/dist/core/index.js +2 -0
- package/dist/core/prompt-builder.js +55 -0
- package/dist/core/types.js +1 -0
- package/dist/i18n/en.json +405 -0
- package/dist/i18n/index.js +43 -0
- package/dist/i18n/ru.json +405 -0
- package/dist/index.js +22 -0
- package/dist/llm/index.js +4 -0
- package/dist/llm/model-loader.js +78 -0
- package/dist/llm/openai-compat.js +277 -0
- package/dist/llm/orchestrator.js +194 -0
- package/dist/llm/provider.js +2 -0
- package/dist/llm/response.js +39 -0
- package/dist/llm/token-counter.js +37 -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/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 +179 -0
- package/dist/modules/execution/auditor.js +72 -0
- package/dist/modules/execution/index.js +6 -0
- package/dist/modules/execution/module.js +334 -0
- package/dist/modules/execution/moe-executor.js +196 -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 +113 -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 +47 -0
- package/dist/modules/hallucination/consistency.js +32 -0
- package/dist/modules/hallucination/detector.js +41 -0
- package/dist/modules/hallucination/factual.js +128 -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/search.js +26 -0
- package/dist/modules/memory/store.js +38 -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/registry.js +45 -0
- package/dist/modules/security/audit-log.js +108 -0
- package/dist/modules/security/audit-notifier.js +292 -0
- package/dist/modules/security/command-validator.js +91 -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 +218 -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 +28 -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 +180 -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/bash.js +77 -0
- package/dist/tools/browser.js +97 -0
- package/dist/tools/create-dir.js +57 -0
- package/dist/tools/delete-file.js +64 -0
- package/dist/tools/edit-file.js +78 -0
- package/dist/tools/executor.js +83 -0
- package/dist/tools/file-info.js +46 -0
- package/dist/tools/filter-tools.js +10 -0
- package/dist/tools/glob-tool.js +19 -0
- package/dist/tools/grep-tool.js +51 -0
- package/dist/tools/index.js +44 -0
- package/dist/tools/list-dir.js +40 -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/pipeline-run.js +39 -0
- package/dist/tools/question.js +142 -0
- package/dist/tools/read-file.js +65 -0
- package/dist/tools/registry.js +36 -0
- package/dist/tools/scope-check.js +30 -0
- package/dist/tools/search-history.js +64 -0
- package/dist/tools/subagent.js +130 -0
- package/dist/tools/types.js +1 -0
- package/dist/tools/user-input.js +123 -0
- package/dist/tools/web-browse.js +51 -0
- package/dist/tools/web-fetch.js +62 -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 +1 -1
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { TokenCounter } from "./token-counter";
|
|
2
|
+
import { t } from "../i18n/index";
|
|
3
|
+
import { createRateLimiter } from "../modules/security/rate-limiter";
|
|
4
|
+
export class OpenAICompatProvider {
|
|
5
|
+
model;
|
|
6
|
+
contextWindow;
|
|
7
|
+
config;
|
|
8
|
+
tokenCounter;
|
|
9
|
+
retryConfig;
|
|
10
|
+
rateLimiter;
|
|
11
|
+
constructor(config) {
|
|
12
|
+
this.config = config;
|
|
13
|
+
this.model = config.model;
|
|
14
|
+
this.contextWindow = config.contextWindow ?? 32768;
|
|
15
|
+
this.tokenCounter = new TokenCounter();
|
|
16
|
+
this.retryConfig = config.retry ?? {
|
|
17
|
+
maxRetries: 3,
|
|
18
|
+
baseDelay: 1000,
|
|
19
|
+
maxDelay: 30000,
|
|
20
|
+
};
|
|
21
|
+
this.rateLimiter = createRateLimiter(config.rateLimits);
|
|
22
|
+
}
|
|
23
|
+
async *chat(messages, tools) {
|
|
24
|
+
// Check rate limit before making request
|
|
25
|
+
if (!this.rateLimiter.canMakeRequest()) {
|
|
26
|
+
throw new Error(`Rate limit exceeded: ${this.rateLimiter.getConfig().maxRequestsPerMinute} requests per minute`);
|
|
27
|
+
}
|
|
28
|
+
// Record this request
|
|
29
|
+
this.rateLimiter.recordRequest();
|
|
30
|
+
const streamResult = this.doStream(messages, tools);
|
|
31
|
+
let hasToolCall = false;
|
|
32
|
+
let hasText = false;
|
|
33
|
+
let reasoningAcc = "";
|
|
34
|
+
for await (const chunk of streamResult) {
|
|
35
|
+
if (chunk.type === "tool_call")
|
|
36
|
+
hasToolCall = true;
|
|
37
|
+
if (chunk.type === "text")
|
|
38
|
+
hasText = true;
|
|
39
|
+
if (chunk.type === "reasoning" && chunk.content) {
|
|
40
|
+
reasoningAcc += chunk.content;
|
|
41
|
+
}
|
|
42
|
+
yield chunk;
|
|
43
|
+
}
|
|
44
|
+
if (!hasToolCall && !hasText) {
|
|
45
|
+
const fallback = await this.doNonStreaming(messages, tools);
|
|
46
|
+
for (const chunk of fallback) {
|
|
47
|
+
yield chunk;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async *doStream(messages, tools) {
|
|
52
|
+
const body = {
|
|
53
|
+
model: this.model,
|
|
54
|
+
messages,
|
|
55
|
+
stream: true,
|
|
56
|
+
max_tokens: this.config.maxCompletionTokens ?? 4096,
|
|
57
|
+
};
|
|
58
|
+
if (tools && tools.length > 0) {
|
|
59
|
+
body.tools = tools.map((t) => ({
|
|
60
|
+
type: "function",
|
|
61
|
+
function: {
|
|
62
|
+
name: t.name,
|
|
63
|
+
description: t.description,
|
|
64
|
+
parameters: t.parameters,
|
|
65
|
+
},
|
|
66
|
+
}));
|
|
67
|
+
body.tool_choice = "auto";
|
|
68
|
+
}
|
|
69
|
+
const headers = {
|
|
70
|
+
"Content-Type": "application/json",
|
|
71
|
+
};
|
|
72
|
+
if (this.config.apiKey && this.config.apiKey !== "not-needed") {
|
|
73
|
+
headers["Authorization"] = `Bearer ${this.config.apiKey}`;
|
|
74
|
+
}
|
|
75
|
+
const controller = new AbortController();
|
|
76
|
+
const totalTimeoutMs = 120000;
|
|
77
|
+
const timeoutId = setTimeout(() => controller.abort(), totalTimeoutMs);
|
|
78
|
+
const response = await this.fetchWithRetry(`${this.config.baseUrl}/chat/completions`, {
|
|
79
|
+
method: "POST",
|
|
80
|
+
headers,
|
|
81
|
+
body: JSON.stringify(body),
|
|
82
|
+
signal: controller.signal,
|
|
83
|
+
});
|
|
84
|
+
if (!response.ok) {
|
|
85
|
+
clearTimeout(timeoutId);
|
|
86
|
+
const errorText = await response.text();
|
|
87
|
+
throw new Error(t("error.llm_api", {
|
|
88
|
+
status: response.status,
|
|
89
|
+
statusText: response.statusText,
|
|
90
|
+
errorText,
|
|
91
|
+
}));
|
|
92
|
+
}
|
|
93
|
+
const reader = response.body?.getReader();
|
|
94
|
+
if (!reader) {
|
|
95
|
+
clearTimeout(timeoutId);
|
|
96
|
+
throw new Error(t("error.no_response_body"));
|
|
97
|
+
}
|
|
98
|
+
const decoder = new TextDecoder();
|
|
99
|
+
let buffer = "";
|
|
100
|
+
const toolCallAccs = new Map();
|
|
101
|
+
try {
|
|
102
|
+
while (true) {
|
|
103
|
+
const { done, value } = await reader.read();
|
|
104
|
+
if (done)
|
|
105
|
+
break;
|
|
106
|
+
buffer += decoder.decode(value, { stream: true });
|
|
107
|
+
const lines = buffer.split("\n");
|
|
108
|
+
buffer = lines.pop() || "";
|
|
109
|
+
for (const line of lines) {
|
|
110
|
+
const trimmed = line.trim();
|
|
111
|
+
if (!trimmed || !trimmed.startsWith("data: "))
|
|
112
|
+
continue;
|
|
113
|
+
const data = trimmed.slice(6);
|
|
114
|
+
if (data === "[DONE]")
|
|
115
|
+
continue;
|
|
116
|
+
try {
|
|
117
|
+
const parsed = JSON.parse(data);
|
|
118
|
+
const choice = parsed.choices?.[0];
|
|
119
|
+
if (!choice)
|
|
120
|
+
continue;
|
|
121
|
+
const delta = choice.delta || {};
|
|
122
|
+
const finishReason = choice.finish_reason;
|
|
123
|
+
if (delta.reasoning_content) {
|
|
124
|
+
yield { type: "reasoning", content: delta.reasoning_content };
|
|
125
|
+
}
|
|
126
|
+
if (delta.tool_calls) {
|
|
127
|
+
for (const tc of delta.tool_calls) {
|
|
128
|
+
const idx = tc.index ?? 0;
|
|
129
|
+
if (!toolCallAccs.has(idx)) {
|
|
130
|
+
toolCallAccs.set(idx, { id: "", name: "", arguments: "" });
|
|
131
|
+
}
|
|
132
|
+
const acc = toolCallAccs.get(idx);
|
|
133
|
+
if (tc.id)
|
|
134
|
+
acc.id = tc.id;
|
|
135
|
+
if (tc.function?.name)
|
|
136
|
+
acc.name = tc.function.name;
|
|
137
|
+
if (tc.function?.arguments) {
|
|
138
|
+
acc.arguments += tc.function.arguments;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (delta.content) {
|
|
143
|
+
yield { type: "text", content: delta.content };
|
|
144
|
+
}
|
|
145
|
+
if (finishReason === "tool_calls" && toolCallAccs.size > 0) {
|
|
146
|
+
for (const [, acc] of toolCallAccs) {
|
|
147
|
+
if (acc.name) {
|
|
148
|
+
yield {
|
|
149
|
+
type: "tool_call",
|
|
150
|
+
toolCall: {
|
|
151
|
+
id: acc.id,
|
|
152
|
+
name: acc.name,
|
|
153
|
+
arguments: acc.arguments || "{}",
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
toolCallAccs.clear();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
// Skip malformed JSON lines
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
clearTimeout(timeoutId);
|
|
169
|
+
reader.releaseLock();
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
async doNonStreaming(messages, tools) {
|
|
173
|
+
const body = {
|
|
174
|
+
model: this.model,
|
|
175
|
+
messages,
|
|
176
|
+
stream: false,
|
|
177
|
+
max_tokens: this.config.maxCompletionTokens ?? 4096,
|
|
178
|
+
};
|
|
179
|
+
if (tools && tools.length > 0) {
|
|
180
|
+
body.tools = tools.map((t) => ({
|
|
181
|
+
type: "function",
|
|
182
|
+
function: {
|
|
183
|
+
name: t.name,
|
|
184
|
+
description: t.description,
|
|
185
|
+
parameters: t.parameters,
|
|
186
|
+
},
|
|
187
|
+
}));
|
|
188
|
+
body.tool_choice = "auto";
|
|
189
|
+
}
|
|
190
|
+
const headers = {
|
|
191
|
+
"Content-Type": "application/json",
|
|
192
|
+
};
|
|
193
|
+
if (this.config.apiKey && this.config.apiKey !== "not-needed") {
|
|
194
|
+
headers["Authorization"] = `Bearer ${this.config.apiKey}`;
|
|
195
|
+
}
|
|
196
|
+
try {
|
|
197
|
+
const response = await this.fetchWithRetry(`${this.config.baseUrl}/chat/completions`, {
|
|
198
|
+
method: "POST",
|
|
199
|
+
headers,
|
|
200
|
+
body: JSON.stringify(body),
|
|
201
|
+
});
|
|
202
|
+
if (!response.ok) {
|
|
203
|
+
const errorText = await response.text();
|
|
204
|
+
console.error("[doNonStreaming] HTTP error:", response.status, errorText.slice(0, 500));
|
|
205
|
+
return [];
|
|
206
|
+
}
|
|
207
|
+
const data = await response.json();
|
|
208
|
+
const choice = data.choices?.[0];
|
|
209
|
+
if (!choice) {
|
|
210
|
+
console.error("[doNonStreaming] No choices in response");
|
|
211
|
+
return [];
|
|
212
|
+
}
|
|
213
|
+
const msg = choice.message || {};
|
|
214
|
+
const chunks = [];
|
|
215
|
+
if (msg.reasoning_content) {
|
|
216
|
+
chunks.push({ type: "reasoning", content: msg.reasoning_content });
|
|
217
|
+
}
|
|
218
|
+
if (msg.content) {
|
|
219
|
+
chunks.push({ type: "text", content: msg.content });
|
|
220
|
+
}
|
|
221
|
+
if (msg.tool_calls) {
|
|
222
|
+
for (const tc of msg.tool_calls) {
|
|
223
|
+
chunks.push({
|
|
224
|
+
type: "tool_call",
|
|
225
|
+
toolCall: {
|
|
226
|
+
id: tc.id || "",
|
|
227
|
+
name: tc.function?.name || "",
|
|
228
|
+
arguments: tc.function?.arguments || "{}",
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
console.error("[doNonStreaming] chunks:", chunks.length, "tool_calls:", msg.tool_calls?.length, "content len:", msg.content?.length);
|
|
234
|
+
if (chunks.length === 0) {
|
|
235
|
+
console.error("[doNonStreaming] Empty response: no content, no tool_calls, no reasoning");
|
|
236
|
+
}
|
|
237
|
+
return chunks;
|
|
238
|
+
}
|
|
239
|
+
catch (err) {
|
|
240
|
+
console.error("[doNonStreaming] Fetch error:", err instanceof Error ? err.message : String(err));
|
|
241
|
+
return [];
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
countTokens(text) {
|
|
245
|
+
return this.tokenCounter.count(text);
|
|
246
|
+
}
|
|
247
|
+
async fetchWithRetry(url, init) {
|
|
248
|
+
const { maxRetries, baseDelay, maxDelay } = this.retryConfig;
|
|
249
|
+
let lastError = null;
|
|
250
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
251
|
+
try {
|
|
252
|
+
const response = await fetch(url, init);
|
|
253
|
+
if (!this.isRetryable(response.status))
|
|
254
|
+
return response;
|
|
255
|
+
lastError = new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
256
|
+
}
|
|
257
|
+
catch (err) {
|
|
258
|
+
if (err.name === "AbortError") {
|
|
259
|
+
throw err;
|
|
260
|
+
}
|
|
261
|
+
lastError = err;
|
|
262
|
+
}
|
|
263
|
+
if (attempt < maxRetries) {
|
|
264
|
+
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
|
|
265
|
+
const jitter = Math.random() * baseDelay * 0.1;
|
|
266
|
+
await this.sleep(delay + jitter);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
throw lastError ?? new Error(t("error.llm_retries"));
|
|
270
|
+
}
|
|
271
|
+
isRetryable(status) {
|
|
272
|
+
return status === 429 || status >= 500;
|
|
273
|
+
}
|
|
274
|
+
sleep(ms) {
|
|
275
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
276
|
+
}
|
|
277
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { OpenAICompatProvider } from './openai-compat';
|
|
2
|
+
import { jsonrepair } from 'jsonrepair';
|
|
3
|
+
const PLAN_SYSTEM_PROMPT = `You are a planning assistant for an agent system with multiple expert sub-agents.
|
|
4
|
+
Break down the user's task into subtasks that can be executed by different expert agents.
|
|
5
|
+
|
|
6
|
+
Available experts and their tool tags:
|
|
7
|
+
- code: file operations, code editing, shell commands
|
|
8
|
+
- research: web search, web fetch, web browse, history search
|
|
9
|
+
- browser: browser automation, screenshots
|
|
10
|
+
- vision: browser + file reading for visual tasks
|
|
11
|
+
|
|
12
|
+
Rules:
|
|
13
|
+
1. Each subtask must have an expert_tag from the available experts.
|
|
14
|
+
2. Use depends_on for ordering when subtask B reads what subtask A writes.
|
|
15
|
+
3. Independent subtasks should NOT depend on each other (they run in parallel).
|
|
16
|
+
4. allowed_files is for files the subtask will CREATE or MODIFY.
|
|
17
|
+
5. read_only_files is for files the subtask needs to READ only.
|
|
18
|
+
6. File paths should be relative to the workspace root.
|
|
19
|
+
7. Do NOT use keyword matching to determine task type. Instead, analyze the actual nature of the task.
|
|
20
|
+
|
|
21
|
+
Respond with a JSON object only (no markdown fences):
|
|
22
|
+
{
|
|
23
|
+
"title": "Plan title",
|
|
24
|
+
"subtasks": [
|
|
25
|
+
{
|
|
26
|
+
"id": "task-1",
|
|
27
|
+
"description": "Clear description",
|
|
28
|
+
"expert_tag": "code",
|
|
29
|
+
"allowed_files": ["src/file.ts"],
|
|
30
|
+
"read_only_files": [],
|
|
31
|
+
"depends_on": [],
|
|
32
|
+
"input_from": [],
|
|
33
|
+
"expected_output": "What this subtask produces",
|
|
34
|
+
"success_criteria": ["criterion 1", "criterion 2"]
|
|
35
|
+
}
|
|
36
|
+
],
|
|
37
|
+
"shared_context": {
|
|
38
|
+
"rules": ["rule 1"],
|
|
39
|
+
"refs": []
|
|
40
|
+
}
|
|
41
|
+
}`;
|
|
42
|
+
const VERIFY_SYSTEM_PROMPT = `You are a verification and merge assistant for an agent system with multiple expert sub-agents.
|
|
43
|
+
You receive the original plan, the results from each subtask, and any verification errors.
|
|
44
|
+
Your job is to determine if the overall task was completed successfully or if re-planning is needed.
|
|
45
|
+
|
|
46
|
+
Respond with JSON only:
|
|
47
|
+
- If successful: {"type": "final", "finalAnswer": "summary of results", "explanation": "details"}
|
|
48
|
+
- If re-plan needed: {"type": "replan", "plan": {updated MoEPlan}, "explanation": "why re-plan is needed"}
|
|
49
|
+
|
|
50
|
+
Max 3 re-plan cycles. After 3 cycles, return partial result.`;
|
|
51
|
+
export class OrchestratorClient {
|
|
52
|
+
config;
|
|
53
|
+
provider = null;
|
|
54
|
+
replanCycle = 0;
|
|
55
|
+
constructor(config, defaultProvider) {
|
|
56
|
+
this.config = config;
|
|
57
|
+
if (config.model) {
|
|
58
|
+
if (config.provider) {
|
|
59
|
+
this.provider = new OpenAICompatProvider({
|
|
60
|
+
model: config.model,
|
|
61
|
+
baseUrl: config.provider.baseUrl || 'http://localhost:1234/v1',
|
|
62
|
+
apiKey: config.provider.apiKey,
|
|
63
|
+
retry: config.retry,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
else if (defaultProvider) {
|
|
67
|
+
this.provider = defaultProvider;
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
this.provider = new OpenAICompatProvider({
|
|
71
|
+
model: config.model,
|
|
72
|
+
baseUrl: 'http://localhost:1234/v1',
|
|
73
|
+
retry: config.retry,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
isEnabled() {
|
|
79
|
+
return this.provider !== null;
|
|
80
|
+
}
|
|
81
|
+
getReplanCycle() {
|
|
82
|
+
return this.replanCycle;
|
|
83
|
+
}
|
|
84
|
+
async chat(messages) {
|
|
85
|
+
if (!this.provider)
|
|
86
|
+
throw new Error('Orchestrator not enabled');
|
|
87
|
+
const chunks = [];
|
|
88
|
+
for await (const chunk of this.provider.chat(messages)) {
|
|
89
|
+
chunks.push(chunk);
|
|
90
|
+
}
|
|
91
|
+
return chunks
|
|
92
|
+
.filter((c) => c.type === 'text')
|
|
93
|
+
.map((c) => c.content)
|
|
94
|
+
.join('');
|
|
95
|
+
}
|
|
96
|
+
parseJSON(text) {
|
|
97
|
+
try {
|
|
98
|
+
return JSON.parse(text);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
try {
|
|
102
|
+
const repaired = jsonrepair(text);
|
|
103
|
+
return JSON.parse(repaired);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
const jsonMatch = text.match(/\{[\s\S]*\}/);
|
|
107
|
+
if (jsonMatch) {
|
|
108
|
+
try {
|
|
109
|
+
const repaired = jsonrepair(jsonMatch[0]);
|
|
110
|
+
return JSON.parse(repaired);
|
|
111
|
+
}
|
|
112
|
+
catch { /* fall through */ }
|
|
113
|
+
}
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async plan(userPrompt, _context) {
|
|
119
|
+
if (!this.provider)
|
|
120
|
+
return { error: 'Orchestrator not enabled — no orchestrator model configured' };
|
|
121
|
+
const messages = [
|
|
122
|
+
{ role: 'system', content: PLAN_SYSTEM_PROMPT },
|
|
123
|
+
{ role: 'user', content: userPrompt },
|
|
124
|
+
];
|
|
125
|
+
const text = await this.chat(messages);
|
|
126
|
+
const parsed = this.parseJSON(text);
|
|
127
|
+
if (parsed && parsed.subtasks && parsed.subtasks.length > 0) {
|
|
128
|
+
return { plan: parsed, raw: text };
|
|
129
|
+
}
|
|
130
|
+
return { error: `Failed to parse plan from LLM output. Raw: ${text.slice(0, 500)}` };
|
|
131
|
+
}
|
|
132
|
+
async verifyAndMerge(input) {
|
|
133
|
+
if (!this.provider)
|
|
134
|
+
return { type: 'final', finalAnswer: input.results.map(r => r.summary).join('\n') };
|
|
135
|
+
this.replanCycle++;
|
|
136
|
+
if (this.replanCycle > 3) {
|
|
137
|
+
return {
|
|
138
|
+
type: 'final',
|
|
139
|
+
finalAnswer: input.results.map(r => `${r.subtaskId}: ${r.success ? 'OK' : 'FAIL'} — ${r.summary}`).join('\n'),
|
|
140
|
+
explanation: 'Max re-plan cycles (3) reached. Returning partial results.',
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
const context = JSON.stringify(input, null, 2);
|
|
144
|
+
const messages = [
|
|
145
|
+
{ role: 'system', content: VERIFY_SYSTEM_PROMPT },
|
|
146
|
+
{ role: 'user', content: context },
|
|
147
|
+
];
|
|
148
|
+
const text = await this.chat(messages);
|
|
149
|
+
const parsed = this.parseJSON(text);
|
|
150
|
+
if (parsed && parsed.type) {
|
|
151
|
+
return parsed;
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
type: 'final',
|
|
155
|
+
finalAnswer: input.results.map(r => r.summary).join('\n'),
|
|
156
|
+
explanation: 'Failed to parse verifier output, returning collected results.',
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
async createPlan(task) {
|
|
160
|
+
if (!this.provider)
|
|
161
|
+
throw new Error('Orchestrator not enabled');
|
|
162
|
+
const messages = [
|
|
163
|
+
{
|
|
164
|
+
role: 'system',
|
|
165
|
+
content: 'You are a planning assistant. Break down tasks into steps. Respond with JSON only: {"steps": ["step 1", "step 2", ...]}',
|
|
166
|
+
},
|
|
167
|
+
{ role: 'user', content: task },
|
|
168
|
+
];
|
|
169
|
+
const text = await this.chat(messages);
|
|
170
|
+
try {
|
|
171
|
+
return JSON.parse(text);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return { steps: [task] };
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
async resolveConflict(context) {
|
|
178
|
+
if (!this.provider)
|
|
179
|
+
throw new Error('Orchestrator not enabled');
|
|
180
|
+
const messages = [
|
|
181
|
+
{
|
|
182
|
+
role: 'system',
|
|
183
|
+
content: 'You are a conflict resolution assistant. Analyze the situation and recommend the best path forward.',
|
|
184
|
+
},
|
|
185
|
+
{ role: 'user', content: context },
|
|
186
|
+
];
|
|
187
|
+
let result = '';
|
|
188
|
+
for await (const chunk of this.provider.chat(messages)) {
|
|
189
|
+
if (chunk.type === 'text' && chunk.content)
|
|
190
|
+
result += chunk.content;
|
|
191
|
+
}
|
|
192
|
+
return result;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export function parseChunks(chunks) {
|
|
2
|
+
let text = '';
|
|
3
|
+
let reasoning;
|
|
4
|
+
const toolCalls = [];
|
|
5
|
+
let hasToolCalls = false;
|
|
6
|
+
for (const chunk of chunks) {
|
|
7
|
+
if (chunk.type === 'text' && chunk.content) {
|
|
8
|
+
text += chunk.content;
|
|
9
|
+
}
|
|
10
|
+
if (chunk.type === 'reasoning' && chunk.content) {
|
|
11
|
+
reasoning = (reasoning || '') + chunk.content;
|
|
12
|
+
}
|
|
13
|
+
if (chunk.type === 'tool_call' && chunk.toolCall) {
|
|
14
|
+
hasToolCalls = true;
|
|
15
|
+
let parsedArgs;
|
|
16
|
+
try {
|
|
17
|
+
parsedArgs = JSON.parse(chunk.toolCall.arguments);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
parsedArgs = {};
|
|
21
|
+
}
|
|
22
|
+
toolCalls.push({
|
|
23
|
+
id: chunk.toolCall.id,
|
|
24
|
+
name: chunk.toolCall.name,
|
|
25
|
+
arguments: parsedArgs,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if (hasToolCalls) {
|
|
30
|
+
return { type: 'tool_call', calls: toolCalls, reasoning };
|
|
31
|
+
}
|
|
32
|
+
if (reasoning && !text) {
|
|
33
|
+
return { type: 'reasoning', content: reasoning };
|
|
34
|
+
}
|
|
35
|
+
if (!text && !reasoning) {
|
|
36
|
+
return { type: 'empty' };
|
|
37
|
+
}
|
|
38
|
+
return { type: 'text', content: text || '', reasoning };
|
|
39
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// src/llm/token-counter.ts
|
|
2
|
+
import { encodingForModel, getEncoding } from "js-tiktoken";
|
|
3
|
+
export class TokenCounter {
|
|
4
|
+
encoder;
|
|
5
|
+
constructor(model = "gpt-4o") {
|
|
6
|
+
try {
|
|
7
|
+
this.encoder = encodingForModel(model);
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
// Fallback to cl100k_base for unknown models
|
|
11
|
+
this.encoder = getEncoding("cl100k_base");
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
count(text) {
|
|
15
|
+
if (!text)
|
|
16
|
+
return 0;
|
|
17
|
+
return this.encoder.encode(text).length;
|
|
18
|
+
}
|
|
19
|
+
countMessages(messages) {
|
|
20
|
+
let total = 0;
|
|
21
|
+
for (const msg of messages) {
|
|
22
|
+
// ~4 tokens per message overhead (role, boundaries)
|
|
23
|
+
total += 4;
|
|
24
|
+
total += this.count(msg.content);
|
|
25
|
+
if (msg.role === "tool")
|
|
26
|
+
total += 2; // tool_call_id
|
|
27
|
+
}
|
|
28
|
+
total += 2; // assistant priming
|
|
29
|
+
return total;
|
|
30
|
+
}
|
|
31
|
+
encode(text) {
|
|
32
|
+
return this.encoder.encode(text);
|
|
33
|
+
}
|
|
34
|
+
decode(tokens) {
|
|
35
|
+
return this.encoder.decode(tokens);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync, existsSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
import { sanitizeLogMessage } from '../modules/security/data-sanitizer';
|
|
4
|
+
const LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
5
|
+
export class Logger {
|
|
6
|
+
level;
|
|
7
|
+
prefix;
|
|
8
|
+
logDir = null;
|
|
9
|
+
constructor(level = 'info', prefix = '') {
|
|
10
|
+
this.level = level;
|
|
11
|
+
this.prefix = prefix;
|
|
12
|
+
}
|
|
13
|
+
setLevel(level) {
|
|
14
|
+
this.level = level;
|
|
15
|
+
}
|
|
16
|
+
setLogDir(dir) {
|
|
17
|
+
this.logDir = dir;
|
|
18
|
+
if (!existsSync(dir)) {
|
|
19
|
+
mkdirSync(dir, { recursive: true });
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
child(prefix) {
|
|
23
|
+
const childLogger = new Logger(this.level, this.prefix ? `${this.prefix}:${prefix}` : prefix);
|
|
24
|
+
if (this.logDir)
|
|
25
|
+
childLogger.setLogDir(this.logDir);
|
|
26
|
+
return childLogger;
|
|
27
|
+
}
|
|
28
|
+
debug(msg, meta) {
|
|
29
|
+
this.log('debug', msg, meta);
|
|
30
|
+
}
|
|
31
|
+
info(msg, meta) {
|
|
32
|
+
this.log('info', msg, meta);
|
|
33
|
+
}
|
|
34
|
+
warn(msg, meta) {
|
|
35
|
+
this.log('warn', msg, meta);
|
|
36
|
+
}
|
|
37
|
+
error(msg, meta) {
|
|
38
|
+
this.log('error', msg, meta);
|
|
39
|
+
}
|
|
40
|
+
log(level, msg, meta) {
|
|
41
|
+
if (LEVELS[level] < LEVELS[this.level])
|
|
42
|
+
return;
|
|
43
|
+
// Sanitize log message to remove sensitive data
|
|
44
|
+
const sanitizedMsg = sanitizeLogMessage(msg);
|
|
45
|
+
const sanitizedMeta = meta ? this.sanitizeMeta(meta) : undefined;
|
|
46
|
+
const ts = new Date().toISOString();
|
|
47
|
+
const prefix = this.prefix ? ` [${this.prefix}]` : '';
|
|
48
|
+
const metaStr = sanitizedMeta ? ` ${JSON.stringify(sanitizedMeta)}` : '';
|
|
49
|
+
const line = `[${level.toUpperCase()}]${prefix} ${ts} — ${sanitizedMsg}${metaStr}`;
|
|
50
|
+
console.log(line);
|
|
51
|
+
if (this.logDir) {
|
|
52
|
+
try {
|
|
53
|
+
appendFileSync(join(this.logDir, 'app.jsonl'), JSON.stringify({ level, ts, prefix: this.prefix, msg: sanitizedMsg, meta: sanitizedMeta ?? null }) + '\n', 'utf-8');
|
|
54
|
+
}
|
|
55
|
+
catch { /* file logging is best-effort */ }
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Sanitize metadata object to remove sensitive data
|
|
60
|
+
*/
|
|
61
|
+
sanitizeMeta(meta) {
|
|
62
|
+
const sanitized = {};
|
|
63
|
+
for (const [key, value] of Object.entries(meta)) {
|
|
64
|
+
if (typeof value === 'string') {
|
|
65
|
+
sanitized[key] = sanitizeLogMessage(value);
|
|
66
|
+
}
|
|
67
|
+
else if (typeof value === 'object' && value !== null) {
|
|
68
|
+
sanitized[key] = this.sanitizeMeta(value);
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
sanitized[key] = value;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return sanitized;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { Logger } from './app-logger';
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { copyFileSync, cpSync, existsSync, mkdirSync, readdirSync, writeFileSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
import { t } from '../i18n/index';
|
|
4
|
+
export class BackupManager {
|
|
5
|
+
configDir;
|
|
6
|
+
constructor(configDir) {
|
|
7
|
+
this.configDir = configDir;
|
|
8
|
+
}
|
|
9
|
+
backupConfig() {
|
|
10
|
+
const configPath = join(this.configDir, 'config.json');
|
|
11
|
+
if (!existsSync(configPath))
|
|
12
|
+
return;
|
|
13
|
+
const bakPath = join(this.configDir, 'config.json.bak');
|
|
14
|
+
copyFileSync(configPath, bakPath);
|
|
15
|
+
}
|
|
16
|
+
backupAll() {
|
|
17
|
+
const bakDir = this.configDir + '.bak';
|
|
18
|
+
if (existsSync(bakDir))
|
|
19
|
+
return;
|
|
20
|
+
if (existsSync(this.configDir)) {
|
|
21
|
+
cpSync(this.configDir, bakDir, { recursive: true });
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
writeFreshConfig(config) {
|
|
25
|
+
if (!existsSync(this.configDir)) {
|
|
26
|
+
mkdirSync(this.configDir, { recursive: true });
|
|
27
|
+
}
|
|
28
|
+
writeFileSync(join(this.configDir, 'config.json'), JSON.stringify(config, null, 2), 'utf-8');
|
|
29
|
+
}
|
|
30
|
+
getBackupSummary() {
|
|
31
|
+
const lines = [];
|
|
32
|
+
const bakConfig = join(this.configDir, 'config.json.bak');
|
|
33
|
+
const bakDir = this.configDir + '.bak';
|
|
34
|
+
if (existsSync(bakConfig)) {
|
|
35
|
+
lines.push(t('migration.config_bak'));
|
|
36
|
+
}
|
|
37
|
+
if (existsSync(bakDir)) {
|
|
38
|
+
const files = readdirSync(bakDir);
|
|
39
|
+
lines.push(t('migration.dir_bak', { count: files.length }));
|
|
40
|
+
}
|
|
41
|
+
return lines.length > 0
|
|
42
|
+
? `${t('migration.migrated')}\n${lines.join('\n')}`
|
|
43
|
+
: t('migration.not_needed');
|
|
44
|
+
}
|
|
45
|
+
}
|