feat(assistant): manage providers models and personal conversation recycle bin
This commit is contained in:
1 parent
506e6fbfad
commit
301cdf669d
29 files changed
+267
-83
No files matched your search
@@ -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};
|
||||
Reference in new issue
Block a user