dsh-memu-memory 1.2.3 → 1.2.4

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.
@@ -0,0 +1,152 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import http from 'node:http'
4
+
5
+ // drive-session 之前一条测试都没有,于是它的 RPC envelope 一直是错的:网关按**参数名**包参数,
6
+ // 单参数 remote 必须是 `{ args: { request: … } }`,直接铺请求字段会在到达宿主前被拒
7
+ // (gateway/arguments-invalid: missing "request")。第一次真机对接才暴露。这里钉住形状。
8
+ const mod = await import('../scripts/drive-session.mjs')
9
+
10
+ test('the prompt envelope names the remote parameter, as the gateway carrier requires', () => {
11
+ const request = {
12
+ requestId: 'memu-eval-x-001-ab',
13
+ sessionId: 'session-1',
14
+ mode: 'queue',
15
+ content: [{ type: 'text', text: '你还记得林眠的相机吗?' }],
16
+ clientTimeZone: 'Asia/Shanghai',
17
+ }
18
+ const envelope = mod.buildPromptEnvelope(request, 'rpc-1')
19
+ assert.equal(envelope.type, 'client-request')
20
+ assert.equal(envelope.rpcId, 'rpc-1')
21
+ assert.equal(envelope.method, 'session/prompt')
22
+ assert.deepEqual(envelope.payload, { args: { request } })
23
+ // 铺平发送会被宿主拒绝:这条断言就是那个 bug 的回归。
24
+ assert.notDeepEqual(envelope.payload.args, request)
25
+ assert.equal(envelope.payload.args.request, request)
26
+
27
+ const auto = mod.buildPromptEnvelope(request)
28
+ assert.match(auto.rpcId, /^[0-9a-f-]{36}$/, 'each send needs its own correlation id')
29
+ assert.notEqual(auto.rpcId, mod.buildPromptEnvelope(request).rpcId)
30
+ })
31
+
32
+ test('request builders give every turn one identity and cycle the prompts', () => {
33
+ const requests = mod.buildRequests({
34
+ sessionId: 'session-9',
35
+ turns: 5,
36
+ prompts: ['第一条', '第二条'],
37
+ clientTimeZone: 'UTC',
38
+ })
39
+ assert.equal(requests.length, 5)
40
+ assert.deepEqual(requests.map((item) => item.turn), [1, 2, 3, 4, 5])
41
+ assert.deepEqual(requests.map((item) => item.request.content[0].text),
42
+ ['第一条', '第二条', '第一条', '第二条', '第一条'])
43
+ assert.equal(new Set(requests.map((item) => item.requestId)).size, 5, 'requestIds must never repeat')
44
+ for (const item of requests) {
45
+ assert.equal(item.request.sessionId, 'session-9')
46
+ assert.equal(item.request.mode, 'queue')
47
+ assert.equal(item.request.clientTimeZone, 'UTC')
48
+ // 日志匹配用的 id 和发出去的 id 必须同源,否则轮次永远判不出完成。
49
+ assert.equal(item.requestId, item.request.requestId)
50
+ }
51
+ })
52
+
53
+ test('completion is read from the transcript, not from an accepted response', () => {
54
+ const requestId = 'memu-eval-run-001-ab'
55
+ const admitted = [{ type: 'agent/inbox/spliced', data: { inserted: [{ source: { rpcId: requestId } }] } }]
56
+ assert.equal(mod.promptAdmitted(admitted, requestId), true, 'a spliced inbox item proves the host took the prompt')
57
+ assert.equal(mod.promptAdmitted([], requestId), false)
58
+ assert.equal(mod.promptAdmitted(admitted, 'other-id'), false)
59
+
60
+ const events = [
61
+ ...admitted,
62
+ { type: 'turn/start', data: { turn: 7 } },
63
+ { type: 'user/message', data: { source: { rpcId: requestId } } },
64
+ { type: 'step/end', data: {} },
65
+ ]
66
+ const claim = mod.promptClaimIndex(events, requestId)
67
+ assert.equal(claim, 2, 'the newest claim for this requestId wins')
68
+ assert.equal(mod.enclosingTurn(events, claim), 7, 'the turn that opened before the claim is the one to wait for')
69
+ // 一条已结束的回合之后再来消息,不属于任何还在跑的回合。
70
+ const after = [...events, { type: 'turn/end', data: { reason: { kind: 'completed' } } },
71
+ { type: 'user/message', data: { source: { rpcId: 'next-id' } } }]
72
+ assert.equal(mod.promptClaimIndex(after, 'next-id'), after.length - 1)
73
+ assert.equal(mod.enclosingTurn(after, after.length - 1), null, 'turn/end closes the window')
74
+ assert.equal(mod.enclosingTurn(events, 0), null, 'nothing encloses a claim with no turn/start before it')
75
+ })
76
+
77
+ test('path segments are encoded so any session id maps to one directory', () => {
78
+ assert.equal(mod.encodeSegment('plain-Name_1.2'), 'plain-Name_1.2')
79
+ assert.equal(mod.encodeSegment('a/b'), 'a~002Fb')
80
+ assert.equal(mod.encodeSegment('a~b'), 'a~007Eb')
81
+ assert.notEqual(mod.encodeSegment('a/b'), mod.encodeSegment('a_b'), 'separators must not collide with names')
82
+ })
83
+
84
+ test('prompt text is read from every accepted text-file shape', () => {
85
+ assert.equal(mod.textOfPromptItem(' 一条 ', 0), '一条')
86
+ assert.equal(mod.textOfPromptItem({ text: 'A' }, 0), 'A')
87
+ assert.equal(mod.textOfPromptItem({ prompt: 'B' }, 1), 'B')
88
+ assert.equal(mod.textOfPromptItem({ content: [{ type: 'text', text: 'C' }, { type: 'text', text: 'D' }] }, 2), 'C\nD')
89
+ assert.throws(() => mod.textOfPromptItem(42, 3), /not a string or object/)
90
+ })
91
+
92
+ // 传输层连错两次(参数没按名字包、返回体引用了不存在的变量),因为一直没有东西真的跑过
93
+ // sendPrompt。用一个 loopback 假网关把它钉住:请求形状、cookie 透传、相关 id 校验、401 提示。
94
+ async function fakeGateway(handler) {
95
+ const server = http.createServer((req, res) => {
96
+ let raw = ''
97
+ req.on('data', (chunk) => { raw += chunk })
98
+ req.on('end', () => handler({ raw, body: JSON.parse(raw), req, res }))
99
+ })
100
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
101
+ return { base: `http://127.0.0.1:${server.address().port}`, close: () => new Promise((resolve) => server.close(resolve)) }
102
+ }
103
+
104
+ test('sendPrompt sends the named-parameter envelope the gateway accepts', async () => {
105
+ const seen = []
106
+ const gateway = await fakeGateway(({ body, req, res }) => {
107
+ seen.push({ body, cookie: req.headers.cookie })
108
+ res.writeHead(200, { 'content-type': 'application/json' })
109
+ res.end(JSON.stringify({ type: 'server-response', rpcId: body.rpcId, result: { ok: true, value: { accepted: true } } }))
110
+ })
111
+ const request = { requestId: 'r-1', sessionId: 'session-1', mode: 'queue', content: [{ type: 'text', text: '第一条' }] }
112
+ try {
113
+ const out = await mod.sendPrompt({ base: gateway.base, request, timeoutMs: 5000, cookie: 'dsh-auth=abc' })
114
+ assert.equal(typeof out.rpcId, 'string', 'the correlation id comes back from the envelope that was actually sent')
115
+ assert.equal(seen[0].body.type, 'client-request')
116
+ assert.equal(seen[0].body.method, 'session/prompt')
117
+ assert.deepEqual(seen[0].body.payload.args.request, request, 'the remote parameter must be named "request"')
118
+ assert.equal(seen[0].cookie, 'dsh-auth=abc', 'the host session cookie is forwarded')
119
+ } finally {
120
+ await gateway.close()
121
+ }
122
+ })
123
+
124
+ test('sendPrompt refuses an unrelated response and says what a 401 needs', async () => {
125
+ const mismatched = await fakeGateway(({ res }) => {
126
+ res.writeHead(200, { 'content-type': 'application/json' })
127
+ res.end(JSON.stringify({ type: 'server-response', rpcId: 'not-the-same', result: { ok: true, value: { accepted: true } } }))
128
+ })
129
+ await assert.rejects(
130
+ mod.sendPrompt({ base: mismatched.base, request: { requestId: 'r' }, timeoutMs: 5000 }),
131
+ /matching Connection RPC envelope/,
132
+ )
133
+ await mismatched.close()
134
+
135
+ const unauthorized = await fakeGateway(({ res }) => { res.writeHead(401); res.end('unauthorized') })
136
+ await assert.rejects(
137
+ mod.sendPrompt({ base: unauthorized.base, request: { requestId: 'r' }, timeoutMs: 5000 }),
138
+ /--cookie-file/,
139
+ 'a 401 has to name the fix, not just the status'
140
+ )
141
+ await unauthorized.close()
142
+
143
+ const rejected = await fakeGateway(({ body, res }) => {
144
+ res.writeHead(200, { 'content-type': 'application/json' })
145
+ res.end(JSON.stringify({ type: 'server-response', rpcId: body.rpcId, result: { ok: false, error: { code: 'gateway/arguments-invalid', message: 'missing "request"' } } }))
146
+ })
147
+ await assert.rejects(
148
+ mod.sendPrompt({ base: rejected.base, request: { requestId: 'r' }, timeoutMs: 5000 }),
149
+ /gateway\/arguments-invalid/,
150
+ )
151
+ await rejected.close()
152
+ })
@@ -6,6 +6,7 @@ import {
6
6
  PROVIDER_ORDER,
7
7
  getEmbeddingCatalog,
8
8
  getEmbeddingModel,
9
+ prefixesRequireRole,
9
10
  profileFingerprint,
10
11
  readOnnxGraphHeader,
11
12
  resolveEmbeddingSources,
@@ -61,12 +62,79 @@ test('目录是冻结的只读快照,未知 id 返回 null 而不是默认模
61
62
  assert.ok(Object.isFrozen(catalog))
62
63
  assert.ok(Object.isFrozen(catalog[0]))
63
64
  assert.throws(() => { catalog.push({ id: 'x' }) }, TypeError)
64
- assert.deepEqual(catalog.map(entry => entry.id), [BGE, 'all-minilm-l6-v2-int8', 'multilingual-e5-small'])
65
+ assert.deepEqual(catalog.map(entry => entry.id), [
66
+ BGE, 'all-minilm-l6-v2-int8', 'multilingual-e5-small', 'qwen3-embedding-0.6b-int8', 'qwen3-embedding-0.6b-q4f16',
67
+ ])
65
68
  assert.equal(getEmbeddingModel('nope'), null)
66
69
  assert.equal(getEmbeddingModel(undefined), null)
67
70
  assert.equal(getEmbeddingModel('../../etc/passwd'), null)
68
71
  })
