docs: seal 1.24.3 model selection acceptance and formal retention

This commit is contained in:
Agent Workbench Dev
2026-11-03 15:37:04 +08:00
parent f53eebb717
commit cd5af2eb7b
755 changed files with 239373 additions and 4 deletions
@@ -0,0 +1,86 @@
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Web.Script.Serialization;
using System.Windows.Forms;
// A fixed, user-level bootstrap. The independent Node host retains task state;
// this program only validates an immutable release and starts its desktop client.
internal static class Launcher {
static bool hidden;
static string Full(string value) { return Path.GetFullPath(value).TrimEnd(Path.DirectorySeparatorChar); }
static bool Same(string a, string b) { return String.Equals(Full(a), Full(b), StringComparison.OrdinalIgnoreCase); }
static bool Inside(string root, string file) { return Full(file).StartsWith(Full(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); }
static void Local(string file) {
string full = Full(file), current = Path.GetPathRoot(full);
if (current.StartsWith("\\\\")) throw new Exception("程序需要本机目录。");
foreach (string part in full.Substring(current.Length).Split(Path.DirectorySeparatorChar)) {
if (part.IndexOf(':') >= 0) throw new Exception("路径包含无效文件名。");
current = Path.Combine(current, part);
if ((File.Exists(current) || Directory.Exists(current)) && (File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0) throw new Exception("程序路径不能使用链接或重解析目录。");
}
}
static Dictionary<string, object> Json(string file) {
Local(file); if (new FileInfo(file).Length > 16 * 1024 * 1024) throw new Exception("安装清单过大。");
JavaScriptSerializer reader = new JavaScriptSerializer(); reader.MaxJsonLength = 16 * 1024 * 1024;
return reader.Deserialize<Dictionary<string, object>>(File.ReadAllText(file, Encoding.UTF8));
}
static string Str(Dictionary<string, object> value, string key) { object result; if (!value.TryGetValue(key, out result) || !(result is string)) throw new Exception("安装登记缺少 " + key); return (string)result; }
static string Hash(string file) { Local(file); using (SHA256 hash = SHA256.Create()) using (FileStream input = File.OpenRead(file)) return BitConverter.ToString(hash.ComputeHash(input)).Replace("-", "").ToLowerInvariant(); }
static string Quote(string value) { if (value.IndexOf('"') >= 0 || value.EndsWith("\\")) throw new Exception("启动参数无效。"); return "\"" + value + "\""; }
static void Verify(string root, string expected, string version) {
string file = Path.Combine(root, "MANIFEST.json"); Dictionary<string, object> manifest = Json(file);
if (Str(manifest, "app") != "agent-workbench" || Str(manifest, "kind") != "portable" || Str(manifest, "platform") != "win32-x64") throw new Exception("需要完整 Windows 桌面发行。");
if (version != null && Str(manifest, "version") != version) throw new Exception("安装版本登记不一致。");
if (expected != null && Hash(file) != expected) throw new Exception("原安装清单发生变化。");
HashSet<string> declared = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (object item in (IEnumerable)manifest["files"]) {
Dictionary<string, object> row = (Dictionary<string, object>)item; string relative = Str(row, "path");
if (relative.IndexOf('\\') >= 0 || relative.IndexOf(':') >= 0 || relative.StartsWith("/") || Array.IndexOf(relative.Split('/'), "..") >= 0 || !declared.Add(relative) || declared.Count > 60000) throw new Exception("清单包含重复或越界文件。");
string source = Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar));
if (!Inside(root, source) || !File.Exists(source) || new FileInfo(source).Length != Convert.ToInt64(row["bytes"]) || Hash(source) != Str(row, "sha256")) throw new Exception("发行文件与原清单不同:" + relative);
}
foreach (string required in new string[] { "runtime/node.exe", "desktop/AgentWorkbench.exe", "dist-server/server.mjs", "dist-server/install-manager.mjs", "dist-desktop/main.cjs", "dist-desktop/preload.cjs" }) if (!declared.Contains(required)) throw new Exception("桌面发行缺少 " + required);
string[] actual = Directory.GetFiles(root, "*", SearchOption.AllDirectories);
if (actual.Length != declared.Count + 1) throw new Exception("发行目录包含未登记文件。");
foreach (string value in actual) { Local(value); string relative = Full(value).Substring(Full(root).Length + 1).Replace('\\', '/'); if (relative != "MANIFEST.json" && !declared.Contains(relative)) throw new Exception("发行目录包含未登记文件。"); }
}
[STAThread] static int Main(string[] args) {
try {
string root = Full(Path.GetDirectoryName(Application.ExecutablePath)), data = Full(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "AgentWorkbench")); int port = 4318;
string selectedData = null; int? selectedPort = null; bool uninstall = false;
for (int i = 0; i < args.Length; i++) {
if (args[i] == "--hidden-window" && !hidden) { hidden = true; continue; }
if (args[i] == "--uninstall-preflight" && !uninstall) { uninstall = true; continue; }
if (args[i] == "--data-root" && selectedData == null && ++i < args.Length) { selectedData = Full(args[i]); continue; }
if (args[i] == "--port" && !selectedPort.HasValue && ++i < args.Length) { selectedPort = Int32.Parse(args[i]); continue; }
throw new Exception("不支持的桌面启动参数。");
}
string recordFile = Path.Combine(root, "current.json"), expected = null, version = null, release = root;
if (File.Exists(recordFile)) {
Dictionary<string, object> record = Json(recordFile), active = (Dictionary<string, object>)record["active"];
if (Convert.ToInt32(record["schema"]) != 1 || Str(record, "app") != "agent-workbench-installation" || !Regex.IsMatch(Str(record, "installId"), "^[a-f0-9-]{36}$") || Convert.ToInt64(record["revision"]) < 1) throw new Exception("安装登记无效。");
string directory = Str(active, "directory"); if (!Regex.IsMatch(directory, "^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$")) throw new Exception("活动版本目录无效。");
release = Full(Path.Combine(root, "versions", directory)); if (!Inside(Path.Combine(root, "versions"), release)) throw new Exception("活动版本越界。");
expected = Str(active, "manifestSha256"); version = Str(active, "version");
if (!Regex.IsMatch(expected, "^[a-f0-9]{64}$") || !Regex.IsMatch(Str(active, "runtimeIdentity"), "^[a-f0-9]{64}$") || !Regex.IsMatch(version, "^\\d+\\.\\d+\\.\\d+$")) throw new Exception("原版本身份无效。");
data = Full(Str(record, "dataRoot")); port = Convert.ToInt32(record["port"]);
if ((selectedData != null && !Same(selectedData, data)) || (selectedPort.HasValue && selectedPort.Value != port)) throw new Exception("已安装应用使用登记的数据目录及端口。");
} else { if (uninstall) throw new Exception("没有可核对的安装登记。"); if (selectedData != null) data = selectedData; if (selectedPort.HasValue) port = selectedPort.Value; }
if (port < 1 || port > 65535 || Same(root, data) || Inside(root, data) || Inside(data, root)) throw new Exception("程序与用户数据需要独立目录及有效端口。");
Local(root); Local(data); Local(release); Verify(release, expected, version);
ProcessStartInfo launch = new ProcessStartInfo(uninstall ? Path.Combine(release, "runtime", "node.exe") : Path.Combine(release, "desktop", "AgentWorkbench.exe"));
launch.Arguments = uninstall ? Quote(Path.Combine(release, "dist-server", "install-manager.mjs")) + " uninstall --install-root " + Quote(root) + " --data-root " + Quote(data) + " --port " + port : "--app-root " + Quote(release) + " --data-root " + Quote(data) + " --port " + port + (hidden ? " --hidden-window" : "");
launch.WorkingDirectory = release; launch.UseShellExecute = false; launch.CreateNoWindow = true;
List<string> keys = new List<string>(); foreach (string key in launch.EnvironmentVariables.Keys) keys.Add(key);
Regex allowed = new Regex("^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|homedrive|homepath|appdata|localappdata|programfiles(?:\\(x86\\))?|commonprogramfiles(?:\\(x86\\))?|lang|lc_all|AGENT_WORKBENCH_(?:DEEPSEEK_ROOT|PURGE_ROOT|PYTHON_PATH|TEST_PYTHON))$", RegexOptions.IgnoreCase);
foreach (string key in keys) if (!allowed.IsMatch(key)) launch.EnvironmentVariables.Remove(key);
using (Process child = Process.Start(launch)) { if (uninstall) { child.WaitForExit(); return child.ExitCode; } } return 0;
} catch (Exception error) { if (!hidden) MessageBox.Show(error.Message, "Agent Workbench 无法打开", MessageBoxButtons.OK, MessageBoxIcon.Error); return 1; }
}
}
@@ -0,0 +1,197 @@
import { WebContentsView, session } from 'electron';
import { lookup } from 'node:dns/promises';
import { isIP } from 'node:net';
import { assertDesktopFrame } from '../shared/contracts/desktop-bridge.mjs';
import { browsingUrl } from '../shared/contracts/browsing.mjs';
// This function runs only in an isolated page world. No renderer-supplied JS,
// selectors, CDP methods or Node APIs cross this boundary.
function pageOperation(operation, input) {
const visible = element => { const style = getComputedStyle(element), rect = element.getBoundingClientRect(); return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden'; };
let state = globalThis.__awbPageObservation;
if (!state || state.document !== document) {
state = { document, epoch: crypto.randomUUID(), revision: 0, elements: new Map() };
state.observer = new MutationObserver(() => state.revision++);
state.observer.observe(document, { subtree: true, attributes: true, childList: true, characterData: true });
globalThis.__awbPageObservation = state;
}
if (state.observer.takeRecords().length) state.revision++;
const revision = () => state.epoch + ':' + state.revision;
if (operation === 'revision') return { revision: revision(), url: location.href };
if (operation === 'act') {
if (revision() !== input.revision) return { stale: true, reason: '页面在原观察后变化,请重新观察。' };
if (input.action === 'scroll') { scrollBy(0, input.amount); return { performed: true }; }
if (!['click','fill'].includes(input.action)) return { performed: false };
const element = state.elements.get(input.ref);
if (!element || !element.isConnected || !visible(element) || element.disabled) return { stale: true, reason: '原可见控件已失效。' };
if (input.action === 'click') { element.click(); return { performed: true }; }
if (!(element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) || element.readOnly
|| element instanceof HTMLInputElement && !['text','search','email','tel','url','number'].includes(element.type)) return { stale: true, reason: '只支持普通文本字段,密码、文件和受限控件不通过代理输入。' };
const prototype = element instanceof HTMLInputElement ? HTMLInputElement.prototype : HTMLTextAreaElement.prototype;
Object.getOwnPropertyDescriptor(prototype, 'value').set.call(element, input.value);
element.dispatchEvent(new Event('input', { bubbles: true })); element.dispatchEvent(new Event('change', { bubbles: true })); return { performed: true };
}
state.elements.clear();
const candidates = document.querySelectorAll('a[href],button,input,textarea,select,[role="button"],[role="link"]'), controls = []; let visited = 0;
for (const element of candidates) {
if (++visited > 6000 || controls.length === 120) break;
if (!visible(element) || element.type === 'hidden') continue;
const ref = 'e' + (controls.length + 1); state.elements.set(ref, element);
const label = element.labels?.[0]?.innerText || element.getAttribute('aria-label') || element.innerText || element.getAttribute('placeholder') || element.getAttribute('name') || element.tagName;
controls.push({ ref, tag: element.tagName.toLowerCase(), type: element.type || '', label: label.slice(0, 180), disabled: !!element.disabled,
...(element instanceof HTMLAnchorElement ? { href: element.href.slice(0, 2000) } : {}),
...(element instanceof HTMLInputElement && ['password','file'].includes(element.type) ? { restricted: true } : {}) });
}
const text = document.body?.innerText ?? '';
return { revision: revision(), url: location.href, title: document.title.slice(0, 300), text: text.slice(0, 16000), controls,
scope: { textCharacters: text.length, controlsSeen: candidates.length, complete: text.length <= 16000 && candidates.length <= 6000 && controls.length < 120 }, sampledAt: new Date().toISOString() };
}
const publicAddress = address => {
if (isIP(address) === 4) { const [a,b] = address.split('.').map(Number); return !(a === 0 || a === 10 || a === 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a >= 224 || a === 100 && b >= 64 && b <= 127); }
return isIP(address) === 6 && !/^(::|fe[89ab]|f[cd]|::ffff:)/i.test(address);
};
export class BrowsingView {
constructor({ window, controller, windowOwner }) {
Object.assign(this, { window, controller, windowOwner }); this.views = new Map(); this.partitions = new Map(); this.current = null; this.disposed = false;
for (const event of ['minimize','resize','blur']) window.on(event, () => this.hide());
window.webContents.on('did-start-loading', () => this.hide());
void this.loop();
}
async loop() {
while (!this.disposed && !this.window.isDestroyed()) {
try {
const states = [...this.views.values()].map(value => ({ id: value.tab.id, url: value.view.webContents.getURL(), title: value.view.webContents.getTitle() }));
const next = await this.controller.api('/browsing-desktop/poll', { method: 'POST', input: { owner: this.windowOwner, states } });
for (const [id] of this.views) if (!next.retainedTabs.includes(id) && !next.commands.some(command => command.tab.id === id && ['close','clear'].includes(command.kind))) this.destroy(id);
for (const command of next.commands) {
if (this.disposed) break;
let reply;
try {
await this.controller.api('/browsing-desktop/validate', { method: 'POST', input: { owner: this.windowOwner, id: command.id, nonce: command.nonce } });
reply = { result: await this.execute(command) };
} catch (error) { reply = { error: error.message, uncertain: command.kind === 'act' && error.noEffect !== true }; }
await this.controller.api('/browsing-desktop/complete', { method: 'POST', input: { owner: this.windowOwner, id: command.id, nonce: command.nonce, ...reply }, timeoutMs: 15000 });
}
} catch { this.hide(); }
await new Promise(resolve => setTimeout(resolve, 350));
}
}
policy(tab, value) { return browsingUrl(value, { ...tab.scope, workbenchOrigin: this.controller.url }); }
async permitted(tab, value) {
if (value === 'about:blank') return false;
// Vite HMR uses a WebSocket on the same explicitly owned origin.
try { const resource = new URL(value); if (resource.protocol === 'ws:' || resource.protocol === 'wss:') { resource.protocol = resource.protocol === 'ws:' ? 'http:' : 'https:'; value = resource.href; } } catch { return false; }
let url; try { url = this.policy(tab, value); } catch { return false; }
if (url.origin === tab.previewOrigin || tab.scope.allowHttpLoopback && url.hostname === '127.0.0.1') return true;
try { const addresses = await lookup(url.hostname, { all: true }); return addresses.length > 0 && addresses.every(item => publicAddress(item.address)); } catch { return false; }
}
async create(tab) {
if (this.views.has(tab.id)) throw new Error('原标签页已打开,不能重放打开。');
let partition = this.partitions.get(tab.profileId);
if (!partition) {
const partitionName = (tab.persistent ? 'persist:' : '') + 'awb-browsing-' + tab.profileId;
partition = session.fromPartition(partitionName, { cache: true }); await partition.setProxy({ mode: 'direct' });
partition.setPermissionRequestHandler((_contents, _permission, callback) => callback(false)); partition.setPermissionCheckHandler(() => false);
partition.on('will-download', (event, item) => { event.preventDefault(); item.cancel(); });
partition.webRequest.onBeforeRequest((details, callback) => {
// All users of one profile have exactly the same authorized origins.
void this.permitted(tab, details.url).then(allowed => callback({ cancel: !allowed }), () => callback({ cancel: true }));
});
this.partitions.set(tab.profileId, partition);
}
const view = new WebContentsView({ webPreferences: { session: partition, sandbox: true, contextIsolation: true, nodeIntegration: false,
webSecurity: true, allowRunningInsecureContent: false, navigateOnDragDrop: false, spellcheck: false, backgroundThrottling: false } });
const value = { tab, view, history: [], historyIndex: -1, historyTarget: null }; this.views.set(tab.id, value); view.setBounds({ x: 0, y: 0, width: 800, height: 600 }); view.setVisible(false);
this.window.contentView.addChildView(view);
const contents = view.webContents; contents.setWindowOpenHandler(() => ({ action: 'deny' }));
for (const name of ['did-navigate','did-navigate-in-page']) contents.on(name, () => this.recordNavigation(value));
contents.on('will-attach-webview', event => event.preventDefault());
for (const name of ['will-navigate','will-frame-navigate','will-redirect']) contents.on(name, (event, url) => {
try { this.policy(tab, typeof url === 'string' ? url : event.url); } catch { event.preventDefault(); }
});
contents.on('render-process-gone', () => { this.hide(); this.destroy(tab.id); });
return value;
}
async script(contents, operation, input = {}) {
return contents.executeJavaScriptInIsolatedWorld(999, [{ code: '(' + pageOperation.toString() + ')(' + JSON.stringify(operation) + ',' + JSON.stringify(input) + ')' }]);
}
async load(contents, url) {
let timer; try { await Promise.race([contents.loadURL(url), new Promise((_,reject) => { timer = setTimeout(() => { contents.stop(); reject(new Error('所属页面加载超过15秒,请核对原网址和请求。')); },15000); })]); }
finally { clearTimeout(timer); }
}
async observe(value) {
const contents = value.view.webContents;
this.recordNavigation(value);
const observation = await this.script(contents, 'observe'); this.policy(value.tab, observation.url);
const png = (await contents.capturePage()).toPNG(); if (png.length > 6 * 1024 * 1024) throw new Error('页面截图超过6MiB上限,请缩小浏览区。');
const after = await this.script(contents, 'revision');
if (after.revision !== observation.revision || after.url !== observation.url) throw Object.assign(new Error('页面在观察/截图期间变化,请重新观察。'), { noEffect: true });
observation.navigation = { mode: 'owned-url-history', canGoBack: value.historyIndex > 0, canGoForward: value.historyIndex < value.history.length - 1 };
return { observation, png: png.toString('base64') };
}
recordNavigation(value) {
const url = value.view.webContents.getURL(); if (!url || url === 'about:blank') return;
this.policy(value.tab,url);
if (value.historyTarget !== null) { value.historyIndex = value.historyTarget; value.history[value.historyTarget] = url; return; }
if (value.history[value.historyIndex] === url) return;
value.history.splice(value.historyIndex + 1); value.history.push(url); if (value.history.length > 100) value.history.shift(); value.historyIndex = value.history.length - 1;
}
async execute(command) {
const { tab, kind, input } = command;
if (kind === 'clear') {
for (const [id, value] of this.views) if (value.tab.profileId === tab.profileId) this.destroy(id);
let partition = this.partitions.get(tab.profileId);
if (!partition) partition = session.fromPartition((tab.persistent ? 'persist:' : '') + 'awb-browsing-' + tab.profileId);
await partition.clearStorageData(); await partition.clearCache(); this.partitions.delete(tab.profileId); return { cleared: true };
}
if (kind === 'close') { this.destroy(tab.id); if (!tab.persistent) { const partition = this.partitions.get(tab.profileId); if (partition) { await partition.clearStorageData(); await partition.clearCache(); this.partitions.delete(tab.profileId); } } return { closed: true }; }
let value = this.views.get(tab.id);
if (kind === 'open') { this.policy(tab, input.url); value = await this.create(tab); await this.load(value.view.webContents,input.url); return this.observe(value); }
if (!value || value.view.webContents.isDestroyed()) throw Object.assign(new Error('原桌面标签页已结束,请明确打开新页面。'), { noEffect: true });
if (value.tab.grantRevision !== tab.grantRevision) throw Object.assign(new Error('原授权已变化。'), { noEffect: true });
if (kind === 'observe') return this.observe(value);
const contents = value.view.webContents, current = await this.script(contents, 'revision');
if (current.revision !== input.revision || current.url !== tab.url) throw Object.assign(new Error('页面在原观察后变化,请重新观察。'), { noEffect: true });
if (['click','fill','scroll'].includes(input.action)) {
const result = await this.script(contents, 'act', input); if (result.stale) throw Object.assign(new Error(result.reason), { noEffect: true });
} else if (input.action === 'navigate') { this.policy(tab, input.url); await this.load(contents,input.url); }
else if (input.action === 'reload') { await this.load(contents,current.url); }
else if (['back','forward'].includes(input.action)) {
const target = value.historyIndex + (input.action === 'back' ? -1 : 1);
if (target < 0 || target >= value.history.length) throw Object.assign(new Error('没有对应的页面历史。'), { noEffect: true });
const url = value.history[target]; this.policy(tab,url); value.historyTarget = target;
try { await this.load(contents,url); } finally { value.historyTarget = null; }
} else if (input.action === 'wait') await new Promise(resolve => setTimeout(resolve, input.milliseconds));
else if (input.action === 'download') {
this.policy(tab, input.url);
const response = await contents.session.fetch(input.url, { redirect: 'error', signal: AbortSignal.timeout(10000) });
if (!response.ok) throw new Error('下载返回HTTP ' + response.status);
let length = 0; const chunks = []; for await (const chunk of response.body) { length += chunk.length; if (length > 6 * 1024 * 1024) throw new Error('下载超过6MiB上限。'); chunks.push(Buffer.from(chunk)); }
return { download: { url: input.url, bytes: Buffer.concat(chunks).toString('base64'), mediaType: response.headers.get('content-type') } };
}
// Let navigation and framework input handlers finish a bounded turn. This
// is observation after one action, never an automatic second action.
await new Promise(resolve => setTimeout(resolve, 150));
return this.observe(value);
}
layout(event, input) {
assertDesktopFrame(event, this.window, this.controller.url);
const reject = message => { this.hide(); throw new Error(message); };
const fields = ['projectId','sessionId','taskId','tabId','bounds','visible'];
if (!input || Array.isArray(input) || Object.keys(input).some(key => !fields.includes(key)) || typeof input.visible !== 'boolean') reject('浏览区域字段无效。');
if (!input.visible) { this.hide(); return { visible: false }; }
const value = this.views.get(input.tabId), zoom = this.window.webContents.getZoomFactor(), available = this.window.getContentBounds();
const bounds = input.bounds && Object.fromEntries(Object.entries(input.bounds).map(([key,value]) => [key, Math.round(value * zoom)]));
if (!value || value.tab.projectId !== input.projectId || value.tab.sessionId !== input.sessionId || value.tab.taskId !== input.taskId) reject('原浏览区域归属已变化。');
if (!bounds || Object.keys(bounds).sort().join() !== 'height,width,x,y' || Object.values(bounds).some(number => !Number.isSafeInteger(number))
|| bounds.x < 0 || bounds.y < 0 || bounds.width < 80 || bounds.height < 80 || bounds.x + bounds.width > available.width + 1 || bounds.y + bounds.height > available.height + 1) reject('原生浏览区域超过当前窗口。');
if (this.window.isMinimized() || !this.window.isVisible()) { this.hide(); return { visible: false }; }
if (this.current !== input.tabId) { this.hide(); this.window.contentView.addChildView(value.view); this.current = input.tabId; }
value.view.setBounds(bounds); value.view.setVisible(true); return { visible: true };
}
hide() { if (this.current) { const value = this.views.get(this.current); if (value) { value.view.setVisible(false); this.window.contentView.removeChildView(value.view); } this.current = null; } }
destroy(id) { if (this.current === id) this.hide(); const value = this.views.get(id); this.views.delete(id); if (value) { this.window.contentView.removeChildView(value.view); if (!value.view.webContents.isDestroyed()) value.view.webContents.close(); } }
dispose() { this.disposed = true; this.hide(); for (const id of [...this.views.keys()]) this.destroy(id); }
}
@@ -0,0 +1,24 @@
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { fileURLToPath } from 'node:url';
import { HostController, HOST_ENVIRONMENT } from '../core/desktop/host-controller.mjs';
const args = process.argv.slice(2);
if (args.includes('--help')) { console.log('node host-launcher.mjs <start|status|stop> [--app-root <absolute>] [--data-root <absolute>] [--node <absolute>] [--port <1..65535>]'); process.exit(0); }
const command = args.shift(); if (!['start', 'status', 'stop'].includes(command)) throw new Error('Use --help for a supported desktop host operation.');
const options = {};
while (args.length) {
const flag = args.shift(), value = args.shift();
if (!['--app-root', '--data-root', '--node', '--port'].includes(flag) || !value || options[flag] !== undefined) throw new Error('Invalid or repeated host option.');
options[flag] = value;
}
const defaultRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const appRoot = options['--app-root'] || process.env.AGENT_WORKBENCH_APP_DIR || defaultRoot;
const dataRoot = options['--data-root'] || process.env.AGENT_WORKBENCH_DATA_DIR || path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), '.local/share'), 'AgentWorkbench');
const nodePath = options['--node'] || (fs.existsSync(path.join(appRoot, 'runtime/node.exe')) ? path.join(appRoot, 'runtime/node.exe') : process.execPath);
try {
const controller = new HostController({ appRoot, dataRoot, nodePath, port: Number(options['--port'] || process.env.AGENT_WORKBENCH_PORT || 4318),
environment: Object.fromEntries(HOST_ENVIRONMENT.filter(key => process.env[key]).map(key => [key, process.env[key]])) });
console.log(JSON.stringify(await controller[command]()));
} catch (cause) { console.error(JSON.stringify({ success: false, code: cause.code || 'HOST_FAILED', message: cause.message })); process.exitCode = 1; }
@@ -0,0 +1,19 @@
import { InstallationManager } from '../core/desktop/install-manager.mjs';
const args = process.argv.slice(2), command = args.shift(), options = {};
if (!['preflight', 'activate', 'uninstall', 'cancel'].includes(command)) throw new Error('Unsupported installation operation.');
while (args.length) {
const flag = args.shift();
if (flag === '--stage-only' && !options.stageOnly) { options.stageOnly = true; continue; }
if (!['--install-root', '--data-root', '--candidate-root', '--port', '--operation-id', '--expected-manifest-sha256'].includes(flag) || !args.length || options[flag] !== undefined) throw new Error('Unsupported or repeated installation field.');
options[flag] = args.shift();
}
try {
const manager = new InstallationManager({ installRoot: options['--install-root'], dataRoot: options['--data-root'], candidateRoot: options['--candidate-root'], port: Number(options['--port'] || 4318), operationId: options['--operation-id'] ?? null, expectedManifestSha256: options['--expected-manifest-sha256'] ?? null,
onProgress: value => {
const counts = value.counts;
console.log('AWBPROGRESS ' + (value.label + (counts ? ` · ${counts.completedFiles}/${counts.totalFiles} 文件` + (counts.completedBytes !== null ? ` · ${counts.completedBytes}/${counts.totalBytes} 字节` : '') + (counts.currentPath ? ' · ' + counts.currentPath : '') : '')).replace(/[\r\n]/g, ' '));
console.log('AWBFILES ' + (counts ? counts.completedFiles + '/' + counts.totalFiles : '-'));
} });
const result = command === 'preflight' ? await manager.preflight({ stageOnly: !!options.stageOnly }) : command === 'activate' ? await manager.activate({ stageOnly: !!options.stageOnly }) : command === 'cancel' ? await manager.cancelPreparation() : await manager.prepareUninstall();
console.log(JSON.stringify(result));
} catch (error) { console.error('AWBERROR ' + error.message); console.error(JSON.stringify({ success: false, code: error.code || 'INSTALLATION_FAILED', message: error.message })); process.exitCode = 1; }
@@ -0,0 +1,138 @@
[Setup]
AppId={{E914E883-46F9-4B82-B27F-BDB2B40DCC90}
AppName=Agent Workbench
AppVersion={#Version}
DefaultDirName={localappdata}\Programs\AgentWorkbench
DefaultGroupName=Agent Workbench
PrivilegesRequired=lowest
ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
DisableProgramGroupPage=yes
UsePreviousAppDir=yes
OutputDir={#OutputRoot}
OutputBaseFilename={#OutputName}
SetupIconFile={#PortableRoot}\public\workbench-icon.ico
UninstallDisplayIcon={app}\AgentWorkbench.exe
Compression=lzma2/fast
SolidCompression=yes
CloseApplications=no
RestartApplications=no
ChangesAssociations=no
WizardStyle=modern
Uninstallable=yes
[Files]
Source: "{#PortableRoot}\runtime\node.exe"; DestName: "awb-install-node.exe"; Flags: dontcopy
Source: "{#PortableRoot}\dist-server\install-manager.mjs"; DestName: "awb-install-manager.mjs"; Flags: dontcopy
Source: "{#PortableRoot}\*"; DestDir: "{app}\versions\{#VersionDirectory}"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "{#PortableRoot}\AgentWorkbench.exe"; DestDir: "{app}"; Flags: onlyifdoesntexist
[Icons]
Name: "{group}\Agent Workbench"; Filename: "{app}\AgentWorkbench.exe"
Name: "{userdesktop}\Agent Workbench"; Filename: "{app}\AgentWorkbench.exe"; Tasks: desktopicon
[Tasks]
Name: "desktopicon"; Description: "创建桌面快捷方式"; Flags: unchecked
[Run]
Filename: "{app}\AgentWorkbench.exe"; Description: "打开 Agent Workbench"; Flags: nowait postinstall skipifsilent; Check: WasActivated
[Code]
var DataRoot: String; Port: String; StageOnly: Boolean; Activated: Boolean; ActivationFailed: Boolean;
OperationId: String; LastManagerError: String; PreflightPassed: Boolean; ManagerFinished: Boolean;
ManagerPage: TOutputProgressWizardPage;
function Quoted(Value: String): String;
begin
if (Pos('"', Value) > 0) or (Pos(#13, Value) > 0) or (Pos(#10, Value) > 0) then RaiseException('安装路径无效。');
Result := '"' + Value + '"';
end;
procedure LoadOptions;
begin
DataRoot := ExpandConstant('{param:DATA_ROOT|{localappdata}\AgentWorkbench}');
Port := ExpandConstant('{param:PORT|4318}');
StageOnly := ExpandConstant('{param:STAGE_ONLY|0}') = '1';
OperationId := GetSHA256OfString(ExpandConstant('{tmp}') + GetDateTimeString('yyyy-mm-dd hh:nn:ss', '-', ':'));
end;
procedure ManagerLog(const S: String; const Error, FirstLine: Boolean);
var Value: String; Separator: Integer;
begin
Log(S);
if Error and (LastManagerError = '') then LastManagerError := S;
if Pos('AWBERROR ', S) = 1 then LastManagerError := Copy(S, 10, Length(S));
if Pos('AWBPROGRESS ', S) = 1 then ManagerPage.SetText(Copy(S, 13, Length(S)), '正在核对实际文件和原状态;阶段变化来自安装进程。请保持此窗口打开。');
if Pos('AWBFILES ', S) = 1 then begin
Value := Copy(S, 10, Length(S)); Separator := Pos('/', Value);
ManagerPage.ProgressBar.Visible := Separator > 0;
if Separator > 0 then ManagerPage.SetProgress(StrToIntDef(Copy(Value, 1, Separator - 1), 0), StrToIntDef(Copy(Value, Separator + 1, Length(Value)), 1));
end;
end;
function RunManager(Command: String; Candidate: Boolean): Boolean;
var Parameters: String; ExitCode: Integer;
begin
LastManagerError := '';
Parameters := Quoted(ExpandConstant('{tmp}\awb-install-manager.mjs')) + ' ' + Command +
' --install-root ' + Quoted(ExpandConstant('{app}')) + ' --data-root ' + Quoted(DataRoot) + ' --port ' + Quoted(Port) +
' --operation-id ' + Quoted(OperationId) + ' --expected-manifest-sha256 {#ManifestSha256}';
if Candidate then Parameters := Parameters + ' --candidate-root ' + Quoted(ExpandConstant('{app}\versions\{#VersionDirectory}'));
if StageOnly then Parameters := Parameters + ' --stage-only';
if ManagerPage = nil then ManagerPage := CreateOutputProgressPage('Agent Workbench 版本更新', '核对原版本、当前阶段与实际结果');
ManagerPage.SetText('准备核对安装操作', '操作记录:' + ExpandConstant('{app}') + '\.installation\progress-' + OperationId + '.json');
ManagerPage.ProgressBar.Visible := False;
if Command <> 'cancel' then ManagerPage.Show;
WizardForm.CancelButton.Enabled := False;
try
Result := ExecAndLogOutput(ExpandConstant('{tmp}\awb-install-node.exe'), Parameters, ExpandConstant('{tmp}'), SW_HIDE, ewWaitUntilTerminated, ExitCode, @ManagerLog) and (ExitCode = 0);
if not Result and (LastManagerError = '') then LastManagerError := '安装进程未返回成功结果;请保留安装日志及原操作收据。';
finally
WizardForm.CancelButton.Enabled := True;
if Command <> 'cancel' then ManagerPage.Hide;
end;
end;
function PrepareToInstall(var NeedsRestart: Boolean): String;
begin
LoadOptions;
ExtractTemporaryFile('awb-install-node.exe'); ExtractTemporaryFile('awb-install-manager.mjs');
if DirExists(ExpandConstant('{app}\versions\{#VersionDirectory}')) then begin
Result := '该独立版本目录已经存在。请保留原版本,使用新的安装候选。'; exit;
end;
PreflightPassed := RunManager('preflight', False);
if not PreflightPassed then Result := '安装预检未通过:' + LastManagerError + #13#10 + '原程序和用户数据保留。日志及阶段记录见 .installation 目录。';
end;
procedure CurStepChanged(CurStep: TSetupStep);
begin
if CurStep = ssPostInstall then begin
ActivationFailed := True;
if not RunManager('activate', True) then RaiseException('候选激活未完成:' + LastManagerError + #13#10 + '请保留 .installation 原操作收据,核对当前指针和回退结果。');
ActivationFailed := False;
Activated := not StageOnly;
ManagerFinished := True;
end;
end;
procedure DeinitializeSetup;
begin
if PreflightPassed and not ManagerFinished and not ActivationFailed then RunManager('cancel', False);
end;
function GetCustomSetupExitCode: Integer;
begin
if ActivationFailed then Result := 8 else Result := 0;
end;
function WasActivated: Boolean;
begin Result := Activated; end;
function InitializeUninstall: Boolean;
var ExitCode: Integer;
begin
{ The native bootstrap verifies the entire registered immutable release before
invoking its fixed uninstall manager. No installed script is executed first. }
Result := Exec(ExpandConstant('{app}\AgentWorkbench.exe'), '--hidden-window --uninstall-preflight', ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, ExitCode) and (ExitCode = 0);
if not Result then MsgBox('卸载预检未通过。请先关闭桌面窗口并等待活动结束;原程序和用户数据保留。', mbError, MB_OK);
end;
@@ -0,0 +1,75 @@
import { app, BrowserWindow, ipcMain, dialog, shell, Menu } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { randomUUID } from 'node:crypto';
import { HostController, HOST_ENVIRONMENT } from '../core/desktop/host-controller.mjs';
import { DesktopBridge } from '../core/desktop/desktop-bridge.mjs';
import { ownedChild, assertLocalTree, samePath } from '../core/desktop/file-state.mjs';
import { observeWindowsProcess, protectUserDirectory } from '../core/desktop/process-identity.mjs';
import { DESKTOP_CHANNELS, desktopOrigin } from '../shared/contracts/desktop-bridge.mjs';
import { desktopLaunchOptions } from '../core/desktop/launch-options.mjs';
import { BrowsingView } from './browsing-view.mjs';
import { localPreviewAddress } from '../core/preview/local-file-preview.mjs';
const options = desktopLaunchOptions(process.argv, { defaultApp: process.defaultApp, mainFile: __filename });
const appRoot = path.resolve(options['--app-root'] || (app.isPackaged ? path.resolve(path.dirname(process.execPath), '..') : path.resolve(__dirname, '..')));
const dataRoot = path.resolve(options['--data-root'] || path.join(process.env.LOCALAPPDATA || os.homedir(), 'AgentWorkbench'));
const port = Number(options['--port'] || 4318);
assertLocalTree(dataRoot, { missing: true }); fs.mkdirSync(dataRoot, { recursive: true });
const profile = ownedChild(dataRoot, '.desktop-profile', { missing: true }); fs.mkdirSync(profile, { recursive: true }); protectUserDirectory(profile); app.setPath('userData', profile);
app.setAppUserModelId('local.agent-workbench'); app.setName('Agent Workbench');
let window, controller, bridge, browsingView, windowId, windowOwner, quitting = false;
const retained = app.requestSingleInstanceLock({ appRoot, dataRoot, port });
if (!retained) app.quit();
else {
app.on('second-instance', (_event, _argv, _directory, incoming) => {
if (!samePath(incoming?.appRoot ?? '', appRoot) || !samePath(incoming?.dataRoot ?? '', dataRoot) || incoming?.port !== port) return;
if (window && !window.isDestroyed()) { if (window.isMinimized()) window.restore(); window.show(); window.focus(); }
});
app.on('window-all-closed', () => app.quit()); // Node owns execution, independent of Electron.
app.on('before-quit', event => {
if (quitting || !controller || !windowOwner) return;
event.preventDefault(); quitting = true;
browsingView?.dispose();
void controller.api('/host/windows/unregister', { method: 'POST', input: windowOwner, timeoutMs: 5000 }).catch(() => {}).finally(() => app.quit());
});
app.whenReady().then(async () => {
controller = new HostController({ appRoot, dataRoot, port, nodePath: options['--node'],
environment: Object.fromEntries(HOST_ENVIRONMENT.filter(key => process.env[key]).map(key => [key, process.env[key]])) });
const host = await controller.start(), observed = observeWindowsProcess(process.pid);
windowId = randomUUID(); windowOwner = { windowId, pid: process.pid, createdAt: observed.createdAt, instanceId: host.identity.instanceId, runtimeIdentity: host.identity.runtimeIdentity };
await controller.api('/host/windows/register', { method: 'POST', input: windowOwner });
const preload = path.join(appRoot, 'dist-desktop/preload.cjs');
window = new BrowserWindow({ title: 'Agent Workbench', width: 1440, height: 1000, minWidth: 390, minHeight: 600,
show: false, backgroundColor: '#edf2f7', icon: path.join(appRoot, 'public/workbench-icon.png'),
webPreferences: { preload, sandbox: true, contextIsolation: true, nodeIntegration: false, webSecurity: true, allowRunningInsecureContent: false } });
window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
window.webContents.on('will-navigate', details => { if (!desktopOrigin(details.url, controller.url)) details.preventDefault(); });
window.webContents.on('will-frame-navigate', details => { if (!desktopOrigin(details.url, controller.url) && !(details.isMainFrame === false && localPreviewAddress(details.url))) details.preventDefault(); });
window.webContents.on('will-attach-webview', event => event.preventDefault());
const session = window.webContents.session;
session.setPermissionRequestHandler((_contents, _permission, callback) => callback(false));
session.setPermissionCheckHandler(() => false);
session.webRequest.onBeforeRequest((details, callback) => {
const permitted = desktopOrigin(details.url, controller.url) || details.url.startsWith('data:image/') || details.url.startsWith('blob:' + controller.url + '/');
if (permitted) return callback({ cancel: false });
if (!localPreviewAddress(details.url) || details.resourceType === 'mainFrame') return callback({ cancel: true });
void controller.api('/local-file-preview-access?url=' + encodeURIComponent(details.url)).then(access => callback({ cancel: !access.allowed })).catch(() => callback({ cancel: true }));
});
bridge = new DesktopBridge(controller, { dialog, shell, getWindow: () => window, onStopped: () => setTimeout(() => app.quit(), 150) });
for (const [action, channel] of Object.entries(DESKTOP_CHANNELS)) ipcMain.handle(channel, (event, input) => bridge.execute(event, action, input));
browsingView = new BrowsingView({ window, controller, windowOwner });
ipcMain.handle('awb:browsing-layout', (event, input) => browsingView.layout(event, input));
Menu.setApplicationMenu(Menu.buildFromTemplate([{ label: '工作台', submenu: [
{ label: '刷新窗口', role: 'reload' }, { label: '关闭窗口(后台任务继续)', accelerator: 'Alt+F4', click: () => window.close() },
] }, { label: '编辑', submenu: [{ role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, { role: 'selectAll' }] }]));
window.on('close', () => browsingView?.dispose());
window.on('closed', () => { window = null; });
await window.loadURL(host.url + '/?desktop=1&release=' + host.identity.version);
if (!options.hidden) window.show();
console.log(JSON.stringify({ app: 'agent-workbench-desktop', ready: true, pid: process.pid, hostPid: host.identity.pid,
instanceId: host.identity.instanceId, appRoot, dataRoot, url: host.url }));
}).catch(error => { console.error(JSON.stringify({ app: 'agent-workbench-desktop', ready: false, message: error.message }));
if (!options.hidden) dialog.showErrorBox('Agent Workbench 无法打开', error.message); app.exit(1); });
}
@@ -0,0 +1,12 @@
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('desktopWorkbench', Object.freeze({
protocol: 'agent-workbench-desktop-v1',
status: () => ipcRenderer.invoke('awb:desktop-status'),
pickProject: () => ipcRenderer.invoke('awb:desktop-pick-project'),
projectFolder: projectId => ipcRenderer.invoke('awb:desktop-project-folder', { projectId }),
openFilePreview: input => ipcRenderer.invoke('awb:desktop-file-preview', input),
reviewTask: input => ipcRenderer.invoke('awb:desktop-review-task', input),
revealFile: input => ipcRenderer.invoke('awb:desktop-reveal-file', input),
stopHost: () => ipcRenderer.invoke('awb:desktop-stop-host'),
browsingLayout: input => ipcRenderer.invoke('awb:browsing-layout', input),
}));