micro-models-agent 0.52.0 → 0.52.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/README.md +358 -358
  2. package/dist/main.js +244 -122
  3. package/dist/modules/browser/bridge-server.mjs +202 -202
  4. package/dist/skills/builtin/git.md +36 -36
  5. package/dist/skills/builtin/typescript.md +35 -35
  6. package/package.json +1 -1
  7. package/dist/cli/commands.js +0 -447
  8. package/dist/cli/completer.js +0 -167
  9. package/dist/cli/index.js +0 -2
  10. package/dist/cli/main.js +0 -153
  11. package/dist/cli/plugin-commands.js +0 -36
  12. package/dist/cli/repl-commands.js +0 -761
  13. package/dist/cli/repl.js +0 -702
  14. package/dist/cli/run-result.js +0 -33
  15. package/dist/cli/security-commands.js +0 -164
  16. package/dist/cli/setup.js +0 -237
  17. package/dist/config/config.js +0 -276
  18. package/dist/config/defaults.js +0 -141
  19. package/dist/config/domains.js +0 -179
  20. package/dist/config/experts.js +0 -15
  21. package/dist/config/index.js +0 -4
  22. package/dist/config/security.js +0 -213
  23. package/dist/config/types.js +0 -1
  24. package/dist/core/agent-moe.js +0 -102
  25. package/dist/core/agent.js +0 -1018
  26. package/dist/core/bootstrap.js +0 -481
  27. package/dist/core/crash-handler.js +0 -51
  28. package/dist/core/environment.js +0 -199
  29. package/dist/core/index.js +0 -2
  30. package/dist/core/prompt-builder.js +0 -76
  31. package/dist/core/session-logger.js +0 -251
  32. package/dist/core/types.js +0 -1
  33. package/dist/core/version.js +0 -26
  34. package/dist/core/workspace.js +0 -76
  35. package/dist/i18n/en.json +0 -679
  36. package/dist/i18n/index.js +0 -46
  37. package/dist/i18n/ru.json +0 -679
  38. package/dist/index.js +0 -22
  39. package/dist/llm/image-utils.js +0 -143
  40. package/dist/llm/index.js +0 -4
  41. package/dist/llm/model-loader.js +0 -78
  42. package/dist/llm/openai-compat.js +0 -497
  43. package/dist/llm/orchestrator.js +0 -200
  44. package/dist/llm/provider.js +0 -10
  45. package/dist/llm/response.js +0 -39
  46. package/dist/llm/token-counter.js +0 -39
  47. package/dist/llm/types.js +0 -1
  48. package/dist/logger/app-logger.js +0 -189
  49. package/dist/logger/file-log.js +0 -151
  50. package/dist/logger/index.js +0 -1
  51. package/dist/migration/backup.js +0 -45
  52. package/dist/migration/detect.js +0 -50
  53. package/dist/migration/index.js +0 -2
  54. package/dist/modules/artifacts/store.js +0 -61
  55. package/dist/modules/browser/actions.js +0 -76
  56. package/dist/modules/browser/bridge-client.js +0 -199
  57. package/dist/modules/browser/bridge-path.js +0 -10
  58. package/dist/modules/browser/cookie-store.js +0 -24
  59. package/dist/modules/browser/driver.js +0 -136
  60. package/dist/modules/browser/index.js +0 -7
  61. package/dist/modules/browser/module.js +0 -29
  62. package/dist/modules/browser/session.js +0 -342
  63. package/dist/modules/browser/snapshot.js +0 -148
  64. package/dist/modules/browser/types.js +0 -12
  65. package/dist/modules/certification/cli.js +0 -213
  66. package/dist/modules/certification/fact-checker.js +0 -82
  67. package/dist/modules/certification/loader.js +0 -106
  68. package/dist/modules/certification/manifest.js +0 -58
  69. package/dist/modules/certification/runner.js +0 -245
  70. package/dist/modules/certification/scenarios.js +0 -407
  71. package/dist/modules/certification/types.js +0 -1
  72. package/dist/modules/context/chunk-query.js +0 -100
  73. package/dist/modules/context/fact-extractor.js +0 -168
  74. package/dist/modules/context/history.js +0 -15
  75. package/dist/modules/context/index.js +0 -1
  76. package/dist/modules/context/manager.js +0 -440
  77. package/dist/modules/execution/audit-runners.js +0 -206
  78. package/dist/modules/execution/auditor.js +0 -218
  79. package/dist/modules/execution/execution-plugin.js +0 -431
  80. package/dist/modules/execution/index.js +0 -8
  81. package/dist/modules/execution/module.js +0 -625
  82. package/dist/modules/execution/moe-executor.js +0 -304
  83. package/dist/modules/execution/plan-coverage.js +0 -68
  84. package/dist/modules/execution/plan-persister.js +0 -46
  85. package/dist/modules/execution/plan-store.js +0 -196
  86. package/dist/modules/execution/plan-tool.js +0 -677
  87. package/dist/modules/execution/plan-validator.js +0 -153
  88. package/dist/modules/execution/planner.js +0 -94
  89. package/dist/modules/execution/stuck-detector.js +0 -746
  90. package/dist/modules/execution/tracker.js +0 -69
  91. package/dist/modules/execution/types.js +0 -1
  92. package/dist/modules/execution/verifier.js +0 -235
  93. package/dist/modules/execution/windows-commands.js +0 -41
  94. package/dist/modules/hallucination/confidence.js +0 -66
  95. package/dist/modules/hallucination/consistency.js +0 -26
  96. package/dist/modules/hallucination/detector.js +0 -47
  97. package/dist/modules/hallucination/factual.js +0 -169
  98. package/dist/modules/hallucination/index.js +0 -5
  99. package/dist/modules/hallucination/js-identifiers.js +0 -262
  100. package/dist/modules/hallucination/llm-judge.js +0 -101
  101. package/dist/modules/index.js +0 -5
  102. package/dist/modules/indexer/cache.js +0 -40
  103. package/dist/modules/indexer/index.js +0 -3
  104. package/dist/modules/indexer/module.js +0 -246
  105. package/dist/modules/indexer/project-profile.js +0 -183
  106. package/dist/modules/indexer/walker.js +0 -101
  107. package/dist/modules/lsp/check-tool.js +0 -58
  108. package/dist/modules/lsp/client.js +0 -389
  109. package/dist/modules/lsp/command.js +0 -60
  110. package/dist/modules/lsp/config.js +0 -135
  111. package/dist/modules/lsp/index.js +0 -3
  112. package/dist/modules/lsp/module.js +0 -260
  113. package/dist/modules/lsp/probe.js +0 -86
  114. package/dist/modules/lsp/project-root.js +0 -32
  115. package/dist/modules/lsp/startup-check.js +0 -144
  116. package/dist/modules/lsp/types.js +0 -1
  117. package/dist/modules/mcp/client.js +0 -399
  118. package/dist/modules/mcp/index.js +0 -3
  119. package/dist/modules/mcp/module.js +0 -142
  120. package/dist/modules/mcp/registry.js +0 -15
  121. package/dist/modules/memory/index.js +0 -1
  122. package/dist/modules/memory/module.js +0 -96
  123. package/dist/modules/memory/search.js +0 -42
  124. package/dist/modules/memory/store.js +0 -69
  125. package/dist/modules/pipelines/engine.js +0 -60
  126. package/dist/modules/pipelines/index.js +0 -3
  127. package/dist/modules/pipelines/parser.js +0 -56
  128. package/dist/modules/pipelines/template.js +0 -14
  129. package/dist/modules/plugins/builtin/lint-on-write.js +0 -334
  130. package/dist/modules/plugins/builtin/notify.js +0 -9
  131. package/dist/modules/plugins/index.js +0 -1
  132. package/dist/modules/plugins/loader.js +0 -70
  133. package/dist/modules/plugins/manager.js +0 -261
  134. package/dist/modules/plugins/types.js +0 -1
  135. package/dist/modules/pricing/index.js +0 -61
  136. package/dist/modules/pricing/prices.js +0 -129
  137. package/dist/modules/processes/detect.js +0 -34
  138. package/dist/modules/processes/index.js +0 -2
  139. package/dist/modules/processes/registry.js +0 -327
  140. package/dist/modules/processes/runner.js +0 -23
  141. package/dist/modules/providers/create.js +0 -22
  142. package/dist/modules/providers/fallback.js +0 -79
  143. package/dist/modules/providers/health.js +0 -46
  144. package/dist/modules/providers/index.js +0 -5
  145. package/dist/modules/providers/manager.js +0 -161
  146. package/dist/modules/providers/presets.js +0 -128
  147. package/dist/modules/providers/registry.js +0 -22
  148. package/dist/modules/providers/types.js +0 -1
  149. package/dist/modules/registry.js +0 -48
  150. package/dist/modules/security/audit-log.js +0 -136
  151. package/dist/modules/security/audit-notifier.js +0 -292
  152. package/dist/modules/security/command-validator.js +0 -219
  153. package/dist/modules/security/content-scanner.js +0 -53
  154. package/dist/modules/security/data-sanitizer.js +0 -89
  155. package/dist/modules/security/encryption.js +0 -242
  156. package/dist/modules/security/index.js +0 -14
  157. package/dist/modules/security/network-validator.js +0 -88
  158. package/dist/modules/security/path-validator.js +0 -203
  159. package/dist/modules/security/rate-limiter.js +0 -119
  160. package/dist/modules/security/security-policies.js +0 -531
  161. package/dist/modules/security/session-encryption.js +0 -210
  162. package/dist/modules/security/session-isolation.js +0 -95
  163. package/dist/modules/session/index.js +0 -3
  164. package/dist/modules/session/manager.js +0 -172
  165. package/dist/modules/session/module.js +0 -24
  166. package/dist/modules/session/store.js +0 -222
  167. package/dist/modules/session/types.js +0 -1
  168. package/dist/modules/skills/index.js +0 -2
  169. package/dist/modules/skills/loader.js +0 -72
  170. package/dist/modules/skills/matcher.js +0 -27
  171. package/dist/modules/skills/module.js +0 -129
  172. package/dist/modules/types.js +0 -1
  173. package/dist/modules/updater/checker.js +0 -96
  174. package/dist/modules/updater/index.js +0 -2
  175. package/dist/modules/updater/module.js +0 -116
  176. package/dist/modules/user-profile/compressor.js +0 -16
  177. package/dist/modules/user-profile/index.js +0 -1
  178. package/dist/modules/user-profile/profile.js +0 -68
  179. package/dist/tools/approve.js +0 -33
  180. package/dist/tools/attach-image.js +0 -101
  181. package/dist/tools/bash.js +0 -519
  182. package/dist/tools/browser.js +0 -115
  183. package/dist/tools/chunk-query.js +0 -100
  184. package/dist/tools/create-dir.js +0 -56
  185. package/dist/tools/delete-file.js +0 -63
  186. package/dist/tools/download-file.js +0 -117
  187. package/dist/tools/edit-file.js +0 -80
  188. package/dist/tools/enable-tools.js +0 -59
  189. package/dist/tools/executor.js +0 -154
  190. package/dist/tools/file-info.js +0 -47
  191. package/dist/tools/filter-tools.js +0 -17
  192. package/dist/tools/glob-tool.js +0 -27
  193. package/dist/tools/grep-tool.js +0 -125
  194. package/dist/tools/hidden-tools-block.js +0 -37
  195. package/dist/tools/index.js +0 -78
  196. package/dist/tools/list-dir.js +0 -49
  197. package/dist/tools/load-skill.js +0 -43
  198. package/dist/tools/mcp-call.js +0 -69
  199. package/dist/tools/move-file.js +0 -86
  200. package/dist/tools/path-utils.js +0 -101
  201. package/dist/tools/pipeline-run.js +0 -145
  202. package/dist/tools/preview.js +0 -2
  203. package/dist/tools/process-kill.js +0 -40
  204. package/dist/tools/process-list.js +0 -37
  205. package/dist/tools/process-log.js +0 -54
  206. package/dist/tools/question.js +0 -141
  207. package/dist/tools/read-file.js +0 -179
  208. package/dist/tools/recall.js +0 -118
  209. package/dist/tools/registry.js +0 -47
  210. package/dist/tools/remember.js +0 -68
  211. package/dist/tools/scope-check.js +0 -32
  212. package/dist/tools/search-history.js +0 -85
  213. package/dist/tools/subagent.js +0 -196
  214. package/dist/tools/types.js +0 -1
  215. package/dist/tools/user-input.js +0 -123
  216. package/dist/tools/web-browse.js +0 -87
  217. package/dist/tools/web-fetch.js +0 -119
  218. package/dist/tools/web-search.js +0 -105
  219. package/dist/tools/write-file.js +0 -82
  220. package/dist/ui/box.js +0 -77
  221. package/dist/ui/colors.js +0 -4
  222. package/dist/ui/diff.js +0 -178
  223. package/dist/ui/index.js +0 -6
  224. package/dist/ui/line-editor.js +0 -822
  225. package/dist/ui/line-math.js +0 -73
  226. package/dist/ui/md-formatter.js +0 -212
  227. package/dist/ui/output.js +0 -13
  228. package/dist/ui/plan-view.js +0 -103
  229. package/dist/ui/renderer.js +0 -259
  230. package/dist/ui/spinner.js +0 -70
  231. package/dist/ui/table.js +0 -144
@@ -1,497 +0,0 @@
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
- }
@@ -1,200 +0,0 @@
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
- }