Files
Agent-Workbench/src/core/desktop/install-manager.mjs
T
2026-11-04 19:40:33 +08:00

269 lines
23 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import { randomUUID, createHash } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import net from 'node:net';
import { isDeepStrictEqual } from 'node:util';
import { HostController } from './host-controller.mjs';
import { inspectHostInstallation } from './app-installation.mjs';
import { observeWindowsProcess, protectUserDirectory, binaryIdentity } from './process-identity.mjs';
import { ownedChild, treeFile, readState, writeState, samePath, assertLocalTree } from './file-state.mjs';
import { upgradeRunning } from '../../../scripts/upgrade-running.mjs';
import { canonicalHost, hostError } from '../../shared/contracts/desktop-host.mjs';
import { InstallationProgress } from './installation-progress.mjs';
const digest = value => createHash('sha256').update(value).digest('hex');
const inside = (root, value) => samePath(root, value) || path.resolve(value).toLowerCase().startsWith(path.resolve(root).toLowerCase() + path.sep);
const fail = message => hostError(message, 'INSTALLATION_REJECTED', 409);
export function validateInstalledVersion(directory, { onProgress = null } = {}) {
const installation = inspectHostInstallation(directory, { full: true, onProgress });
if (installation.kind !== 'portable') throw fail('安装候选需要完整便携发行清单。');
const manifest = readState(path.join(installation.root, 'MANIFEST.json'), 16 * 1024 * 1024), actual = [];
const walk = relative => { for (const entry of fs.readdirSync(path.join(installation.root, relative), { withFileTypes: true })) {
// Recheck file ownership after the hash scan: an optional shipped file may
// have acquired another link in the meantime. Keep the single-realpath
// file check rather than walking every ancestor again for every file.
const next = path.posix.join(relative, entry.name);
if (entry.isDirectory()) { ownedChild(installation.root, next); walk(next); } else if (entry.isFile()) {
treeFile(installation.root, next);
actual.push(next); onProgress?.({ scope: 'directory-inventory', root: installation.root, completedFiles: actual.length, totalFiles: manifest.files.length + 1, completedBytes: null, totalBytes: null, currentPath: next });
} else throw fail('安装候选含有链接或非常规文件。');
} }; walk('');
const declared = manifest.files.map(value => value.path).concat('MANIFEST.json').sort();
if (!isDeepStrictEqual(actual.sort(), declared)) throw fail('安装候选的实际文件范围与清单不同。');
for (const relative of ['AgentWorkbench.exe', 'runtime/node.exe', 'desktop/AgentWorkbench.exe', 'desktop/resources/app/main.cjs', 'desktop/resources/app/package.json', 'dist-desktop/main.cjs', 'dist-desktop/preload.cjs', 'dist-server/install-manager.mjs']) if (!declared.includes(relative)) throw fail('桌面安装缺少必要运行文件。');
// Full-manifest verification covers all shipped bytes; the host identity is
// deliberately the same narrower loaded-input identity used by HostController.
return inspectHostInstallation(directory, { onProgress });
}
export function snapshotPersistentData(dataRoot) {
assertLocalTree(dataRoot); const databaseFile = path.join(dataRoot, 'workbench.sqlite'), tables = {};
if (fs.existsSync(databaseFile)) {
ownedChild(dataRoot, 'workbench.sqlite'); const database = new DatabaseSync(databaseFile, { readOnly: true });
try {
for (const { name } of database.prepare("SELECT name FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all()) {
if (!/^[a-z_]+$/.test(name)) throw fail('原数据库包含无法核对的表名。');
const rows = database.prepare('SELECT * FROM "' + name + '"').all().filter(row => !(name === 'metadata' && row.key === 'runtimeOwner'));
const hashes = rows.map(row => digest(JSON.stringify(canonicalHost(row)))).sort(); tables[name] = { count: hashes.length, hashes };
}
} finally { database.close(); }
}
const artifacts = [], artifactRoot = path.join(dataRoot, 'artifacts');
if (fs.existsSync(artifactRoot)) {
const walk = relative => { for (const entry of fs.readdirSync(path.join(artifactRoot, relative), { withFileTypes: true })) {
const next = path.posix.join(relative, entry.name), file = ownedChild(dataRoot, 'artifacts/' + next);
if (entry.isDirectory()) walk(next); else if (entry.isFile()) { const bytes = fs.readFileSync(file); artifacts.push({ path: next, bytes: bytes.length, sha256: digest(bytes) }); } else throw fail('原工件目录包含非常规文件。');
} }; walk('');
}
const files = ['config.json', 'projects.json'].filter(relative => fs.existsSync(path.join(dataRoot, relative))).map(relative => ({ path: relative, sha256: digest(fs.readFileSync(ownedChild(dataRoot, relative))) }));
return { tables, artifacts: artifacts.sort((a, b) => a.path.localeCompare(b.path)), files, scope: 'Every persistent database row except runtimeOwner, every original artifact byte and existing public config/project files; no credential is decrypted or returned.' };
}
export class InstallationManager {
constructor({ installRoot, dataRoot, port = 4318, candidateRoot = null, timeoutMs = 60000, operationId = null, expectedManifestSha256 = null, onProgress = null }) {
for (const value of [installRoot, dataRoot]) if (typeof value !== 'string' || !path.isAbsolute(value)) throw fail('安装和数据目录必须为本机绝对路径。');
if (inside(installRoot, dataRoot) || inside(dataRoot, installRoot) || !Number.isInteger(port) || port < 1 || port > 65535) throw fail('程序与用户数据需要独立目录及有效本机端口。');
assertLocalTree(installRoot, { missing: true }); assertLocalTree(dataRoot, { missing: true });
fs.mkdirSync(installRoot, { recursive: true }); fs.mkdirSync(dataRoot, { recursive: true });
this.installRoot = fs.realpathSync.native(installRoot); this.dataRoot = fs.realpathSync.native(dataRoot); this.port = port; this.timeoutMs = timeoutMs;
this.candidateRoot = candidateRoot ? fs.realpathSync.native(candidateRoot) : null;
this.recordFile = ownedChild(this.installRoot, 'current.json', { missing: true });
this.stateRoot = ownedChild(this.installRoot, '.installation', { missing: true }); fs.mkdirSync(this.stateRoot, { recursive: true }); protectUserDirectory(this.stateRoot);
this.progressOptions = { operationId, expectedManifestSha256, onProgress };
if (expectedManifestSha256 !== null && !/^[a-f0-9]{64}$/.test(expectedManifestSha256)) throw fail('安装候选清单身份无效。');
}
async operation(command, action) {
return this.lock(async () => {
const progress = new InstallationProgress({ stateRoot: this.stateRoot, installRoot: this.installRoot, dataRoot: this.dataRoot, command, ...this.progressOptions });
this.progress = progress; this.receiptFile = null;
try {
const result = await action();
// The verified publication receipt is authoritative. A status-file error
// after commit must not relabel an activated version as a failed update.
try { progress.finish(command === 'preflight' ? 'ready-to-copy' : command === 'cancel' ? 'cancelled' : result.phase === 'staged' ? 'staged' : command === 'uninstall' ? 'uninstall-ready' : 'completed', { activeVersion: result.active?.version ?? result.current?.version ?? result.candidate?.version ?? null, receiptFile: result.receiptFile ?? null }); }
catch (error) { if (command === 'preflight') throw error; return { ...result, operationId: progress.value.id, progressFile: progress.file, progressWarning: error.message }; }
return { ...result, progressFile: progress.file, operationId: progress.value.id };
} catch (error) { try { progress.finish('failed', { error: { code: error.code ?? 'INSTALLATION_FAILED', message: error.message }, receiptFile: this.receiptFile, pointer: fs.existsSync(this.recordFile) ? 'retained-record; inspect original receipt' : 'not-published' }); } catch {} throw error; }
finally { this.progress = null; }
});
}
phase(name, detail = {}) { this.progress?.phase(name, detail); }
async cancelPreparation() { return this.operation('cancel', async () => ({ phase: 'cancelled', activated: false, dataPolicy: 'preserve-original-data' })); }
verification(scope) { return value => this.progress?.count(scope, value); }
current() {
if (!fs.existsSync(this.recordFile)) return null;
const value = readState(this.recordFile, 16384);
if (value.schema !== 1 || value.app !== 'agent-workbench-installation' || !/^[a-f0-9-]{36}$/.test(value.installId ?? '') || !Number.isSafeInteger(value.revision)
|| value.revision < 1 || !samePath(value.dataRoot ?? '', this.dataRoot) || value.port !== this.port) throw fail('当前安装登记无法核对,保留原记录。');
this.phase('verify-current', { version: value.active.version });
const root = this.versionRoot(value.active), actual = validateInstalledVersion(root, { onProgress: this.verification('verify-current') });
if (actual.version !== value.active.version || actual.manifestSha256 !== value.active.manifestSha256 || actual.identitySha256 !== value.active.runtimeIdentity) throw fail('当前活动版本的实际程序与原登记不同。');
if (value.previous) this.versionRoot(value.previous);
return value;
}
versionRoot(version) {
if (!version || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/.test(version.directory ?? '') || !/^\d+\.\d+\.\d+$/.test(version.version ?? '')
|| !/^[a-f0-9]{64}$/.test(version.manifestSha256 ?? '') || !/^[a-f0-9]{64}$/.test(version.runtimeIdentity ?? '')) throw fail('原活动版本登记无效。');
return ownedChild(this.installRoot, 'versions/' + version.directory);
}
candidate() {
if (!this.candidateRoot) throw fail('没有指定独立安装候选。');
const expected = path.join(this.installRoot, 'versions', path.basename(this.candidateRoot));
if (!samePath(expected, this.candidateRoot)) throw fail('新版本只能位于当前安装的独立versions目录。');
this.phase('verify-candidate');
const identity = validateInstalledVersion(this.candidateRoot, { onProgress: this.verification('verify-candidate') });
if (this.progressOptions.expectedManifestSha256 && identity.manifestSha256 !== this.progressOptions.expectedManifestSha256) throw fail('新候选与本次安装器固定的原清单不同。');
this.progress?.candidate(identity);
return { directory: path.basename(identity.root), version: identity.version, manifestSha256: identity.manifestSha256, runtimeIdentity: identity.identitySha256 };
}
async host() {
const infoFile = ownedChild(this.dataRoot, 'service-info.json', { missing: true });
if (!fs.existsSync(infoFile)) { await this.assertFreePort(); return null; }
const info = readState(infoFile), actual = observeWindowsProcess(info.pid);
if (!actual || info.createdAt && info.createdAt !== actual.createdAt) {
await this.assertFreePort();
return null;
}
if (!info.instanceId || !info.createdAt || !info.runtimeIdentity || !info.runtimeRoot || info.port !== this.port || !samePath(info.dataRoot ?? '', this.dataRoot)) throw fail('旧执行宿主没有可核验的桌面身份。可先暂存安装候选,再通过保留状态的升级流程接入。');
const controller = new HostController({ appRoot: info.runtimeRoot, dataRoot: this.dataRoot, port: this.port, nodePath: process.execPath, timeoutMs: this.timeoutMs });
const connected = await controller.connect(); if (!connected) throw fail('原执行进程仍活动,接口尚不可核对。');
const status = await controller.status();
if (status.state !== 'ready' || status.activity.active || status.desktopWindows.count) throw fail('先等待原任务、审批、工具或模型请求结束,并关闭桌面窗口;后台宿主可保持运行。');
return { controller, identity: connected.identity, status };
}
async assertFreePort() {
await new Promise((resolve, reject) => {
const socket = net.createConnection({ host: '127.0.0.1', port: this.port });
socket.setTimeout(1500);
socket.once('connect', () => { socket.destroy(); reject(fail('本机端口被未知或未登记服务占用,保留原安装。')); });
socket.once('timeout', () => { socket.destroy(); reject(fail('原端口状态无法核对。')); });
socket.once('error', error => { socket.destroy(); error.code === 'ECONNREFUSED' ? resolve() : reject(fail('原端口状态无法核对。')); });
});
}
async lock(action) {
const directory = ownedChild(this.stateRoot, 'operation.lock', { missing: true }), nonce = randomUUID(), observed = observeWindowsProcess(process.pid);
try { fs.mkdirSync(directory); } catch (error) {
if (error.code !== 'EEXIST') throw error;
const owner = readState(ownedChild(directory, 'owner.json'), 16384), actual = observeWindowsProcess(owner.pid);
if (actual && actual.createdAt === owner.createdAt) throw fail('原安装操作仍在运行。');
const archive = ownedChild(this.stateRoot, 'stale-lock-' + randomUUID(), { missing: true }); fs.renameSync(directory, archive); fs.mkdirSync(directory);
}
protectUserDirectory(directory);
const file = path.join(directory, 'owner.json'); writeState(file, { nonce, pid: process.pid, createdAt: observed.createdAt, userSid: observed.userSid });
try { return await action(); } finally { if (fs.existsSync(file) && readState(file).nonce === nonce) { fs.unlinkSync(file); fs.rmdirSync(directory); } }
}
async preflight({ stageOnly = false } = {}) {
return this.operation('preflight', async () => {
const current = this.current(); this.phase('inspect-root'); this.inspectRoot(current); this.phase('inspect-host'); const host = stageOnly ? null : await this.host();
return { allowed: true, phase: stageOnly ? 'stage-only' : 'preflight', current: current?.active ?? null,
host: host ? { pid: host.identity.pid, instanceId: host.identity.instanceId, unresolvedTools: host.status.activity.unresolvedTools } : null,
dataRoot: this.dataRoot, dataPolicy: 'preserve-original-data' };
});
}
inspectRoot(current) {
for (const entry of fs.readdirSync(this.installRoot, { withFileTypes: true })) {
ownedChild(this.installRoot, entry.name);
if (!((entry.isDirectory() && ['.installation', 'versions'].includes(entry.name)) || (entry.isFile() && (['current.json', 'AgentWorkbench.exe'].includes(entry.name) || /^unins\d{3}\.(exe|dat|msg)$/.test(entry.name))))) throw fail('程序根目录存在未登记内容,不覆盖原目录。');
}
const bootstrap = ownedChild(this.installRoot, 'AgentWorkbench.exe', { missing: true });
if (fs.existsSync(bootstrap)) {
const root = current ? this.versionRoot(current.active) : this.candidateRoot;
if (!root || binaryIdentity(bootstrap).sha256 !== binaryIdentity(ownedChild(root, 'AgentWorkbench.exe')).sha256) throw fail('原根启动器与所属发行不一致,不复用或覆盖未知程序。');
}
}
async activate({ stageOnly = false, beforePointer = null, afterPointer = null } = {}) {
return this.operation('activate', async () => {
const candidate = this.candidate(), old = this.current(); this.inspectRoot(old); const priorHost = stageOnly ? null : await this.host();
this.phase('snapshot-data');
const snapshot = snapshotPersistentData(this.dataRoot), id = randomUUID(), receiptFile = path.join(this.stateRoot, 'operation-' + id + '.json');
this.receiptFile = receiptFile;
const receipt = { schema: 1, id, operationId: this.progress?.value.id, state: 'prepared', candidate, original: old?.active ?? null, dataRoot: this.dataRoot, snapshot, stageOnly, startedAt: new Date().toISOString() };
writeState(receiptFile, receipt);
if (stageOnly) { writeState(receiptFile, { ...receipt, state: 'staged' }); return { phase: 'staged', candidate, receiptFile, activated: false }; }
let upgraded = false, next = null, pointerPublished = false;
const originalPointer = old ? fs.readFileSync(this.recordFile) : null;
const bootstrapFile = ownedChild(this.installRoot, 'AgentWorkbench.exe', { missing: true });
const originalBootstrap = fs.existsSync(bootstrapFile) ? fs.readFileSync(bootstrapFile) : null;
const candidateBootstrap = fs.readFileSync(ownedChild(this.candidateRoot, 'AgentWorkbench.exe'));
let bootstrapPublished = false;
const replaceBootstrap = bytes => {
const temporary = ownedChild(this.stateRoot, 'bootstrap-' + randomUUID() + '.tmp', { missing: true });
const descriptor = fs.openSync(temporary, 'wx', 0o600);
try { fs.writeFileSync(descriptor, bytes); fs.fsyncSync(descriptor); } finally { fs.closeSync(descriptor); }
try { fs.renameSync(temporary, bootstrapFile); } finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
};
try {
if (priorHost && !samePath(priorHost.identity.runtimeRoot, this.candidateRoot)) {
this.phase('retain-host', { pid: priorHost.identity.pid });
await upgradeRunning({ url: priorHost.controller.url, pid: priorHost.identity.pid, currentRoot: priorHost.identity.appRoot, handlerRoot: priorHost.identity.runtimeRoot, newRoot: this.candidateRoot }); upgraded = true;
const nextHost = await this.host();
if (!nextHost || nextHost.identity.pid !== priorHost.identity.pid || nextHost.identity.instanceId !== priorHost.identity.instanceId || nextHost.identity.runtimeIdentity !== candidate.runtimeIdentity) throw fail('新处理器没有保持原宿主实例。');
}
this.phase('verify-data');
const after = snapshotPersistentData(this.dataRoot); if (!isDeepStrictEqual(snapshot, after)) throw fail('安装更新改变了原持久行或工件。');
if (beforePointer) await beforePointer();
if (!isDeepStrictEqual(old, this.current())) throw fail('原安装指针已发生变化,停止发布候选。');
if (!isDeepStrictEqual(candidate, this.candidate())) throw fail('新候选在预检后发生变化,停止发布候选。');
this.phase('publish-pointer', { interruptible: false });
const actualBootstrap = fs.existsSync(bootstrapFile) ? fs.readFileSync(bootstrapFile) : null;
if (!isDeepStrictEqual(actualBootstrap, originalBootstrap)) throw fail('原启动器在预检后发生变化,停止发布候选。');
if (!isDeepStrictEqual(originalBootstrap, candidateBootstrap)) { replaceBootstrap(candidateBootstrap); bootstrapPublished = true; }
next = { schema: 1, app: 'agent-workbench-installation', installId: old?.installId ?? randomUUID(), revision: (old?.revision ?? 0) + 1,
dataRoot: this.dataRoot, port: this.port, active: candidate, previous: old?.active ?? null, activatedAt: new Date().toISOString() };
writeState(this.recordFile, next);
pointerPublished = true;
this.phase('verify-publication', { interruptible: false });
if (afterPointer) await afterPointer(); // Explicit in-process QA fault fixture, never exposed by the CLI.
this.inspectRoot(next);
writeState(receiptFile, { ...receipt, state: 'activated', hostRetained: upgraded, finishedAt: new Date().toISOString() });
return { phase: 'activated', active: candidate, receiptFile, hostRetained: upgraded, dataPreserved: true };
} catch (error) {
try { this.phase('rollback', { interruptible: false, originalError: error.message }); } catch {}
let rollback = 'pointer-preserved';
try {
if (pointerPublished && fs.existsSync(this.recordFile)) {
if (!isDeepStrictEqual(readState(this.recordFile), next)) throw fail('发布后的指针被其他操作改变,不能覆盖未知记录。');
if (originalPointer) {
const temporary = ownedChild(this.installRoot, '.rollback-' + id + '.json', { missing: true });
fs.writeFileSync(temporary, originalPointer, { flag: 'wx' }); fs.renameSync(temporary, this.recordFile);
} else fs.unlinkSync(this.recordFile);
} else if (pointerPublished && old) throw fail('发布后的指针已丢失,回退需要核对。');
if (bootstrapPublished) {
if (!fs.existsSync(bootstrapFile) || !fs.readFileSync(bootstrapFile).equals(candidateBootstrap)) throw fail('发布后的启动器被其他操作改变,不能覆盖未知程序。');
if (originalBootstrap) replaceBootstrap(originalBootstrap); else fs.unlinkSync(bootstrapFile);
}
if (upgraded) {
await upgradeRunning({ url: priorHost.controller.url, pid: priorHost.identity.pid, currentRoot: priorHost.identity.appRoot, handlerRoot: this.candidateRoot, newRoot: priorHost.identity.runtimeRoot });
const restored = await priorHost.controller.connect(); if (!restored || restored.identity.instanceId !== priorHost.identity.instanceId || restored.identity.pid !== priorHost.identity.pid) throw fail('原宿主回退仍需核对。');
rollback = 'original-host-and-pointer-restored';
}
if (!isDeepStrictEqual(snapshot, snapshotPersistentData(this.dataRoot)) || (old && !fs.readFileSync(this.recordFile).equals(originalPointer))) throw fail('原持久数据或安装指针回退仍需核对。');
if (!isDeepStrictEqual(fs.existsSync(bootstrapFile) ? fs.readFileSync(bootstrapFile) : null, originalBootstrap)) throw fail('原启动器回退仍需核对。');
} catch (rollbackError) {
try { writeState(receiptFile, { ...receipt, state: 'rollback-unverified', error: error.message, rollbackError: rollbackError.message }); } catch {}
throw fail('安装失败,原宿主或指针回退尚待核对。请保留原操作记录,不重新执行任务。');
}
try { writeState(receiptFile, { ...receipt, state: 'failed', error: error.message, rollback }); } catch {}
throw error;
}
});
}
async prepareUninstall() {
return this.operation('uninstall', async () => {
const current = this.current(); if (!current) throw fail('没有可核对的本产品安装登记。');
this.inspectRoot(current);
this.phase('snapshot-data'); const snapshot = snapshotPersistentData(this.dataRoot); this.phase('inspect-host'); const host = await this.host();
if (host) await host.controller.stop();
if (!isDeepStrictEqual(snapshot, snapshotPersistentData(this.dataRoot))) throw fail('停止后原持久数据变化,卸载仍需核对。');
const receiptFile = path.join(this.stateRoot, 'uninstall-' + randomUUID() + '.json');
const result = { allowed: true, phase: 'uninstall-ready', dataRoot: this.dataRoot, dataPolicy: 'preserve-original-data', hostExited: !!host, active: current.active, snapshot };
writeState(receiptFile, result);
if (!isDeepStrictEqual(current, this.current())) throw fail('卸载期间原指针发生变化,保留原记录。');
fs.renameSync(this.recordFile, ownedChild(this.stateRoot, 'uninstalled-' + current.installId + '-' + current.revision + '.json', { missing: true }));
return { ...result, snapshot: undefined, receiptFile };
});
}
}