@kingsleyasher/dsh-knowledge-base 3.1.6 → 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.
@@ -69,8 +69,19 @@ export async function createDesktopFiles({root,privateDir,desktopRoot,core,withL
69
69
  return {id:p,path:p,name:path.posix.basename(p),type:s.isDirectory()?'directory':'file',mime:s.isFile()?mimeOf(p):undefined,size:Number(s.size),modifiedAt:Number(s.mtimeMs),revision:version(s),access:accessInfo,protected:system,hasChildren:s.isDirectory(),...(original?{category:original.category,kind:original.kind,original:true}:{})};
70
70
  }
71
71
  const listCache=new Map(),LIST_CACHE_MS=15000,LIST_CACHE_MAX=64;
72
+ let listCacheRevision=0;
73
+ function invalidate(paths){
74
+ listCacheRevision++;
75
+ if(!Array.isArray(paths)){listCache.clear();return;}
76
+ const scopes=paths.map(p=>String(p).replaceAll('\\','/').toLowerCase());
77
+ for(const key of listCache.keys()){
78
+ const parent=key.slice(0,key.lastIndexOf('|')).toLowerCase();
79
+ if(scopes.some(p=>!p||parent===p||parent.startsWith(p+'/')||path.posix.dirname(p)===(parent||'.')))listCache.delete(key);
80
+ }
81
+ }
72
82
  const dirSignature=async folder=>{const s=await lstat(folder,{bigint:true});return [String(s.dev),String(s.ino),String(s.mtimeNs),String(s.ctimeNs)].join(':')};
73
83
  async function list(parent='',offset=0,limit=500,sort='name-asc'){
84
+ const revision=listCacheRevision;
74
85
  const folder=parent?await checked(parent):base,signature=await dirSignature(folder);
75
86
  const cacheKey=parent+'|'+sort,catalog=getCatalog(),hint=[signature,indexPolicySignature(base),catalog?`${catalog.revision??0}:${catalog.policyRevision??0}`:'-',showPrivate()?'1':'0',getPrivateDirs().join('|')].join('#');
76
87
  const cached=listCache.get(cacheKey);
@@ -79,14 +90,20 @@ export async function createDesktopFiles({root,privateDir,desktopRoot,core,withL
79
90
  return {items:cached.items.slice(offset,offset+limit),nextOffset:offset+limit<cached.items.length?offset+limit:undefined,total:cached.items.length};
80
91
  }
81
92
  const matcher=policyMatcher(),rows=[];
82
- for(const e of await readdir(folder,{withFileTypes:true})){
83
- const p=parent?parent+'/'+e.name:e.name;
84
- if(e.name.startsWith('.')||e.isSymbolicLink()||privatePath(p)||['node_modules','索引层'].includes(e.name))continue;
85
- try{rows.push(await info(p,matcher,path.join(folder,e.name)));}catch(e){if(!['FORBIDDEN','LINK_DENIED','EACCES','ENOENT'].includes(e.code))throw e;}
93
+ const entries=await readdir(folder,{withFileTypes:true});
94
+ async function readEntry(entry){
95
+ const p=parent?parent+'/'+entry.name:entry.name;
96
+ if(entry.name.startsWith('.')||entry.isSymbolicLink()||privatePath(p)||['node_modules','索引层'].includes(entry.name))return;
97
+ try{return await info(p,matcher,path.join(folder,entry.name));}
98
+ catch(error){if(!['FORBIDDEN','LINK_DENIED','EACCES','ENOENT'].includes(error.code))throw error;}
99
+ }
100
+ for(let i=0;i<entries.length;i+=16){
101
+ const batch=await Promise.all(entries.slice(i,i+16).map(readEntry));
102
+ rows.push(...batch.filter(Boolean));
86
103
  }
87
104
  const nameOrder=(a,b)=>a.name.localeCompare(b.name,'zh-CN',{numeric:true});
88
105
  rows.sort((a,b)=>(a.type===b.type?0:a.type==='directory'?-1:1)||(sort==='modified-desc'?b.modifiedAt-a.modifiedAt:sort==='modified-asc'?a.modifiedAt-b.modifiedAt:sort==='name-desc'?-nameOrder(a,b):nameOrder(a,b))||nameOrder(a,b));
89
- if(rows.length<=3000){if(listCache.size>=LIST_CACHE_MAX)listCache.delete(listCache.keys().next().value);listCache.set(cacheKey,{hint,at:Date.now(),items:rows});}
106
+ if(revision===listCacheRevision&&rows.length<=3000){if(listCache.size>=LIST_CACHE_MAX)listCache.delete(listCache.keys().next().value);listCache.set(cacheKey,{hint,at:Date.now(),items:rows});}
90
107
  return {items:rows.slice(offset,offset+limit),nextOffset:offset+limit<rows.length?offset+limit:undefined,total:rows.length};
91
108
  }
92
109
  async function walk(parent='',out=[],depth=0){
@@ -460,6 +477,7 @@ export async function createDesktopFiles({root,privateDir,desktopRoot,core,withL
460
477
  if(intent?.operation==='backupDelete')await finishBackupDelete(match[1],intent);
461
478
  }
462
479
  return {
480
+ invalidate,
463
481
  async sourceFromStage(id,caller){const s=stages.get(id);if(!s||s.caller!==caller||!s.final)throw error('FORBIDDEN');const data=await readFile(s.file);if(hash(data)!==s.hash)throw error('CONFLICT','暂存原件已变化');return {data,name:s.name,bytes:data.length,external:true};},
464
482
  async recoverReceipt(operationId){const intent=await readJson(path.join(storage,'operations',operationId,'intent.json'),null);if(intent?.operation==='backupDelete')return finishBackupDelete(operationId,intent);const receipt=await readJson(path.join(storage,'operations',operationId,'committed.json'),null);if(receipt)return receipt;if(intent?.operation==='trash'){
465
483
  const dir=await trashDir(operationId),item=await readJson(path.join(dir,'manifest.json'),null);
@@ -16,6 +16,7 @@ import {startDesktopHostLinks} from './desktop-host-links.js'
16
16
  import {createParseSourceAuthority} from '../kb-core/src/parse-source-authority.js'
17
17
  import {createFlowWorkspaceManager} from '../kb-core/src/flow-workspace.js'
18
18
  import {registerHostAssets} from './host-assets.js'
19
+ import {withHostRequestAuth} from './host-request-auth.js'
19
20
  // Called only by an explicitly configured Host. It never starts an embedded writer.
20
21
  export async function mountServiceHost(ctx, config, { isLiveKnowledgeGrant, gatewayApply, createCitationGuard, build, getFlowWorkspace,installApi,legacyStateDir,profileDir,library,python='python' }) {
21
22
  const definitions = JSON.parse(await readFile(new URL('./tool-definitions.json', import.meta.url),'utf8'))
@@ -87,7 +88,7 @@ export async function mountServiceHost(ctx, config, { isLiveKnowledgeGrant, gate
87
88
  const systemPrompt = ctx.get('systemPrompt')
88
89
  if (typeof systemPrompt?.context === 'function') ctx.effect(() => systemPrompt.context({ name:'kb:parse-policy', order:600, interpolate:false, text:parseRule }), 'kb-service: parse policy')
89
90
  for (const definition of definitions) {
90
- const entry = { name:definition.name, description:definition.name === 'kb_parse' ? parseRule + '用 action=submit、kind=asr/ocr 和 sourcePath/sourceRef/sourceRel 提交;action=providers 查询当前设置,job/result 查看任务和结果。providerId 不能覆盖会话默认服务。' : '共享知识库服务:'+definition.name, parameters:definition.parameters,
91
+ const entry = { name:definition.name, description:definition.name === 'kb_parse' ? parseRule + '用 action=submit、kind=asr/ocr 和 sourcePath/sourceRef/sourceRel 提交;action=providers 查询当前设置,job/result 查看任务和结果。providerId 不能覆盖会话默认服务。' : definition.description ?? '共享知识库服务:'+definition.name, parameters:definition.parameters,
91
92
  output:{schema:definition.outputSchema,render:(_args,value)=>[{type:'text',text:JSON.stringify(value)}]},
92
93
  isConcurrencySafe:()=>false,
93
94
  async execute(input,exec) {const invoke=async()=>{const target=desktopLinks?.clientForAgent(exec?.agent);if(target===null)return {ok:false,reason:'HOST_UNAVAILABLE'};return routing.run(target??primaryClient,async()=>{
@@ -137,15 +138,15 @@ export async function mountServiceHost(ctx, config, { isLiveKnowledgeGrant, gate
137
138
  return send(res,200,await client.call('adapter.dispatch',{operation:body},{requestId:body.requestId??randomUUID()}))
138
139
  }catch(e){send(res,200,{ok:false,code:e.code??'HOST_UNAVAILABLE',error:e.message})}
139
140
  };
140
- ctx.effect(()=>installApi?installApi(apiHandler):server.register({kind:'exact',path:'/kb-core/api',handler:apiHandler}),'kb-service: existing workbench API')
141
- ctx.effect(()=>server.register({kind:'exact',path:'/kb-core/workbench-events',handler:async(req,res)=>{
141
+ ctx.effect(()=>installApi?installApi(apiHandler):server.register({kind:'exact',path:'/kb-core/api',handler:withHostRequestAuth(ctx,apiHandler)}),'kb-service: existing workbench API')
142
+ ctx.effect(()=>server.register({kind:'exact',path:'/kb-core/workbench-events',handler:withHostRequestAuth(ctx,async(req,res)=>{
142
143
  if(req.method!=='GET'||!sameOrigin(req))return send(res,403,{ok:false})
143
144
  res.writeHead(200,{'content-type':'text/event-stream','cache-control':'no-store'})
144
145
  res.write(': shared-service\n\n')
145
146
  const off=client.subscribe(event=>res.write('data: '+JSON.stringify(event)+'\n\n'))
146
- try{await client.call('events.subscribe')}catch(e){res.write('data: '+JSON.stringify({type:'service-unavailable',code:e.code})+'\n\n')}
147
147
  const heartbeat=setInterval(()=>res.write(': heartbeat\n\n'),15000);res.once('close',()=>{off();clearInterval(heartbeat)})
148
- }}),'kb-service: existing workbench events')
148
+ try{await client.call('events.subscribe')}catch(e){if(!res.destroyed)res.write('data: '+JSON.stringify({type:'service-unavailable',code:e.code})+'\n\n')}
149
+ })}),'kb-service: existing workbench events')
149
150
  }
150
151
  return {mode:'service',tools:definitions.map(x=>x.name),client}
151
152
  }
@@ -0,0 +1,31 @@
1
+ function rejectionStatus(connection, request) {
2
+ if (typeof connection?.admit === 'function') {
3
+ const admission = connection.admit(request)
4
+ if (admission?.peer) return admission.peer.principal?.kind === 'owner' ? undefined : 403
5
+ return admission?.rejection === 403 ? 403 : 401
6
+ }
7
+ // Older web hosts authenticate their browser session through this method.
8
+ if (typeof connection?.requestRejection === 'function') {
9
+ const rejection = connection.requestRejection(request)
10
+ if (rejection === undefined || rejection === 401 || rejection === 403) return rejection
11
+ }
12
+ return 503
13
+ }
14
+
15
+ export function withHostRequestAuth(ctx, handler) {
16
+ return (request, response) => {
17
+ let status
18
+ try {
19
+ status = rejectionStatus(ctx.get('connection'), request)
20
+ } catch {
21
+ status = 503
22
+ }
23
+ response.setHeader('cache-control', 'no-store')
24
+ if (status === undefined) return handler(request, response)
25
+
26
+ response.statusCode = status
27
+ response.setHeader('content-type', 'application/json; charset=utf-8')
28
+ const code = status === 401 ? 'HOST_AUTH_REQUIRED' : status === 403 ? 'FORBIDDEN' : 'HOST_AUTH_UNAVAILABLE'
29
+ response.end(JSON.stringify({ ok: false, code }))
30
+ }
31
+ }
@@ -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
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
- }
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}))
95
25
  },
96
26
  }
97
27
  }
@@ -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
  };
@@ -1,104 +1,104 @@
1
- import path from 'node:path'
2
- import { readFile, mkdir, writeFile, stat } from 'node:fs/promises'
3
- import { createHash } from 'node:crypto'
4
- import { spawn } from 'node:child_process'
5
- import { resolveHostPython } from './host-python.js'
6
- import { native } from './io.js'
7
- import { readCandidateBuild } from './build.js'
8
-
9
- // The worker and Python live outside the replaceable package. The receipt is
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' }) {
12
- let operation
13
- const home = path.join(profileDir, journalName)
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
- async function invoke(action, args = []) {
16
- const source = await readFile(path.join(packageRoot, 'tools/kb-transactional-update.py'))
17
- const python=await ensureHome()
18
- const script = path.join(home, 'installer-' + createHash('sha256').update(source).digest('hex') + '.py')
19
- try { await writeFile(script, source, { flag: 'wx', mode: 0o600 }) } catch (e) { if (e.code !== 'EEXIST') throw e }
20
- if (!(await readFile(script)).equals(source)) throw Error('Update worker integrity mismatch')
21
- return await new Promise((resolve, reject) => {
22
- const child = spawn(python, ['-I', '-X', 'utf8', script, action, '--profile', profileDir, ...args], { detached: true, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
23
- let output = '', errors = ''
24
- child.stdout.on('data', chunk => { if (output.length < 65536) output += chunk })
25
- child.stderr.on('data', chunk => { if (errors.length < 4096) errors += chunk })
26
- child.once('error', reject)
27
- child.once('exit', code => {
28
- try { const result = JSON.parse(output.trim().split('\n').at(-1)); if (code || !result.ok) throw Error(result.error || 'Update failed; backup retained'); resolve(result) }
29
- catch (error) {
30
- const message = error.message === 'An unresolved update requires recovery first'
31
- ? '检测到尚未完成的安装事务,需要先恢复该事务;未开始新安装。'
32
- : error.message === 'Profile writer is busy; old installation unchanged'
33
- ? '其他安装进程正在写入配置,请等待其完成后重试;当前安装未改变。'
34
- : code ? '安全更新未完成;旧版本或恢复备份已保留,请查看更新事务记录。' : error.message
35
- reject(Object.assign(Error(message), { code: 'UPDATE_TRANSACTION_FAILED' }))
36
- }
37
- })
38
- })
39
- }
40
- async function activateCommitted(committed) {
41
- if (activeBuild?.buildId === committed.buildId && activeBuild.version === committed.version) {
42
- return { ...committed, application:'applied' }
43
- }
44
- if (activate) {
45
- try {
46
- const result = await activate()
47
- if (result && !result.restartReason && !result.pending?.length) return { ...committed, application:'applied' }
48
- } catch {
49
- // A committed candidate never goes through package installation again.
50
- }
51
- }
52
- // Keep the existing adapter available if the Host did not replace it.
53
- await resume?.()
54
- return committed
55
- }
56
- return {
57
- async prepare(prepared) {
58
- if (operation) throw Error('另一个安全更新正在进行')
59
- const expected = path.join(home, 'expected-' + (prepared.buildId || prepared.sha256) + '.json')
60
- await ensureHome(); await writeFile(expected, JSON.stringify(prepared), { mode: 0o600 })
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 }
63
- },
64
- install({ transactionId, expectedVersion }) {
65
- if (operation) return operation
66
- operation = (async () => {
67
- const plan = JSON.parse(await readFile(path.join(home, 'transaction.json'), 'utf8'))
68
- if (plan.work !== transactionId || plan.version !== expectedVersion) throw Error('更新事务已变化,请重新检查')
69
- if (plan.phase === 'committed') return activateCommitted({ application:'restart-required', version:plan.version, buildId:plan.buildId, transactionId:plan.work })
70
- if (plan.phase !== 'prepared') throw Error('该事务需要恢复,未重新开始安装')
71
- // Must fail closed when the current runtime cannot prove quiescence.
72
- if (!quiesce) throw Error('当前运行模式不支持安全停服,更新已延后,旧版未改动')
73
- let committed
74
- try {
75
- committed = await withUpdateLock(async () => {
76
- await quiesce()
77
- return invoke('commit',['--transaction',transactionId])
78
- })
79
- } catch (error) {
80
- const state = JSON.parse(await readFile(path.join(home,'transaction.json'),'utf8'))
81
- if (['rolled-back','prepared','aborted'].includes(state.phase)) await resume?.()
82
- if (state.phase === 'prepared' && error.code === 'STATE_BUSY') {
83
- return { application:'deferred', error:error.message, retryable:true }
84
- }
85
- throw error
86
- }
87
- return activateCommitted(committed)
88
- })().finally(() => { operation = null })
89
- return operation
90
- },
91
- async status() {
92
- let plan
93
- try{plan=JSON.parse(await readFile(path.join(home,'transaction.json'),'utf8'))}catch(error){if(error.code!=='ENOENT')throw error;plan={phase:'none'}}
94
- if(plan.phase==='publishing'&&!operation){try{await invoke('recover');plan=JSON.parse(await readFile(path.join(home,'transaction.json'),'utf8'))}catch{/* live worker or recovery requires attention */}}
95
- let writerBusy
96
- try{await stat(path.join(profileDir,'package.json.lock'));writerBusy=true}catch(error){if(error.code!=='ENOENT')throw error;writerBusy=false}
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 */}
99
- return { phase: plan.phase, version: plan.version, buildId: plan.buildId, transactionId: plan.work, restartRequired: plan.phase === 'committed',
100
- confirmationProtocol:1,operationActive:Boolean(operation),writerBusy,installedBuild,
101
- canRetryLegacy:Boolean(installedBuild&&!operation&&!writerBusy&&['none','committed','aborted','rolled-back'].includes(plan.phase)) }
102
- },
103
- }
104
- }
1
+ import path from 'node:path'
2
+ import { readFile, mkdir, writeFile, stat } from 'node:fs/promises'
3
+ import { createHash } from 'node:crypto'
4
+ import { spawn } from 'node:child_process'
5
+ import { resolveHostPython } from './host-python.js'
6
+ import { native } from './io.js'
7
+ import { readCandidateBuild } from './build.js'
8
+
9
+ // The worker and Python live outside the replaceable package. The receipt is
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 }) {
12
+ let operation
13
+ const home = path.join(profileDir, '.kb-safe-updates')
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
+ async function invoke(action, args = []) {
16
+ const source = await readFile(path.join(packageRoot, 'tools/kb-transactional-update.py'))
17
+ const python=await ensureHome()
18
+ const script = path.join(home, 'installer-' + createHash('sha256').update(source).digest('hex') + '.py')
19
+ try { await writeFile(script, source, { flag: 'wx', mode: 0o600 }) } catch (e) { if (e.code !== 'EEXIST') throw e }
20
+ if (!(await readFile(script)).equals(source)) throw Error('Update worker integrity mismatch')
21
+ return await new Promise((resolve, reject) => {
22
+ const child = spawn(python, ['-I', '-X', 'utf8', script, action, '--profile', profileDir, ...args], { detached: true, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
23
+ let output = '', errors = ''
24
+ child.stdout.on('data', chunk => { if (output.length < 65536) output += chunk })
25
+ child.stderr.on('data', chunk => { if (errors.length < 4096) errors += chunk })
26
+ child.once('error', reject)
27
+ child.once('exit', code => {
28
+ try { const result = JSON.parse(output.trim().split('\n').at(-1)); if (code || !result.ok) throw Error(result.error || 'Update failed; backup retained'); resolve(result) }
29
+ catch (error) {
30
+ const message = error.message === 'An unresolved update requires recovery first'
31
+ ? '检测到尚未完成的安装事务,需要先恢复该事务;未开始新安装。'
32
+ : error.message === 'Profile writer is busy; old installation unchanged'
33
+ ? '其他安装进程正在写入配置,请等待其完成后重试;当前安装未改变。'
34
+ : code ? '安全更新未完成;旧版本或恢复备份已保留,请查看更新事务记录。' : error.message
35
+ reject(Object.assign(Error(message), { code: 'UPDATE_TRANSACTION_FAILED' }))
36
+ }
37
+ })
38
+ })
39
+ }
40
+ async function activateCommitted(committed) {
41
+ if (activeBuild?.buildId === committed.buildId && activeBuild.version === committed.version) {
42
+ return { ...committed, application:'applied' }
43
+ }
44
+ if (activate) {
45
+ try {
46
+ const result = await activate()
47
+ if (result && !result.restartReason && !result.pending?.length) return { ...committed, application:'applied' }
48
+ } catch {
49
+ // A committed candidate never goes through package installation again.
50
+ }
51
+ }
52
+ // Keep the existing adapter available if the Host did not replace it.
53
+ await resume?.()
54
+ return committed
55
+ }
56
+ return {
57
+ async prepare(prepared) {
58
+ if (operation) throw Error('另一个安全更新正在进行')
59
+ const expected = path.join(home, 'expected-' + prepared.buildId + '.json')
60
+ await ensureHome(); await writeFile(expected, JSON.stringify(prepared), { mode: 0o600 })
61
+ const plan = await invoke('prepare', ['--archive', prepared.spec, '--expected', expected])
62
+ return { ...prepared, safeInstall: true, hotActivation: Boolean(activate), transactionId: plan.transactionId }
63
+ },
64
+ install({ transactionId, expectedVersion }) {
65
+ if (operation) return operation
66
+ operation = (async () => {
67
+ const plan = JSON.parse(await readFile(path.join(home, 'transaction.json'), 'utf8'))
68
+ if (plan.work !== transactionId || plan.version !== expectedVersion) throw Error('更新事务已变化,请重新检查')
69
+ if (plan.phase === 'committed') return activateCommitted({ application:'restart-required', version:plan.version, buildId:plan.buildId, transactionId:plan.work })
70
+ if (plan.phase !== 'prepared') throw Error('该事务需要恢复,未重新开始安装')
71
+ // Must fail closed when the current runtime cannot prove quiescence.
72
+ if (!quiesce) throw Error('当前运行模式不支持安全停服,更新已延后,旧版未改动')
73
+ let committed
74
+ try {
75
+ committed = await withUpdateLock(async () => {
76
+ await quiesce()
77
+ return invoke('commit',['--transaction',transactionId])
78
+ })
79
+ } catch (error) {
80
+ const state = JSON.parse(await readFile(path.join(home,'transaction.json'),'utf8'))
81
+ if (['rolled-back','prepared','aborted'].includes(state.phase)) await resume?.()
82
+ if (state.phase === 'prepared' && error.code === 'STATE_BUSY') {
83
+ return { application:'deferred', error:error.message, retryable:true }
84
+ }
85
+ throw error
86
+ }
87
+ return activateCommitted(committed)
88
+ })().finally(() => { operation = null })
89
+ return operation
90
+ },
91
+ async status() {
92
+ let plan
93
+ try{plan=JSON.parse(await readFile(path.join(home,'transaction.json'),'utf8'))}catch(error){if(error.code!=='ENOENT')throw error;plan={phase:'none'}}
94
+ if(plan.phase==='publishing'&&!operation){try{await invoke('recover');plan=JSON.parse(await readFile(path.join(home,'transaction.json'),'utf8'))}catch{/* live worker or recovery requires attention */}}
95
+ let writerBusy
96
+ try{await stat(path.join(profileDir,'package.json.lock'));writerBusy=true}catch(error){if(error.code!=='ENOENT')throw error;writerBusy=false}
97
+ let installedBuild
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
+ return { phase: plan.phase, version: plan.version, buildId: plan.buildId, transactionId: plan.work, restartRequired: plan.phase === 'committed',
100
+ confirmationProtocol:1,operationActive:Boolean(operation),writerBusy,installedBuild,
101
+ canRetryLegacy:Boolean(installedBuild&&!operation&&!writerBusy&&['none','committed','aborted','rolled-back'].includes(plan.phase)) }
102
+ },
103
+ }
104
+ }
@@ -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,5 +1,17 @@
1
1
  import path from 'node:path';import {error} from './io.js';
2
2
  import {toolWrites} from './operations.js';
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
+
3
15
  export function normalizeToolResult(name,input,value){
4
16
  if(name==='kb_flow')return {...value,action:String(input?.action??'')};
5
17
  if(name==='kb_check'&&value?.ok===false)return {execution:'error',quality:'unknown',defects:[],...value};
@@ -11,7 +23,7 @@ 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}))};}
26
+ if(name==='kb_search')return executeKbSearch(wb,a);
15
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);