refactor: organize source web and tests by business module
This commit is contained in:
1 parent
9854d2d5c2
commit
2aed328774
113 files changed
+189
-183
No files matched your search
@@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
const {fail}=require('./store.cjs'),{redact,cleanMessage,snapshot,checkAction,parseResponse}=require('./policy.cjs');
|
||||
class AssistantService{
|
||||
constructor({store,runtime,...deps}){this.store=store;this.runtime=runtime;this.deps=deps;this.running=new Map();this.actions=new Set();this.stopped=false;}
|
||||
context(user){return snapshot(this.deps,user);}
|
||||
async check(){const config=this.store.secretSettings();return {...await this.runtime.probe(config.runtimePath),modelConfigured:!!(config.apiBase&&config.model&&config.apiKey)};}
|
||||
send(id,principal,text){
|
||||
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 字的消息。');
|
||||
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('请管理员先配置并启用 ZCode 助手。',409);
|
||||
const context=JSON.parse(JSON.stringify(this.context(principal.user),(_key,value)=>typeof value==='string'?cleanMessage(value,config.apiKey):value));
|
||||
const history=this.store.conversation(id,principal.user.id).turns.filter(t=>t.status==='success').slice(-12).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)),controller=new AbortController();
|
||||
const timer=setTimeout(()=>controller.abort(fail('ZCode 回复超时,可稍后重试。',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});if(controller.signal.aborted)throw controller.signal.reason;
|
||||
const response=parseResponse(raw,this.deps,principal.user);response.reply=cleanMessage(response.reply,config.apiKey);if(!config.allowActions)response.actions=[];
|
||||
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;this.store.updateTurn(turn.id,cancelled?'cancelled':'error',{error:cleanMessage(redact(e.status?e.message:'ZCode 调用未完成,请检查运行包和模型配置。'),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;
|
||||
}
|
||||
cancel(id,principal){this.store.conversation(id,principal.user.id);for(const r of this.running.values())if(r.conversationId===id)r.controller.abort(fail('已停止本轮回复。',499));return {ok:true};}
|
||||
async executeAction(conversationId,actionId,principal){
|
||||
if(this.stopped)throw fail('助手服务正在停止。',503);
|
||||
const settings=this.store.settings();if(!settings.enabled||!settings.allowActions||principal.user.role==='viewer')throw fail('助手已暂停、未开放恢复操作或账号无权限。',403);
|
||||
const action=this.store.action(conversationId,principal.user.id,actionId,a=>{if(a.status!=='proposed')throw fail('此操作已执行或结果待核实,不能重复提交。',409);checkAction({kind:a.kind,targetId:a.targetId},this.deps,principal.user);a.status='running';a.startedAt=new Date().toISOString();return {...a};});
|
||||
const task=(async()=>{try{let result;
|
||||
if(action.kind==='check_storage'){const s=await this.deps.storage.check(action.targetId);result={readable:s.state.readable,writable:s.state.writable};}
|
||||
else if(action.kind==='scan_bpm'){const s=await this.deps.scanner.scan(action.targetId,principal);result={seen:s.seen,added:s.added};}
|
||||
else{const a=this.deps.storage.store.archives().find(a=>a.id===action.targetId);const s=await this.deps.storage.archive(a.serverId,a.jobId,a.baseDirectory??a.directory??'',principal.user.username);result={status:s.status,relativePath:s.relativePath};}
|
||||
this.deps.workspace?.record(principal.user,'ZCode 助手固定操作',action.kind+' '+action.targetId);
|
||||
return this.store.action(conversationId,principal.user.id,actionId,a=>Object.assign(a,{status:'success',result,finishedAt:new Date().toISOString()}));
|
||||
}catch(e){this.store.action(conversationId,principal.user.id,actionId,a=>Object.assign(a,{status:'error',error:redact(e.status?e.message:'操作未完成,请在原功能页面核实结果。'),finishedAt:new Date().toISOString()}));throw fail(e.status?redact(e.message):'操作未完成,请核实结果。',e.status||502);}})();
|
||||
this.actions.add(task);try{return await task;}finally{this.actions.delete(task);}
|
||||
}
|
||||
async stop(){this.stopped=true;for(const r of this.running.values())r.controller.abort(fail('服务正在停止,本轮已取消。',499));await Promise.allSettled([...this.running.values()].map(r=>r.task).concat([...this.actions]));}
|
||||
}
|
||||
module.exports={AssistantService};
|
||||
Reference in new issue
Block a user