58 lines
8.0 KiB
JavaScript
58 lines
8.0 KiB
JavaScript
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
import { inspectHostInstallation } from '../core/desktop/app-installation.mjs';
|
||
import { binaryIdentity } from '../core/desktop/process-identity.mjs';
|
||
import { canonicalHost } from '../shared/contracts/desktop-host.mjs';
|
||
|
||
export function inspectOperations({ store, provider, runtime, server, appDirectory, version, parameters = new URLSearchParams() }) {
|
||
for (const key of parameters.keys()) if (!['artifactOffset', 'artifactLimit'].includes(key) || parameters.getAll(key).length !== 1) throw Object.assign(Error('巡检分页字段无效。'), { status: 400 });
|
||
const number = (key, fallback, minimum, maximum) => {
|
||
const raw = parameters.get(key); if (raw === null) return fallback;
|
||
if (!/^(0|[1-9]\d*)$/.test(raw) || !Number.isSafeInteger(Number(raw)) || Number(raw) < minimum || Number(raw) > maximum) throw Object.assign(Error('巡检分页范围无效。'), { status: 400 });
|
||
return Number(raw);
|
||
};
|
||
const all = [...store.core.artifact.values()], limit = number('artifactLimit', 50, 1, 100), offset = number('artifactOffset', Math.max(0, all.length - limit), 0, all.length);
|
||
const checks = [], check = (id, title, action) => { try { const result = action(); checks.push({ id, title, status: 'passed', ...(typeof result === 'string' ? { detail: result } : result) }); } catch (error) { checks.push({ id, title, status: 'failed', detail: provider.redact(error.message) }); } };
|
||
check('node', '执行宿主', () => { if (Number(process.versions.node.split('.')[0]) < 24) throw Error('需要Node.js24或以上。'); return process.version + ' · PID ' + process.pid; });
|
||
check('database', '任务数据库', () => { const rows = store.storage.database.prepare('PRAGMA quick_check').all(); if (rows.some(row => Object.values(row)[0] !== 'ok')) throw Error('数据库一致性检查未通过。'); return 'SQLite quick_check通过;' + store.sessions.size + '个会话。'; });
|
||
const inspected = [];
|
||
for (const value of all.slice(offset, offset + limit)) { try { store.artifactStore.readBytes(value); inspected.push({ id: value.id, sha256: value.sha256, bytes: value.bytes, passed: true }); } catch (error) { inspected.push({ id: value.id, passed: false, error: provider.redact(error.message) }); } }
|
||
const artifacts = { offset, limit, checked: inspected.length, total: all.length, olderOffset: offset > 0 ? Math.max(0, offset - limit) : null,
|
||
newerOffset: offset + inspected.length < all.length ? offset + inspected.length : null, remaining: all.length - inspected.length, results: inspected };
|
||
checks.push({ id: 'artifacts', title: '原执行工件', status: inspected.every(value => value.passed) ? 'passed' : 'failed', detail: '本次逐字节核对第' + (all.length ? offset + 1 : 0) + '至' + (offset + inspected.length) + '项,共' + all.length + '项;未覆盖' + artifacts.remaining + '项。' });
|
||
const center = provider.modelHub(store).view();
|
||
checks.push({ id: 'models', title: '模型连接', status: center.connections.some(value => value.status === 'configured' && value.model) ? 'configured' : 'attention', detail: center.connections.filter(value => value.enabled).length + '个启用连接;配置状态与真实模型响应分别记录。' });
|
||
const activity = server?.workbenchHostAuthority?.activity() ?? { counts: { tasks: runtime.active.size, approvals: runtime.waiters.size, workers: runtime.workers?.active.size ?? 0, controlledEngines: runtime.controlledEngines?.drivers.size ?? 0, mcp: runtime.mcp?.active.size ?? 0, checks: runtime.checks?.active.size ?? 0 }, scope: '现有内存管理器数量;本次没有初始化或登记桌面宿主。' };
|
||
const titles = { tasks: '任务', approvals: '审批', workers: '子任务', controlledEngines: '原生引擎', mcp: 'MCP', checks: '工程检查', deliveries: 'Git交付', fileBatches: '文件审查', workspaces: '工作区', research: '研究', engines: '引擎探测', browsers: '浏览器', plans: '计划', modelRequests: '模型请求', modelQueue: '模型排队', modelLeases: '模型占用' };
|
||
checks.push({ id: 'managers', title: '所属执行管理器', status: 'passed', detail: Object.entries(activity.counts).map(([key, count]) => (titles[key] ?? key) + ':' + count).join(' · ') });
|
||
const unknown = [];
|
||
for (const kind of ['tool', 'worker', 'engine_run', 'mcp_job', 'check_job', 'collaboration']) for (const value of store.core[kind]?.values() ?? []) if (value.requiresVerification) unknown.push({ kind, id: value.id, sessionId: value.sessionId, taskId: value.taskId, runId: value.runId, status: value.state ?? value.status });
|
||
checks.push({ id: 'unknown', title: '原结果待核对', status: unknown.length ? 'attention' : 'passed', detail: unknown.length + '项原结果需要显式核对;本次只列出归属,不重放工具或解除状态。' });
|
||
check('installation', '当前程序来源', () => { const value = inspectHostInstallation(appDirectory); return { detail: 'v' + value.version + ' · ' + value.inputs.length + '份实际宿主/客户端输入 · ' + value.root, runtimeIdentity: value.identitySha256, checked: value.inputs.length, scope: value.verification }; });
|
||
const sources = [];
|
||
for (const [id, driver] of runtime.controlledEngines?.drivers ?? []) {
|
||
try { driver.assertInput(); driver.native?.verifyLaunch?.(); sources.push({ kind: 'controlled-engine', id, taskId: driver.run?.taskId, status: 'passed', scope: 'Original active driver input/source binding; no prompt or process is started.' }); }
|
||
catch (error) { sources.push({ kind: 'controlled-engine', id, status: 'failed', error: provider.redact(error.message) }); }
|
||
}
|
||
check('sources', '引擎与MCP来源', () => {
|
||
const registrations = store.storage.meta('projectMcpRegistry', { registrations: [] }).registrations;
|
||
if (!Array.isArray(registrations)) throw Error('原MCP登记格式无法核对。');
|
||
for (const value of registrations) {
|
||
try {
|
||
for (const identity of [value.launch?.executable, value.launch?.entry].filter(Boolean)) if (JSON.stringify(canonicalHost(binaryIdentity(identity.path))) !== JSON.stringify(canonicalHost(identity))) throw Error('原登记MCP程序发生变化。');
|
||
if (runtime.mcp && value.contract) runtime.mcp.contract(value);
|
||
sources.push({ kind: 'mcp', id: value.id, projectId: value.projectId, status: 'passed', scope: runtime.mcp && value.contract ? 'Registered program and original handshake bytes.' : 'Registered program bytes; no new handshake or tool call.' });
|
||
} catch (error) { sources.push({ kind: 'mcp', id: value.id, status: 'failed', error: provider.redact(error.message) }); }
|
||
}
|
||
return { status: sources.some(value => value.status === 'failed') ? 'failed' : 'passed', detail: sources.length + '项活动原生执行/已登记MCP来源;未接入引擎和未记录的进程创建身份不在本次范围内。', checked: sources.length };
|
||
});
|
||
const disk = [];
|
||
check('disk', '程序与数据磁盘', () => {
|
||
for (const directory of [...new Set([path.resolve(appDirectory), path.resolve(store.directory)])]) { const value = fs.statfsSync(directory, { bigint: true }), bytes = value.bavail * value.bsize; disk.push({ directory, freeBytes: bytes.toString(), status: bytes < 64n * 1024n * 1024n ? 'attention' : 'passed' }); }
|
||
return { status: disk.some(value => value.status === 'attention') ? 'attention' : 'passed', detail: disk.map(value => value.directory + ' · 剩余' + Number(BigInt(value.freeBytes) / (1024n * 1024n)).toLocaleString() + ' MB').join(';') };
|
||
});
|
||
return { version, checkedAt: new Date().toISOString(), checks, activeTasks: runtime.active.size, queue: center.waiting, modelAttempts: center.attemptCount, modelRequests: 0,
|
||
artifacts, activity, unknown: { total: unknown.length, items: unknown.slice(0, 100), omitted: Math.max(0, unknown.length - 100) }, sources, disk,
|
||
scope: '本地只读巡检:数据库quick_check、明确分页的原工件、现有管理器与待核对归属、当前程序/已登记来源及磁盘余量;不发送模型请求、不执行项目命令或自动修复。一次分页通过不代表全部历史工件已核对。' };
|
||
}
|