69
72
 
73
+ test('三个模型的向量空间指纹钉死:改目录必须是有意识地来这里更新', () => {
74
+ assert.deepEqual(
75
+ Object.fromEntries(getEmbeddingCatalog().map(entry => [entry.id, entry.profileFingerprint])),
76
+ {
77
+ 'bge-small-zh-v1.5-int8': '47511436d7468fa53b17dbd46d5dfd1454dbca9a70f34dc016c3af0a9decd748',
78
+ 'all-minilm-l6-v2-int8': '2ede97e232225e6e6a14d9b0ef870fe8cc5ba5ac6273ae9a6da8263c314b4082',
79
+ 'multilingual-e5-small': '4826773bf4a498168decd66edcef48e66befb982c3c60405a1416fb3fd0c5fcb',
80
+ 'qwen3-embedding-0.6b-int8': '0934c5b89781cea545ba40f87b1bc0a9e9eb5a95cdde20390953f3642bd386bb',
81
+ 'qwen3-embedding-0.6b-q4f16': 'a987005b6c033a3e2fdb7502836d73d6376bf8c15ea3c10be60ea0ca63a0a030',
82
+ },
83
+ )
84
+ })
85
+
86
+ // int8 与 int4 是两种量化、两个向量空间(quantization 进指纹),所以必须是两张卡片、
87
+ // 两份 DB,而不是一个条目挂两个图文件让用户以为可以混用。
88
+ test('Qwen3 的两张卡片是两个不同的向量空间', () => {
89
+ const int8 = getEmbeddingModel('qwen3-embedding-0.6b-int8')
90
+ const q4 = getEmbeddingModel('qwen3-embedding-0.6b-q4f16')
91
+ assert.notEqual(int8.profileFingerprint, q4.profileFingerprint)
92
+ assert.equal(int8.quantization.weights, 'qint8')
93
+ assert.equal(int8.quantization.scheme, 'dynamic-per-tensor')
94
+ assert.equal(q4.quantization.weights, 'uint4-nbits')
95
+ assert.notEqual(q4.quantization.scheme, int8.quantization.scheme)
96
+ for (const entry of [int8, q4]) {
97
+ assert.equal(entry.availability, 'available', entry.id)
98
+ assert.equal(entry.pooling, 'last', entry.id)
99
+ assert.equal(entry.dimension, 1024, entry.id)
100
+ assert.equal(entry.graph.opset, 21, entry.id)
101
+ // 因果 LM:只有 input_ids + attention_mask,没有 token_type_ids
102
+ assert.deepEqual(entry.graph.inputs.map(io => io.name), ['input_ids', 'attention_mask'], entry.id)
103
+ assert.deepEqual(entry.graph.outputs[0].shape, [1, 'sequence_length', 1024], entry.id)
104
+ // 32k 上下文的制品按 4096 分窗:刻意的延迟策略(不得超过制品上限,那条由下载器的
105
+ // verifyStagedArtifacts 把),窗口本身进指纹所以可复现。
106
+ assert.equal(entry.maxTokens, 4096, entry.id)
107
+ assert.ok(validateEmbeddingManifest(entry).errors.length === 0, entry.id)
108
+ }
109
+ assert.equal(int8.graph.outputs[0].dtype, 'float32')
110
+ assert.equal(q4.graph.outputs[0].dtype, 'float16')
111
+ assert.equal(int8.tier, 'preferred')
112
+ assert.equal(q4.tier, 'optional')
113
+ })
114
+
115
+ // Qwen3 的导出仓库在 ModelScope 上没有对应条目,所以它只能走 huggingface 系:
116
+ // 默认镜像站,源站作第二顺位;两者 pin 同一个 commit,落盘都按同一份 sha256 校。
117
+ test('Qwen3 卡片的默认来源是 hf-mirror,源站同 commit 可选', () => {
118
+ for (const id of ['qwen3-embedding-0.6b-int8', 'qwen3-embedding-0.6b-q4f16']) {
119
+ const resolved = resolveEmbeddingSources(id)
120
+ assert.deepEqual(resolved.sources.map(source => source.provider), ['hf-mirror', 'huggingface'], id)
121
+ assert.equal(resolved.primary.provider, 'hf-mirror', id + ' 默认必须是镜像站')
122
+ assert.deepEqual(resolved.skipped.map(item => item.provider), ['modelscope'], id)
123
+ assert.equal(resolved.skipped[0].reason, 'not-mapped', id)
124
+ const revision = getEmbeddingModel(id).sources['hf-mirror'].revision
125
+ assert.equal(getEmbeddingModel(id).sources.huggingface.revision, revision, id + ' 两个来源必须同 commit')
126
+ const mirrorGraph = resolved.primary.files.find(file => file.role === 'graph')
127
+ const originGraph = resolveEmbeddingSources(id, { providers: ['huggingface'] }).primary.files.find(file => file.role === 'graph')
128
+ assert.ok(mirrorGraph.url.startsWith('https://hf-mirror.com/n24q02m/'), mirrorGraph.url)
129
+ assert.ok(originGraph.url.startsWith('https://huggingface.co/n24q02m/'), originGraph.url)
130
+ assert.equal(mirrorGraph.sha256, originGraph.sha256, id)
131
+ // 见证制品来自基座仓库,且两个 provider 都合法(否则换源会被 origin 规则整条封掉)
132
+ const pooling = resolveEmbeddingSources(id, { providers: ['huggingface'] }).primary.files.find(file => file.path === '1_Pooling/config.json')
133
+ assert.ok(pooling.url.includes('/Qwen/Qwen3-Embedding-0.6B/'), pooling.url)
134
+ assert.equal(validateEmbeddingManifest(getEmbeddingModel(id)).warnings.filter(item => item.code === 'SOURCE_REVISION_UNPINNED').length, 0, id)
135
+ }
136
+ })
137
+
70
138
  test('首个 BGE 条目带着已核实的固定 commit、逐文件字节数与 SHA-256', () => {
71
139
  const entry = getEmbeddingModel(BGE)
72
140
  assert.equal(entry.availability, 'available')
@@ -105,19 +173,59 @@ test('已核实的 BGE manifest 通过校验,但把未核实项如实标成警
105
173
  assert.equal(codes.filter(code => code === 'SOURCE_REVISION_UNPINNED').length, 2)
106
174
  })
107
175
 
108
- test('未核实模型是 pending:没有文件、没有哈希、理由齐全', () => {
176
+ test('MiniLM 与 e5 已核实:制品齐全、清单合法、来源可下载', () => {
109
177
  for (const id of ['all-minilm-l6-v2-int8', 'multilingual-e5-small']) {
110
178
  const entry = getEmbeddingModel(id)
111
- assert.equal(entry.availability, 'pending')
112
- assert.deepEqual(entry.files, [])
113
- assert.equal(entry.totalBytes, 0)
114
- assert.ok(entry.pendingReasons.length >= 2)
179
+ assert.equal(entry.availability, 'available', id)
180
+ assert.deepEqual(entry.pendingReasons, [], id)
181
+ assert.equal(entry.verification.status, 'verified', id)
182
+ assert.match(entry.sources.modelscope.revision, /^[0-9a-f]{40}$/, id + ' revision')
183
+ assert.equal(entry.dimension, 384, id)
184
+ assert.equal(entry.maxTokens, 512, id)
185
+ assert.equal(entry.pooling, 'mean', id)
186
+ assert.ok(entry.files.length >= 8, id + ' files')
187
+ assert.ok(entry.totalBytes > 0, id)
188
+ assert.equal(entry.graph.outputs[0].shape[2], entry.dimension, id)
115
189
  const report = validateEmbeddingManifest(entry)
116
- assert.equal(report.ok, true, id + ' pending 条目本身应结构合法')
117
- assert.equal(report.errors.length, 0)
190
+ assert.deepEqual(report.errors.map(item => item.code), [], id + ' manifest must be installable')
191
+ const resolved = resolveEmbeddingSources(entry)
192
+ assert.equal(resolved.primary.provider, 'modelscope', id)
193
+ assert.equal(resolved.primary.files.length, entry.files.length, id)
194
+ // 见证制品(官方仓库的 1_Pooling)必须来自另一个 repo+revision,而不是冒充导出仓库
195
+ const pooling = resolved.primary.files.find(file => file.path === '1_Pooling/config.json')
196
+ assert.ok(pooling, id + ' needs a pooling witness')
197
+ assert.notEqual(pooling.repo, entry.sources.modelscope.repo, id)
118
198
  }
119
199
  })
120
200
 
201
+ test('只有非对称前缀的模型需要角色通道,对称前缀的模型不需要', () => {
202
+ assert.equal(prefixesRequireRole(getEmbeddingModel('bge-small-zh-v1.5-int8')), false)
203
+ assert.equal(prefixesRequireRole(getEmbeddingModel('all-minilm-l6-v2-int8')), false)
204
+ assert.equal(prefixesRequireRole(getEmbeddingModel('multilingual-e5-small')), true)
205
+ // 这条要求必须对用户可见:校验器把它列成警告,而不是静默地把模型标成可用
206
+ const codes = validateEmbeddingManifest(getEmbeddingModel('multilingual-e5-small')).warnings.map(item => item.code)
207
+ assert.ok(codes.includes('PREFIX_ASYMMETRIC'))
208
+ assert.equal(validateEmbeddingManifest(getEmbeddingModel('all-minilm-l6-v2-int8')).warnings
209
+ .some(item => item.code === 'PREFIX_ASYMMETRIC'), false)
210
+ })
211
+
212
+ test('未核实的目录条目依然被挡住:没有文件、没有哈希、理由齐全', () => {
213
+ const pending = clone(getEmbeddingModel('all-minilm-l6-v2-int8'))
214
+ pending.availability = 'pending'
215
+ pending.pendingReasons = ['制品未核实']
216
+ pending.files = []
217
+ pending.totalBytes = 0
218
+ pending.verification = { ...pending.verification, status: 'unverified' }
219
+ delete pending.profileFingerprint
220
+ const withFingerprint = { ...pending, profileFingerprint: profileFingerprint(pending) }
221
+ const report = validateEmbeddingManifest(withFingerprint)
222
+ assert.equal(report.ok, true, 'pending 条目本身结构合法')
223
+ assert.equal(report.errors.length, 0)
224
+ // pending 的原因必须写出来,不能只说「不可用」
225
+ const noReason = { ...withFingerprint, pendingReasons: [] }
226
+ assert.ok(validateEmbeddingManifest(noReason).errors.some(item => item.code === 'PENDING_REASON_MISSING'))
227
+ })
228
+
121
229
  test('manifest 校验会拒绝伪造/缺失的制品元数据', () => {
122
230
  const broken = clone(getEmbeddingModel(BGE))
123
231
  broken.files[0].sha256 = 'not-a-hash'
@@ -147,9 +147,19 @@ test('没有明确确认就绝不下模型,也不发任何请求', async () =>
147
147
 
148
148
  test('pending 模型与未知 id 都被拒绝,且不会联网', async () => {
149
149
  const { entry, payloads } = fixtureManifest()
150
+ const pending = {
151
+ ...entry,
152
+ id: 'fixture-pending-model',
153
+ availability: 'pending',
154
+ files: [],
155
+ totalBytes: 0,
156
+ pendingReasons: ['制品未核实:没有可比对的 bytes/sha256'],
157
+ verification: { ...entry.verification, status: 'unverified' },
158
+ }
159
+ pending.profileFingerprint = profileFingerprint(pending)
150
160
  const { fetchImpl, calls } = makeFetch(entry, payloads)
151
- const { manager } = managerFor(entry, fetchImpl)
152
- await assert.rejects(manager.download('all-minilm-l6-v2-int8', { confirmed: true }), error => {
161
+ const { manager } = managerFor(pending, fetchImpl)
162
+ await assert.rejects(manager.download('fixture-pending-model', { confirmed: true }), error => {
153
163
  assert.equal(error.code, 'EMBEDDING_MODEL_UNAVAILABLE')
154
164
  assert.ok(error.pendingReasons.length > 0)
155
165
  return true
@@ -159,6 +169,91 @@ test('pending 模型与未知 id 都被拒绝,且不会联网', async () => {
159
169
  assert.equal(manager.getStatus('does-not-exist').state, 'unknown')
160
170
  })
161
171
 
172
+ // hf-mirror 对小文件用 chunked 传输(不发 content-length)。把「头缺失」当成 0 字节会
173
+ // 让每一个小文件都被误判成大小不符——真实装 Qwen3 时踩到的就是这个。
174
+ test('来源不发 content-length 时按下落的实际字节判断,不当成 0', async () => {
175
+ const { entry, payloads } = fixtureManifest()
176
+ const { fetchImpl } = makeFetch(entry, payloads, { responseFor: filePath => (filePath === 'config.json' ? { contentLength: null } : {}) })
177
+ const { manager } = managerFor(entry, fetchImpl)
178
+ const status = await manager.download(entry.id, { confirmed: true })
179
+ assert.equal(status.state, 'installed')
180
+ assert.equal(status.installed, true)
181
+ })
182
+
183
+ // 多来源条目(Qwen3 卡片就是 hf-mirror + huggingface 同一个 commit):默认取目录顺序里
184
+ // 第一个,显式选源就只能用那一个,失败也不许回退到另一个源去下载。
185
+ test('显式选源只走那一个 provider,不回退到默认源', async () => {
186
+ const { entry, payloads } = fixtureManifest()
187
+ const mirrored = { ...entry, sources: {
188
+ 'hf-mirror': { repo: 'fixture/tiny', revision: REVISION },
189
+ huggingface: { repo: 'fixture/tiny', revision: REVISION },
190
+ } }
191
+ const routes = new Map()
192
+ for (const provider of ['hf-mirror', 'huggingface']) {
193
+ for (const file of resolveEmbeddingSources(mirrored, { providers: [provider] }).primary.files) routes.set(file.url, { provider, path: file.path })
194
+ }
195
+ const calls = []
196
+ const fetchImpl = async (url, init) => {
197
+ calls.push(url)
198
+ const route = routes.get(url)
199
+ if (!route) return { ok: false, status: 404, headers: { get: () => null }, body: null }
200
+ return responseFor(payloads[route.path], {})
201
+ }
202
+ const { manager } = managerFor(mirrored, fetchImpl)
203
+ const byDefault = await manager.download(mirrored.id, { confirmed: true })
204
+ assert.equal(byDefault.provider, 'hf-mirror', '默认必须是镜像站')
205
+ assert.ok(calls[0].startsWith('https://hf-mirror.com/'), calls[0])
206
+
207
+ const { root } = managerFor(mirrored, fetchImpl)
208
+ const second = createEmbeddingDownloadManager({ root, catalog: [mirrored], fetchImpl })
209
+ const chosen = await second.download(mirrored.id, { confirmed: true, provider: 'huggingface' })
210
+ assert.equal(chosen.provider, 'huggingface')
211
+ assert.ok(calls.some(url => url.startsWith('https://huggingface.co/')), '选源后要真的打到源站')
212
+ // 不存在的 provider 与「存在但这个条目没固定」是两种错,都要如实分开
213
+ await assert.rejects(second.download(mirrored.id, { confirmed: true, provider: 'ollama' }), error => error.code === 'EMBEDDING_PROVIDER_UNKNOWN')
214
+ await assert.rejects(second.download(mirrored.id, { confirmed: true, provider: 'modelscope' }), error => {
215
+ assert.equal(error.code, 'EMBEDDING_SOURCE_UNAVAILABLE')
216
+ assert.ok(String(error.message).includes('on modelscope'), error.message)
217
+ return true
218
+ })
219
+ // 换源之后默认源仍然可用(不许把条目卡在唯一来源上)
220
+ const third = createEmbeddingDownloadManager({ root, catalog: [mirrored], fetchImpl })
221
+ assert.equal((await third.download(mirrored.id, { confirmed: true })).provider, 'hf-mirror')
222
+ })
223
+
224
+ test('verifyStagedArtifacts 核对 last-token pooling、float16 输出与窗口上限', async () => {
225
+ const dir = fs.mkdtempSync(path.join(scratch, 'last-'))
226
+ const graph = tinyOnnxGraph(8)
227
+ fs.mkdirSync(path.join(dir, '1_Pooling'), { recursive: true })
228
+ const base = {
229
+ id: 'fixture-last', dimension: 8, maxTokens: 32, pooling: 'last', normalization: 'l2',
230
+ graph: { path: 'onnx/tiny.onnx', opset: 11, inputs: [
231
+ { name: 'input_ids', dtype: 'int64' }, { name: 'attention_mask', dtype: 'int64' }, { name: 'token_type_ids', dtype: 'int64' },
232
+ ], outputs: [{ name: 'last_hidden_state', dtype: 'float32', shape: ['batch_size', 'sequence_length', 8] }] },
233
+ files: [
234
+ { path: 'config.json', role: 'config' },
235
+ { path: 'onnx/tiny.onnx', role: 'graph' },
236
+ { path: '1_Pooling/config.json', role: 'pooling-config' },
237
+ ],
238
+ }
239
+ fs.writeFileSync(path.join(dir, 'config.json'), JSON.stringify({ hidden_size: 8, max_position_embeddings: 32 }), 'utf8')
240
+ fs.mkdirSync(path.join(dir, 'onnx'), { recursive: true })
241
+ fs.writeFileSync(path.join(dir, 'onnx/tiny.onnx'), graph)
242
+ fs.writeFileSync(path.join(dir, '1_Pooling', 'config.json'), JSON.stringify({ word_embedding_dimension: 8, pooling_mode_lasttoken: true }), 'utf8')
243
+ const ok = await verifyStagedArtifacts({ entry: base, dir })
244
+ assert.ok(ok.checks.includes('pooling=last'), JSON.stringify(ok.checks))
245
+
246
+ fs.writeFileSync(path.join(dir, '1_Pooling', 'config.json'), JSON.stringify({ word_embedding_dimension: 8, pooling_mode_mean_tokens: true }), 'utf8')
247
+ await assert.rejects(verifyStagedArtifacts({ entry: base, dir }), /not last-token pooling/)
248
+ fs.writeFileSync(path.join(dir, '1_Pooling', 'config.json'), JSON.stringify({ word_embedding_dimension: 8, pooling_mode_lasttoken: true }), 'utf8')
249
+
250
+ // 窗口可以比制品小(刻意策略),但不能比制品大(必炸)
251
+ await assert.rejects(verifyStagedArtifacts({ entry: { ...base, maxTokens: 64 }, dir }), /exceeds the artifact's max_position_embeddings/)
252
+ // float16 图输出是可以接受的,但声明必须与图一致
253
+ const fp16 = { ...base, files: base.files.map(file => (file.role === 'graph' ? file : file)), graph: { ...base.graph, outputs: [{ name: 'last_hidden_state', dtype: 'float16', shape: ['batch_size', 'sequence_length', 8] }] } }
254
+ await assert.rejects(verifyStagedArtifacts({ entry: fp16, dir }), /output dtype/)
255
+ })
256
+
162
257
  test('校验通过的制品原子安装:staging 清空、installed.json 记录 active:false', async () => {
163
258
  const { entry, payloads } = fixtureManifest()
164
259
  const { fetchImpl, calls } = makeFetch(entry, payloads)
@@ -10,7 +10,7 @@ process.env.DSH_MEMU_HOME = home
10
10
  delete process.env.DSH_MEMU_EMBED_RUNTIME_DIR
11
11
 
12
12
  const runtime = await import('../lib/embedding-runtime.js')
13
- const { getEmbeddingModel } = await import('../lib/embedding-catalog.js')
13
+ const { getEmbeddingCatalog, getEmbeddingModel } = await import('../lib/embedding-catalog.js')
14
14
  const service = await import('../lib/local-vector-service.js')
15
15
  const { profileFromCatalog, setRequestedProfile } = await import('../lib/vector-profile.js')
16
16
 
@@ -105,7 +105,12 @@ function makeInstaller(root, options = {}) {
105
105
  }
106
106
 
107
107
  test('a pending catalog model pins no runtime and is refused before any download', () => {
108
- const plan = runtime.runtimePlan(getEmbeddingModel('all-minilm-l6-v2-int8'), 'win32-x64')
108
+ // 目录里现在没有 pending 条目,所以这里造一个:未核实的候选就是没有 runtime 事实。
109
+ const plan = runtime.runtimePlan({
110
+ id: 'pending-candidate',
111
+ availability: 'pending',
112
+ runtime: { engine: 'onnxruntime-node', version: null, abi: 'napi-v6' },
113
+ }, 'win32-x64')
109
114
  assert.equal(plan.ok, false)
110
115
  assert.ok(plan.errors.some(item => item.code === 'RUNTIME_ENTRY_NOT_AVAILABLE'))
111
116
  assert.ok(plan.errors.some(item => item.code === 'RUNTIME_ARTIFACTS_MISSING'))
@@ -118,18 +123,21 @@ test('a platform with no pinned native binaries fails closed instead of guessing
118
123
  assert.deepEqual(plan.errors.map(item => item.code), ['RUNTIME_NATIVE_MISSING'])
119
124
  })
120
125
 
121
- test('the verified BGE entry pins a complete runtime for every shipped platform', () => {
122
- const entry = getEmbeddingModel('bge-small-zh-v1.5-int8')
123
- for (const platform of ['win32-x64', 'win32-arm64', 'linux-x64', 'linux-arm64', 'darwin-arm64']) {
124
- const plan = runtime.runtimePlan(entry, platform)
125
- assert.equal(plan.ok, true, platform + ': ' + JSON.stringify(plan.errors))
126
- assert.equal(plan.artifacts.length, 3)
127
- for (const artifact of plan.artifacts) {
128
- assert.match(artifact.sha256, /^[0-9a-f]{64}$/)
129
- assert.equal(artifact.url.startsWith('https://'), true)
130
- assert.ok(artifact.bytes > 0)
126
+ // 三个模型共用同一棵 pin 住的受管运行时树(PINNED_ONNX_RUNTIME),所以每条都得能整成
127
+ // 完整计划;哪天共享常量被改坏,这里会先红。
128
+ test('每一条已核实的目录条目都钉住了每个平台的完整运行时', () => {
129
+ for (const entry of getEmbeddingCatalog()) {
130
+ for (const platform of ['win32-x64', 'win32-arm64', 'linux-x64', 'linux-arm64', 'darwin-arm64']) {
131
+ const plan = runtime.runtimePlan(entry, platform)
132
+ assert.equal(plan.ok, true, entry.id + ' ' + platform + ': ' + JSON.stringify(plan.errors))
133
+ assert.equal(plan.artifacts.length, 3, entry.id)
134
+ for (const artifact of plan.artifacts) {
135
+ assert.match(artifact.sha256, /^[0-9a-f]{64}$/)
136
+ assert.equal(artifact.url.startsWith('https://'), true)
137
+ assert.ok(artifact.bytes > 0)
138
+ }
139
+ assert.ok(plan.native.length >= 2, entry.id + ' ' + platform)
131
140
  }
132
- assert.ok(plan.native.length >= 2)
133
141
  }
134
142
  })
135
143