micro-models-agent 0.56.5 → 0.57.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.
- package/CHANGELOG.md +481 -463
- package/README.md +358 -358
- package/dist/certification/certifications.json +493 -493
- package/dist/cli/commands.js +447 -0
- package/dist/cli/completer.js +167 -0
- package/dist/cli/index.js +2 -0
- package/dist/cli/main.js +153 -0
- package/dist/cli/plugin-commands.js +36 -0
- package/dist/cli/repl-commands.js +761 -0
- package/dist/cli/repl.js +702 -0
- package/dist/cli/run-result.js +33 -0
- package/dist/cli/security-commands.js +164 -0
- package/dist/cli/setup.js +237 -0
- package/dist/config/config.js +276 -0
- package/dist/config/defaults.js +141 -0
- package/dist/config/domains.js +179 -0
- package/dist/config/experts.js +15 -0
- package/dist/config/index.js +4 -0
- package/dist/config/security.js +213 -0
- package/dist/config/types.js +1 -0
- package/dist/core/agent-moe.js +102 -0
- package/dist/core/agent.js +1018 -0
- package/dist/core/bootstrap.js +481 -0
- package/dist/core/crash-handler.js +51 -0
- package/dist/core/environment.js +199 -0
- package/dist/core/index.js +2 -0
- package/dist/core/prompt-builder.js +76 -0
- package/dist/core/session-logger.js +251 -0
- package/dist/core/types.js +1 -0
- package/dist/core/version.js +26 -0
- package/dist/core/workspace.js +76 -0
- package/dist/i18n/en.json +679 -0
- package/dist/i18n/index.js +46 -0
- package/dist/i18n/ru.json +679 -0
- package/dist/index.js +22 -0
- package/dist/llm/image-utils.js +143 -0
- package/dist/llm/index.js +4 -0
- package/dist/llm/model-loader.js +78 -0
- package/dist/llm/openai-compat.js +497 -0
- package/dist/llm/orchestrator.js +200 -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 +189 -0
- package/dist/logger/file-log.js +151 -0
- package/dist/logger/index.js +1 -0
- package/dist/main.js +457 -324
- package/dist/migration/backup.js +45 -0
- package/dist/migration/detect.js +50 -0
- package/dist/migration/index.js +2 -0
- package/dist/modules/artifacts/store.js +61 -0
- package/dist/modules/browser/actions.js +76 -0
- package/dist/modules/browser/bridge-client.js +199 -0
- package/dist/modules/browser/bridge-path.js +10 -0
- package/dist/modules/browser/bridge-server.mjs +219 -219
- package/dist/modules/browser/cookie-store.js +24 -0
- package/dist/modules/browser/driver.js +136 -0
- package/dist/modules/browser/index.js +7 -0
- package/dist/modules/browser/module.js +29 -0
- package/dist/modules/browser/session.js +342 -0
- package/dist/modules/browser/snapshot.js +148 -0
- package/dist/modules/browser/types.js +12 -0
- package/dist/modules/certification/cli.js +213 -0
- package/dist/modules/certification/fact-checker.js +82 -0
- package/dist/modules/certification/loader.js +106 -0
- package/dist/modules/certification/manifest.js +58 -0
- package/dist/modules/certification/runner.js +245 -0
- package/dist/modules/certification/scenarios.js +407 -0
- package/dist/modules/certification/types.js +1 -0
- package/dist/modules/context/chunk-query.js +100 -0
- package/dist/modules/context/fact-extractor.js +168 -0
- package/dist/modules/context/history.js +15 -0
- package/dist/modules/context/index.js +1 -0
- package/dist/modules/context/manager.js +440 -0
- package/dist/modules/execution/audit-runners.js +206 -0
- package/dist/modules/execution/auditor.js +218 -0
- package/dist/modules/execution/execution-plugin.js +431 -0
- package/dist/modules/execution/index.js +8 -0
- package/dist/modules/execution/module.js +625 -0
- package/dist/modules/execution/moe-executor.js +304 -0
- package/dist/modules/execution/plan-coverage.js +68 -0
- package/dist/modules/execution/plan-persister.js +46 -0
- package/dist/modules/execution/plan-store.js +196 -0
- package/dist/modules/execution/plan-tool.js +677 -0
- package/dist/modules/execution/plan-validator.js +153 -0
- package/dist/modules/execution/planner.js +94 -0
- package/dist/modules/execution/stuck-detector.js +746 -0
- package/dist/modules/execution/tracker.js +69 -0
- package/dist/modules/execution/types.js +1 -0
- package/dist/modules/execution/verifier.js +235 -0
- package/dist/modules/execution/windows-commands.js +41 -0
- package/dist/modules/hallucination/confidence.js +66 -0
- package/dist/modules/hallucination/consistency.js +26 -0
- package/dist/modules/hallucination/detector.js +47 -0
- package/dist/modules/hallucination/factual.js +169 -0
- package/dist/modules/hallucination/index.js +5 -0
- package/dist/modules/hallucination/js-identifiers.js +262 -0
- package/dist/modules/hallucination/llm-judge.js +101 -0
- package/dist/modules/index.js +5 -0
- package/dist/modules/indexer/cache.js +40 -0
- package/dist/modules/indexer/index.js +3 -0
- package/dist/modules/indexer/module.js +246 -0
- package/dist/modules/indexer/project-profile.js +183 -0
- package/dist/modules/indexer/walker.js +101 -0
- package/dist/modules/lsp/check-tool.js +58 -0
- package/dist/modules/lsp/client.js +389 -0
- package/dist/modules/lsp/command.js +60 -0
- package/dist/modules/lsp/config.js +135 -0
- package/dist/modules/lsp/index.js +3 -0
- package/dist/modules/lsp/module.js +260 -0
- package/dist/modules/lsp/probe.js +86 -0
- package/dist/modules/lsp/project-root.js +32 -0
- package/dist/modules/lsp/startup-check.js +144 -0
- package/dist/modules/lsp/types.js +1 -0
- package/dist/modules/mcp/client.js +399 -0
- package/dist/modules/mcp/index.js +3 -0
- package/dist/modules/mcp/module.js +142 -0
- package/dist/modules/mcp/registry.js +15 -0
- package/dist/modules/memory/index.js +1 -0
- package/dist/modules/memory/module.js +96 -0
- package/dist/modules/memory/search.js +42 -0
- package/dist/modules/memory/store.js +69 -0
- package/dist/modules/pipelines/engine.js +60 -0
- package/dist/modules/pipelines/index.js +3 -0
- package/dist/modules/pipelines/parser.js +56 -0
- package/dist/modules/pipelines/template.js +14 -0
- package/dist/modules/plugins/builtin/lint-on-write.js +334 -0
- package/dist/modules/plugins/builtin/notify.js +9 -0
- package/dist/modules/plugins/index.js +1 -0
- package/dist/modules/plugins/loader.js +70 -0
- package/dist/modules/plugins/manager.js +261 -0
- package/dist/modules/plugins/types.js +1 -0
- package/dist/modules/pricing/index.js +61 -0
- package/dist/modules/pricing/prices.js +129 -0
- package/dist/modules/processes/detect.js +34 -0
- package/dist/modules/processes/index.js +2 -0
- package/dist/modules/processes/registry.js +327 -0
- package/dist/modules/processes/runner.js +23 -0
- package/dist/modules/providers/create.js +22 -0
- package/dist/modules/providers/fallback.js +79 -0
- package/dist/modules/providers/health.js +46 -0
- package/dist/modules/providers/index.js +5 -0
- package/dist/modules/providers/manager.js +161 -0
- package/dist/modules/providers/presets.js +128 -0
- package/dist/modules/providers/registry.js +22 -0
- package/dist/modules/providers/types.js +1 -0
- package/dist/modules/registry.js +48 -0
- package/dist/modules/security/audit-log.js +136 -0
- package/dist/modules/security/audit-notifier.js +292 -0
- package/dist/modules/security/command-validator.js +219 -0
- package/dist/modules/security/content-scanner.js +53 -0
- package/dist/modules/security/data-sanitizer.js +89 -0
- package/dist/modules/security/encryption.js +242 -0
- package/dist/modules/security/index.js +14 -0
- package/dist/modules/security/network-validator.js +88 -0
- package/dist/modules/security/path-validator.js +203 -0
- package/dist/modules/security/rate-limiter.js +119 -0
- package/dist/modules/security/security-policies.js +531 -0
- package/dist/modules/security/session-encryption.js +210 -0
- package/dist/modules/security/session-isolation.js +95 -0
- package/dist/modules/session/index.js +3 -0
- package/dist/modules/session/manager.js +172 -0
- package/dist/modules/session/module.js +24 -0
- package/dist/modules/session/store.js +222 -0
- package/dist/modules/session/types.js +1 -0
- package/dist/modules/skills/index.js +2 -0
- package/dist/modules/skills/loader.js +72 -0
- package/dist/modules/skills/matcher.js +27 -0
- package/dist/modules/skills/module.js +129 -0
- package/dist/modules/types.js +1 -0
- package/dist/modules/updater/checker.js +96 -0
- package/dist/modules/updater/index.js +2 -0
- package/dist/modules/updater/module.js +116 -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/skills/builtin/git.md +36 -36
- package/dist/skills/builtin/typescript.md +35 -35
- package/dist/tools/approve.js +33 -0
- package/dist/tools/attach-image.js +101 -0
- package/dist/tools/bash.js +519 -0
- package/dist/tools/browser.js +115 -0
- package/dist/tools/chunk-query.js +100 -0
- package/dist/tools/create-dir.js +56 -0
- package/dist/tools/delete-file.js +63 -0
- package/dist/tools/download-file.js +117 -0
- package/dist/tools/edit-file.js +80 -0
- package/dist/tools/enable-tools.js +59 -0
- package/dist/tools/executor.js +154 -0
- package/dist/tools/file-info.js +47 -0
- package/dist/tools/filter-tools.js +17 -0
- package/dist/tools/glob-tool.js +27 -0
- package/dist/tools/grep-tool.js +125 -0
- package/dist/tools/hidden-tools-block.js +37 -0
- package/dist/tools/index.js +78 -0
- package/dist/tools/list-dir.js +49 -0
- package/dist/tools/load-skill.js +43 -0
- package/dist/tools/mcp-call.js +69 -0
- package/dist/tools/move-file.js +86 -0
- package/dist/tools/path-utils.js +101 -0
- package/dist/tools/pipeline-run.js +145 -0
- package/dist/tools/preview.js +2 -0
- package/dist/tools/process-kill.js +40 -0
- package/dist/tools/process-list.js +37 -0
- package/dist/tools/process-log.js +54 -0
- package/dist/tools/question.js +141 -0
- package/dist/tools/read-file.js +179 -0
- package/dist/tools/recall.js +118 -0
- package/dist/tools/registry.js +47 -0
- package/dist/tools/remember.js +68 -0
- package/dist/tools/scope-check.js +32 -0
- package/dist/tools/search-history.js +85 -0
- package/dist/tools/subagent.js +196 -0
- package/dist/tools/types.js +1 -0
- package/dist/tools/user-input.js +123 -0
- package/dist/tools/web-browse.js +87 -0
- package/dist/tools/web-fetch.js +119 -0
- package/dist/tools/web-search.js +105 -0
- package/dist/tools/write-file.js +82 -0
- package/dist/ui/box.js +77 -0
- package/dist/ui/colors.js +4 -0
- package/dist/ui/diff.js +178 -0
- package/dist/ui/index.js +6 -0
- package/dist/ui/line-editor.js +822 -0
- package/dist/ui/line-math.js +73 -0
- package/dist/ui/md-formatter.js +212 -0
- package/dist/ui/output.js +13 -0
- package/dist/ui/plan-view.js +103 -0
- package/dist/ui/renderer.js +259 -0
- package/dist/ui/spinner.js +70 -0
- package/dist/ui/table.js +144 -0
- package/package.json +51 -51
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
import { TokenCounter } from "./token-counter";
|
|
2
|
+
import { t } from "../i18n/index";
|
|
3
|
+
import { createRateLimiter } from "../modules/security/rate-limiter";
|
|
4
|
+
const REQUEST_TIMEOUT_MS = 120000;
|
|
5
|
+
function buildRequestBody(opts) {
|
|
6
|
+
const body = {
|
|
7
|
+
model: opts.model,
|
|
8
|
+
messages: opts.messages,
|
|
9
|
+
stream: opts.stream,
|
|
10
|
+
};
|
|
11
|
+
if (opts.maxTokens !== undefined)
|
|
12
|
+
body.max_tokens = opts.maxTokens;
|
|
13
|
+
if (opts.reasoningEffort) {
|
|
14
|
+
body.reasoning_effort = opts.reasoningEffort;
|
|
15
|
+
}
|
|
16
|
+
if (opts.tools && opts.tools.length > 0) {
|
|
17
|
+
body.tools = opts.tools.map((t) => ({
|
|
18
|
+
type: "function",
|
|
19
|
+
function: {
|
|
20
|
+
name: t.name,
|
|
21
|
+
description: t.description,
|
|
22
|
+
parameters: t.parameters,
|
|
23
|
+
},
|
|
24
|
+
}));
|
|
25
|
+
body.tool_choice = "auto";
|
|
26
|
+
}
|
|
27
|
+
return body;
|
|
28
|
+
}
|
|
29
|
+
export class OpenAICompatProvider {
|
|
30
|
+
model;
|
|
31
|
+
contextWindow;
|
|
32
|
+
config;
|
|
33
|
+
tokenCounter;
|
|
34
|
+
retryConfig;
|
|
35
|
+
rateLimiter;
|
|
36
|
+
constructor(config) {
|
|
37
|
+
this.config = config;
|
|
38
|
+
this.model = config.model;
|
|
39
|
+
this.contextWindow = config.contextWindow ?? 32768;
|
|
40
|
+
this.tokenCounter = new TokenCounter();
|
|
41
|
+
this.retryConfig = config.retry ?? {
|
|
42
|
+
maxRetries: 3,
|
|
43
|
+
baseDelay: 1000,
|
|
44
|
+
maxDelay: 30000,
|
|
45
|
+
maxStreamRetries: 2,
|
|
46
|
+
noDataTimeoutMs: 180000,
|
|
47
|
+
};
|
|
48
|
+
this.rateLimiter = createRateLimiter(config.rateLimits);
|
|
49
|
+
}
|
|
50
|
+
async *chat(messages, tools, signal, options) {
|
|
51
|
+
// Check rate limit before making request
|
|
52
|
+
if (!this.rateLimiter.canMakeRequest()) {
|
|
53
|
+
throw new Error(`Rate limit exceeded: ${this.rateLimiter.getConfig().maxRequestsPerMinute} requests per minute`);
|
|
54
|
+
}
|
|
55
|
+
// Record this request
|
|
56
|
+
this.rateLimiter.recordRequest();
|
|
57
|
+
const streamResult = this.doStream(messages, tools, signal, options);
|
|
58
|
+
let hasToolCall = false;
|
|
59
|
+
let hasText = false;
|
|
60
|
+
for await (const chunk of streamResult) {
|
|
61
|
+
if (chunk.type === "tool_call")
|
|
62
|
+
hasToolCall = true;
|
|
63
|
+
if (chunk.type === "text")
|
|
64
|
+
hasText = true;
|
|
65
|
+
yield chunk;
|
|
66
|
+
}
|
|
67
|
+
if (!hasToolCall && !hasText) {
|
|
68
|
+
const fallback = await this.doNonStreaming(messages, tools, signal, options);
|
|
69
|
+
for (const chunk of fallback) {
|
|
70
|
+
yield chunk;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
async *doStream(messages, tools, signal, options) {
|
|
75
|
+
const { baseDelay, maxDelay, maxStreamRetries, noDataTimeoutMs } = this.retryConfig;
|
|
76
|
+
const streamRetries = maxStreamRetries ?? 2;
|
|
77
|
+
const idleTimeoutMs = noDataTimeoutMs ?? 180000;
|
|
78
|
+
for (let attempt = 0;; attempt++) {
|
|
79
|
+
let emitted = false;
|
|
80
|
+
const onEmit = () => {
|
|
81
|
+
emitted = true;
|
|
82
|
+
};
|
|
83
|
+
try {
|
|
84
|
+
const sawDone = yield* this.streamOnce(messages, tools, signal, options, onEmit, idleTimeoutMs);
|
|
85
|
+
// Clean [DONE] or any partial content → deliver what we have.
|
|
86
|
+
if (sawDone || emitted)
|
|
87
|
+
return;
|
|
88
|
+
// Stream closed before [DONE] with zero content → retryable truncation.
|
|
89
|
+
if (attempt >= streamRetries)
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
catch (err) {
|
|
93
|
+
if (err?.name === "AbortError" || err?.llmTerminal || signal?.aborted)
|
|
94
|
+
throw err;
|
|
95
|
+
// Content was already delivered — a re-stream would duplicate chunks.
|
|
96
|
+
if (emitted || attempt >= streamRetries)
|
|
97
|
+
throw err;
|
|
98
|
+
// Connection dropped before any content → retry the whole request.
|
|
99
|
+
}
|
|
100
|
+
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
|
|
101
|
+
const jitter = Math.random() * baseDelay * 0.1;
|
|
102
|
+
await this.sleep(delay + jitter, signal);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async *streamOnce(messages, tools, signal, options, onEmit, idleTimeoutMs) {
|
|
106
|
+
const maxTokens = options?.maxTokens ?? this.config.maxCompletionTokens ?? 4096;
|
|
107
|
+
const body = buildRequestBody({
|
|
108
|
+
model: this.model,
|
|
109
|
+
messages,
|
|
110
|
+
tools,
|
|
111
|
+
stream: true,
|
|
112
|
+
maxTokens,
|
|
113
|
+
reasoningEffort: options?.reasoningEffort,
|
|
114
|
+
});
|
|
115
|
+
const { headers, abortSignal, cleanup, isTimeout, flagTimeout, controller } = this.buildRequestSetup(signal);
|
|
116
|
+
let response;
|
|
117
|
+
try {
|
|
118
|
+
response = await this.fetchWithRetry(`${this.config.baseUrl}/chat/completions`, {
|
|
119
|
+
method: "POST",
|
|
120
|
+
headers,
|
|
121
|
+
body: JSON.stringify(body),
|
|
122
|
+
signal: abortSignal,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
// Fetch-level failures are already HTTP-retried inside fetchWithRetry —
|
|
127
|
+
// don't double-retry them at the stream level.
|
|
128
|
+
if (err?.name === "AbortError")
|
|
129
|
+
throw err;
|
|
130
|
+
const wrapped = err instanceof Error ? err : new Error(String(err));
|
|
131
|
+
wrapped.llmTerminal = true;
|
|
132
|
+
throw wrapped;
|
|
133
|
+
}
|
|
134
|
+
if (!response.ok) {
|
|
135
|
+
cleanup();
|
|
136
|
+
const errorText = await response.text();
|
|
137
|
+
const err = new Error(t("error.llm_api", {
|
|
138
|
+
status: response.status,
|
|
139
|
+
statusText: response.statusText,
|
|
140
|
+
errorText,
|
|
141
|
+
}));
|
|
142
|
+
err.llmTerminal = true;
|
|
143
|
+
throw err;
|
|
144
|
+
}
|
|
145
|
+
const reader = response.body?.getReader();
|
|
146
|
+
if (!reader) {
|
|
147
|
+
cleanup();
|
|
148
|
+
throw new Error(t("error.no_response_body"));
|
|
149
|
+
}
|
|
150
|
+
const decoder = new TextDecoder();
|
|
151
|
+
let buffer = "";
|
|
152
|
+
const toolCallAccs = new Map();
|
|
153
|
+
// A tool_call started accumulating — the server committed to a response.
|
|
154
|
+
// If the stream stalls after this, the provider most likely buffers SSE
|
|
155
|
+
// instead of streaming argument deltas (seen with LM Studio).
|
|
156
|
+
let sawToolCallStart = false;
|
|
157
|
+
let usage;
|
|
158
|
+
let sawDone = false;
|
|
159
|
+
let lastFinishReason;
|
|
160
|
+
let sawText = false;
|
|
161
|
+
const readIdle = () => new Promise((resolve, reject) => {
|
|
162
|
+
const idleTimer = setTimeout(() => {
|
|
163
|
+
flagTimeout();
|
|
164
|
+
controller.abort();
|
|
165
|
+
}, idleTimeoutMs);
|
|
166
|
+
reader.read().then((result) => {
|
|
167
|
+
clearTimeout(idleTimer);
|
|
168
|
+
if (isTimeout())
|
|
169
|
+
reject(new Error(t(sawToolCallStart ? "error.llm_stream_idle_toolcall" : "error.llm_stream_idle", { timeout: idleTimeoutMs })));
|
|
170
|
+
else
|
|
171
|
+
resolve(result);
|
|
172
|
+
}, (err) => {
|
|
173
|
+
clearTimeout(idleTimer);
|
|
174
|
+
if (isTimeout())
|
|
175
|
+
reject(new Error(t(sawToolCallStart ? "error.llm_stream_idle_toolcall" : "error.llm_stream_idle", { timeout: idleTimeoutMs })));
|
|
176
|
+
else
|
|
177
|
+
reject(err);
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
try {
|
|
181
|
+
while (true) {
|
|
182
|
+
const { done, value } = await readIdle();
|
|
183
|
+
if (done)
|
|
184
|
+
break;
|
|
185
|
+
buffer += decoder.decode(value, { stream: true });
|
|
186
|
+
const lines = buffer.split("\n");
|
|
187
|
+
buffer = lines.pop() || "";
|
|
188
|
+
for (const line of lines) {
|
|
189
|
+
const trimmed = line.trim();
|
|
190
|
+
if (!trimmed || !trimmed.startsWith("data: "))
|
|
191
|
+
continue;
|
|
192
|
+
const data = trimmed.slice(6);
|
|
193
|
+
if (data === "[DONE]") {
|
|
194
|
+
sawDone = true;
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
try {
|
|
198
|
+
const parsed = JSON.parse(data);
|
|
199
|
+
const choice = parsed.choices?.[0];
|
|
200
|
+
if (!choice) {
|
|
201
|
+
// Usage comes in the last chunk with empty choices
|
|
202
|
+
if (parsed.usage) {
|
|
203
|
+
usage = {
|
|
204
|
+
promptTokens: parsed.usage.prompt_tokens ?? 0,
|
|
205
|
+
completionTokens: parsed.usage.completion_tokens ?? 0,
|
|
206
|
+
totalTokens: parsed.usage.total_tokens ?? 0,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
const delta = choice.delta || {};
|
|
212
|
+
const finishReason = choice.finish_reason;
|
|
213
|
+
if (finishReason)
|
|
214
|
+
lastFinishReason = finishReason;
|
|
215
|
+
if (delta.reasoning_content) {
|
|
216
|
+
onEmit();
|
|
217
|
+
yield { type: "reasoning", content: delta.reasoning_content };
|
|
218
|
+
}
|
|
219
|
+
if (delta.tool_calls) {
|
|
220
|
+
sawToolCallStart = true;
|
|
221
|
+
for (const tc of delta.tool_calls) {
|
|
222
|
+
const idx = tc.index ?? 0;
|
|
223
|
+
if (!toolCallAccs.has(idx)) {
|
|
224
|
+
toolCallAccs.set(idx, { id: "", name: "", arguments: "" });
|
|
225
|
+
}
|
|
226
|
+
const acc = toolCallAccs.get(idx);
|
|
227
|
+
if (tc.id)
|
|
228
|
+
acc.id = tc.id;
|
|
229
|
+
if (tc.function?.name)
|
|
230
|
+
acc.name = tc.function.name;
|
|
231
|
+
if (tc.function?.arguments) {
|
|
232
|
+
acc.arguments += tc.function.arguments;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (delta.content) {
|
|
237
|
+
onEmit();
|
|
238
|
+
sawText = true;
|
|
239
|
+
yield { type: "text", content: delta.content };
|
|
240
|
+
}
|
|
241
|
+
if (finishReason === "tool_calls" && toolCallAccs.size > 0) {
|
|
242
|
+
for (const [, acc] of toolCallAccs) {
|
|
243
|
+
if (acc.name) {
|
|
244
|
+
onEmit();
|
|
245
|
+
yield {
|
|
246
|
+
type: "tool_call",
|
|
247
|
+
toolCall: {
|
|
248
|
+
id: acc.id,
|
|
249
|
+
name: acc.name,
|
|
250
|
+
arguments: acc.arguments || "{}",
|
|
251
|
+
},
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
toolCallAccs.clear();
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
// Skip malformed JSON lines
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (usage) {
|
|
264
|
+
onEmit();
|
|
265
|
+
yield { type: "done", usage };
|
|
266
|
+
}
|
|
267
|
+
// finish_reason "length": the completion hit the token limit. An
|
|
268
|
+
// unfinished tool_call would otherwise be silently swallowed (tool_calls
|
|
269
|
+
// are only yielded on finish_reason "tool_calls") and surface as an
|
|
270
|
+
// empty response → blind hallucination retries. Surface the real cause.
|
|
271
|
+
if (lastFinishReason === "length") {
|
|
272
|
+
const truncatedToolCall = sawToolCallStart && toolCallAccs.size > 0;
|
|
273
|
+
if (truncatedToolCall || !sawText) {
|
|
274
|
+
const err = new Error(t(truncatedToolCall ? "error.llm_truncated_toolcall" : "error.llm_truncated", {
|
|
275
|
+
tokens: maxTokens,
|
|
276
|
+
}));
|
|
277
|
+
err.llmTerminal = true;
|
|
278
|
+
// The provider is fine — the model just overran the completion
|
|
279
|
+
// limit. The agent loop feeds this back so the model can adapt
|
|
280
|
+
// (split the output) instead of the session dying.
|
|
281
|
+
err.recoverableLlm = true;
|
|
282
|
+
throw err;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
finally {
|
|
287
|
+
cleanup();
|
|
288
|
+
reader.releaseLock();
|
|
289
|
+
}
|
|
290
|
+
return sawDone;
|
|
291
|
+
}
|
|
292
|
+
/** Shared request setup: auth headers + timeout/abort controller wiring. */
|
|
293
|
+
buildRequestSetup(signal) {
|
|
294
|
+
const headers = {
|
|
295
|
+
"Content-Type": "application/json",
|
|
296
|
+
};
|
|
297
|
+
if (this.config.apiKey && this.config.apiKey !== "not-needed") {
|
|
298
|
+
headers["Authorization"] = `Bearer ${this.config.apiKey}`;
|
|
299
|
+
}
|
|
300
|
+
const controller = new AbortController();
|
|
301
|
+
let timedOut = false;
|
|
302
|
+
const timeoutId = setTimeout(() => {
|
|
303
|
+
timedOut = true;
|
|
304
|
+
controller.abort();
|
|
305
|
+
}, REQUEST_TIMEOUT_MS);
|
|
306
|
+
const abortSignal = (() => {
|
|
307
|
+
if (!signal)
|
|
308
|
+
return controller.signal;
|
|
309
|
+
try {
|
|
310
|
+
return AbortSignal.any([controller.signal, signal]);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
signal.addEventListener("abort", () => controller.abort(), {
|
|
314
|
+
once: true,
|
|
315
|
+
});
|
|
316
|
+
return controller.signal;
|
|
317
|
+
}
|
|
318
|
+
})();
|
|
319
|
+
return {
|
|
320
|
+
headers,
|
|
321
|
+
abortSignal,
|
|
322
|
+
cleanup: () => clearTimeout(timeoutId),
|
|
323
|
+
isTimeout: () => timedOut,
|
|
324
|
+
flagTimeout: () => {
|
|
325
|
+
timedOut = true;
|
|
326
|
+
},
|
|
327
|
+
controller,
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
async doNonStreaming(messages, tools, signal, options) {
|
|
331
|
+
const body = buildRequestBody({
|
|
332
|
+
model: this.model,
|
|
333
|
+
messages,
|
|
334
|
+
tools,
|
|
335
|
+
stream: false,
|
|
336
|
+
maxTokens: options?.maxTokens ?? this.config.maxCompletionTokens ?? 4096,
|
|
337
|
+
reasoningEffort: options?.reasoningEffort,
|
|
338
|
+
});
|
|
339
|
+
const { headers, abortSignal, cleanup, isTimeout } = this.buildRequestSetup(signal);
|
|
340
|
+
try {
|
|
341
|
+
const response = await this.fetchWithRetry(`${this.config.baseUrl}/chat/completions`, {
|
|
342
|
+
method: "POST",
|
|
343
|
+
headers,
|
|
344
|
+
body: JSON.stringify(body),
|
|
345
|
+
signal: abortSignal,
|
|
346
|
+
});
|
|
347
|
+
if (!response.ok) {
|
|
348
|
+
const errorText = await response.text();
|
|
349
|
+
throw new Error(t("error.llm_api", {
|
|
350
|
+
status: response.status,
|
|
351
|
+
statusText: response.statusText,
|
|
352
|
+
errorText: errorText.slice(0, 500),
|
|
353
|
+
}));
|
|
354
|
+
}
|
|
355
|
+
const data = await response.json();
|
|
356
|
+
const choice = data.choices?.[0];
|
|
357
|
+
if (!choice) {
|
|
358
|
+
return [];
|
|
359
|
+
}
|
|
360
|
+
const msg = choice.message || {};
|
|
361
|
+
const chunks = [];
|
|
362
|
+
if (msg.reasoning_content) {
|
|
363
|
+
chunks.push({ type: "reasoning", content: msg.reasoning_content });
|
|
364
|
+
}
|
|
365
|
+
if (msg.content) {
|
|
366
|
+
chunks.push({ type: "text", content: msg.content });
|
|
367
|
+
}
|
|
368
|
+
if (msg.tool_calls) {
|
|
369
|
+
for (const tc of msg.tool_calls) {
|
|
370
|
+
chunks.push({
|
|
371
|
+
type: "tool_call",
|
|
372
|
+
toolCall: {
|
|
373
|
+
id: tc.id || "",
|
|
374
|
+
name: tc.function?.name || "",
|
|
375
|
+
arguments: tc.function?.arguments || "{}",
|
|
376
|
+
},
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
// Append usage from API response
|
|
381
|
+
if (data.usage) {
|
|
382
|
+
chunks.push({
|
|
383
|
+
type: "done",
|
|
384
|
+
usage: {
|
|
385
|
+
promptTokens: data.usage.prompt_tokens ?? 0,
|
|
386
|
+
completionTokens: data.usage.completion_tokens ?? 0,
|
|
387
|
+
totalTokens: data.usage.total_tokens ?? 0,
|
|
388
|
+
},
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
return chunks;
|
|
392
|
+
}
|
|
393
|
+
catch (err) {
|
|
394
|
+
if (isTimeout() && err?.name === "AbortError") {
|
|
395
|
+
throw new Error(t("error.llm_timeout", { timeout: REQUEST_TIMEOUT_MS }));
|
|
396
|
+
}
|
|
397
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
398
|
+
}
|
|
399
|
+
finally {
|
|
400
|
+
cleanup();
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
countTokens(text) {
|
|
404
|
+
return this.tokenCounter.count(text);
|
|
405
|
+
}
|
|
406
|
+
async listModels() {
|
|
407
|
+
try {
|
|
408
|
+
const url = `${this.config.baseUrl.replace(/\/+$/, "")}/models`;
|
|
409
|
+
const headers = {
|
|
410
|
+
"Content-Type": "application/json",
|
|
411
|
+
};
|
|
412
|
+
if (this.config.apiKey && this.config.apiKey !== "not-needed") {
|
|
413
|
+
headers["Authorization"] = `Bearer ${this.config.apiKey}`;
|
|
414
|
+
}
|
|
415
|
+
const response = await fetch(url, {
|
|
416
|
+
method: "GET",
|
|
417
|
+
headers,
|
|
418
|
+
});
|
|
419
|
+
if (!response.ok) {
|
|
420
|
+
// Surface the failure: health probes must distinguish a dead
|
|
421
|
+
// provider from one that serves an empty model list.
|
|
422
|
+
throw new Error(`HTTP ${response.status} from ${url}`);
|
|
423
|
+
}
|
|
424
|
+
const data = (await response.json());
|
|
425
|
+
const models = (data.data || data || [])
|
|
426
|
+
.map((m) => m.id || m.name || m.model || "")
|
|
427
|
+
.filter(Boolean);
|
|
428
|
+
return models;
|
|
429
|
+
}
|
|
430
|
+
catch (err) {
|
|
431
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
async fetchWithRetry(url, init) {
|
|
435
|
+
const { maxRetries, baseDelay, maxDelay } = this.retryConfig;
|
|
436
|
+
let lastStatus = 0;
|
|
437
|
+
let lastRetryAfter = 0;
|
|
438
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
439
|
+
try {
|
|
440
|
+
const response = await fetch(url, init);
|
|
441
|
+
if (!this.isRetryable(response.status))
|
|
442
|
+
return response;
|
|
443
|
+
lastStatus = response.status;
|
|
444
|
+
const retryAfter = Number(response.headers.get("retry-after") ?? 0);
|
|
445
|
+
lastRetryAfter = retryAfter > 0 ? retryAfter * 1000 : 0;
|
|
446
|
+
}
|
|
447
|
+
catch (err) {
|
|
448
|
+
if (err.name === "AbortError") {
|
|
449
|
+
throw err;
|
|
450
|
+
}
|
|
451
|
+
if (attempt === maxRetries)
|
|
452
|
+
throw err;
|
|
453
|
+
}
|
|
454
|
+
if (attempt < maxRetries) {
|
|
455
|
+
// Prefer the provider's Retry-After window (saturating at maxDelay);
|
|
456
|
+
// otherwise exponential backoff. 429s from free tiers need a real wait.
|
|
457
|
+
const delay = lastRetryAfter > 0
|
|
458
|
+
? Math.min(lastRetryAfter, maxDelay)
|
|
459
|
+
: Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
|
|
460
|
+
const jitter = Math.random() * baseDelay * 0.1;
|
|
461
|
+
await this.sleep(delay + jitter, init.signal ?? undefined);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
if (lastStatus === 429) {
|
|
465
|
+
const e429 = new Error(t("error.llm_429", {
|
|
466
|
+
model: this.model,
|
|
467
|
+
baseUrl: this.config.baseUrl,
|
|
468
|
+
}));
|
|
469
|
+
e429.llmStatus = lastStatus;
|
|
470
|
+
throw e429;
|
|
471
|
+
}
|
|
472
|
+
const eRetry = new Error(t("error.llm_retries"));
|
|
473
|
+
eRetry.llmStatus = lastStatus;
|
|
474
|
+
throw eRetry;
|
|
475
|
+
}
|
|
476
|
+
isRetryable(status) {
|
|
477
|
+
return status === 429 || status >= 500;
|
|
478
|
+
}
|
|
479
|
+
sleep(ms, signal) {
|
|
480
|
+
return new Promise((resolve, reject) => {
|
|
481
|
+
if (signal?.aborted) {
|
|
482
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
let timer;
|
|
486
|
+
const onAbort = () => {
|
|
487
|
+
clearTimeout(timer);
|
|
488
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
489
|
+
};
|
|
490
|
+
timer = setTimeout(() => {
|
|
491
|
+
signal?.removeEventListener("abort", onAbort);
|
|
492
|
+
resolve();
|
|
493
|
+
}, ms);
|
|
494
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { createProvider } from "../modules/providers/create";
|
|
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 = createProvider(config.provider.type ?? "openai-compat", {
|
|
60
|
+
model: config.model,
|
|
61
|
+
baseUrl: config.provider.baseUrl || "http://localhost:1234/v1",
|
|
62
|
+
apiKey: config.provider.apiKey,
|
|
63
|
+
contextWindow: 32768,
|
|
64
|
+
retry: config.retry,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
else if (defaultProvider) {
|
|
68
|
+
this.provider = defaultProvider;
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
this.provider = createProvider("openai-compat", {
|
|
72
|
+
model: config.model,
|
|
73
|
+
baseUrl: "http://localhost:1234/v1",
|
|
74
|
+
contextWindow: 32768,
|
|
75
|
+
retry: config.retry,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
isEnabled() {
|
|
81
|
+
return this.provider !== null;
|
|
82
|
+
}
|
|
83
|
+
getReplanCycle() {
|
|
84
|
+
return this.replanCycle;
|
|
85
|
+
}
|
|
86
|
+
async chat(messages) {
|
|
87
|
+
if (!this.provider)
|
|
88
|
+
throw new Error("Orchestrator not enabled");
|
|
89
|
+
const chunks = [];
|
|
90
|
+
for await (const chunk of this.provider.chat(messages)) {
|
|
91
|
+
chunks.push(chunk);
|
|
92
|
+
}
|
|
93
|
+
return chunks
|
|
94
|
+
.filter((c) => c.type === "text")
|
|
95
|
+
.map((c) => c.content)
|
|
96
|
+
.join("");
|
|
97
|
+
}
|
|
98
|
+
parseJSON(text) {
|
|
99
|
+
try {
|
|
100
|
+
return JSON.parse(text);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
try {
|
|
104
|
+
const repaired = jsonrepair(text);
|
|
105
|
+
return JSON.parse(repaired);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
const jsonMatch = text.match(/\{[\s\S]*\}/);
|
|
109
|
+
if (jsonMatch) {
|
|
110
|
+
try {
|
|
111
|
+
const repaired = jsonrepair(jsonMatch[0]);
|
|
112
|
+
return JSON.parse(repaired);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
/* fall through */
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
async plan(userPrompt, _context) {
|
|
123
|
+
if (!this.provider)
|
|
124
|
+
return { error: "Orchestrator not enabled — no orchestrator model configured" };
|
|
125
|
+
const messages = [
|
|
126
|
+
{ role: "system", content: PLAN_SYSTEM_PROMPT },
|
|
127
|
+
{ role: "user", content: userPrompt },
|
|
128
|
+
];
|
|
129
|
+
const text = await this.chat(messages);
|
|
130
|
+
const parsed = this.parseJSON(text);
|
|
131
|
+
if (parsed && parsed.subtasks && parsed.subtasks.length > 0) {
|
|
132
|
+
return { plan: parsed, raw: text };
|
|
133
|
+
}
|
|
134
|
+
return { error: `Failed to parse plan from LLM output. Raw: ${text.slice(0, 500)}` };
|
|
135
|
+
}
|
|
136
|
+
async verifyAndMerge(input) {
|
|
137
|
+
if (!this.provider)
|
|
138
|
+
return { type: "final", finalAnswer: input.results.map((r) => r.summary).join("\n") };
|
|
139
|
+
this.replanCycle++;
|
|
140
|
+
if (this.replanCycle > 3) {
|
|
141
|
+
return {
|
|
142
|
+
type: "final",
|
|
143
|
+
finalAnswer: input.results
|
|
144
|
+
.map((r) => `${r.subtaskId}: ${r.success ? "OK" : "FAIL"} — ${r.summary}`)
|
|
145
|
+
.join("\n"),
|
|
146
|
+
explanation: "Max re-plan cycles (3) reached. Returning partial results.",
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
const context = JSON.stringify(input, null, 2);
|
|
150
|
+
const messages = [
|
|
151
|
+
{ role: "system", content: VERIFY_SYSTEM_PROMPT },
|
|
152
|
+
{ role: "user", content: context },
|
|
153
|
+
];
|
|
154
|
+
const text = await this.chat(messages);
|
|
155
|
+
const parsed = this.parseJSON(text);
|
|
156
|
+
if (parsed && parsed.type) {
|
|
157
|
+
return parsed;
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
type: "final",
|
|
161
|
+
finalAnswer: input.results.map((r) => r.summary).join("\n"),
|
|
162
|
+
explanation: "Failed to parse verifier output, returning collected results.",
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
async createPlan(task) {
|
|
166
|
+
if (!this.provider)
|
|
167
|
+
throw new Error("Orchestrator not enabled");
|
|
168
|
+
const messages = [
|
|
169
|
+
{
|
|
170
|
+
role: "system",
|
|
171
|
+
content: 'You are a planning assistant. Break down tasks into steps. Respond with JSON only: {"steps": ["step 1", "step 2", ...]}',
|
|
172
|
+
},
|
|
173
|
+
{ role: "user", content: task },
|
|
174
|
+
];
|
|
175
|
+
const text = await this.chat(messages);
|
|
176
|
+
try {
|
|
177
|
+
return JSON.parse(text);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return { steps: [task] };
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
async resolveConflict(context) {
|
|
184
|
+
if (!this.provider)
|
|
185
|
+
throw new Error("Orchestrator not enabled");
|
|
186
|
+
const messages = [
|
|
187
|
+
{
|
|
188
|
+
role: "system",
|
|
189
|
+
content: "You are a conflict resolution assistant. Analyze the situation and recommend the best path forward.",
|
|
190
|
+
},
|
|
191
|
+
{ role: "user", content: context },
|
|
192
|
+
];
|
|
193
|
+
let result = "";
|
|
194
|
+
for await (const chunk of this.provider.chat(messages)) {
|
|
195
|
+
if (chunk.type === "text" && chunk.content)
|
|
196
|
+
result += chunk.content;
|
|
197
|
+
}
|
|
198
|
+
return result;
|
|
199
|
+
}
|
|
200
|
+
}
|