feat(assistant): complete controlled management attachments and native schedules

This commit is contained in:
abaishu0730 committed 2026-10-29 09:22:15 +08:00
1 parent d0bc4b0da2
commit 8341986067
119 files changed
+20519 -1618

No files matched your search

+361 -49
View File
@@ -1,51 +1,363 @@
'use strict';
const {fail}=require('./store.cjs'),{secureBpmTransport}=require('../bpm/api.cjs');
function bodyKeys(body,keys){if(!body||Array.isArray(body)||Object.keys(body).some(k=>!keys.includes(k)))throw fail('助手请求包含不支持的字段。');}
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'){
const params=new URL(request.url,'http://localhost').searchParams;
if([...params.keys()].some(k=>k!=='after')||params.getAll('after').length>1)throw fail('事件查询参数无效。');
const raw=eventRoute[2]==='stream'&&request.headers['last-event-id']!==undefined?request.headers['last-event-id']:params.get('after')??'0';
if(typeof raw!=='string'||!/^\d+$/.test(raw)||!Number.isSafeInteger(Number(raw)))throw fail('事件游标无效。');
const after=Number(raw),[_,id,kind]=eventRoute;
assistant.store.row(id,user.id);if(after>assistant.store.eventCursor(id,user.id))throw fail('事件游标超过会话范围。');
if(kind==='events')reply(200,assistant.store.events(id,user.id,{after}));
else streams.open({request,response,id,user,after,authenticate:authenticateStream});
return true;
}
if((route==='/api/assistant/settings'||route==='/api/assistant/check')&&method==='POST'){
if(user.role!=='admin')throw fail('仅管理员可以配置或检查 DSH。',403);if(!secureBpmTransport(request,trustedProxy))throw fail('请在部署机本地或 HTTPS 页面维护模型配置。',403);
if(route.endsWith('/settings')){const saved=assistant.store.saveSettings(body);workspace?.record(user,'配置 DSH 助手',saved.enabled?'已启用':'已暂停');reply(200,saved);}else{bodyKeys(body,[]);reply(200,await assistant.check());}return true;
}
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'){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;}
bodyKeys(body,[]);if(action==='cancel'){reply(200,assistant.cancel(id,principal));return true;}
if(actionId){reply(200,await assistant.executeAction(id,actionId,principal));return true;}
}
}
throw fail('没有找到此助手操作。',404);
const { fail } = require('./store.cjs'),
{ secureBpmTransport } = require('../bpm/api.cjs');
function bodyKeys(body, keys) {
if (!body || Array.isArray(body) || Object.keys(body).some((k) => !keys.includes(k)))
throw fail('助手请求包含不支持的字段。');
}
module.exports={assistantApi};
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/usage' && method === 'GET') {
reply(200, assistant.store.usage());
return true;
}
if (route === '/api/assistant/management' && method === 'GET') {
reply(200, require('./management.cjs').directory(assistant, user));
return true;
}
if (route === '/api/assistant/management/query' && method === 'POST') {
reply(200, await require('./management.cjs').query(assistant, body, principal));
return true;
}
if (
await require('./schedules-api.cjs').schedulesApi({
assistant,
principal,
route,
method,
body,
request,
reply,
trustedProxy,
})
)
return true;
if (route === '/api/assistant' && method === 'GET') {
const settings = assistant.store.settings();
reply(200, {
settings:
user.role === 'admin'
? settings
: {
runtimeConfigured: !!settings.runtimePath,
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/attachments' && method === 'POST') {
const files = require('./attachments.cjs'),
controller = new AbortController(),
abort = () => {
if (!response.writableEnded) controller.abort();
};
response.once('close', abort);
try {
const parsed = await files.parse(body, { signal: controller.signal });
if (controller.signal.aborted) throw fail('已取消附件解析。', 499);
for (const key of assistant.secretKeys())
parsed.content = parsed.content.split(key).join('[已隐藏]');
if (parsed.kind !== 'image') parsed.characters = parsed.content.length;
reply(201, files.stage(assistant.store, user.id, parsed));
} finally {
response.removeListener('close', abort);
}
return true;
}
const imagePreview =
/^\/api\/assistant\/conversations\/([\w-]+)\/attachments\/([\w-]+)\/preview$/.exec(route);
if (imagePreview && method === 'GET') {
const file = require('./attachments.cjs').readImage(
assistant.store,
user.id,
imagePreview[1],
imagePreview[2],
);
response.writeHead(200, {
'Content-Type': file.mediaType,
'Cache-Control': 'no-store',
'Content-Security-Policy': "default-src 'none'; sandbox",
});
response.end(Buffer.from(file.imageData, 'base64'));
return true;
}
const removeAttachment = /^\/api\/assistant\/attachments\/([\w-]+)\/remove$/.exec(route);
if (removeAttachment && method === 'POST') {
bodyKeys(body, []);
reply(200, require('./attachments.cjs').remove(assistant.store, user.id, removeAttachment[1]));
return true;
}
if (route === '/api/assistant/context' && method === 'GET') {
reply(200, assistant.context(user));
return true;
}
const configurationReview =
/^\/api\/assistant\/conversations\/([\w-]+)\/actions\/([\w-]+)\/(review|reject)$/.exec(route);
if (configurationReview && method === 'POST') {
if (!secureBpmTransport(request, trustedProxy))
throw fail('请在部署机本地或 HTTPS 页面审查设置修改。', 403);
bodyKeys(body, []);
const [, id, actionId, operation] = configurationReview;
reply(
200,
require('./configuration-approval.cjs')[operation](assistant, id, actionId, principal),
);
return true;
}
const eventRoute = /^\/api\/assistant\/conversations\/([\w-]+)\/(events|stream)$/.exec(route);
if (eventRoute && method === 'GET') {
const params = new URL(request.url, 'http://localhost').searchParams;
if ([...params.keys()].some((k) => k !== 'after') || params.getAll('after').length > 1)
throw fail('事件查询参数无效。');
const raw =
eventRoute[2] === 'stream' && request.headers['last-event-id'] !== undefined
? request.headers['last-event-id']
: (params.get('after') ?? '0');
if (typeof raw !== 'string' || !/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw)))
throw fail('事件游标无效。');
const after = Number(raw),
[_, id, kind] = eventRoute;
assistant.store.row(id, user.id);
if (after > assistant.store.eventCursor(id, user.id)) throw fail('事件游标超过会话范围。');
if (kind === 'events') reply(200, assistant.store.events(id, user.id, { after }));
else streams.open({ request, response, id, user, after, authenticate: authenticateStream });
return true;
}
if (
(route === '/api/assistant/settings' || route === '/api/assistant/check') &&
method === 'POST'
) {
if (user.role !== 'admin') throw fail('仅管理员可以配置或检查 DSH。', 403);
if (!secureBpmTransport(request, trustedProxy))
throw fail('请在部署机本地或 HTTPS 页面维护模型配置。', 403);
if (route.endsWith('/settings')) {
const saved = assistant.store.saveSettings(body);
workspace?.record(user, '配置 DSH 助手', saved.enabled ? '已启用' : '已暂停');
reply(200, saved);
} else {
bodyKeys(body, []);
reply(200, await assistant.check());
}
return true;
}
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);
if (['delete', 'purge'].includes(action)) await assistant.schedules?.stopSession(id);
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);
if (['archive', 'continue'].includes(history[2]))
await assistant.schedules?.stopSession(history[1]);
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') {
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', 'attachments']);
const diagnostic = require('./diagnostic-context.cjs').validateDiagnostic(
body.diagnostic,
assistant.deps,
user,
);
reply(
202,
assistant.send(id, principal, body.text, {
diagnostic,
requestId: body.requestId,
attachments: body.attachments,
}),
);
return true;
}
bodyKeys(body, actionId ? ['approvalToken'] : []);
if (action === 'cancel') {
reply(200, assistant.cancel(id, principal));
return true;
}
if (actionId) {
if (user.role === 'viewer') throw fail('只读成员不能执行操作。', 403);
const candidate = assistant.store
.conversation(id, user.id)
.turns.flatMap((t) => t.actions || [])
.find((a) => a.id === actionId);
if (
['update_configuration', 'manage_schedule'].includes(candidate?.kind) &&
!secureBpmTransport(request, trustedProxy)
)
throw fail('请在部署机本地或 HTTPS 页面授权设置修改。', 403);
reply(200, await assistant.executeAction(id, actionId, principal, body));
return true;
}
}
}
throw fail('没有找到此助手操作。', 404);
}
module.exports = { assistantApi };