73 lines
8.8 KiB
JavaScript
73 lines
8.8 KiB
JavaScript
'use strict';
|
||
const path=require('node:path'),crypto=require('node:crypto'),fs=require('node:fs'),{DatabaseSync}=require('node:sqlite'),{BpmVault}=require('../../platform/security/vault.cjs');
|
||
const fail=(message,status=400)=>Object.assign(new Error(message),{status}),now=()=>new Date().toISOString();
|
||
const {ConversationHistory}=require('./conversation-history.cjs');
|
||
const day=()=>new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date());
|
||
function installedRuntime(dir){try{
|
||
const root=path.join(path.dirname(dir),'zcode-runtime'),manifest=JSON.parse(fs.readFileSync(path.join(root,'manifest.json'),'utf8')),entry=path.join(root,'3.14.3','package','resources','glm','zcode.cjs');
|
||
if(manifest.releaseVersion!=='3.14.3'||manifest.cliVersion!=='0.16.9'||path.resolve(manifest.runtimePath)!==path.resolve(entry))return '';
|
||
const digest='sha256:'+crypto.createHash('sha256').update(fs.readFileSync(entry)).digest('hex');return digest===manifest.runtimeSha256?entry:'';
|
||
}catch{return '';}}
|
||
class AssistantStore{
|
||
constructor(dir){
|
||
try {
|
||
this.dir=path.resolve(dir);this.defaultRuntime=installedRuntime(this.dir);this.vault=new BpmVault({stateDir:this.dir});this.db=new DatabaseSync(path.join(this.dir,'assistant.sqlite'));
|
||
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
|
||
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY,version INTEGER NOT NULL,payload BLOB NOT NULL);
|
||
CREATE TABLE IF NOT EXISTS conversations(id TEXT PRIMARY KEY,owner TEXT NOT NULL,payload BLOB NOT NULL,created_at TEXT NOT NULL,updated_at TEXT NOT NULL);
|
||
CREATE TABLE IF NOT EXISTS turns(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,status TEXT NOT NULL,payload BLOB NOT NULL,day TEXT NOT NULL,created_at TEXT NOT NULL);
|
||
CREATE INDEX IF NOT EXISTS conversation_turns ON turns(conversation_id,created_at);`);
|
||
this.conversationHistory=new ConversationHistory(this);
|
||
} catch(error) {
|
||
try { this.db?.close(); } catch {}
|
||
try { this.vault?.destroy(); } catch {}
|
||
throw error;
|
||
}
|
||
}
|
||
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(e){this.db.exec('ROLLBACK');throw e;}}
|
||
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?{...saved,runtimePath:saved.runtimePath||this.defaultRuntime,version:row.version}:{version:1,enabled:false,runtimePath:this.defaultRuntime,apiBase:'',model:'',apiKey:'',timeoutSeconds:90,dailyLimit:100,allowActions:false};}
|
||
settings(){const {apiKey,...settings}=this.secretSettings();return {...settings,hasApiKey:!!apiKey};}
|
||
saveSettings(input){return this.transaction(()=>{
|
||
const old=this.secretSettings(),keys=['version','enabled','runtimePath','apiBase','model','apiKey','hasApiKey','timeoutSeconds','dailyLimit','allowActions'];
|
||
if(!input||Array.isArray(input)||Object.keys(input).some(k=>!keys.includes(k)))throw fail('助手配置格式不正确。');
|
||
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('运行包、模型地址或名称格式不正确。');
|
||
const runtimePath=input.runtimePath.trim(),apiBase=input.apiBase.trim().replace(/\/+$/,''),model=input.model.trim();
|
||
if(runtimePath&&(!path.isAbsolute(runtimePath)||!['.exe','.cjs','.mjs','.js'].includes(path.extname(runtimePath).toLowerCase())))throw fail('请选择本机官方 ZCode CLI 的绝对路径(exe/cjs/mjs/js)。');
|
||
if(apiBase){let u;try{u=new URL(apiBase);}catch{throw fail('模型 API 地址无效。');}if(u.username||u.password||u.search||u.hash||!(u.protocol==='https:'||(u.protocol==='http:'&&['127.0.0.1','localhost','[::1]'].includes(u.hostname))))throw fail('模型 API 请使用 HTTPS,或本机 HTTP 地址。');}
|
||
if(typeof input.apiKey!=='string'||input.apiKey.length>4096||/[\r\n]/.test(input.apiKey))throw fail('请输入有效模型密钥。');
|
||
if(!input.apiKey&&old.apiKey&&(apiBase!==old.apiBase||model!==old.model))throw fail('更换模型地址或名称后请重新填写密钥。');
|
||
const saved={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();
|
||
});}
|
||
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;}
|
||
create(owner,options){return this.conversationHistory.create(owner,options);}
|
||
conversation(id,owner){return this.conversationHistory.conversation(id,owner);}
|
||
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);}
|
||
history(id,owner){return this.conversationHistory.history(id,owner);}
|
||
beginTurn(id,owner,text){return this.transaction(()=>{
|
||
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:[]};this.db.prepare('INSERT INTO turns VALUES(?,?,?,?,?,?)').run(turnId,id,'running',this.encode(turnId,payload),day(),at);
|
||
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);return {id:turnId,status:'running',createdAt:at,...payload};
|
||
});}
|
||
updateTurn(id,status,patch){const row=this.db.prepare('SELECT * FROM turns WHERE id=?').get(id);if(!row)throw fail('回复不存在。',404);const value={...this.decode(id,row.payload),...patch};this.db.prepare('UPDATE turns SET status=?,payload=? WHERE id=?').run(status,this.encode(id,value),id);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(){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='interrupted';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};}
|
||
close(){this.db.close();this.vault.destroy();}
|
||
}
|
||
module.exports={AssistantStore,fail};
|