micro-models-agent 0.28.0 → 0.28.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 (167) hide show
  1. package/dist/main.js +314 -208
  2. package/package.json +1 -1
  3. package/dist/cli/commands.js +0 -220
  4. package/dist/cli/completer.js +0 -168
  5. package/dist/cli/index.js +0 -2
  6. package/dist/cli/main.js +0 -113
  7. package/dist/cli/repl.js +0 -987
  8. package/dist/cli/security-commands.js +0 -166
  9. package/dist/cli/setup.js +0 -229
  10. package/dist/config/config.js +0 -186
  11. package/dist/config/defaults.js +0 -91
  12. package/dist/config/experts.js +0 -15
  13. package/dist/config/index.js +0 -3
  14. package/dist/config/security.js +0 -193
  15. package/dist/config/types.js +0 -1
  16. package/dist/core/agent-moe.js +0 -98
  17. package/dist/core/agent.js +0 -461
  18. package/dist/core/bootstrap.js +0 -321
  19. package/dist/core/index.js +0 -2
  20. package/dist/core/prompt-builder.js +0 -55
  21. package/dist/core/session-logger.js +0 -122
  22. package/dist/core/types.js +0 -1
  23. package/dist/i18n/en.json +0 -461
  24. package/dist/i18n/index.js +0 -43
  25. package/dist/i18n/ru.json +0 -461
  26. package/dist/index.js +0 -22
  27. package/dist/llm/image-utils.js +0 -144
  28. package/dist/llm/index.js +0 -4
  29. package/dist/llm/model-loader.js +0 -78
  30. package/dist/llm/openai-compat.js +0 -324
  31. package/dist/llm/orchestrator.js +0 -194
  32. package/dist/llm/provider.js +0 -10
  33. package/dist/llm/response.js +0 -39
  34. package/dist/llm/token-counter.js +0 -39
  35. package/dist/llm/types.js +0 -1
  36. package/dist/logger/app-logger.js +0 -76
  37. package/dist/logger/index.js +0 -1
  38. package/dist/migration/backup.js +0 -45
  39. package/dist/migration/detect.js +0 -50
  40. package/dist/migration/index.js +0 -2
  41. package/dist/modules/browser/actions.js +0 -46
  42. package/dist/modules/browser/cookie-store.js +0 -24
  43. package/dist/modules/browser/index.js +0 -5
  44. package/dist/modules/browser/module.js +0 -28
  45. package/dist/modules/browser/session.js +0 -287
  46. package/dist/modules/browser/snapshot.js +0 -114
  47. package/dist/modules/browser/types.js +0 -9
  48. package/dist/modules/context/history.js +0 -15
  49. package/dist/modules/context/index.js +0 -1
  50. package/dist/modules/context/manager.js +0 -240
  51. package/dist/modules/execution/auditor.js +0 -72
  52. package/dist/modules/execution/index.js +0 -6
  53. package/dist/modules/execution/module.js +0 -337
  54. package/dist/modules/execution/moe-executor.js +0 -209
  55. package/dist/modules/execution/plan-validator.js +0 -153
  56. package/dist/modules/execution/planner.js +0 -35
  57. package/dist/modules/execution/stuck-detector.js +0 -134
  58. package/dist/modules/execution/tracker.js +0 -53
  59. package/dist/modules/execution/types.js +0 -1
  60. package/dist/modules/execution/verifier.js +0 -149
  61. package/dist/modules/hallucination/confidence.js +0 -54
  62. package/dist/modules/hallucination/consistency.js +0 -60
  63. package/dist/modules/hallucination/detector.js +0 -41
  64. package/dist/modules/hallucination/factual.js +0 -170
  65. package/dist/modules/hallucination/index.js +0 -4
  66. package/dist/modules/index.js +0 -5
  67. package/dist/modules/indexer/cache.js +0 -38
  68. package/dist/modules/indexer/index.js +0 -3
  69. package/dist/modules/indexer/module.js +0 -192
  70. package/dist/modules/indexer/walker.js +0 -101
  71. package/dist/modules/mcp/client.js +0 -393
  72. package/dist/modules/mcp/index.js +0 -3
  73. package/dist/modules/mcp/module.js +0 -146
  74. package/dist/modules/mcp/registry.js +0 -15
  75. package/dist/modules/memory/index.js +0 -1
  76. package/dist/modules/memory/module.js +0 -48
  77. package/dist/modules/memory/search.js +0 -40
  78. package/dist/modules/memory/store.js +0 -65
  79. package/dist/modules/pipelines/engine.js +0 -60
  80. package/dist/modules/pipelines/index.js +0 -3
  81. package/dist/modules/pipelines/parser.js +0 -53
  82. package/dist/modules/pipelines/template.js +0 -14
  83. package/dist/modules/plugins/builtin/lint-on-write.js +0 -121
  84. package/dist/modules/plugins/builtin/notify.js +0 -8
  85. package/dist/modules/plugins/index.js +0 -1
  86. package/dist/modules/plugins/loader.js +0 -28
  87. package/dist/modules/plugins/manager.js +0 -161
  88. package/dist/modules/plugins/types.js +0 -1
  89. package/dist/modules/processes/detect.js +0 -34
  90. package/dist/modules/processes/index.js +0 -3
  91. package/dist/modules/processes/registry.js +0 -148
  92. package/dist/modules/processes/runner.js +0 -124
  93. package/dist/modules/registry.js +0 -45
  94. package/dist/modules/security/audit-log.js +0 -116
  95. package/dist/modules/security/audit-notifier.js +0 -292
  96. package/dist/modules/security/command-validator.js +0 -185
  97. package/dist/modules/security/content-scanner.js +0 -52
  98. package/dist/modules/security/data-sanitizer.js +0 -97
  99. package/dist/modules/security/encryption.js +0 -240
  100. package/dist/modules/security/index.js +0 -14
  101. package/dist/modules/security/network-validator.js +0 -79
  102. package/dist/modules/security/path-validator.js +0 -155
  103. package/dist/modules/security/rate-limiter.js +0 -119
  104. package/dist/modules/security/security-policies.js +0 -393
  105. package/dist/modules/security/session-encryption.js +0 -193
  106. package/dist/modules/security/session-isolation.js +0 -95
  107. package/dist/modules/session/index.js +0 -3
  108. package/dist/modules/session/manager.js +0 -167
  109. package/dist/modules/session/module.js +0 -24
  110. package/dist/modules/session/store.js +0 -174
  111. package/dist/modules/session/types.js +0 -1
  112. package/dist/modules/skills/index.js +0 -3
  113. package/dist/modules/skills/loader.js +0 -72
  114. package/dist/modules/skills/matcher.js +0 -27
  115. package/dist/modules/skills/module.js +0 -143
  116. package/dist/modules/types.js +0 -1
  117. package/dist/modules/updater/checker.js +0 -32
  118. package/dist/modules/updater/index.js +0 -1
  119. package/dist/modules/user-profile/compressor.js +0 -16
  120. package/dist/modules/user-profile/index.js +0 -1
  121. package/dist/modules/user-profile/profile.js +0 -68
  122. package/dist/tools/approve.js +0 -32
  123. package/dist/tools/attach-image.js +0 -89
  124. package/dist/tools/bash.js +0 -140
  125. package/dist/tools/browser.js +0 -97
  126. package/dist/tools/create-dir.js +0 -56
  127. package/dist/tools/delete-file.js +0 -63
  128. package/dist/tools/edit-file.js +0 -77
  129. package/dist/tools/executor.js +0 -95
  130. package/dist/tools/file-info.js +0 -45
  131. package/dist/tools/filter-tools.js +0 -10
  132. package/dist/tools/glob-tool.js +0 -26
  133. package/dist/tools/grep-tool.js +0 -64
  134. package/dist/tools/index.js +0 -52
  135. package/dist/tools/list-dir.js +0 -47
  136. package/dist/tools/load-skill.js +0 -48
  137. package/dist/tools/mcp-call.js +0 -68
  138. package/dist/tools/move-file.js +0 -84
  139. package/dist/tools/path-utils.js +0 -51
  140. package/dist/tools/pipeline-run.js +0 -144
  141. package/dist/tools/preview.js +0 -2
  142. package/dist/tools/process-kill.js +0 -29
  143. package/dist/tools/process-list.js +0 -38
  144. package/dist/tools/process-log.js +0 -41
  145. package/dist/tools/question.js +0 -142
  146. package/dist/tools/read-file.js +0 -73
  147. package/dist/tools/recall.js +0 -110
  148. package/dist/tools/registry.js +0 -36
  149. package/dist/tools/remember.js +0 -67
  150. package/dist/tools/scope-check.js +0 -30
  151. package/dist/tools/search-history.js +0 -64
  152. package/dist/tools/subagent.js +0 -142
  153. package/dist/tools/types.js +0 -1
  154. package/dist/tools/user-input.js +0 -123
  155. package/dist/tools/web-browse.js +0 -57
  156. package/dist/tools/web-fetch.js +0 -72
  157. package/dist/tools/web-search.js +0 -59
  158. package/dist/tools/write-file.js +0 -80
  159. package/dist/ui/box.js +0 -81
  160. package/dist/ui/colors.js +0 -4
  161. package/dist/ui/diff.js +0 -185
  162. package/dist/ui/index.js +0 -6
  163. package/dist/ui/md-formatter.js +0 -212
  164. package/dist/ui/output.js +0 -13
  165. package/dist/ui/renderer.js +0 -141
  166. package/dist/ui/spinner.js +0 -70
  167. package/dist/ui/table.js +0 -144
