feat(assistant): manage providers models and personal conversation recycle bin

This commit is contained in:
abaishu0730 committed 2026-10-28 09:58:11 +08:00
1 parent 506e6fbfad
commit 301cdf669d
29 files changed
+267 -83

No files matched your search

+11 -1
View File
@@ -4,6 +4,14 @@ function bodyKeys(body,keys){if(!body||Array.isArray(body)||Object.keys(body).so
async function assistantApi({assistant,user,sessionId,route,method,body,request,response,streams,authenticateStream,reply,workspace,trustedProxy=false}){
if(!route.startsWith('/api/assistant'))return false;if(!assistant)throw fail('DSH 助手服务未启动。',503);const principal={user,sessionId};
if(route==='/api/assistant'&&method==='GET'){const settings=assistant.store.settings();reply(200,{settings:user.role==='admin'?settings:{enabled:settings.enabled,allowActions:settings.allowActions,model:settings.model},skills:require('./skills.cjs').projectSkills(),usage:assistant.store.usage(),conversations:assistant.store.conversations(user.id)});return true;}
if(route==='/api/assistant/providers'&&method==='GET'){const list=assistant.store.providers.list();if(user.role==='admin')reply(200,list);else reply(200,{version:list.version,defaultSelection:list.defaultSelection,providers:list.providers.filter(p=>p.enabled&&p.hasApiKey&&p.models.length).map(({id,name,version,models})=>({id,name,version,models}))});return true;}
if((route==='/api/assistant/providers'||route==='/api/assistant/providers/default'||/^\/api\/assistant\/providers\/[\w-]+\/(delete|models)$/.test(route))&&method==='POST'){
if(user.role!=='admin')throw fail('仅管理员可以维护模型供应商。',403);if(!secureBpmTransport(request,trustedProxy))throw fail('请在部署机本地或 HTTPS 页面维护模型供应商。',403);
if(route==='/api/assistant/providers'){const saved=assistant.store.providers.save(body);workspace?.record(user,'维护模型供应商','已保存供应商配置');reply(body.version===0?201:200,saved);return true;}
if(route.endsWith('/default')){bodyKeys(body,['version','providerId','modelId']);reply(200,assistant.store.providers.chooseDefault(body));return true;}
const providerRoute=/^\/api\/assistant\/providers\/([\w-]+)\/(delete|models)$/.exec(route);bodyKeys(body,['version']);
if(providerRoute[2]==='delete'){if([...assistant.running.values()].some(run=>run.providerId===providerRoute[1]))throw fail('此供应商仍在回复,请停止并等待完成后删除。',409);const result=assistant.store.providers.remove(providerRoute[1],body);workspace?.record(user,'删除模型供应商',providerRoute[1]);reply(200,result);}else{const controller=new AbortController(),abort=()=>{if(!response.writableEnded)controller.abort();};response.once('close',abort);try{reply(200,await assistant.store.providers.discover(providerRoute[1],{version:body.version,signal:controller.signal}));}finally{response.removeListener('close',abort);}}return true;
}
if(route==='/api/assistant/context'&&method==='GET'){reply(200,require('./diagnostic-context.cjs').diagnosticContext(assistant.deps,user));return true;}
const eventRoute=/^\/api\/assistant\/conversations\/([\w-]+)\/(events|stream)$/.exec(route);
if(eventRoute&&method==='GET'){
@@ -24,11 +32,13 @@ async function assistantApi({assistant,user,sessionId,route,method,body,request,
if(route==='/api/assistant/operations'&&method==='GET'){const params=new URL(request.url,'http://localhost').searchParams;if([...params.keys()].some(k=>k!=='beforeId')||params.getAll('beforeId').length>1)throw fail('操作记录查询参数无效。');const beforeId=params.has('beforeId')?Number(params.get('beforeId')):undefined;if(beforeId!==undefined&&(!Number.isSafeInteger(beforeId)||beforeId<1))throw fail('操作记录游标无效。');reply(200,{events:assistant.operations(principal,{beforeId})});return true;}
if(route==='/api/assistant/conversations'&&method==='POST'){bodyKeys(body,[]);reply(201,assistant.store.create(user.id));return true;}
if(route==='/api/assistant/conversations'&&method==='GET'){const params=new URL(request.url,'http://localhost').searchParams,filters={};for(const [key,value]of params){if(!['scope','page','pageSize','query'].includes(key)||params.getAll(key).length!==1)throw fail('会话查询参数无效。');filters[key]=['scope','query'].includes(key)?value:Number(value);}reply(200,filters.query?await require('./conversation-search.cjs').search(assistant.store,user.id,filters):assistant.store.listConversations(user.id,filters));return true;}
const management=/^\/api\/assistant\/conversations\/([\w-]+)\/(delete|restore-deleted|purge|model)$/.exec(route);
if(management&&method==='POST'){const [,id,action]=management;bodyKeys(body,action==='purge'?['version','confirm']:action==='model'?['version','providerId','modelId']:['version']);const result=assistant.store[{delete:'trash','restore-deleted':'restoreDeleted',purge:'purge',model:'setModel'}[action]](id,user.id,body);workspace?.record(user,action==='model'?'选择个人对话模型':'管理个人会话',action+' '+id);reply(200,result);return true;}
const history=/^\/api\/assistant\/conversations\/([\w-]+)\/(archive|restore|continue)$/.exec(route);
if(history&&method==='POST'){bodyKeys(body,['version']);const result=assistant.store[{archive:'archive',restore:'restore',continue:'continueConversation'}[history[2]]](history[1],user.id,body);workspace?.record(user,'管理个人助手会话',history[2]);reply(200,result);return true;}
const match=/^\/api\/assistant\/conversations\/([\w-]+)(?:\/(messages|repair-messages|cancel)|\/actions\/([\w-]+)\/execute)?$/.exec(route);
if(match){const [,id,action,actionId]=match;
if(!action&&!actionId&&method==='GET'){reply(200,assistant.store.conversation(id,user.id));return true;}
if(!action&&!actionId&&method==='GET'){const params=new URL(request.url,'http://localhost').searchParams;if([...params.keys()].some(k=>k!=='scope')||params.getAll('scope').length>1||params.has('scope')&&params.get('scope')!=='deleted')throw fail('会话读取参数无效。');reply(200,assistant.store.conversation(id,user.id,{includeDeleted:params.get('scope')==='deleted'}));return true;}
if(method==='POST'){
if(action==='repair-messages'){bodyKeys(body,['text','paths']);reply(202,assistant.sendRepair(id,principal,body.text,body.paths));return true;}
if(action==='messages'){bodyKeys(body,['text','diagnostic','requestId']);const diagnostic=require('./diagnostic-context.cjs').validateDiagnostic(body.diagnostic,assistant.deps,user);reply(202,assistant.send(id,principal,body.text,{diagnostic,requestId:body.requestId}));return true;}
+15 -10
View File
@@ -2,13 +2,13 @@
const crypto=require('node:crypto');
const fail=(message,status=400)=>Object.assign(Error(message),{status});
class ConversationHistory{
constructor(store){this.store=store;if(!store.db.prepare('PRAGMA table_info(conversations)').all().some(column=>column.name==='archived'))store.db.exec('ALTER TABLE conversations ADD COLUMN archived INTEGER NOT NULL DEFAULT 0');store.db.exec('CREATE INDEX IF NOT EXISTS conversation_scope ON conversations(owner,archived,updated_at DESC)');}
constructor(store){this.store=store;const columns=store.db.prepare('PRAGMA table_info(conversations)').all();if(!columns.some(column=>column.name==='archived'))store.db.exec('ALTER TABLE conversations ADD COLUMN archived INTEGER NOT NULL DEFAULT 0');if(!columns.some(column=>column.name==='deleted_at'))store.db.exec('ALTER TABLE conversations ADD COLUMN deleted_at TEXT');store.db.exec('CREATE INDEX IF NOT EXISTS conversation_scope ON conversations(owner,archived,updated_at DESC)');}
metadata(row){return this.store.decode(row.id,row.payload);}
count(owner){return this.store.db.prepare('SELECT COUNT(*) AS n FROM conversations WHERE owner=? AND archived=0').get(owner).n;}
count(owner){return this.store.db.prepare('SELECT COUNT(*) AS n FROM conversations WHERE owner=? AND archived=0 AND deleted_at IS NULL').get(owner).n;}
list(owner,{scope='active',page=1,pageSize=50}={}){
if(!['active','archived'].includes(scope)||!Number.isSafeInteger(page)||page<1||!Number.isInteger(pageSize)||pageSize<1||pageSize>50)throw fail('会话查询条件无效。');
const archived=Number(scope==='archived'),total=this.store.db.prepare('SELECT COUNT(*) AS n FROM conversations WHERE owner=? AND archived=?').get(owner,archived).n,actual=Math.min(page,Math.max(1,Math.ceil(total/pageSize)));
const items=this.store.db.prepare('SELECT * FROM conversations WHERE owner=? AND archived=? ORDER BY updated_at DESC,rowid DESC LIMIT ? OFFSET ?').all(owner,archived,pageSize,(actual-1)*pageSize).map(row=>({id:row.id,...this.metadata(row),version:this.metadata(row).version||1,archived:!!row.archived,createdAt:row.created_at,updatedAt:row.updated_at}));
if(!['active','archived','deleted'].includes(scope)||!Number.isSafeInteger(page)||page<1||!Number.isInteger(pageSize)||pageSize<1||pageSize>50)throw fail('会话查询条件无效。');
const archived=Number(scope==='archived'),filter=scope==='deleted'?'deleted_at IS NOT NULL':'archived=? AND deleted_at IS NULL',args=scope==='deleted'?[owner]:[owner,archived],total=this.store.db.prepare('SELECT COUNT(*) AS n FROM conversations WHERE owner=? AND '+filter).get(...args).n,actual=Math.min(page,Math.max(1,Math.ceil(total/pageSize)));
const items=this.store.db.prepare('SELECT * FROM conversations WHERE owner=? AND '+filter+' ORDER BY updated_at DESC,rowid DESC LIMIT ? OFFSET ?').all(...args,pageSize,(actual-1)*pageSize).map(row=>({id:row.id,title:this.metadata(row).title,modelSelection:this.metadata(row).modelSelection||null,version:this.metadata(row).version||1,archived:!!row.archived,deletedAt:row.deleted_at||null,createdAt:row.created_at,updatedAt:row.updated_at}));
return {items,total,page:actual,pageSize};
}
create(owner,{continuationOf}={}){
@@ -16,7 +16,7 @@ class ConversationHistory{
const id=crypto.randomUUID(),at=new Date().toISOString(),metadata={title:'新对话',version:1,...(continuationOf?{continuationOf}: {})};
this.store.db.prepare('INSERT INTO conversations(id,owner,payload,created_at,updated_at,archived) VALUES(?,?,?,?,?,0)').run(id,owner,this.store.encode(id,metadata),at,at);return this.conversation(id,owner);
}
conversation(id,owner){return this.store.transaction(()=>{const row=this.store.row(id,owner),metadata=this.metadata(row);return {id,title:metadata.title,version:metadata.version||1,archived:!!row.archived,continuationOf:metadata.continuationOf||null,continuedTo:metadata.continuedTo||null,eventCursor:this.store.eventCursor(id,owner),turns:this.store.db.prepare('SELECT * FROM turns WHERE conversation_id=? ORDER BY rowid').all(id).map(turn=>({id:turn.id,status:turn.status,createdAt:turn.created_at,...this.store.decode(turn.id,turn.payload)}))};});}
conversation(id,owner,{includeDeleted=false}={}){return this.store.transaction(()=>{const row=this.store.row(id,owner,{includeDeleted}),metadata=this.metadata(row);return {id,title:metadata.title,version:metadata.version||1,archived:!!row.archived,deletedAt:row.deleted_at||null,modelSelection:metadata.modelSelection||null,continuationOf:metadata.continuationOf||null,continuedTo:metadata.continuedTo||null,eventCursor:includeDeleted?this.store.conversationEvents.highWater(id):this.store.eventCursor(id,owner),turns:this.store.db.prepare('SELECT * FROM turns WHERE conversation_id=? ORDER BY rowid').all(id).map(turn=>({id:turn.id,status:turn.status,createdAt:turn.created_at,...this.store.decode(turn.id,turn.payload)}))};});}
checkIdle(id){for(const turn of this.store.db.prepare('SELECT id,status,payload FROM turns WHERE conversation_id=?').all(id))if(turn.status==='running'||this.store.decode(turn.id,turn.payload).actions?.some(action=>action.status==='running'))throw fail('此会话仍在回复或执行操作,请先停止并等待完成。',409);}
validate(row,input){if(!input||Object.keys(input).some(key=>key!=='version')||!Number.isSafeInteger(input.version)||input.version!==(this.metadata(row).version||1))throw fail('会话已变化,请刷新后重试。',409);}
setArchived(id,owner,archived,input){return this.store.transaction(()=>{
@@ -26,11 +26,16 @@ class ConversationHistory{
});}
continue(id,owner,input){return this.store.transaction(()=>{
const row=this.store.row(id,owner),metadata=this.metadata(row);if(!Number.isSafeInteger(input?.version)||input.version<1)throw fail('会话版本无效。');
if(metadata.continuedTo)return this.conversation(metadata.continuedTo,owner);
if(metadata.continuedTo){let child;try{child=this.store.row(metadata.continuedTo,owner,{includeDeleted:true});}catch(error){if(error.status!==404)throw error;}if(child){if(child.deleted_at)throw fail('已延续的会话在回收站,请先恢复,或新建其他对话。',409);return this.conversation(metadata.continuedTo,owner);}delete metadata.continuedTo;}
this.validate(row,input);this.checkIdle(id);const at=new Date().toISOString();
this.store.db.prepare('UPDATE conversations SET archived=1 WHERE id=?').run(id);const child=this.create(owner,{continuationOf:id});metadata.version=(metadata.version||1)+1;metadata.continuedTo=child.id;
this.store.db.prepare('UPDATE conversations SET payload=?,updated_at=? WHERE id=?').run(this.store.encode(id,metadata),at,id);return child;
this.store.db.prepare('UPDATE conversations SET archived=1 WHERE id=?').run(id);const child=this.create(owner,{continuationOf:id});const childMeta=this.metadata(this.store.row(child.id,owner));childMeta.inheritedHistory=this.history(id,owner).slice(-3).map(t=>({text:t.text,reply:t.reply,status:'success'}));if(metadata.modelSelection)childMeta.modelSelection=metadata.modelSelection;this.store.db.prepare('UPDATE conversations SET payload=? WHERE id=?').run(this.store.encode(child.id,childMeta),child.id);metadata.version=(metadata.version||1)+1;metadata.continuedTo=child.id;
this.store.db.prepare('UPDATE conversations SET payload=?,updated_at=? WHERE id=?').run(this.store.encode(id,metadata),at,id);return this.conversation(child.id,owner);
});}
history(id,owner){const current=this.conversation(id,owner),prior=current.continuationOf?this.conversation(current.continuationOf,owner).turns.filter(turn=>turn.status==='success').slice(-3):[];return [...prior,...current.turns.filter(turn=>turn.status==='success')].slice(-12);}
history(id,owner){const current=this.conversation(id,owner),metadata=this.metadata(this.store.row(id,owner));let prior=metadata.inheritedHistory;if(!Array.isArray(prior)){try{prior=current.continuationOf?this.conversation(current.continuationOf,owner,{includeDeleted:true}).turns.filter(turn=>turn.status==='success').slice(-3):[];}catch(error){if(error.status!==404)throw error;prior=[];}}return [...prior,...current.turns.filter(turn=>turn.status==='success')].slice(-12);}
retainChildren(id,owner){const inherited=this.conversation(id,owner,{includeDeleted:true}).turns.filter(t=>t.status==='success').slice(-3).map(t=>({text:t.text,reply:t.reply,status:'success'}));for(const row of this.store.db.prepare('SELECT * FROM conversations WHERE owner=? AND id<>?').all(owner,id)){const metadata=this.metadata(row);if(metadata.continuationOf===id&&!Array.isArray(metadata.inheritedHistory)){metadata.inheritedHistory=inherited;this.store.db.prepare('UPDATE conversations SET payload=? WHERE id=?').run(this.store.encode(row.id,metadata),row.id);}}}
trash(id,owner,input){return this.store.transaction(()=>{const row=this.store.row(id,owner);this.validate(row,input);this.checkIdle(id);this.retainChildren(id,owner);const metadata=this.metadata(row);metadata.version=(metadata.version||1)+1;const at=new Date().toISOString();this.store.db.prepare('UPDATE conversations SET deleted_at=?,updated_at=?,payload=? WHERE id=?').run(at,at,this.store.encode(id,metadata),id);return {id,version:metadata.version,deletedAt:at,archived:!!row.archived};});}
restoreDeleted(id,owner,input){return this.store.transaction(()=>{const row=this.store.row(id,owner,{includeDeleted:true});this.validate(row,input);if(!row.deleted_at)throw fail('此会话不在回收站。',409);if(!row.archived&&this.count(owner)>=50)throw fail('活跃会话已达50个,请先归档其他会话。',409);const metadata=this.metadata(row);metadata.version=(metadata.version||1)+1;this.store.db.prepare('UPDATE conversations SET deleted_at=NULL,updated_at=?,payload=? WHERE id=?').run(new Date().toISOString(),this.store.encode(id,metadata),id);return this.conversation(id,owner);});}
purge(id,owner,input){return this.store.transaction(()=>{const row=this.store.row(id,owner,{includeDeleted:true});if(input?.confirm!=='delete'||Object.keys(input).some(k=>!['version','confirm'].includes(k)))throw fail('请明确确认永久删除。');this.validate(row,{version:input.version});if(!row.deleted_at)throw fail('请先将会话移入回收站。',409);this.checkIdle(id);this.retainChildren(id,owner);this.store.db.prepare('DELETE FROM conversation_events WHERE conversation_id=?').run(id);this.store.db.prepare('DELETE FROM assistant_requests WHERE conversation_id=?').run(id);this.store.db.prepare('DELETE FROM turns WHERE conversation_id=?').run(id);this.store.db.prepare('DELETE FROM conversations WHERE id=? AND owner=?').run(id,owner);return {id,purged:true};});}
setModel(id,owner,input){return this.store.transaction(()=>{const row=this.store.row(id,owner);this.validate(row,{version:input.version});if(row.archived)throw fail('请先恢复归档会话。',409);this.store.providers.resolve({providerId:input.providerId,modelId:input.modelId});const metadata=this.metadata(row);metadata.modelSelection={providerId:input.providerId,modelId:input.modelId};metadata.version=(metadata.version||1)+1;this.store.db.prepare('UPDATE conversations SET payload=?,updated_at=? WHERE id=?').run(this.store.encode(id,metadata),new Date().toISOString(),id);return this.conversation(id,owner);});}
}
module.exports={ConversationHistory};
@@ -2,13 +2,13 @@
const {setImmediate:yieldLoop}=require('node:timers/promises');
const fail=message=>Object.assign(new Error(message),{status:400});
async function search(store,owner,{scope='active',page=1,pageSize=25,query}){
if(typeof query!=='string'||query.length>100||!['active','archived'].includes(scope)||!Number.isSafeInteger(page)||page<1||!Number.isSafeInteger(pageSize)||pageSize<1||pageSize>50)throw fail('会话搜索条件无效。');
const term=query.trim().toLocaleLowerCase(),archived=Number(scope==='archived'),maximum=archived?2000:50;
const count=store.db.prepare('SELECT COUNT(*) n FROM conversations WHERE owner=? AND archived=?').get(owner,archived).n,found=[];
if(typeof query!=='string'||query.length>100||!['active','archived','deleted'].includes(scope)||!Number.isSafeInteger(page)||page<1||!Number.isSafeInteger(pageSize)||pageSize<1||pageSize>50)throw fail('会话搜索条件无效。');
const term=query.trim().toLocaleLowerCase(),archived=Number(scope==='archived'),maximum=scope==='active'?50:2000,filter=scope==='deleted'?'deleted_at IS NOT NULL':'archived=? AND deleted_at IS NULL',args=scope==='deleted'?[owner]:[owner,archived];
const count=store.db.prepare('SELECT COUNT(*) n FROM conversations WHERE owner=? AND '+filter).get(...args).n,found=[];
// Capture IDs once so a concurrent update cannot shift offsets and skip rows.
const rows=store.db.prepare('SELECT id,payload,created_at,updated_at FROM conversations WHERE owner=? AND archived=? ORDER BY updated_at DESC,rowid DESC LIMIT ?').all(owner,archived,maximum);
const rows=store.db.prepare('SELECT id,payload,archived,deleted_at,created_at,updated_at FROM conversations WHERE owner=? AND '+filter+' ORDER BY updated_at DESC,rowid DESC LIMIT ?').all(...args,maximum);
for(let offset=0;offset<rows.length;offset+=100){
for(const row of rows.slice(offset,offset+100)){const metadata=store.decode(row.id,row.payload);if(String(metadata.title||'').toLocaleLowerCase().includes(term))found.push({id:row.id,...metadata,archived:!!archived,createdAt:row.created_at,updatedAt:row.updated_at});}
for(const row of rows.slice(offset,offset+100)){const metadata=store.decode(row.id,row.payload);if(String(metadata.title||'').toLocaleLowerCase().includes(term))found.push({id:row.id,title:metadata.title,version:metadata.version||1,modelSelection:metadata.modelSelection||null,archived:!!row.archived,deletedAt:row.deleted_at||null,createdAt:row.created_at,updatedAt:row.updated_at});}
await yieldLoop();
}
const actual=Math.min(page,Math.max(1,Math.ceil(found.length/pageSize)));
+3 -2
View File
@@ -7,7 +7,7 @@ class AssistantStreams{
open({request,response,id,user,after,authenticate}){
if(this.closed)throw fail('助手事件服务正在停止。',503);
if(this.clients.size>=30||[...this.clients].filter(c=>c.owner===user.id).length>=2)throw fail('事件连接过多,请稍后重试或使用轮询。',429);
const client={owner:user.id,response};this.clients.add(client);let cursor=after,ended=false,lastHeartbeat=Date.now();
const client={owner:user.id,response};this.clients.add(client);let cursor=after,ended=false,lastHeartbeat=Date.now(),metadataVersion=null,lastMetadataAt=0;
const close=()=>{if(ended)return;ended=true;clearInterval(timer);this.clients.delete(client);response.end();};client.close=close;
const write=frame=>{if(ended||response.destroyed)return false;if(response.writableLength+Buffer.byteLength(frame)>256*1024){close();return false;}response.write(frame);return true;};
const pump=()=>{
@@ -19,7 +19,8 @@ class AssistantStreams{
}
const batch=this.store.events(id,user.id,{after:cursor});
for(const event of batch.events){if(!write('id: '+event.seq+'\nevent: assistant_event\ndata: '+JSON.stringify(event)+'\n\n'))return;cursor=event.seq;}
}catch{write('event: stream_error\ndata: {"status":503}\n\n');close();}
if(now-lastMetadataAt>=1000){const row=this.store.row(id,user.id),version=this.store.decode(id,row.payload).version||1;lastMetadataAt=now;if(version!==metadataVersion){metadataVersion=version;write('event: conversation_updated\ndata: '+JSON.stringify({version})+'\n\n');}}
}catch(error){write(error.status===404?'event: conversation_removed\ndata: {"status":404}\n\n':'event: stream_error\ndata: {"status":503}\n\n');close();}
};
const timer=setInterval(pump,this.tickMs);timer.unref?.();
response.once('close',close);
+15 -12
View File
@@ -2,35 +2,38 @@
const {fail}=require('./store.cjs'),{cleanMessage,snapshot,checkAction,parseResponse}=require('./policy.cjs'),{redact}=require('../../shared/redact.cjs');
class AssistantService{
constructor({store,runtime,journal,repairFactory,...deps}){this.store=store;this.runtime=runtime;this.journal=journal;this.repairFactory=repairFactory;this.deps=deps;this.running=new Map();this.actions=new Set();this.stopped=false;}
secretKeys(){const keys=[this.store.secretSettings().apiKey,...this.store.db.prepare('SELECT id FROM assistant_providers').all().map(row=>this.store.providers.read(row.id).apiKey)];return [...new Set(keys.filter(key=>typeof key==='string'&&key.length))];}
context(user,diagnostic){return require('./diagnostic-context.cjs').diagnosticContext(this.deps,user,diagnostic);}
async check(){const config=this.store.secretSettings();return {...await this.runtime.probe(config.runtimePath),modelConfigured:!!(config.apiBase&&config.model&&config.apiKey)};}
async check(){const config=this.store.secretSettings();let modelConfigured=false;try{modelConfigured=!!this.store.providers.resolve();}catch{}return {...await this.runtime.probe(config.runtimePath),modelConfigured};}
record(id,principal,step,status,detail){return this.journal?.append({operationId:id,actor:principal.user.id,step,status,detail});}
operations(principal,{beforeId}={}){const users=principal.user.role==='admin'?this.deps.dashboard?.users?.()||[]:[];return (this.journal?.list({actor:principal.user.id,isAdmin:principal.user.role==='admin',beforeId})||[]).map(e=>({...e,actorLabel:e.actor===principal.user.id?principal.user.username:users.find(u=>u.id===e.actor)?.username||e.actor}));}
repairRunner(principal){const config=this.store.settings();if(!config.enabled||principal.user.role!=='admin'||!config.allowActions||!config.allowCodeRepair||!config.repairRepository)throw fail('代码修复未开放或账号无权限。',403);if(this.repairFactory)return this.repairFactory(config);const path=require('node:path');return new(require('./code-repair.cjs').CodeRepairRunner)({repoRoot:config.repairRepository,repairRoot:path.join(this.store.dir,'repairs'),journal:this.journal,validator:{command:process.execPath,args:[path.join(__dirname,'repair-validator.cjs')],env:{NODE_PATH:path.join(config.repairRepository,'node_modules')},timeoutMs:300000}});}
sendRepair(id,principal,text,paths){const runner=this.repairRunner(principal);if(!Array.isArray(paths)||paths.length>5)throw fail('每次请选择1至5个源码文件。');const repair={...runner.readSources(paths),repositoryRoot:this.store.settings().repairRepository};if(JSON.stringify(repair).length>60000)throw fail('源码超过本轮修复上下文限制,请减少所选文件。');return this.send(id,principal,text,{repair});}
sendRepair(id,principal,text,paths){const runner=this.repairRunner(principal);if(!Array.isArray(paths)||paths.length>5)throw fail('每次请选择1至5个源码文件。');const repair={...runner.readSources(paths),repositoryRoot:this.store.settings().repairRepository};if(repair.files.some(file=>this.secretKeys().some(key=>String(file.content).includes(key))))throw fail('选定源码包含已保存的模型凭据,请先移除凭据。');if(JSON.stringify(repair).length>60000)throw fail('源码超过本轮修复上下文限制,请减少所选文件。');return this.send(id,principal,text,{repair});}
send(id,principal,text,{repair,diagnostic,requestId}={}){
if(this.stopped)throw fail('助手服务正在停止。',503);if(!principal?.user?.id)throw fail('请先登录。',401);
if(typeof text!=='string'||!text.trim()||text.length>4000)throw fail('请输入 1–4000 字的消息。');
const requestPayload={text,diagnostic:diagnostic?{command:diagnostic.command,...(diagnostic.targetId!==undefined?{targetId:diagnostic.targetId}:{})}:null,repair:repair||null},existing=this.store.requestTurn(id,principal.user.id,requestId,requestPayload);if(existing)return existing;
this.store.conversation(id,principal.user.id);if([...this.running.values()].some(r=>r.conversationId===id))throw fail('当前对话正在回复,请等待或停止。',409);
const conversation=this.store.conversation(id,principal.user.id);if([...this.running.values()].some(r=>r.conversationId===id))throw fail('当前对话正在回复,请等待或停止。',409);
if(this.running.size>=2)throw fail('助手正在处理其他对话,请稍后重试。',429);
const config=this.store.secretSettings();if(!config.enabled||!config.runtimePath||!config.apiBase||!config.model||!config.apiKey)throw fail('请管理员先配置并启用 DSH 助手。',409);
const context=require('./dsh-runtime.cjs').prepareContext(JSON.parse(JSON.stringify({...this.context(principal.user,diagnostic),...(repair?{repair}:{}),...(diagnostic?{diagnostic:requestPayload.diagnostic}:{})},(_key,value)=>typeof value==='string'?cleanMessage(value,config.apiKey):value)));
const history=this.store.history(id,principal.user.id).map(t=>({user:cleanMessage(redact(t.text),config.apiKey),assistant:cleanMessage(redact(t.reply),config.apiKey)}));
const turn=this.store.beginTurn(id,principal.user.id,cleanMessage(redact(text.trim(),4000),config.apiKey),{requestId,requestPayload,diagnosticSnapshot:context}),controller=new AbortController();
if(this.journal&&config.apiKey&&!this.journal.secrets.includes(config.apiKey))this.journal.secrets.push(config.apiKey);
const settings=this.store.secretSettings();if(!settings.enabled||!settings.runtimePath)throw fail('请管理员先配置并启用 DSH 助手。',409);const config={...settings,...this.store.providers.resolve(conversation.modelSelection||undefined)};
const secrets=this.secretKeys(),sanitize=value=>secrets.reduce((text,key)=>cleanMessage(text,key),String(value??''));
const context=require('./dsh-runtime.cjs').prepareContext(JSON.parse(JSON.stringify({...this.context(principal.user,diagnostic),...(repair?{repair}:{}),...(diagnostic?{diagnostic:requestPayload.diagnostic}:{})},(_key,value)=>typeof value==='string'?sanitize(value,config.apiKey):value)));
const history=this.store.history(id,principal.user.id).map(t=>({user:sanitize(redact(t.text),config.apiKey),assistant:sanitize(redact(t.reply),config.apiKey)}));
const modelSelection={providerId:config.providerId,providerName:config.providerName,providerVersion:config.providerVersion,modelId:config.model,modelName:config.modelName};
const turn=this.store.beginTurn(id,principal.user.id,sanitize(redact(text.trim(),4000),config.apiKey),{requestId,requestPayload,diagnosticSnapshot:context,modelSelection}),controller=new AbortController();
if(this.journal&&Array.isArray(this.journal.secrets))for(const key of secrets)if(!this.journal.secrets.includes(key))this.journal.secrets.push(key);
try{this.record(turn.id,principal,'context','running',repair?'管理员选定源码,基线 '+repair.baselineCommit:'已读取授权业务状态快照');}catch{this.store.updateTurn(turn.id,'error',{error:'操作审计不可用,未调用模型。'});throw fail('操作审计不可用,已停止本轮。',503);}
const timer=setTimeout(()=>controller.abort(fail('DSH 回复超时,可稍后重试。',504)),config.timeoutSeconds*1000);
const task=Promise.resolve().then(async()=>{
try{if(controller.signal.aborted)throw controller.signal.reason;
const raw=await this.runtime.chat({config,text:cleanMessage(redact(text,4000),config.apiKey),context,history,signal:controller.signal,onEvent:event=>{if(!controller.signal.aborted&&['runtime','model'].includes(event?.kind))this.store.stage(turn.id,event.kind,event.data);}});if(controller.signal.aborted)throw controller.signal.reason;
const raw=await this.runtime.chat({config,text:sanitize(redact(text,4000),config.apiKey),context,history,signal:controller.signal,onEvent:event=>{if(!controller.signal.aborted&&['runtime','model'].includes(event?.kind))this.store.stage(turn.id,event.kind,event.data);}});if(controller.signal.aborted)throw controller.signal.reason;
this.store.stage(turn.id,'validation');
const response=require('./repair-response.cjs').parseRepairResponse(raw,this.deps,principal.user,repair,config.apiKey);response.reply=cleanMessage(redact(response.reply,20000),config.apiKey);if(!config.allowActions)response.actions=[];
const response=require('./repair-response.cjs').parseRepairResponse(raw,this.deps,principal.user,repair,config.apiKey);if(response.actions.some(action=>action.kind==='repair_code'&&action.files.some(file=>secrets.some(key=>file.content.includes(key)))))throw fail('修复建议包含模型凭据,未保存此建议。',502);response.reply=sanitize(redact(response.reply,20000),config.apiKey);if(!config.allowActions)response.actions=[];
this.record(turn.id,principal,'model','success','模型回复已校验;操作建议 '+response.actions.length+' 项,尚未执行');
this.store.updateTurn(turn.id,'success',{...response,evidence:[{label:'诊断快照时间',value:context.at},{label:'范围',value:`${context.connections.length} 个授权 BPM 连接,${context.servers.length} 个存储配置,${context.jobs.length} 条导出记录`}],finishedAt:new Date().toISOString()});
}catch(e){const cancelled=e.status===499&&!e.stopUnconfirmed&&controller.signal.aborted&&controller.signal.reason?.status===499,status=e.stopUnconfirmed?'needs_review':cancelled?'cancelled':'error';try{this.record(turn.id,principal,'model',status,cleanMessage(redact(e.status?e.message:'模型调用未完成'),config.apiKey));}catch{}this.store.updateTurn(turn.id,status,{error:cleanMessage(redact(e.status?e.message:'DSH 调用未完成,请检查运行包和模型配置。'),config.apiKey),finishedAt:new Date().toISOString()});}
}catch(e){const cancelled=e.status===499&&!e.stopUnconfirmed&&controller.signal.aborted&&controller.signal.reason?.status===499,status=e.stopUnconfirmed?'needs_review':cancelled?'cancelled':'error';try{this.record(turn.id,principal,'model',status,sanitize(redact(e.status?e.message:'模型调用未完成'),config.apiKey));}catch{}this.store.updateTurn(turn.id,status,{error:sanitize(redact(e.status?e.message:'DSH 调用未完成,请检查运行包和模型配置。'),config.apiKey),finishedAt:new Date().toISOString()});}
finally{clearTimeout(timer);this.running.delete(turn.id);}
});this.running.set(turn.id,{conversationId:id,owner:principal.user.id,controller,task});return turn;
});this.running.set(turn.id,{conversationId:id,owner:principal.user.id,providerId:config.providerId,controller,task});return turn;
}
cancel(id,principal){this.store.conversation(id,principal.user.id);for(const [turnId,r] of this.running)if(r.conversationId===id&&!r.controller.signal.aborted){this.store.updateTurn(turnId,'running',{cancelRequested:true});r.controller.abort(fail('已停止本轮回复。',499));}return {ok:true};}
async executeAction(conversationId,actionId,principal){
+20 -9
View File
@@ -16,7 +16,9 @@ class AssistantStore{
CREATE INDEX IF NOT EXISTS conversation_turns ON turns(conversation_id,created_at);`);
this.transactionDepth=0;this.pendingEvents=[];this.eventListeners=new Set();
this.db.exec('CREATE TABLE IF NOT EXISTS assistant_requests(conversation_id TEXT NOT NULL,request_key TEXT NOT NULL,turn_id TEXT NOT NULL,payload BLOB NOT NULL,PRIMARY KEY(conversation_id,request_key))');
this.db.exec('CREATE TABLE IF NOT EXISTS assistant_usage(turn_id TEXT PRIMARY KEY,day TEXT NOT NULL); CREATE INDEX IF NOT EXISTS assistant_usage_day ON assistant_usage(day); INSERT OR IGNORE INTO assistant_usage SELECT id,day FROM turns');
this.conversationHistory=new ConversationHistory(this);this.conversationEvents=new ConversationEvents(this);
this.transaction(()=>{this.providers=new(require('./providers.cjs').ProviderRegistry)(this);const row=this.db.prepare('SELECT * FROM config WHERE id=1').get();if(row){const raw=this.decode('config',row.payload);if(raw.apiKey)this.db.prepare('UPDATE config SET payload=? WHERE id=1').run(this.encode('config',{...raw,apiKey:''}));}});
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
@@ -30,12 +32,15 @@ class AssistantStore{
stage(turnId,kind,data){return this.conversationEvents.append(turnId,kind,data);}
encode(id,value){return this.vault.encode('assistant:'+id,value);}
decode(id,value){return this.vault.decode('assistant:'+id,value);}
secretSettings(){const row=this.db.prepare('SELECT * FROM config WHERE id=1').get(),saved=row?this.decode('config',row.payload):null;return row?{allowCodeRepair:false,repairRepository:'',...saved,runtimePath:saved.engine==='dsh'?saved.runtimePath||this.defaultRuntime:this.defaultRuntime,version:row.version}:{version:1,enabled:false,runtimePath:this.defaultRuntime,apiBase:'https://api.deepseek.com/anthropic',model:'deepseek-flash',apiKey:'',timeoutSeconds:90,dailyLimit:100,allowActions:false,allowCodeRepair:false,repairRepository:''};}
secretSettings(){const row=this.db.prepare('SELECT * FROM config WHERE id=1').get(),saved=row?this.decode('config',row.payload):null;const result=row?{allowCodeRepair:false,repairRepository:'',...saved,runtimePath:saved.engine==='dsh'?saved.runtimePath||this.defaultRuntime:this.defaultRuntime,version:row.version}:{version:1,enabled:false,runtimePath:this.defaultRuntime,apiBase:'https://api.deepseek.com/anthropic',model:'deepseek-flash',apiKey:'',timeoutSeconds:90,dailyLimit:100,allowActions:false,allowCodeRepair:false,repairRepository:''};if(this.providers){let legacy;try{legacy=this.providers.read('deepseek');}catch(error){if(error.status!==409)throw error;}result.apiKey=legacy?.apiKey||'';if(legacy){result.apiBase=legacy.apiBase;if(!legacy.models.some(m=>m.id===result.model))result.model=legacy.models[0]?.id||'';}}return result;}
settings(){const {apiKey,...settings}=this.secretSettings();return {...settings,hasApiKey:!!apiKey};}
saveSettings(input){return this.transaction(()=>{
const legacyWrite=!!input&&['apiBase','model','apiKey'].some(key=>Object.hasOwn(input,key));
const old=this.secretSettings(),keys=['version','enabled','runtimePath','apiBase','model','apiKey','hasApiKey','timeoutSeconds','dailyLimit','allowActions','allowCodeRepair','repairRepository','engine'];
if(!input||Array.isArray(input)||Object.keys(input).some(k=>!keys.includes(k)))throw fail('助手配置格式不正确。');
if(input.version!==old.version)throw fail('助手配置已更新,请刷新后重试。',409);
input={...old,...input,apiKey:input.apiKey??''};
if(input.version!==old.version)throw fail('助手配置已更新,请刷新后重试。',409);
for(const key of ['enabled','allowActions'])if(typeof input[key]!=='boolean')throw fail('请选择是否启用助手及恢复操作。');
if(!Number.isInteger(input.timeoutSeconds)||input.timeoutSeconds<15||input.timeoutSeconds>180||!Number.isInteger(input.dailyLimit)||input.dailyLimit<1||input.dailyLimit>1000)throw fail('超时须为 15–180 秒,每日调用上限须为 1–1000。');
for(const key of ['runtimePath','apiBase','model'])if(typeof input[key]!=='string'||input[key].length>1000||/[\x00-\x1f]/.test(input[key]))throw fail('运行包、模型地址或名称格式不正确。');
@@ -48,27 +53,33 @@ class AssistantStore{
if(typeof allowCodeRepair!=='boolean'||typeof repairRepository!=='string'||repairRepository.length>1000||repairRepository&&(!path.isAbsolute(repairRepository)||/[\x00-\x1f]/.test(repairRepository)))throw fail('代码修复权限或仓库路径无效。');
if(allowCodeRepair&&!repairRepository)throw fail('开放代码修复前请选择源码仓库。');
const saved={engine:'dsh',allowCodeRepair,repairRepository,enabled:input.enabled,runtimePath,apiBase,model,apiKey:input.apiKey||old.apiKey,timeoutSeconds:input.timeoutSeconds,dailyLimit:input.dailyLimit,allowActions:input.allowActions};
if(saved.enabled&&(!runtimePath||!apiBase||!model||!saved.apiKey))throw fail('启用前请填写运行包路径、模型 API 地址、模型名称和密钥。');
this.db.prepare('INSERT INTO config VALUES(1,?,?) ON CONFLICT(id) DO UPDATE SET version=excluded.version,payload=excluded.payload').run(old.version+1,this.encode('config',saved));return this.settings();
let providerReady=false;try{providerReady=!!this.providers?.resolve();}catch{}
if(saved.enabled&&(!runtimePath||!(legacyWrite&&apiBase&&model&&saved.apiKey||providerReady)))throw fail('启用前请填写运行包,并配置可用供应商和默认模型。');
this.db.prepare('INSERT INTO config VALUES(1,?,?) ON CONFLICT(id) DO UPDATE SET version=excluded.version,payload=excluded.payload').run(old.version+1,this.encode('config',{...saved,apiKey:''}));if(legacyWrite)this.providers?.syncLegacy(saved);return this.settings();
});}
conversations(owner,filters){return this.conversationHistory.list(owner,filters).items;}
listConversations(owner,filters){return this.conversationHistory.list(owner,filters);}
row(id,owner){const row=this.db.prepare('SELECT * FROM conversations WHERE id=? AND owner=?').get(id,owner);if(!row)throw fail('没有找到此对话。',404);return row;}
row(id,owner,{includeDeleted=false}={}){const row=this.db.prepare('SELECT * FROM conversations WHERE id=? AND owner=?').get(id,owner);if(!row||row.deleted_at&&!includeDeleted)throw fail('没有找到此对话。',404);return row;}
create(owner,options){return this.conversationHistory.create(owner,options);}
conversation(id,owner){return this.conversationHistory.conversation(id,owner);}
conversation(id,owner,options){return this.conversationHistory.conversation(id,owner,options);}
archive(id,owner,input){return this.conversationHistory.setArchived(id,owner,true,input);}
restore(id,owner,input){return this.conversationHistory.setArchived(id,owner,false,input);}
continueConversation(id,owner,input){return this.conversationHistory.continue(id,owner,input);}
trash(id,owner,input){return this.conversationHistory.trash(id,owner,input);}
restoreDeleted(id,owner,input){return this.conversationHistory.restoreDeleted(id,owner,input);}
purge(id,owner,input){return this.conversationHistory.purge(id,owner,input);}
setModel(id,owner,input){return this.conversationHistory.setModel(id,owner,input);}
history(id,owner){return this.conversationHistory.history(id,owner);}
requestTurn(id,owner,requestId,payload){this.row(id,owner);if(requestId===undefined)return null;if(typeof requestId!=='string'||!/^[-\w]{1,100}$/.test(requestId))throw fail('请求编号无效。');const key=crypto.createHash('sha256').update(requestId).digest('hex'),row=this.db.prepare('SELECT * FROM assistant_requests WHERE conversation_id=? AND request_key=?').get(id,key);if(!row)return null;const digest=crypto.createHash('sha256').update(JSON.stringify(payload)).digest('hex');if(this.decode('request:'+id+':'+key,row.payload).digest!==digest)throw fail('此请求编号已用于不同的消息。',409);const turn=this.db.prepare('SELECT * FROM turns WHERE id=?').get(row.turn_id);if(!turn)throw fail('请求结果不可用,请重新读取会话。',409);return {id:turn.id,status:turn.status,createdAt:turn.created_at,...this.decode(turn.id,turn.payload)};}
beginTurn(id,owner,text,{requestId,requestPayload,diagnosticSnapshot}={}){return this.transaction(()=>{
beginTurn(id,owner,text,{requestId,requestPayload,diagnosticSnapshot,modelSelection}={}){return this.transaction(()=>{
const existing=this.requestTurn(id,owner,requestId,requestPayload);if(existing)return existing;
const row=this.row(id,owner),count=this.db.prepare('SELECT COUNT(*) AS n FROM turns WHERE conversation_id=?').get(id).n;
if(row.archived)throw fail('请先恢复归档会话或继续新对话。',409);
if(count>=100)throw fail('此对话已达 100 轮,请新建对话。',409);
if(this.db.prepare("SELECT 1 FROM turns WHERE conversation_id=? AND status='running'").get(id))throw fail('当前对话正在回复,请等待或停止。',409);
if(this.db.prepare('SELECT COUNT(*) AS n FROM turns WHERE day=?').get(day()).n>=this.settings().dailyLimit)throw fail('已达到今天的模型调用上限。',429);
const turnId=crypto.randomUUID(),at=now(),payload={text,reply:'',actions:[],evidence:[],...(diagnosticSnapshot?{diagnosticSnapshot}:{})};this.db.prepare('INSERT INTO turns VALUES(?,?,?,?,?,?)').run(turnId,id,'running',this.encode(turnId,payload),day(),at);
if(this.db.prepare('SELECT COUNT(*) AS n FROM assistant_usage WHERE day=?').get(day()).n>=this.settings().dailyLimit)throw fail('已达到今天的模型调用上限。',429);
const turnId=crypto.randomUUID(),at=now(),payload={text,reply:'',actions:[],evidence:[],...(diagnosticSnapshot?{diagnosticSnapshot}:{}),...(modelSelection?{modelSelection}:{})};this.db.prepare('INSERT INTO turns VALUES(?,?,?,?,?,?)').run(turnId,id,'running',this.encode(turnId,payload),day(),at);
this.db.prepare('INSERT INTO assistant_usage VALUES(?,?)').run(turnId,day());
if(requestId!==undefined){const key=crypto.createHash('sha256').update(requestId).digest('hex'),digest=crypto.createHash('sha256').update(JSON.stringify(requestPayload)).digest('hex');this.db.prepare('INSERT INTO assistant_requests VALUES(?,?,?,?)').run(id,key,turnId,this.encode('request:'+id+':'+key,{digest}));}
const metadata=this.decode(id,row.payload);this.db.prepare('UPDATE conversations SET payload=?,updated_at=? WHERE id=?').run(this.encode(id,{...metadata,title:count?metadata.title:text.slice(0,40),version:(metadata.version||1)+1}),at,id);this.stage(turnId,'queued');if(diagnosticSnapshot)this.stage(turnId,'snapshot',{observedAt:diagnosticSnapshot.at,connectionCount:diagnosticSnapshot.connections?.length,serverCount:diagnosticSnapshot.servers?.length,jobCount:diagnosticSnapshot.jobs?.length});return {id:turnId,status:'running',createdAt:at,...payload};
});}
@@ -80,7 +91,7 @@ class AssistantStore{
return {id,status,createdAt:row.created_at,...value};});}
action(conversationId,owner,actionId,work){return this.transaction(()=>{if(this.row(conversationId,owner).archived)throw fail('请先恢复归档会话。',409);for(const row of this.db.prepare('SELECT * FROM turns WHERE conversation_id=? ORDER BY rowid DESC').all(conversationId)){const turn=this.decode(row.id,row.payload),action=turn.actions.find(a=>a.id===actionId);if(action){const result=work(action);this.updateTurn(row.id,row.status,{actions:turn.actions});return result;}}throw fail('操作卡片不存在。',404);});}
recover(){return this.transaction(()=>{for(const row of this.db.prepare('SELECT * FROM turns').all()){const turn=this.decode(row.id,row.payload);let changed=row.status==='running';for(const a of turn.actions||[])if(a.status==='running'){a.status='needs_review';a.error='服务重启,操作结果需要核实。';changed=true;}if(changed)this.updateTurn(row.id,row.status==='running'?'interrupted':row.status,{...turn,error:'服务重启,上一轮已中断。'});}});}
usage(){return {today:day(),calls:this.db.prepare('SELECT COUNT(*) AS n FROM turns WHERE day=?').get(day()).n,limit:this.settings().dailyLimit};}
usage(){return {today:day(),calls:this.db.prepare('SELECT COUNT(*) AS n FROM assistant_usage WHERE day=?').get(day()).n,limit:this.settings().dailyLimit};}
close(){this.eventListeners.clear();this.db.close();this.vault.destroy();}
}
module.exports={AssistantStore,fail};