454 lines
30 KiB
JavaScript
454 lines
30 KiB
JavaScript
// src/desktop/host-cli.mjs
|
|
import fs5 from "node:fs";
|
|
import path6 from "node:path";
|
|
import os from "node:os";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
// src/core/desktop/host-controller.mjs
|
|
import fs4 from "node:fs";
|
|
import path5 from "node:path";
|
|
import { spawn, execFileSync as execFileSync2 } from "node:child_process";
|
|
import { randomBytes, randomUUID as randomUUID2 } from "node:crypto";
|
|
import { setTimeout as delay } from "node:timers/promises";
|
|
|
|
// src/shared/contracts/desktop-host.mjs
|
|
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
var HOST_PROTOCOL = "agent-workbench-host-v1";
|
|
var HOST_REGISTRATION_FILE = "host-authority-v1.json";
|
|
var hostError = (message, code = "HOST_IDENTITY_REJECTED", status = 409) => Object.assign(new Error(message), { code, status });
|
|
var canonicalHost = (value) => Array.isArray(value) ? value.map(canonicalHost) : value && typeof value === "object" ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonicalHost(value[key])])) : value;
|
|
function hostProof(identity, challenge, secret) {
|
|
if (!/^[a-f0-9]{64}$/.test(challenge) || !Buffer.isBuffer(secret) || secret.length !== 32) throw hostError("\u5BBF\u4E3B\u6838\u9A8C\u6311\u6218\u683C\u5F0F\u65E0\u6548\u3002", "HOST_CHALLENGE_INVALID", 400);
|
|
return createHmac("sha256", secret).update(JSON.stringify(canonicalHost({ identity, challenge }))).digest("hex");
|
|
}
|
|
function verifyHostProof(reply, challenge, secret) {
|
|
if (!reply?.identity || reply.challenge !== challenge || !/^[a-f0-9]{64}$/.test(reply.proof ?? "")) throw hostError("\u5BBF\u4E3B\u6CA1\u6709\u63D0\u4F9B\u5339\u914D\u7684\u5B9E\u4F8B\u6838\u9A8C\u3002");
|
|
const actual = Buffer.from(reply.proof, "hex"), expected = Buffer.from(hostProof(reply.identity, challenge, secret), "hex");
|
|
if (!timingSafeEqual(actual, expected)) throw hostError("\u7AEF\u53E3\u54CD\u5E94\u4E0D\u5C5E\u4E8E\u767B\u8BB0\u7684\u6267\u884C\u5BBF\u4E3B\u3002");
|
|
return reply.identity;
|
|
}
|
|
|
|
// src/core/process-environment.mjs
|
|
import path from "node:path";
|
|
function projectEnvironment(extra = {}) {
|
|
const allowed = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|homedrive|homepath|home|appdata|localappdata|programfiles(?:\(x86\))?|commonprogramfiles(?:\(x86\))?|lang|lc_all)$/i;
|
|
const environment = Object.fromEntries(Object.entries(process.env).filter(([name]) => allowed.test(name)));
|
|
const inheritedPath = Object.entries(environment).find(([name]) => name.toLowerCase() === "path")?.[1] || "";
|
|
for (const name of Object.keys(environment)) if (name.toLowerCase() === "path") delete environment[name];
|
|
return { ...environment, PATH: [path.dirname(process.execPath), inheritedPath].filter(Boolean).join(path.delimiter), ...extra };
|
|
}
|
|
|
|
// src/core/desktop/process-identity.mjs
|
|
import fs2 from "node:fs";
|
|
import path3 from "node:path";
|
|
import { execFileSync } from "node:child_process";
|
|
import { createHash } from "node:crypto";
|
|
|
|
// src/core/desktop/file-state.mjs
|
|
import fs from "node:fs";
|
|
import path2 from "node:path";
|
|
import { randomUUID } from "node:crypto";
|
|
var normalized = (value) => process.platform === "win32" ? value.toLowerCase() : value;
|
|
var samePath = (a, b) => normalized(path2.resolve(a)) === normalized(path2.resolve(b));
|
|
function assertLocalTree(absolute, { missing = false } = {}) {
|
|
const resolved = path2.resolve(absolute), parsed = path2.parse(resolved);
|
|
let current = parsed.root;
|
|
const components = resolved.slice(parsed.root.length).split(path2.sep).filter(Boolean);
|
|
for (const component of components) {
|
|
if (component.includes(":") || component.includes("\0")) throw hostError("\u672C\u673A\u72B6\u6001\u8DEF\u5F84\u683C\u5F0F\u65E0\u6548\u3002");
|
|
current = path2.join(current, component);
|
|
let stat;
|
|
try {
|
|
stat = fs.lstatSync(current);
|
|
} catch (cause) {
|
|
if (missing && cause.code === "ENOENT") return resolved;
|
|
throw cause;
|
|
}
|
|
if (stat.isSymbolicLink() || !samePath(current, fs.realpathSync.native(current))) throw hostError("\u672C\u673A\u72B6\u6001\u4E0D\u63A5\u53D7\u94FE\u63A5\u6216\u91CD\u89E3\u6790\u76EE\u5F55\u3002");
|
|
if (stat.isFile() && stat.nlink !== 1) throw hostError("\u672C\u673A\u72B6\u6001\u6587\u4EF6\u5177\u6709\u591A\u4E2A\u8DEF\u5F84\u3002");
|
|
}
|
|
return resolved;
|
|
}
|
|
function ownedChild(root, relative, { missing = false } = {}) {
|
|
if (typeof relative !== "string") throw hostError("\u672C\u673A\u72B6\u6001\u8DEF\u5F84\u65E0\u6548\u3002");
|
|
assertLocalTree(root);
|
|
const base = fs.realpathSync.native(root), target = path2.resolve(base, relative);
|
|
if (path2.isAbsolute(relative) || path2.win32.isAbsolute(relative) || relative.includes("\0") || !normalized(target).startsWith(normalized(base + path2.sep))) throw hostError("\u672C\u673A\u72B6\u6001\u8DEF\u5F84\u8D85\u51FA\u6240\u5C5E\u76EE\u5F55\u3002");
|
|
let existing = target;
|
|
while (!fs.existsSync(existing)) {
|
|
if (!missing) throw hostError("\u672C\u673A\u72B6\u6001\u6587\u4EF6\u4E0D\u5B58\u5728\u3002", "HOST_REGISTRATION_MISSING");
|
|
const parent = path2.dirname(existing);
|
|
if (parent === existing) throw hostError("\u672C\u673A\u72B6\u6001\u8DEF\u5F84\u65E0\u6CD5\u6838\u5BF9\u3002");
|
|
existing = parent;
|
|
}
|
|
const real = fs.realpathSync.native(existing);
|
|
if (!samePath(base, real) && !normalized(real).startsWith(normalized(base + path2.sep))) throw hostError("\u672C\u673A\u72B6\u6001\u94FE\u63A5\u8D85\u51FA\u6240\u5C5E\u76EE\u5F55\u3002");
|
|
if (fs.lstatSync(existing).isSymbolicLink()) throw hostError("\u672C\u673A\u72B6\u6001\u4E0D\u63A5\u53D7\u94FE\u63A5\u6216\u91CD\u89E3\u6790\u76EE\u5F55\u3002");
|
|
const stat = fs.statSync(existing);
|
|
if (stat.isFile() && stat.nlink !== 1) throw hostError("\u672C\u673A\u72B6\u6001\u6587\u4EF6\u5177\u6709\u591A\u4E2A\u8DEF\u5F84\u3002");
|
|
return assertLocalTree(target, { missing });
|
|
}
|
|
function readState(file, maximum = 4 * 1024 * 1024) {
|
|
assertLocalTree(file);
|
|
const stat = fs.lstatSync(file);
|
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > maximum) throw hostError("\u672C\u673A\u72B6\u6001\u6587\u4EF6\u683C\u5F0F\u6216\u4F5C\u7528\u8303\u56F4\u65E0\u6548\u3002");
|
|
try {
|
|
return JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
|
|
} catch {
|
|
throw hostError("\u672C\u673A\u72B6\u6001\u6587\u4EF6\u635F\u574F\uFF0C\u8BF7\u6838\u5BF9\u539F\u8BB0\u5F55\u3002");
|
|
}
|
|
}
|
|
function writeState(file, value) {
|
|
assertLocalTree(file, { missing: true });
|
|
const directory = path2.dirname(file), temporary = path2.join(directory, "." + path2.basename(file) + "-" + randomUUID() + ".tmp");
|
|
if (fs.existsSync(file)) readState(file);
|
|
try {
|
|
const descriptor = fs.openSync(temporary, "wx", 384);
|
|
try {
|
|
fs.writeFileSync(descriptor, JSON.stringify(value, null, 2) + "\n");
|
|
fs.fsyncSync(descriptor);
|
|
} finally {
|
|
fs.closeSync(descriptor);
|
|
}
|
|
assertLocalTree(file, { missing: true });
|
|
fs.renameSync(temporary, file);
|
|
} finally {
|
|
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
|
|
}
|
|
}
|
|
|
|
// src/core/desktop/process-identity.mjs
|
|
function windowsProcessObservationScript(pid) {
|
|
if (!Number.isInteger(pid) || pid < 1 || pid > 2147483647) throw hostError("\u5BBF\u4E3BPID\u65E0\u6548\u3002");
|
|
const query = 'Get-CimInstance Win32_Process -Filter "ProcessId=' + pid + '"';
|
|
return "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';[Console]::OutputEncoding=New-Object System.Text.UTF8Encoding($false);$awbProcess=" + query + ';if($null -eq $awbProcess){Write-Output "null";exit 0};try{$awbOwner=Invoke-CimMethod -InputObject $awbProcess -MethodName GetOwnerSid;if($awbOwner.ReturnValue -ne 0 -or -not $awbOwner.Sid){throw "Owner identity unavailable"};}catch{$awbRemaining=' + query + ';if($null -eq $awbRemaining){Write-Output "null";exit 0};throw};[pscustomobject]@{pid=[int]$awbProcess.ProcessId;parentPid=[int]$awbProcess.ParentProcessId;createdAt=$awbProcess.CreationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");executable=$awbProcess.ExecutablePath;userSid=$awbOwner.Sid}|ConvertTo-Json -Compress';
|
|
}
|
|
function observeWindowsProcess(pid) {
|
|
if (process.platform !== "win32") throw hostError("\u6B64\u684C\u9762\u5BBF\u4E3B\u6838\u9A8C\u9700\u8981Windows\u3002", "HOST_PLATFORM_UNSUPPORTED");
|
|
const script = windowsProcessObservationScript(pid);
|
|
try {
|
|
const shell = path3.join(process.env.SystemRoot || "C:\\Windows", "System32/WindowsPowerShell/v1.0/powershell.exe");
|
|
const output = execFileSync(
|
|
shell,
|
|
["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")],
|
|
{ windowsHide: true, encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], timeout: 15e3, maxBuffer: 65536, env: projectEnvironment() }
|
|
);
|
|
const value = JSON.parse(output.trim().replace(/^\uFEFF/, ""));
|
|
if (value === null) return null;
|
|
if (value.pid !== pid || !Number.isFinite(Date.parse(value.createdAt)) || !/^S-1-\d+(?:-\d+)+$/.test(value.userSid) || !value.executable || !fs2.existsSync(value.executable)) throw new Error("Invalid observation");
|
|
return { ...value, executable: fs2.realpathSync.native(value.executable) };
|
|
} catch {
|
|
throw hostError("\u65E0\u6CD5\u6838\u5BF9Windows\u5BBF\u4E3B\u521B\u5EFA\u3001\u7528\u6237\u6216\u53EF\u6267\u884C\u8EAB\u4EFD\uFF1B\u4E0D\u4F1A\u590D\u7528\u6216\u505C\u6B62\u672A\u77E5\u8FDB\u7A0B\u3002", "HOST_PROCESS_UNVERIFIED");
|
|
}
|
|
}
|
|
function binaryIdentity(file) {
|
|
assertLocalTree(file);
|
|
const absolute = fs2.realpathSync.native(file), stat = fs2.lstatSync(absolute);
|
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 256 * 1024 * 1024) throw hostError("\u5BBF\u4E3B\u53EF\u6267\u884C\u6587\u4EF6\u8EAB\u4EFD\u65E0\u6548\u3002");
|
|
return { path: absolute, bytes: stat.size, sha256: createHash("sha256").update(fs2.readFileSync(absolute)).digest("hex") };
|
|
}
|
|
|
|
// src/core/desktop/app-installation.mjs
|
|
import fs3 from "node:fs";
|
|
import path4 from "node:path";
|
|
import { createHash as createHash2 } from "node:crypto";
|
|
function inspectHostInstallation(directory, { full = false, onProgress = null } = {}) {
|
|
assertLocalTree(directory);
|
|
const root = fs3.realpathSync.native(path4.resolve(directory));
|
|
if (!fs3.statSync(root).isDirectory()) throw hostError("\u5BBF\u4E3B\u5B89\u88C5\u76EE\u5F55\u65E0\u6548\u3002");
|
|
const digest = (value) => createHash2("sha256").update(value).digest("hex");
|
|
const manifestFile = path4.join(root, "MANIFEST.json"), manifest = fs3.existsSync(manifestFile) ? readState(manifestFile, 16 * 1024 * 1024) : null;
|
|
if (manifest && (manifest.app !== "agent-workbench" || !Array.isArray(manifest.files) || manifest.files.length > 6e4)) throw hostError("\u5BBF\u4E3B\u53D1\u884C\u6E05\u5355\u65E0\u6548\u3002");
|
|
const version = manifest?.version ?? (fs3.existsSync(path4.join(root, "package.json")) ? readState(path4.join(root, "package.json")).version : null);
|
|
if (typeof version !== "string" || !/^\d+\.\d+\.\d+$/.test(version)) throw hostError("\u5BBF\u4E3B\u5B89\u88C5\u7248\u672C\u65E0\u6548\u3002");
|
|
const files = /* @__PURE__ */ new Set(["dist-server/server.mjs", "dist-server/hot-upgrade.mjs", "dist-client/index.html"]);
|
|
if (!manifest || fs3.existsSync(path4.join(root, "dist-server/host-launcher.mjs"))) files.add("dist-server/host-launcher.mjs");
|
|
if (fs3.existsSync(path4.join(root, "dist-server/install-manager.mjs"))) files.add("dist-server/install-manager.mjs");
|
|
for (const relative of ["dist-desktop/main.cjs", "dist-desktop/preload.cjs"]) if (fs3.existsSync(path4.join(root, relative))) files.add(relative);
|
|
const names = /* @__PURE__ */ new Map();
|
|
for (const row of manifest?.files ?? []) {
|
|
if (!row || typeof row.path !== "string" || row.path.includes("\\") || row.path.split("/").includes("..") || names.has(row.path) || !/^[a-f0-9]{64}$/.test(row.sha256 ?? "") || !Number.isSafeInteger(row.bytes) || row.bytes < 0) throw hostError("\u5BBF\u4E3B\u6E05\u5355\u5305\u542B\u91CD\u590D\u6216\u8D8A\u754C\u8F93\u5165\u3002");
|
|
names.set(row.path, row);
|
|
if (full || /^(dist-client|dist-server|dist-desktop)\//.test(row.path)) files.add(row.path);
|
|
}
|
|
if (!manifest || manifest.kind === "source") for (const entry of fs3.readdirSync(path4.join(root, "dist-client/assets"))) files.add("dist-client/assets/" + entry);
|
|
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("\u5B9E\u9645\u5BBF\u4E3B\u7A0B\u5E8F\u4E0D\u5728\u539F\u53D1\u884C\u6E05\u5355\u4E2D\u3002");
|
|
if (declared && (identity.bytes !== declared.bytes || identity.sha256 !== declared.sha256)) throw hostError("\u5B9E\u9645\u5BBF\u4E3B\u7A0B\u5E8F\u4E0E\u539F\u53D1\u884C\u6E05\u5355\u4E0D\u4E00\u81F4\u3002");
|
|
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(fs3.readFileSync(manifestFile)) : null,
|
|
inputs,
|
|
verification: full ? "full-manifest" : "loaded-host-and-client-inputs"
|
|
};
|
|
return { ...result, identitySha256: digest(JSON.stringify(canonicalHost(result))) };
|
|
}
|
|
|
|
// src/core/desktop/host-controller.mjs
|
|
var HOST_ENVIRONMENT = Object.freeze(["AGENT_WORKBENCH_DEEPSEEK_ROOT", "AGENT_WORKBENCH_PURGE_ROOT", "AGENT_WORKBENCH_PYTHON_PATH", "AGENT_WORKBENCH_TEST_PYTHON"]);
|
|
async function jsonResponse(response) {
|
|
if (!response.ok) throw hostError("\u672C\u673A\u5BBF\u4E3B\u63A5\u53E3\u62D2\u7EDD\u64CD\u4F5C\uFF08HTTP " + response.status + "\uFF09\u3002", "HOST_API_REJECTED", response.status);
|
|
const chunks = [];
|
|
let length = 0;
|
|
for await (const chunk of response.body) {
|
|
length += chunk.length;
|
|
if (length > 4 * 1024 * 1024) throw hostError("\u672C\u673A\u5BBF\u4E3B\u54CD\u5E94\u8FC7\u5927\u3002");
|
|
chunks.push(chunk);
|
|
}
|
|
try {
|
|
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
} catch {
|
|
throw hostError("\u7AEF\u53E3\u672A\u8FD4\u56DE\u6709\u6548\u7684\u5BBF\u4E3B\u534F\u8BAE\u3002");
|
|
}
|
|
}
|
|
var HostController = class {
|
|
constructor({ appRoot: appRoot2, dataRoot: dataRoot2, port = 4318, nodePath: nodePath2 = null, timeoutMs = 45e3, environment = {} }) {
|
|
if (!Number.isInteger(port) || port < 1 || port > 65535 || typeof dataRoot2 !== "string" || !path5.isAbsolute(dataRoot2)) throw hostError("\u684C\u9762\u5BBF\u4E3B\u76EE\u5F55\u6216\u7AEF\u53E3\u65E0\u6548\u3002");
|
|
this.installation = inspectHostInstallation(appRoot2);
|
|
this.appRoot = this.installation.root;
|
|
assertLocalTree(dataRoot2, { missing: true });
|
|
fs4.mkdirSync(dataRoot2, { recursive: true });
|
|
this.dataRoot = fs4.realpathSync.native(dataRoot2);
|
|
const bundled = path5.join(this.appRoot, "runtime/node.exe");
|
|
const executable = nodePath2 ?? (fs4.existsSync(bundled) ? bundled : !process.versions.electron ? process.execPath : null);
|
|
if (!executable) throw hostError("\u684C\u9762\u5B89\u88C5\u7F3A\u5C11\u72EC\u7ACBNode\u5BBF\u4E3B\u3002");
|
|
this.node = binaryIdentity(executable);
|
|
const version = execFileSync2(this.node.path, ["--version"], { encoding: "utf8", windowsHide: true, timeout: 1e4, env: projectEnvironment() }).trim();
|
|
if (!/^v24\./.test(version)) throw hostError("\u684C\u9762\u5BBF\u4E3B\u9700\u8981\u5DF2\u7ECF\u6838\u9A8C\u7684Node24\u8FD0\u884C\u5668\u3002");
|
|
this.node.version = version;
|
|
this.port = port;
|
|
this.url = "http://127.0.0.1:" + port;
|
|
this.timeoutMs = Math.min(6e4, Math.max(1e3, timeoutMs));
|
|
const allowed = new Set(HOST_ENVIRONMENT);
|
|
if (Object.keys(environment).some((key) => !allowed.has(key) || typeof environment[key] !== "string" || !path5.isAbsolute(environment[key]))) throw hostError("\u5BBF\u4E3B\u542F\u52A8\u53EA\u63A5\u53D7\u5DF2\u58F0\u660E\u7684\u672C\u673A\u8FD0\u884C\u5668\u8DEF\u5F84\u3002");
|
|
this.environment = environment;
|
|
}
|
|
async api(route, { method = "GET", input = null, timeoutMs = 15e3 } = {}) {
|
|
if (typeof route !== "string" || !route.startsWith("/") || route.startsWith("//")) throw hostError("\u5BBF\u4E3B\u63A5\u53E3\u8DEF\u5F84\u65E0\u6548\u3002");
|
|
return jsonResponse(await fetch(this.url + "/api" + route, {
|
|
method,
|
|
headers: {
|
|
Connection: "close",
|
|
...this.token ? { "X-Workbench-Token": this.token } : {},
|
|
...input ? { "Content-Type": "application/json" } : {}
|
|
},
|
|
body: input ? JSON.stringify(input) : void 0,
|
|
signal: AbortSignal.timeout(timeoutMs)
|
|
}));
|
|
}
|
|
async health() {
|
|
try {
|
|
return await this.api("/health", { timeoutMs: 1500 });
|
|
} catch (cause) {
|
|
if (cause.cause?.code === "ECONNREFUSED" || cause.cause?.errors?.every((value) => value.code === "ECONNREFUSED")) return null;
|
|
throw hostError("\u7AEF\u53E3\u88AB\u5360\u7528\u6216\u54CD\u5E94\u65E0\u6CD5\u6838\u5BF9\uFF1B\u4E0D\u4F1A\u542F\u52A8\u53E6\u4E00\u5957\u5BBF\u4E3B\u3002", "HOST_PORT_UNVERIFIED");
|
|
}
|
|
}
|
|
async connect() {
|
|
const health = await this.health();
|
|
if (!health) return null;
|
|
if (health.app !== "agent-workbench" || health.ready !== true || !Number.isInteger(health.pid)) throw hostError("\u7AEF\u53E3\u5C5E\u4E8E\u672A\u77E5\u670D\u52A1\u3002");
|
|
const bootstrap = await this.api("/bootstrap");
|
|
if (bootstrap.version !== this.installation.version || typeof bootstrap.token !== "string") throw hostError("\u8FD0\u884C\u7248\u672C\u4E0D\u5339\u914D\uFF0C\u8BF7\u4F7F\u7528\u660E\u786E\u7684\u5347\u7EA7\u6D41\u7A0B\u3002", "HOST_VERSION_MISMATCH");
|
|
this.token = bootstrap.token;
|
|
const challenge = randomBytes(32).toString("hex"), reply = await this.api("/host/identity?challenge=" + challenge);
|
|
ownedChild(this.dataRoot, ".secrets");
|
|
const registration = readState(ownedChild(this.dataRoot, ".secrets/" + HOST_REGISTRATION_FILE), 16384);
|
|
if (registration.schema !== 1 || registration.protocol !== HOST_PROTOCOL || !/^[A-Za-z0-9+/]{43}=$/.test(registration.secret ?? "")) throw hostError("\u672C\u673A\u539F\u6CE8\u518C\u683C\u5F0F\u65E0\u6CD5\u6838\u5BF9\u3002");
|
|
const identity = verifyHostProof(reply, challenge, Buffer.from(registration.secret, "base64"));
|
|
const actual = observeWindowsProcess(identity.pid), caller = observeWindowsProcess(process.pid);
|
|
if (!actual || !caller || identity.pid !== health.pid || identity.pid !== registration.pid || identity.createdAt !== actual.createdAt || identity.createdAt !== registration.createdAt || identity.instanceId !== registration.instanceId || identity.ownerId !== registration.ownerId || identity.userSid !== actual.userSid || identity.userSid !== registration.userSid || identity.userSid !== caller.userSid || identity.protocol !== HOST_PROTOCOL || identity.version !== this.installation.version || identity.port !== this.port || !samePath(identity.dataRoot, this.dataRoot) || !samePath(identity.runtimeRoot, this.appRoot) || identity.runtimeIdentity !== this.installation.identitySha256 || !samePath(identity.executable.path, actual.executable) || identity.executable.sha256 !== this.node.sha256 || binaryIdentity(actual.executable).sha256 !== this.node.sha256) throw hostError("\u5B9E\u9645PID\u521B\u5EFA\u3001\u7528\u6237\u3001\u7A0B\u5E8F\u3001\u5B89\u88C5\u6216\u6570\u636E\u76EE\u5F55\u4E0E\u539F\u5BBF\u4E3B\u767B\u8BB0\u4E0D\u4E00\u81F4\u3002");
|
|
const info = readState(ownedChild(this.dataRoot, "service-info.json"));
|
|
if (info.pid !== identity.pid || info.instanceId !== identity.instanceId || info.createdAt !== identity.createdAt || info.port !== this.port || info.userSid !== identity.userSid || info.ownerId !== identity.ownerId || info.runtimeIdentity !== identity.runtimeIdentity || !samePath(info.appRoot, identity.appRoot) || !samePath(info.dataRoot, this.dataRoot) || !samePath(info.runtimeRoot, this.appRoot)) throw hostError("\u672C\u673A\u5BBF\u4E3B\u7D22\u5F15\u4E0E\u5B9E\u9645\u5B9E\u4F8B\u4E0D\u4E00\u81F4\u3002");
|
|
this.identity = identity;
|
|
return { url: this.url, identity };
|
|
}
|
|
async lock(action) {
|
|
const lockDirectory = ownedChild(this.dataRoot, ".desktop-launch.lock", { missing: true }), nonce = randomUUID2(), observed = observeWindowsProcess(process.pid);
|
|
const deadline = Date.now() + this.timeoutMs;
|
|
while (true) {
|
|
try {
|
|
fs4.mkdirSync(lockDirectory, { mode: 448 });
|
|
break;
|
|
} catch (cause) {
|
|
if (cause.code !== "EEXIST") throw cause;
|
|
ownedChild(this.dataRoot, ".desktop-launch.lock");
|
|
const ownerFile2 = path5.join(lockDirectory, "owner.json");
|
|
if (fs4.existsSync(ownerFile2)) {
|
|
ownedChild(this.dataRoot, ".desktop-launch.lock/owner.json");
|
|
const owner = readState(ownerFile2, 16384);
|
|
if (!Number.isInteger(owner.pid) || typeof owner.createdAt !== "string" || typeof owner.nonce !== "string") throw hostError("\u542F\u52A8\u9501\u7684\u539F\u8EAB\u4EFD\u65E0\u6CD5\u6838\u5BF9\u3002");
|
|
const active = observeWindowsProcess(owner.pid);
|
|
if (active && active.createdAt === owner.createdAt && (owner.userSid !== active.userSid || owner.userSid !== observed.userSid)) throw hostError("\u542F\u52A8\u9501\u4E0D\u5C5E\u4E8E\u5F53\u524DWindows\u7528\u6237\u3002");
|
|
if (!active || active.createdAt !== owner.createdAt) {
|
|
if (readState(ownerFile2).nonce !== owner.nonce) continue;
|
|
const archive = ownedChild(this.dataRoot, ".desktop-launch-stale-" + randomUUID2(), { missing: true });
|
|
try {
|
|
fs4.renameSync(lockDirectory, archive);
|
|
} catch (error) {
|
|
if (!["ENOENT", "EEXIST"].includes(error.code)) throw error;
|
|
}
|
|
continue;
|
|
}
|
|
} else if (Date.now() - fs4.statSync(lockDirectory).mtimeMs > 1e4) throw hostError("\u542F\u52A8\u9501\u7F3A\u5C11\u539F\u8BB0\u5F55\uFF0C\u8BF7\u6838\u5BF9\u8BE5\u76EE\u5F55\u3002");
|
|
if (Date.now() >= deadline) throw hostError("\u6B63\u5728\u7B49\u5F85\u539F\u542F\u52A8\u64CD\u4F5C\uFF0C\u8BF7\u6838\u5BF9\u5F53\u524D\u5BBF\u4E3B\u3002", "HOST_START_PENDING");
|
|
await delay(100);
|
|
}
|
|
}
|
|
const ownerFile = path5.join(lockDirectory, "owner.json");
|
|
try {
|
|
writeState(ownerFile, { schema: 1, pid: process.pid, createdAt: observed.createdAt, userSid: observed.userSid, nonce });
|
|
return await action();
|
|
} finally {
|
|
if (fs4.existsSync(ownerFile) && readState(ownerFile).nonce === nonce) {
|
|
fs4.unlinkSync(ownerFile);
|
|
fs4.rmdirSync(lockDirectory);
|
|
}
|
|
}
|
|
}
|
|
async start() {
|
|
return this.lock(async () => {
|
|
const existing = await this.connect();
|
|
if (existing) return { ...existing, reused: true };
|
|
const intentFile = ownedChild(this.dataRoot, "desktop-launch-state.json", { missing: true });
|
|
if (fs4.existsSync(intentFile)) {
|
|
const intent = readState(intentFile);
|
|
if (intent.pid && !["exited", "failed"].includes(intent.state)) {
|
|
const actual = observeWindowsProcess(intent.pid);
|
|
if (actual && actual.createdAt === intent.createdAt) throw hostError("\u539F\u542F\u52A8\u8FDB\u7A0B\u4ECD\u6D3B\u52A8\u4F46\u6CA1\u6709\u53EF\u6838\u9A8C\u63A5\u53E3\uFF0C\u8BF7\u6838\u5BF9\u539F\u65E5\u5FD7\uFF1B\u4E0D\u4F1A\u518D\u542F\u52A8\u53E6\u4E00\u8FDB\u7A0B\u3002", "HOST_START_UNVERIFIED");
|
|
}
|
|
}
|
|
const logs = ownedChild(this.dataRoot, "logs", { missing: true });
|
|
if (!fs4.existsSync(logs)) fs4.mkdirSync(logs);
|
|
const id = randomUUID2(), stdoutPath = path5.join(logs, "desktop-host-" + id + "-stdout.log"), stderrPath = path5.join(logs, "desktop-host-" + id + "-stderr.log");
|
|
let output, errors, child;
|
|
try {
|
|
output = fs4.openSync(stdoutPath, "wx", 384);
|
|
errors = fs4.openSync(stderrPath, "wx", 384);
|
|
child = spawn(this.node.path, [ownedChild(this.appRoot, "dist-server/server.mjs")], {
|
|
cwd: this.appRoot,
|
|
windowsHide: true,
|
|
detached: true,
|
|
env: projectEnvironment({ ...this.environment, AGENT_WORKBENCH_APP_DIR: this.appRoot, AGENT_WORKBENCH_DATA_DIR: this.dataRoot, AGENT_WORKBENCH_PORT: String(this.port) }),
|
|
stdio: ["ignore", output, errors]
|
|
});
|
|
} finally {
|
|
if (output !== void 0) fs4.closeSync(output);
|
|
if (errors !== void 0) fs4.closeSync(errors);
|
|
}
|
|
let failure = null;
|
|
child.on("error", (cause) => {
|
|
failure = cause;
|
|
});
|
|
child.unref();
|
|
const observedChild = child.pid ? observeWindowsProcess(child.pid) : null;
|
|
writeState(intentFile, {
|
|
schema: 1,
|
|
state: observedChild ? "starting" : "failed",
|
|
id,
|
|
pid: child.pid ?? null,
|
|
createdAt: observedChild?.createdAt ?? null,
|
|
appRoot: this.appRoot,
|
|
dataRoot: this.dataRoot,
|
|
port: this.port,
|
|
stdoutPath,
|
|
stderrPath
|
|
});
|
|
const deadline = Date.now() + this.timeoutMs;
|
|
while (Date.now() < deadline) {
|
|
if (failure || child.exitCode !== null) throw hostError("\u6240\u5C5E\u5BBF\u4E3B\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u67E5\u770B\u672C\u673A\u542F\u52A8\u8BB0\u5F55\u3002", "HOST_START_FAILED");
|
|
await delay(100);
|
|
let health;
|
|
try {
|
|
health = await this.health();
|
|
} catch (cause) {
|
|
if (cause.code !== "HOST_PORT_UNVERIFIED") throw cause;
|
|
const waiting = observeWindowsProcess(child.pid);
|
|
if (!waiting || !observedChild || waiting.createdAt !== observedChild.createdAt || waiting.userSid !== observedChild.userSid || !samePath(waiting.executable, this.node.path)) throw hostError("\u6240\u5C5E\u5BBF\u4E3B\u542F\u52A8\u8FDB\u7A0B\u5DF2\u7ED3\u675F\u6216\u8EAB\u4EFD\u53D8\u5316\uFF0C\u8BF7\u6838\u5BF9\u539F\u65E5\u5FD7\u3002", "HOST_START_FAILED");
|
|
continue;
|
|
}
|
|
if (!health) continue;
|
|
if (health.pid !== child.pid) throw hostError("\u542F\u52A8\u671F\u95F4\u7AEF\u53E3\u88AB\u5176\u4ED6\u8FDB\u7A0B\u5360\u7528\u3002");
|
|
const connected = await this.connect();
|
|
if (connected) {
|
|
writeState(intentFile, { ...readState(intentFile), state: "ready", instanceId: connected.identity.instanceId });
|
|
return { ...connected, reused: false, logs: { stdoutPath, stderrPath } };
|
|
}
|
|
}
|
|
throw hostError("\u6240\u5C5E\u5BBF\u4E3B\u5C1A\u672A\u5B8C\u6210\u6CE8\u518C\uFF1B\u4E0D\u4F1A\u91CD\u65B0\u542F\u52A8\u6216\u7ED3\u675F\u672A\u77E5\u8FDB\u7A0B\u3002", "HOST_START_UNVERIFIED");
|
|
});
|
|
}
|
|
async status() {
|
|
if (!await this.connect()) return { state: "not-running", url: this.url };
|
|
return this.api("/host/status");
|
|
}
|
|
async stop() {
|
|
return this.lock(async () => {
|
|
const connection = await this.connect();
|
|
if (!connection) return { state: "not-running", url: this.url };
|
|
const original = connection.identity;
|
|
await this.api("/host/stop", { method: "POST", input: {
|
|
instanceId: original.instanceId,
|
|
createdAt: original.createdAt,
|
|
runtimeIdentity: original.runtimeIdentity,
|
|
confirmation: "stop-owned-host"
|
|
}, timeoutMs: this.timeoutMs });
|
|
const deadline = Date.now() + this.timeoutMs;
|
|
while (Date.now() < deadline) {
|
|
await delay(200);
|
|
const observed = observeWindowsProcess(original.pid);
|
|
if (!observed) {
|
|
if (await this.health()) throw hostError("\u539F\u5BBF\u4E3B\u5DF2\u7ED3\u675F\uFF0C\u4F46\u7AEF\u53E3\u5B58\u5728\u5176\u4ED6\u670D\u52A1\u3002");
|
|
return { state: "stopped", identity: original, processExited: true };
|
|
}
|
|
if (observed.createdAt !== original.createdAt) throw hostError("\u539FPID\u5DF2\u88AB\u590D\u7528\uFF0C\u4E0D\u4F1A\u7ED3\u675F\u65B0\u7684\u8FDB\u7A0B\u3002");
|
|
}
|
|
throw hostError("\u6240\u5C5E\u5BBF\u4E3B\u9000\u51FA\u4ECD\u5F85\u6838\u5BF9\uFF0C\u8BF7\u4FDD\u7559\u539F\u5B9E\u4F8B\u8BB0\u5F55\u3002", "HOST_STOP_UNVERIFIED");
|
|
});
|
|
}
|
|
};
|
|
|
|
// src/desktop/host-cli.mjs
|
|
var 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);
|
|
}
|
|
var command = args.shift();
|
|
if (!["start", "status", "stop"].includes(command)) throw new Error("Use --help for a supported desktop host operation.");
|
|
var options = {};
|
|
while (args.length) {
|
|
const flag = args.shift(), value = args.shift();
|
|
if (!["--app-root", "--data-root", "--node", "--port"].includes(flag) || !value || options[flag] !== void 0) throw new Error("Invalid or repeated host option.");
|
|
options[flag] = value;
|
|
}
|
|
var defaultRoot = path6.resolve(path6.dirname(fileURLToPath(import.meta.url)), "..");
|
|
var appRoot = options["--app-root"] || process.env.AGENT_WORKBENCH_APP_DIR || defaultRoot;
|
|
var dataRoot = options["--data-root"] || process.env.AGENT_WORKBENCH_DATA_DIR || path6.join(process.env.LOCALAPPDATA || path6.join(os.homedir(), ".local/share"), "AgentWorkbench");
|
|
var nodePath = options["--node"] || (fs5.existsSync(path6.join(appRoot, "runtime/node.exe")) ? path6.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;
|
|
}
|