@@ -1,144 +0,0 @@
1
- import { readFileSync } from "fs";
2
- import { extname } from "path";
3
- const MIME_MAP = {
4
- ".png": "image/png",
5
- ".jpg": "image/jpeg",
6
- ".jpeg": "image/jpeg",
7
- ".gif": "image/gif",
8
- ".webp": "image/webp",
9
- ".bmp": "image/bmp",
10
- ".svg": "image/svg+xml",
11
- };
12
- /** Detect MIME type from file extension. */
13
- export function detectMime(filePath) {
14
- const ext = extname(filePath).toLowerCase();
15
- return MIME_MAP[ext] ?? "image/png";
16
- }
17
- /**
18
- * Read image from system clipboard using Bun.Image (macOS/Windows).
19
- * Falls back to platform-specific commands on Linux.
20
- * Returns null if clipboard has no image.
21
- */
22
- export async function readClipboardImage() {
23
- // Bun.Image.fromClipboard() works on macOS and Windows
24
- if (typeof Bun !== "undefined" && typeof Bun.Image !== "undefined") {
25
- try {
26
- const img = Bun.Image.fromClipboard();
27
- if (img) {
28
- const buf = await img
29
- .resize(800, 800, { fit: "inside" })
30
- .jpeg({ quality: 60 })
31
- .buffer();
32
- return Buffer.from(buf);
33
- }
34
- }
35
- catch {
36
- // Bun.Image.fromClipboard() failed — fall through to platform fallback
37
- }
38
- }
39
- // Linux fallback: xclip/wl-paste → temp file → read
40
- return readClipboardFallback();
41
- }
42
- async function readClipboardFallback() {
43
- const { platform } = await import("os");
44
- const { execSync } = await import("child_process");
45
- const { readFileSync, unlinkSync } = await import("fs");
46
- const { join } = await import("path");
47
- const tmpPath = join(process.env.TEMP || process.env.TMP || "/tmp", `mma-clip-${Date.now()}.png`);
48
- try {
49
- if (platform() === "linux") {
50
- execSync(`xclip -selection clipboard -t image/png -o > "${tmpPath}" 2>/dev/null`, { timeout: 5000 });
51
- }
52
- else {
53
- return null; // macOS/Windows should use Bun.Image
54
- }
55
- const buf = readFileSync(tmpPath);
56
- unlinkSync(tmpPath);
57
- return buf.length > 0 ? buf : null;
58
- }
59
- catch {
60
- try {
61
- unlinkSync(tmpPath);
62
- }
63
- catch { }
64
- return null;
65
- }
66
- }
67
- /**
68
- * Load an image from a file path, resize via Bun.Image, return as JPEG data URL.
69
- * Target: ~800px wide, JPEG quality 60 — typically 5-15KB (~2-4K tokens).
70
- */
71
- export async function loadFileAsDataUrl(filePath) {
72
- const buf = readFileSync(filePath);
73
- // Use Bun.Image if available — resize + convert to JPEG
74
- if (typeof Bun !== "undefined" && typeof Bun.Image !== "undefined") {
75
- try {
76
- const img = new Bun.Image(buf);
77
- const { width } = await img.metadata();
78
- const targetWidth = Math.min(800, width || 800);
79
- const dataUrl = await img
80
- .resize(targetWidth, 800, { fit: "inside" })
81
- .jpeg({ quality: 60 })
82
- .dataurl();
83
- return { dataUrl };
84
- }
85
- catch {
86
- // Bun.Image failed — fall through to raw base64
87
- }
88
- }
89
- // Fallback: raw base64 (no resize)
90
- const b64 = buf.toString("base64");
91
- const ext = filePath.split(".").pop()?.toLowerCase();
92
- const mime = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : ext === "webp" ? "image/webp" : "image/png";
93
- return { dataUrl: `data:${mime};base64,${b64}` };
94
- }
95
- /**
96
- * Load an image from a URL, resize, return as JPEG data URL.
97
- */
98
- export async function loadUrlAsDataUrl(url) {
99
- const resp = await fetch(url);
100
- if (!resp.ok) {
101
- throw new Error(`Failed to fetch image: ${resp.status} ${resp.statusText}`);
102
- }
103
- const buf = Buffer.from(await resp.arrayBuffer());
104
- if (typeof Bun !== "undefined" && typeof Bun.Image !== "undefined") {
105
- try {
106
- const img = new Bun.Image(buf);
107
- const { width } = await img.metadata();
108
- const targetWidth = Math.min(800, width || 800);
109
- const dataUrl = await img
110
- .resize(targetWidth, 800, { fit: "inside" })
111
- .jpeg({ quality: 60 })
112
- .dataurl();
113
- return { dataUrl };
114
- }
115
- catch {
116
- // fall through
117
- }
118
- }
119
- const b64 = buf.toString("base64");
120
- return { dataUrl: `data:image/png;base64,${b64}` };
121
- }
122
- /**
123
- * Process a clipboard buffer (already resized by readClipboardImage)
124
- * into a data URL. Used by Ctrl+V handler.
125
- */
126
- export async function bufferToDataUrl(buf) {
127
- if (typeof Bun !== "undefined" && typeof Bun.Image !== "undefined") {
128
- try {
129
- const img = new Bun.Image(buf);
130
- const { width } = await img.metadata();
131
- const targetWidth = Math.min(800, width || 800);
132
- const dataUrl = await img
133
- .resize(targetWidth, 800, { fit: "inside" })
134
- .jpeg({ quality: 60 })
135
- .dataurl();
136
- return { dataUrl };
137
- }
138
- catch {
139
- // fall through
140
- }
141
- }
142
- const b64 = buf.toString("base64");
143
- return { dataUrl: `data:image/png;base64,${b64}` };
144
- }
package/dist/llm/index.js DELETED
@@ -1,4 +0,0 @@
1
- export { OpenAICompatProvider } from './openai-compat';
2
- export { TokenCounter } from './token-counter';
3
- export { parseChunks } from './response';
4
- export { OrchestratorClient } from './orchestrator';
@@ -1,78 +0,0 @@
1
- export class ModelLoader {
2
- baseUrl;
3
- logger;
4
- constructor(baseUrl, logger) {
5
- const url = baseUrl.replace(/\/$/, '');
6
- this.baseUrl = url.replace(/\/v1\/?$/, '');
7
- this.logger = logger;
8
- }
9
- async ensureModelLoaded(config) {
10
- if (config.autoLoad === false) {
11
- return { success: true, alreadyLoaded: true };
12
- }
13
- try {
14
- const isLoaded = await this.isModelLoaded(config.model, config.contextLength);
15
- if (isLoaded) {
16
- this.logger.debug(`Model ${config.model} already loaded with correct context`);
17
- return { success: true, alreadyLoaded: true };
18
- }
19
- return await this.loadModel(config);
20
- }
21
- catch (err) {
22
- this.logger.error(`Model loader failed: ${err.message}`);
23
- return { success: false, error: err.message };
24
- }
25
- }
26
- async isModelLoaded(model, contextLength) {
27
- try {
28
- const response = await fetch(`${this.baseUrl}/api/v1/models`, {
29
- signal: AbortSignal.timeout(3000),
30
- });
31
- if (!response.ok)
32
- return false;
33
- const data = await response.json();
34
- const models = data.models || [];
35
- const found = models.find((m) => m.key === model || m.name === model);
36
- if (!found)
37
- return false;
38
- const loadedInstances = found.loaded_instances || [];
39
- return loadedInstances.some((inst) => inst.config?.context_length === contextLength);
40
- }
41
- catch {
42
- return false;
43
- }
44
- }
45
- async loadModel(config) {
46
- const body = {
47
- model: config.model,
48
- context_length: config.contextLength,
49
- };
50
- if (config.flashAttention !== undefined)
51
- body.flash_attention = config.flashAttention;
52
- if (config.evalBatchSize !== undefined)
53
- body.eval_batch_size = config.evalBatchSize;
54
- if (config.offloadKvCacheToGpu !== undefined)
55
- body.offload_kv_cache_to_gpu = config.offloadKvCacheToGpu;
56
- this.logger.info(`Loading model ${config.model} with context_length=${config.contextLength}`);
57
- this.logger.debug(`POST ${this.baseUrl}/api/v1/models/load`);
58
- const response = await fetch(`${this.baseUrl}/api/v1/models/load`, {
59
- method: 'POST',
60
- headers: { 'Content-Type': 'application/json' },
61
- body: JSON.stringify(body),
62
- signal: AbortSignal.timeout(120000),
63
- });
64
- if (!response.ok) {
65
- const error = await response.text();
66
- this.logger.error(`Model load failed: HTTP ${response.status}: ${error}`);
67
- return { success: false, error: `HTTP ${response.status}: ${error}` };
68
- }
69
- const result = await response.json();
70
- this.logger.debug(`Model load response: ${JSON.stringify(result)}`);
71
- const loadTime = result.load_time_seconds ?? result.loadTime;
72
- return {
73
- success: true,
74
- alreadyLoaded: false,
75
- loadTime,
76
- };
77
- }
78
- }
@@ -1,324 +0,0 @@
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
- let usage;
102
- try {
103
- while (true) {
104
- const { done, value } = await reader.read();
105
- if (done)
106
- break;
107
- buffer += decoder.decode(value, { stream: true });
108
- const lines = buffer.split("\n");
109
- buffer = lines.pop() || "";
110
- for (const line of lines) {
111
- const trimmed = line.trim();
112
- if (!trimmed || !trimmed.startsWith("data: "))
113
- continue;
114
- const data = trimmed.slice(6);
115
- if (data === "[DONE]")
116
- continue;
117
- try {
118
- const parsed = JSON.parse(data);
119
- const choice = parsed.choices?.[0];
120
- if (!choice) {
121
- // Usage comes in the last chunk with empty choices
122
- if (parsed.usage) {
123
- usage = {
124
- promptTokens: parsed.usage.prompt_tokens ?? 0,
125
- completionTokens: parsed.usage.completion_tokens ?? 0,
126
- totalTokens: parsed.usage.total_tokens ?? 0,
127
- };
128
- }
129
- continue;
130
- }
131
- const delta = choice.delta || {};
132
- const finishReason = choice.finish_reason;
133
- if (delta.reasoning_content) {
134
- yield { type: "reasoning", content: delta.reasoning_content };
135
- }
136
- if (delta.tool_calls) {
137
- for (const tc of delta.tool_calls) {
138
- const idx = tc.index ?? 0;
139
- if (!toolCallAccs.has(idx)) {
140
- toolCallAccs.set(idx, { id: "", name: "", arguments: "" });
141
- }
142
- const acc = toolCallAccs.get(idx);
143
- if (tc.id)
144
- acc.id = tc.id;
145
- if (tc.function?.name)
146
- acc.name = tc.function.name;
147
- if (tc.function?.arguments) {
148
- acc.arguments += tc.function.arguments;
149
- }
150
- }
151
- }
152
- if (delta.content) {
153
- yield { type: "text", content: delta.content };
154
- }
155
- if (finishReason === "tool_calls" && toolCallAccs.size > 0) {
156
- for (const [, acc] of toolCallAccs) {
157
- if (acc.name) {
158
- yield {
159
- type: "tool_call",
160
- toolCall: {
161
- id: acc.id,
162
- name: acc.name,
163
- arguments: acc.arguments || "{}",
164
- },
165
- };
166
- }
167
- }
168
- toolCallAccs.clear();
169
- }
170
- }
171
- catch {
172
- // Skip malformed JSON lines
173
- }
174
- }
175
- }
176
- if (usage) {
177
- yield { type: "done", usage };
178
- }
179
- }
180
- finally {
181
- clearTimeout(timeoutId);
182
- reader.releaseLock();
183
- }
184
- }
185
- async doNonStreaming(messages, tools) {
186
- const body = {
187
- model: this.model,
188
- messages,
189
- stream: false,
190
- max_tokens: this.config.maxCompletionTokens ?? 4096,
191
- };
192
- if (tools && tools.length > 0) {
193
- body.tools = tools.map((t) => ({
194
- type: "function",
195
- function: {
196
- name: t.name,
197
- description: t.description,
198
- parameters: t.parameters,
199
- },
200
- }));
201
- body.tool_choice = "auto";
202
- }
203
- const headers = {
204
- "Content-Type": "application/json",
205
- };
206
- if (this.config.apiKey && this.config.apiKey !== "not-needed") {
207
- headers["Authorization"] = `Bearer ${this.config.apiKey}`;
208
- }
209
- try {
210
- const response = await this.fetchWithRetry(`${this.config.baseUrl}/chat/completions`, {
211
- method: "POST",
212
- headers,
213
- body: JSON.stringify(body),
214
- });
215
- if (!response.ok) {
216
- const errorText = await response.text();
217
- throw new Error(t("error.llm_api", {
218
- status: response.status,
219
- statusText: response.statusText,
220
- errorText: errorText.slice(0, 500),
221
- }));
222
- }
223
- const data = await response.json();
224
- const choice = data.choices?.[0];
225
- if (!choice) {
226
- return [];
227
- }
228
- const msg = choice.message || {};
229
- const chunks = [];
230
- if (msg.reasoning_content) {
231
- chunks.push({ type: "reasoning", content: msg.reasoning_content });
232
- }
233
- if (msg.content) {
234
- chunks.push({ type: "text", content: msg.content });
235
- }
236
- if (msg.tool_calls) {
237
- for (const tc of msg.tool_calls) {
238
- chunks.push({
239
- type: "tool_call",
240
- toolCall: {
241
- id: tc.id || "",
242
- name: tc.function?.name || "",
243
- arguments: tc.function?.arguments || "{}",
244
- },
245
- });
246
- }
247
- }
248
- // Append usage from API response
249
- if (data.usage) {
250
- chunks.push({
251
- type: "done",
252
- usage: {
253
- promptTokens: data.usage.prompt_tokens ?? 0,
254
- completionTokens: data.usage.completion_tokens ?? 0,
255
- totalTokens: data.usage.total_tokens ?? 0,
256
- },
257
- });
258
- }
259
- return chunks;
260
- }
261
- catch (err) {
262
- throw err instanceof Error ? err : new Error(String(err));
263
- }
264
- }
265
- countTokens(text) {
266
- return this.tokenCounter.count(text);
267
- }
268
- async listModels() {
269
- try {
270
- const url = `${this.config.baseUrl.replace(/\/+$/, "")}/models`;
271
- const headers = {
272
- "Content-Type": "application/json",
273
- };
274
- if (this.config.apiKey && this.config.apiKey !== "not-needed") {
275
- headers["Authorization"] = `Bearer ${this.config.apiKey}`;
276
- }
277
- const response = await fetch(url, {
278
- method: "GET",
279
- headers,
280
- });
281
- if (!response.ok) {
282
- return [];
283
- }
284
- const data = (await response.json());
285
- const models = (data.data || data || [])
286
- .map((m) => m.id || m.name || m.model || "")
287
- .filter(Boolean);
288
- return models;
289
- }
290
- catch {
291
- return [];
292
- }
293
- }
294
- async fetchWithRetry(url, init) {
295
- const { maxRetries, baseDelay, maxDelay } = this.retryConfig;
296
- let lastError = null;
297
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
298
- try {
299
- const response = await fetch(url, init);
300
- if (!this.isRetryable(response.status))
301
- return response;
302
- lastError = new Error(`HTTP ${response.status}: ${response.statusText}`);
303
- }
304
- catch (err) {
305
- if (err.name === "AbortError") {
306
- throw err;
307
- }
308
- lastError = err;
309
- }
310
- if (attempt < maxRetries) {
311
- const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
312
- const jitter = Math.random() * baseDelay * 0.1;
313
- await this.sleep(delay + jitter);
314
- }
315
- }
316
- throw lastError ?? new Error(t("error.llm_retries"));
317
- }
318
- isRetryable(status) {
319
- return status === 429 || status >= 500;
320
- }
321
- sleep(ms) {
322
- return new Promise((resolve) => setTimeout(resolve, ms));
323
- }
324
- }