@kingsleyasher/dsh-knowledge-base 3.1.5 → 3.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,97 +1,27 @@
1
- import { createHash } from 'node:crypto'
2
- import { mkdtemp, rm, writeFile } from 'node:fs/promises'
3
- import os from 'node:os'
4
1
  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'
2
+ import {createSafeUpdate} from './safe-update.js'
3
+ import {createUpdateChecker,createUpdateDownloader,startAutomaticChecks} from '../../src/host/updates.js'
8
4
 
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
5
+ // Update only the Host package; library identity and engine storage stay untouched.
6
+ export function createHostUpdates({ctx,build,profileDir,fetch,packageRoot=path.resolve(import.meta.dirname,'../..'),quiesce,resume,withUpdateLock}) {
7
+ const checker=createUpdateChecker({currentVersion:build.version,...(fetch?{fetch}:{})})
8
+ const profile=ctx.get('profileContext')
9
+ const directory=profile?.dir || profileDir
10
+ const downloader=createUpdateDownloader({checker,cacheDir:directory?path.join(directory,'.kb-plugin-updates'):null,...(fetch?{fetch}:{})})
11
+ const hmr=ctx.get('hmr')
12
+ const activate=typeof hmr?.runExclusive==='function'&&typeof hmr?.reconcileProfile==='function'
13
+ ? ()=>hmr.runExclusive(()=>hmr.reconcileProfile())
14
+ : undefined
15
+ const safe=directory?createSafeUpdate({profileDir:directory,packageRoot,quiesce,resume,withUpdateLock,activate,activeBuild:build}):null
16
+ const supported=()=>Boolean(directory && typeof ctx.get('pluginManager')?.installBundle==='function')
17
+ ctx.effect(()=>startAutomaticChecks(checker),'kb-service: automatic update checks')
18
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
19
+ async check(body={}) {return {...await checker.check({force:body.force===true}),installSupported:supported()}},
20
+ install:body=>safe.install(body),
21
+ status:()=>safe.status(),
22
+ async prepare(body={}) {
23
+ if(!supported())return {ok:false,code:'CAPABILITY_UNSUPPORTED',error:'当前宿主不支持插件安装,请手动安装已校验的正式发布包。'}
24
+ return safe.prepare(await downloader.prepare({expectedVersion:body.expectedVersion}))
45
25
  },
46
26
  }
