micro-models-agent 0.28.9 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/dist/cli/commands.js +220 -0
  2. package/dist/cli/completer.js +168 -0
  3. package/dist/cli/index.js +2 -0
  4. package/dist/cli/main.js +113 -0
  5. package/dist/cli/repl.js +987 -0
  6. package/dist/cli/security-commands.js +166 -0
  7. package/dist/cli/setup.js +229 -0
  8. package/dist/config/config.js +186 -0
  9. package/dist/config/defaults.js +91 -0
  10. package/dist/config/experts.js +15 -0
  11. package/dist/config/index.js +3 -0
  12. package/dist/config/security.js +193 -0
  13. package/dist/config/types.js +1 -0
  14. package/dist/core/agent-moe.js +98 -0
  15. package/dist/core/agent.js +461 -0
  16. package/dist/core/bootstrap.js +321 -0
  17. package/dist/core/index.js +2 -0
  18. package/dist/core/prompt-builder.js +55 -0
  19. package/dist/core/session-logger.js +122 -0
  20. package/dist/core/types.js +1 -0
  21. package/dist/i18n/en.json +461 -0
  22. package/dist/i18n/index.js +43 -0
  23. package/dist/i18n/ru.json +461 -0
  24. package/dist/index.js +22 -0
  25. package/dist/llm/image-utils.js +144 -0
  26. package/dist/llm/index.js +4 -0
  27. package/dist/llm/model-loader.js +78 -0
  28. package/dist/llm/openai-compat.js +324 -0
  29. package/dist/llm/orchestrator.js +194 -0
  30. package/dist/llm/provider.js +10 -0
  31. package/dist/llm/response.js +39 -0
  32. package/dist/llm/token-counter.js +39 -0
  33. package/dist/llm/types.js +1 -0
  34. package/dist/logger/app-logger.js +76 -0
  35. package/dist/logger/index.js +1 -0
  36. package/dist/main.js +2251 -724
  37. package/dist/migration/backup.js +45 -0
  38. package/dist/migration/detect.js +50 -0
  39. package/dist/migration/index.js +2 -0
  40. package/dist/modules/browser/actions.js +46 -0
  41. package/dist/modules/browser/cookie-store.js +24 -0
  42. package/dist/modules/browser/index.js +5 -0
  43. package/dist/modules/browser/module.js +28 -0
  44. package/dist/modules/browser/session.js +287 -0
  45. package/dist/modules/browser/snapshot.js +114 -0
  46. package/dist/modules/browser/types.js +9 -0
  47. package/dist/modules/context/history.js +15 -0
  48. package/dist/modules/context/index.js +1 -0
  49. package/dist/modules/context/manager.js +240 -0
  50. package/dist/modules/execution/auditor.js +72 -0
  51. package/dist/modules/execution/index.js +6 -0
  52. package/dist/modules/execution/module.js +337 -0
  53. package/dist/modules/execution/moe-executor.js +209 -0
  54. package/dist/modules/execution/plan-validator.js +153 -0
  55. package/dist/modules/execution/planner.js +35 -0
  56. package/dist/modules/execution/stuck-detector.js +134 -0
  57. package/dist/modules/execution/tracker.js +53 -0
  58. package/dist/modules/execution/types.js +1 -0
  59. package/dist/modules/execution/verifier.js +149 -0
  60. package/dist/modules/hallucination/confidence.js +54 -0
  61. package/dist/modules/hallucination/consistency.js +60 -0
  62. package/dist/modules/hallucination/detector.js +41 -0
  63. package/dist/modules/hallucination/factual.js +170 -0
  64. package/dist/modules/hallucination/index.js +4 -0
  65. package/dist/modules/index.js +5 -0
  66. package/dist/modules/indexer/cache.js +38 -0
  67. package/dist/modules/indexer/index.js +3 -0
  68. package/dist/modules/indexer/module.js +192 -0
  69. package/dist/modules/indexer/walker.js +101 -0
  70. package/dist/modules/mcp/client.js +393 -0
  71. package/dist/modules/mcp/index.js +3 -0
  72. package/dist/modules/mcp/module.js +146 -0
  73. package/dist/modules/mcp/registry.js +15 -0
  74. package/dist/modules/memory/index.js +1 -0
  75. package/dist/modules/memory/module.js +48 -0
  76. package/dist/modules/memory/search.js +40 -0
  77. package/dist/modules/memory/store.js +65 -0
  78. package/dist/modules/pipelines/engine.js +60 -0
  79. package/dist/modules/pipelines/index.js +3 -0
  80. package/dist/modules/pipelines/parser.js +53 -0
  81. package/dist/modules/pipelines/template.js +14 -0
  82. package/dist/modules/plugins/builtin/lint-on-write.js +121 -0
  83. package/dist/modules/plugins/builtin/notify.js +8 -0
  84. package/dist/modules/plugins/index.js +1 -0
  85. package/dist/modules/plugins/loader.js +28 -0
  86. package/dist/modules/plugins/manager.js +161 -0
  87. package/dist/modules/plugins/types.js +1 -0
  88. package/dist/modules/processes/detect.js +34 -0
  89. package/dist/modules/processes/index.js +3 -0
  90. package/dist/modules/processes/registry.js +148 -0
  91. package/dist/modules/processes/runner.js +124 -0
  92. package/dist/modules/registry.js +45 -0
  93. package/dist/modules/security/audit-log.js +116 -0
  94. package/dist/modules/security/audit-notifier.js +292 -0
  95. package/dist/modules/security/command-validator.js +185 -0
  96. package/dist/modules/security/content-scanner.js +52 -0
  97. package/dist/modules/security/data-sanitizer.js +97 -0
  98. package/dist/modules/security/encryption.js +240 -0
  99. package/dist/modules/security/index.js +14 -0
  100. package/dist/modules/security/network-validator.js +79 -0
  101. package/dist/modules/security/path-validator.js +155 -0
  102. package/dist/modules/security/rate-limiter.js +119 -0
  103. package/dist/modules/security/security-policies.js +393 -0
  104. package/dist/modules/security/session-encryption.js +193 -0
  105. package/dist/modules/security/session-isolation.js +95 -0
  106. package/dist/modules/session/index.js +3 -0
  107. package/dist/modules/session/manager.js +167 -0
  108. package/dist/modules/session/module.js +24 -0
  109. package/dist/modules/session/store.js +174 -0
  110. package/dist/modules/session/types.js +1 -0
  111. package/dist/modules/skills/index.js +3 -0
  112. package/dist/modules/skills/loader.js +72 -0
  113. package/dist/modules/skills/matcher.js +27 -0
  114. package/dist/modules/skills/module.js +143 -0
  115. package/dist/modules/types.js +1 -0
  116. package/dist/modules/updater/checker.js +32 -0
  117. package/dist/modules/updater/index.js +1 -0
  118. package/dist/modules/user-profile/compressor.js +16 -0
  119. package/dist/modules/user-profile/index.js +1 -0
  120. package/dist/modules/user-profile/profile.js +68 -0
  121. package/dist/tools/approve.js +32 -0
  122. package/dist/tools/attach-image.js +89 -0
  123. package/dist/tools/bash.js +140 -0
  124. package/dist/tools/browser.js +97 -0
  125. package/dist/tools/create-dir.js +56 -0
  126. package/dist/tools/delete-file.js +63 -0
  127. package/dist/tools/edit-file.js +77 -0
  128. package/dist/tools/executor.js +95 -0
  129. package/dist/tools/file-info.js +45 -0
  130. package/dist/tools/filter-tools.js +10 -0
  131. package/dist/tools/glob-tool.js +26 -0
  132. package/dist/tools/grep-tool.js +64 -0
  133. package/dist/tools/index.js +52 -0
  134. package/dist/tools/list-dir.js +47 -0
  135. package/dist/tools/load-skill.js +48 -0
  136. package/dist/tools/mcp-call.js +68 -0
  137. package/dist/tools/move-file.js +84 -0
  138. package/dist/tools/path-utils.js +51 -0
  139. package/dist/tools/pipeline-run.js +144 -0
  140. package/dist/tools/preview.js +2 -0
  141. package/dist/tools/process-kill.js +29 -0
  142. package/dist/tools/process-list.js +38 -0
  143. package/dist/tools/process-log.js +41 -0
  144. package/dist/tools/question.js +142 -0
  145. package/dist/tools/read-file.js +73 -0
  146. package/dist/tools/recall.js +110 -0
  147. package/dist/tools/registry.js +36 -0
  148. package/dist/tools/remember.js +67 -0
  149. package/dist/tools/scope-check.js +30 -0
  150. package/dist/tools/search-history.js +64 -0
  151. package/dist/tools/subagent.js +142 -0
  152. package/dist/tools/types.js +1 -0
  153. package/dist/tools/user-input.js +123 -0
  154. package/dist/tools/web-browse.js +57 -0
  155. package/dist/tools/web-fetch.js +72 -0
  156. package/dist/tools/web-search.js +59 -0
  157. package/dist/tools/write-file.js +80 -0
  158. package/dist/ui/box.js +81 -0
  159. package/dist/ui/colors.js +4 -0
  160. package/dist/ui/diff.js +185 -0
  161. package/dist/ui/index.js +6 -0
  162. package/dist/ui/md-formatter.js +212 -0
  163. package/dist/ui/output.js +13 -0
  164. package/dist/ui/renderer.js +141 -0
  165. package/dist/ui/spinner.js +70 -0
  166. package/dist/ui/table.js +144 -0
  167. package/package.json +4 -4
@@ -0,0 +1,144 @@
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
+ }
@@ -0,0 +1,4 @@
1
+ export { OpenAICompatProvider } from './openai-compat';
2
+ export { TokenCounter } from './token-counter';
3
+ export { parseChunks } from './response';
4
+ export { OrchestratorClient } from './orchestrator';
@@ -0,0 +1,78 @@
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
+ }
@@ -0,0 +1,324 @@
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
+ }