feat: ship lean runtime bundles and attributable update progress

This commit is contained in:
Agent Workbench Dev
2026-11-02 09:50:08 +08:00
parent 397099b284
commit befae3313d
40 changed files with 789 additions and 89 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
import { approvalBinding } from '../../shared/contracts/companion.mjs';
import { approvalKind } from '../../shared/approval-presentation.mjs';
export const pick = (value, names) => Object.fromEntries(names.filter(key => value?.[key] !== undefined).map(key => [key, structuredClone(value[key])]));
export const reportKinds = new Set(['delivery-report', 'delivery-report-markdown']);
@@ -24,7 +25,7 @@ export function mobileSession(store, runtime, session, redact = String) {
messages: session.messages.filter(value => ['assistant', 'system'].includes(value.role)).slice(-8).map(value => ({ ...pick(value, ['id', 'role', 'createdAt']), content: String(value.content).slice(0, 12000) })),
approvals: session.approvals.filter(value => value.status === 'pending' && value.taskId === session.taskId && value.runId === session.runId).map(value => ({
...pick(value, ['id', 'taskId', 'runId', 'projectId', 'command', 'reason', 'shell', 'createdAt']),
fingerprint: approvalBinding(session, value), actionable: runtime.waiters.get(value.id)?.runId === session.runId })),
kind: approvalKind(value), fingerprint: approvalBinding(session, value), actionable: runtime.waiters.get(value.id)?.runId === session.runId })),
changes: session.changes.filter(value => value.taskId === session.taskId).slice(-100).map(value => pick(value, ['id', 'path', 'reason', 'status', 'sha256', 'baseSha256', 'additions', 'deletions'])),
checks: checks.slice(-12).map(value => ({ ...pick(value, ['id', 'status', 'summary', 'requiresVerification', 'createdAt', 'finishedAt']),
results: (value.results ?? []).map(item => pick(item, ['name', 'status', 'exitCode', 'tests', 'durationMs'])) })),
+7 -2
View File
@@ -5,7 +5,7 @@ import { binaryIdentity } from './process-identity.mjs';
import { ownedChild, readState, assertLocalTree } from './file-state.mjs';
import { canonicalHost, hostError } from '../../shared/contracts/desktop-host.mjs';
export function inspectHostInstallation(directory, { full = false } = {}) {
export function inspectHostInstallation(directory, { full = false, onProgress = null } = {}) {
assertLocalTree(directory);
const root = fs.realpathSync.native(path.resolve(directory));
if (!fs.statSync(root).isDirectory()) throw hostError('宿主安装目录无效。');
@@ -26,10 +26,15 @@ export function inspectHostInstallation(directory, { full = false } = {}) {
if (full || /^(dist-client|dist-server|dist-desktop)\//.test(row.path)) files.add(row.path);
}
if (!manifest || manifest.kind === 'source') for (const entry of fs.readdirSync(path.join(root, 'dist-client/assets'))) files.add('dist-client/assets/' + entry);
const inputs = [...files].sort().map(relative => {
const selected = [...files].sort(), totalBytes = selected.reduce((sum, name) => sum + (names.get(name)?.bytes ?? 0), 0);
let completedFiles = 0, completedBytes = 0;
const report = currentPath => onProgress?.({ scope: full ? 'full-manifest' : 'loaded-inputs', root, totalFiles: selected.length, totalBytes: manifest ? totalBytes : null, completedFiles, completedBytes, currentPath });
report(null);
const inputs = selected.map(relative => {
const file = ownedChild(root, relative), identity = binaryIdentity(file), declared = names.get(relative);
if (manifest?.kind === 'portable' && !declared) throw hostError('实际宿主程序不在原发行清单中。');
if (declared && (identity.bytes !== declared.bytes || identity.sha256 !== declared.sha256)) throw hostError('实际宿主程序与原发行清单不一致。');
completedFiles++; completedBytes += identity.bytes; report(relative);
return { path: relative, bytes: identity.bytes, sha256: identity.sha256 };
});
const result = { root, version, kind: manifest?.kind ?? 'development-build', manifestSha256: manifest ? digest(fs.readFileSync(manifestFile)) : null,
+48 -12
View File
@@ -10,25 +10,28 @@ import { observeWindowsProcess, protectUserDirectory, binaryIdentity } from './p
import { ownedChild, 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) {
const installation = inspectHostInstallation(directory, { full: true });
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 })) {
const next = path.posix.join(relative, entry.name); ownedChild(installation.root, next);
if (entry.isDirectory()) walk(next); else if (entry.isFile()) actual.push(next); else throw fail('安装候选含有链接或非常规文件。');
if (entry.isDirectory()) walk(next); else if (entry.isFile()) {
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);
return inspectHostInstallation(directory, { onProgress });
}
export function snapshotPersistentData(dataRoot) {
@@ -55,7 +58,7 @@ export function snapshotPersistentData(dataRoot) {
}
export class InstallationManager {
constructor({ installRoot, dataRoot, port = 4318, candidateRoot = null, timeoutMs = 60000 }) {
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 });
@@ -64,13 +67,34 @@ export class InstallationManager {
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('当前安装登记无法核对,保留原记录。');
const root = this.versionRoot(value.active), actual = validateInstalledVersion(root);
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;
@@ -84,7 +108,10 @@ export class InstallationManager {
if (!this.candidateRoot) throw fail('没有指定独立安装候选。');
const expected = path.join(this.installRoot, 'versions', path.basename(this.candidateRoot));
if (!samePath(expected, this.candidateRoot)) throw fail('新版本只能位于当前安装的独立versions目录。');
const identity = validateInstalledVersion(this.candidateRoot);
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() {
@@ -124,10 +151,12 @@ export class InstallationManager {
try { return await action(); } finally { if (fs.existsSync(file) && readState(file).nonce === nonce) { fs.unlinkSync(file); fs.rmdirSync(directory); } }
}
async preflight({ stageOnly = false } = {}) {
const current = this.current(); this.inspectRoot(current); const host = stageOnly ? null : await this.host();
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 })) {
@@ -141,10 +170,12 @@ export class InstallationManager {
}
}
async activate({ stageOnly = false, beforePointer = null, afterPointer = null } = {}) {
return this.lock(async () => {
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');
const receipt = { schema: 1, id, state: 'prepared', candidate, original: old?.active ?? null, dataRoot: this.dataRoot, snapshot, stageOnly, startedAt: new Date().toISOString() };
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;
@@ -161,14 +192,17 @@ export class InstallationManager {
};
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; }
@@ -176,11 +210,13 @@ export class InstallationManager {
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)) {
@@ -211,10 +247,10 @@ export class InstallationManager {
});
}
async prepareUninstall() {
return this.lock(async () => {
return this.operation('uninstall', async () => {
const current = this.current(); if (!current) throw fail('没有可核对的本产品安装登记。');
this.inspectRoot(current);
const snapshot = snapshotPersistentData(this.dataRoot), host = await this.host();
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');
@@ -0,0 +1,84 @@
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { performance } from 'node:perf_hooks';
import { ownedChild, readState, writeState, samePath } from './file-state.mjs';
import { observeWindowsProcess } from './process-identity.mjs';
import { hostError } from '../../shared/contracts/desktop-host.mjs';
export const INSTALLATION_STAGES = Object.freeze({
preparing: '准备安装核对', 'verify-current': '核对原活动版本', 'verify-candidate': '核对新版本',
'inspect-root': '核对安装目录', 'inspect-host': '核对后台宿主与活动任务', 'snapshot-data': '记录原会话与工件',
'retain-host': '保留原宿主与模型连接', 'verify-data': '核对原会话与工件保持',
'publish-pointer': '发布活动版本', 'verify-publication': '核对已发布版本', rollback: '核对原版本回退',
'ready-to-copy': '预检通过,等待安装器写入版本文件', staged: '候选已暂存,尚未切换版本',
completed: '版本激活完成', failed: '安装未完成,请核对原始原因', 'uninstall-ready': '卸载预检完成,用户数据保留', cancelled: '本次安装准备已取消',
});
const terminal = new Set(['staged', 'completed', 'failed', 'uninstall-ready', 'cancelled']);
const validId = value => typeof value === 'string' && /^(?:[a-f0-9]{64}|[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})$/.test(value);
export class InstallationProgress {
constructor({ stateRoot, installRoot, dataRoot, command, operationId = null, expectedManifestSha256 = null, onProgress = null }) {
const id = operationId ?? randomUUID();
if (!validId(id)) throw hostError('安装操作编号无效。');
this.file = ownedChild(stateRoot, 'progress-' + id + '.json', { missing: true });
const previous = fs.existsSync(this.file) ? readState(this.file, 512 * 1024) : null;
if (previous && (previous.schema !== 1 || previous.id !== id || !samePath(previous.installRoot, installRoot) || !samePath(previous.dataRoot, dataRoot)
|| previous.expectedManifestSha256 !== expectedManifestSha256 || previous.state !== 'ready-to-copy' || !['activate', 'cancel'].includes(command))) throw hostError('原安装操作不允许重放或改变来源。');
if (!previous && command === 'cancel') throw hostError('没有可取消的原安装准备记录。');
this.onProgress = onProgress; this.lastSaved = 0;
this.value = { schema: 1, id, installRoot, dataRoot, command, expectedManifestSha256,
startedAt: previous?.startedAt ?? new Date().toISOString(), sequence: previous?.sequence ?? 0, history: previous?.history ?? [],
process: observeWindowsProcess(process.pid), candidate: previous?.candidate ?? null, state: 'running', stage: 'preparing', scope: null, counts: null, interruptible: false };
// Process identity only; environment, credentials and private data are never included.
const processIdentity = this.value.process;
this.value.process = processIdentity ? { pid: processIdentity.pid, createdAt: processIdentity.createdAt } : { pid: process.pid, createdAt: null };
this.phase('preparing');
}
phase(stage, detail = {}) {
if (!Object.hasOwn(INSTALLATION_STAGES, stage)) throw hostError('安装阶段无效。');
if (this.value.stageStartedAt) this.value.history.push({ stage: this.value.stage, scope: this.value.scope, counts: this.value.counts, startedAt: this.value.stageStartedAt, finishedAt: new Date().toISOString(), elapsedMs: Math.round(performance.now() - this.phaseStarted) });
this.value.history = this.value.history.slice(-96);
Object.assign(this.value, { stage, label: INSTALLATION_STAGES[stage], scope: null, counts: null, detail, stageStartedAt: new Date().toISOString() });
this.phaseStarted = performance.now(); this.save();
}
count(stage, value) {
if (this.value.stage !== stage || this.value.scope !== value.scope) this.phase(stage, { root: value.root });
this.value.scope = value.scope;
this.value.counts = { completedFiles: value.completedFiles, totalFiles: value.totalFiles, completedBytes: value.completedBytes, totalBytes: value.totalBytes, currentPath: value.currentPath };
if (performance.now() - this.lastSaved >= 500 || value.completedFiles === value.totalFiles || value.completedFiles === 0) this.save();
}
candidate(identity) {
this.value.candidate = { root: identity.root, version: identity.version, manifestSha256: identity.manifestSha256, runtimeIdentity: identity.identitySha256 };
this.save();
}
save() {
this.value.sequence++; this.value.updatedAt = new Date().toISOString();
this.value.elapsedMs = Math.max(0, Date.now() - Date.parse(this.value.startedAt));
writeState(this.file, this.value); this.lastSaved = performance.now();
// UI/console observers must never decide the installation result.
try { this.onProgress?.(structuredClone(this.value)); } catch {}
}
finish(state, detail = {}) {
if (!terminal.has(state) && state !== 'ready-to-copy') throw hostError('安装终态无效。');
this.value.state = state; this.phase(state, detail);
}
}
export function readInstallationProgress({ appRoot, dataRoot }) {
const versions = path.dirname(appRoot);
if (path.basename(versions).toLowerCase() !== 'versions') return { installed: false, operations: [] };
const installRoot = path.dirname(versions), pointerFile = ownedChild(installRoot, 'current.json', { missing: true });
if (!fs.existsSync(pointerFile)) return { installed: false, operations: [] };
const pointer = readState(pointerFile, 16384);
if (pointer.app !== 'agent-workbench-installation' || !samePath(pointer.dataRoot, dataRoot) || !pointer.active?.version) throw hostError('安装进度与当前数据目录不一致。');
const stateRoot = ownedChild(installRoot, '.installation', { missing: true });
const operations = fs.existsSync(stateRoot) ? fs.readdirSync(stateRoot).filter(name => /^progress-(?:[a-f0-9-]{36}|[a-f0-9]{64})\.json$/.test(name)).map(name => {
const value = readState(ownedChild(stateRoot, name), 512 * 1024);
if (value.schema !== 1 || !validId(value.id) || name !== 'progress-' + value.id + '.json' || !samePath(value.installRoot, installRoot) || !samePath(value.dataRoot, dataRoot) || !Number.isSafeInteger(value.sequence) || !Object.hasOwn(INSTALLATION_STAGES, value.stage)) throw hostError('原安装进度无法核对,请保留操作收据。');
const actual = value.state === 'running' ? observeWindowsProcess(value.process?.pid) : null;
const unknown = value.state === 'running' && (!actual || actual.createdAt !== value.process?.createdAt);
return { ...value, state: unknown ? 'unknown' : value.state, interrupted: unknown, progressFile: path.join(stateRoot, name) };
}).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, 5) : [];
return { installed: true, activeVersion: pointer.active.version, previousVersion: pointer.previous?.version ?? null, revision: pointer.revision, installRoot, operations };
}