'use strict'; 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, conversationId) { return { ...require('./diagnostic-context.cjs').diagnosticContext(this.deps, user, diagnostic), configuration: require('./configuration.cjs').snapshot(this.deps, this.store, user), management: require('./management.cjs').directory(this, user), ...(this.schedules ? { schedules: this.schedules.snapshot(conversationId, user) } : {}), }; } 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 ( 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 ( 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, attachments } = {}) { if (this.stopped) throw fail('助手服务正在停止。', 503); if (!principal?.user?.id) throw fail('请先登录。', 401); const files = require('./attachments.cjs'), attachmentIds = files.ids(attachments); if (text === '' && attachmentIds.length) text = '请分析附件。'; 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, ...(attachmentIds.length ? { attachments: attachmentIds } : {}), }, existing = this.store.requestTurn(id, principal.user.id, requestId, requestPayload); if (existing) return existing; 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 settings = this.store.secretSettings(); if (!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 currentFiles = files.resolve(this.store, principal.user.id, attachmentIds), fileInput = files.modelInput( this.store, principal.user.id, id, currentFiles, conversation.turns, config, ), fileContext = fileInput.attachments; const context = require('./dsh-runtime.cjs').prepareContext( JSON.parse( JSON.stringify( { ...this.context(principal.user, diagnostic, id), ...(fileContext.length ? { attachments: fileContext } : {}), ...(fileInput.attachmentNote ? { attachmentNote: fileInput.attachmentNote } : {}), ...(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.transaction(() => { const accepted = this.store.beginTurn( id, principal.user.id, sanitize(redact(text.trim(), 4000), config.apiKey), { requestId, requestPayload, diagnosticSnapshot: context, modelSelection, attachments: currentFiles.map((file) => { const { content, ...safe } = files.metadata(file); return safe; }), }, ); files.consume(this.store, principal.user.id, attachmentIds, id); return accepted; }), 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 require('./management-turn.cjs').chatWithManagement( this, turn.id, principal, { config, images: fileInput.images, 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); } }, }, sanitize, ); this.store.stage(turn.id, 'validation'); const response = require('./repair-response.cjs').parseRepairResponse( raw, { ...this.deps, assistantStore: this.store, configurationSnapshot: context.configuration, schedules: this.schedules, conversationId: id, }, principal.user, repair, config.apiKey, ); if ( response.actions.some( (action) => action.kind === 'update_configuration' && secrets.some((key) => JSON.stringify(action.changes).includes(key)), ) ) throw fail('设置建议包含模型凭据,未保存此建议。', 502); 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 = response.actions.filter((a) => a.kind === 'manage_schedule'); 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, 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, 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, options = {}) { if (principal.user.role === 'viewer') throw fail('只读成员不能执行操作。', 403); const candidate = this.store .conversation(conversationId, principal.user.id) .turns.flatMap((t) => t.actions || []) .find((a) => a.id === actionId); if (['update_configuration', 'manage_schedule'].includes(candidate?.kind)) return require('./configuration-approval.cjs').execute( this, conversationId, actionId, principal, options.approvalToken, ); if (this.stopped) throw fail('助手服务正在停止。', 503); const settings = this.store.settings(); if (!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); if (a.kind === 'repair_code') { this.repairRunner(principal); if (a.repositoryRoot !== settings.repairRepository) throw fail('修复仓库已变化,请重新生成建议。', 409); } else checkAction({ kind: a.kind, targetId: a.targetId }, this.deps, principal.user); a.status = 'running'; a.startedAt = new Date().toISOString(); return { ...a }; }); try { this.record(action.id, principal, 'execute', 'running', action.kind + ' ' + action.targetId); } catch { this.store.action(conversationId, principal.user.id, actionId, (a) => Object.assign(a, { status: 'error', error: '操作审计不可用,未执行。' }), ); throw fail('操作审计不可用,未执行。', 503); } const task = (async () => { let result; let operationStarted = false; try { const runner = action.kind === 'repair_code' ? this.repairRunner(principal) : null; operationStarted = true; if (action.kind === 'repair_code') result = await runner.run({ actor: principal.user.id, isAdmin: true, files: action.files, expectedCommit: action.baselineCommit, }); else 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 if (['collect_field_samples', 'collect_history_samples'].includes(action.kind)) result = await require('./field-skill.cjs').collect( this.deps, action.targetId, principal, action.id, (progress) => { this.record( action.id, principal, 'sample_progress', 'running', '完成 ' + progress.completed + '/' + progress.total + ',成功 ' + progress.captured + ',受阻 ' + progress.failed, ); return this.store.action(conversationId, principal.user.id, actionId, (a) => Object.assign(a, { progress }), ); }, action.kind === 'collect_history_samples' ? 'history' : 'configuration', ); else if (action.kind === 'prepare_field_mapping') result = await require('./field-skill.cjs').prepare( this.deps, action.targetId, principal, action.id, action.guard, ); 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, 'DSH 助手固定操作', action.kind + ' ' + action.targetId, ); this.record( action.id, principal, 'execute', result?.status || 'success', action.kind + (result?.operationId ? ' · 修复记录 ' + result.operationId : ''), ); return this.store.action(conversationId, principal.user.id, actionId, (a) => Object.assign(a, { status: 'success', result, finishedAt: new Date().toISOString() }), ); } catch (e) { const uncertain = operationStarted || e.mutationApplied === true; const status = uncertain ? 'needs_review' : 'error'; const message = uncertain ? '操作可能已产生影响,请到原功能页面核实;请勿重复执行。' : e.status ? redact(e.message) : '操作未完成,请核实结果。'; try { this.record( action.id, principal, 'execute', status, JSON.stringify({ message, ...(result !== undefined ? { result } : {}), }), ); } catch {} this.store.action(conversationId, principal.user.id, actionId, (a) => Object.assign(a, { status, error: message, ...(result !== undefined ? { result } : {}), finishedAt: new Date().toISOString(), }), ); throw Object.assign(fail(message, e.status || 502), { outcome: uncertain ? 'uncertain' : 'rejected', }); } })(); this.actions.add(task); try { return await task; } finally { this.actions.delete(task); } } async stop() { this.stopped = true; for (const [turnId, r] of this.running) { if (!r.controller.signal.aborted) this.store.updateTurn(turnId, 'running', { cancelRequested: true }); r.controller.abort(fail('服务正在停止,本轮已取消。', 499)); } await Promise.allSettled( [...this.running.values()] .map((r) => r.task) .concat([...this.actions], this.schedules ? [this.schedules.stop()] : []), ); } } module.exports = { AssistantService };