@imliulian/dsh-zeromem 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +13 -0
- package/LICENSE +661 -0
- package/NOTICE +17 -0
- package/README.md +112 -2
- package/README.zh.md +114 -0
- package/assets/panel.js +2880 -0
- package/cordis.patch.yml +13 -0
- package/lib/config.mjs +469 -0
- package/lib/contracts.mjs +391 -0
- package/lib/expiry.mjs +255 -0
- package/lib/hooks.mjs +278 -0
- package/lib/index.mjs +118 -0
- package/lib/llm.mjs +823 -0
- package/lib/memory.mjs +654 -0
- package/lib/store.mjs +1008 -0
- package/lib/tools.mjs +470 -0
- package/lib/web.mjs +551 -0
- package/package.json +56 -4
package/lib/llm.mjs
ADDED
|
@@ -0,0 +1,823 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dual-backend LLM client for ZeroMem DSH plugin:
|
|
3
|
+
* 1. Local Ollama (`provider: "ollama"`) — direct node:http/https loopback requests
|
|
4
|
+
* (bypasses system proxy cleanly on Windows/macOS), auto-detects Qwen3.5-4B-Memory-V2,
|
|
5
|
+
* enforces deterministic anti-OTL parameters.
|
|
6
|
+
* 2. OpenAI-compatible API (`provider: "openai-compatible"`) — standard `/chat/completions`
|
|
7
|
+
* supporting DeepSeek, OpenAI, SiliconFlow, OpenRouter, LM Studio, vLLM, etc.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { execFile, spawn } from "node:child_process";
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import http from "node:http";
|
|
13
|
+
import https from "node:https";
|
|
14
|
+
import os from "node:os";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import { DEFAULT_API_BASE_URL, DEFAULT_API_MODEL, DEFAULT_NUM_CTX, DEFAULT_OLLAMA_URL } from "./config.mjs";
|
|
17
|
+
|
|
18
|
+
export const HF_REPO_ID = "IMLIULIAN/qwen3.5-4b-memory-v2";
|
|
19
|
+
export const SAFE_OLLAMA_MODEL_RE = /^[a-zA-Z0-9._:/-]{2,140}$/;
|
|
20
|
+
|
|
21
|
+
export const RECOMMENDED_LOCAL_PULL_MODELS = Object.freeze([
|
|
22
|
+
{
|
|
23
|
+
id: `hf.co/${HF_REPO_ID}:Q8_0`,
|
|
24
|
+
shortLabel: "V2 标准版",
|
|
25
|
+
sizeHint: "4.5 GB · 推荐",
|
|
26
|
+
recommended: true,
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
id: `hf.co/${HF_REPO_ID}:Q4_K_M`,
|
|
30
|
+
shortLabel: "V2 轻量版",
|
|
31
|
+
sizeHint: "2.7 GB · 低显存",
|
|
32
|
+
recommended: false,
|
|
33
|
+
},
|
|
34
|
+
]);
|
|
35
|
+
|
|
36
|
+
export function getOllamaInstallGuide(platform = process.platform) {
|
|
37
|
+
if (platform === "win32") {
|
|
38
|
+
return {
|
|
39
|
+
platform: "win32",
|
|
40
|
+
command: "winget install Ollama.Ollama",
|
|
41
|
+
downloadUrl: "https://ollama.com/download/windows",
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
if (platform === "darwin") {
|
|
45
|
+
return {
|
|
46
|
+
platform: "darwin",
|
|
47
|
+
command: "brew install --cask ollama",
|
|
48
|
+
downloadUrl: "https://ollama.com/download/mac",
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
platform,
|
|
53
|
+
command: "curl -fsSL https://ollama.com/install.sh | sh",
|
|
54
|
+
downloadUrl: "https://ollama.com/download/linux",
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function execFileVersion(binPath) {
|
|
59
|
+
return new Promise((resolve) => {
|
|
60
|
+
try {
|
|
61
|
+
execFile(binPath, ["--version"], { timeout: 2500, windowsHide: true }, (err, stdout, stderr) => {
|
|
62
|
+
if (err) {
|
|
63
|
+
resolve(null);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const out = String(stdout || stderr || "").trim();
|
|
67
|
+
resolve({ binPath, version: out.slice(0, 80) });
|
|
68
|
+
});
|
|
69
|
+
} catch {
|
|
70
|
+
resolve(null);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function detectOllamaBinary({ env = process.env, platform = process.platform } = {}) {
|
|
76
|
+
const candidates = ["ollama"];
|
|
77
|
+
if (platform === "win32") {
|
|
78
|
+
const localApp = env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local");
|
|
79
|
+
const winBin = path.join(localApp, "Programs", "Ollama", "ollama.exe");
|
|
80
|
+
if (fs.existsSync(winBin)) candidates.push(winBin);
|
|
81
|
+
} else if (platform === "darwin") {
|
|
82
|
+
for (const p of [
|
|
83
|
+
"/opt/homebrew/bin/ollama",
|
|
84
|
+
"/usr/local/bin/ollama",
|
|
85
|
+
"/Applications/Ollama.app/Contents/Resources/ollama",
|
|
86
|
+
]) {
|
|
87
|
+
if (fs.existsSync(p)) candidates.push(p);
|
|
88
|
+
}
|
|
89
|
+
} else {
|
|
90
|
+
for (const p of ["/usr/local/bin/ollama", "/usr/bin/ollama"]) {
|
|
91
|
+
if (fs.existsSync(p)) candidates.push(p);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
for (const cand of candidates) {
|
|
96
|
+
const found = await execFileVersion(cand);
|
|
97
|
+
if (found) return { installed: true, binPath: found.binPath, version: found.version };
|
|
98
|
+
}
|
|
99
|
+
return { installed: false, binPath: "", version: "" };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function startLocalOllamaService({ baseUrl = DEFAULT_OLLAMA_URL, waitMs = 10_000 } = {}) {
|
|
103
|
+
const cleanUrl = String(baseUrl || DEFAULT_OLLAMA_URL).replace(/\/+$/, "");
|
|
104
|
+
let parsed;
|
|
105
|
+
try {
|
|
106
|
+
parsed = new URL(cleanUrl);
|
|
107
|
+
} catch {
|
|
108
|
+
throw new Error("无效的 Ollama 地址");
|
|
109
|
+
}
|
|
110
|
+
if (!isLoopbackHost(parsed.hostname)) {
|
|
111
|
+
throw new Error("仅支持一键启动本机回环 Ollama 服务");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Already running?
|
|
115
|
+
try {
|
|
116
|
+
const alive = await directHttpJson(`${cleanUrl}/api/tags`, { method: "GET", timeoutMs: 2500 });
|
|
117
|
+
if (alive.ok) return { ok: true, alreadyRunning: true, message: "本地 Ollama 已在运行" };
|
|
118
|
+
} catch {
|
|
119
|
+
// not running yet
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const bin = await detectOllamaBinary();
|
|
123
|
+
if (!bin.installed) {
|
|
124
|
+
return {
|
|
125
|
+
ok: false,
|
|
126
|
+
state: "ollama_not_installed",
|
|
127
|
+
install_guide: getOllamaInstallGuide(),
|
|
128
|
+
message: "未检测到本机 Ollama,请先安装或切换云端 API",
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const child = spawn(bin.binPath, ["serve"], {
|
|
133
|
+
detached: true,
|
|
134
|
+
stdio: "ignore",
|
|
135
|
+
windowsHide: true,
|
|
136
|
+
});
|
|
137
|
+
child.unref();
|
|
138
|
+
|
|
139
|
+
const deadline = Date.now() + Math.max(2000, waitMs);
|
|
140
|
+
while (Date.now() < deadline) {
|
|
141
|
+
await new Promise((r) => setTimeout(r, 450));
|
|
142
|
+
try {
|
|
143
|
+
const alive = await directHttpJson(`${cleanUrl}/api/tags`, { method: "GET", timeoutMs: 2000 });
|
|
144
|
+
if (alive.ok) return { ok: true, started: true, message: "本地 Ollama 已后台启动" };
|
|
145
|
+
} catch {
|
|
146
|
+
// keep polling until ready
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return { ok: false, state: "start_timeout", message: "Ollama 启动超时,请手动确认服务状态" };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function pullOllamaModel({
|
|
153
|
+
baseUrl = DEFAULT_OLLAMA_URL,
|
|
154
|
+
model = RECOMMENDED_LOCAL_PULL_MODELS[0].id,
|
|
155
|
+
onProgress = null,
|
|
156
|
+
signal = null,
|
|
157
|
+
} = {}) {
|
|
158
|
+
const targetModel = String(model || RECOMMENDED_LOCAL_PULL_MODELS[0].id).trim();
|
|
159
|
+
if (!SAFE_OLLAMA_MODEL_RE.test(targetModel)) {
|
|
160
|
+
return Promise.reject(new Error("无效的 Ollama 模型名"));
|
|
161
|
+
}
|
|
162
|
+
const cleanUrl = String(baseUrl || DEFAULT_OLLAMA_URL).replace(/\/+$/, "");
|
|
163
|
+
let parsed;
|
|
164
|
+
try {
|
|
165
|
+
parsed = new URL(`${cleanUrl}/api/pull`);
|
|
166
|
+
} catch {
|
|
167
|
+
return Promise.reject(new Error("无效的 Ollama 地址"));
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return new Promise((resolve, reject) => {
|
|
171
|
+
const isHttps = parsed.protocol === "https:";
|
|
172
|
+
const transport = isHttps ? https : http;
|
|
173
|
+
const payloadBuf = Buffer.from(JSON.stringify({ name: targetModel, stream: true }), "utf8");
|
|
174
|
+
let settled = false;
|
|
175
|
+
const finishOk = (val) => {
|
|
176
|
+
if (settled) return;
|
|
177
|
+
settled = true;
|
|
178
|
+
resolve(val);
|
|
179
|
+
};
|
|
180
|
+
const finishErr = (err) => {
|
|
181
|
+
if (settled) return;
|
|
182
|
+
settled = true;
|
|
183
|
+
reject(err);
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
const req = transport.request(
|
|
187
|
+
{
|
|
188
|
+
protocol: parsed.protocol,
|
|
189
|
+
hostname: parsed.hostname,
|
|
190
|
+
port: parsed.port || (isHttps ? 443 : 80),
|
|
191
|
+
path: `${parsed.pathname}${parsed.search}`,
|
|
192
|
+
method: "POST",
|
|
193
|
+
headers: {
|
|
194
|
+
"content-type": "application/json",
|
|
195
|
+
"content-length": String(payloadBuf.length),
|
|
196
|
+
},
|
|
197
|
+
},
|
|
198
|
+
(res) => {
|
|
199
|
+
if ((res.statusCode || 0) < 200 || (res.statusCode || 0) >= 300) {
|
|
200
|
+
const errChunks = [];
|
|
201
|
+
res.on("data", (c) => errChunks.push(c));
|
|
202
|
+
res.on("end", () => {
|
|
203
|
+
const raw = Buffer.concat(errChunks).toString("utf8").slice(0, 220);
|
|
204
|
+
finishErr(new Error(`Ollama /api/pull HTTP ${res.statusCode}: ${raw}`));
|
|
205
|
+
});
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
let buf = "";
|
|
210
|
+
let lastStatus = "pulling";
|
|
211
|
+
const processLine = (line) => {
|
|
212
|
+
const trimmed = line.trim();
|
|
213
|
+
if (!trimmed) return;
|
|
214
|
+
let obj;
|
|
215
|
+
try {
|
|
216
|
+
obj = JSON.parse(trimmed);
|
|
217
|
+
} catch {
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (obj.error) {
|
|
221
|
+
finishErr(new Error(String(obj.error)));
|
|
222
|
+
req.destroy();
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
const status = String(obj.status || lastStatus);
|
|
226
|
+
lastStatus = status;
|
|
227
|
+
const total = Number(obj.total || 0);
|
|
228
|
+
const completed = Number(obj.completed || 0);
|
|
229
|
+
const percent =
|
|
230
|
+
status === "success"
|
|
231
|
+
? 100
|
|
232
|
+
: total > 0
|
|
233
|
+
? Math.max(0, Math.min(99, Math.round((completed / total) * 100)))
|
|
234
|
+
: null;
|
|
235
|
+
if (typeof onProgress === "function") {
|
|
236
|
+
onProgress({ status, model: targetModel, completed, total, percent });
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
res.on("data", (chunk) => {
|
|
241
|
+
buf += chunk.toString("utf8");
|
|
242
|
+
let idx = buf.indexOf("\n");
|
|
243
|
+
while (idx !== -1) {
|
|
244
|
+
const line = buf.slice(0, idx);
|
|
245
|
+
buf = buf.slice(idx + 1);
|
|
246
|
+
processLine(line);
|
|
247
|
+
idx = buf.indexOf("\n");
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
res.on("end", () => {
|
|
251
|
+
if (buf.trim()) processLine(buf);
|
|
252
|
+
finishOk({ ok: true, model: targetModel, status: lastStatus });
|
|
253
|
+
});
|
|
254
|
+
res.on("error", (err) => finishErr(err));
|
|
255
|
+
}
|
|
256
|
+
);
|
|
257
|
+
|
|
258
|
+
if (signal) {
|
|
259
|
+
if (signal.aborted) {
|
|
260
|
+
req.destroy(new Error("已取消下载"));
|
|
261
|
+
finishErr(new Error("已取消下载"));
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
signal.addEventListener(
|
|
265
|
+
"abort",
|
|
266
|
+
() => {
|
|
267
|
+
req.destroy(new Error("已取消下载"));
|
|
268
|
+
finishErr(new Error("已取消下载"));
|
|
269
|
+
},
|
|
270
|
+
{ once: true }
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
req.on("error", (err) => finishErr(err));
|
|
275
|
+
req.write(payloadBuf);
|
|
276
|
+
req.end();
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export const PREFERRED_LOCAL_MODELS = Object.freeze([
|
|
281
|
+
"imliulian/qwen3.5-4b-memory:v2",
|
|
282
|
+
"imliulian/qwen3.5-4b-memory:v2-q8_0",
|
|
283
|
+
"qwen3.5:4b-memory-v2",
|
|
284
|
+
`hf.co/${HF_REPO_ID}:Q8_0`,
|
|
285
|
+
`hf.co/${HF_REPO_ID}:q8_0`,
|
|
286
|
+
"imliulian/qwen3.5-4b-memory:v2-q4_k_m",
|
|
287
|
+
"qwen3.5:4b-memory-v2-q4",
|
|
288
|
+
`hf.co/${HF_REPO_ID}:Q4_K_M`,
|
|
289
|
+
`hf.co/${HF_REPO_ID}:q4_k_m`,
|
|
290
|
+
]);
|
|
291
|
+
|
|
292
|
+
export function isV2ModelName(name) {
|
|
293
|
+
const low = String(name || "").toLowerCase();
|
|
294
|
+
return low.includes("memory-v2") || low.includes("qwen3.5-4b-memory:v2");
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function isLoopbackHost(hostname) {
|
|
298
|
+
const h = String(hostname || "").toLowerCase().replace(/^\[|\]$/g, "");
|
|
299
|
+
return h === "localhost" || h === "::1" || h.startsWith("127.");
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Direct HTTP JSON request via node:http / node:https (never routes loopback through system proxy).
|
|
304
|
+
*/
|
|
305
|
+
function directHttpJson(urlStr, { method = "GET", headers = {}, body = null, timeoutMs = 15_000 } = {}) {
|
|
306
|
+
return new Promise((resolve, reject) => {
|
|
307
|
+
let parsed;
|
|
308
|
+
try {
|
|
309
|
+
parsed = new URL(urlStr);
|
|
310
|
+
} catch (err) {
|
|
311
|
+
reject(new Error(`Invalid URL: ${urlStr}`));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const isHttps = parsed.protocol === "https:";
|
|
316
|
+
const transport = isHttps ? https : http;
|
|
317
|
+
const payloadBuf = body !== null && body !== undefined ? Buffer.from(JSON.stringify(body), "utf8") : null;
|
|
318
|
+
const reqHeaders = { ...headers };
|
|
319
|
+
if (payloadBuf) {
|
|
320
|
+
reqHeaders["content-type"] = "application/json";
|
|
321
|
+
reqHeaders["content-length"] = String(payloadBuf.length);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const req = transport.request(
|
|
325
|
+
{
|
|
326
|
+
protocol: parsed.protocol,
|
|
327
|
+
hostname: parsed.hostname,
|
|
328
|
+
port: parsed.port || (isHttps ? 443 : 80),
|
|
329
|
+
path: `${parsed.pathname}${parsed.search}`,
|
|
330
|
+
method,
|
|
331
|
+
headers: reqHeaders,
|
|
332
|
+
timeout: timeoutMs,
|
|
333
|
+
},
|
|
334
|
+
(res) => {
|
|
335
|
+
const chunks = [];
|
|
336
|
+
res.on("data", (c) => chunks.push(c));
|
|
337
|
+
res.on("end", () => {
|
|
338
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
339
|
+
let json = null;
|
|
340
|
+
try {
|
|
341
|
+
json = raw ? JSON.parse(raw) : null;
|
|
342
|
+
} catch {
|
|
343
|
+
json = null;
|
|
344
|
+
}
|
|
345
|
+
resolve({
|
|
346
|
+
ok: res.statusCode >= 200 && res.statusCode < 300,
|
|
347
|
+
status: res.statusCode || 0,
|
|
348
|
+
json,
|
|
349
|
+
text: raw,
|
|
350
|
+
});
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
);
|
|
354
|
+
|
|
355
|
+
req.on("timeout", () => {
|
|
356
|
+
req.destroy(new Error(`Request timeout after ${timeoutMs}ms`));
|
|
357
|
+
});
|
|
358
|
+
req.on("error", (err) => reject(err));
|
|
359
|
+
|
|
360
|
+
if (payloadBuf) req.write(payloadBuf);
|
|
361
|
+
req.end();
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
async function httpJson(urlStr, { method = "GET", headers = {}, body = null, timeoutMs = 30_000 } = {}) {
|
|
366
|
+
const parsed = new URL(urlStr);
|
|
367
|
+
// Always use direct node:http/https for loopback to avoid Windows/macOS HTTP_PROXY interception
|
|
368
|
+
if (isLoopbackHost(parsed.hostname)) {
|
|
369
|
+
return directHttpJson(urlStr, { method, headers, body, timeoutMs });
|
|
370
|
+
}
|
|
371
|
+
const init = {
|
|
372
|
+
method,
|
|
373
|
+
headers: {
|
|
374
|
+
...(body !== null && body !== undefined ? { "content-type": "application/json" } : {}),
|
|
375
|
+
...headers,
|
|
376
|
+
},
|
|
377
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
378
|
+
};
|
|
379
|
+
if (body !== null && body !== undefined) {
|
|
380
|
+
init.body = JSON.stringify(body);
|
|
381
|
+
}
|
|
382
|
+
const res = await fetch(urlStr, init);
|
|
383
|
+
const raw = await res.text();
|
|
384
|
+
let json = null;
|
|
385
|
+
try {
|
|
386
|
+
json = raw ? JSON.parse(raw) : null;
|
|
387
|
+
} catch {
|
|
388
|
+
json = null;
|
|
389
|
+
}
|
|
390
|
+
return { ok: res.ok, status: res.status, json, text: raw };
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
export class OllamaAdapter {
|
|
394
|
+
constructor({ baseUrl = DEFAULT_OLLAMA_URL, model = "", numCtx = DEFAULT_NUM_CTX, timeoutMs = 90_000 } = {}) {
|
|
395
|
+
this.baseUrl = String(baseUrl || DEFAULT_OLLAMA_URL).replace(/\/+$/, "");
|
|
396
|
+
this.explicitModel = String(model || "").trim();
|
|
397
|
+
this.resolvedModel = this.explicitModel || "";
|
|
398
|
+
this.numCtx = Number(numCtx) || DEFAULT_NUM_CTX;
|
|
399
|
+
this.timeoutMs = Number(timeoutMs) || 90_000;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
async listModels() {
|
|
403
|
+
const res = await httpJson(`${this.baseUrl}/api/tags`, {
|
|
404
|
+
method: "GET",
|
|
405
|
+
timeoutMs: Math.min(this.timeoutMs, 8_000),
|
|
406
|
+
});
|
|
407
|
+
if (!res.ok) throw new Error(`Ollama /api/tags HTTP ${res.status}: ${res.text.slice(0, 160)}`);
|
|
408
|
+
const models = Array.isArray(res.json?.models) ? res.json.models : [];
|
|
409
|
+
return models.map((m) => String(m?.name || "")).filter(Boolean);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
async listRunningModels() {
|
|
413
|
+
try {
|
|
414
|
+
const res = await httpJson(`${this.baseUrl}/api/ps`, {
|
|
415
|
+
method: "GET",
|
|
416
|
+
timeoutMs: Math.min(this.timeoutMs, 5_000),
|
|
417
|
+
});
|
|
418
|
+
if (!res.ok) return [];
|
|
419
|
+
const models = Array.isArray(res.json?.models) ? res.json.models : [];
|
|
420
|
+
return models.map((m) => String(m?.name || "")).filter(Boolean);
|
|
421
|
+
} catch {
|
|
422
|
+
return [];
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async resolveModel() {
|
|
427
|
+
if (this.resolvedModel) return this.resolvedModel;
|
|
428
|
+
|
|
429
|
+
const running = await this.listRunningModels();
|
|
430
|
+
for (const r of running) {
|
|
431
|
+
if (isV2ModelName(r)) {
|
|
432
|
+
this.resolvedModel = r;
|
|
433
|
+
return r;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
const available = await this.listModels();
|
|
438
|
+
const availSet = new Set(available);
|
|
439
|
+
for (const cand of PREFERRED_LOCAL_MODELS) {
|
|
440
|
+
if (availSet.has(cand)) {
|
|
441
|
+
this.resolvedModel = cand;
|
|
442
|
+
return cand;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
for (const name of available) {
|
|
446
|
+
if (isV2ModelName(name)) {
|
|
447
|
+
this.resolvedModel = name;
|
|
448
|
+
return name;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
throw new Error(
|
|
453
|
+
"本地 Ollama 未检测到 Qwen3.5-4B-Memory-V2 模型。请运行 `ollama pull hf.co/IMLIULIAN/qwen3.5-4b-memory-v2:Q8_0`,或在设置中指定已有模型 / 切换为 API 模式。"
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async chatJson(systemPrompt, userPayload, { numPredict = 1024, retries = 1 } = {}) {
|
|
458
|
+
const model = await this.resolveModel();
|
|
459
|
+
const payload = {
|
|
460
|
+
model,
|
|
461
|
+
messages: [
|
|
462
|
+
{ role: "system", content: systemPrompt },
|
|
463
|
+
{ role: "user", content: JSON.stringify(userPayload) },
|
|
464
|
+
],
|
|
465
|
+
stream: false,
|
|
466
|
+
think: false,
|
|
467
|
+
options: {
|
|
468
|
+
num_ctx: this.numCtx,
|
|
469
|
+
num_predict: Number(numPredict) || 1024,
|
|
470
|
+
temperature: 0.0,
|
|
471
|
+
top_k: 20,
|
|
472
|
+
top_p: 0.95,
|
|
473
|
+
presence_penalty: 0.0,
|
|
474
|
+
repeat_penalty: 1.08,
|
|
475
|
+
},
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
let lastErr = null;
|
|
479
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
480
|
+
const t0 = Date.now();
|
|
481
|
+
try {
|
|
482
|
+
const res = await httpJson(`${this.baseUrl}/api/chat`, {
|
|
483
|
+
method: "POST",
|
|
484
|
+
body: payload,
|
|
485
|
+
timeoutMs: this.timeoutMs,
|
|
486
|
+
});
|
|
487
|
+
if (!res.ok) {
|
|
488
|
+
throw new Error(`Ollama /api/chat HTTP ${res.status}: ${res.text.slice(0, 200)}`);
|
|
489
|
+
}
|
|
490
|
+
const content = String(res.json?.message?.content || "").trim();
|
|
491
|
+
return {
|
|
492
|
+
content,
|
|
493
|
+
meta: {
|
|
494
|
+
provider: "ollama",
|
|
495
|
+
model,
|
|
496
|
+
elapsed_ms: Date.now() - t0,
|
|
497
|
+
done_reason: res.json?.done_reason ?? null,
|
|
498
|
+
},
|
|
499
|
+
};
|
|
500
|
+
} catch (err) {
|
|
501
|
+
lastErr = err;
|
|
502
|
+
if (attempt < retries) {
|
|
503
|
+
await new Promise((r) => setTimeout(r, 800));
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
throw new Error(`Ollama 调用失败 (${model}): ${lastErr?.message || lastErr}`);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
async probe() {
|
|
511
|
+
const t0 = Date.now();
|
|
512
|
+
try {
|
|
513
|
+
const [available, running] = await Promise.all([this.listModels(), this.listRunningModels()]);
|
|
514
|
+
const elapsedMs = Date.now() - t0;
|
|
515
|
+
const target = this.explicitModel || "";
|
|
516
|
+
const runningMatch = target
|
|
517
|
+
? running.find((m) => m === target)
|
|
518
|
+
: running.find((m) => isV2ModelName(m));
|
|
519
|
+
if (runningMatch) {
|
|
520
|
+
return {
|
|
521
|
+
ok: true,
|
|
522
|
+
provider: "ollama",
|
|
523
|
+
state: "resident",
|
|
524
|
+
model: runningMatch,
|
|
525
|
+
elapsed_ms: elapsedMs,
|
|
526
|
+
available_models: available.slice(0, 40),
|
|
527
|
+
running_models: running,
|
|
528
|
+
message: `本地常驻:${runningMatch}`,
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
const installedMatch = target
|
|
532
|
+
? available.find((m) => m === target)
|
|
533
|
+
: PREFERRED_LOCAL_MODELS.find((cand) => available.includes(cand)) ||
|
|
534
|
+
available.find((m) => isV2ModelName(m));
|
|
535
|
+
if (installedMatch) {
|
|
536
|
+
return {
|
|
537
|
+
ok: true,
|
|
538
|
+
provider: "ollama",
|
|
539
|
+
state: "ready",
|
|
540
|
+
model: installedMatch,
|
|
541
|
+
elapsed_ms: elapsedMs,
|
|
542
|
+
available_models: available.slice(0, 40),
|
|
543
|
+
running_models: running,
|
|
544
|
+
message: `本地已就绪:${installedMatch}`,
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
return {
|
|
548
|
+
ok: false,
|
|
549
|
+
provider: "ollama",
|
|
550
|
+
state: "missing_model",
|
|
551
|
+
model: target || "qwen3.5:4b-memory-v2",
|
|
552
|
+
elapsed_ms: elapsedMs,
|
|
553
|
+
available_models: available.slice(0, 40),
|
|
554
|
+
running_models: running,
|
|
555
|
+
ollama_installed: true,
|
|
556
|
+
can_pull: true,
|
|
557
|
+
recommended_models: RECOMMENDED_LOCAL_PULL_MODELS,
|
|
558
|
+
message: target
|
|
559
|
+
? `Ollama 已连接,未找到模型 ${target},可一键拉取`
|
|
560
|
+
: "Ollama 已就绪,尚未下载零忆 V2 模型,可一键拉取",
|
|
561
|
+
};
|
|
562
|
+
} catch (err) {
|
|
563
|
+
let parsedHost = "";
|
|
564
|
+
try {
|
|
565
|
+
parsedHost = new URL(this.baseUrl).hostname;
|
|
566
|
+
} catch {
|
|
567
|
+
// ignore
|
|
568
|
+
}
|
|
569
|
+
if (isLoopbackHost(parsedHost)) {
|
|
570
|
+
const bin = await detectOllamaBinary();
|
|
571
|
+
if (bin.installed) {
|
|
572
|
+
return {
|
|
573
|
+
ok: false,
|
|
574
|
+
provider: "ollama",
|
|
575
|
+
state: "ollama_stopped",
|
|
576
|
+
model: this.explicitModel || "",
|
|
577
|
+
elapsed_ms: Date.now() - t0,
|
|
578
|
+
available_models: [],
|
|
579
|
+
running_models: [],
|
|
580
|
+
ollama_installed: true,
|
|
581
|
+
ollama_version: bin.version,
|
|
582
|
+
can_start_ollama: true,
|
|
583
|
+
recommended_models: RECOMMENDED_LOCAL_PULL_MODELS,
|
|
584
|
+
message: "已安装 Ollama(未启动),可一键后台启动",
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
return {
|
|
588
|
+
ok: false,
|
|
589
|
+
provider: "ollama",
|
|
590
|
+
state: "ollama_not_installed",
|
|
591
|
+
model: this.explicitModel || "",
|
|
592
|
+
elapsed_ms: Date.now() - t0,
|
|
593
|
+
available_models: [],
|
|
594
|
+
running_models: [],
|
|
595
|
+
ollama_installed: false,
|
|
596
|
+
can_start_ollama: false,
|
|
597
|
+
install_guide: getOllamaInstallGuide(),
|
|
598
|
+
recommended_models: RECOMMENDED_LOCAL_PULL_MODELS,
|
|
599
|
+
message: "未检测到本机 Ollama,可安装后一键拉取模型或改用云端 API",
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
return {
|
|
603
|
+
ok: false,
|
|
604
|
+
provider: "ollama",
|
|
605
|
+
state: "offline",
|
|
606
|
+
model: this.explicitModel || "",
|
|
607
|
+
elapsed_ms: Date.now() - t0,
|
|
608
|
+
available_models: [],
|
|
609
|
+
running_models: [],
|
|
610
|
+
message: `无法连接 Ollama (${this.baseUrl}): ${err?.message || err}`,
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
export class OpenAICompatibleAdapter {
|
|
617
|
+
constructor({
|
|
618
|
+
baseUrl = DEFAULT_API_BASE_URL,
|
|
619
|
+
apiKey = "",
|
|
620
|
+
model = DEFAULT_API_MODEL,
|
|
621
|
+
timeoutMs = 90_000,
|
|
622
|
+
} = {}) {
|
|
623
|
+
this.baseUrl = String(baseUrl || DEFAULT_API_BASE_URL).replace(/\/+$/, "");
|
|
624
|
+
this.apiKey = String(apiKey || "").trim();
|
|
625
|
+
this.model = String(model || DEFAULT_API_MODEL).trim() || DEFAULT_API_MODEL;
|
|
626
|
+
this.timeoutMs = Number(timeoutMs) || 90_000;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
_authHeaders() {
|
|
630
|
+
const headers = {};
|
|
631
|
+
if (this.apiKey) headers.authorization = `Bearer ${this.apiKey}`;
|
|
632
|
+
return headers;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
_completionsUrl() {
|
|
636
|
+
if (this.baseUrl.endsWith("/chat/completions")) return this.baseUrl;
|
|
637
|
+
return `${this.baseUrl}/chat/completions`;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
_modelsUrl() {
|
|
641
|
+
if (this.baseUrl.endsWith("/chat/completions")) {
|
|
642
|
+
return this.baseUrl.replace(/\/chat\/completions$/, "/models");
|
|
643
|
+
}
|
|
644
|
+
return `${this.baseUrl}/models`;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
async chatJson(systemPrompt, userPayload, { numPredict = 1024, retries = 1 } = {}) {
|
|
648
|
+
const url = this._completionsUrl();
|
|
649
|
+
const isLocal = isLoopbackHost(new URL(url).hostname);
|
|
650
|
+
if (!this.apiKey && !isLocal) {
|
|
651
|
+
throw new Error("未配置 API Key,请在 ZeroMem 设置中填写 API Key(或设置环境变量 ZEROMEM_API_KEY)。");
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
const buildBody = (withResponseFormat) => {
|
|
655
|
+
const body = {
|
|
656
|
+
model: this.model,
|
|
657
|
+
messages: [
|
|
658
|
+
{ role: "system", content: systemPrompt },
|
|
659
|
+
{ role: "user", content: JSON.stringify(userPayload) },
|
|
660
|
+
],
|
|
661
|
+
temperature: 0.0,
|
|
662
|
+
max_tokens: Number(numPredict) || 1024,
|
|
663
|
+
stream: false,
|
|
664
|
+
};
|
|
665
|
+
if (withResponseFormat) {
|
|
666
|
+
body.response_format = { type: "json_object" };
|
|
667
|
+
}
|
|
668
|
+
return body;
|
|
669
|
+
};
|
|
670
|
+
|
|
671
|
+
let useJsonFormat = true;
|
|
672
|
+
let lastErr = null;
|
|
673
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
674
|
+
const t0 = Date.now();
|
|
675
|
+
try {
|
|
676
|
+
const res = await httpJson(url, {
|
|
677
|
+
method: "POST",
|
|
678
|
+
headers: this._authHeaders(),
|
|
679
|
+
body: buildBody(useJsonFormat),
|
|
680
|
+
timeoutMs: this.timeoutMs,
|
|
681
|
+
});
|
|
682
|
+
if (!res.ok) {
|
|
683
|
+
// Some OpenAI-compatible gateways reject response_format; retry once without it
|
|
684
|
+
if (useJsonFormat && res.status === 400 && /response_format/i.test(res.text)) {
|
|
685
|
+
useJsonFormat = false;
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
const detail = res.json?.error?.message || res.text.slice(0, 200);
|
|
689
|
+
throw new Error(`API HTTP ${res.status}: ${detail}`);
|
|
690
|
+
}
|
|
691
|
+
const msg = res.json?.choices?.[0]?.message;
|
|
692
|
+
const content =
|
|
693
|
+
typeof msg?.content === "string"
|
|
694
|
+
? msg.content.trim()
|
|
695
|
+
: Array.isArray(msg?.content)
|
|
696
|
+
? msg.content.map((b) => b?.text || "").join("").trim()
|
|
697
|
+
: "";
|
|
698
|
+
return {
|
|
699
|
+
content,
|
|
700
|
+
meta: {
|
|
701
|
+
provider: "openai-compatible",
|
|
702
|
+
model: String(res.json?.model || this.model),
|
|
703
|
+
elapsed_ms: Date.now() - t0,
|
|
704
|
+
finish_reason: res.json?.choices?.[0]?.finish_reason ?? null,
|
|
705
|
+
},
|
|
706
|
+
};
|
|
707
|
+
} catch (err) {
|
|
708
|
+
lastErr = err;
|
|
709
|
+
if (attempt < retries) {
|
|
710
|
+
await new Promise((r) => setTimeout(r, 800));
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
throw new Error(`API 调用失败 (${this.model}): ${lastErr?.message || lastErr}`);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
async probe({ liveChat = false } = {}) {
|
|
718
|
+
const t0 = Date.now();
|
|
719
|
+
let parsedUrl;
|
|
720
|
+
try {
|
|
721
|
+
parsedUrl = new URL(this._completionsUrl());
|
|
722
|
+
} catch {
|
|
723
|
+
return {
|
|
724
|
+
ok: false,
|
|
725
|
+
provider: "openai-compatible",
|
|
726
|
+
state: "invalid_config",
|
|
727
|
+
model: this.model,
|
|
728
|
+
elapsed_ms: 0,
|
|
729
|
+
message: `无效的 API Base URL: ${this.baseUrl}`,
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
const isLocal = isLoopbackHost(parsedUrl.hostname);
|
|
734
|
+
if (!this.apiKey && !isLocal) {
|
|
735
|
+
return {
|
|
736
|
+
ok: false,
|
|
737
|
+
provider: "openai-compatible",
|
|
738
|
+
state: "missing_key",
|
|
739
|
+
model: this.model,
|
|
740
|
+
elapsed_ms: 0,
|
|
741
|
+
message: "尚未配置 API Key(可在设置页填入,密钥仅存本地)",
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
if (!liveChat) {
|
|
746
|
+
try {
|
|
747
|
+
const res = await httpJson(this._modelsUrl(), {
|
|
748
|
+
method: "GET",
|
|
749
|
+
headers: this._authHeaders(),
|
|
750
|
+
timeoutMs: Math.min(this.timeoutMs, 10_000),
|
|
751
|
+
});
|
|
752
|
+
if (res.ok) {
|
|
753
|
+
const list = Array.isArray(res.json?.data)
|
|
754
|
+
? res.json.data.map((m) => String(m?.id || "")).filter(Boolean).slice(0, 40)
|
|
755
|
+
: [];
|
|
756
|
+
return {
|
|
757
|
+
ok: true,
|
|
758
|
+
provider: "openai-compatible",
|
|
759
|
+
state: "ready",
|
|
760
|
+
model: this.model,
|
|
761
|
+
elapsed_ms: Date.now() - t0,
|
|
762
|
+
available_models: list,
|
|
763
|
+
message: `API 已连通(${this.model})`,
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
if (res.status === 401 || res.status === 403) {
|
|
767
|
+
return {
|
|
768
|
+
ok: false,
|
|
769
|
+
provider: "openai-compatible",
|
|
770
|
+
state: "auth_error",
|
|
771
|
+
model: this.model,
|
|
772
|
+
elapsed_ms: Date.now() - t0,
|
|
773
|
+
message: `API 鉴权失败 (HTTP ${res.status})`,
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
} catch {
|
|
777
|
+
// Fall through to minimal chat probe if /models isn't supported
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
try {
|
|
782
|
+
const res = await this.chatJson(
|
|
783
|
+
'Return strictly valid JSON: {"ok":true}',
|
|
784
|
+
{ ping: 1 },
|
|
785
|
+
{ numPredict: 32, retries: 0 }
|
|
786
|
+
);
|
|
787
|
+
return {
|
|
788
|
+
ok: true,
|
|
789
|
+
provider: "openai-compatible",
|
|
790
|
+
state: "ready",
|
|
791
|
+
model: res.meta.model || this.model,
|
|
792
|
+
elapsed_ms: Date.now() - t0,
|
|
793
|
+
message: `API 实测连通(${res.meta.model || this.model},${Date.now() - t0}ms)`,
|
|
794
|
+
};
|
|
795
|
+
} catch (err) {
|
|
796
|
+
return {
|
|
797
|
+
ok: false,
|
|
798
|
+
provider: "openai-compatible",
|
|
799
|
+
state: "offline",
|
|
800
|
+
model: this.model,
|
|
801
|
+
elapsed_ms: Date.now() - t0,
|
|
802
|
+
message: String(err?.message || err),
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
export function createLlmAdapter(cfg, { apiKey = "" } = {}) {
|
|
809
|
+
if (cfg.provider === "openai-compatible") {
|
|
810
|
+
return new OpenAICompatibleAdapter({
|
|
811
|
+
baseUrl: cfg.apiBaseUrl,
|
|
812
|
+
apiKey: apiKey || cfg.apiKey,
|
|
813
|
+
model: cfg.apiModel,
|
|
814
|
+
timeoutMs: cfg.timeoutMs,
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
return new OllamaAdapter({
|
|
818
|
+
baseUrl: cfg.ollamaUrl,
|
|
819
|
+
model: cfg.ollamaModel,
|
|
820
|
+
numCtx: cfg.numCtx,
|
|
821
|
+
timeoutMs: cfg.timeoutMs,
|
|
822
|
+
});
|
|
823
|
+
}
|