// src/core/desktop/install-manager.mjs import fs7 from "node:fs"; import path7 from "node:path"; import { randomUUID as randomUUID4, createHash as createHash3 } from "node:crypto"; import { DatabaseSync } from "node:sqlite"; import net from "node:net"; import { isDeepStrictEqual } from "node:util"; // 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 protectUserDirectory(directory) { assertLocalTree(directory); if (process.platform !== "win32") throw hostError("\u672C\u673A\u79D8\u5BC6\u76EE\u5F55\u9700\u8981Windows\u7528\u6237\u6743\u9650\u3002"); const script = `$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';$awbPath=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Console]::In.ReadToEnd()));$awbSid=[Security.Principal.WindowsIdentity]::GetCurrent().User;$awbAcl=[IO.Directory]::GetAccessControl($awbPath,[Security.AccessControl.AccessControlSections]::Access);$awbAcl.SetAccessRuleProtection($true,$false);foreach($awbExisting in $awbAcl.GetAccessRules($true,$false,[Security.Principal.SecurityIdentifier])){$awbAcl.RemoveAccessRuleSpecific($awbExisting)};$awbRule=New-Object Security.AccessControl.FileSystemAccessRule($awbSid,"FullControl","ContainerInherit,ObjectInherit","None","Allow");$awbAcl.AddAccessRule($awbRule);[IO.Directory]::SetAccessControl($awbPath,$awbAcl)`; try { execFileSync( path3.join(process.env.SystemRoot || "C:\\Windows", "System32/WindowsPowerShell/v1.0/powershell.exe"), ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { input: Buffer.from(directory, "utf8").toString("base64"), encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], windowsHide: true, timeout: 15e3, maxBuffer: 65536, env: projectEnvironment() } ); } catch { throw hostError("\u65E0\u6CD5\u4E3A\u672C\u673A\u79D8\u5BC6\u76EE\u5F55\u8BBE\u7F6E\u5F53\u524DWindows\u7528\u6237\u6743\u9650\u3002", "HOST_DIRECTORY_UNPROTECTED"); } } 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 digest2 = (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 ? digest2(fs3.readFileSync(manifestFile)) : null, inputs, verification: full ? "full-manifest" : "loaded-host-and-client-inputs" }; return { ...result, identitySha256: digest2(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, dataRoot, port = 4318, nodePath = null, timeoutMs = 45e3, environment = {} }) { if (!Number.isInteger(port) || port < 1 || port > 65535 || typeof dataRoot !== "string" || !path5.isAbsolute(dataRoot)) throw hostError("\u684C\u9762\u5BBF\u4E3B\u76EE\u5F55\u6216\u7AEF\u53E3\u65E0\u6548\u3002"); this.installation = inspectHostInstallation(appRoot); this.appRoot = this.installation.root; assertLocalTree(dataRoot, { missing: true }); fs4.mkdirSync(dataRoot, { recursive: true }); this.dataRoot = fs4.realpathSync.native(dataRoot); const bundled = path5.join(this.appRoot, "runtime/node.exe"); const executable = nodePath ?? (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"); }); } }; // scripts/upgrade-running.mjs import fs5 from "node:fs"; import path6 from "node:path"; import { fileURLToPath } from "node:url"; import { setTimeout as delay2 } from "node:timers/promises"; function localUrl(value) { const url = new URL(value); if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.username || url.password || url.search || url.hash) throw new Error("Upgrade only accepts the local Workbench address."); return url.origin; } async function within(promise, milliseconds, label) { let timer; try { return await Promise.race([promise, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(label + " timed out.")), milliseconds); })]); } finally { clearTimeout(timer); } } async function readUpgradeJson(address, milliseconds, stage) { try { const response = await fetch(address, { headers: { Connection: "close" }, signal: AbortSignal.timeout(milliseconds) }); if (!response.ok) throw new Error("HTTP " + response.status); return await response.json(); } catch (error) { throw new Error(stage + ": " + error.message + (error.cause?.code ? " (" + error.cause.code + ")" : ""), { cause: error }); } } var Protocol = class { constructor(socket) { this.socket = socket; this.nextId = 1; this.pending = /* @__PURE__ */ new Map(); this.listeners = /* @__PURE__ */ new Map(); socket.addEventListener("message", (event) => { const message = JSON.parse(String(event.data)); if (message.id) { const pending = this.pending.get(message.id); if (!pending) return; this.pending.delete(message.id); if (message.error) pending.reject(new Error(message.error.message)); else pending.resolve(message.result); } else for (const listener of this.listeners.get(message.method) ?? []) listener(message.params); }); socket.addEventListener("close", () => { for (const pending of this.pending.values()) pending.reject(new Error("Inspector connection closed.")); this.pending.clear(); }); } on(method, listener) { this.listeners.set(method, [...this.listeners.get(method) ?? [], listener]); } send(method, params = {}) { return within(new Promise((resolve, reject) => { const id = this.nextId++; this.pending.set(id, { resolve, reject }); this.socket.send(JSON.stringify({ id, method, params })); }), 1e4, method); } }; function sameFile(url, file) { try { return path6.resolve(fileURLToPath(url)).toLowerCase() === path6.resolve(file).toLowerCase(); } catch { return false; } } function sameTarget(target, file) { if (sameFile(target.url, file)) return true; const displayName = path6.resolve(file).replaceAll("\\", "_").replaceAll("/", "_"); return target.title === displayName && target.url === "file://" + displayName; } async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRoot }) { const origin = localUrl(url), original = fs5.realpathSync.native(currentRoot), next = fs5.realpathSync.native(newRoot); const originalScript = path6.join(original, "dist-server", "server.mjs"); const upgradeScript = path6.join(next, "dist-server", "hot-upgrade.mjs"); if (!fs5.existsSync(originalScript) || !fs5.existsSync(upgradeScript) || !fs5.existsSync(path6.join(next, "dist-client", "index.html"))) throw new Error("Upgrade bundles are incomplete."); if (!Number.isInteger(pid) || pid < 1 || pid === process.pid) throw new Error("Invalid target process."); const before = await readUpgradeJson(origin + "/api/bootstrap", 5e3, "Read original Workbench"); if (!before.token || !["0.1.0", "1.0.0", "1.1.0", "1.2.0", "1.3.0", "1.4.0", "1.5.0", "1.5.1", "1.6.0", "1.6.1", "1.6.2", "1.7.0", "1.8.0", "1.9.0", "1.10.0", "1.10.1", "1.11.0", "1.12.0", "1.12.1", "1.13.0", "1.14.0", "1.15.0", "1.16.0", "1.17.0", "1.18.0", "1.19.0", "1.20.0", "1.20.1", "1.20.2", "1.20.3", "1.21.0", "1.22.0", "1.22.1", "1.23.0", "1.24.0", "1.24.1", "1.24.2"].includes(before.version)) throw new Error("This migration accepts a supported existing Workbench."); if (before.sessions.some((session) => ["running", "awaiting_approval", "stopping"].includes(session.status))) throw new Error("Wait for existing tasks and approvals before upgrading."); let protocol, socket, enabledHere = false, paused = false; const breakpoints = []; try { let targets; try { targets = await readUpgradeJson("http://127.0.0.1:9229/json/list", 500, "Discover inspector"); } catch { } if (targets && !targets.some((target2) => sameTarget(target2, originalScript))) throw new Error("The local inspector port belongs to another process."); if (!targets) { process._debugProcess(pid); enabledHere = true; for (let attempt = 0; attempt < 40 && !targets; attempt++) { await delay2(100); try { targets = await readUpgradeJson("http://127.0.0.1:9229/json/list", 500, "Discover opened inspector"); } catch { } } } const target = targets?.find((item) => sameTarget(item, originalScript)); if (!target || !target.webSocketDebuggerUrl?.startsWith("ws://127.0.0.1:9229/")) throw new Error("The expected Workbench inspector was not found."); socket = new WebSocket(target.webSocketDebuggerUrl); await within(new Promise((resolve, reject) => { socket.addEventListener("open", resolve, { once: true }); socket.addEventListener("error", reject, { once: true }); }), 1e4, "Inspector connection"); protocol = new Protocol(socket); const scripts = []; protocol.on("Debugger.scriptParsed", (script) => scripts.push(script)); let pausedResolve; const pausedEvent = new Promise((resolve) => { pausedResolve = resolve; }); protocol.on("Debugger.paused", (event2) => { paused = true; pausedResolve(event2); }); await protocol.send("Runtime.enable"); const identity = await protocol.send("Runtime.evaluate", { expression: "process.pid", returnByValue: true }); if (identity.result.value !== pid) throw new Error("The inspector belongs to a different process."); await protocol.send("Debugger.enable"); const previousRoot = handlerRoot || before.runtimeRoot; const expectedScripts = [originalScript, ...previousRoot ? [path6.join(fs5.realpathSync.native(previousRoot), "dist-server", "hot-upgrade.mjs")] : []]; const candidates = scripts.filter((item) => expectedScripts.some((file) => sameFile(item.url, file))); if (!candidates.length) throw new Error("The existing server module is missing from inspector metadata."); for (const script of candidates) { const { scriptSource } = await protocol.send("Debugger.getScriptSource", { scriptId: script.scriptId }); const locations = scriptSource.split("\n").flatMap((line, index) => /const url = new URL\(request\.url,\s*["']http:\/\/127\.0\.0\.1:["']\s*\+\s*actualPort\d*\)/.test(line) ? [index] : []); if (locations.length !== 1) throw new Error("The existing request handler could not be identified uniquely."); breakpoints.push((await protocol.send("Debugger.setBreakpoint", { location: { scriptId: script.scriptId, lineNumber: locations[0] } })).breakpointId); } const probe = readUpgradeJson(origin + "/api/health", 15e3, "Observe owned request handler"); probe.catch(() => { }); const event = await within(pausedEvent, 1e4, "Workbench request observation"); const captureExpression = "(() => { const currentServer = typeof server !== 'undefined' ? server : typeof server2 !== 'undefined' ? server2 : undefined; const currentStore = typeof store !== 'undefined' ? store : typeof store2 !== 'undefined' ? store2 : undefined; const currentProvider = typeof provider !== 'undefined' ? provider : typeof provider2 !== 'undefined' ? provider2 : undefined; const currentRuntime = typeof runtime !== 'undefined' ? runtime : typeof runtime2 !== 'undefined' ? runtime2 : undefined; const currentToken = typeof token !== 'undefined' ? token : typeof token2 !== 'undefined' ? token2 : undefined; const currentClients = typeof clients !== 'undefined' ? clients : typeof clients2 !== 'undefined' ? clients2 : undefined; const currentStarted = typeof started !== 'undefined' ? started : typeof started2 !== 'undefined' ? started2 : undefined; const currentExampleProject = typeof exampleProject !== 'undefined' ? exampleProject : typeof exampleProject2 !== 'undefined' ? exampleProject2 : undefined; const currentShutdown = typeof shutdown !== 'undefined' ? shutdown : typeof shutdown2 !== 'undefined' ? shutdown2 : undefined; const servers = currentServer ? [currentServer] : process._getActiveHandles().filter(handle => handle?.listening && handle.address?.()?.address === '127.0.0.1' && handle.address?.()?.port === " + new URL(origin).port + "); if (servers.length !== 1 || !currentStore || !currentProvider || !currentRuntime || !currentToken || !currentClients || !currentShutdown) throw new Error('The existing Workbench context is incomplete.'); globalThis.__awUpgradeContext = { server: servers[0], store: currentStore, provider: currentProvider, runtime: currentRuntime, token: currentToken, clients: currentClients, started: currentStarted, exampleProject: currentExampleProject, shutdown: currentShutdown }; return 'context-ready'; })()"; const captured = await protocol.send("Debugger.evaluateOnCallFrame", { callFrameId: event.callFrames[0].callFrameId, expression: captureExpression, returnByValue: true }); if (captured.exceptionDetails || captured.result.value !== "context-ready") throw new Error("Could not retain the existing runtime objects."); for (const breakpointId of breakpoints.splice(0)) await protocol.send("Debugger.removeBreakpoint", { breakpointId }); await protocol.send("Debugger.resume"); paused = false; await probe; const expression = '(() => { try { const module = process.getBuiltinModule("module").createRequire(' + JSON.stringify(upgradeScript) + ")(" + JSON.stringify(upgradeScript) + "); return module.installUpgrade(globalThis.__awUpgradeContext, { appDirectory: " + JSON.stringify(next) + " }); } finally { delete globalThis.__awUpgradeContext; } })()"; const upgraded = await protocol.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }); if (upgraded.exceptionDetails) throw new Error("Runtime upgrade failed: " + (upgraded.exceptionDetails.exception?.description ?? upgraded.exceptionDetails.text)); const result = upgraded.result.value; const after = await readUpgradeJson(origin + "/api/bootstrap", 5e3, "Read upgraded Workbench"); const health = await readUpgradeJson(origin + "/api/health", 5e3, "Verify upgraded PID"); if (health.pid !== pid || result.pid !== pid || after.version !== result.version || after.config.hasKey !== before.config.hasKey || after.config.model !== before.config.model || after.config.baseUrl !== before.config.baseUrl || JSON.stringify(after.projects) !== JSON.stringify(before.projects) || JSON.stringify(after.sessions) !== JSON.stringify(before.sessions)) throw new Error("The upgraded runtime did not preserve the existing state."); return { ...result, verified: true, connectionPreserved: true, url: origin }; } finally { if (protocol) { for (const breakpointId of breakpoints) { try { await protocol.send("Debugger.removeBreakpoint", { breakpointId }); } catch { } } try { if (paused) await protocol.send("Debugger.resume"); } catch { } try { await protocol.send("Runtime.evaluate", { expression: "delete globalThis.__awUpgradeContext; true", returnByValue: true }); } catch { } if (enabledHere) { try { await protocol.send("Runtime.evaluate", { expression: "setTimeout(() => process.getBuiltinModule('inspector').close(), 25); true", returnByValue: true }); } catch { } } } socket?.close(); if (enabledHere) await delay2(150); } } if (path6.basename(fileURLToPath(import.meta.url)) === "upgrade-running.mjs" && process.argv[1] && path6.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const raw = process.argv.slice(2), args2 = {}, options2 = /* @__PURE__ */ new Set(["url", "pid", "current-root", "new-root", "handler-root"]); if (raw.length === 1 && raw[0] === "--help") { console.log("node scripts/upgrade-running.mjs --pid PID --current-root DIR --new-root DIR [--url http://127.0.0.1:4318] [--handler-root DIR]"); process.exit(0); } for (let index = 0; index < raw.length; index += 2) { const key = raw[index].startsWith("--") ? raw[index].slice(2) : ""; if (!options2.has(key) || Object.hasOwn(args2, key) || !raw[index + 1] || raw[index + 1].startsWith("--")) throw new Error("Unknown or incomplete argument; use --help."); args2[key] = raw[index + 1]; } if (!/^\d+$/.test(args2.pid ?? "") || !path6.isAbsolute(args2["current-root"] ?? "") || !path6.isAbsolute(args2["new-root"] ?? "") || args2["handler-root"] !== void 0 && !path6.isAbsolute(args2["handler-root"])) throw new Error("PID and absolute current/new roots are required arguments; use --help."); const result = await upgradeRunning({ url: args2.url || "http://127.0.0.1:4318", pid: Number(args2.pid), currentRoot: args2["current-root"], newRoot: args2["new-root"], handlerRoot: args2["handler-root"] }); console.log(JSON.stringify(result, null, 2)); } // src/core/desktop/installation-progress.mjs import fs6 from "node:fs"; import { randomUUID as randomUUID3 } from "node:crypto"; import { performance } from "node:perf_hooks"; var INSTALLATION_STAGES = Object.freeze({ preparing: "\u51C6\u5907\u5B89\u88C5\u6838\u5BF9", "verify-current": "\u6838\u5BF9\u539F\u6D3B\u52A8\u7248\u672C", "verify-candidate": "\u6838\u5BF9\u65B0\u7248\u672C", "inspect-root": "\u6838\u5BF9\u5B89\u88C5\u76EE\u5F55", "inspect-host": "\u6838\u5BF9\u540E\u53F0\u5BBF\u4E3B\u4E0E\u6D3B\u52A8\u4EFB\u52A1", "snapshot-data": "\u8BB0\u5F55\u539F\u4F1A\u8BDD\u4E0E\u5DE5\u4EF6", "retain-host": "\u4FDD\u7559\u539F\u5BBF\u4E3B\u4E0E\u6A21\u578B\u8FDE\u63A5", "verify-data": "\u6838\u5BF9\u539F\u4F1A\u8BDD\u4E0E\u5DE5\u4EF6\u4FDD\u6301", "publish-pointer": "\u53D1\u5E03\u6D3B\u52A8\u7248\u672C", "verify-publication": "\u6838\u5BF9\u5DF2\u53D1\u5E03\u7248\u672C", rollback: "\u6838\u5BF9\u539F\u7248\u672C\u56DE\u9000", "ready-to-copy": "\u9884\u68C0\u901A\u8FC7\uFF0C\u7B49\u5F85\u5B89\u88C5\u5668\u5199\u5165\u7248\u672C\u6587\u4EF6", staged: "\u5019\u9009\u5DF2\u6682\u5B58\uFF0C\u5C1A\u672A\u5207\u6362\u7248\u672C", completed: "\u7248\u672C\u6FC0\u6D3B\u5B8C\u6210", failed: "\u5B89\u88C5\u672A\u5B8C\u6210\uFF0C\u8BF7\u6838\u5BF9\u539F\u59CB\u539F\u56E0", "uninstall-ready": "\u5378\u8F7D\u9884\u68C0\u5B8C\u6210\uFF0C\u7528\u6237\u6570\u636E\u4FDD\u7559", cancelled: "\u672C\u6B21\u5B89\u88C5\u51C6\u5907\u5DF2\u53D6\u6D88" }); var terminal = /* @__PURE__ */ new Set(["staged", "completed", "failed", "uninstall-ready", "cancelled"]); var validId = (value) => typeof value === "string" && /^(?:[a-f0-9]{64}|[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})$/.test(value); var InstallationProgress = class { constructor({ stateRoot, installRoot, dataRoot, command: command2, operationId = null, expectedManifestSha256 = null, onProgress = null }) { const id = operationId ?? randomUUID3(); if (!validId(id)) throw hostError("\u5B89\u88C5\u64CD\u4F5C\u7F16\u53F7\u65E0\u6548\u3002"); this.file = ownedChild(stateRoot, "progress-" + id + ".json", { missing: true }); const previous = fs6.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(command2))) throw hostError("\u539F\u5B89\u88C5\u64CD\u4F5C\u4E0D\u5141\u8BB8\u91CD\u653E\u6216\u6539\u53D8\u6765\u6E90\u3002"); if (!previous && command2 === "cancel") throw hostError("\u6CA1\u6709\u53EF\u53D6\u6D88\u7684\u539F\u5B89\u88C5\u51C6\u5907\u8BB0\u5F55\u3002"); this.onProgress = onProgress; this.lastSaved = 0; this.value = { schema: 1, id, installRoot, dataRoot, command: command2, expectedManifestSha256, startedAt: previous?.startedAt ?? (/* @__PURE__ */ 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 }; 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("\u5B89\u88C5\u9636\u6BB5\u65E0\u6548\u3002"); 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: (/* @__PURE__ */ 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: (/* @__PURE__ */ 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 = (/* @__PURE__ */ 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(); try { this.onProgress?.(structuredClone(this.value)); } catch { } } finish(state, detail = {}) { if (!terminal.has(state) && state !== "ready-to-copy") throw hostError("\u5B89\u88C5\u7EC8\u6001\u65E0\u6548\u3002"); this.value.state = state; this.phase(state, detail); } }; // src/core/desktop/install-manager.mjs var digest = (value) => createHash3("sha256").update(value).digest("hex"); var inside = (root, value) => samePath(root, value) || path7.resolve(value).toLowerCase().startsWith(path7.resolve(root).toLowerCase() + path7.sep); var fail = (message) => hostError(message, "INSTALLATION_REJECTED", 409); function validateInstalledVersion(directory, { onProgress = null } = {}) { const installation = inspectHostInstallation(directory, { full: true, onProgress }); if (installation.kind !== "portable") throw fail("\u5B89\u88C5\u5019\u9009\u9700\u8981\u5B8C\u6574\u4FBF\u643A\u53D1\u884C\u6E05\u5355\u3002"); const manifest = readState(path7.join(installation.root, "MANIFEST.json"), 16 * 1024 * 1024), actual = []; const walk = (relative) => { for (const entry of fs7.readdirSync(path7.join(installation.root, relative), { withFileTypes: true })) { const next = path7.posix.join(relative, entry.name); ownedChild(installation.root, next); 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("\u5B89\u88C5\u5019\u9009\u542B\u6709\u94FE\u63A5\u6216\u975E\u5E38\u89C4\u6587\u4EF6\u3002"); } }; walk(""); const declared = manifest.files.map((value) => value.path).concat("MANIFEST.json").sort(); if (!isDeepStrictEqual(actual.sort(), declared)) throw fail("\u5B89\u88C5\u5019\u9009\u7684\u5B9E\u9645\u6587\u4EF6\u8303\u56F4\u4E0E\u6E05\u5355\u4E0D\u540C\u3002"); 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("\u684C\u9762\u5B89\u88C5\u7F3A\u5C11\u5FC5\u8981\u8FD0\u884C\u6587\u4EF6\u3002"); return inspectHostInstallation(directory, { onProgress }); } function snapshotPersistentData(dataRoot) { assertLocalTree(dataRoot); const databaseFile = path7.join(dataRoot, "workbench.sqlite"), tables = {}; if (fs7.existsSync(databaseFile)) { ownedChild(dataRoot, "workbench.sqlite"); const database = new DatabaseSync(databaseFile, { readOnly: true }); try { for (const { name } of database.prepare("SELECT name FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all()) { if (!/^[a-z_]+$/.test(name)) throw fail("\u539F\u6570\u636E\u5E93\u5305\u542B\u65E0\u6CD5\u6838\u5BF9\u7684\u8868\u540D\u3002"); const rows = database.prepare('SELECT * FROM "' + name + '"').all().filter((row) => !(name === "metadata" && row.key === "runtimeOwner")); const hashes = rows.map((row) => digest(JSON.stringify(canonicalHost(row)))).sort(); tables[name] = { count: hashes.length, hashes }; } } finally { database.close(); } } const artifacts = [], artifactRoot = path7.join(dataRoot, "artifacts"); if (fs7.existsSync(artifactRoot)) { const walk = (relative) => { for (const entry of fs7.readdirSync(path7.join(artifactRoot, relative), { withFileTypes: true })) { const next = path7.posix.join(relative, entry.name), file = ownedChild(dataRoot, "artifacts/" + next); if (entry.isDirectory()) walk(next); else if (entry.isFile()) { const bytes = fs7.readFileSync(file); artifacts.push({ path: next, bytes: bytes.length, sha256: digest(bytes) }); } else throw fail("\u539F\u5DE5\u4EF6\u76EE\u5F55\u5305\u542B\u975E\u5E38\u89C4\u6587\u4EF6\u3002"); } }; walk(""); } const files = ["config.json", "projects.json"].filter((relative) => fs7.existsSync(path7.join(dataRoot, relative))).map((relative) => ({ path: relative, sha256: digest(fs7.readFileSync(ownedChild(dataRoot, relative))) })); return { tables, artifacts: artifacts.sort((a, b) => a.path.localeCompare(b.path)), files, scope: "Every persistent database row except runtimeOwner, every original artifact byte and existing public config/project files; no credential is decrypted or returned." }; } var InstallationManager = class { constructor({ installRoot, dataRoot, port = 4318, candidateRoot = null, timeoutMs = 6e4, operationId = null, expectedManifestSha256 = null, onProgress = null }) { for (const value of [installRoot, dataRoot]) if (typeof value !== "string" || !path7.isAbsolute(value)) throw fail("\u5B89\u88C5\u548C\u6570\u636E\u76EE\u5F55\u5FC5\u987B\u4E3A\u672C\u673A\u7EDD\u5BF9\u8DEF\u5F84\u3002"); if (inside(installRoot, dataRoot) || inside(dataRoot, installRoot) || !Number.isInteger(port) || port < 1 || port > 65535) throw fail("\u7A0B\u5E8F\u4E0E\u7528\u6237\u6570\u636E\u9700\u8981\u72EC\u7ACB\u76EE\u5F55\u53CA\u6709\u6548\u672C\u673A\u7AEF\u53E3\u3002"); assertLocalTree(installRoot, { missing: true }); assertLocalTree(dataRoot, { missing: true }); fs7.mkdirSync(installRoot, { recursive: true }); fs7.mkdirSync(dataRoot, { recursive: true }); this.installRoot = fs7.realpathSync.native(installRoot); this.dataRoot = fs7.realpathSync.native(dataRoot); this.port = port; this.timeoutMs = timeoutMs; this.candidateRoot = candidateRoot ? fs7.realpathSync.native(candidateRoot) : null; this.recordFile = ownedChild(this.installRoot, "current.json", { missing: true }); this.stateRoot = ownedChild(this.installRoot, ".installation", { missing: true }); fs7.mkdirSync(this.stateRoot, { recursive: true }); protectUserDirectory(this.stateRoot); this.progressOptions = { operationId, expectedManifestSha256, onProgress }; if (expectedManifestSha256 !== null && !/^[a-f0-9]{64}$/.test(expectedManifestSha256)) throw fail("\u5B89\u88C5\u5019\u9009\u6E05\u5355\u8EAB\u4EFD\u65E0\u6548\u3002"); } async operation(command2, action) { return this.lock(async () => { const progress = new InstallationProgress({ stateRoot: this.stateRoot, installRoot: this.installRoot, dataRoot: this.dataRoot, command: command2, ...this.progressOptions }); this.progress = progress; this.receiptFile = null; try { const result = await action(); try { progress.finish(command2 === "preflight" ? "ready-to-copy" : command2 === "cancel" ? "cancelled" : result.phase === "staged" ? "staged" : command2 === "uninstall" ? "uninstall-ready" : "completed", { activeVersion: result.active?.version ?? result.current?.version ?? result.candidate?.version ?? null, receiptFile: result.receiptFile ?? null }); } catch (error) { if (command2 === "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: fs7.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 (!fs7.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("\u5F53\u524D\u5B89\u88C5\u767B\u8BB0\u65E0\u6CD5\u6838\u5BF9\uFF0C\u4FDD\u7559\u539F\u8BB0\u5F55\u3002"); 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("\u5F53\u524D\u6D3B\u52A8\u7248\u672C\u7684\u5B9E\u9645\u7A0B\u5E8F\u4E0E\u539F\u767B\u8BB0\u4E0D\u540C\u3002"); if (value.previous) this.versionRoot(value.previous); return value; } versionRoot(version) { if (!version || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/.test(version.directory ?? "") || !/^\d+\.\d+\.\d+$/.test(version.version ?? "") || !/^[a-f0-9]{64}$/.test(version.manifestSha256 ?? "") || !/^[a-f0-9]{64}$/.test(version.runtimeIdentity ?? "")) throw fail("\u539F\u6D3B\u52A8\u7248\u672C\u767B\u8BB0\u65E0\u6548\u3002"); return ownedChild(this.installRoot, "versions/" + version.directory); } candidate() { if (!this.candidateRoot) throw fail("\u6CA1\u6709\u6307\u5B9A\u72EC\u7ACB\u5B89\u88C5\u5019\u9009\u3002"); const expected = path7.join(this.installRoot, "versions", path7.basename(this.candidateRoot)); if (!samePath(expected, this.candidateRoot)) throw fail("\u65B0\u7248\u672C\u53EA\u80FD\u4F4D\u4E8E\u5F53\u524D\u5B89\u88C5\u7684\u72EC\u7ACBversions\u76EE\u5F55\u3002"); 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("\u65B0\u5019\u9009\u4E0E\u672C\u6B21\u5B89\u88C5\u5668\u56FA\u5B9A\u7684\u539F\u6E05\u5355\u4E0D\u540C\u3002"); this.progress?.candidate(identity); return { directory: path7.basename(identity.root), version: identity.version, manifestSha256: identity.manifestSha256, runtimeIdentity: identity.identitySha256 }; } async host() { const infoFile = ownedChild(this.dataRoot, "service-info.json", { missing: true }); if (!fs7.existsSync(infoFile)) { await this.assertFreePort(); return null; } const info = readState(infoFile), actual = observeWindowsProcess(info.pid); if (!actual || info.createdAt && info.createdAt !== actual.createdAt) { await this.assertFreePort(); return null; } if (!info.instanceId || !info.createdAt || !info.runtimeIdentity || !info.runtimeRoot || info.port !== this.port || !samePath(info.dataRoot ?? "", this.dataRoot)) throw fail("\u65E7\u6267\u884C\u5BBF\u4E3B\u6CA1\u6709\u53EF\u6838\u9A8C\u7684\u684C\u9762\u8EAB\u4EFD\u3002\u53EF\u5148\u6682\u5B58\u5B89\u88C5\u5019\u9009\uFF0C\u518D\u901A\u8FC7\u4FDD\u7559\u72B6\u6001\u7684\u5347\u7EA7\u6D41\u7A0B\u63A5\u5165\u3002"); const controller = new HostController({ appRoot: info.runtimeRoot, dataRoot: this.dataRoot, port: this.port, nodePath: process.execPath, timeoutMs: this.timeoutMs }); const connected = await controller.connect(); if (!connected) throw fail("\u539F\u6267\u884C\u8FDB\u7A0B\u4ECD\u6D3B\u52A8\uFF0C\u63A5\u53E3\u5C1A\u4E0D\u53EF\u6838\u5BF9\u3002"); const status = await controller.status(); if (status.state !== "ready" || status.activity.active || status.desktopWindows.count) throw fail("\u5148\u7B49\u5F85\u539F\u4EFB\u52A1\u3001\u5BA1\u6279\u3001\u5DE5\u5177\u6216\u6A21\u578B\u8BF7\u6C42\u7ED3\u675F\uFF0C\u5E76\u5173\u95ED\u684C\u9762\u7A97\u53E3\uFF1B\u540E\u53F0\u5BBF\u4E3B\u53EF\u4FDD\u6301\u8FD0\u884C\u3002"); return { controller, identity: connected.identity, status }; } async assertFreePort() { await new Promise((resolve, reject) => { const socket = net.createConnection({ host: "127.0.0.1", port: this.port }); socket.setTimeout(1500); socket.once("connect", () => { socket.destroy(); reject(fail("\u672C\u673A\u7AEF\u53E3\u88AB\u672A\u77E5\u6216\u672A\u767B\u8BB0\u670D\u52A1\u5360\u7528\uFF0C\u4FDD\u7559\u539F\u5B89\u88C5\u3002")); }); socket.once("timeout", () => { socket.destroy(); reject(fail("\u539F\u7AEF\u53E3\u72B6\u6001\u65E0\u6CD5\u6838\u5BF9\u3002")); }); socket.once("error", (error) => { socket.destroy(); error.code === "ECONNREFUSED" ? resolve() : reject(fail("\u539F\u7AEF\u53E3\u72B6\u6001\u65E0\u6CD5\u6838\u5BF9\u3002")); }); }); } async lock(action) { const directory = ownedChild(this.stateRoot, "operation.lock", { missing: true }), nonce = randomUUID4(), observed = observeWindowsProcess(process.pid); try { fs7.mkdirSync(directory); } catch (error) { if (error.code !== "EEXIST") throw error; const owner = readState(ownedChild(directory, "owner.json"), 16384), actual = observeWindowsProcess(owner.pid); if (actual && actual.createdAt === owner.createdAt) throw fail("\u539F\u5B89\u88C5\u64CD\u4F5C\u4ECD\u5728\u8FD0\u884C\u3002"); const archive = ownedChild(this.stateRoot, "stale-lock-" + randomUUID4(), { missing: true }); fs7.renameSync(directory, archive); fs7.mkdirSync(directory); } protectUserDirectory(directory); const file = path7.join(directory, "owner.json"); writeState(file, { nonce, pid: process.pid, createdAt: observed.createdAt, userSid: observed.userSid }); try { return await action(); } finally { if (fs7.existsSync(file) && readState(file).nonce === nonce) { fs7.unlinkSync(file); fs7.rmdirSync(directory); } } } async preflight({ stageOnly = false } = {}) { return this.operation("preflight", async () => { const current = this.current(); this.phase("inspect-root"); this.inspectRoot(current); this.phase("inspect-host"); const host = stageOnly ? null : await this.host(); return { allowed: true, phase: stageOnly ? "stage-only" : "preflight", current: current?.active ?? null, host: host ? { pid: host.identity.pid, instanceId: host.identity.instanceId, unresolvedTools: host.status.activity.unresolvedTools } : null, dataRoot: this.dataRoot, dataPolicy: "preserve-original-data" }; }); } inspectRoot(current) { for (const entry of fs7.readdirSync(this.installRoot, { withFileTypes: true })) { ownedChild(this.installRoot, entry.name); if (!(entry.isDirectory() && [".installation", "versions"].includes(entry.name) || entry.isFile() && (["current.json", "AgentWorkbench.exe"].includes(entry.name) || /^unins\d{3}\.(exe|dat|msg)$/.test(entry.name)))) throw fail("\u7A0B\u5E8F\u6839\u76EE\u5F55\u5B58\u5728\u672A\u767B\u8BB0\u5185\u5BB9\uFF0C\u4E0D\u8986\u76D6\u539F\u76EE\u5F55\u3002"); } const bootstrap = ownedChild(this.installRoot, "AgentWorkbench.exe", { missing: true }); if (fs7.existsSync(bootstrap)) { const root = current ? this.versionRoot(current.active) : this.candidateRoot; if (!root || binaryIdentity(bootstrap).sha256 !== binaryIdentity(ownedChild(root, "AgentWorkbench.exe")).sha256) throw fail("\u539F\u6839\u542F\u52A8\u5668\u4E0E\u6240\u5C5E\u53D1\u884C\u4E0D\u4E00\u81F4\uFF0C\u4E0D\u590D\u7528\u6216\u8986\u76D6\u672A\u77E5\u7A0B\u5E8F\u3002"); } } async activate({ stageOnly = false, beforePointer = null, afterPointer = null } = {}) { return this.operation("activate", async () => { const candidate = this.candidate(), old = this.current(); this.inspectRoot(old); const priorHost = stageOnly ? null : await this.host(); this.phase("snapshot-data"); const snapshot = snapshotPersistentData(this.dataRoot), id = randomUUID4(), receiptFile = path7.join(this.stateRoot, "operation-" + id + ".json"); this.receiptFile = receiptFile; const receipt = { schema: 1, id, operationId: this.progress?.value.id, state: "prepared", candidate, original: old?.active ?? null, dataRoot: this.dataRoot, snapshot, stageOnly, startedAt: (/* @__PURE__ */ new Date()).toISOString() }; writeState(receiptFile, receipt); if (stageOnly) { writeState(receiptFile, { ...receipt, state: "staged" }); return { phase: "staged", candidate, receiptFile, activated: false }; } let upgraded = false, next = null, pointerPublished = false; const originalPointer = old ? fs7.readFileSync(this.recordFile) : null; const bootstrapFile = ownedChild(this.installRoot, "AgentWorkbench.exe", { missing: true }); const originalBootstrap = fs7.existsSync(bootstrapFile) ? fs7.readFileSync(bootstrapFile) : null; const candidateBootstrap = fs7.readFileSync(ownedChild(this.candidateRoot, "AgentWorkbench.exe")); let bootstrapPublished = false; const replaceBootstrap = (bytes) => { const temporary = ownedChild(this.stateRoot, "bootstrap-" + randomUUID4() + ".tmp", { missing: true }); const descriptor = fs7.openSync(temporary, "wx", 384); try { fs7.writeFileSync(descriptor, bytes); fs7.fsyncSync(descriptor); } finally { fs7.closeSync(descriptor); } try { fs7.renameSync(temporary, bootstrapFile); } finally { if (fs7.existsSync(temporary)) fs7.unlinkSync(temporary); } }; try { if (priorHost && !samePath(priorHost.identity.runtimeRoot, this.candidateRoot)) { this.phase("retain-host", { pid: priorHost.identity.pid }); await upgradeRunning({ url: priorHost.controller.url, pid: priorHost.identity.pid, currentRoot: priorHost.identity.appRoot, handlerRoot: priorHost.identity.runtimeRoot, newRoot: this.candidateRoot }); upgraded = true; const nextHost = await this.host(); if (!nextHost || nextHost.identity.pid !== priorHost.identity.pid || nextHost.identity.instanceId !== priorHost.identity.instanceId || nextHost.identity.runtimeIdentity !== candidate.runtimeIdentity) throw fail("\u65B0\u5904\u7406\u5668\u6CA1\u6709\u4FDD\u6301\u539F\u5BBF\u4E3B\u5B9E\u4F8B\u3002"); } this.phase("verify-data"); const after = snapshotPersistentData(this.dataRoot); if (!isDeepStrictEqual(snapshot, after)) throw fail("\u5B89\u88C5\u66F4\u65B0\u6539\u53D8\u4E86\u539F\u6301\u4E45\u884C\u6216\u5DE5\u4EF6\u3002"); if (beforePointer) await beforePointer(); if (!isDeepStrictEqual(old, this.current())) throw fail("\u539F\u5B89\u88C5\u6307\u9488\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u505C\u6B62\u53D1\u5E03\u5019\u9009\u3002"); if (!isDeepStrictEqual(candidate, this.candidate())) throw fail("\u65B0\u5019\u9009\u5728\u9884\u68C0\u540E\u53D1\u751F\u53D8\u5316\uFF0C\u505C\u6B62\u53D1\u5E03\u5019\u9009\u3002"); this.phase("publish-pointer", { interruptible: false }); const actualBootstrap = fs7.existsSync(bootstrapFile) ? fs7.readFileSync(bootstrapFile) : null; if (!isDeepStrictEqual(actualBootstrap, originalBootstrap)) throw fail("\u539F\u542F\u52A8\u5668\u5728\u9884\u68C0\u540E\u53D1\u751F\u53D8\u5316\uFF0C\u505C\u6B62\u53D1\u5E03\u5019\u9009\u3002"); if (!isDeepStrictEqual(originalBootstrap, candidateBootstrap)) { replaceBootstrap(candidateBootstrap); bootstrapPublished = true; } next = { schema: 1, app: "agent-workbench-installation", installId: old?.installId ?? randomUUID4(), revision: (old?.revision ?? 0) + 1, dataRoot: this.dataRoot, port: this.port, active: candidate, previous: old?.active ?? null, activatedAt: (/* @__PURE__ */ new Date()).toISOString() }; writeState(this.recordFile, next); pointerPublished = true; this.phase("verify-publication", { interruptible: false }); if (afterPointer) await afterPointer(); this.inspectRoot(next); writeState(receiptFile, { ...receipt, state: "activated", hostRetained: upgraded, finishedAt: (/* @__PURE__ */ 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 && fs7.existsSync(this.recordFile)) { if (!isDeepStrictEqual(readState(this.recordFile), next)) throw fail("\u53D1\u5E03\u540E\u7684\u6307\u9488\u88AB\u5176\u4ED6\u64CD\u4F5C\u6539\u53D8\uFF0C\u4E0D\u80FD\u8986\u76D6\u672A\u77E5\u8BB0\u5F55\u3002"); if (originalPointer) { const temporary = ownedChild(this.installRoot, ".rollback-" + id + ".json", { missing: true }); fs7.writeFileSync(temporary, originalPointer, { flag: "wx" }); fs7.renameSync(temporary, this.recordFile); } else fs7.unlinkSync(this.recordFile); } else if (pointerPublished && old) throw fail("\u53D1\u5E03\u540E\u7684\u6307\u9488\u5DF2\u4E22\u5931\uFF0C\u56DE\u9000\u9700\u8981\u6838\u5BF9\u3002"); if (bootstrapPublished) { if (!fs7.existsSync(bootstrapFile) || !fs7.readFileSync(bootstrapFile).equals(candidateBootstrap)) throw fail("\u53D1\u5E03\u540E\u7684\u542F\u52A8\u5668\u88AB\u5176\u4ED6\u64CD\u4F5C\u6539\u53D8\uFF0C\u4E0D\u80FD\u8986\u76D6\u672A\u77E5\u7A0B\u5E8F\u3002"); if (originalBootstrap) replaceBootstrap(originalBootstrap); else fs7.unlinkSync(bootstrapFile); } if (upgraded) { await upgradeRunning({ url: priorHost.controller.url, pid: priorHost.identity.pid, currentRoot: priorHost.identity.appRoot, handlerRoot: this.candidateRoot, newRoot: priorHost.identity.runtimeRoot }); const restored = await priorHost.controller.connect(); if (!restored || restored.identity.instanceId !== priorHost.identity.instanceId || restored.identity.pid !== priorHost.identity.pid) throw fail("\u539F\u5BBF\u4E3B\u56DE\u9000\u4ECD\u9700\u6838\u5BF9\u3002"); rollback = "original-host-and-pointer-restored"; } if (!isDeepStrictEqual(snapshot, snapshotPersistentData(this.dataRoot)) || old && !fs7.readFileSync(this.recordFile).equals(originalPointer)) throw fail("\u539F\u6301\u4E45\u6570\u636E\u6216\u5B89\u88C5\u6307\u9488\u56DE\u9000\u4ECD\u9700\u6838\u5BF9\u3002"); if (!isDeepStrictEqual(fs7.existsSync(bootstrapFile) ? fs7.readFileSync(bootstrapFile) : null, originalBootstrap)) throw fail("\u539F\u542F\u52A8\u5668\u56DE\u9000\u4ECD\u9700\u6838\u5BF9\u3002"); } catch (rollbackError) { try { writeState(receiptFile, { ...receipt, state: "rollback-unverified", error: error.message, rollbackError: rollbackError.message }); } catch { } throw fail("\u5B89\u88C5\u5931\u8D25\uFF0C\u539F\u5BBF\u4E3B\u6216\u6307\u9488\u56DE\u9000\u5C1A\u5F85\u6838\u5BF9\u3002\u8BF7\u4FDD\u7559\u539F\u64CD\u4F5C\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u65B0\u6267\u884C\u4EFB\u52A1\u3002"); } try { writeState(receiptFile, { ...receipt, state: "failed", error: error.message, rollback }); } catch { } throw error; } }); } async prepareUninstall() { return this.operation("uninstall", async () => { const current = this.current(); if (!current) throw fail("\u6CA1\u6709\u53EF\u6838\u5BF9\u7684\u672C\u4EA7\u54C1\u5B89\u88C5\u767B\u8BB0\u3002"); this.inspectRoot(current); this.phase("snapshot-data"); const snapshot = snapshotPersistentData(this.dataRoot); this.phase("inspect-host"); const host = await this.host(); if (host) await host.controller.stop(); if (!isDeepStrictEqual(snapshot, snapshotPersistentData(this.dataRoot))) throw fail("\u505C\u6B62\u540E\u539F\u6301\u4E45\u6570\u636E\u53D8\u5316\uFF0C\u5378\u8F7D\u4ECD\u9700\u6838\u5BF9\u3002"); const receiptFile = path7.join(this.stateRoot, "uninstall-" + randomUUID4() + ".json"); const result = { allowed: true, phase: "uninstall-ready", dataRoot: this.dataRoot, dataPolicy: "preserve-original-data", hostExited: !!host, active: current.active, snapshot }; writeState(receiptFile, result); if (!isDeepStrictEqual(current, this.current())) throw fail("\u5378\u8F7D\u671F\u95F4\u539F\u6307\u9488\u53D1\u751F\u53D8\u5316\uFF0C\u4FDD\u7559\u539F\u8BB0\u5F55\u3002"); fs7.renameSync(this.recordFile, ownedChild(this.stateRoot, "uninstalled-" + current.installId + "-" + current.revision + ".json", { missing: true })); return { ...result, snapshot: void 0, receiptFile }; }); } }; // src/desktop/install-cli.mjs var args = process.argv.slice(2); var command = args.shift(); var 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] !== void 0) 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 ? ` \xB7 ${counts.completedFiles}/${counts.totalFiles} \u6587\u4EF6` + (counts.completedBytes !== null ? ` \xB7 ${counts.completedBytes}/${counts.totalBytes} \u5B57\u8282` : "") + (counts.currentPath ? " \xB7 " + 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; }