@restregular/dsh-memory 0.3.1 → 0.4.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.
@@ -1,1002 +1,1144 @@
1
- /**
2
- * dsh-memory-local — 向量后端「下载并配置」安装器(零运行时依赖)。
3
- *
4
- * 背景:本地语义检索需要一个 OpenAI 兼容的 /v1/embeddings 服务,而默认没人替
5
- * 用户准备好后端——得自己去下 llama.cpp 的 llama-server 和 bge-m3 的 GGUF 模
6
- * 型,再手填两个绝对路径。本模块把那套手工动作收成一个按钮:
7
- * 查 GitHub 最新构建 → 下运行时压缩包 → 解压 → 下模型 → 校验布局
8
- * 落盘位置与「手工装好的既有布局」逐字节一致,装完由 EmbedServerManager 托管
9
- * 启动(见 embed-server.ts)。
10
- *
11
- * 为什么零依赖(任何 npm 包都不用):
12
- * - 这个包要被别人 `pnpm add dsh-memory-local` 直接装上就用,每多一个依赖就多
13
- * 一份升级、审计、甚至原生编译的负担;解压一个发行包不值得把包袱转嫁给用户;
14
- * - 真正需要的能力 node 内置已经齐了:zip 要的只是「中央目录 + inflateRaw」,
15
- * tar.gz 要的只是「gunzip + 512 字节头」,zlib 直接给;流式写盘用 fs 流;
16
- * HTTPS/TLS 交给全局 fetch(不碰 node:https,证书与代理策略跟随宿主)。
17
- *
18
- * 硬约束(都对应一条真实教训):
19
- * - 默认绝不下载:只有显式 start() 才碰网络,构造/导入阶段零 I/O;
20
- * - 幂等:已在跑、或已经装好,start() 什么都不做;
21
- * - 绝不抛异常:start() 是 fire-and-forget,任何失败都变成 phase:'error' +
22
- * 可读 message(面板直接显示这两个字段);
23
- * - 半成品绝不落地:下载先写 <目标>.part,收流完整后 rename——否则一次断网
24
- * 留下的半个 gguf 会被 detectInstalled 当成「已安装」,然后 llama-server
25
- * 报一句莫名其妙的加载失败;
26
- * - 可取消:cancel() 中止在途请求、删掉 .part、phase 回到 idle;
27
- * - 解压必须防路径穿越:压缩包是远端内容,`../` 或绝对路径条目一律拒绝;
28
- * - 每条下载都留了备用通道:运行时是「下载直链 → GitHub API 资产端点」,模型
29
- * 是多个源,全部按序回退(详见 runtimeDownloadSources / MODEL_SOURCES)。
30
- * 这不是锦上添花——直链会 302 到 release-assets.githubusercontent.com,该主机
31
- * 在部分网络会被重置连接,而 api.github.com 通畅,没有备用通道就等于装不上。
32
- *
33
- * 布局(installPaths 是唯一事实来源,检测与安装都走它):
34
- * <root>/llamacpp/llama-server[.exe] ← 运行时(同目录还有几十个 dll/so)
35
- * <root>/models/bge-m3-Q4_K_M.gguf ← 模型
36
- * <root>/llama-server.log ← 托管启动时追加的日志
37
- */
38
- import { chmodSync, createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
39
-
40
- import { basename, dirname, join, resolve, sep } from 'node:path'
41
- import { gunzipSync, inflateRawSync } from 'node:zlib'
42
-
43
- /** 模型文件名:下载目标与「是否已安装」的判据都用它,不要在两处各写一遍。 */
44
- export const MODEL_FILE_NAME = 'bge-m3-Q4_K_M.gguf'
45
-
46
- /** 运行时的 zip/pkg 文件名(Windows 是 zip,Linux/macOS 是 tar.gz)。 */
47
- export const RUNTIME_DIR_NAME = 'llamacpp'
48
- export const MODELS_DIR_NAME = 'models'
49
- export const LOG_FILE_NAME = 'llama-server.log'
50
-
51
- /** GitHub API:查询 llama.cpp 发行版列表(不硬编码构建号)。 */
52
- const RELEASES_API = 'https://api.github.com/repos/ggml-org/llama.cpp/releases?per_page=20'
53
- /** GitHub 要求带 UA;不带会被 403。 */
54
- const USER_AGENT = 'dsh-memory-local-installer'
55
-
56
- /**
57
- * 模型下载源,按顺序回退(同一份 Q4_K_M,仓库都是 gpustack/bge-m3-GGUF)。
58
- *
59
- * 2026-10-10 逐个核实过(只发 HEAD / Range,没有真的拉 400MB):
60
- * - hf-mirror.com → 302 → HF CDN,content-length 437778496 ✅
61
- * - modelscope.cn → 302 → cdn-lfs-cn-1.modelscope.cn,206 + `bytes 0-0/437778496` ✅
62
- * - huggingface.co → 本机直连超时(curl 28,15s 无响应)❌ 但海外用户应该优先官方源
63
- * 三个源的大小都等于本机 `D:\.deepseek\memory-stack\models\bge-m3-Q4_K_M.gguf`
64
- * 的 437778496 字节,即同一份量化。
65
- *
66
- * 顺序取「国内可达的两个在前、官方源在最后」:本机/国内是第一现场,官方源排在
67
- * 列表里仍然会被尝试,海外用户只是多花一次失败请求的代价。
68
- */
69
- export const MODEL_SOURCES = [
70
- 'https://hf-mirror.com/gpustack/bge-m3-GGUF/resolve/main/bge-m3-Q4_K_M.gguf',
71
- 'https://modelscope.cn/models/gpustack/bge-m3-GGUF/resolve/master/bge-m3-Q4_K_M.gguf',
72
- 'https://huggingface.co/gpustack/bge-m3-GGUF/resolve/main/bge-m3-Q4_K_M.gguf',
73
- ]
74
- /**
75
- * 期望字节数(437778496 = 417.5 MiB)。**只用于消息里的「约 X MB」,不做硬校验**:
76
- * 上游随时可能重新量化/更新,把大小当断言会让一次正常的上游更新变成安装失败。
77
- * 真实进度一律以响应的 content-length 为准。
78
- */
79
- export const MODEL_SIZE_BYTES = 437_778_496
80
-
81
- /** 安装布局。与手工装好的既有布局一致(embed-server 直接吃这几个字段)。 */
82
-
83
-        
84
-
85
-      
86
-
87
-       
88
-
89
-                     
90
-
91
-
92
-
93
-
94
-
95
-
96
-
97
- /** 安装状态机。idle/error 都可能再次 start()。 */
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
-
106
-
107
- /**
108
- * 面板直接渲染的快照。receivedBytes/totalBytes 是**当前这一个文件**的进度
109
- * (totalBytes 取 content-length,拿不到就是 null),所以百分比 =
110
- * receivedBytes/totalBytes 才有意义。
111
- */
112
-
113
-
114
-
115
-
116
-
117
-
118
-
119
-
120
-
121
-
122
-               
123
-
124
-                      
125
-
126
-                              
127
-
128
-                                
129
-
130
-                           
131
-
132
-                                
133
-
134
-         
135
-
136
-
137
-
138
- /** zip 中央目录里一条记录(只保留解压需要的字段)。 */
139
-
140
-
141
-
142
-
143
-
144
-        
145
-
146
-
147
-
148
- /** tar 里一条记录。 */
149
-
150
-
151
-
152
-                     
153
-
154
-
155
-
156
-
157
-
158
- export function installPaths(root ) {
159
- const dir = join(root, RUNTIME_DIR_NAME)
160
- // 宿主平台决定可执行文件名:Windows 上 llama.cpp 的启动器带 .exe。
161
- const exeName = process.platform === 'win32' ? 'llama-server.exe' : 'llama-server'
162
- return {
163
- root,
164
- dir,
165
- exe: join(dir, exeName),
166
- cwd: dir,
167
- model: join(root, MODELS_DIR_NAME, MODEL_FILE_NAME),
168
- logFile: join(root, LOG_FILE_NAME),
169
- }
170
- }
171
-
172
- /**
173
- * 已安装则返回布局,否则 null(判据:exe 与 model 两个文件都在)。
174
- *
175
- * 只看「存在」就够:安装器永远先写 .part 再 rename,所以这两个路径上不可能
176
- * 出现半成品;反过来,用户手工放好的文件也会被如实采纳(这正是
177
- * `<root>/llamacpp` + `<root>/models` 这套既有布局的意义)。
178
- * 绝不抛异常:它在 resolveConfig 里被同步调用。
179
- */
180
- export function detectInstalled(root ) {
181
- try {
182
- const paths = installPaths(root)
183
- if (!isFile(paths.exe) || !isFile(paths.model)) return null
184
- return paths
185
- } catch {
186
- return null
187
- }
188
- }
189
-
190
- /**
191
- * 平台 → 发行资产名正则。按平台挑包,绝不硬编码构建号:
192
- * win32-x64 → llama-b<号>-bin-win-cpu-x64.zip
193
- * win32-arm64 → llama-b<号>-bin-win-cpu-arm64.zip
194
- * linux-x64 → llama-b<号>-bin-ubuntu-x64.tar.gz(历史版本曾是 .zip,故两者都收)
195
- * linux-arm64 → llama-b<号>-bin-ubuntu-arm64.tar.gz
196
- * darwin-arm64 → llama-b<号>-bin-macos-arm64.tar.gz
197
- * darwin-x64 → llama-b<号>-bin-macos-x64.tar.gz
198
- *
199
- * 正则收尾用 `$` 锚定:同一批资产里还有 cuda/vulkan/sycl/openvino/rocm 变体,
200
- * 不锚定就会把 `-ubuntu-vulkan-x64.tar.gz` 之类当成 CPU 包下下来(几百 MB 白下)。
201
- */
202
- export function runtimeAssetPattern(platform , arch ) {
203
- const key = `${platform}-${arch}`
204
- switch (key) {
205
- case 'win32-x64': return /-bin-win-cpu-x64\.zip$/
206
- case 'win32-arm64': return /-bin-win-cpu-arm64\.zip$/
207
- case 'linux-x64': return /-bin-ubuntu-x64\.(?:zip|tar\.gz)$/
208
- case 'linux-arm64': return /-bin-ubuntu-arm64\.(?:zip|tar\.gz)$/
209
- case 'darwin-arm64': return /-bin-macos-arm64\.(?:zip|tar\.gz)$/
210
- case 'darwin-x64': return /-bin-macos-x64\.(?:zip|tar\.gz)$/
211
- default:
212
- throw new Error(
213
- `资产匹配失败:${key}(暂不支持该平台;已支持 win32-x64 / win32-arm64 / linux-x64 / linux-arm64 / darwin-arm64 / darwin-x64)`,
214
- )
215
- }
216
- }
217
-
218
- /** 一个发行资产的两条下载通道(见 runtimeDownloadSources)。 */
219
-
220
-
221
-                   
222
-
223
-            
224
-
225
-
226
-
227
- /** 在一批 GitHub 资产里按平台挑第一个匹配的包。 */
228
- export function pickRuntimeAsset(
229
- assets ,
230
- platform ,
231
- arch ,
232
- ) {
233
- return matchAsset(assets, runtimeAssetPattern(platform, arch))
234
- }
235
-
236
- function matchAsset(assets , pattern ) {
237
- for (const asset of assets) {
238
- if (typeof asset !== 'object' || asset === null) continue
239
- const name = (asset ).name
240
- const url = (asset ).browser_download_url
241
- const apiUrl = (asset ).url
242
- if (typeof name !== 'string' || typeof url !== 'string') continue
243
- if (pattern.test(name)) return { name, url, apiUrl: typeof apiUrl === 'string' ? apiUrl : '' }
244
- }
245
- return null
246
- }
247
-
248
- /** 一个下载候选通道。 */
249
-
250
-
251
-          
252
-
253
-                         
254
-
255
-
256
-
257
- /**
258
- * 运行时的两条通道,按序回退:
259
- * 1. `browser_download_url`(下载直链)——标准通道,大多数网络下最快;
260
- * 2. `asset.url`(GitHub API 资产端点,Accept: application/octet-stream)——
261
- * 直链会 302 到 release-assets/objects.githubusercontent.com,这个主机在
262
- * 部分网络(含本机)会被重置连接,而 api.github.com 是通的,所以它是本机
263
- * 能一键装上的关键备用通道。
264
- * 实测(2026-10-10,node 全局 fetch,只读响应头):直链 fetch failed;
265
- * API 端点 HTTP 200 + content-length 19518702,1.2s。
266
- */
267
- export function runtimeDownloadSources(asset ) {
268
- const sources = [
269
- { url: asset.url, accept: '*/*', label: '发行包直链' },
270
- ]
271
- const withAccept = { url: asset.apiUrl, accept: 'application/octet-stream', label: 'GitHub API 资产端点' }
272
- if (asset.apiUrl !== '' && asset.apiUrl !== asset.url) sources.push(withAccept)
273
- return sources.filter((source) => source.url !== '')
274
- }
275
-
276
- /**
277
- * 按魔数解压 zip / tar.gz 到 destDir,返回写入的文件数。
278
- * 看魔数而不是扩展名:远端文件名不可靠,内容头是可靠的。
279
- */
280
- export function extractArchive(archive , destDir ) {
281
- if (archive.length >= 4 && archive[0] === 0x50 && archive[1] === 0x4b) return extractZip(archive, destDir)
282
- if (archive.length >= 2 && archive[0] === 0x1f && archive[1] === 0x8b) return extractTarGz(archive, destDir)
283
- throw new Error('不支持的压缩格式:既不是 zip(PK)也不是 gzip(1f 8b)')
284
- }
285
-
286
- // ───────────────────────────── zip ─────────────────────────────
287
-
288
- /** 从尾部往前找 End of Central Directory(最多回扫 65557 字节 = 22 + 注释上限)。 */
289
- function findEocd(buf ) {
290
- const floor = Math.max(0, buf.length - 65_557)
291
- for (let i = buf.length - 22; i >= floor; i--) {
292
- if (buf.readUInt32LE(i) === 0x06054b50) return i
293
- }
294
- throw new Error('不是有效的 ZIP 文件:找不到中央目录结尾记录')
295
- }
296
-
297
- /** 读中央目录(解压前先拿到全部条目的名字/大小/压缩方式/偏移)。 */
298
- function readZipEntries(buf ) {
299
- const eocd = findEocd(buf)
300
- const count = buf.readUInt16LE(eocd + 10)
301
- const cdOffset = buf.readUInt32LE(eocd + 16)
302
- if (count === 0xffff || cdOffset === 0xffffffff) {
303
- // 这些哨兵值代表真实信息在 ZIP64 记录里——llama.cpp 的包远没到 4GB,不实现。
304
- throw new Error('暂不支持 ZIP64 归档')
305
- }
306
- const entries = []
307
- let p = cdOffset
308
- for (let i = 0; i < count; i++) {
309
- if (p + 46 > buf.length || buf.readUInt32LE(p) !== 0x02014b50) {
310
- throw new Error('ZIP 中央目录已损坏(条目签名不匹配或越界)')
311
- }
312
- const nameLen = buf.readUInt16LE(p + 28)
313
- const extraLen = buf.readUInt16LE(p + 30)
314
- const commentLen = buf.readUInt16LE(p + 32)
315
- entries.push({
316
- method: buf.readUInt16LE(p + 10),
317
- compressedSize: buf.readUInt32LE(p + 20),
318
- uncompressedSize: buf.readUInt32LE(p + 24),
319
- offset: buf.readUInt32LE(p + 42),
320
- name: buf.toString('utf8', p + 46, p + 46 + nameLen),
321
- })
322
- p += 46 + nameLen + extraLen + commentLen
323
- }
324
- if (entries.length === 0) throw new Error('ZIP 里没有任何条目')
325
- return entries
326
- }
327
-
328
- /** 取一条条目的原始(未压缩)内容。stored/deflate 之外一律明确报错。 */
329
- function readZipEntryData(buf , entry ) {
330
- const p = entry.offset
331
- if (p + 30 > buf.length || buf.readUInt32LE(p) !== 0x04034b50) {
332
- throw new Error(`ZIP 条目本地头损坏:${entry.name}`)
333
- }
334
- // 本地头的 name/extra 长度可能与中央目录不同(历史上被改过 extra),必须按本地头算。
335
- const nameLen = buf.readUInt16LE(p + 26)
336
- const extraLen = buf.readUInt16LE(p + 28)
337
- const start = p + 30 + nameLen + extraLen
338
- const end = start + entry.compressedSize
339
- if (end > buf.length) throw new Error(`ZIP 条目数据越界:${entry.name}`)
340
- const raw = buf.subarray(start, end)
341
- if (entry.method === 0) return Buffer.from(raw)
342
- if (entry.method === 8) {
343
- try {
344
- return inflateRawSync(raw)
345
- } catch (error) {
346
- throw new Error(`解压条目失败:${entry.name}(${describeError(error)})`)
347
- }
348
- }
349
- throw new Error(`不支持的 ZIP 压缩方式:${entry.method}(仅支持 stored=0 / deflate=8)`)
350
- }
351
-
352
- function extractZip(buf , destDir ) {
353
- const entries = readZipEntries(buf)
354
- // 先按**原始条目名**做一次安全检查:剥掉公共顶层目录之后再看就晚了
355
- // (`C:/x.txt` 这种绝对路径一剥就变成无害的相对路径了)。
356
- for (const entry of entries) assertSafeName(entry.name)
357
- const prefix = commonPrefix(entries.map((entry) => entry.name))
358
- let written = 0
359
- for (const entry of entries) {
360
- const rel = stripPrefix(entry.name, prefix)
361
- if (rel === '') continue
362
- // 目录项也要过一遍路径校验:`../` 目录同样不该被静默放行。
363
- const target = safeTarget(destDir, rel)
364
- if (rel.endsWith('/')) continue
365
- const data = readZipEntryData(buf, entry)
366
- if (data.length !== entry.uncompressedSize) {
367
- throw new Error(`解压校验失败:${entry.name} 声明 ${entry.uncompressedSize} 字节,实际 ${data.length} 字节`)
368
- }
369
- writeFile(target, data)
370
- written++
371
- }
372
- if (written === 0) throw new Error('压缩包里没有任何文件')
373
- return written
374
- }
375
-
376
- // ─────────────────────────── tar.gz ───────────────────────────
377
-
378
- /**
379
- * tar.gz 解压:gunzip 之后就是 512 字节头 + 数据的顺序流,没有压缩,顺序读即可。
380
- * (Linux/macOS 的 llama.cpp 发行包是 .tar.gz,Windows 才是 zip。)
381
- */
382
- function extractTarGz(buf , destDir ) {
383
- let tar
384
- try {
385
- tar = gunzipSync(buf)
386
- } catch (error) {
387
- throw new Error(`gzip 解压失败:${describeError(error)}`)
388
- }
389
- const entries = readTarEntries(tar)
390
- for (const entry of entries) assertSafeName(entry.name)
391
- const prefix = commonPrefix(entries.map((entry) => entry.name))
392
- let written = 0
393
- for (const entry of entries) {
394
- const rel = stripPrefix(entry.name, prefix)
395
- if (rel === '') continue
396
- const target = safeTarget(destDir, rel)
397
- if (entry.type === '5' || rel.endsWith('/')) continue
398
- if (entry.type !== '0' && entry.type !== '\0') continue // 符号链接/硬链接等一律跳过
399
- writeFile(target, entry.data, entry.mode)
400
- written++
401
- }
402
- if (written === 0) throw new Error('压缩包里没有任何文件')
403
- return written
404
- }
405
-
406
- function readTarEntries(tar ) {
407
- const entries = []
408
- let offset = 0
409
- let longName = null
410
- while (offset + 512 <= tar.length) {
411
- const header = tar.subarray(offset, offset + 512)
412
- if (isZeroBlock(header)) break // 归档结束标记:两个全零块
413
- const size = readOctal(header, 124, 12)
414
- const mode = readOctal(header, 100, 8)
415
- const type = String.fromCharCode(header[156] ?? 0)
416
- const dataStart = offset + 512
417
- const dataEnd = dataStart + size
418
- if (dataEnd > tar.length) throw new Error('tar 归档已损坏(条目数据越界)')
419
- const namePrefix = readText(header, 345, 155) // ustar 的长路径前缀
420
- let name = readText(header, 0, 100)
421
- if (namePrefix !== '') name = `${namePrefix}/${name}`
422
- if (longName !== null) {
423
- name = longName
424
- longName = null
425
- }
426
- const next = dataStart + pad512(size)
427
- if (type === 'L') {
428
- // GNU 长文件名:这一条的数据就是下一条的名字。
429
- longName = tar.toString('utf8', dataStart, dataEnd).replace(/\0+$/, '')
430
- offset = next
431
- continue
432
- }
433
- if (type === 'x' || type === 'g') {
434
- // pax 扩展头(含 UTF-8 路径等元数据):忽略内容,不影响普通条目。
435
- offset = next
436
- continue
437
- }
438
- entries.push({
439
- name,
440
- size,
441
- type,
442
- mode,
443
- linkName: readText(header, 157, 100),
444
- data: tar.subarray(dataStart, dataEnd),
445
- })
446
- offset = next
447
- }
448
- if (entries.length === 0) throw new Error('tar 归档里没有任何条目')
449
- return entries
450
- }
451
-
452
- function isZeroBlock(block ) {
453
- for (const byte of block) {
454
- if (byte !== 0) return false
455
- }
456
- return true
457
- }
458
-
459
- /** tar 的数字字段是八进制 ASCII;GNU 的大文件用 base-256(首字节最高位为 1)。 */
460
- function readOctal(buf , offset , length ) {
461
- const first = buf[offset]
462
- if (first !== undefined && (first & 0x80) !== 0) {
463
- let value = first & 0x7f
464
- for (let i = 1; i < length; i++) value = value * 256 + (buf[offset + i] ?? 0)
465
- return value
466
- }
467
- const text = buf.toString('latin1', offset, offset + length).replace(/\0/g, ' ').trim()
468
- const value = Number.parseInt(text, 8)
469
- return Number.isFinite(value) ? value : 0
470
- }
471
-
472
- function readText(buf , offset , length ) {
473
- return buf.toString('utf8', offset, offset + length).replace(/\0.*$/, '').trim()
474
- }
475
-
476
- function pad512(size ) {
477
- return Math.ceil(size / 512) * 512
478
- }
479
-
480
- // ─────────────────────── 路径安全 / 小工具 ───────────────────────
481
-
482
- /**
483
- * 压缩包里所有条目共享的第一段目录(如 `llama-b11429/`),没有就返回 ''。
484
- * 剥掉它,解压结果才是「llamacpp/ 下直接躺着 llama-server.exe」这种既有布局;
485
- * 只有当**每一条**都带这个前缀时才剥,避免误伤顶层散落的文件。
486
- */
487
- function commonPrefix(names ) {
488
- const first = names[0]
489
- if (first === undefined) return ''
490
- const cut = first.indexOf('/')
491
- if (cut <= 0) return ''
492
- const head = first.slice(0, cut + 1)
493
- for (const name of names) {
494
- if (!name.startsWith(head)) return ''
495
- }
496
- return head
497
- }
498
-
499
- function stripPrefix(name , prefix ) {
500
- return prefix !== '' && name.startsWith(prefix) ? name.slice(prefix.length) : name
501
- }
502
-
503
- /**
504
- * 条目名的原始安全检查:绝对路径(`/x`、`C:/x`、`\\server\share`)与任何
505
- * `..` 段一律拒绝。必须在剥公共顶层目录**之前**做,否则 `C:/x.txt` 会先被
506
- * 剥成 `x.txt`,检查就形同虚设。
507
- */
508
- function assertSafeName(rel ) {
509
- const clean = rel.replace(/\\/g, '/')
510
- if (clean.startsWith('/') || /^[A-Za-z]:/.test(clean)) {
511
- throw new Error(`压缩包条目使用了绝对路径:${rel}`)
512
- }
513
- for (const part of clean.split('/')) {
514
- if (part === '..') throw new Error(`压缩包条目试图跳出安装目录:${rel}`)
515
- }
516
- }
517
-
518
- /**
519
- * 把条目相对路径解析到 destDir 之内,越界就抛。
520
- * 压缩包是远端内容,绝对路径与 `..` 段都必须拒绝,否则一个恶意/被篡改的发行
521
- * 包就能往安装目录外写文件。这里再做一次解析边界校验,兜住拼接层面的意外。
522
- */
523
- function safeTarget(destDir , rel ) {
524
- assertSafeName(rel)
525
- const root = resolve(destDir)
526
- const target = resolve(root, rel.replace(/\\/g, '/'))
527
- if (target !== root && !target.startsWith(root + sep)) {
528
- throw new Error(`压缩包条目试图跳出安装目录:${rel}`)
529
- }
530
- return target
531
- }
532
-
533
- function writeFile(target , data , mode ) {
534
- try {
535
- mkdirSync(dirname(target), { recursive: true })
536
- writeFileSync(target, data)
537
- // tar 保留了权限位:不加这一步,Linux/macOS 上的 llama-server 落地就没有
538
- // 执行权限,spawn 直接 EACCES。
539
- if (mode !== undefined && process.platform !== 'win32') chmodSync(target, mode & 0o777)
540
- } catch (error) {
541
- throw diskError(`写入 ${target}`, error)
542
- }
543
- }
544
-
545
- function ensureDir(dir , what ) {
546
- try {
547
- mkdirSync(dir, { recursive: true })
548
- } catch (error) {
549
- throw diskError(what, error)
550
- }
551
- }
552
-
553
- function isFile(path ) {
554
- try {
555
- return statSync(path).isFile()
556
- } catch {
557
- return false
558
- }
559
- }
560
-
561
- function fileSize(path ) {
562
- try {
563
- return statSync(path).size
564
- } catch {
565
- return 0
566
- }
567
- }
568
-
569
- function parseContentLength(header ) {
570
- if (header === null) return null
571
- const value = Number.parseInt(header, 10)
572
- return Number.isFinite(value) && value >= 0 ? value : null
573
- }
574
-
575
- function isAbortError(error ) {
576
- if (typeof error !== 'object' || error === null) return false
577
- return (error ).name === 'AbortError'
578
- }
579
-
580
- function describeError(error ) {
581
- if (error instanceof Error) return error.message
582
- return String(error)
583
- }
584
-
585
- /** 把底层 fs 错误翻译成面板能看懂的话(缺权限 / 磁盘满是最常见的两种)。 */
586
- function diskError(what , error ) {
587
- const code = (error )?.code
588
- const detail = describeError(error)
589
- if (typeof code === 'string' && ['EACCES', 'EPERM', 'EROFS', 'ENOSPC', 'EBUSY', 'EMFILE', 'ENFILE'].includes(code)) {
590
- return new Error(`磁盘写入失败(${what}):${detail}`)
591
- }
592
- return error instanceof Error ? error : new Error(`${what}:${detail}`)
593
- }
594
-
595
- function formatBytes(bytes ) {
596
- if (bytes < 1024) return `${bytes} B`
597
- const mb = bytes / (1024 * 1024)
598
- if (mb < 1024) return `${mb.toFixed(1)} MB`
599
- return `${(mb / 1024).toFixed(2)} GB`
600
- }
601
-
602
- function urlHost(url ) {
603
- try {
604
- return new URL(url).host
605
- } catch {
606
- return url
607
- }
608
- }
609
-
610
- /** 等一个背压 drain;顺手把流错误也变成 reject,免得卡死。 */
611
- function waitDrain(stream ) {
612
- return new Promise((resolve, reject) => {
613
- const onDrain = () => { cleanup(); resolve() }
614
- const onError = (error ) => { cleanup(); reject(error) }
615
- const cleanup = () => {
616
- stream.off('drain', onDrain)
617
- stream.off('error', onError)
618
- }
619
- stream.once('drain', onDrain)
620
- stream.once('error', onError)
621
- })
622
- }
623
-
624
- function closeStream(stream ) {
625
- return new Promise((resolve, reject) => {
626
- stream.once('error', reject)
627
- stream.end(() => resolve())
628
- })
629
- }
630
-
631
- // ────────────────────────── 安装器本体 ──────────────────────────
632
-
633
- /**
634
- * 下载 + 解压 + 校验。用法(面板按钮):
635
- * const installer = new VectorInstaller({ root, onProgress: p => render(p) })
636
- * installer.start() // fire-and-forget,绝不抛
637
- * installer.cancel() // 中止并清理 .part
638
- * installer.progress // 随时读快照
639
- */
640
- export class VectorInstaller {
641
- opts
642
- state = {
643
- phase: 'idle',
644
- message: '',
645
- receivedBytes: 0,
646
- totalBytes: null,
647
- error: null,
648
- paths: null,
649
- }
650
- running = false
651
- cancelled = false
652
- /** 每轮 cancel 自增:在途 run() 用它判断自己是否已经过期(别再改状态)。 */
653
- generation = 0
654
- controller = null
655
- /** 当前正在写的 .part 与它的流(取消时要立刻销毁,否则 fd 悬着)。 */
656
- sink = null
657
-
658
- constructor(opts ) {
659
- this.opts = opts
660
- }
661
-
662
- /** 状态快照(返回副本,调用方改不动内部状态)。 */
663
- get progress() {
664
- return { ...this.state }
665
- }
666
-
667
- /** 幂等:已在跑、或已装好,直接返回。 */
668
- start() {
669
- if (this.running) return
670
- const installed = detectInstalled(this.opts.root)
671
- if (installed) {
672
- this.report(this.generation, {
673
- phase: 'done',
674
- message: '向量后端已就绪,无需下载',
675
- error: null,
676
- receivedBytes: 0,
677
- totalBytes: null,
678
- paths: installed,
679
- })
680
- return
681
- }
682
- const gen = this.generation
683
- this.running = true
684
- this.cancelled = false
685
- this.controller = new AbortController()
686
- // 关键:不 await、不 rethrow。start() 的调用方是 UI 事件处理器,
687
- // 一个未捕获的 rejection 会在宿主里变成 unhandledRejection。
688
- void this.run(gen)
689
- .catch((error ) => {
690
- if (gen !== this.generation || this.cancelled) return
691
- this.fail(error)
692
- })
693
- .finally(() => {
694
- if (gen === this.generation) {
695
- this.running = false
696
- this.controller = null
697
- }
698
- })
699
- }
700
-
701
- /** 取消:中止在途请求、销毁 .part、phase 回到 idle。没在跑就是 no-op。 */
702
- cancel() {
703
- if (!this.running && this.controller === null) return
704
- this.generation++
705
- this.cancelled = true
706
- this.running = false
707
- const controller = this.controller
708
- this.controller = null
709
- controller?.abort()
710
- this.dropSink()
711
- this.report(this.generation, {
712
- phase: 'idle',
713
- message: '已取消',
714
- error: null,
715
- receivedBytes: 0,
716
- totalBytes: null,
717
- paths: null,
718
- })
719
- }
720
-
721
- async run(gen ) {
722
- const root = this.opts.root
723
- const platform = this.opts.platform ?? process.platform
724
- const arch = this.opts.arch ?? process.arch
725
- const paths = installPaths(root)
726
- try {
727
- this.setPhase(gen, 'preparing', `准备安装目录 ${root}`)
728
- ensureDir(root, '创建安装根目录')
729
- ensureDir(paths.dir, '创建运行时目录')
730
- ensureDir(dirname(paths.model), '创建模型目录')
731
-
732
- const asset = await this.resolveRuntimeAsset(gen, platform, arch)
733
- const archivePath = join(paths.dir, asset.name)
734
- if (fileSize(archivePath) > 0) {
735
- // 上轮下完但解压/下模型失败:压缩包还在,别白下第二遍。
736
- this.setPhase(gen, 'downloading-runtime', `已存在 ${asset.name},跳过下载`, { receivedBytes: 0, totalBytes: null })
737
- } else {
738
- this.setPhase(gen, 'downloading-runtime', `正在下载 llama.cpp 运行时 ${asset.name}`)
739
- const got = await this.downloadFrom(gen, runtimeDownloadSources(asset), archivePath, 'llama.cpp 运行时', 'downloading-runtime', '通道')
740
- // 成功日志里写清走的哪条通道:直链还是 API 资产端点,排障时第一眼要看的就是它。
741
- this.report(gen, { message: `运行时下载完成(${formatBytes(got.bytes)},通道:${got.source.label})` })
742
- }
743
-
744
- this.setPhase(gen, 'extracting', `正在解压 ${asset.name}`)
745
- let archive
746
- try {
747
- archive = readFileSync(archivePath)
748
- } catch (error) {
749
- throw diskError(`读取 ${archivePath}`, error)
750
- }
751
- let written
752
- try {
753
- written = extractArchive(archive, paths.dir)
754
- } catch (error) {
755
- // 解压失败说明压缩包本身坏了:删掉它,下次点击会重新下载,
756
- // 而不是每次都撞同一个坏文件(.part 早就没了,这个包是「完整但损坏」)。
757
- try { rmSync(archivePath, { force: true }) } catch { /* 尽力而为 */ }
758
- throw error
759
- }
760
- if (!existsSync(paths.exe)) {
761
- throw new Error(`解压完成但没找到 ${basename(paths.exe)}:${asset.name} 的目录结构可能变了`)
762
- }
763
- if (platform !== 'win32') {
764
- // tar 的权限位在大多数归档里是齐的,这里再兜一次底。
765
- try { chmodSync(paths.exe, 0o755) } catch { /* 尽力而为 */ }
766
- }
767
- this.setPhase(gen, 'extracting', `已解压 ${written} 个文件`)
768
-
769
- if (fileSize(paths.model) > 0) {
770
- // 模型 417MB,重下一次代价太大:已经在就直接用。
771
- this.setPhase(gen, 'downloading-model', '模型已存在,跳过下载', { receivedBytes: 0, totalBytes: null })
772
- } else {
773
- this.setPhase(gen, 'downloading-model', `正在下载 bge-m3 模型(约 ${formatBytes(MODEL_SIZE_BYTES)})`)
774
- const got = await this.downloadModel(gen, paths.model)
775
- this.report(gen, { message: `模型下载完成(已下载 ${formatBytes(got.bytes)},来源:${got.source.label})` })
776
- }
777
-
778
- const installed = detectInstalled(root)
779
- if (installed === null) throw new Error('安装校验失败:llama-server 或模型文件缺失')
780
- this.report(gen, {
781
- phase: 'done',
782
- message: `安装完成:模型 ${formatBytes(fileSize(installed.model))},运行时 ${basename(installed.exe)}`,
783
- error: null,
784
- receivedBytes: 0,
785
- totalBytes: null,
786
- paths: installed,
787
- })
788
- } catch (error) {
789
- // 取消不是错误:清掉半成品,回到 idle(面板据此把进度条收起来)。
790
- if (this.cancelled || gen !== this.generation || isAbortError(error)) {
791
- if (this.sink?.gen === gen) this.dropSink()
792
- this.setPhase(gen, 'idle', '已取消')
793
- return
794
- }
795
- throw error
796
- }
797
- }
798
-
799
- /** 查发行版列表 → 按平台挑包。latest 不可用(见下),按时间倒序取第一个命中的。 */
800
- async resolveRuntimeAsset(
801
- gen ,
802
- platform ,
803
- arch ,
804
- ) {
805
- const pattern = runtimeAssetPattern(platform, arch)
806
- const label = `${platform}-${arch}`
807
- this.report(gen, { message: `正在查询 llama.cpp 最新构建(${label})` })
808
- // 注意:不要用 /releases/latest。llama.cpp 的 b#### 构建线全部带
809
- // prerelease:true,而 latest 只认正式版,现在返回的是一个与本项目无关的
810
- // v0.6.0(资产只有 nightly-tag.txt)——照它匹配必然失败。正确做法是拉倒序
811
- // 列表,取第一个含匹配资产的 release(prerelease 与否无关)。
812
- const releases = await this.fetchJson(RELEASES_API, '查询 llama.cpp 发行版')
813
- if (!Array.isArray(releases)) throw new Error('llama.cpp 发行版接口返回的数据格式异常')
814
- for (const release of releases) {
815
- if (typeof release !== 'object' || release === null) continue
816
- const assets = (release ).assets
817
- if (!Array.isArray(assets)) continue
818
- const hit = matchAsset(assets, pattern)
819
- if (hit !== null) return hit
820
- }
821
- throw new Error(`资产匹配失败:${label}(最近 20 个发行版里没有匹配 ${String(pattern)} 的包)`)
822
- }
823
-
824
- /** 模型下载:多源顺序回退(noun 只影响报错文案)。 */
825
- async downloadModel(gen , dest ) {
826
- const urls = this.opts.modelSources ?? MODEL_SOURCES
827
- const sources = urls.map((url) => ({ url, accept: '*/*', label: urlHost(url) }))
828
- return this.downloadFrom(gen, sources, dest, 'bge-m3 模型', 'downloading-model', '源')
829
- }
830
-
831
- /**
832
- * 按候选顺序下载,当前候选失败(网络错误 / 非 2xx / 中途断流)就换下一个,
833
- * 每个候选都从 0 重新下(不做断点续传,失败时 download() 已经清掉 .part)。
834
- * 全部失败时把所有候选各自的原因一起报出来——只报一句「下载失败」的话,用户
835
- * 根本分不清是墙、是 DNS、还是磁盘满。
836
- */
837
- async downloadFrom(
838
- gen ,
839
- sources ,
840
- dest ,
841
- what ,
842
- phase ,
843
- noun ,
844
- ) {
845
- const failures = []
846
- for (const source of sources) {
847
- try {
848
- const bytes = await this.download(gen, source, dest, what, phase)
849
- return { bytes, source }
850
- } catch (error) {
851
- if (this.cancelled || isAbortError(error)) throw error
852
- const reason = describeError(error)
853
- const host = urlHost(source.url)
854
- // 通道名里已经含主机名(模型源就是这么标的)时不要重复一遍。
855
- const who = source.label.includes(host) ? source.label : `${source.label}(${host})`
856
- failures.push(`${who}:${reason}`)
857
- this.report(gen, {
858
- message: `${who} 下载失败(${reason}),换下一个${noun}重试`,
859
- receivedBytes: 0,
860
- totalBytes: null,
861
- })
862
- }
863
- }
864
- if (failures.length === 0) throw new Error(`下载${what}失败:没有配置任何下载${noun}`)
865
- throw new Error(`下载${what}失败:所有${noun}都失败\n${failures.map((line) => ` - ${line}`).join('\n')}`)
866
- }
867
-
868
- /**
869
- * 流式下载到 dest:先写 `<dest>.part`,完整收流后 rename。
870
- * 每收到一块就上报一次 receivedBytes(面板的百分比来源)。
871
- */
872
- async download(
873
- gen ,
874
- source ,
875
- dest ,
876
- what ,
877
- phase ,
878
- ) {
879
- const url = source.url
880
- const part = `${dest}.part`
881
- const res = await this.request(url, source.accept)
882
- if (!res.ok) {
883
- throw new Error(`下载${what}失败:HTTP ${res.status}${res.statusText !== '' ? ` ${res.statusText}` : ''}(${url})`)
884
- }
885
- const total = parseContentLength(res.headers.get('content-length')) // 拿不到就是 null
886
- const body = res.body
887
- if (body === null) throw new Error(`下载${what}失败:响应没有可读的数据流`)
888
- const reader = body.getReader()
889
- const stream = createWriteStream(part, { flags: 'w' })
890
- this.sink = { gen, part, stream }
891
- // 用容器而不是裸 let:错误在回调里赋值、在循环里读,容器能让 TS 的类型收窄
892
- // 保持可预测(裸 let 在闭包里赋值后收窄会被重置/变 never)。
893
- const failure = { error: null }
894
- stream.on('error', (error) => { failure.error = error })
895
- let received = 0
896
- try {
897
- for (;;) {
898
- const chunk = await reader.read()
899
- if (chunk.done) break
900
- const value = chunk.value
901
- if (value === undefined || value.byteLength === 0) continue
902
- received += value.byteLength
903
- if (!stream.write(value)) await waitDrain(stream)
904
- if (failure.error !== null) throw failure.error
905
- this.report(gen, { phase, receivedBytes: received, totalBytes: total, error: null })
906
- }
907
- await closeStream(stream)
908
- if (failure.error !== null) throw failure.error
909
- } catch (error) {
910
- try { stream.destroy() } catch { /* 已经坏了 */ }
911
- try { rmSync(part, { force: true }) } catch { /* 尽力而为 */ }
912
- if (this.sink?.part === part) this.sink = null
913
- // 写盘失败(磁盘满/无权限)要说得明白,别把 ERR_STREAM 之类的丢给用户。
914
- if (failure.error !== null && !isAbortError(error)) throw diskError(`写入 ${part}`, failure.error)
915
- throw error
916
- }
917
- try {
918
- renameSync(part, dest)
919
- } catch (error) {
920
- if (this.sink?.part === part) this.sink = null
921
- throw diskError(`重命名 ${dest}`, error)
922
- }
923
- if (this.sink?.part === part) this.sink = null
924
- this.report(gen, { phase, receivedBytes: received, totalBytes: total, error: null })
925
- return received
926
- }
927
-
928
- /** 发一个带 UA 的请求;网络层错误翻译成人话,但 AbortError 原样上抛。 */
929
- async request(url , accept ) {
930
- const impl = this.opts.fetchImpl ?? fetch
931
- const signal = this.requestSignal()
932
- try {
933
- return await impl(url, { headers: { accept, 'user-agent': USER_AGENT }, signal, redirect: 'follow' })
934
- } catch (error) {
935
- if (isAbortError(error)) throw error
936
- throw new Error(`网络请求失败(${urlHost(url)}):${describeError(error)}`)
937
- }
938
- }
939
-
940
- async fetchJson(url , what ) {
941
- const res = await this.request(url, 'application/vnd.github+json')
942
- if (res.status === 403 || res.status === 429) {
943
- throw new Error('GitHub API 限流(未认证请求每小时 60 次),请稍后重试')
944
- }
945
- if (!res.ok) throw new Error(`${what}失败:HTTP ${res.status}(${url})`)
946
- try {
947
- return await res.json()
948
- } catch (error) {
949
- throw new Error(`${what}返回的不是合法 JSON:${describeError(error)}`)
950
- }
951
- }
952
-
953
- /** 自带 controller + 调用方 signal 的合并信号。 */
954
- requestSignal() {
955
- const external = this.opts.signal
956
- const controller = this.controller
957
- if (controller === null) return external ?? new AbortController().signal
958
- return external === undefined ? controller.signal : AbortSignal.any([controller.signal, external])
959
- }
960
-
961
- /** 销毁在途的 .part 流并删文件(取消路径)。 */
962
- dropSink() {
963
- const sink = this.sink
964
- this.sink = null
965
- if (sink === null) return
966
- try { sink.stream.destroy() } catch { /* 已经坏了 */ }
967
- try { rmSync(sink.part, { force: true }) } catch { /* 尽力而为 */ }
968
- }
969
-
970
- fail(error ) {
971
- this.dropSink()
972
- const message = describeError(error)
973
- this.report(this.generation, {
974
- phase: 'error',
975
- message,
976
- error: message,
977
- totalBytes: null,
978
- paths: detectInstalled(this.opts.root),
979
- })
980
- }
981
-
982
- /** 状态上报;gen 过期(已被 cancel 顶掉)就整条丢掉,不污染新一轮。 */
983
- report(gen , patch ) {
984
- if (gen !== this.generation) return
985
- this.state = { ...this.state, ...patch }
986
- const listener = this.opts.onProgress
987
- if (listener === undefined) return
988
- try {
989
- listener({ ...this.state })
990
- } catch {
991
- // 面板回调自己出错,不能把安装带崩
992
- }
993
- }
994
-
995
- /** 切阶段:进度一律清零,免得面板把上一个文件的字节数算到新阶段头上。 */
996
- setPhase(gen , phase , message , extra = {}) {
997
- this.report(gen, { phase, message, error: null, receivedBytes: 0, totalBytes: null, ...extra })
998
- }
999
- }
1000
-
1001
-
1002
- //# sourceURL=D:\.deepseek\memory-plugin\packages\memory-local\src\embed-install.ts
1
+ /**
2
+ * dsh-memory-local — 向量后端「下载并配置」安装器(零运行时依赖)。
3
+ *
4
+ * 背景:本地语义检索需要一个 OpenAI 兼容的 /v1/embeddings 服务,而默认没人替
5
+ * 用户准备好后端——得自己去下 llama.cpp 的 llama-server 和 bge-m3 的 GGUF 模
6
+ * 型,再手填两个绝对路径。本模块把那套手工动作收成一个按钮:
7
+ * 查 GitHub 最新构建 → 下运行时压缩包 → 解压 → 下模型 → 校验布局
8
+ * 落盘位置与「手工装好的既有布局」逐字节一致,装完由 EmbedServerManager 托管
9
+ * 启动(见 embed-server.ts)。
10
+ *
11
+ * 为什么零依赖(任何 npm 包都不用):
12
+ * - 这个包要被别人 `pnpm add dsh-memory-local` 直接装上就用,每多一个依赖就多
13
+ * 一份升级、审计、甚至原生编译的负担;解压一个发行包不值得把包袱转嫁给用户;
14
+ * - 真正需要的能力 node 内置已经齐了:zip 要的只是「中央目录 + inflateRaw」,
15
+ * tar.gz 要的只是「gunzip + 512 字节头」,zlib 直接给;流式写盘用 fs 流;
16
+ * HTTPS/TLS 交给全局 fetch(不碰 node:https,证书与代理策略跟随宿主)。
17
+ *
18
+ * 硬约束(都对应一条真实教训):
19
+ * - 默认绝不下载:只有显式 start() 才碰网络,构造/导入阶段零 I/O;
20
+ * - 幂等:已在跑、或已经装好,start() 什么都不做;
21
+ * - 绝不抛异常:start() 是 fire-and-forget,任何失败都变成 phase:'error' +
22
+ * 可读 message(面板直接显示这两个字段);
23
+ * - 半成品绝不落地:下载先写 <目标>.part,收流完整后 rename——否则一次断网
24
+ * 留下的半个 gguf 会被 detectInstalled 当成「已安装」,然后 llama-server
25
+ * 报一句莫名其妙的加载失败;
26
+ * - 可取消:cancel() 中止在途请求、删掉 .part、phase 回到 idle;
27
+ * - 解压必须防路径穿越:压缩包是远端内容,`../` 或绝对路径条目一律拒绝;
28
+ * - 每条下载都留了备用通道:运行时是「下载直链 → GitHub API 资产端点」,模型
29
+ * 是多个源,全部按序回退(详见 runtimeDownloadSources / MODEL_SOURCES)。
30
+ * 这不是锦上添花——直链会 302 到 release-assets.githubusercontent.com,该主机
31
+ * 在部分网络会被重置连接,而 api.github.com 通畅,没有备用通道就等于装不上。
32
+ *
33
+ * 布局(installPaths 是唯一事实来源,检测与安装都走它):
34
+ * <root>/llamacpp/llama-server[.exe] ← 运行时(同目录还有几十个 dll/so)
35
+ * <root>/models/bge-m3-Q4_K_M.gguf ← 模型
36
+ * <root>/llama-server.log ← 托管启动时追加的日志
37
+ */
38
+ import { chmodSync, createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
39
+
40
+ import { basename, dirname, join, resolve, sep } from 'node:path'
41
+ import { gunzipSync, inflateRawSync } from 'node:zlib'
42
+
43
+
44
+ /** 模型文件名:下载目标与「是否已安装」的判据都用它,不要在两处各写一遍。 */
45
+ export const MODEL_FILE_NAME = 'bge-m3-Q4_K_M.gguf'
46
+
47
+ /** 运行时的 zip/pkg 文件名(Windows 是 zip,Linux/macOS 是 tar.gz)。 */
48
+ export const RUNTIME_DIR_NAME = 'llamacpp'
49
+ export const MODELS_DIR_NAME = 'models'
50
+ export const LOG_FILE_NAME = 'llama-server.log'
51
+
52
+ /** GitHub API:查询 llama.cpp 发行版列表(不硬编码构建号)。 */
53
+ const RELEASES_API = 'https://api.github.com/repos/ggml-org/llama.cpp/releases?per_page=20'
54
+ /** GitHub 要求带 UA;不带会被 403。 */
55
+ const USER_AGENT = 'dsh-memory-local-installer'
56
+
57
+ /**
58
+ * 模型下载源,按顺序回退(同一份 Q4_K_M,仓库都是 gpustack/bge-m3-GGUF)。
59
+ *
60
+ * 2026-10-10 逐个核实过(只发 HEAD / Range,没有真的拉 400MB):
61
+ * - hf-mirror.com → 302 → HF CDN,content-length 437778496 ✅
62
+ * - modelscope.cn → 302 → cdn-lfs-cn-1.modelscope.cn,206 + `bytes 0-0/437778496` ✅
63
+ * - huggingface.co → 本机直连超时(curl 28,15s 无响应)❌ 但海外用户应该优先官方源
64
+ * 三个源的大小都等于本机 `D:\.deepseek\memory-stack\models\bge-m3-Q4_K_M.gguf`
65
+ * 的 437778496 字节,即同一份量化。
66
+ *
67
+ * 顺序取「国内可达的两个在前、官方源在最后」:本机/国内是第一现场,官方源排在
68
+ * 列表里仍然会被尝试,海外用户只是多花一次失败请求的代价。
69
+ */
70
+ export const MODEL_SOURCES = [
71
+ 'https://hf-mirror.com/gpustack/bge-m3-GGUF/resolve/main/bge-m3-Q4_K_M.gguf',
72
+ 'https://modelscope.cn/models/gpustack/bge-m3-GGUF/resolve/master/bge-m3-Q4_K_M.gguf',
73
+ 'https://huggingface.co/gpustack/bge-m3-GGUF/resolve/main/bge-m3-Q4_K_M.gguf',
74
+ ]
75
+ /**
76
+ * 期望字节数(437778496 = 417.5 MiB)。**只用于消息里的「约 X MB」,不做硬校验**:
77
+ * 上游随时可能重新量化/更新,把大小当断言会让一次正常的上游更新变成安装失败。
78
+ * 真实进度一律以响应的 content-length 为准。
79
+ */
80
+ export const MODEL_SIZE_BYTES = 437_778_496
81
+
82
+ /** 安装布局。与手工装好的既有布局一致(embed-server 直接吃这几个字段)。 */
83
+
84
+        
85
+
86
+      
87
+
88
+       
89
+
90
+                     
91
+
92
+                           
93
+
94
+
95
+
96
+
97
+
98
+ /** 要安装的模型:文件名是唯一事实来源(落盘名 + 「装没装」判据)。 */
99
+
100
+
101
+                         
102
+
103
+                          
104
+
105
+
106
+
107
+ /** 安装状态机。idle/error 都可能再次 start()。 */
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+
117
+ /**
118
+ * 面板直接渲染的快照。receivedBytes/totalBytes 是**当前这一个文件**的进度
119
+ * (totalBytes 取 content-length,拿不到就是 null),所以百分比 =
120
+ * receivedBytes/totalBytes 才有意义。
121
+ */
122
+
123
+
124
+
125
+
126
+
127
+
128
+
129
+
130
+
131
+
132
+               
133
+
134
+                      
135
+
136
+                              
137
+
138
+                                
139
+
140
+
141
+                           
142
+             
143
+
144
+
145
+                 
146
+
147
+                       
148
+
149
+                                
150
+
151
+         
152
+
153
+
154
+
155
+ /** zip 中央目录里一条记录(只保留解压需要的字段)。 */
156
+
157
+
158
+
159
+
160
+
161
+        
162
+
163
+
164
+
165
+ /** tar 里一条记录。 */
166
+
167
+
168
+
169
+                     
170
+
171
+
172
+
173
+
174
+
175
+ export function installPaths(root , modelFile = MODEL_FILE_NAME) {
176
+ const dir = join(root, RUNTIME_DIR_NAME)
177
+ // 宿主平台决定可执行文件名:Windows 上 llama.cpp 的启动器带 .exe。
178
+ const exeName = process.platform === 'win32' ? 'llama-server.exe' : 'llama-server'
179
+ return {
180
+ root,
181
+ dir,
182
+ exe: join(dir, exeName),
183
+ cwd: dir,
184
+ model: join(root, MODELS_DIR_NAME, modelFile),
185
+ logFile: join(root, LOG_FILE_NAME),
186
+ }
187
+ }
188
+
189
+ /**
190
+ * 已安装则返回布局,否则 null(判据:exe 与**所选模型的**文件都在)。
191
+ *
192
+ * 只看「存在」就够:安装器永远先写 .part 再 rename,所以这两个路径上不可能
193
+ * 出现半成品;反过来,用户手工放好的文件也会被如实采纳(这正是
194
+ * `<root>/llamacpp` + `<root>/models` 这套既有布局的意义)。
195
+ * 绝不抛异常:它在 resolveConfig 里被同步调用。
196
+ */
197
+ export function detectInstalled(root , modelFile = MODEL_FILE_NAME) {
198
+ try {
199
+ const paths = installPaths(root, modelFile)
200
+ if (!isFile(paths.exe) || !isFile(paths.model)) return null
201
+ return paths
202
+ } catch {
203
+ return null
204
+ }
205
+ }
206
+
207
+ /**
208
+ * 平台 + 风味 → 发行资产名正则。按平台挑包,绝不硬编码构建号。
209
+ *
210
+ * 资产名逐个核实过(llama.cpp b11678,2026-10-16 查的 API):
211
+ * cpu win/linux/macos 的通用包(win-cpu-x64 / ubuntu-x64 / macos-*)
212
+ * vulkan `-bin-win-vulkan-x64.zip` / `-bin-ubuntu-vulkan-x64.tar.gz` —— 自包含,驱动自带 Vulkan 即可
213
+ * cuda `-bin-win-cuda-12.4-x64.zip` / `-bin-ubuntu-cuda-12.8-x64.tar.gz` —— **还需要 cudart 伴随包**
214
+ * metal macOS 构建自带 Metal,资产与 cpu 相同
215
+ *
216
+ * 正则一律用 `$` 锚定:同一批资产里还有 cuda/vulkan/sycl/openvino/rocm/adreno 变体,
217
+ * 不锚定就会把 `-ubuntu-vulkan-x64.tar.gz` 之类当成 CPU 包下下来(几百 MB 白下)。
218
+ * CUDA 的次版本号写进正则是有意的:不同 CUDA 版本需要不同的 cudart 与之配对,
219
+ * 让它们一起被选中才能保证两个包属于同一套工具链。
220
+ */
221
+ export function runtimeAssetPattern(
222
+ platform ,
223
+ arch ,
224
+ flavor = 'cpu',
225
+ ) {
226
+ const key = `${platform}-${arch}`
227
+ const cpu = () => {
228
+ switch (key) {
229
+ case 'win32-x64': return /-bin-win-cpu-x64\.zip$/
230
+ case 'win32-arm64': return /-bin-win-cpu-arm64\.zip$/
231
+ case 'linux-x64': return /-bin-ubuntu-x64\.(?:zip|tar\.gz)$/
232
+ case 'linux-arm64': return /-bin-ubuntu-arm64\.(?:zip|tar\.gz)$/
233
+ case 'darwin-arm64': return /-bin-macos-arm64\.(?:zip|tar\.gz)$/
234
+ case 'darwin-x64': return /-bin-macos-x64\.(?:zip|tar\.gz)$/
235
+ default:
236
+ throw new Error(
237
+ `资产匹配失败:${key}(暂不支持该平台;已支持 win32-x64 / win32-arm64 / linux-x64 / linux-arm64 / darwin-arm64 / darwin-x64)`,
238
+ )
239
+ }
240
+ }
241
+ if (flavor === 'cpu' || flavor === 'metal') return cpu()
242
+ if (flavor === 'vulkan') {
243
+ switch (key) {
244
+ case 'win32-x64': return /-bin-win-vulkan-x64\.zip$/
245
+ case 'win32-arm64': return /-bin-win-vulkan-arm64\.zip$/
246
+ case 'linux-x64': return /-bin-ubuntu-vulkan-x64\.tar\.gz$/
247
+ case 'linux-arm64': return /-bin-ubuntu-vulkan-arm64\.tar\.gz$/
248
+ // macOS 没有独立的 Vulkan 包(Metal 就是它的 GPU 路径),退回 CPU 构建。
249
+ default: return cpu()
250
+ }
251
+ }
252
+ // cuda
253
+ switch (key) {
254
+ case 'win32-x64': return /-bin-win-cuda-12\.4-x64\.zip$/
255
+ case 'win32-arm64': return /-bin-win-cuda-13\.4-arm64\.zip$/
256
+ case 'linux-x64': return /-bin-ubuntu-cuda-12\.8-x64\.tar\.gz$/
257
+ case 'linux-arm64': return /-bin-ubuntu-cuda-13\.4-arm64\.tar\.gz$/
258
+ default: return cpu()
259
+ }
260
+ }
261
+
262
+ /**
263
+ * CUDA 风味需要的伴随资产(cudart:运行时 + cuBLAS 等),没有它 llama-server 起不来。
264
+ *
265
+ * 注意它的命名和主包**不一致**:有的带构建号、有的不带
266
+ * (`cudart-llama-bin-win-cuda-12.4-x64.zip` vs `cudart-llama-b11678-bin-win-cuda-13.4-x64.zip`),
267
+ * 所以正则不能要求 `b<号>`,只能靠 cuda 次版本号把两者配对。
268
+ */
269
+ export function runtimeCompanionPattern(
270
+ platform ,
271
+ arch ,
272
+ flavor ,
273
+ ) {
274
+ if (flavor !== 'cuda') return null
275
+ switch (`${platform}-${arch}`) {
276
+ case 'win32-x64': return /^cudart-.*bin-win-cuda-12\.4-x64\.zip$/
277
+ case 'win32-arm64': return /^cudart-.*bin-win-cuda-13\.4-arm64\.zip$/
278
+ case 'linux-x64': return /^cudart-.*bin-ubuntu-cuda-12\.8-x64\.tar\.gz$/
279
+ case 'linux-arm64': return /^cudart-.*bin-ubuntu-cuda-13\.4-arm64\.tar\.gz$/
280
+ default: return null
281
+ }
282
+ }
283
+
284
+ /** 一个发行资产的两条下载通道(见 runtimeDownloadSources)。 */
285
+
286
+
287
+                   
288
+
289
+            
290
+
291
+
292
+
293
+ /** 在一批 GitHub 资产里按平台 + 风味挑第一个匹配的包。 */
294
+ export function pickRuntimeAsset(
295
+ assets ,
296
+ platform ,
297
+ arch ,
298
+ flavor = 'cpu',
299
+ ) {
300
+ return matchAsset(assets, runtimeAssetPattern(platform, arch, flavor))
301
+ }
302
+
303
+ /** 挑 CUDA 的 cudart 伴随包(非 cuda 风味或无匹配时为 null)。 */
304
+ export function pickRuntimeCompanion(
305
+ assets ,
306
+ platform ,
307
+ arch ,
308
+ flavor ,
309
+ ) {
310
+ const pattern = runtimeCompanionPattern(platform, arch, flavor)
311
+ return pattern === null ? null : matchAsset(assets, pattern)
312
+ }
313
+
314
+ function matchAsset(assets , pattern ) {
315
+ for (const asset of assets) {
316
+ if (typeof asset !== 'object' || asset === null) continue
317
+ const name = (asset ).name
318
+ const url = (asset ).browser_download_url
319
+ const apiUrl = (asset ).url
320
+ if (typeof name !== 'string' || typeof url !== 'string') continue
321
+ if (pattern.test(name)) return { name, url, apiUrl: typeof apiUrl === 'string' ? apiUrl : '' }
322
+ }
323
+ return null
324
+ }
325
+
326
+ /** 在倒序的发行版列表里找第一个含匹配资产的 release(latest 不可用,见 resolveRuntimeAsset)。 */
327
+ function findAssetInReleases(releases , pattern ) {
328
+ for (const release of releases) {
329
+ if (typeof release !== 'object' || release === null) continue
330
+ const assets = (release ).assets
331
+ if (!Array.isArray(assets)) continue
332
+ const hit = matchAsset(assets, pattern)
333
+ if (hit !== null) return hit
334
+ }
335
+ return null
336
+ }
337
+
338
+ /** 一个下载候选通道。 */
339
+
340
+
341
+          
342
+
343
+                         
344
+
345
+
346
+
347
+ /**
348
+ * 运行时的两条通道,按序回退:
349
+ * 1. `browser_download_url`(下载直链)——标准通道,大多数网络下最快;
350
+ * 2. `asset.url`(GitHub API 资产端点,Accept: application/octet-stream)——
351
+ * 直链会 302 到 release-assets/objects.githubusercontent.com,这个主机在
352
+ * 部分网络(含本机)会被重置连接,而 api.github.com 是通的,所以它是本机
353
+ * 能一键装上的关键备用通道。
354
+ * 实测(2026-10-10,node 全局 fetch,只读响应头):直链 fetch failed;
355
+ * API 端点 HTTP 200 + content-length 19518702,1.2s。
356
+ */
357
+ export function runtimeDownloadSources(asset ) {
358
+ const sources = [
359
+ { url: asset.url, accept: '*/*', label: '发行包直链' },
360
+ ]
361
+ const withAccept = { url: asset.apiUrl, accept: 'application/octet-stream', label: 'GitHub API 资产端点' }
362
+ if (asset.apiUrl !== '' && asset.apiUrl !== asset.url) sources.push(withAccept)
363
+ return sources.filter((source) => source.url !== '')
364
+ }
365
+
366
+ /**
367
+ * 按魔数解压 zip / tar.gz 到 destDir,返回写入的文件数。
368
+ * 看魔数而不是扩展名:远端文件名不可靠,内容头是可靠的。
369
+ */
370
+ export function extractArchive(archive , destDir ) {
371
+ if (archive.length >= 4 && archive[0] === 0x50 && archive[1] === 0x4b) return extractZip(archive, destDir)
372
+ if (archive.length >= 2 && archive[0] === 0x1f && archive[1] === 0x8b) return extractTarGz(archive, destDir)
373
+ throw new Error('不支持的压缩格式:既不是 zip(PK)也不是 gzip(1f 8b)')
374
+ }
375
+
376
+ // ───────────────────────────── zip ─────────────────────────────
377
+
378
+ /** 从尾部往前找 End of Central Directory(最多回扫 65557 字节 = 22 + 注释上限)。 */
379
+ function findEocd(buf ) {
380
+ const floor = Math.max(0, buf.length - 65_557)
381
+ for (let i = buf.length - 22; i >= floor; i--) {
382
+ if (buf.readUInt32LE(i) === 0x06054b50) return i
383
+ }
384
+ throw new Error('不是有效的 ZIP 文件:找不到中央目录结尾记录')
385
+ }
386
+
387
+ /** 读中央目录(解压前先拿到全部条目的名字/大小/压缩方式/偏移)。 */
388
+ function readZipEntries(buf ) {
389
+ const eocd = findEocd(buf)
390
+ const count = buf.readUInt16LE(eocd + 10)
391
+ const cdOffset = buf.readUInt32LE(eocd + 16)
392
+ if (count === 0xffff || cdOffset === 0xffffffff) {
393
+ // 这些哨兵值代表真实信息在 ZIP64 记录里——llama.cpp 的包远没到 4GB,不实现。
394
+ throw new Error('暂不支持 ZIP64 归档')
395
+ }
396
+ const entries = []
397
+ let p = cdOffset
398
+ for (let i = 0; i < count; i++) {
399
+ if (p + 46 > buf.length || buf.readUInt32LE(p) !== 0x02014b50) {
400
+ throw new Error('ZIP 中央目录已损坏(条目签名不匹配或越界)')
401
+ }
402
+ const nameLen = buf.readUInt16LE(p + 28)
403
+ const extraLen = buf.readUInt16LE(p + 30)
404
+ const commentLen = buf.readUInt16LE(p + 32)
405
+ entries.push({
406
+ method: buf.readUInt16LE(p + 10),
407
+ compressedSize: buf.readUInt32LE(p + 20),
408
+ uncompressedSize: buf.readUInt32LE(p + 24),
409
+ offset: buf.readUInt32LE(p + 42),
410
+ name: buf.toString('utf8', p + 46, p + 46 + nameLen),
411
+ })
412
+ p += 46 + nameLen + extraLen + commentLen
413
+ }
414
+ if (entries.length === 0) throw new Error('ZIP 里没有任何条目')
415
+ return entries
416
+ }
417
+
418
+ /** 取一条条目的原始(未压缩)内容。stored/deflate 之外一律明确报错。 */
419
+ function readZipEntryData(buf , entry ) {
420
+ const p = entry.offset
421
+ if (p + 30 > buf.length || buf.readUInt32LE(p) !== 0x04034b50) {
422
+ throw new Error(`ZIP 条目本地头损坏:${entry.name}`)
423
+ }
424
+ // 本地头的 name/extra 长度可能与中央目录不同(历史上被改过 extra),必须按本地头算。
425
+ const nameLen = buf.readUInt16LE(p + 26)
426
+ const extraLen = buf.readUInt16LE(p + 28)
427
+ const start = p + 30 + nameLen + extraLen
428
+ const end = start + entry.compressedSize
429
+ if (end > buf.length) throw new Error(`ZIP 条目数据越界:${entry.name}`)
430
+ const raw = buf.subarray(start, end)
431
+ if (entry.method === 0) return Buffer.from(raw)
432
+ if (entry.method === 8) {
433
+ try {
434
+ return inflateRawSync(raw)
435
+ } catch (error) {
436
+ throw new Error(`解压条目失败:${entry.name}(${describeError(error)})`)
437
+ }
438
+ }
439
+ throw new Error(`不支持的 ZIP 压缩方式:${entry.method}(仅支持 stored=0 / deflate=8)`)
440
+ }
441
+
442
+ function extractZip(buf , destDir ) {
443
+ const entries = readZipEntries(buf)
444
+ // 先按**原始条目名**做一次安全检查:剥掉公共顶层目录之后再看就晚了
445
+ // (`C:/x.txt` 这种绝对路径一剥就变成无害的相对路径了)。
446
+ for (const entry of entries) assertSafeName(entry.name)
447
+ const prefix = commonPrefix(entries.map((entry) => entry.name))
448
+ let written = 0
449
+ for (const entry of entries) {
450
+ const rel = stripPrefix(entry.name, prefix)
451
+ if (rel === '') continue
452
+ // 目录项也要过一遍路径校验:`../` 目录同样不该被静默放行。
453
+ const target = safeTarget(destDir, rel)
454
+ if (rel.endsWith('/')) continue
455
+ const data = readZipEntryData(buf, entry)
456
+ if (data.length !== entry.uncompressedSize) {
457
+ throw new Error(`解压校验失败:${entry.name} 声明 ${entry.uncompressedSize} 字节,实际 ${data.length} 字节`)
458
+ }
459
+ writeFile(target, data)
460
+ written++
461
+ }
462
+ if (written === 0) throw new Error('压缩包里没有任何文件')
463
+ return written
464
+ }
465
+
466
+ // ─────────────────────────── tar.gz ───────────────────────────
467
+
468
+ /**
469
+ * tar.gz 解压:gunzip 之后就是 512 字节头 + 数据的顺序流,没有压缩,顺序读即可。
470
+ * (Linux/macOS 的 llama.cpp 发行包是 .tar.gz,Windows 才是 zip。)
471
+ */
472
+ function extractTarGz(buf , destDir ) {
473
+ let tar
474
+ try {
475
+ tar = gunzipSync(buf)
476
+ } catch (error) {
477
+ throw new Error(`gzip 解压失败:${describeError(error)}`)
478
+ }
479
+ const entries = readTarEntries(tar)
480
+ for (const entry of entries) assertSafeName(entry.name)
481
+ const prefix = commonPrefix(entries.map((entry) => entry.name))
482
+ let written = 0
483
+ for (const entry of entries) {
484
+ const rel = stripPrefix(entry.name, prefix)
485
+ if (rel === '') continue
486
+ const target = safeTarget(destDir, rel)
487
+ if (entry.type === '5' || rel.endsWith('/')) continue
488
+ if (entry.type !== '0' && entry.type !== '\0') continue // 符号链接/硬链接等一律跳过
489
+ writeFile(target, entry.data, entry.mode)
490
+ written++
491
+ }
492
+ if (written === 0) throw new Error('压缩包里没有任何文件')
493
+ return written
494
+ }
495
+
496
+ function readTarEntries(tar ) {
497
+ const entries = []
498
+ let offset = 0
499
+ let longName = null
500
+ while (offset + 512 <= tar.length) {
501
+ const header = tar.subarray(offset, offset + 512)
502
+ if (isZeroBlock(header)) break // 归档结束标记:两个全零块
503
+ const size = readOctal(header, 124, 12)
504
+ const mode = readOctal(header, 100, 8)
505
+ const type = String.fromCharCode(header[156] ?? 0)
506
+ const dataStart = offset + 512
507
+ const dataEnd = dataStart + size
508
+ if (dataEnd > tar.length) throw new Error('tar 归档已损坏(条目数据越界)')
509
+ const namePrefix = readText(header, 345, 155) // ustar 的长路径前缀
510
+ let name = readText(header, 0, 100)
511
+ if (namePrefix !== '') name = `${namePrefix}/${name}`
512
+ if (longName !== null) {
513
+ name = longName
514
+ longName = null
515
+ }
516
+ const next = dataStart + pad512(size)
517
+ if (type === 'L') {
518
+ // GNU 长文件名:这一条的数据就是下一条的名字。
519
+ longName = tar.toString('utf8', dataStart, dataEnd).replace(/\0+$/, '')
520
+ offset = next
521
+ continue
522
+ }
523
+ if (type === 'x' || type === 'g') {
524
+ // pax 扩展头(含 UTF-8 路径等元数据):忽略内容,不影响普通条目。
525
+ offset = next
526
+ continue
527
+ }
528
+ entries.push({
529
+ name,
530
+ size,
531
+ type,
532
+ mode,
533
+ linkName: readText(header, 157, 100),
534
+ data: tar.subarray(dataStart, dataEnd),
535
+ })
536
+ offset = next
537
+ }
538
+ if (entries.length === 0) throw new Error('tar 归档里没有任何条目')
539
+ return entries
540
+ }
541
+
542
+ function isZeroBlock(block ) {
543
+ for (const byte of block) {
544
+ if (byte !== 0) return false
545
+ }
546
+ return true
547
+ }
548
+
549
+ /** tar 的数字字段是八进制 ASCII;GNU 的大文件用 base-256(首字节最高位为 1)。 */
550
+ function readOctal(buf , offset , length ) {
551
+ const first = buf[offset]
552
+ if (first !== undefined && (first & 0x80) !== 0) {
553
+ let value = first & 0x7f
554
+ for (let i = 1; i < length; i++) value = value * 256 + (buf[offset + i] ?? 0)
555
+ return value
556
+ }
557
+ const text = buf.toString('latin1', offset, offset + length).replace(/\0/g, ' ').trim()
558
+ const value = Number.parseInt(text, 8)
559
+ return Number.isFinite(value) ? value : 0
560
+ }
561
+
562
+ function readText(buf , offset , length ) {
563
+ return buf.toString('utf8', offset, offset + length).replace(/\0.*$/, '').trim()
564
+ }
565
+
566
+ function pad512(size ) {
567
+ return Math.ceil(size / 512) * 512
568
+ }
569
+
570
+ // ─────────────────────── 路径安全 / 小工具 ───────────────────────
571
+
572
+ /**
573
+ * 压缩包里所有条目共享的第一段目录(如 `llama-b11429/`),没有就返回 ''。
574
+ * 剥掉它,解压结果才是「llamacpp/ 下直接躺着 llama-server.exe」这种既有布局;
575
+ * 只有当**每一条**都带这个前缀时才剥,避免误伤顶层散落的文件。
576
+ */
577
+ function commonPrefix(names ) {
578
+ const first = names[0]
579
+ if (first === undefined) return ''
580
+ const cut = first.indexOf('/')
581
+ if (cut <= 0) return ''
582
+ const head = first.slice(0, cut + 1)
583
+ for (const name of names) {
584
+ if (!name.startsWith(head)) return ''
585
+ }
586
+ return head
587
+ }
588
+
589
+ function stripPrefix(name , prefix ) {
590
+ return prefix !== '' && name.startsWith(prefix) ? name.slice(prefix.length) : name
591
+ }
592
+
593
+ /**
594
+ * 条目名的原始安全检查:绝对路径(`/x`、`C:/x`、`\\server\share`)与任何
595
+ * `..` 段一律拒绝。必须在剥公共顶层目录**之前**做,否则 `C:/x.txt` 会先被
596
+ * 剥成 `x.txt`,检查就形同虚设。
597
+ */
598
+ function assertSafeName(rel ) {
599
+ const clean = rel.replace(/\\/g, '/')
600
+ if (clean.startsWith('/') || /^[A-Za-z]:/.test(clean)) {
601
+ throw new Error(`压缩包条目使用了绝对路径:${rel}`)
602
+ }
603
+ for (const part of clean.split('/')) {
604
+ if (part === '..') throw new Error(`压缩包条目试图跳出安装目录:${rel}`)
605
+ }
606
+ }
607
+
608
+ /**
609
+ * 把条目相对路径解析到 destDir 之内,越界就抛。
610
+ * 压缩包是远端内容,绝对路径与 `..` 段都必须拒绝,否则一个恶意/被篡改的发行
611
+ * 包就能往安装目录外写文件。这里再做一次解析边界校验,兜住拼接层面的意外。
612
+ */
613
+ function safeTarget(destDir , rel ) {
614
+ assertSafeName(rel)
615
+ const root = resolve(destDir)
616
+ const target = resolve(root, rel.replace(/\\/g, '/'))
617
+ if (target !== root && !target.startsWith(root + sep)) {
618
+ throw new Error(`压缩包条目试图跳出安装目录:${rel}`)
619
+ }
620
+ return target
621
+ }
622
+
623
+ function writeFile(target , data , mode ) {
624
+ try {
625
+ mkdirSync(dirname(target), { recursive: true })
626
+ writeFileSync(target, data)
627
+ // tar 保留了权限位:不加这一步,Linux/macOS 上的 llama-server 落地就没有
628
+ // 执行权限,spawn 直接 EACCES。
629
+ if (mode !== undefined && process.platform !== 'win32') chmodSync(target, mode & 0o777)
630
+ } catch (error) {
631
+ throw diskError(`写入 ${target}`, error)
632
+ }
633
+ }
634
+
635
+ function ensureDir(dir , what ) {
636
+ try {
637
+ mkdirSync(dir, { recursive: true })
638
+ } catch (error) {
639
+ throw diskError(what, error)
640
+ }
641
+ }
642
+
643
+ function isFile(path ) {
644
+ try {
645
+ return statSync(path).isFile()
646
+ } catch {
647
+ return false
648
+ }
649
+ }
650
+
651
+ function fileSize(path ) {
652
+ try {
653
+ return statSync(path).size
654
+ } catch {
655
+ return 0
656
+ }
657
+ }
658
+
659
+ function parseContentLength(header ) {
660
+ if (header === null) return null
661
+ const value = Number.parseInt(header, 10)
662
+ return Number.isFinite(value) && value >= 0 ? value : null
663
+ }
664
+
665
+ function isAbortError(error ) {
666
+ if (typeof error !== 'object' || error === null) return false
667
+ return (error ).name === 'AbortError'
668
+ }
669
+
670
+ function describeError(error ) {
671
+ if (error instanceof Error) return error.message
672
+ return String(error)
673
+ }
674
+
675
+ /** 把底层 fs 错误翻译成面板能看懂的话(缺权限 / 磁盘满是最常见的两种)。 */
676
+ function diskError(what , error ) {
677
+ const code = (error )?.code
678
+ const detail = describeError(error)
679
+ if (typeof code === 'string' && ['EACCES', 'EPERM', 'EROFS', 'ENOSPC', 'EBUSY', 'EMFILE', 'ENFILE'].includes(code)) {
680
+ return new Error(`磁盘写入失败(${what}):${detail}`)
681
+ }
682
+ return error instanceof Error ? error : new Error(`${what}:${detail}`)
683
+ }
684
+
685
+ function formatBytes(bytes ) {
686
+ if (bytes < 1024) return `${bytes} B`
687
+ const mb = bytes / (1024 * 1024)
688
+ if (mb < 1024) return `${mb.toFixed(1)} MB`
689
+ return `${(mb / 1024).toFixed(2)} GB`
690
+ }
691
+
692
+ function urlHost(url ) {
693
+ try {
694
+ return new URL(url).host
695
+ } catch {
696
+ return url
697
+ }
698
+ }
699
+
700
+ /** 等一个背压 drain;顺手把流错误也变成 reject,免得卡死。 */
701
+ function waitDrain(stream ) {
702
+ return new Promise((resolve, reject) => {
703
+ const onDrain = () => { cleanup(); resolve() }
704
+ const onError = (error ) => { cleanup(); reject(error) }
705
+ const cleanup = () => {
706
+ stream.off('drain', onDrain)
707
+ stream.off('error', onError)
708
+ }
709
+ stream.once('drain', onDrain)
710
+ stream.once('error', onError)
711
+ })
712
+ }
713
+
714
+ function closeStream(stream ) {
715
+ return new Promise((resolve, reject) => {
716
+ stream.once('error', reject)
717
+ stream.end(() => resolve())
718
+ })
719
+ }
720
+
721
+ // ────────────────────────── 安装器本体 ──────────────────────────
722
+
723
+ /**
724
+ * 下载 + 解压 + 校验。用法(面板按钮):
725
+ * const installer = new VectorInstaller({ root, onProgress: p => render(p) })
726
+ * installer.start() // fire-and-forget,绝不抛
727
+ * installer.cancel() // 中止并清理 .part
728
+ * installer.progress // 随时读快照
729
+ */
730
+ export class VectorInstaller {
731
+ opts
732
+ state = {
733
+ phase: 'idle',
734
+ message: '',
735
+ receivedBytes: 0,
736
+ totalBytes: null,
737
+ error: null,
738
+ paths: null,
739
+ }
740
+ running = false
741
+ cancelled = false
742
+ /** 每轮 cancel 自增:在途 run() 用它判断自己是否已经过期(别再改状态)。 */
743
+ generation = 0
744
+ controller = null
745
+ /** 当前正在写的 .part 与它的流(取消时要立刻销毁,否则 fd 悬着)。 */
746
+ sink = null
747
+
748
+ constructor(opts ) {
749
+ this.opts = opts
750
+ }
751
+
752
+ /** 状态快照(返回副本,调用方改不动内部状态)。 */
753
+ get progress() {
754
+ return { ...this.state }
755
+ }
756
+
757
+ /** 幂等:已在跑、或已装好,直接返回。 */
758
+ start() {
759
+ if (this.running) return
760
+ const installed = detectInstalled(this.opts.root)
761
+ if (installed) {
762
+ this.report(this.generation, {
763
+ phase: 'done',
764
+ message: '向量后端已就绪,无需下载',
765
+ error: null,
766
+ receivedBytes: 0,
767
+ totalBytes: null,
768
+ paths: installed,
769
+ })
770
+ return
771
+ }
772
+ const gen = this.generation
773
+ this.running = true
774
+ this.cancelled = false
775
+ this.controller = new AbortController()
776
+ // 关键:不 await、不 rethrow。start() 的调用方是 UI 事件处理器,
777
+ // 一个未捕获的 rejection 会在宿主里变成 unhandledRejection。
778
+ void this.run(gen)
779
+ .catch((error ) => {
780
+ if (gen !== this.generation || this.cancelled) return
781
+ this.fail(error)
782
+ })
783
+ .finally(() => {
784
+ if (gen === this.generation) {
785
+ this.running = false
786
+ this.controller = null
787
+ }
788
+ })
789
+ }
790
+
791
+ /** 取消:中止在途请求、销毁 .part、phase 回到 idle。没在跑就是 no-op。 */
792
+ cancel() {
793
+ if (!this.running && this.controller === null) return
794
+ this.generation++
795
+ this.cancelled = true
796
+ this.running = false
797
+ const controller = this.controller
798
+ this.controller = null
799
+ controller?.abort()
800
+ this.dropSink()
801
+ this.report(this.generation, {
802
+ phase: 'idle',
803
+ message: '已取消',
804
+ error: null,
805
+ receivedBytes: 0,
806
+ totalBytes: null,
807
+ paths: null,
808
+ })
809
+ }
810
+
811
+ async run(gen ) {
812
+ const root = this.opts.root
813
+ const platform = this.opts.platform ?? process.platform
814
+ const arch = this.opts.arch ?? process.arch
815
+ // 所选模型:不给就是内置的 bge-m3 Q4_K_M(与合并前行为一致)。
816
+ const model = this.opts.model ?? {
817
+ file: MODEL_FILE_NAME,
818
+ bytes: MODEL_SIZE_BYTES,
819
+ ...(this.opts.modelSources ? { sources: this.opts.modelSources } : {}),
820
+ }
821
+ const flavor = this.opts.flavor ?? 'cpu'
822
+ const paths = installPaths(root, model.file)
823
+ try {
824
+ this.setPhase(gen, 'preparing', `准备安装目录 ${root}`)
825
+ ensureDir(root, '创建安装根目录')
826
+ ensureDir(paths.dir, '创建运行时目录')
827
+ ensureDir(dirname(paths.model), '创建模型目录')
828
+
829
+ const asset = await this.resolveRuntimeAsset(gen, platform, arch, flavor)
830
+ const archivePath = join(paths.dir, asset.name)
831
+ if (fileSize(archivePath) > 0) {
832
+ // 上轮下完但解压/下模型失败:压缩包还在,别白下第二遍。
833
+ this.setPhase(gen, 'downloading-runtime', `已存在 ${asset.name},跳过下载`, { receivedBytes: 0, totalBytes: null })
834
+ } else {
835
+ this.setPhase(gen, 'downloading-runtime', `正在下载 llama.cpp 运行时 ${asset.name}`)
836
+ const got = await this.downloadFrom(gen, runtimeDownloadSources(asset), archivePath, 'llama.cpp 运行时', 'downloading-runtime', '通道')
837
+ // 成功日志里写清走的哪条通道:直链还是 API 资产端点,排障时第一眼要看的就是它。
838
+ this.report(gen, { message: `运行时下载完成(${formatBytes(got.bytes)},通道:${got.source.label})` })
839
+ }
840
+
841
+ this.setPhase(gen, 'extracting', `正在解压 ${asset.name}`)
842
+ let archive
843
+ try {
844
+ archive = readFileSync(archivePath)
845
+ } catch (error) {
846
+ throw diskError(`读取 ${archivePath}`, error)
847
+ }
848
+ let written
849
+ try {
850
+ written = extractArchive(archive, paths.dir)
851
+ } catch (error) {
852
+ // 解压失败说明压缩包本身坏了:删掉它,下次点击会重新下载,
853
+ // 而不是每次都撞同一个坏文件(.part 早就没了,这个包是「完整但损坏」)。
854
+ try { rmSync(archivePath, { force: true }) } catch { /* 尽力而为 */ }
855
+ throw error
856
+ }
857
+ // CUDA 风味:主包只有 llama-server 本体,cuBLAS/cudart 在**另一个**资产里,
858
+ // 两个包必须来自同一套工具链(靠 cuda 次版本号配对),所以一起下一起解压。
859
+ const companion = await this.resolveRuntimeCompanion(gen, platform, arch, flavor)
860
+ if (companion !== null) {
861
+ const companionPath = join(paths.dir, companion.name)
862
+ if (fileSize(companionPath) === 0) {
863
+ this.setPhase(gen, 'downloading-runtime', `正在下载 CUDA 运行库 ${companion.name}`)
864
+ const got = await this.downloadFrom(gen, runtimeDownloadSources(companion), companionPath, 'CUDA 运行库', 'downloading-runtime', '通道')
865
+ this.report(gen, { message: `CUDA 运行库下载完成(${formatBytes(got.bytes)},通道:${got.source.label})` })
866
+ }
867
+ try {
868
+ written += extractArchive(readFileSync(companionPath), paths.dir)
869
+ } catch (error) {
870
+ try { rmSync(companionPath, { force: true }) } catch { /* 尽力而为 */ }
871
+ throw error
872
+ }
873
+ }
874
+ if (!existsSync(paths.exe)) {
875
+ throw new Error(`解压完成但没找到 ${basename(paths.exe)}:${asset.name} 的目录结构可能变了`)
876
+ }
877
+ if (platform !== 'win32') {
878
+ // tar 的权限位在大多数归档里是齐的,这里再兜一次底。
879
+ try { chmodSync(paths.exe, 0o755) } catch { /* 尽力而为 */ }
880
+ }
881
+ this.setPhase(gen, 'extracting', `已解压 ${written} 个文件`)
882
+
883
+ if (fileSize(paths.model) > 0) {
884
+ // 模型几百 MB 起步,重下一次代价太大:已经在就直接用。
885
+ this.setPhase(gen, 'downloading-model', '模型已存在,跳过下载', { receivedBytes: 0, totalBytes: null })
886
+ } else {
887
+ this.setPhase(gen, 'downloading-model', `正在下载 ${model.file}${model.bytes !== undefined ? `(约 ${formatBytes(model.bytes)})` : ''}`)
888
+ const got = await this.downloadModel(gen, paths.model, model)
889
+ this.report(gen, { message: `模型下载完成(已下载 ${formatBytes(got.bytes)},来源:${got.source.label})` })
890
+ }
891
+
892
+ const installed = detectInstalled(root, model.file)
893
+ if (installed === null) throw new Error('安装校验失败:llama-server 或模型文件缺失')
894
+ this.report(gen, {
895
+ phase: 'done',
896
+ message: `安装完成:模型 ${formatBytes(fileSize(installed.model))},运行时 ${basename(installed.exe)}`,
897
+ error: null,
898
+ receivedBytes: 0,
899
+ totalBytes: null,
900
+ paths: installed,
901
+ })
902
+ } catch (error) {
903
+ // 取消不是错误:清掉半成品,回到 idle(面板据此把进度条收起来)。
904
+ if (this.cancelled || gen !== this.generation || isAbortError(error)) {
905
+ if (this.sink?.gen === gen) this.dropSink()
906
+ this.setPhase(gen, 'idle', '已取消')
907
+ return
908
+ }
909
+ throw error
910
+ }
911
+ }
912
+
913
+ /**
914
+ * 查发行版列表 → 按平台 + 风味挑包。latest 不可用(见下),按时间倒序取第一个命中的。
915
+ *
916
+ * 风味包找不到时**退回 CPU 包**并说明原因:装得上但慢,好过装不上。
917
+ */
918
+ async resolveRuntimeAsset(
919
+ gen ,
920
+ platform ,
921
+ arch ,
922
+ flavor ,
923
+ ) {
924
+ const pattern = runtimeAssetPattern(platform, arch, flavor)
925
+ const label = `${platform}-${arch} ${flavor}`
926
+ this.report(gen, { message: `正在查询 llama.cpp 最新构建(${label})` })
927
+ // 注意:不要用 /releases/latest。llama.cpp 的 b#### 构建线全部带
928
+ // prerelease:true,而 latest 只认正式版,现在返回的是一个与本项目无关的
929
+ // v0.6.0(资产只有 nightly-tag.txt)——照它匹配必然失败。正确做法是拉倒序
930
+ // 列表,取第一个含匹配资产的 release(prerelease 与否无关)。
931
+ const releases = await this.fetchJson(RELEASES_API, '查询 llama.cpp 发行版')
932
+ if (!Array.isArray(releases)) throw new Error('llama.cpp 发行版接口返回的数据格式异常')
933
+ const wanted = flavor === 'metal' ? 'cpu' : flavor
934
+ const hit = findAssetInReleases(releases, pattern)
935
+ if (hit !== null) return hit
936
+ if (wanted !== 'cpu') {
937
+ const fallback = findAssetInReleases(releases, runtimeAssetPattern(platform, arch, 'cpu'))
938
+ if (fallback !== null) {
939
+ this.report(gen, {
940
+ message: `最近 20 个发行版里没有 ${wanted} 运行时(匹配 ${String(pattern)}),已改用 CPU 运行时;想在 GPU 上跑可以自己装好再把 spawn.exe 指过去`,
941
+ })
942
+ return fallback
943
+ }
944
+ }
945
+ throw new Error(`资产匹配失败:${label}(最近 20 个发行版里没有匹配 ${String(pattern)} 的包)`)
946
+ }
947
+
948
+ /** CUDA 风味的 cudart 伴随包;非 cuda 或无匹配返回 null(不阻塞安装)。 */
949
+ async resolveRuntimeCompanion(
950
+ gen ,
951
+ platform ,
952
+ arch ,
953
+ flavor ,
954
+ ) {
955
+ const pattern = runtimeCompanionPattern(platform, arch, flavor)
956
+ if (pattern === null) return null
957
+ const releases = await this.fetchJson(RELEASES_API, '查询 llama.cpp 发行版')
958
+ if (!Array.isArray(releases)) return null
959
+ const hit = findAssetInReleases(releases, pattern)
960
+ if (hit === null) {
961
+ this.report(gen, { message: `没有找到 CUDA 运行库(匹配 ${String(pattern)}):llama-server 可能起不来,可改用 Vulkan 或 CPU 运行时` })
962
+ }
963
+ return hit
964
+ }
965
+
966
+ /** 模型下载:多源顺序回退(noun 只影响报错文案)。 */
967
+ async downloadModel(gen , dest , model ) {
968
+ const urls = model.sources ?? this.opts.modelSources ?? MODEL_SOURCES
969
+ const sources = urls.map((url) => ({ url, accept: '*/*', label: urlHost(url) }))
970
+ return this.downloadFrom(gen, sources, dest, model.file, 'downloading-model', '源')
971
+ }
972
+
973
+ /**
974
+ * 按候选顺序下载,当前候选失败(网络错误 / 非 2xx / 中途断流)就换下一个,
975
+ * 每个候选都从 0 重新下(不做断点续传,失败时 download() 已经清掉 .part)。
976
+ * 全部失败时把所有候选各自的原因一起报出来——只报一句「下载失败」的话,用户
977
+ * 根本分不清是墙、是 DNS、还是磁盘满。
978
+ */
979
+ async downloadFrom(
980
+ gen ,
981
+ sources ,
982
+ dest ,
983
+ what ,
984
+ phase ,
985
+ noun ,
986
+ ) {
987
+ const failures = []
988
+ for (const source of sources) {
989
+ try {
990
+ const bytes = await this.download(gen, source, dest, what, phase)
991
+ return { bytes, source }
992
+ } catch (error) {
993
+ if (this.cancelled || isAbortError(error)) throw error
994
+ const reason = describeError(error)
995
+ const host = urlHost(source.url)
996
+ // 通道名里已经含主机名(模型源就是这么标的)时不要重复一遍。
997
+ const who = source.label.includes(host) ? source.label : `${source.label}(${host})`
998
+ failures.push(`${who}:${reason}`)
999
+ this.report(gen, {
1000
+ message: `${who} 下载失败(${reason}),换下一个${noun}重试`,
1001
+ receivedBytes: 0,
1002
+ totalBytes: null,
1003
+ })
1004
+ }
1005
+ }
1006
+ if (failures.length === 0) throw new Error(`下载${what}失败:没有配置任何下载${noun}`)
1007
+ throw new Error(`下载${what}失败:所有${noun}都失败\n${failures.map((line) => ` - ${line}`).join('\n')}`)
1008
+ }
1009
+
1010
+ /**
1011
+ * 流式下载到 dest:先写 `<dest>.part`,完整收流后 rename。
1012
+ * 每收到一块就上报一次 receivedBytes(面板的百分比来源)。
1013
+ */
1014
+ async download(
1015
+ gen ,
1016
+ source ,
1017
+ dest ,
1018
+ what ,
1019
+ phase ,
1020
+ ) {
1021
+ const url = source.url
1022
+ const part = `${dest}.part`
1023
+ const res = await this.request(url, source.accept)
1024
+ if (!res.ok) {
1025
+ throw new Error(`下载${what}失败:HTTP ${res.status}${res.statusText !== '' ? ` ${res.statusText}` : ''}(${url})`)
1026
+ }
1027
+ const total = parseContentLength(res.headers.get('content-length')) // 拿不到就是 null
1028
+ const body = res.body
1029
+ if (body === null) throw new Error(`下载${what}失败:响应没有可读的数据流`)
1030
+ const reader = body.getReader()
1031
+ const stream = createWriteStream(part, { flags: 'w' })
1032
+ this.sink = { gen, part, stream }
1033
+ // 用容器而不是裸 let:错误在回调里赋值、在循环里读,容器能让 TS 的类型收窄
1034
+ // 保持可预测(裸 let 在闭包里赋值后收窄会被重置/变 never)。
1035
+ const failure = { error: null }
1036
+ stream.on('error', (error) => { failure.error = error })
1037
+ let received = 0
1038
+ try {
1039
+ for (;;) {
1040
+ const chunk = await reader.read()
1041
+ if (chunk.done) break
1042
+ const value = chunk.value
1043
+ if (value === undefined || value.byteLength === 0) continue
1044
+ received += value.byteLength
1045
+ if (!stream.write(value)) await waitDrain(stream)
1046
+ if (failure.error !== null) throw failure.error
1047
+ this.report(gen, { phase, receivedBytes: received, totalBytes: total, error: null })
1048
+ }
1049
+ await closeStream(stream)
1050
+ if (failure.error !== null) throw failure.error
1051
+ } catch (error) {
1052
+ try { stream.destroy() } catch { /* 已经坏了 */ }
1053
+ try { rmSync(part, { force: true }) } catch { /* 尽力而为 */ }
1054
+ if (this.sink?.part === part) this.sink = null
1055
+ // 写盘失败(磁盘满/无权限)要说得明白,别把 ERR_STREAM 之类的丢给用户。
1056
+ if (failure.error !== null && !isAbortError(error)) throw diskError(`写入 ${part}`, failure.error)
1057
+ throw error
1058
+ }
1059
+ try {
1060
+ renameSync(part, dest)
1061
+ } catch (error) {
1062
+ if (this.sink?.part === part) this.sink = null
1063
+ throw diskError(`重命名 ${dest}`, error)
1064
+ }
1065
+ if (this.sink?.part === part) this.sink = null
1066
+ this.report(gen, { phase, receivedBytes: received, totalBytes: total, error: null })
1067
+ return received
1068
+ }
1069
+
1070
+ /** 发一个带 UA 的请求;网络层错误翻译成人话,但 AbortError 原样上抛。 */
1071
+ async request(url , accept ) {
1072
+ const impl = this.opts.fetchImpl ?? fetch
1073
+ const signal = this.requestSignal()
1074
+ try {
1075
+ return await impl(url, { headers: { accept, 'user-agent': USER_AGENT }, signal, redirect: 'follow' })
1076
+ } catch (error) {
1077
+ if (isAbortError(error)) throw error
1078
+ throw new Error(`网络请求失败(${urlHost(url)}):${describeError(error)}`)
1079
+ }
1080
+ }
1081
+
1082
+ async fetchJson(url , what ) {
1083
+ const res = await this.request(url, 'application/vnd.github+json')
1084
+ if (res.status === 403 || res.status === 429) {
1085
+ throw new Error('GitHub API 限流(未认证请求每小时 60 次),请稍后重试')
1086
+ }
1087
+ if (!res.ok) throw new Error(`${what}失败:HTTP ${res.status}(${url})`)
1088
+ try {
1089
+ return await res.json()
1090
+ } catch (error) {
1091
+ throw new Error(`${what}返回的不是合法 JSON:${describeError(error)}`)
1092
+ }
1093
+ }
1094
+
1095
+ /** 自带 controller + 调用方 signal 的合并信号。 */
1096
+ requestSignal() {
1097
+ const external = this.opts.signal
1098
+ const controller = this.controller
1099
+ if (controller === null) return external ?? new AbortController().signal
1100
+ return external === undefined ? controller.signal : AbortSignal.any([controller.signal, external])
1101
+ }
1102
+
1103
+ /** 销毁在途的 .part 流并删文件(取消路径)。 */
1104
+ dropSink() {
1105
+ const sink = this.sink
1106
+ this.sink = null
1107
+ if (sink === null) return
1108
+ try { sink.stream.destroy() } catch { /* 已经坏了 */ }
1109
+ try { rmSync(sink.part, { force: true }) } catch { /* 尽力而为 */ }
1110
+ }
1111
+
1112
+ fail(error ) {
1113
+ this.dropSink()
1114
+ const message = describeError(error)
1115
+ this.report(this.generation, {
1116
+ phase: 'error',
1117
+ message,
1118
+ error: message,
1119
+ totalBytes: null,
1120
+ paths: detectInstalled(this.opts.root),
1121
+ })
1122
+ }
1123
+
1124
+ /** 状态上报;gen 过期(已被 cancel 顶掉)就整条丢掉,不污染新一轮。 */
1125
+ report(gen , patch ) {
1126
+ if (gen !== this.generation) return
1127
+ this.state = { ...this.state, ...patch }
1128
+ const listener = this.opts.onProgress
1129
+ if (listener === undefined) return
1130
+ try {
1131
+ listener({ ...this.state })
1132
+ } catch {
1133
+ // 面板回调自己出错,不能把安装带崩
1134
+ }
1135
+ }
1136
+
1137
+ /** 切阶段:进度一律清零,免得面板把上一个文件的字节数算到新阶段头上。 */
1138
+ setPhase(gen , phase , message , extra = {}) {
1139
+ this.report(gen, { phase, message, error: null, receivedBytes: 0, totalBytes: null, ...extra })
1140
+ }
1141
+ }
1142
+
1143
+
1144
+ //# sourceURL=source/memory-local/src/embed-install.ts