micro-models-agent 0.57.0 → 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 -476
- 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/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,327 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "child_process";
|
|
2
|
+
import { platform } from "os";
|
|
3
|
+
const MAX_LOG_LINES = 2000;
|
|
4
|
+
const MAX_KEPT_PROCESSES = 20;
|
|
5
|
+
let seq = 0;
|
|
6
|
+
/** OEM decoder (Russian CP866 / active code page) — cached after first use. */
|
|
7
|
+
let oemDecoder;
|
|
8
|
+
function getOemDecoder() {
|
|
9
|
+
if (oemDecoder !== undefined)
|
|
10
|
+
return oemDecoder;
|
|
11
|
+
oemDecoder = null;
|
|
12
|
+
try {
|
|
13
|
+
const cpOut = spawnSync("chcp.com", {
|
|
14
|
+
encoding: "buffer",
|
|
15
|
+
timeout: 2000,
|
|
16
|
+
windowsHide: true,
|
|
17
|
+
}).stdout;
|
|
18
|
+
const m = cpOut ? cpOut.toString("latin1").match(/(\d+)/) : null;
|
|
19
|
+
if (m) {
|
|
20
|
+
try {
|
|
21
|
+
oemDecoder = new TextDecoder("ibm" + m[1]);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
oemDecoder = null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
/* ignore */
|
|
30
|
+
}
|
|
31
|
+
if (!oemDecoder) {
|
|
32
|
+
try {
|
|
33
|
+
oemDecoder = new TextDecoder("ibm866");
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
oemDecoder = null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return oemDecoder;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Decode one complete line of output to UTF-8.
|
|
43
|
+
*
|
|
44
|
+
* Modern tools (Bun, Node, npm, git) write UTF-8 into the pipe regardless of
|
|
45
|
+
* the console code page, while built-in cmd.exe commands (echo, type, dir)
|
|
46
|
+
* emit the OEM code page (CP866 on Russian Windows). Try strict UTF-8 first;
|
|
47
|
+
* fall back to the OEM decoder when the bytes are not valid UTF-8.
|
|
48
|
+
*/
|
|
49
|
+
function decodeLineToUtf8(buf) {
|
|
50
|
+
try {
|
|
51
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(buf);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
/* not valid UTF-8 → OEM code page output */
|
|
55
|
+
}
|
|
56
|
+
const oem = getOemDecoder();
|
|
57
|
+
if (oem) {
|
|
58
|
+
try {
|
|
59
|
+
return oem.decode(buf);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
/* unknown encoding — latin1 fallback */
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return buf.toString("latin1");
|
|
66
|
+
}
|
|
67
|
+
/** Synchronous pause without blocking the event loop (via Atomics.wait). */
|
|
68
|
+
function sleepSync(ms) {
|
|
69
|
+
try {
|
|
70
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
/* ignore */
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function taskkillPid(pid) {
|
|
77
|
+
try {
|
|
78
|
+
spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], {
|
|
79
|
+
windowsHide: true,
|
|
80
|
+
stdio: "ignore",
|
|
81
|
+
timeout: 5000,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
/* already dead */
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Kill a spawned tree on Windows.
|
|
90
|
+
*
|
|
91
|
+
* `taskkill /T` has a race: when cmd.exe is killed, a child (node) that is
|
|
92
|
+
* still starting up can survive as an orphan because it was never attached to
|
|
93
|
+
* the tree at kill time. A single pass misses it. Running taskkill twice with
|
|
94
|
+
* a settle gap catches those late starters on the second pass — the second
|
|
95
|
+
* tree walk sees the child that was still being created during the first one.
|
|
96
|
+
* This is much cheaper than enumerating processes (wmic/PowerShell), which
|
|
97
|
+
* slows every kill down to seconds under parallel load.
|
|
98
|
+
*/
|
|
99
|
+
export function killTree(child) {
|
|
100
|
+
const pid = child.pid;
|
|
101
|
+
if (!pid)
|
|
102
|
+
return;
|
|
103
|
+
if (platform() === "win32") {
|
|
104
|
+
taskkillPid(pid);
|
|
105
|
+
sleepSync(150);
|
|
106
|
+
taskkillPid(pid);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
process.kill(-pid, "SIGTERM");
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
try {
|
|
114
|
+
child.kill("SIGKILL");
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
/* already dead */
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
class ProcessRegistry {
|
|
122
|
+
procs = new Map();
|
|
123
|
+
children = new Map();
|
|
124
|
+
exitWaiters = new Map();
|
|
125
|
+
/**
|
|
126
|
+
* Start a command. The returned entry buffers output and reports status; a
|
|
127
|
+
* call may check `waitForExit(id)` to learn when (if ever) it finishes.
|
|
128
|
+
*/
|
|
129
|
+
start(command, cwd, sessionId) {
|
|
130
|
+
const id = `proc_${Date.now()}_${++seq}`;
|
|
131
|
+
const entry = {
|
|
132
|
+
id,
|
|
133
|
+
pid: 0,
|
|
134
|
+
command,
|
|
135
|
+
cwd,
|
|
136
|
+
sessionId,
|
|
137
|
+
status: "running",
|
|
138
|
+
exitCode: null,
|
|
139
|
+
startedAt: new Date().toISOString(),
|
|
140
|
+
log: [],
|
|
141
|
+
};
|
|
142
|
+
this.trimOldEntries();
|
|
143
|
+
this.procs.set(id, entry);
|
|
144
|
+
let child;
|
|
145
|
+
try {
|
|
146
|
+
child = spawn(command, {
|
|
147
|
+
cwd,
|
|
148
|
+
shell: true,
|
|
149
|
+
windowsHide: true,
|
|
150
|
+
detached: platform() !== "win32",
|
|
151
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
catch (e) {
|
|
155
|
+
entry.status = "killed";
|
|
156
|
+
entry.spawnError = e?.message || String(e);
|
|
157
|
+
entry.log.push(`[process error] ${entry.spawnError}`);
|
|
158
|
+
return entry;
|
|
159
|
+
}
|
|
160
|
+
this.children.set(id, child);
|
|
161
|
+
entry.pid = child.pid ?? 0;
|
|
162
|
+
let buf = "";
|
|
163
|
+
let byteBuf = Buffer.alloc(0);
|
|
164
|
+
const isWin = platform() === "win32";
|
|
165
|
+
const unixDecoder = new TextDecoder("utf-8");
|
|
166
|
+
const pushLine = (line) => {
|
|
167
|
+
if (entry.log.length >= MAX_LOG_LINES) {
|
|
168
|
+
entry.log.shift();
|
|
169
|
+
}
|
|
170
|
+
entry.log.push(line);
|
|
171
|
+
};
|
|
172
|
+
const append = (chunk) => {
|
|
173
|
+
if (!isWin) {
|
|
174
|
+
const decoded = unixDecoder.decode(chunk, { stream: true });
|
|
175
|
+
buf += decoded;
|
|
176
|
+
const lines = buf.split(/\r?\n/);
|
|
177
|
+
buf = lines.pop() ?? "";
|
|
178
|
+
for (const line of lines) {
|
|
179
|
+
pushLine(line);
|
|
180
|
+
}
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
// Windows: buffer raw bytes and decode per line. Modern tools (Bun, Node,
|
|
184
|
+
// npm, git) write UTF-8 into the pipe regardless of the console code
|
|
185
|
+
// page; cmd.exe builtins (echo, type, dir) emit the OEM code page. Pick
|
|
186
|
+
// the right decoding per line so Russian text survives either way.
|
|
187
|
+
byteBuf = byteBuf.length ? Buffer.concat([byteBuf, chunk]) : Buffer.from(chunk);
|
|
188
|
+
let nl;
|
|
189
|
+
while ((nl = byteBuf.indexOf(0x0a)) !== -1) {
|
|
190
|
+
const raw = byteBuf.subarray(0, nl);
|
|
191
|
+
byteBuf = byteBuf.subarray(nl + 1);
|
|
192
|
+
pushLine(decodeLineToUtf8(raw).replace(/\r$/, ""));
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
const flush = () => {
|
|
196
|
+
if (!isWin) {
|
|
197
|
+
buf += unixDecoder.decode();
|
|
198
|
+
if (buf) {
|
|
199
|
+
pushLine(buf);
|
|
200
|
+
buf = "";
|
|
201
|
+
}
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (byteBuf.length) {
|
|
205
|
+
pushLine(decodeLineToUtf8(byteBuf));
|
|
206
|
+
byteBuf = Buffer.alloc(0);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
const resolveExit = () => {
|
|
210
|
+
this.exitWaiters.get(id)?.resolve();
|
|
211
|
+
};
|
|
212
|
+
child.stdout?.on("data", append);
|
|
213
|
+
child.stderr?.on("data", append);
|
|
214
|
+
child.on("error", (err) => {
|
|
215
|
+
if (entry.status === "running") {
|
|
216
|
+
entry.status = "killed";
|
|
217
|
+
}
|
|
218
|
+
entry.spawnError = err.message;
|
|
219
|
+
// Write directly to the log, not through `append`: a failed spawn often
|
|
220
|
+
// never emits `close`, so the buffered line would never be flushed and
|
|
221
|
+
// the log would be empty (observed: "records a spawn error" test).
|
|
222
|
+
pushLine(`[process error] ${err.message}`);
|
|
223
|
+
resolveExit();
|
|
224
|
+
});
|
|
225
|
+
child.on("close", (code) => {
|
|
226
|
+
flush();
|
|
227
|
+
if (entry.status === "running") {
|
|
228
|
+
entry.status = "exited";
|
|
229
|
+
}
|
|
230
|
+
entry.exitCode = code;
|
|
231
|
+
this.children.delete(id);
|
|
232
|
+
resolveExit();
|
|
233
|
+
});
|
|
234
|
+
let resolve;
|
|
235
|
+
const promise = new Promise((r) => {
|
|
236
|
+
resolve = r;
|
|
237
|
+
});
|
|
238
|
+
this.exitWaiters.set(id, { promise, resolve });
|
|
239
|
+
return entry;
|
|
240
|
+
}
|
|
241
|
+
list(sessionId) {
|
|
242
|
+
const all = Array.from(this.procs.values());
|
|
243
|
+
if (!sessionId)
|
|
244
|
+
return all;
|
|
245
|
+
return all.filter((p) => p.sessionId === sessionId);
|
|
246
|
+
}
|
|
247
|
+
get(id) {
|
|
248
|
+
return this.procs.get(id);
|
|
249
|
+
}
|
|
250
|
+
getLog(id, tail) {
|
|
251
|
+
const entry = this.procs.get(id);
|
|
252
|
+
if (!entry)
|
|
253
|
+
return "";
|
|
254
|
+
const lines = tail && tail > 0 ? entry.log.slice(-tail) : entry.log;
|
|
255
|
+
return lines.join("\n");
|
|
256
|
+
}
|
|
257
|
+
/** Kill a background process tree. Returns false when not found. */
|
|
258
|
+
kill(id) {
|
|
259
|
+
const entry = this.procs.get(id);
|
|
260
|
+
if (!entry)
|
|
261
|
+
return false;
|
|
262
|
+
if (entry.status === "running") {
|
|
263
|
+
entry.status = "killed";
|
|
264
|
+
const child = this.children.get(id);
|
|
265
|
+
if (child) {
|
|
266
|
+
killTree(child);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return true;
|
|
270
|
+
}
|
|
271
|
+
/** Kill every managed background process (used on agent shutdown). */
|
|
272
|
+
killAll(sessionId) {
|
|
273
|
+
const targets = this.list(sessionId);
|
|
274
|
+
for (const entry of targets) {
|
|
275
|
+
this.kill(entry.id);
|
|
276
|
+
}
|
|
277
|
+
return targets.length;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Resolve `true` when the process exits (or fails to spawn) within
|
|
281
|
+
* `timeoutMs`, otherwise `false` (still running → a background process).
|
|
282
|
+
*/
|
|
283
|
+
waitForExit(id, timeoutMs) {
|
|
284
|
+
const entry = this.procs.get(id);
|
|
285
|
+
const waiter = this.exitWaiters.get(id);
|
|
286
|
+
if (!entry || entry.status !== "running" || !waiter) {
|
|
287
|
+
return Promise.resolve(true);
|
|
288
|
+
}
|
|
289
|
+
return new Promise((resolve) => {
|
|
290
|
+
const timer = setTimeout(() => resolve(false), timeoutMs);
|
|
291
|
+
waiter.promise.then(() => {
|
|
292
|
+
clearTimeout(timer);
|
|
293
|
+
resolve(true);
|
|
294
|
+
});
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Remove a finished entry (foreground results do not linger). A still-running
|
|
299
|
+
* entry is killed first so nothing is orphaned.
|
|
300
|
+
*/
|
|
301
|
+
remove(id) {
|
|
302
|
+
const entry = this.procs.get(id);
|
|
303
|
+
if (!entry)
|
|
304
|
+
return false;
|
|
305
|
+
if (entry.status === "running") {
|
|
306
|
+
const child = this.children.get(id);
|
|
307
|
+
if (child) {
|
|
308
|
+
killTree(child);
|
|
309
|
+
}
|
|
310
|
+
entry.status = "killed";
|
|
311
|
+
}
|
|
312
|
+
this.procs.delete(id);
|
|
313
|
+
this.children.delete(id);
|
|
314
|
+
this.exitWaiters.delete(id);
|
|
315
|
+
return true;
|
|
316
|
+
}
|
|
317
|
+
trimOldEntries() {
|
|
318
|
+
if (this.procs.size < MAX_KEPT_PROCESSES)
|
|
319
|
+
return;
|
|
320
|
+
const sorted = Array.from(this.procs.values()).sort((a, b) => a.startedAt.localeCompare(b.startedAt));
|
|
321
|
+
const toRemove = sorted.slice(0, sorted.length - MAX_KEPT_PROCESSES + 1);
|
|
322
|
+
for (const entry of toRemove) {
|
|
323
|
+
this.remove(entry.id);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
export const processRegistry = new ProcessRegistry();
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const activeChildren = new Map();
|
|
2
|
+
/** Register a kill callback for a tool call id (executor timeout/abort). */
|
|
3
|
+
export function registerKillable(callId, kill) {
|
|
4
|
+
activeChildren.set(callId, { kill });
|
|
5
|
+
}
|
|
6
|
+
/** Unregister a tool call's kill callback once its handler finished. */
|
|
7
|
+
export function unregisterKillable(callId) {
|
|
8
|
+
activeChildren.delete(callId);
|
|
9
|
+
}
|
|
10
|
+
/** Invoke (and drop) the kill callback registered for `callId`. */
|
|
11
|
+
export function killByCallId(callId) {
|
|
12
|
+
const entry = activeChildren.get(callId);
|
|
13
|
+
if (!entry)
|
|
14
|
+
return false;
|
|
15
|
+
activeChildren.delete(callId);
|
|
16
|
+
try {
|
|
17
|
+
entry.kill();
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
/* already dead */
|
|
21
|
+
}
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { BUILTIN_PROVIDERS } from "./presets";
|
|
2
|
+
import { ProviderRegistry as Registry } from "./registry";
|
|
3
|
+
/**
|
|
4
|
+
* The single entry point for building a provider. Unknown types fall back to
|
|
5
|
+
* the OpenAI-compatible provider (backward compatible with legacy configs that
|
|
6
|
+
* use a custom `type` + baseUrl).
|
|
7
|
+
*/
|
|
8
|
+
export function createProvider(type, opts, registry = defaultRegistry()) {
|
|
9
|
+
const spec = registry.get(type);
|
|
10
|
+
if (!spec) {
|
|
11
|
+
return BUILTIN_PROVIDERS[0].create(opts);
|
|
12
|
+
}
|
|
13
|
+
return spec.create(opts);
|
|
14
|
+
}
|
|
15
|
+
/** Registry preloaded with all builtin provider presets. */
|
|
16
|
+
export function defaultRegistry() {
|
|
17
|
+
const registry = new Registry();
|
|
18
|
+
for (const spec of BUILTIN_PROVIDERS) {
|
|
19
|
+
registry.register(spec);
|
|
20
|
+
}
|
|
21
|
+
return registry;
|
|
22
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** True when the error is worth failing over to another provider. */
|
|
2
|
+
export function isFailoverError(err) {
|
|
3
|
+
const e = err;
|
|
4
|
+
if (e?.name === "AbortError")
|
|
5
|
+
return false;
|
|
6
|
+
// HTTP status attached by openai-compat: retryable statuses only.
|
|
7
|
+
if (typeof e?.llmStatus === "number")
|
|
8
|
+
return e.llmStatus === 429 || e.llmStatus >= 500;
|
|
9
|
+
// Network-level failures by errno-style code (Bun: "ConnectionRefused",
|
|
10
|
+
// Node: "ECONNREFUSED", DNS: "ENOTFOUND"/"EAI_AGAIN", etc).
|
|
11
|
+
const normCode = (e?.code ?? "").replace(/[-_]/g, "").toLowerCase();
|
|
12
|
+
if (/^abort/.test(normCode))
|
|
13
|
+
return false;
|
|
14
|
+
if (/conn(refused|reset|timedout)|enotfound|eai_again|namenotresolved/.test(normCode)) {
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
// Network-level failures by message (fetch failed, timeouts, socket resets).
|
|
18
|
+
return /fetch failed|unable to connect|network|econnrefused|enotfound|etimedout|socket hang up|connection refused|connection reset/i.test(e?.message ?? "");
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Wraps a FallbackSource so that retryable failures (429/5xx/network) on the
|
|
22
|
+
* active provider transparently switch to the next configured entry and retry
|
|
23
|
+
* there. Failover happens ONLY before any chunk was emitted — mid-stream
|
|
24
|
+
* failures rethrow to avoid duplicated output. The last provider that served
|
|
25
|
+
* a successful call becomes the new active entry (sticky).
|
|
26
|
+
*/
|
|
27
|
+
export class FallbackProvider {
|
|
28
|
+
source;
|
|
29
|
+
onFailover;
|
|
30
|
+
constructor(source, onFailover) {
|
|
31
|
+
this.source = source;
|
|
32
|
+
this.onFailover = onFailover;
|
|
33
|
+
}
|
|
34
|
+
get model() {
|
|
35
|
+
return this.source.active.model;
|
|
36
|
+
}
|
|
37
|
+
get contextWindow() {
|
|
38
|
+
return this.source.active.contextWindow;
|
|
39
|
+
}
|
|
40
|
+
async *chat(messages, tools, signal, options) {
|
|
41
|
+
const names = this.source.listNames();
|
|
42
|
+
if (names.length <= 1) {
|
|
43
|
+
yield* this.source.active.chat(messages, tools, signal, options);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
let emitted = false;
|
|
47
|
+
let idx = Math.max(0, names.indexOf(this.source.activeName));
|
|
48
|
+
let lastError;
|
|
49
|
+
for (let attempt = 0; attempt < names.length; attempt++) {
|
|
50
|
+
const name = names[idx];
|
|
51
|
+
const provider = name === this.source.activeName
|
|
52
|
+
? this.source.active
|
|
53
|
+
: this.source.switch(name);
|
|
54
|
+
try {
|
|
55
|
+
for await (const chunk of provider.chat(messages, tools, signal, options)) {
|
|
56
|
+
emitted = true;
|
|
57
|
+
yield chunk;
|
|
58
|
+
}
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
catch (err) {
|
|
62
|
+
// Mid-stream failure after content was delivered: a restart would
|
|
63
|
+
// duplicate chunks — surface the error instead of failing over.
|
|
64
|
+
if (emitted || !isFailoverError(err))
|
|
65
|
+
throw err;
|
|
66
|
+
lastError = err;
|
|
67
|
+
idx = (idx + 1) % names.length;
|
|
68
|
+
this.onFailover?.(name, names[idx], err);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
throw lastError;
|
|
72
|
+
}
|
|
73
|
+
countTokens(text) {
|
|
74
|
+
return this.source.active.countTokens(text);
|
|
75
|
+
}
|
|
76
|
+
async listModels() {
|
|
77
|
+
return this.source.active.listModels();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Probe providers concurrently (bounded by the caller passing few entries)
|
|
3
|
+
* and report ✓/✗ per entry. Uses `listModels()` — a free, cheap call — never
|
|
4
|
+
* a billed chat completion. Input order is preserved in the output.
|
|
5
|
+
*/
|
|
6
|
+
export async function probeProviders(targets, opts) {
|
|
7
|
+
const timeoutMs = opts?.timeoutMs ?? 5000;
|
|
8
|
+
const results = await Promise.all(targets.map((t) => probeOne(t, timeoutMs)));
|
|
9
|
+
return results;
|
|
10
|
+
}
|
|
11
|
+
async function probeOne(target, timeoutMs) {
|
|
12
|
+
const start = Date.now();
|
|
13
|
+
try {
|
|
14
|
+
const models = await withTimeout(target.listModels(), timeoutMs);
|
|
15
|
+
return { name: target.name, ok: true, ms: Date.now() - start, models: models.length };
|
|
16
|
+
}
|
|
17
|
+
catch (err) {
|
|
18
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
19
|
+
return {
|
|
20
|
+
name: target.name,
|
|
21
|
+
ok: false,
|
|
22
|
+
ms: Date.now() - start,
|
|
23
|
+
models: 0,
|
|
24
|
+
error: message,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function withTimeout(promise, ms) {
|
|
29
|
+
return new Promise((resolve, reject) => {
|
|
30
|
+
const timer = setTimeout(() => reject(new Error(`timeout after ${ms}ms`)), ms);
|
|
31
|
+
promise.then((v) => {
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
resolve(v);
|
|
34
|
+
}, (e) => {
|
|
35
|
+
clearTimeout(timer);
|
|
36
|
+
reject(e);
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
/** Build probe targets from a name→provider mapping (priority order). */
|
|
41
|
+
export function targetsFromProviders(entries) {
|
|
42
|
+
return entries.map(({ name, provider }) => ({
|
|
43
|
+
name,
|
|
44
|
+
listModels: () => provider.listModels(),
|
|
45
|
+
}));
|
|
46
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { ProviderRegistry } from "./registry";
|
|
2
|
+
export { createProvider, defaultRegistry } from "./create";
|
|
3
|
+
export { ProviderManager, presetOf } from "./manager";
|
|
4
|
+
export { probeProviders, targetsFromProviders, } from "./health";
|
|
5
|
+
export { BUILTIN_PROVIDERS, HOSTED_BASE_URLS } from "./presets";
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { createProvider, defaultRegistry } from "./create";
|
|
2
|
+
import { BUILTIN_PROVIDERS } from "./presets";
|
|
3
|
+
/**
|
|
4
|
+
* Manages the active provider + model at runtime. Supports several configured
|
|
5
|
+
* providers (`ProviderConfig.entries`) with hot-swap (`switch`, `setModel`).
|
|
6
|
+
* Legacy single-provider configs (`{type, baseUrl, apiKey}`) are normalized
|
|
7
|
+
* into a single-entry list, so existing configs keep working.
|
|
8
|
+
*/
|
|
9
|
+
export class ProviderManager {
|
|
10
|
+
entries;
|
|
11
|
+
activeProviderName;
|
|
12
|
+
model;
|
|
13
|
+
opts;
|
|
14
|
+
registry;
|
|
15
|
+
cache = new Map();
|
|
16
|
+
constructor(config, opts) {
|
|
17
|
+
this.opts = opts;
|
|
18
|
+
this.registry = opts.registry ?? defaultRegistry();
|
|
19
|
+
this.entries = this.normalizeEntries(config);
|
|
20
|
+
this.activeProviderName = this.resolveActive(config);
|
|
21
|
+
this.model = "";
|
|
22
|
+
}
|
|
23
|
+
/** The model the active provider is built with. */
|
|
24
|
+
get activeModel() {
|
|
25
|
+
return this.model;
|
|
26
|
+
}
|
|
27
|
+
/** Name/label of the active provider. */
|
|
28
|
+
get activeName() {
|
|
29
|
+
return this.activeProviderName;
|
|
30
|
+
}
|
|
31
|
+
get active() {
|
|
32
|
+
return this.build(this.activeProviderName);
|
|
33
|
+
}
|
|
34
|
+
get activeEntry() {
|
|
35
|
+
const entry = this.entryByName(this.activeProviderName);
|
|
36
|
+
if (!entry)
|
|
37
|
+
throw new Error(`Unknown active provider "${this.activeProviderName}"`);
|
|
38
|
+
return entry;
|
|
39
|
+
}
|
|
40
|
+
/** All configured entries (resolved with preset metadata), priority-ordered. */
|
|
41
|
+
list() {
|
|
42
|
+
return this.entries
|
|
43
|
+
.map((e) => {
|
|
44
|
+
const preset = this.registry.get(e.type);
|
|
45
|
+
return { ...e, label: e.label || preset?.label || e.type };
|
|
46
|
+
})
|
|
47
|
+
.map((e, i) => ({ e, i, p: e.priority ?? Number.MAX_SAFE_INTEGER }))
|
|
48
|
+
.sort((a, b) => a.p - b.p || a.i - b.i)
|
|
49
|
+
.map(({ e }) => e);
|
|
50
|
+
}
|
|
51
|
+
listNames() {
|
|
52
|
+
return this.list().map((e) => e.label);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* CODE-ONLY capability routing (Phase 4.4): pick the first entry (priority
|
|
56
|
+
* order) whose preset capabilities and context window satisfy `needs`.
|
|
57
|
+
* Never exposed to the LLM — the model must not choose providers.
|
|
58
|
+
*/
|
|
59
|
+
pickFor(needs) {
|
|
60
|
+
const globalWindow = this.opts.contextWindow;
|
|
61
|
+
// No constraints → keep the current active provider.
|
|
62
|
+
if (!needs.vision && !needs.tools && needs.minContext === undefined) {
|
|
63
|
+
return this.activeProviderName;
|
|
64
|
+
}
|
|
65
|
+
for (const e of this.list()) {
|
|
66
|
+
const caps = this.registry.get(e.type)?.capabilities;
|
|
67
|
+
if (needs.vision && !caps?.vision)
|
|
68
|
+
continue;
|
|
69
|
+
if (needs.tools && !caps?.tools)
|
|
70
|
+
continue;
|
|
71
|
+
if (needs.minContext !== undefined &&
|
|
72
|
+
(e.contextWindow ?? globalWindow) < needs.minContext) {
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
return e.label;
|
|
76
|
+
}
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
/** Hot-swap to a named provider; rebuild the active provider. */
|
|
80
|
+
switch(name, model) {
|
|
81
|
+
if (!this.entryByName(name)) {
|
|
82
|
+
throw new Error(`Unknown provider "${name}"`);
|
|
83
|
+
}
|
|
84
|
+
this.activeProviderName = name;
|
|
85
|
+
if (model !== undefined)
|
|
86
|
+
this.model = model;
|
|
87
|
+
return this.active;
|
|
88
|
+
}
|
|
89
|
+
/** Rebuild the active provider with a new model. */
|
|
90
|
+
setModel(model) {
|
|
91
|
+
this.model = model;
|
|
92
|
+
return this.active;
|
|
93
|
+
}
|
|
94
|
+
/** Serialize back to ProviderConfig (keeps active/entries in sync). */
|
|
95
|
+
toConfig() {
|
|
96
|
+
const active = this.activeEntry;
|
|
97
|
+
return {
|
|
98
|
+
active: this.activeProviderName,
|
|
99
|
+
entries: this.entries,
|
|
100
|
+
fallback: false,
|
|
101
|
+
type: active.type,
|
|
102
|
+
baseUrl: active.baseUrl,
|
|
103
|
+
apiKey: active.apiKey,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
normalizeEntries(config) {
|
|
107
|
+
if (Array.isArray(config.entries) && config.entries.length > 0) {
|
|
108
|
+
return config.entries.map((e) => ({ ...e, label: e.label || e.type }));
|
|
109
|
+
}
|
|
110
|
+
// Legacy single-provider form (or empty config) → one default entry.
|
|
111
|
+
return [
|
|
112
|
+
{
|
|
113
|
+
type: config.type ?? "openai-compat",
|
|
114
|
+
label: config.type ?? "openai-compat",
|
|
115
|
+
baseUrl: config.baseUrl ?? "",
|
|
116
|
+
apiKey: config.apiKey,
|
|
117
|
+
maxCompletionTokens: config.maxCompletionTokens,
|
|
118
|
+
},
|
|
119
|
+
];
|
|
120
|
+
}
|
|
121
|
+
resolveActive(config) {
|
|
122
|
+
if (config.active && this.entryByName(config.active))
|
|
123
|
+
return config.active;
|
|
124
|
+
const first = this.entries[0];
|
|
125
|
+
return first ? (first.label ?? "openai-compat") : "openai-compat";
|
|
126
|
+
}
|
|
127
|
+
entryByName(name) {
|
|
128
|
+
return this.entries.find((e) => e.label === name || e.type === name);
|
|
129
|
+
}
|
|
130
|
+
build(name) {
|
|
131
|
+
const entry = this.entryByName(name);
|
|
132
|
+
if (!entry)
|
|
133
|
+
throw new Error(`Unknown provider "${name}"`);
|
|
134
|
+
const key = `${name}|${this.model}`;
|
|
135
|
+
const cached = this.cache.get(key);
|
|
136
|
+
if (cached)
|
|
137
|
+
return cached;
|
|
138
|
+
const provider = createProvider(entry.type, {
|
|
139
|
+
model: this.model,
|
|
140
|
+
baseUrl: entry.baseUrl,
|
|
141
|
+
apiKey: entry.apiKey,
|
|
142
|
+
contextWindow: entry.contextWindow ?? this.opts.contextWindow,
|
|
143
|
+
retry: entry.retry ?? this.opts.retry,
|
|
144
|
+
rateLimits: entry.rateLimits ?? this.opts.rateLimits,
|
|
145
|
+
maxCompletionTokens: entry.maxCompletionTokens,
|
|
146
|
+
}, this.registry);
|
|
147
|
+
this.cache.set(key, provider);
|
|
148
|
+
return provider;
|
|
149
|
+
}
|
|
150
|
+
/** Clear the build cache (on config change). */
|
|
151
|
+
resetCache() {
|
|
152
|
+
this.cache.clear();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/** Export preset metadata for the CLI (label/capabilities/baseUrl). */
|
|
156
|
+
export function presetOf(type) {
|
|
157
|
+
const spec = BUILTIN_PROVIDERS.find((p) => p.type === type);
|
|
158
|
+
if (!spec)
|
|
159
|
+
return undefined;
|
|
160
|
+
return { label: spec.label, baseUrl: spec.baseUrl };
|
|
161
|
+
}
|