47
27
  }
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
- }
97
- }
@@ -11,7 +11,11 @@ export function createLegacyPorts({kernel,kbId,root,maintenance,changeMaintenanc
11
11
  if(a.op==='index-maintenance.status'){const s=await kernel.core.status();return {ok:true,enabled:(await kernel.core.getConfig()).autoIndex!==false,scheduler:maintenance()?.status(),maintenance:kernel.core.maintenanceStatus(),kbId,index:s.index};}
12
12
  if(a.op==='index-maintenance.configure'){const r=await kernel.core.setConfig({autoIndex:a.enabled===true});changeMaintenance(a.enabled===true);return r;}
13
13
  if(a.op==='index-snapshots')return kernel.core.indexSnapshots({restore:a.restore,expectedKbId:kbId});
14
- if(a.op==='index-rebuild'){const result=await kernel.core.maintainIndex({full:true,expectedKbId:kbId,expectedRevision:a.expectedRevision,confirmDrop:a.confirmDrop});return {ok:result.ok,result,error:result.ok?undefined:result.detail??result.reason};}
14
+ if(a.op==='index-rebuild'){
15
+ const result=await kernel.core.maintainIndex({full:true,expectedKbId:kbId,expectedRevision:a.expectedRevision,confirmDrop:a.confirmDrop});
16
+ if(result.ok)maintenance()?.resume();
17
+ return {ok:result.ok,result,error:result.ok?undefined:result.detail??result.reason};
18
+ }
15
19
  if(['setup','bind','probe-folder'].includes(a.op)){if(path.resolve(a.path??a.kbPath??root).toLowerCase()!==root.toLowerCase())throw error('BINDING_CHANGED','共库连接绑定当前库;切换库需重新建立该库连接,未切换或改动其他库');return {ok:true,result:{ok:true,bound:true,kbId,kbPath:root,action:'already-bound'},folder:{path:root,kind:'knowledge-base'}};}
16
20
  throw error('CAPABILITY_UNSUPPORTED');
17
21
  };
@@ -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, installedRoot = path.join(profileDir, 'node_modules/@local/dsh-knowledge-base'), journalName = '.kb-safe-updates' }) {
11
+ export function createSafeUpdate({ profileDir, packageRoot, quiesce, resume, withUpdateLock = task => task(), activate, activeBuild }) {
12
12
  let operation
13
- const home = path.join(profileDir, journalName)
13
+ const home = path.join(profileDir, '.kb-safe-updates')
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 || prepared.sha256) + '.json')
59
+ const expected = path.join(home, 'expected-' + prepared.buildId + '.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, ok: true, buildId: plan.buildId || prepared.buildId, safeInstall: true, hotActivation: Boolean(activate), transactionId: plan.transactionId }
62
+ return { ...prepared, 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(installedRoot);installedBuild={version:build.version,buildId:build.buildId}}catch{/* incomplete package is never proof that retry is safe */}
98
+ try{const build=await readCandidateBuild(path.join(profileDir,'node_modules/@local/dsh-knowledge-base'));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)) }
@@ -79,6 +79,7 @@ export async function startService({ library, privateDir, python, sources = {},
79
79
  if (!filePolicyPaths.has(relative) && relative.split('/').some(part => part.startsWith('.') || part === '索引层' || part === 'node_modules')) return
80
80
  if(relative==='索引层/文件目录.json')catalogChanged=true;else if(!relative||filePolicyPaths.has(relative))fileGlobal=true;else fileChanges.add(relative)
81
81
  if(fileChanges.size>1024){fileGlobal=true;fileChanges.clear()}
82
+ desktopFiles?.invalidate(relative==='索引层/文件目录.json'||fileGlobal?undefined:[relative])
82
83
  kernel.workbench.invalidateBrowse()
83
84
  firstFileEvent??=Date.now();clearTimeout(fileEventTimer)
84
85
  fileEventTimer = setTimeout(() => { firstFileEvent=null;const data=fileGlobal?{}:{paths:[...fileChanges],catalogChanged};fileGlobal=false;catalogChanged=false;fileChanges.clear();void queue(()=>event(data)).catch(() => {}) }, Math.max(0,Math.min(150,1000-(Date.now()-firstFileEvent))))
@@ -305,7 +306,11 @@ export async function startService({ library, privateDir, python, sources = {},
305
306
  connection.subscribed = true
306
307
  return { bootId, seq: sequence, events: a.afterSeq == null ? [] : ring.filter(x => x.seq > a.afterSeq).map(x=>eventFor(x,caller)) }
307
308
  }
308
- if(call.method==='host.tool')return toolRouter(a,{...caller,operationId:call.operationId})
309
+ if(call.method==='host.tool'){
310
+ const result = await toolRouter(a, {...caller,operationId:call.operationId})
311
+ if (a.name === 'kb_check' && a.input?.confirmDrop && result.indexWritten) maintenance?.resume()
312
+ return result
313
+ }
309
314
  if (call.method === 'adapter.dispatch') {
310
315
  const operation = a.operation
311
316
  if (operation?.owner&&!operation.op?.startsWith('onboarding.') || operation?.caller || operation?.roles) throw error('BAD_REQUEST')
@@ -350,6 +355,7 @@ export async function startService({ library, privateDir, python, sources = {},
350
355
  try {
351
356
  const result = await route({ ...call, operationId }, connection)
352
357
  const paths=['document.save','document.create'].includes(call.method)?[call.args.path]:undefined
358
+ desktopFiles?.invalidate(paths)
353
359
  kernel.workbench.invalidate();kernel.workbench.notify({type:'snapshot-dirty',kbId,paths})
354
360
  await fault('operation:published')
355
361
  journal.state = 'committed'; journal.result = result
@@ -398,7 +404,7 @@ export async function startService({ library, privateDir, python, sources = {},
398
404
  }
399
405
  function startMaintenance() {
400
406
  if (!maintenance) maintenance = createIndexMaintenance({ getCore: () => ({ ...kernel.core, maintainIndex: args => queue(async () => closing || !await active() ? { ok: false, reason: 'service-inactive' } : kernel.core.maintainIndex(args)) }), onChange: result => {if(result.indexWritten)kernel.workbench.invalidateBrowse();void queue(()=>event({indexOnly:true}))}, resources: kernel.workbench.resources })
401
- if(!automaticTimer){automaticTimer=setInterval(()=>{void queue(async()=>{if(closing||!await active())return;const before=hash(await bytes(path.join(root,'.kbmeta/shared-state.json')));await kernel.workbench.runAutomatic();if(before!==hash(await bytes(path.join(root,'.kbmeta/shared-state.json')))){writeSequence++;await atomic(path.join(privateDir,'sequence.json'),{value:writeSequence});await event();}}).catch(e=>console.warn('[kb-service] automatic maintenance: '+String(e.code??'failed')));},60000);automaticTimer.unref?.()}
407
+ if(!automaticTimer){automaticTimer=setInterval(()=>{void queue(async()=>{if(closing||!await active())return;const before=hash(await bytes(path.join(root,'.kbmeta/shared-state.json')));await kernel.workbench.runAutomatic();if(before!==hash(await bytes(path.join(root,'.kbmeta/shared-state.json')))){writeSequence++;await atomic(path.join(privateDir,'sequence.json'),{value:writeSequence});await event(fileWatcher?{stateOnly:true}:{});}}).catch(e=>console.warn('[kb-service] automatic maintenance: '+String(e.code??'failed')));},60000);automaticTimer.unref?.()}
402
408
  }
403
409
  try {
404
410
  // Service state is wholly separate from all existing DSH profile directories.
@@ -504,6 +504,7 @@
504
504
  },
505
505
  {
506
506
  "name": "kb_check",
507
+ "description": "检查知识库并报告索引差异与缺陷。recover=true 时在成功写入索引后消费 recover-todo。如果返回 indexWriteBlocked,请向用户报告条目降幅并核对差异,用户确认后用该结果的 confirmationToken 作为 confirmDrop 重试。",
507
508
  "parameters": {
508
509
  "type": "object",
509
510
  "additionalProperties": false,
@@ -513,6 +514,10 @@
513
514
  },
514
515
  "recover": {
515
516
  "type": "boolean"
517
+ },
518
+ "confirmDrop": {
519
+ "type": "string",
520
+ "description": "用户确认本次索引降幅后,填入 indexWriteBlocked.confirmationToken"
516
521
  }
517
522
  }
518
523
  },
@@ -1,9 +1,21 @@
1
1
  import path from 'node:path';import {error} from './io.js';
2
2
  import {toolWrites} from './operations.js';
3
- // The shared engine returns domain data; the Host tool contract also requires
4
- // the requested action on kb_flow successes and structured failures.
3
+
4
+ export async function executeKbSearch(dispatch, { query, retrievalMode, limit }) {
5
+ const found = await dispatch({
6
+ op: 'search.list', mode: 'body', q: query, retrievalMode,
7
+ limit: Math.max(1, Math.min(20, limit || 5)),
8
+ });
9
+ const hits = found.items.map(item => ({ ...item, revision: item.revision?.slice(0, 12) || null }));
10
+ // Match the JSON wire representation of optional fields and non-finite numbers.
11
+ // DSH validates the returned object before it can be rendered.
12
+ return JSON.parse(JSON.stringify({ ...found, ok: true, hits }));
13
+ }
14
+
5
15
  export function normalizeToolResult(name,input,value){
6
- return name==='kb_flow'?{...value,action:String(input?.action??'')}:value;
16
+ if(name==='kb_flow')return {...value,action:String(input?.action??'')};
17
+ if(name==='kb_check'&&value?.ok===false)return {execution:'error',quality:'unknown',defects:[],...value};
18
+ return value;
7
19
  }
8
20
  export function createToolRouter({kernel,engines,wb,write,online,root,kbId,sourceFromStage}){
9
21
  return async function route({name,input,hostSession,hostAuthority,sourceStage},caller){
@@ -11,11 +23,15 @@ export function createToolRouter({kernel,engines,wb,write,online,root,kbId,sourc
11
23
  if(name==='kb_status')return kernel.core.status();
12
24
  if(name==='kb_bind'){if(path.resolve(a.path??'').toLowerCase()!==root.toLowerCase())throw error('BINDING_CHANGED','一个共库连接只能绑定一个库;请从库切换入口重新连接');return {ok:true,kbPath:root,kbId,initialized:true,alreadyInitialized:true,needsConfirm:false,willCreate:[],willModify:[]};}
13
25
  if(name==='kb_init')return {ok:true,kbPath:root,kbId,alreadyInitialized:true,installState:'complete',steps:[]};
14
- if(name==='kb_search'){const found=await wb({op:'search.list',mode:'body',q:a.query,retrievalMode:a.retrievalMode,limit:Math.max(1,Math.min(20,a.limit||5))});return {...found,ok:true,hits:found.items.map(h=>({...h,revision:h.revision?.slice(0,12)||null}))};}
15
- if(name==='kb_check'){write(caller);return kernel.core.check(a);}
26
+ if(name==='kb_search')return executeKbSearch(wb,a);
27
+ if(name==='kb_check'){write(caller);return kernel.core.checkEntry(a);}
16
28
  if(name==='kb_inbox'){
17
29
  if(a.action==='list')return wb({op:'inbox.list',limit:a.limit,offset:a.offset});write(caller);
18
- if(a.action==='complete')return wb({op:'inbox.complete',path:a.path,entryPath:a.entryPath});throw error('BAD_REQUEST');
30
+ if(a.action==='complete'){
31
+ try{return await wb({op:'inbox.complete',path:a.path,entryPath:a.entryPath});}
32
+ catch(e){if(['BAD_PATH','SOURCE_MISMATCH'].includes(e.code))throw error('BAD_REQUEST',e.message);throw e;}
33
+ }
34
+ throw error('BAD_REQUEST');
19
35
  }
20
36
  if(name==='kb_record'){
21
37
  write(caller);if(a.action==='create'&&['知识','项目','素材','人物','画像'].includes(a.kind))return kernel.core.createEntry({...a,requestId:a.requestId??caller.operationId});