dsh-memu-memory 1.2.4 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.md +9 -9
  3. package/README.zh.md +6 -6
  4. package/docs/binding-lifecycle.md +1 -1
  5. package/docs/env-and-commands.md +4 -1
  6. package/docs/host-adaptation.md +318 -0
  7. package/docs/host-api.md +29 -5
  8. package/docs/memory-semantics.md +45 -9
  9. package/docs/troubleshooting.md +27 -8
  10. package/lib/binding-diagnostics.js +2 -2
  11. package/lib/client.js +246 -56
  12. package/lib/consolidation-ledger.js +46 -1
  13. package/lib/consolidation-worker.js +1 -0
  14. package/lib/cycle.js +51 -17
  15. package/lib/embedding-catalog.js +14 -0
  16. package/lib/embedding-runtime.js +202 -25
  17. package/lib/global-graph.js +99 -1
  18. package/lib/index.js +8 -0
  19. package/lib/inject.js +71 -33
  20. package/lib/lexicon-scope.js +143 -0
  21. package/lib/lexicon.js +31 -4
  22. package/lib/local-vector-service.js +82 -6
  23. package/lib/memory.js +186 -12
  24. package/lib/memu.js +318 -3
  25. package/lib/private.js +310 -67
  26. package/lib/rpc.js +183 -23
  27. package/lib/salient-wake.js +38 -2
  28. package/lib/state.js +7 -5
  29. package/lib/tools.js +40 -17
  30. package/lib/vector-migration.js +13 -1
  31. package/lib/webui/graph-view.bundle.js +1 -1
  32. package/lib/webui/graph-view.js +4 -1
  33. package/package.json +1 -1
  34. package/tests/absorb-review.test.mjs +2 -1
  35. package/tests/backend-compensation.test.mjs +1 -1
  36. package/tests/browser.test.mjs +58 -1
  37. package/tests/client-render.test.mjs +39 -0
  38. package/tests/consolidation-fork.test.mjs +81 -6
  39. package/tests/cross-library-recall.test.mjs +113 -0
  40. package/tests/curator-absorb.test.mjs +2 -1
  41. package/tests/curator-clusters.test.mjs +2 -1
  42. package/tests/curator-commit.test.mjs +2 -1
  43. package/tests/curator-link.test.mjs +2 -1
  44. package/tests/curator-review-mode.test.mjs +2 -1
  45. package/tests/cycle.test.mjs +2 -2
  46. package/tests/embedding-runtime.test.mjs +53 -1
  47. package/tests/global-graph.test.mjs +90 -0
  48. package/tests/lexicon-scope.test.mjs +256 -0
  49. package/tests/lexicon-ui.test.mjs +23 -0
  50. package/tests/managed-memory.test.mjs +1 -1
  51. package/tests/recall-dedup.test.mjs +1 -1
  52. package/tests/salient-wake.test.mjs +28 -1
  53. package/tests/settings-plumbing.test.mjs +1 -0
  54. package/tests/stubs/dsh-schedule.js +35 -0
  55. package/tests/ui-defaults.test.mjs +1 -1
  56. package/tests/vector-migration.test.mjs +20 -0
  57. package/tests/webui-auth.test.mjs +28 -0
