@kingsleyasher/dsh-knowledge-base 3.1.4 → 3.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NPM-EDITION.md +12 -9
- package/PROJECT-RECORD.en.md +4 -0
- package/PROJECT-RECORD.md +4 -0
- package/package.json +2 -2
- package/packages/kb-core/src/kbcore.js +1 -1
- package/packages/kb-service/host-updates.js +96 -10
- package/packages/kb-service/safe-update.js +5 -5
- package/src/client/index.js +11 -16
- package/src/host/index.js +4 -8
- package/src/host/updates.js +5 -5
- package/tools/kb-transactional-update.py +19 -11
package/NPM-EDITION.md
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
# npm
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
1
|
+
# npm 发行版 / npm distribution
|
|
2
|
+
|
|
3
|
+
本包是 DeepSeek Harness(DSH)插件,包名为 `@kingsleyasher/dsh-knowledge-base`,包含 Windows Python 运行时。与 GitHub 旧版 `@local/dsh-knowledge-base` 的包身份不同。请只启用其中一份;旧版迁移尚未验证。
|
|
4
|
+
|
|
5
|
+
## 安装和更新
|
|
6
|
+
|
|
7
|
+
- 从 3.1.5 起,可在知识库版本栏检查 npm 的最新正式版。共享服务模式下,若当前包安装在 DSH 管理的配置目录,且服务支持安全交接,打开知识库界面后会自动下载安装,也可从版本栏手动操作。更新前会等待知识库任务结束,宿主如需重启会给出提示。
|
|
8
|
+
- 嵌入模式、链接安装等不能安全交接的环境显示新版信息,由 DSH 插件管理器安装。
|
|
9
|
+
- 已安装的 npm 3.1.4 需要先通过 DSH 更新一次,才能获得这套更新功能。使用 DSH 网页版时,可在关闭该 profile 的 DSH 进程后运行 `dsh plugin --profile web add @kingsleyasher/dsh-knowledge-base@latest`,再启动 DSH。桌面版在应用中管理。
|
|
10
|
+
- npm 版仅跟踪 npm 的 `latest` 正式版标签。源码和旧版发布记录见 [Personal-Knowledge-Base](https://github.com/KingsleyAsher/Personal-Knowledge-Base)。
|
|
11
|
+
|
|
12
|
+
Version 3.1.5 introduces stable npm update checks and automatic or manual installation in shared service mode where safe handoff is available. In embedded mode, use the host plugin manager to install the reported update. Existing npm 3.1.4 installations need one host-managed upgrade to acquire this feature.
|
package/PROJECT-RECORD.en.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
[English](PROJECT-RECORD.en.md) · [简体中文](PROJECT-RECORD.md)
|
|
4
4
|
|
|
5
|
+
## 2026-11-26 · Plugin npm 3.1.5 candidate · Update discovery and installation
|
|
6
|
+
|
|
7
|
+
The npm edition checks the registry for stable versions of its own package. With the knowledge base UI open, shared service installs that support safe handoff can update automatically or retry manually from the version badge. The updater checks npm SHA-512, package identity, version, and build, then uses the transaction installer and retains the recovery record. Embedded mode detects updates and leaves installation to DSH. The legacy GitHub edition retains its separate package identity. In an isolated profile on Windows DSH Desktop 0.2.2-rc.5, a 3.1.3 test fixture running the candidate updater automatically installed the public npm 3.1.4 package. The transaction committed and the plugin UI and shared service both loaded the new version. npm 3.1.5 publication is pending.
|
|
8
|
+
|
|
5
9
|
<!-- project-record-version: 3.1.4 -->
|
|
6
10
|
|
|
7
11
|
**Plugin 3.1.4; desktop client 2.0.3 · 2026-11-16.**
|
package/PROJECT-RECORD.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
[English](PROJECT-RECORD.en.md) · [简体中文](PROJECT-RECORD.md)
|
|
4
4
|
|
|
5
|
+
## 2026-11-26 · 插件 npm 3.1.5 候选 · 更新检测与安装
|
|
6
|
+
|
|
7
|
+
npm 版按包名检查 npm 的正式版更新。知识库界面打开时,支持安全停服的共享服务安装可以自动升级,也可从版本栏手动重试。更新核对 npm 的 SHA-512、包身份、版本和构建号,随后通过现有事务安装方式切换包、保留恢复记录。嵌入模式可检测新版,由 DSH 管理安装。旧 GitHub 版仍是独立包身份。在 Windows DSH 桌面 0.2.2-rc.5 的隔离配置中,使用候选代码构造的 3.1.3 测试版自动升级到 npm 正式 3.1.4,确认事务提交、插件界面及共享服务均加载新版。3.1.5 待发布。
|
|
8
|
+
|
|
5
9
|
<!-- project-record-version: 3.1.4 -->
|
|
6
10
|
|
|
7
11
|
**插件 3.1.4;客户端 2.0.3 · 2026-11-16。**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kingsleyasher/dsh-knowledge-base",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.5",
|
|
4
4
|
"description": "个人知识工作台:可控隐私、首次设置、目录地图、快速收集、阅读摘录、引用问答与按需备份。",
|
|
5
5
|
"icon": "./src/client/capture-icon.svg",
|
|
6
6
|
"type": "module",
|
|
@@ -74,5 +74,5 @@
|
|
|
74
74
|
"type": "git",
|
|
75
75
|
"url": "git+https://github.com/KingsleyAsher/Personal-Knowledge-Base.git"
|
|
76
76
|
},
|
|
77
|
-
"homepage": "https://github.com/KingsleyAsher/Personal-Knowledge-Base
|
|
77
|
+
"homepage": "https://github.com/KingsleyAsher/Personal-Knowledge-Base"
|
|
78
78
|
}
|
|
@@ -26,7 +26,7 @@ import {catalogActive,readCatalog,refreshCatalog,classifyOriginal} from './file-
|
|
|
26
26
|
import { CLASSIFICATION_VERSION } from './file-classification.js'
|
|
27
27
|
|
|
28
28
|
// 版本单一来源:package.json 的 version 必须与此一致(详见 INSTALL 说明)
|
|
29
|
-
export const VERSION = '3.1.
|
|
29
|
+
export const VERSION = '3.1.5'
|
|
30
30
|
|
|
31
31
|
export const REQUIRED_FIELDS = ['title', 'type', 'tags', 'status', 'updated']
|
|
32
32
|
export const SCHEMA_VERSION = 1
|
|
@@ -1,11 +1,97 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
|
3
|
+
import os from 'node:os'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { createSafeUpdate } from './safe-update.js'
|
|
6
|
+
import { readCandidateBuild } from './build.js'
|
|
7
|
+
import { compareStableVersions, readUpdateSourceBytes, startAutomaticChecks, UPDATE_INTERVAL_MS } from '../../src/host/updates.js'
|
|
8
|
+
|
|
9
|
+
const PACKAGE = '@kingsleyasher/dsh-knowledge-base'
|
|
10
|
+
const registry = 'https://registry.npmjs.org'
|
|
11
|
+
const registrySource = { id: 'npm', hosts: ['registry.npmjs.org'], file: url => url }
|
|
12
|
+
const packagePage = 'https://www.npmjs.com/package/' + PACKAGE
|
|
13
|
+
const stable = /^\d+\.\d+\.\d+$/
|
|
14
|
+
const sha512 = /^sha512-[A-Za-z0-9+/]{86}==$/
|
|
15
|
+
|
|
16
|
+
export function createNpmUpdateChecker({ currentVersion, fetch = globalThis.fetch, now = Date.now }) {
|
|
17
|
+
let cache, expiresAt = 0, pending
|
|
18
|
+
return {
|
|
19
|
+
check({ force = false } = {}) {
|
|
20
|
+
if (pending) return pending
|
|
21
|
+
if (!force && cache && now() < expiresAt) return Promise.resolve(cache)
|
|
22
|
+
pending = (async () => {
|
|
23
|
+
const base = { distribution: 'npm', currentVersion, currentChannel: 'stable', channel: 'stable', sourceName: 'npm', notesUrl: packagePage }
|
|
24
|
+
try {
|
|
25
|
+
const url = registry + '/' + encodeURIComponent(PACKAGE) + '/latest'
|
|
26
|
+
const raw = await readUpdateSourceBytes(fetch, registrySource, url, 1024 * 1024, 8000)
|
|
27
|
+
const manifest = JSON.parse(raw)
|
|
28
|
+
const { version, dist } = manifest
|
|
29
|
+
const archiveUrl = registry + '/' + PACKAGE + '/-/dsh-knowledge-base-' + version + '.tgz'
|
|
30
|
+
if (manifest.name !== PACKAGE || !stable.test(version) || dist?.tarball !== archiveUrl || !sha512.test(dist.integrity)) {
|
|
31
|
+
throw Error('npm 返回的版本或安装包信息无效')
|
|
32
|
+
}
|
|
33
|
+
const comparison = compareStableVersions(version, currentVersion)
|
|
34
|
+
return { ...base, ok: true, onlineChecked: true, latestVersion: version, updateAvailable: comparison > 0,
|
|
35
|
+
autoInstallEligible: comparison > 0, ahead: comparison < 0, integrity: dist.integrity, archiveUrl }
|
|
36
|
+
} catch (error) {
|
|
37
|
+
return { ...base, ok: false, updateAvailable: false, error: 'npm 更新检查失败:' + error.message }
|
|
38
|
+
}
|
|
39
|
+
})().then(result => {
|
|
40
|
+
cache = result
|
|
41
|
+
expiresAt = now() + (result.ok ? UPDATE_INTERVAL_MS : 5 * 60 * 1000)
|
|
42
|
+
return result
|
|
43
|
+
}).finally(() => { pending = null })
|
|
44
|
+
return pending
|
|
45
|
+
},
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function createHostUpdates({ ctx, build, profileDir, fetch = globalThis.fetch,
|
|
50
|
+
packageRoot = path.resolve(import.meta.dirname, '../..'), quiesce, resume, withUpdateLock }) {
|
|
51
|
+
const checker = createNpmUpdateChecker({ currentVersion: build.version, fetch })
|
|
52
|
+
const directory = ctx.get('profileContext')?.dir || profileDir
|
|
53
|
+
const installedRoot = directory && path.join(directory, 'node_modules', PACKAGE)
|
|
54
|
+
const hmr = ctx.get('hmr')
|
|
55
|
+
const canActivate = typeof hmr?.runExclusive === 'function' && typeof hmr?.reconcileProfile === 'function'
|
|
56
|
+
const safe = installedRoot && quiesce && withUpdateLock && createSafeUpdate({
|
|
57
|
+
profileDir: directory, packageRoot, installedRoot, journalName: '.kb-npm-updates',
|
|
58
|
+
quiesce, resume, withUpdateLock, activeBuild: build,
|
|
59
|
+
activate: canActivate ? () => hmr.runExclusive(() => hmr.reconcileProfile()) : undefined,
|
|
60
|
+
})
|
|
61
|
+
const installedHere = Boolean(installedRoot && path.relative(installedRoot, packageRoot) === '')
|
|
62
|
+
const supported = Boolean(safe && installedHere)
|
|
63
|
+
const unavailable = () => ({ ok: false, code: 'NPM_MANAGED_UPDATE',
|
|
64
|
+
error: '当前安装模式无法安全交接知识库,请通过 DSH 插件管理器更新 npm 版。' })
|
|
65
|
+
let preparing
|
|
66
|
+
ctx.effect(() => startAutomaticChecks(checker), 'kb-service: npm update checks')
|
|
67
|
+
return {
|
|
68
|
+
async check(body = {}) {
|
|
69
|
+
return { ...await checker.check({ force: body.force === true }), installSupported: supported }
|
|
70
|
+
},
|
|
71
|
+
status: () => supported ? safe.status() : { phase: 'none', installSupported: false },
|
|
72
|
+
install: body => supported ? safe.install(body) : unavailable(),
|
|
73
|
+
async prepare({ expectedVersion } = {}) {
|
|
74
|
+
if (!supported) return unavailable()
|
|
75
|
+
if (preparing) throw Error('另一个 npm 更新正在准备')
|
|
76
|
+
preparing = true
|
|
77
|
+
let temp
|
|
78
|
+
try {
|
|
79
|
+
const installed = await readCandidateBuild(installedRoot)
|
|
80
|
+
if (installed.version !== build.version || installed.buildId !== build.buildId) throw Error('已安装的插件发生变化,请先重启 DSH')
|
|
81
|
+
const release = await checker.check({ force: true })
|
|
82
|
+
if (!release.ok) throw Error(release.error)
|
|
83
|
+
if (!release.updateAvailable || release.latestVersion !== expectedVersion) throw Error('npm 最新版本已变化,请重新检查')
|
|
84
|
+
const raw = await readUpdateSourceBytes(fetch, registrySource, release.archiveUrl, 64 * 1024 * 1024, 20000)
|
|
85
|
+
if ('sha512-' + createHash('sha512').update(raw).digest('base64') !== release.integrity) throw Error('npm 安装包完整性校验失败')
|
|
86
|
+
temp = await mkdtemp(path.join(os.tmpdir(), 'kb-npm-update-'))
|
|
87
|
+
const spec = path.join(temp, 'plugin.tgz')
|
|
88
|
+
await writeFile(spec, raw, { flag: 'wx', mode: 0o600 })
|
|
89
|
+
return await safe.prepare({ spec, latestVersion: expectedVersion, currentVersion: build.version, bytes: raw.length,
|
|
90
|
+
sha256: createHash('sha256').update(raw).digest('hex'), integrity: release.integrity })
|
|
91
|
+
} finally {
|
|
92
|
+
preparing = false
|
|
93
|
+
if (temp) await rm(temp, { recursive: true, force: true }).catch(() => {})
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
}
|
|
11
97
|
}
|
|
@@ -8,9 +8,9 @@ import { readCandidateBuild } from './build.js'
|
|
|
8
8
|
|
|
9
9
|
// The worker and Python live outside the replaceable package. The receipt is
|
|
10
10
|
// durable, so losing the HTTP/HMR reply never means installation is repeated.
|
|
11
|
-
export function createSafeUpdate({ profileDir, packageRoot, quiesce, resume, withUpdateLock = task => task(), activate, activeBuild }) {
|
|
11
|
+
export function createSafeUpdate({ profileDir, packageRoot, quiesce, resume, withUpdateLock = task => task(), activate, activeBuild, installedRoot = path.join(profileDir, 'node_modules/@local/dsh-knowledge-base'), journalName = '.kb-safe-updates' }) {
|
|
12
12
|
let operation
|
|
13
|
-
const home = path.join(profileDir,
|
|
13
|
+
const home = path.join(profileDir, journalName)
|
|
14
14
|
async function ensureHome(){const python=await resolveHostPython(packageRoot,{home:path.join(profileDir,'.kb-update-python')});await native(python,'private-dir',{path:home});return python}
|
|
15
15
|
async function invoke(action, args = []) {
|
|
16
16
|
const source = await readFile(path.join(packageRoot, 'tools/kb-transactional-update.py'))
|
|
@@ -56,10 +56,10 @@ export function createSafeUpdate({ profileDir, packageRoot, quiesce, resume, wit
|
|
|
56
56
|
return {
|
|
57
57
|
async prepare(prepared) {
|
|
58
58
|
if (operation) throw Error('另一个安全更新正在进行')
|
|
59
|
-
const expected = path.join(home, 'expected-' + prepared.buildId + '.json')
|
|
59
|
+
const expected = path.join(home, 'expected-' + (prepared.buildId || prepared.sha256) + '.json')
|
|
60
60
|
await ensureHome(); await writeFile(expected, JSON.stringify(prepared), { mode: 0o600 })
|
|
61
61
|
const plan = await invoke('prepare', ['--archive', prepared.spec, '--expected', expected])
|
|
62
|
-
return { ...prepared, safeInstall: true, hotActivation: Boolean(activate), transactionId: plan.transactionId }
|
|
62
|
+
return { ...prepared, ok: true, buildId: plan.buildId || prepared.buildId, safeInstall: true, hotActivation: Boolean(activate), transactionId: plan.transactionId }
|
|
63
63
|
},
|
|
64
64
|
install({ transactionId, expectedVersion }) {
|
|
65
65
|
if (operation) return operation
|
|
@@ -95,7 +95,7 @@ export function createSafeUpdate({ profileDir, packageRoot, quiesce, resume, wit
|
|
|
95
95
|
let writerBusy
|
|
96
96
|
try{await stat(path.join(profileDir,'package.json.lock'));writerBusy=true}catch(error){if(error.code!=='ENOENT')throw error;writerBusy=false}
|
|
97
97
|
let installedBuild
|
|
98
|
-
try{const build=await readCandidateBuild(
|
|
98
|
+
try{const build=await readCandidateBuild(installedRoot);installedBuild={version:build.version,buildId:build.buildId}}catch{/* incomplete package is never proof that retry is safe */}
|
|
99
99
|
return { phase: plan.phase, version: plan.version, buildId: plan.buildId, transactionId: plan.work, restartRequired: plan.phase === 'committed',
|
|
100
100
|
confirmationProtocol:1,operationActive:Boolean(operation),writerBusy,installedBuild,
|
|
101
101
|
canRetryLegacy:Boolean(installedBuild&&!operation&&!writerBusy&&['none','committed','aborted','rolled-back'].includes(plan.phase)) }
|
package/src/client/index.js
CHANGED
|
@@ -3342,7 +3342,7 @@ body:not([data-ds-dark-theme]) .kbm option{background:#fff;color:#0f1115}
|
|
|
3342
3342
|
// A host-owned installation can outlive this module during HMR. Persist its
|
|
3343
3343
|
// request ID, then reconcile via the native manager and the active build.
|
|
3344
3344
|
function createClientUpdateFlow({ api, manager, storage, notify, clientVersion = () => null, retryLater, delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }) {
|
|
3345
|
-
const key = 'dsh-kb-update-operation'
|
|
3345
|
+
const key = 'dsh-kb-npm-update-operation'
|
|
3346
3346
|
let running = null, retryQueued = false
|
|
3347
3347
|
const read = () => { try { return JSON.parse(storage.getItem(key)) } catch { return null } }
|
|
3348
3348
|
const save = (record) => { try { storage.setItem(key, JSON.stringify(record)) } catch { throw Error('无法保存更新状态,请检查客户端存储后重试') } }
|
|
@@ -3482,8 +3482,6 @@ body:not([data-ds-dark-theme]) .kbm option{background:#fff;color:#0f1115}
|
|
|
3482
3482
|
}
|
|
3483
3483
|
return
|
|
3484
3484
|
}
|
|
3485
|
-
const remote = manager()
|
|
3486
|
-
if (typeof remote?.installBundle !== 'function' || typeof remote?.waitForInstall !== 'function') throw Error('当前宿主未提供客户端安装接口,请使用宿主插件管理器')
|
|
3487
3485
|
show('正在下载并校验安装包…', { busy: true })
|
|
3488
3486
|
const prepared = await api({ op: 'updates.prepare', expectedVersion })
|
|
3489
3487
|
if (!prepared?.ok || prepared.latestVersion !== expectedVersion || !/^[a-f0-9]{16}$/.test(prepared.buildId || '') || typeof prepared.spec !== 'string') throw Error(prepared?.error || '下载结果无效')
|
|
@@ -3547,17 +3545,14 @@ body:not([data-ds-dark-theme]) .kbm option{background:#fff;color:#0f1115}
|
|
|
3547
3545
|
}
|
|
3548
3546
|
function isAutomaticUpdate(update) {
|
|
3549
3547
|
return update?.ok && update.updateAvailable === true && update.autoInstallEligible === true && update.installSupported !== false &&
|
|
3550
|
-
|
|
3548
|
+
Boolean(update.integrity && update.latestVersion)
|
|
3551
3549
|
}
|
|
3552
3550
|
function maybeAutoInstallUpdate(update = buildBadgeState.update) {
|
|
3553
3551
|
const candidates = availableUpdates({ ...buildBadgeState, update }).map(release => ({ ...release, installSupported: update?.installSupported })).filter(isAutomaticUpdate).sort((a,b) => compareReleaseVersions(b.latestVersion,a.latestVersion))
|
|
3554
3552
|
update = candidates[0]
|
|
3555
3553
|
if (!update) return
|
|
3556
|
-
const manager = updateManager
|
|
3557
|
-
if (typeof manager?.installBundle !== 'function' || typeof manager?.waitForInstall !== 'function') return
|
|
3558
3554
|
if (updateViewState.busy || updateViewState.uncertain || updateViewState.restartRequired || updateViewState.refreshRequired) return
|
|
3559
|
-
|
|
3560
|
-
const attempt = update.latestVersion + ':' + update.buildId
|
|
3555
|
+
const attempt = update.latestVersion + ':' + update.integrity
|
|
3561
3556
|
if (automaticUpdateAttempts.has(attempt)) return
|
|
3562
3557
|
automaticUpdateAttempts.add(attempt)
|
|
3563
3558
|
void updateFlow.install(update.latestVersion)
|
|
@@ -3611,17 +3606,16 @@ body:not([data-ds-dark-theme]) .kbm option{background:#fff;color:#0f1115}
|
|
|
3611
3606
|
if (update.channel === 'local' || update.status === 'candidate' || update.checkSkipped) return update.message || '本机试用版尚未进行在线更新检查'
|
|
3612
3607
|
if (update.migrationRequired) return update.updateAvailable ? '发现正式版 ' + update.latestVersion + ';本机试用版需手动迁移' : '本机试用版;正式发布版本 ' + update.latestVersion
|
|
3613
3608
|
if (!update.onlineChecked && !update.sourceStatus?.some(source => source.ok)) return update.message || '尚未完成在线更新检查'
|
|
3614
|
-
if (update.updateAvailable) return '发现新版本 ' + update.latestVersion
|
|
3609
|
+
if (update.updateAvailable) return '发现新版本 ' + update.latestVersion + (update.installSupported === false ? ',请通过 DSH 插件管理器更新' : '')
|
|
3615
3610
|
if (update.ahead) return '当前版本高于更新源;最新发布版本 ' + update.latestVersion
|
|
3616
3611
|
return update.currentChannel === 'preview' ? '已是最新预览版' : '已是最新正式版'
|
|
3617
3612
|
}
|
|
3618
3613
|
function BuildBadge({ passive = false } = {}) {
|
|
3619
3614
|
const { version, update, checking } = react.useSyncExternalStore(subscribeBuildBadge, getBuildBadge, getBuildBadge)
|
|
3620
3615
|
const [updating, setUpdating] = react.useState(updateViewState)
|
|
3621
|
-
const [canInstall, setCanInstall] = react.useState(Boolean(updateManager))
|
|
3622
3616
|
react.useEffect(() => {
|
|
3623
3617
|
const changed = (event) => { if (event.detail) setUpdating(event.detail) }
|
|
3624
|
-
const capability = () => {
|
|
3618
|
+
const capability = () => { void updateFlow.recover() }
|
|
3625
3619
|
window.addEventListener('kb-plugin-update', changed)
|
|
3626
3620
|
window.addEventListener('kb-update-capability', capability)
|
|
3627
3621
|
capability()
|
|
@@ -3645,7 +3639,7 @@ body:not([data-ds-dark-theme]) .kbm option{background:#fff;color:#0f1115}
|
|
|
3645
3639
|
...(update.preview?.downloadSources || []).map(s => e('a', { key: 'preview-' + s.id, href: s.url, target: '_blank', rel: 'noopener noreferrer', style: { marginRight: 12 } }, s.name + ' 预览版下载'))) : null,
|
|
3646
3640
|
!checking && update?.preview?.updateAvailable ? e(react.Fragment, null,
|
|
3647
3641
|
e('span', { role: 'status' }, '发现可选预览版 ' + update.preview.latestVersion + '(测试版本,按需选择)'),
|
|
3648
|
-
e('button', { className: 'kbc-btn kbc-btn-ghost', disabled:
|
|
3642
|
+
e('button', { className: 'kbc-btn kbc-btn-ghost', disabled: update.installSupported === false || updating.busy || updating.uncertain || updating.restartRequired || updating.refreshRequired,
|
|
3649
3643
|
onClick: () => { void updateFlow.install(update.preview.latestVersion) } }, '安装预览版'),
|
|
3650
3644
|
e('a', { href: update.preview.notesUrl, target: '_blank', rel: 'noopener noreferrer' }, '预览版说明')) : null,
|
|
3651
3645
|
!checking && update?.preview?.available === false ? e('span', { role: 'status' }, '暂无预览版') : null,
|
|
@@ -3654,8 +3648,8 @@ body:not([data-ds-dark-theme]) .kbm option{background:#fff;color:#0f1115}
|
|
|
3654
3648
|
updating.uncertain ? e('button', { className: 'kbc-btn kbc-btn-ghost', disabled: updating.busy, onClick: () => { void updateFlow.recover() } }, '核对更新状态') : null,
|
|
3655
3649
|
updating.refreshRequired ? e('button', { className: 'kbc-btn kbc-btn-ghost', onClick: () => window.location.reload() }, '刷新界面') : null,
|
|
3656
3650
|
!checking && update && update.ok && update.updateAvailable
|
|
3657
|
-
? e('button', { className: 'kbc-btn kbc-btn-ghost', disabled:
|
|
3658
|
-
title:
|
|
3651
|
+
? e('button', { className: 'kbc-btn kbc-btn-ghost', disabled: update.installSupported === false || updating.busy || updating.uncertain || updating.restartRequired || updating.refreshRequired,
|
|
3652
|
+
title: update.installSupported !== false ? '自动下载、校验并由 DSH 安装;支持时直接热加载' : '当前模式请通过 DSH 插件管理器更新',
|
|
3659
3653
|
onClick: () => { void updateFlow.install(update.latestVersion) } }, updating.busy ? '更新中…' : '安装新版本') : null)
|
|
3660
3654
|
}
|
|
3661
3655
|
|
|
@@ -3733,7 +3727,7 @@ body:not([data-ds-dark-theme]) .kbm option{background:#fff;color:#0f1115}
|
|
|
3733
3727
|
if((updating.manualHelp||handoffError)&&!helpClosed)return reactDom.createPortal(e('div',{className:'kb-release-backdrop'},e('section',{className:'kb-release-card',role:'alertdialog','aria-modal':'true','aria-label':'更新未完成'},
|
|
3734
3728
|
e('h2',null,'自动更新未完成'),e('p',null,handoffError?'旧服务交接暂未完成,请等待现有任务结束或按恢复说明处理。':updating.message),
|
|
3735
3729
|
e('p',null,'请勿反复安装或清空知识库与解析记录。保存工作后,可按说明核对状态并恢复安装。'),
|
|
3736
|
-
e('a',{href:'https://
|
|
3730
|
+
e('a',{href:'https://www.npmjs.com/package/@kingsleyasher/dsh-knowledge-base',target:'_blank',rel:'noopener noreferrer'},'查看 npm 安装与更新说明'),
|
|
3737
3731
|
e('button',{className:'kb-update-install',onClick:()=>{updateFailureMemory.dismiss(failureKey);setHelpClosed(true);window.dispatchEvent(new CustomEvent('kb-update-failure-dismissed'))}},'关闭'))),document.body)
|
|
3738
3732
|
if (updating.restartRequired && !restartDeferred) return reactDom.createPortal(e('div', { className: 'kb-release-backdrop', role: 'presentation' },
|
|
3739
3733
|
e('section', { className: 'kb-release-card', role: 'alertdialog', 'aria-modal': 'true', 'aria-labelledby': 'kb-restart-title', 'aria-describedby': 'kb-restart-intro' },
|
|
@@ -4647,11 +4641,12 @@ body:not([data-ds-dark-theme]) .kbm option{background:#fff;color:#0f1115}
|
|
|
4647
4641
|
}
|
|
4648
4642
|
// END GENERATED TODO LIFECYCLE UI
|
|
4649
4643
|
|
|
4650
|
-
const RELEASE_VERSION = '3.1.
|
|
4644
|
+
const RELEASE_VERSION = '3.1.5'
|
|
4651
4645
|
const RELEASE_NOTICE_STATE_KEY = 'dsh-kb-release-state'
|
|
4652
4646
|
// Keep shipped releases for summaries of versions skipped during this upgrade.
|
|
4653
4647
|
// Patch-only installs stay quiet; unread older notes do not widen the range.
|
|
4654
4648
|
const RELEASE_NOTICES = [
|
|
4649
|
+
{version:'3.1.5',items:['npm 版插件可检查正式版更新,并在支持安全交接的 DSH 安装中自动升级。']},
|
|
4655
4650
|
{version:'3.1.4',items:['修复 OCR 服务保存失败时只显示 HTTP 400,显示具体的配置校验原因。']},
|
|
4656
4651
|
{version:'3.1.3',items:['文件树与目录读取改用缓存:未变化的资料库不再每次重读目录和排除策略,客户端展开目录只请求新增项。','索引巡检在内容未变化时复用已有目录,减少周期性卡顿;资料内容变化仍会重新核对。']},
|
|
4657
4652
|
{version:'3.1.2',items:['共享模式补回解析工具说明和全体 Agent 规则:当前服务设置优先于记忆。','默认 OCR/ASR 失败时说明原因并询问,未经本次明确同意不切换本机、其他云端或脚本。']},
|
package/src/host/index.js
CHANGED
|
@@ -31,7 +31,8 @@ import { installCommandDescriptionFallback } from './command-description.js'
|
|
|
31
31
|
import { apply as applyTodoLifecycle } from './todo-lifecycle.js'
|
|
32
32
|
import { createFlowEngine } from './flows.js'
|
|
33
33
|
import { createFlowWorkspaceManager, prepareFlowConversation } from './flow-workspace.js'
|
|
34
|
-
import {
|
|
34
|
+
import { startAutomaticChecks, downloadBrowserExtension } from './updates.js'
|
|
35
|
+
import { createNpmUpdateChecker } from '../../packages/kb-service/host-updates.js'
|
|
35
36
|
import { runSelftest } from './selftest.js'
|
|
36
37
|
import { walkTree, privateRootOf, normSegs, toPosix as toPosixFile, DEFAULT_PRIVATE_DIRS, readImportSources, derivedPrivatePartitions, effectivePrivateDirs, knowledgeCount } from './fsindex.js'
|
|
37
38
|
import { createImportService } from './import-service.js'
|
|
@@ -280,10 +281,7 @@ export function apply(ctx, config) {
|
|
|
280
281
|
return () => { clearInterval(timer); embeddedKernel.dispose() }
|
|
281
282
|
}, 'kb-workbench: opt-in background maintenance')
|
|
282
283
|
const flowWorkspaceManager = createFlowWorkspaceManager({ getRegistry: () => ctx.get('workspaceRegistry') })
|
|
283
|
-
const updateChecker =
|
|
284
|
-
const updateProfile = ctx.get('profileContext')
|
|
285
|
-
const updateDownloader = createUpdateDownloader({ checker: updateChecker,
|
|
286
|
-
cacheDir: typeof updateProfile?.dir === 'string' ? path.join(updateProfile.dir, '.kb-plugin-updates') : null })
|
|
284
|
+
const updateChecker = createNpmUpdateChecker({ currentVersion: PLUGIN_VERSION })
|
|
287
285
|
// 自动检查属于宿主后台机制,页面关闭后仍继续按周期检查。
|
|
288
286
|
ctx.effect(() => startAutomaticChecks(updateChecker), 'kb-core: automatic update checks')
|
|
289
287
|
// R1:UI 与工具共用的导入服务。在 install() 里创建(要等 core 就绪后才拿得到配置)。
|
|
@@ -1837,9 +1835,7 @@ let parsingService = null
|
|
|
1837
1835
|
(origin && (() => { try { return new URL(origin).host !== req.headers.host } catch { return true } })())) {
|
|
1838
1836
|
return kbSendJson(res, 403, { ok: false, error: '更新请求必须来自当前客户端' })
|
|
1839
1837
|
}
|
|
1840
|
-
return kbSendJson(res,409,{ok:false,error:'
|
|
1841
|
-
try { return kbSendJson(res, 200, await updateDownloader.prepare({ expectedVersion: body.expectedVersion })) }
|
|
1842
|
-
catch (error) { return kbSendJson(res, 400, { ok: false, error: String(error.message || error) }) }
|
|
1838
|
+
return kbSendJson(res,409,{ok:false,error:'嵌入模式暂不支持安全停服,请通过 DSH 插件管理器更新 npm 版。'})
|
|
1843
1839
|
}
|
|
1844
1840
|
if (body.op === 'index-maintenance.status') {
|
|
1845
1841
|
const status = await current.status()
|
package/src/host/updates.js
CHANGED
|
@@ -48,7 +48,7 @@ function selectedSources(ids) {
|
|
|
48
48
|
|
|
49
49
|
// Follow only a bounded set of HTTPS redirects belonging to the selected service.
|
|
50
50
|
// No cookies, authorization, mirror-provided download URLs or user paths are sent.
|
|
51
|
-
async function
|
|
51
|
+
export async function readUpdateSourceBytes(fetchFn, source, rel, limit, timeoutMs) {
|
|
52
52
|
const controller = new AbortController()
|
|
53
53
|
let timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
54
54
|
// Large archives may take longer than a metadata request. Bound idle time
|
|
@@ -102,7 +102,7 @@ export function createUpdateChecker({ currentVersion, fetch: fetchFn = globalThi
|
|
|
102
102
|
async function channel(preview) {
|
|
103
103
|
const results = await Promise.all(sources.map(async source => {
|
|
104
104
|
try {
|
|
105
|
-
const raw = await
|
|
105
|
+
const raw = await readUpdateSourceBytes(fetchFn, source, preview ? 'preview-manifest.json' : 'release-manifest-v2.json', 1024 * 1024, timeoutMs)
|
|
106
106
|
const m = JSON.parse(raw.toString('utf8'))
|
|
107
107
|
if (preview && m.package === '@local/dsh-knowledge-base' && m.channel === 'preview' && m.active === false) return { source, ok: true, inactive: true }
|
|
108
108
|
const parsedVersion = parseKnowledgeVersion(m.version, { allowLegacyPreview: preview })
|
|
@@ -231,7 +231,7 @@ export function createUpdateDownloader({ checker, cacheDir, fetch: fetchFn = glo
|
|
|
231
231
|
while (!failed && next < count) {
|
|
232
232
|
const index = next++, bytes = Math.min(UPDATE_PART_BYTES, release.bytes - index * UPDATE_PART_BYTES)
|
|
233
233
|
const rel = 'dist/update-parts/' + release.sha256 + '/' + String(index).padStart(4, '0') + '.b64'
|
|
234
|
-
const encoded = await
|
|
234
|
+
const encoded = await readUpdateSourceBytes(fetchFn, source, rel, Math.ceil(bytes / 3) * 4 + 1, timeoutMs)
|
|
235
235
|
const text = encoded.toString('utf8').trim()
|
|
236
236
|
if (text.length % 4 || !/^[A-Za-z0-9+/]*={0,2}$/.test(text)) throw Error('更新分片编码无效')
|
|
237
237
|
const part = Buffer.from(text, 'base64')
|
|
@@ -242,7 +242,7 @@ export function createUpdateDownloader({ checker, cacheDir, fetch: fetchFn = glo
|
|
|
242
242
|
const failure = results.find(r => r.status === 'rejected')
|
|
243
243
|
if (failure) throw failure.reason
|
|
244
244
|
raw = Buffer.concat(parts)
|
|
245
|
-
} else raw = await
|
|
245
|
+
} else raw = await readUpdateSourceBytes(fetchFn, source, 'dist/' + encodeURIComponent(release.tgz), release.bytes, timeoutMs)
|
|
246
246
|
verifyUpdateArchive(raw, release)
|
|
247
247
|
await writeFile(temporary, raw, { flag: 'wx', mode: 0o600 })
|
|
248
248
|
try { await unlink(target) } catch (error) { if (error.code !== 'ENOENT') throw error }
|
|
@@ -272,7 +272,7 @@ export async function downloadBrowserExtension({ fetch: fetchFn = globalThis.fet
|
|
|
272
272
|
const errors = []
|
|
273
273
|
for (const source of UPDATE_SOURCES) {
|
|
274
274
|
try {
|
|
275
|
-
const raw = await
|
|
275
|
+
const raw = await readUpdateSourceBytes(fetchFn, source, 'dist/knowledge-base-browser-extension.zip', 4 * 1024 * 1024, timeoutMs)
|
|
276
276
|
if (createHash('sha256').update(raw).digest('hex') !== EXTENSION_ARCHIVE_SHA256) throw Error('扩展文件校验失败')
|
|
277
277
|
return { ok: true, filename: 'knowledge-base-browser-extension.zip', base64: raw.toString('base64') }
|
|
278
278
|
} catch (error) { errors.push(source.name + ':' + String(error.message || error)) }
|
|
@@ -7,7 +7,7 @@ from pathlib import Path
|
|
|
7
7
|
from contextlib import contextmanager
|
|
8
8
|
import argparse, base64, hashlib, json, os, re, shutil, subprocess, sys, tarfile, uuid
|
|
9
9
|
|
|
10
|
-
PACKAGE = '@
|
|
10
|
+
PACKAGE = '@kingsleyasher/dsh-knowledge-base'
|
|
11
11
|
METADATA = ('package.json', 'pnpm-lock.yaml')
|
|
12
12
|
|
|
13
13
|
def sha(data): return hashlib.sha256(data).hexdigest()
|
|
@@ -65,13 +65,15 @@ def profile_lock(profile):
|
|
|
65
65
|
|
|
66
66
|
def locations(profile):
|
|
67
67
|
profile = profile.resolve(strict=True)
|
|
68
|
-
plugin = profile / 'node_modules
|
|
68
|
+
plugin = profile / 'node_modules' / PACKAGE
|
|
69
69
|
if plugin.is_symlink() or plugin.is_junction(): raise RuntimeError('Linked installations require a Host-managed migration')
|
|
70
|
-
return profile, plugin, profile / '.kb-
|
|
70
|
+
return profile, plugin, profile / '.kb-npm-updates/transaction.json'
|
|
71
71
|
|
|
72
72
|
def validate_archive(archive, expected, destination):
|
|
73
73
|
raw = archive.read_bytes()
|
|
74
|
-
|
|
74
|
+
integrity = 'sha512-' + base64.b64encode(hashlib.sha512(raw).digest()).decode('ascii')
|
|
75
|
+
if len(raw) != expected['bytes'] or sha(raw) != expected['sha256'] or integrity != expected['integrity']:
|
|
76
|
+
raise RuntimeError('Archive digest mismatch')
|
|
75
77
|
seen = set(); total = 0
|
|
76
78
|
with tarfile.open(archive, 'r:gz') as stream:
|
|
77
79
|
for entry in stream:
|
|
@@ -100,8 +102,7 @@ def validate_archive(archive, expected, destination):
|
|
|
100
102
|
for name in files:
|
|
101
103
|
if name not in extracted: raise RuntimeError('Build inventory path missing')
|
|
102
104
|
digest.update((name + '\0' + sha((destination / name).read_bytes()) + '\n').encode())
|
|
103
|
-
|
|
104
|
-
return pkg
|
|
105
|
+
return pkg, digest.hexdigest()[:16]
|
|
105
106
|
|
|
106
107
|
def lock_entries(lines, start, end, indent):
|
|
107
108
|
rows = []
|
|
@@ -174,13 +175,16 @@ def prepare(profile, archive, expected, pnpm=None):
|
|
|
174
175
|
if not (plugin / 'package.json').is_file(): raise RuntimeError('Existing plugin is incomplete; use the recovery installer with a trusted old package')
|
|
175
176
|
work = journal.parent / ('transaction-' + uuid.uuid4().hex); work.mkdir(parents=True)
|
|
176
177
|
candidate = work / 'candidate'; candidate.mkdir()
|
|
177
|
-
|
|
178
|
+
current = json.loads((plugin / 'package.json').read_text(encoding='utf-8'))
|
|
179
|
+
if current.get('name') != PACKAGE or current.get('version') != expected['currentVersion']:
|
|
180
|
+
raise RuntimeError('The installed npm package changed; restart and check again')
|
|
181
|
+
pkg, build_id = validate_archive(archive, expected, candidate)
|
|
178
182
|
old = {name: base64.b64encode(data).decode() if (data := read(profile / name)) is not None else None for name in METADATA}
|
|
179
183
|
shadow = work / 'profile'; shadow.mkdir()
|
|
180
184
|
for name in (*METADATA, '.npmrc', 'pnpm-workspace.yaml'):
|
|
181
185
|
if (profile / name).is_file(): shutil.copyfile(profile / name, shadow / name)
|
|
182
186
|
staged_config = json.loads(json.dumps(config))
|
|
183
|
-
staged_config['dependencies'][PACKAGE] = '
|
|
187
|
+
staged_config['dependencies'][PACKAGE] = pkg['version']
|
|
184
188
|
save(shadow / 'package.json', staged_config)
|
|
185
189
|
pnpm = pnpm or Path(os.environ.get('APPDATA', str(Path.home() / 'AppData/Roaming'))) / 'npm/node_modules/pnpm/bin/pnpm.mjs'
|
|
186
190
|
node = shutil.which('node.exe') or shutil.which('node')
|
|
@@ -188,11 +192,15 @@ def prepare(profile, archive, expected, pnpm=None):
|
|
|
188
192
|
resolver = work / 'resolver'; resolver.mkdir()
|
|
189
193
|
save(resolver / 'package.json', {'private': True, 'dependencies': {PACKAGE: staged_config['dependencies'][PACKAGE]}})
|
|
190
194
|
(resolver / 'pnpm-workspace.yaml').write_text('packages:\n - .\n', encoding='utf-8')
|
|
191
|
-
command = [node, str(pnpm), 'install', '--ignore-workspace', '--lockfile-only', '--
|
|
195
|
+
command = [node, str(pnpm), 'install', '--ignore-workspace', '--lockfile-only', '--registry=https://registry.npmjs.org/', '--ignore-scripts', '--no-frozen-lockfile']
|
|
192
196
|
with (work / 'prepare.log').open('wb') as log:
|
|
193
197
|
result = subprocess.run(command, cwd=resolver, stdout=log, stderr=subprocess.STDOUT, timeout=120)
|
|
194
198
|
if result.returncode: raise RuntimeError('Staging failed; live profile unchanged. ' + (work / 'prepare.log').read_text(encoding='utf-8', errors='replace')[-2000:])
|
|
195
199
|
resolved_lock = (resolver / 'pnpm-lock.yaml').read_text(encoding='utf-8')
|
|
200
|
+
lines, blocks = managed_lock_blocks(resolved_lock)
|
|
201
|
+
start, end = blocks[1]
|
|
202
|
+
if not re.search(r'\bintegrity:\s*' + re.escape(expected['integrity']) + r'(?=[,}\s])', ''.join(lines[start:end])):
|
|
203
|
+
raise RuntimeError('Registry lock integrity does not match the verified archive')
|
|
196
204
|
original_lock = read(profile / 'pnpm-lock.yaml')
|
|
197
205
|
if original_lock is None:
|
|
198
206
|
if any(name != PACKAGE for group in ('dependencies', 'devDependencies', 'optionalDependencies') for name in config.get(group, {})): raise RuntimeError('Existing lockfile required to preserve unrelated dependencies')
|
|
@@ -203,9 +211,9 @@ def prepare(profile, archive, expected, pnpm=None):
|
|
|
203
211
|
next_config = json.loads(base64.b64decode(new['package.json']))
|
|
204
212
|
check = json.loads(json.dumps(next_config)); check['dependencies'][PACKAGE] = config['dependencies'][PACKAGE]
|
|
205
213
|
if check != config: raise RuntimeError('Staged package manager changed unrelated profile configuration')
|
|
206
|
-
plan = {'phase': 'prepared', 'work': work.name, 'version': pkg['version'], 'buildId':
|
|
214
|
+
plan = {'phase': 'prepared', 'work': work.name, 'version': pkg['version'], 'buildId': build_id, 'old': old, 'new': new, 'oldTree': tree(plugin), 'newTree': tree(candidate)}
|
|
207
215
|
save(journal, plan)
|
|
208
|
-
return {'ok': True, 'phase': 'prepared', 'transactionId': work.name, 'version': pkg['version']}
|
|
216
|
+
return {'ok': True, 'phase': 'prepared', 'transactionId': work.name, 'version': pkg['version'], 'buildId': build_id}
|
|
209
217
|
|
|
210
218
|
def restore(profile, plugin, journal, plan):
|
|
211
219
|
for name in METADATA:
|