@@ -273,6 +273,19 @@ export function failJob({ sessionId, jobId, reasonCode = 'failed', retryable = t
273
273
  }
274
274
  entry.lastReasonCode = reasonCode
275
275
  entry.lastError = clampText(error || reasonCode)
276
+ // 同一快照的失败次数单独记:窗口已经很小,但同一段转录不该无限重跑。
277
+ // 新事件会改变 snapshotHash,自然得到一份新的操作键与新的机会。
278
+ if (job.snapshot?.hash) {
279
+ const key = operationKey({ sessionId, libraryId: job.libraryId, snapshotHash: job.snapshot.hash, scopeGeneration: job.scopeGeneration })
280
+ const prior = entry.operations[key]
281
+ entry.operations[key] = {
282
+ outcome: 'failed',
283
+ ids: Array.isArray(prior?.ids) ? prior.ids : [],
284
+ at: stamp(),
285
+ failures: (Number(prior?.failures) || 0) + 1,
286
+ firstFailedAt: prior?.firstFailedAt || stamp(),
287
+ }
288
+ }
276
289
  pushHistory(entry, { jobId, status: 'failed', reasonCode, at: stamp() })
277
290
  entry.updatedAt = stamp()
278
291
  return { pending: entry.pending, retryAt: entry.retryAt || null, attempts: entry.attempts }
@@ -323,7 +336,8 @@ export function findOperation(sessionId, key, ledger = loadLedger()) {
323
336
  export function recordOperation({ sessionId, key, outcome, ids = [], at = Date.now() }) {
324
337
  return mutateLedger((ledger) => {
325
338
  const entry = ensureEntry(ledger, sessionId)
326
- entry.operations[String(key)] = { outcome, ids: Array.isArray(ids) ? ids.slice(0, 50) : [], at: new Date(at).toISOString() }
339
+ // A later success clears the same-snapshot failure streak.
340
+ entry.operations[String(key)] = { outcome, ids: Array.isArray(ids) ? ids.slice(0, 50) : [], at: new Date(at).toISOString(), failures: 0 }
327
341
  const keys = Object.keys(entry.operations)
328
342
  if (keys.length > OPERATION_LIMIT) {
329
343
  for (const stale of keys.slice(0, keys.length - OPERATION_LIMIT)) delete entry.operations[stale]
@@ -333,6 +347,37 @@ export function recordOperation({ sessionId, key, outcome, ids = [], at = Date.n
333
347
  })
334
348
  }
335
349
 
350
+ /**
351
+ * 政策跳过:评估结论是「这段本来就不值得写」(寒暄 / 没有真人回合),
352
+ * 不是失败也不是 worker 回执。把 checked 推进到这段快照,pending 同步裁剪,
353
+ * 否则 pending 会一直把同一段寒暄当成 backlog,扫描每 5 分钟重读一次。
354
+ */
355
+ export function skipRange({ sessionId, snapshot, reasonCode = 'no-value' }) {
356
+ return mutateLedger((ledger) => {
357
+ const entry = ensureEntry(ledger, sessionId)
358
+ const from = Number(snapshot?.fromSeq)
359
+ const through = Number(snapshot?.throughSeq)
360
+ if (!Number.isSafeInteger(from) || !Number.isSafeInteger(through) || through < from) {
361
+ return { advanced: false, checked: entry.checked, pending: entry.pending }
362
+ }
363
+ entry.checked = {
364
+ fromSeq: from, throughSeq: through, at: stamp(), status: 'skipped',
365
+ outcome: 'no_value', jobId: null, reasonCode, snapshotHash: snapshot?.hash || null,
366
+ eventCount: snapshot?.eventCount ?? null, receipt: null,
367
+ }
368
+ const pendingThrough = Number(entry.pending?.throughSeq)
369
+ if (entry.pending && (!Number.isSafeInteger(pendingThrough) || pendingThrough <= through)) entry.pending = null
370
+ else if (entry.pending) entry.pending = { fromSeq: through + 1, throughSeq: pendingThrough, at: entry.pending.at }
371
+ entry.attempts = 0
372
+ entry.retryAt = null
373
+ entry.lastReasonCode = reasonCode
374
+ entry.lastError = null
375
+ pushHistory(entry, { jobId: null, status: 'skipped', outcome: 'no_value', reasonCode, at: stamp() })
376
+ entry.updatedAt = stamp()
377
+ return { advanced: true, checked: entry.checked, pending: entry.pending }
378
+ })
379
+ }
380
+
336
381
  export function clearSessionState(sessionId) {
337
382
  return mutateLedger((ledger) => {
338
383
  delete ledger.sessions[String(sessionId || '')]
@@ -150,6 +150,7 @@ export function buildWorkerBrief({ snapshot, probe = null, contract = '', reason
150
150
  '[私有整理 worker' + (jobId ? ' · ' + jobId : '') + ' · ' + (reason === 'manual' ? '手动' : '自动') + ']',
151
151
  '你不是这场对话里的角色,也不继承上面转录的说话方式:你是后台整理私有记忆的 worker。',
152
152
  '只处理 ' + rangeLine(snapshot) + ';范围之外的内容不要读、不要推断、不要写。',
153
+ '转录开头的 [memory-catalog · 已有记忆目录] 是本库已有条目,只用来去重/合并,不是对话内容,也不是用户发言。',
153
154
  '本轮可用的工具:' + tools + '。',
154
155
  '要做的:先按主题检索相关旧条目去重;同一事实的补充用 memu_private_update 合并(先拿到 id);真正新增、或与已有说法矛盾的内容用 memu_private_remember 一条一件;矛盾不要自己裁决,让它进待复核。',
155
156
  '写完(remember/update 拿到 id)后调用 memu_private_link_suggest({ids:[...]}),把本轮创建/更新的 id 都传进去:高置信的记忆↔记忆关联与实体枢纽算法已经自动连好,只有不确定的候选交给你裁决。不回读整段会话,也不为这个另起一次整理。',
package/lib/cycle.js CHANGED
@@ -4,13 +4,13 @@ import {
4
4
  deleteLibrary, restoreLibrary, normalizeCwd,
5
5
  } from './state.js'
6
6
  import { expireShortTerm } from './memory.js'
7
- import { requestPrivateConsolidation } from './private.js'
7
+ import { requestPrivateConsolidation, CONSOLIDATION_BACKLOG_EVENTS, CONSOLIDATION_PROBE_MINUTES } from './private.js'
8
8
  import { startGlobalCuration } from './curator.js'
9
9
  import { runVisibilityMigrationPass } from './migrate.js'
10
10
  import { runSalientWakePass } from './salient-wake.js'
11
11
  import { record } from './activity-log.js'
12
12
  import { ACTIVE_MEMORY_POLICY, suppressionReason } from './active-memory.js'
13
- import { clearSessionState } from './consolidation-ledger.js'
13
+ import { clearSessionState, loadLedger, sessionState } from './consolidation-ledger.js'
14
14
 
15
15
  const SWEEP_MS = 5 * 60 * 1000
16
16
  // Long enough that the host has restored its session list and the agent objects
@@ -77,27 +77,52 @@ export function isGoneSessionError(message) {
77
77
  export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limit = 2 } = {}) {
78
78
  const settings = getSettings()
79
79
  if (settings.sleepConsolidation !== true) return { ran: 0, skipped: 'disabled' }
80
- const idleMs = Math.max(1, Number(settings.sleepAfterIdleMinutes) || 3) * 60_000
80
+ const idleMs = Math.max(1, Number(settings.sleepAfterIdleMinutes) || 2) * 60_000
81
+ const probeMs = Math.max(1, Number(CONSOLIDATION_PROBE_MINUTES) || 15) * 60_000
82
+ // One ledger read per sweep: pending backlog is the cheap水位 signal that does
83
+ // not need a transcript read.
84
+ let ledger = null
85
+ try { ledger = loadLedger() } catch { ledger = null }
81
86
  const candidates = []
82
87
  for (const binding of listSessionBindings()) {
83
88
  if (binding.consolidationFork || !binding.lastTurnAt) continue
84
89
  if (binding.sessionGone) continue
90
+ const lastSleepAt = getLastSleepAt(binding.sessionId)
85
91
  const activeAt = Math.max(Date.parse(binding.lastTurnAt) || 0, Date.parse(binding.lastInboundAt) || 0, Date.parse(binding.lastAgentIdleAt) || 0)
86
- if (now - activeAt < idleMs) continue
92
+ const idle = now - activeAt >= idleMs
93
+ const newActivity = older(lastSleepAt, binding.lastTurnAt) < 0
94
+ const state = ledger ? sessionState(binding.sessionId, ledger) : null
95
+ const pendingEvents = state?.pending && (!state.checked || state.pending.throughSeq > state.checked.throughSeq)
96
+ ? Number(state.pending.throughSeq) - (Number.isSafeInteger(Number(state.checked?.throughSeq)) ? Number(state.checked.throughSeq) : -1)
97
+ : 0
98
+ const backlog = pendingEvents >= CONSOLIDATION_BACKLOG_EVENTS
99
+ const neverSlept = !lastSleepAt
100
+ const lastProbe = Date.parse(binding.lastConsolidationProbeAt || '') || 0
101
+ const probeDue = newActivity && now - lastProbe >= probeMs
102
+ // Idle time alone is not new evidence: after a successful window the sleep
103
+ // stamp already covers the transcript, so a quiet idle sweep must not fork it again.
104
+ if (!newActivity && !backlog) continue
105
+ // Three independent reasons to look: idle (normal), a real pending backlog
106
+ // (watermark), or a bounded probe when new activity has arrived but not enough
107
+ // to know its size yet. The probe reads the transcript and decides without a
108
+ // fork, so it costs CPU, not tokens.
109
+ if (!idle && !backlog && !neverSlept && !probeDue) continue
87
110
  // Running includes a long-lived asynchronous tool. Waiting is not proof that
88
111
  // the conversation ended, and a fork should not race its active agent.
89
112
  if (liveAgent(ctx, binding.sessionId)?.status === 'running') continue
90
113
  if (binding.inbound?.pending?.length) continue
91
- if (older(getLastSleepAt(binding.sessionId), binding.lastTurnAt) >= 0) continue
92
114
  if ((Date.parse(binding.sleepRetryAt || '') || 0) > now) continue
93
- candidates.push({ binding, activeAt })
115
+ // Backlog first, then real idle, then cheap probes: a sweep with a limited
116
+ // budget must not let probe-only sessions crowd out work that is actually due.
117
+ candidates.push({ binding, activeAt, trigger: idle ? 'idle' : 'backlog', priority: backlog ? 3 : idle ? 2 : 1 })
94
118
  }
95
- // Newest first: a catch-up run after the app was closed should tidy what the user
96
- // just lived through, not a week-old chat that has already waited this long.
97
- candidates.sort((a, b) => b.activeAt - a.activeAt)
119
+ // Newest first within the same priority: a catch-up run after the app was closed
120
+ // should tidy what the user just lived through, not a week-old chat that has
121
+ // already waited this long.
122
+ candidates.sort((a, b) => (b.priority - a.priority) || (b.activeAt - a.activeAt))
98
123
  const budget = Math.max(1, Math.min(10, Number(limit) || 2))
99
124
  let ran = 0
100
- for (const { binding } of candidates.slice(0, budget)) {
125
+ for (const { binding, trigger } of candidates.slice(0, budget)) {
101
126
  if (binding.useLibrary === false) {
102
127
  setLastSleepAt(binding.sessionId)
103
128
  continue
@@ -108,8 +133,6 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
108
133
  // A live session used to be consolidated in place, which is exactly what put
109
134
  // a queued draft above the user's composer and then left a housekeeping turn
110
135
  // in their transcript for good.
111
- // 近期刚整理过、或刚注入过记忆的会话不再 fork:长会话每次整理都会把整段
112
- // 转录种进子会话,连续触发等于重复付同一笔 token。
113
136
  const suppression = suppressionReason({
114
137
  now,
115
138
  lastSleepAt: getLastSleepAt(binding.sessionId),
@@ -117,28 +140,39 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
117
140
  consolidatedCooldownMinutes: Number(settings.activeMemoryCooldownMinutes ?? ACTIVE_MEMORY_POLICY.consolidatedCooldownMinutes),
118
141
  recallCooldownMinutes: Number(settings.activeMemoryRecallCooldownMinutes ?? ACTIVE_MEMORY_POLICY.recallCooldownMinutes),
119
142
  })
120
- if (suppression) {
143
+ // 「刚注入过记忆」只压空闲收尾,不压水位/探针:后者先读转录再决定,不合并不 fork。
144
+ const blocked = suppression && !(trigger === 'backlog' && suppression === 'recent-recall')
145
+ if (blocked) {
121
146
  log(`sleep consolidation suppressed for ${binding.sessionId}: ${suppression}`)
122
147
  record({
123
148
  kind: 'check', scope: 'private', sessionId: binding.sessionId, libraryId: binding.libraryId || null, ok: true,
124
149
  message: '闲时检查抑制:' + suppression,
125
- detail: { trigger: 'idle', reason: suppression, lastSleepAt: getLastSleepAt(binding.sessionId), lastInjectedAt: binding.lastInjectedAt || null },
150
+ detail: { trigger, reason: suppression, lastSleepAt: getLastSleepAt(binding.sessionId), lastInjectedAt: binding.lastInjectedAt || null },
126
151
  })
127
152
  continue
128
153
  }
129
154
  try {
130
- const result = await requestPrivateConsolidation(ctx, binding.sessionId)
155
+ const result = await requestPrivateConsolidation(ctx, binding.sessionId, { trigger })
131
156
  if (result?.ok) {
132
157
  // 证据不足(low-score)不是"已整理":不推进游标、不计数,等空闲越过饥饿阈值
133
158
  // 或后续证据变多再检查。否则这句话会被永久跳过。
134
159
  if (result.settled === false) {
160
+ // 探针/水位不足阈值:记下这次探针时间,避免每 5 分钟重读同一段。
161
+ if (result.skipped === 'backlog-below-threshold' || result.deferred === true) {
162
+ setSessionBinding(binding.sessionId, { lastConsolidationProbeAt: new Date(now).toISOString() })
163
+ }
135
164
  log(`sleep consolidation deferred for ${binding.sessionId}: ${result.skipped || 'not settled'}`)
136
165
  continue
137
166
  }
138
167
  // Only cover activity this pass began with, not new messages during it.
139
168
  setLastSleepAt(binding.sessionId, binding.lastTurnAt)
140
- setSessionBinding(binding.sessionId, { sleepRetryAt: null, sleepAttempts: 0, lastSleepError: null })
141
- ran += 1
169
+ setSessionBinding(binding.sessionId, {
170
+ sleepRetryAt: null, sleepAttempts: 0, lastSleepError: null,
171
+ lastConsolidationProbeAt: new Date(now).toISOString(),
172
+ })
173
+ // A terminal policy skip (greetings, no new events) advances the sleep stamp
174
+ // but is not a verified worker run; `ran` must keep that distinction.
175
+ if (!result.skipped) ran += 1
142
176
  } else if (isGoneSessionError(result?.error)) {
143
177
  setSessionBinding(binding.sessionId, { sessionGone: true, sessionGoneAt: new Date(now).toISOString(), sleepRetryAt: null, sleepAttempts: 0, lastSleepError: String(result.error) })
144
178
  try { clearSessionState(binding.sessionId) } catch {}
@@ -127,10 +127,16 @@ const PINNED_ONNX_RUNTIME = Object.freeze({
127
127
  },
128
128
  evidence: 'npm tarball sha256 与 registry integrity 双向一致;解包最小树真实推理通过;原生库逐文件 sha256 取自同一棵已核实树',
129
129
  },
130
+ // Every source serves the same npm tarball; the installer still verifies the pinned
131
+ // bytes+sha256 after download, so a mirror can never change the runtime tree.
130
132
  artifacts: [
131
133
  {
132
134
  name: 'onnxruntime-node', version: '1.31.1', license: 'MIT',
133
135
  url: 'https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.31.1.tgz',
136
+ sources: [
137
+ { id: 'npmjs', label: 'npmjs', url: 'https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.31.1.tgz' },
138
+ { id: 'npmmirror', label: 'npmmirror(国内镜像)', url: 'https://registry.npmmirror.com/onnxruntime-node/-/onnxruntime-node-1.31.1.tgz' },
139
+ ],
134
140
  bytes: 115391311,
135
141
  sha256: 'd7a3de2b1bba92614abc74af909cc0ba4f4dd5347735418794edeb58cfef2d22',
136
142
  integrity: 'sha512-ijnSghbDHVWaQ2nDPmVccPlCHI8kH1Mx1aJ4a/qzRP16bBcVs4E3EqZQKZCkhWnbqN1tuQWxagimFtDpbPYYQw==',
@@ -139,6 +145,10 @@ const PINNED_ONNX_RUNTIME = Object.freeze({
139
145
  {
140
146
  name: 'onnxruntime-common', version: '1.31.1', license: 'MIT',
141
147
  url: 'https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.31.1.tgz',
148
+ sources: [
149
+ { id: 'npmjs', label: 'npmjs', url: 'https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.31.1.tgz' },
150
+ { id: 'npmmirror', label: 'npmmirror(国内镜像)', url: 'https://registry.npmmirror.com/onnxruntime-common/-/onnxruntime-common-1.31.1.tgz' },
151
+ ],
142
152
  bytes: 72322,
143
153
  sha256: '967acac0c2a22122461e526aeda07305da7289d94f276920d8a6919483f07bfc',
144
154
  integrity: 'sha512-F+nnYNiQtmNJ95V6R/isBJqiVpdANCrsMEg1OaF+Bkbl3GAtzWLR7Ng17Ld0QtYtYJyotOHPJzOQn1Y6PLZjpg==',
@@ -147,6 +157,10 @@ const PINNED_ONNX_RUNTIME = Object.freeze({
147
157
  {
148
158
  name: '@huggingface/tokenizers', version: '0.2.0', license: 'Apache-2.0',
149
159
  url: 'https://registry.npmjs.org/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz',
160
+ sources: [
161
+ { id: 'npmjs', label: 'npmjs', url: 'https://registry.npmjs.org/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz' },
162
+ { id: 'npmmirror', label: 'npmmirror(国内镜像)', url: 'https://registry.npmmirror.com/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz' },
163
+ ],
150
164
  bytes: 87011,
151
165
  sha256: '2800014c83b8186b2e4210c20672f1fb65a12cef85d7e95e0f2003e022611b4a',
152
166
  integrity: 'sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==',
@@ -25,6 +25,7 @@ import { getEmbeddingCatalog, getEmbeddingModel } from './embedding-catalog.js'
25
25
  export const RUNTIME_RECORD = 'installed.json'
26
26
  export const RUNTIME_ACTIVE = 'active.json'
27
27
  export const RUNTIME_STAGING = '.staging'
28
+ export const RUNTIME_CACHE = '.cache'
28
29
  export const RUNTIME_TRASH = '.trash'
29
30
  export const RUNTIME_LAYOUT = 'node_modules'
30
31
  export const RUNTIME_STATES = Object.freeze(['unknown', 'unsupported', 'absent', 'downloading', 'verifying', 'installing', 'installed', 'failed', 'cancelled'])
@@ -64,6 +65,25 @@ function sha256Of(buffer) {
64
65
  return crypto.createHash('sha256').update(buffer).digest('hex')
65
66
  }
66
67
 
68
+ function sha256File(file) {
69
+ return new Promise((resolve, reject) => {
70
+ const hash = crypto.createHash('sha256')
71
+ const stream = fs.createReadStream(file)
72
+ stream.on('data', chunk => hash.update(chunk))
73
+ stream.on('error', reject)
74
+ stream.on('end', () => resolve(hash.digest('hex')))
75
+ })
76
+ }
77
+
78
+ function artifactSafeName(artifact) {
79
+ return String(artifact?.name || 'artifact').replace(/[^A-Za-z0-9._@-]+/g, '-')
80
+ }
81
+
82
+ function cachePaths(cacheDir, artifact) {
83
+ const base = path.join(cacheDir, `${artifactSafeName(artifact)}-${artifact.sha256}.tgz`)
84
+ return { final: base, part: base + '.part' }
85
+ }
86
+
67
87
  export function embeddingRuntimePlatform(platform = process.platform, arch = process.arch) {
68
88
  return String(platform) + '-' + String(arch)
69
89
  }
@@ -84,7 +104,7 @@ export function runtimePlan(entry, platform = embeddingRuntimePlatform()) {
84
104
  const reject = (code, message) => errors.push({ code, message })
85
105
  const runtime = isPlainObject(entry?.runtime) ? entry.runtime : null
86
106
  const key = runtimeKeyFor(entry, platform)
87
- const empty = { ok: false, errors, key, platform, engine: null, version: null, abi: null, artifacts: [], packageFiles: [], native: [] }
107
+ const empty = { ok: false, errors, key, platform, engine: null, version: null, abi: null, artifacts: [], packageFiles: [], native: [], sources: [] }
88
108
  if (!runtime) {
89
109
  reject('RUNTIME_SPEC_MISSING', 'the catalog entry has no runtime spec')
90
110
  return empty
@@ -97,6 +117,7 @@ export function runtimePlan(entry, platform = embeddingRuntimePlatform()) {
97
117
  if (!version) reject('RUNTIME_VERSION_UNPINNED', 'runtime.version must be a pinned version, not null')
98
118
  if (!abi) reject('RUNTIME_ABI_MISSING', 'runtime.abi is required')
99
119
  const artifacts = []
120
+ const sourcesById = new Map()
100
121
  for (const artifact of Array.isArray(runtime.artifacts) ? runtime.artifacts : []) {
101
122
  if (!isPlainObject(artifact)) { reject('RUNTIME_ARTIFACT_INVALID', 'each runtime artifact must be an object'); continue }
102
123
  const name = String(artifact.name || '')
@@ -107,10 +128,28 @@ export function runtimePlan(entry, platform = embeddingRuntimePlatform()) {
107
128
  if (!Number.isInteger(artifact.bytes) || artifact.bytes <= 0) reject('RUNTIME_ARTIFACT_BYTES_INVALID', `artifact ${name} needs exact bytes`)
108
129
  if (!isSha256(artifact.sha256)) reject('RUNTIME_ARTIFACT_SHA256_INVALID', `artifact ${name} needs a lowercase sha256; guessed hashes are not accepted`)
109
130
  if (!Array.isArray(artifact.extract) || !artifact.extract.length) reject('RUNTIME_ARTIFACT_EXTRACT_MISSING', `artifact ${name} needs an explicit extraction allow-list`)
131
+ const sourceList = []
132
+ for (const source of Array.isArray(artifact.sources) ? artifact.sources : []) {
133
+ if (!isPlainObject(source)) { reject('RUNTIME_ARTIFACT_SOURCE_INVALID', `artifact ${name} has a non-object source`); continue }
134
+ const id = String(source.id || '').trim()
135
+ let sourceUrl = null
136
+ try { sourceUrl = new URL(String(source.url || '')) } catch { sourceUrl = null }
137
+ if (!id || !/^[a-z0-9._-]+$/.test(id) || !sourceUrl || sourceUrl.protocol !== 'https:') {
138
+ reject('RUNTIME_ARTIFACT_SOURCE_INVALID', `artifact ${name} has an invalid source: ${JSON.stringify(source.id || source.url)}`)
139
+ continue
140
+ }
141
+ if (sourceList.some(item => item.id === id)) { reject('RUNTIME_ARTIFACT_SOURCE_INVALID', `artifact ${name} repeats source ${id}`); continue }
142
+ sourceList.push({ id, label: String(source.label || id).slice(0, 80), url: sourceUrl.href })
143
+ }
144
+ if (!sourceList.length && url) sourceList.push({ id: 'npmjs', label: 'npmjs', url: url.href })
145
+ for (const source of sourceList) {
146
+ if (!sourcesById.has(source.id)) sourcesById.set(source.id, { id: source.id, label: source.label })
147
+ }
110
148
  artifacts.push({
111
149
  name,
112
150
  version: String(artifact.version || version),
113
151
  url: url ? url.href : null,
152
+ sources: sourceList,
114
153
  bytes: Number.isInteger(artifact.bytes) ? artifact.bytes : null,
115
154
  sha256: String(artifact.sha256 || ''),
116
155
  integrity: typeof artifact.integrity === 'string' ? artifact.integrity : null,
@@ -136,7 +175,19 @@ export function runtimePlan(entry, platform = embeddingRuntimePlatform()) {
136
175
  native.push({ path: file.path, bytes: Number(file.bytes), sha256: String(file.sha256) })
137
176
  }
138
177
  if (!native.length) reject('RUNTIME_NATIVE_MISSING', `no verified native runtime is pinned for ${platform}; refusing to install on this platform`)
139
- return { ok: errors.length === 0, errors, key, platform, engine: engine || null, version: version || null, abi: abi || null, artifacts, packageFiles, native }
178
+ return {
179
+ ok: errors.length === 0,
180
+ errors,
181
+ key,
182
+ platform,
183
+ engine: engine || null,
184
+ version: version || null,
185
+ abi: abi || null,
186
+ artifacts,
187
+ packageFiles,
188
+ native,
189
+ sources: [...sourcesById.values()],
190
+ }
140
191
  }
141
192
 
142
193
  /** 下载到的字节必须与 pin 的 bytes+sha256 完全一致;不匹配一律拒绝执行。 */
@@ -201,6 +252,7 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
201
252
  const smoke = typeof options.smoke === 'function' ? options.smoke : defaultSmoke
202
253
  const resolveEntry = typeof options.resolveEntry === 'function' ? options.resolveEntry : id => (id ? getEmbeddingModel(String(id)) : null)
203
254
  const activeFile = path.join(baseDir, RUNTIME_ACTIVE)
255
+ const cacheDir = path.join(baseDir, RUNTIME_CACHE)
204
256
  const inflight = new Map()
205
257
  let job = null
206
258
  let outcome = null
@@ -314,12 +366,12 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
314
366
  try { resolved = planFor(modelId) } catch (error) { return { ...base, status: 'unsupported', ready: false, key: null, path: null, error: { code: String(error?.code || 'LOCAL_VECTOR_RUNTIME_UNVERIFIED'), message: String(error?.message || error) } } }
315
367
  const entry = resolved.entry
316
368
  const plan = resolved.plan
317
- const pinned = { key: plan.key, engine: plan.engine, version: plan.version, abi: plan.abi, artifacts: plan.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256, license: item.license })), verifiedPlatforms: Object.keys(entry?.runtime?.install?.platforms || {}) }
369
+ const pinned = { key: plan.key, engine: plan.engine, version: plan.version, abi: plan.abi, artifacts: plan.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256, license: item.license })), sources: plan.sources, verifiedPlatforms: Object.keys(entry?.runtime?.install?.platforms || {}) }
318
370
  if (!plan.ok) {
319
371
  return { ...base, ...pinned, status: 'unsupported', ready: false, path: null, error: { code: 'LOCAL_VECTOR_RUNTIME_UNVERIFIED', message: 'the catalog does not pin a complete runtime for this platform', errors: plan.errors } }
320
372
  }
321
373
  if (job && job.key === plan.key) {
322
- return { ...base, ...pinned, status: job.state, ready: false, path: null, progress: { ...job.progress }, startedAt: job.startedAt }
374
+ return { ...base, ...pinned, status: job.state, ready: false, path: null, progress: { ...job.progress }, startedAt: job.startedAt, downloadSource: job.source || null }
323
375
  }
324
376
  const inspect = inspectPlan(plan, { deep })
325
377
  if (inspect.ok) {
@@ -366,25 +418,137 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
366
418
  throw failure('LOCAL_VECTOR_RUNTIME_BUSY', 'cannot take the managed runtime install lock; retry later')
367
419
  }
368
420
 
369
- async function downloadArtifact(artifact, targetDir, controller) {
421
+ function seedArtifactCache(plan, stagingRoot) {
422
+ ensureDir(insideRoot(cacheDir))
423
+ let dirs = []
424
+ try {
425
+ dirs = fs.readdirSync(stagingRoot, { withFileTypes: true })
426
+ .filter(entry => entry.isDirectory() && entry.name.startsWith('install-'))
427
+ .map(entry => entry.name)
428
+ } catch { return }
429
+ for (const artifact of plan.artifacts) {
430
+ const paths = cachePaths(cacheDir, artifact)
431
+ if (fs.existsSync(paths.final)) continue
432
+ let currentPart = 0
433
+ try { currentPart = fs.statSync(paths.part).size } catch {}
434
+ const wanted = `${artifactSafeName(artifact)}.tgz`
435
+ let best = null
436
+ for (const dir of dirs) {
437
+ const artifactDir = path.join(stagingRoot, dir, '.artifacts')
438
+ let files = []
439
+ try { files = fs.readdirSync(artifactDir) } catch { continue }
440
+ for (const name of files) {
441
+ if (name !== wanted) continue
442
+ try {
443
+ const stat = fs.statSync(path.join(artifactDir, name))
444
+ if (stat.isFile() && stat.size > 0 && stat.size <= artifact.bytes && (!best || stat.size > best.size)) {
445
+ best = { file: path.join(artifactDir, name), size: stat.size }
446
+ }
447
+ } catch {}
448
+ }
449
+ }
450
+ if (!best || best.size <= currentPart) continue
451
+ try {
452
+ fs.copyFileSync(best.file, paths.part)
453
+ warn(`seeded runtime artifact cache from previous staging: ${artifact.name} (${best.size} bytes)`)
454
+ } catch (error) {
455
+ warn(`cannot seed runtime artifact cache for ${artifact.name}: ${error?.message || error}`)
456
+ }
457
+ }
458
+ }
459
+
460
+ async function downloadArtifact(artifact, sourceId, controller, report) {
370
461
  if (!Number.isInteger(artifact.bytes) || artifact.bytes <= 0) throw failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', `artifact ${artifact.name} has no exact byte count`)
371
462
  if (artifact.bytes > maxArtifactBytes) throw failure('LOCAL_VECTOR_RUNTIME_TOO_LARGE', `artifact ${artifact.name} declares ${artifact.bytes} bytes, above the ${maxArtifactBytes} byte cap`)
372
- const target = path.join(targetDir, `${artifact.name.replace(/[^A-Za-z0-9._-]+/g, '-')}.tgz`)
463
+ const source = artifact.sources.find(item => item.id === sourceId) || artifact.sources[0] || null
464
+ const url = source?.url || artifact.url
465
+ if (!url) throw failure('LOCAL_VECTOR_RUNTIME_ARTIFACT_URL_INVALID', `artifact ${artifact.name} has no download URL`)
466
+ ensureDir(insideRoot(cacheDir))
467
+ const paths = cachePaths(cacheDir, artifact)
468
+ const bump = (bytes) => {
469
+ job.progress.bytes += bytes
470
+ const nowMs = Date.now()
471
+ const elapsed = (nowMs - (job.progress.speedAt || nowMs)) / 1000
472
+ if (elapsed >= 0.5) {
473
+ job.progress.speedBps = Math.max(0, (job.progress.bytes - (job.progress.speedBytes || 0)) / elapsed)
474
+ job.progress.speedAt = nowMs
475
+ job.progress.speedBytes = job.progress.bytes
476
+ report()
477
+ }
478
+ }
479
+ try {
480
+ const complete = fs.statSync(paths.final)
481
+ if (complete.size === artifact.bytes) {
482
+ const digest = await sha256File(paths.final)
483
+ if (digest === artifact.sha256) {
484
+ job.progress.bytes += artifact.bytes
485
+ report()
486
+ return { path: paths.final, bytes: artifact.bytes, sha256: digest, source: source?.id || null, cached: true }
487
+ }
488
+ }
489
+ try { fs.rmSync(paths.final, { force: true }) } catch {}
490
+ } catch {}
491
+ let existing = 0
492
+ try { existing = fs.statSync(paths.part).size } catch {}
493
+ if (existing > artifact.bytes) {
494
+ try { fs.rmSync(paths.part, { force: true }) } catch {}
495
+ existing = 0
496
+ }
497
+ if (existing === artifact.bytes) {
498
+ const digest = await sha256File(paths.part)
499
+ if (digest === artifact.sha256) {
500
+ await renameWithRetry(paths.part, paths.final)
501
+ job.progress.bytes += artifact.bytes
502
+ report()
503
+ return { path: paths.final, bytes: artifact.bytes, sha256: digest, source: source?.id || null, cached: true }
504
+ }
505
+ try { fs.rmSync(paths.part, { force: true }) } catch {}
506
+ existing = 0
507
+ }
508
+ if (existing > 0) {
509
+ job.progress.bytes += existing
510
+ // Speed is about the bytes this process receives, not the part inherited
511
+ // from the previous run; anchor the sample at the resumed offset.
512
+ job.progress.speedBytes = job.progress.bytes
513
+ job.progress.speedAt = Date.now()
514
+ job.progress.current = artifact.name
515
+ report()
516
+ }
517
+ const headers = { 'accept-encoding': 'identity' }
518
+ if (existing > 0) headers.Range = `bytes=${existing}-`
373
519
  let response
374
520
  try {
375
- response = await fetchImpl(artifact.url, { signal: controller.signal, redirect: 'follow', headers: { 'accept-encoding': 'identity' } })
521
+ response = await fetchImpl(url, { signal: controller.signal, redirect: 'follow', headers })
376
522
  } catch (error) {
377
523
  if (isAbort(error, controller.signal)) throw failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted', { cause: error })
378
524
  throw failure('LOCAL_VECTOR_RUNTIME_NETWORK_ERROR', `cannot fetch ${artifact.name}: ${error?.message || error}`, { cause: error })
379
525
  }
380
526
  if (!response || !response.ok) throw failure('LOCAL_VECTOR_RUNTIME_HTTP_ERROR', `registry returned ${response?.status ?? 'no response'} for ${artifact.name}`)
381
- const declared = Number(response.headers?.get?.('content-length'))
382
- if (Number.isFinite(declared) && declared > 0 && declared !== artifact.bytes) {
383
- throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} content-length ${declared} does not match the pinned ${artifact.bytes} bytes`)
527
+ let append = existing > 0
528
+ if (append && response.status === 200) {
529
+ // The source ignored Range. Keep the file correct by starting over; a later
530
+ // attempt may still resume from the new bytes.
531
+ job.progress.bytes = Math.max(0, job.progress.bytes - existing)
532
+ append = false
533
+ existing = 0
534
+ } else if (append) {
535
+ const contentRange = String(response.headers?.get?.('content-range') || '')
536
+ const match = /^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(contentRange)
537
+ if (!match || Number(match[1]) !== existing || Number(match[3]) !== artifact.bytes) {
538
+ throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} returned an unexpected Content-Range: ${contentRange || '(missing)'}`)
539
+ }
540
+ const declared = Number(response.headers?.get?.('content-length'))
541
+ if (Number.isFinite(declared) && declared > 0 && declared !== artifact.bytes - existing) {
542
+ throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} content-length ${declared} does not match the remaining ${artifact.bytes - existing} bytes`)
543
+ }
544
+ } else {
545
+ const declared = Number(response.headers?.get?.('content-length'))
546
+ if (Number.isFinite(declared) && declared > 0 && declared !== artifact.bytes) {
547
+ throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} content-length ${declared} does not match the pinned ${artifact.bytes} bytes`)
548
+ }
384
549
  }
385
- const hash = crypto.createHash('sha256')
386
- let size = 0
387
- const fd = fs.openSync(target, 'wx', 0o600)
550
+ let size = existing
551
+ const fd = fs.openSync(paths.part, append ? 'a' : 'w', 0o600)
388
552
  try {
389
553
  const body = response.body
390
554
  if (body && typeof body[Symbol.asyncIterator] === 'function') {
@@ -392,25 +556,27 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
392
556
  if (controller.signal.aborted) throw failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted')
393
557
  size += chunk.length
394
558
  if (size > artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} exceeded the pinned ${artifact.bytes} bytes`)
395
- hash.update(chunk)
396
559
  fs.writeSync(fd, chunk)
397
- job.progress.bytes += chunk.length
560
+ bump(chunk.length)
398
561
  }
399
562
  } else {
400
563
  const buffer = Buffer.from(await response.arrayBuffer())
401
- size = buffer.length
564
+ size += buffer.length
402
565
  if (size > artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} exceeded the pinned ${artifact.bytes} bytes`)
403
- hash.update(buffer)
404
566
  fs.writeSync(fd, buffer)
405
- job.progress.bytes += buffer.length
567
+ bump(buffer.length)
406
568
  }
407
569
  } finally {
408
570
  fs.closeSync(fd)
409
571
  }
410
572
  if (size !== artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} is ${size} bytes, expected ${artifact.bytes}`)
411
- const digest = hash.digest('hex')
412
- if (digest !== artifact.sha256) throw failure('LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', `${artifact.name} sha256 ${digest} does not match the pinned ${artifact.sha256}`)
413
- return { path: target, bytes: size, sha256: digest }
573
+ const digest = await sha256File(paths.part)
574
+ if (digest !== artifact.sha256) {
575
+ try { fs.rmSync(paths.part, { force: true }) } catch {}
576
+ throw failure('LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', `${artifact.name} sha256 ${digest} does not match the pinned ${artifact.sha256}`)
577
+ }
578
+ await renameWithRetry(paths.part, paths.final)
579
+ return { path: paths.final, bytes: size, sha256: digest, source: source?.id || null, cached: false }
414
580
  }
415
581
 
416
582
  function verifyExtracted(plan, dir) {
@@ -446,6 +612,12 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
446
612
  }
447
613
 
448
614
  async function install(plan, options) {
615
+ const requestedSource = options.source ? String(options.source) : null
616
+ const source = requestedSource
617
+ ? plan.sources.find(item => item.id === requestedSource)
618
+ : plan.sources[0] || null
619
+ if (requestedSource && !source) throw failure('LOCAL_VECTOR_RUNTIME_SOURCE_UNKNOWN', `unknown runtime download source: ${requestedSource}`)
620
+ const downloadSource = source?.id || null
449
621
  const controller = new AbortController()
450
622
  const onAbort = () => controller.abort()
451
623
  options.signal?.addEventListener('abort', onAbort, { once: true })
@@ -454,8 +626,9 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
454
626
  key: plan.key,
455
627
  state: 'downloading',
456
628
  startedAt: now(),
629
+ source: downloadSource,
457
630
  controller,
458
- progress: { artifacts: plan.artifacts.length, done: 0, bytes: 0, totalBytes, current: null },
631
+ progress: { artifacts: plan.artifacts.length, done: 0, bytes: 0, totalBytes, current: null, speedBps: 0, speedAt: Date.now(), speedBytes: 0 },
459
632
  }
460
633
  const report = () => { try { options.onProgress?.({ ...job.progress }) } catch {} }
461
634
  let staging = null
@@ -470,16 +643,20 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
470
643
  job = null
471
644
  return { status: 'installed', ready: true, reused: true, key: plan.key, platform: plan.platform, path: existing.dir, engine: plan.engine, version: plan.version, abi: plan.abi, installedAt: existing.record.installedAt || null, verifiedAt: existing.record.verifiedAt || null, checks: Array.isArray(existing.record.checks) ? existing.record.checks : [], artifacts: plan.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256 })), smoke: existing.record.smoke || null }
472
645
  }
646
+ // Pick up a partial download from an interrupted process. Old installers kept
647
+ // the tarball inside their own staging dir; this stable cache is what makes a
648
+ // restart resume instead of re-downloading 115 MB.
649
+ seedArtifactCache(plan, stagingRoot)
473
650
  staging = fs.mkdtempSync(path.join(stagingRoot, 'install-'))
474
- const artifactDir = ensureDir(path.join(staging, '.artifacts'))
475
651
  const archives = []
476
652
  for (const artifact of plan.artifacts) {
477
653
  if (controller.signal.aborted) throw failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted')
478
654
  job.progress.current = artifact.name
479
655
  report()
480
- const saved = await downloadArtifact(artifact, artifactDir, controller)
656
+ const saved = await downloadArtifact(artifact, downloadSource, controller, report)
481
657
  archives.push({ artifact, file: saved.path })
482
658
  job.progress.done += 1
659
+ report()
483
660
  }
484
661
  job.state = 'verifying'
485
662
  job.progress.current = null
@@ -490,7 +667,6 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
490
667
  const target = ensureDir(path.join(staging, RUNTIME_LAYOUT, artifact.name))
491
668
  await extract({ file, cwd: target, allowList, maxFileBytes, artifact })
492
669
  }
493
- try { fs.rmSync(artifactDir, { recursive: true, force: true }) } catch {}
494
670
  const checks = verifyExtracted(plan, staging)
495
671
  const files = inventoryTree(plan, staging)
496
672
  job.state = 'installing'
@@ -510,6 +686,7 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
510
686
  installedAt: now(),
511
687
  verifiedAt: now(),
512
688
  source: 'catalog-pinned',
689
+ downloadSource,
513
690
  postinstall: 'never-run',
514
691
  inventoryVersion: 1,
515
692
  artifacts: plan.artifacts.map(artifact => ({ name: artifact.name, version: artifact.version, url: artifact.url, bytes: artifact.bytes, sha256: artifact.sha256, integrity: artifact.integrity, license: artifact.license })),