"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key2 of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key2) && key2 !== except) __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // src/desktop/main.mjs var import_electron2 = require("electron"); var import_node_fs8 = __toESM(require("node:fs"), 1); var import_node_path10 = __toESM(require("node:path"), 1); var import_node_os = __toESM(require("node:os"), 1); var import_node_crypto7 = require("node:crypto"); // src/core/desktop/host-controller.mjs var import_node_fs4 = __toESM(require("node:fs"), 1); var import_node_path5 = __toESM(require("node:path"), 1); var import_node_child_process2 = require("node:child_process"); var import_node_crypto5 = require("node:crypto"); var import_promises = require("node:timers/promises"); // src/shared/contracts/desktop-host.mjs var import_node_crypto = require("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((key2) => [key2, canonicalHost(value[key2])])) : 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 (0, import_node_crypto.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 (!(0, import_node_crypto.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 var import_node_path = __toESM(require("node:path"), 1); 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: [import_node_path.default.dirname(process.execPath), inheritedPath].filter(Boolean).join(import_node_path.default.delimiter), ...extra }; } // src/core/desktop/process-identity.mjs var import_node_fs2 = __toESM(require("node:fs"), 1); var import_node_path3 = __toESM(require("node:path"), 1); var import_node_child_process = require("node:child_process"); var import_node_crypto3 = require("node:crypto"); // src/core/desktop/file-state.mjs var import_node_fs = __toESM(require("node:fs"), 1); var import_node_path2 = __toESM(require("node:path"), 1); var import_node_crypto2 = require("node:crypto"); var normalized = (value) => process.platform === "win32" ? value.toLowerCase() : value; var samePath = (a, b) => normalized(import_node_path2.default.resolve(a)) === normalized(import_node_path2.default.resolve(b)); function assertLocalTree(absolute, { missing = false } = {}) { const resolved = import_node_path2.default.resolve(absolute), parsed = import_node_path2.default.parse(resolved); let current = parsed.root; const components = resolved.slice(parsed.root.length).split(import_node_path2.default.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 = import_node_path2.default.join(current, component); let stat; try { stat = import_node_fs.default.lstatSync(current); } catch (cause) { if (missing && cause.code === "ENOENT") return resolved; throw cause; } if (stat.isSymbolicLink() || !samePath(current, import_node_fs.default.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 = import_node_fs.default.realpathSync.native(root), target = import_node_path2.default.resolve(base, relative); if (import_node_path2.default.isAbsolute(relative) || import_node_path2.default.win32.isAbsolute(relative) || relative.includes("\0") || !normalized(target).startsWith(normalized(base + import_node_path2.default.sep))) throw hostError("\u672C\u673A\u72B6\u6001\u8DEF\u5F84\u8D85\u51FA\u6240\u5C5E\u76EE\u5F55\u3002"); let existing = target; while (!import_node_fs.default.existsSync(existing)) { if (!missing) throw hostError("\u672C\u673A\u72B6\u6001\u6587\u4EF6\u4E0D\u5B58\u5728\u3002", "HOST_REGISTRATION_MISSING"); const parent = import_node_path2.default.dirname(existing); if (parent === existing) throw hostError("\u672C\u673A\u72B6\u6001\u8DEF\u5F84\u65E0\u6CD5\u6838\u5BF9\u3002"); existing = parent; } const real = import_node_fs.default.realpathSync.native(existing); if (!samePath(base, real) && !normalized(real).startsWith(normalized(base + import_node_path2.default.sep))) throw hostError("\u672C\u673A\u72B6\u6001\u94FE\u63A5\u8D85\u51FA\u6240\u5C5E\u76EE\u5F55\u3002"); if (import_node_fs.default.lstatSync(existing).isSymbolicLink()) throw hostError("\u672C\u673A\u72B6\u6001\u4E0D\u63A5\u53D7\u94FE\u63A5\u6216\u91CD\u89E3\u6790\u76EE\u5F55\u3002"); const stat = import_node_fs.default.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 = import_node_fs.default.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(import_node_fs.default.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 = import_node_path2.default.dirname(file), temporary = import_node_path2.default.join(directory, "." + import_node_path2.default.basename(file) + "-" + (0, import_node_crypto2.randomUUID)() + ".tmp"); if (import_node_fs.default.existsSync(file)) readState(file); try { const descriptor = import_node_fs.default.openSync(temporary, "wx", 384); try { import_node_fs.default.writeFileSync(descriptor, JSON.stringify(value, null, 2) + "\n"); import_node_fs.default.fsyncSync(descriptor); } finally { import_node_fs.default.closeSync(descriptor); } assertLocalTree(file, { missing: true }); import_node_fs.default.renameSync(temporary, file); } finally { if (import_node_fs.default.existsSync(temporary)) import_node_fs.default.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 { (0, import_node_child_process.execFileSync)( import_node_path3.default.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 shell2 = import_node_path3.default.join(process.env.SystemRoot || "C:\\Windows", "System32/WindowsPowerShell/v1.0/powershell.exe"); const output = (0, import_node_child_process.execFileSync)( shell2, ["-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 || !import_node_fs2.default.existsSync(value.executable)) throw new Error("Invalid observation"); return { ...value, executable: import_node_fs2.default.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 = import_node_fs2.default.realpathSync.native(file), stat = import_node_fs2.default.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: (0, import_node_crypto3.createHash)("sha256").update(import_node_fs2.default.readFileSync(absolute)).digest("hex") }; } // src/core/desktop/app-installation.mjs var import_node_fs3 = __toESM(require("node:fs"), 1); var import_node_path4 = __toESM(require("node:path"), 1); var import_node_crypto4 = require("node:crypto"); function inspectHostInstallation(directory, { full = false, onProgress = null } = {}) { assertLocalTree(directory); const root = import_node_fs3.default.realpathSync.native(import_node_path4.default.resolve(directory)); if (!import_node_fs3.default.statSync(root).isDirectory()) throw hostError("\u5BBF\u4E3B\u5B89\u88C5\u76EE\u5F55\u65E0\u6548\u3002"); const digest = (value) => (0, import_node_crypto4.createHash)("sha256").update(value).digest("hex"); const manifestFile = import_node_path4.default.join(root, "MANIFEST.json"), manifest = import_node_fs3.default.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 ?? (import_node_fs3.default.existsSync(import_node_path4.default.join(root, "package.json")) ? readState(import_node_path4.default.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 || import_node_fs3.default.existsSync(import_node_path4.default.join(root, "dist-server/host-launcher.mjs"))) files.add("dist-server/host-launcher.mjs"); if (import_node_fs3.default.existsSync(import_node_path4.default.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 (import_node_fs3.default.existsSync(import_node_path4.default.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 import_node_fs3.default.readdirSync(import_node_path4.default.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(import_node_fs3.default.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: port2 = 4318, nodePath = null, timeoutMs = 45e3, environment = {} }) { if (!Number.isInteger(port2) || port2 < 1 || port2 > 65535 || typeof dataRoot2 !== "string" || !import_node_path5.default.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 }); import_node_fs4.default.mkdirSync(dataRoot2, { recursive: true }); this.dataRoot = import_node_fs4.default.realpathSync.native(dataRoot2); const bundled = import_node_path5.default.join(this.appRoot, "runtime/node.exe"); const executable = nodePath ?? (import_node_fs4.default.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 = (0, import_node_child_process2.execFileSync)(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 = port2; this.url = "http://127.0.0.1:" + port2; this.timeoutMs = Math.min(6e4, Math.max(1e3, timeoutMs)); const allowed = new Set(HOST_ENVIRONMENT); if (Object.keys(environment).some((key2) => !allowed.has(key2) || typeof environment[key2] !== "string" || !import_node_path5.default.isAbsolute(environment[key2]))) 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 = (0, import_node_crypto5.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 = (0, import_node_crypto5.randomUUID)(), observed = observeWindowsProcess(process.pid); const deadline = Date.now() + this.timeoutMs; while (true) { try { import_node_fs4.default.mkdirSync(lockDirectory, { mode: 448 }); break; } catch (cause) { if (cause.code !== "EEXIST") throw cause; ownedChild(this.dataRoot, ".desktop-launch.lock"); const ownerFile2 = import_node_path5.default.join(lockDirectory, "owner.json"); if (import_node_fs4.default.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-" + (0, import_node_crypto5.randomUUID)(), { missing: true }); try { import_node_fs4.default.renameSync(lockDirectory, archive); } catch (error) { if (!["ENOENT", "EEXIST"].includes(error.code)) throw error; } continue; } } else if (Date.now() - import_node_fs4.default.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 (0, import_promises.setTimeout)(100); } } const ownerFile = import_node_path5.default.join(lockDirectory, "owner.json"); try { writeState(ownerFile, { schema: 1, pid: process.pid, createdAt: observed.createdAt, userSid: observed.userSid, nonce }); return await action(); } finally { if (import_node_fs4.default.existsSync(ownerFile) && readState(ownerFile).nonce === nonce) { import_node_fs4.default.unlinkSync(ownerFile); import_node_fs4.default.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 (import_node_fs4.default.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 (!import_node_fs4.default.existsSync(logs)) import_node_fs4.default.mkdirSync(logs); const id = (0, import_node_crypto5.randomUUID)(), stdoutPath = import_node_path5.default.join(logs, "desktop-host-" + id + "-stdout.log"), stderrPath = import_node_path5.default.join(logs, "desktop-host-" + id + "-stderr.log"); let output, errors, child; try { output = import_node_fs4.default.openSync(stdoutPath, "wx", 384); errors = import_node_fs4.default.openSync(stderrPath, "wx", 384); child = (0, import_node_child_process2.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) import_node_fs4.default.closeSync(output); if (errors !== void 0) import_node_fs4.default.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 (0, import_promises.setTimeout)(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 (0, import_promises.setTimeout)(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/core/desktop/desktop-bridge.mjs var import_node_fs7 = __toESM(require("node:fs"), 1); var import_node_path8 = __toESM(require("node:path"), 1); var import_node_crypto6 = require("node:crypto"); // src/server/files.mjs var import_node_fs6 = __toESM(require("node:fs"), 1); var import_node_path7 = __toESM(require("node:path"), 1); // src/shared/contracts/workspaces.mjs var import_node_fs5 = __toESM(require("node:fs"), 1); var import_node_path6 = __toESM(require("node:path"), 1); var conflict = (message) => Object.assign(new Error(message), { status: 409 }); var key = (value) => process.platform === "win32" ? import_node_path6.default.resolve(value).toLowerCase() : import_node_path6.default.resolve(value); var same = (a, b) => key(a) === key(b); function controlFile(file) { const stat = import_node_fs5.default.lstatSync(file); if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 4096) throw conflict("\u9694\u79BB\u5DE5\u4F5C\u533A\u7684Git\u8EAB\u4EFD\u6587\u4EF6\u5DF2\u53D8\u5316\uFF0C\u8BF7\u6838\u5BF9\u539F\u5DE5\u4F5C\u533A\u3002"); return import_node_fs5.default.readFileSync(file, "utf8").trim(); } function assertWorkspacePath(project) { if (!project.workspace) return; const identity = project.workspace; if (!identity.gitDir || !identity.commonGitDir || !identity.branch) throw conflict("\u9694\u79BB\u5DE5\u4F5C\u533A\u7F3A\u5C11\u5DF2\u9A8C\u8BC1\u7684Git\u8EAB\u4EFD\u3002"); const root = import_node_fs5.default.lstatSync(project.root); if (!root.isDirectory() || root.isSymbolicLink() || !same(import_node_fs5.default.realpathSync.native(project.root), project.root)) throw conflict("\u9694\u79BB\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5DF2\u53D8\u5316\uFF0C\u4E0D\u80FD\u7EE7\u7EED\u4F7F\u7528\u65E7\u9879\u76EE\u8EAB\u4EFD\u3002"); if (!key(identity.gitDir).startsWith(key(import_node_path6.default.join(identity.commonGitDir, "worktrees")) + import_node_path6.default.sep) || !same(import_node_fs5.default.realpathSync.native(identity.gitDir), identity.gitDir) || !same(import_node_fs5.default.realpathSync.native(identity.commonGitDir), identity.commonGitDir)) throw conflict("\u9694\u79BB\u5DE5\u4F5C\u533AGit\u7BA1\u7406\u76EE\u5F55\u4E0E\u6765\u6E90\u4E0D\u5339\u914D\u3002"); const gitFile = import_node_path6.default.join(project.root, ".git"), match = controlFile(gitFile).match(/^gitdir: (.+)$/); if (!match || !same(import_node_path6.default.resolve(project.root, match[1]), identity.gitDir) || !same(controlFile(import_node_path6.default.join(identity.gitDir, "gitdir")), gitFile) || !same(import_node_path6.default.resolve(identity.gitDir, controlFile(import_node_path6.default.join(identity.gitDir, "commondir"))), identity.commonGitDir) || controlFile(import_node_path6.default.join(identity.gitDir, "HEAD")) !== "ref: refs/heads/" + identity.branch) throw conflict( "\u9694\u79BB\u5DE5\u4F5C\u533A\u7684\u76EE\u5F55\u3001Git\u767B\u8BB0\u6216\u5206\u652F\u5DF2\u88AB\u5916\u90E8\u4FEE\u6539\uFF0C\u8BF7\u4FDD\u7559\u73B0\u573A\u5E76\u6838\u5BF9\u540E\u91CD\u65B0\u6253\u5F00\u3002" ); } // node_modules/smol-toml/dist/stringify.js var HAS_WELLFORMED = !!"".isWellFormed; // src/core/python-runtime.mjs var import_node_child_process3 = require("node:child_process"); var import_node_util = require("node:util"); var executeFile = (0, import_node_util.promisify)(import_node_child_process3.execFile); // src/shared/contracts/task-control.mjs var DIAGNOSTIC_TOOLS = /* @__PURE__ */ new Set([ "diagnose_environment", "inspect_session", "inspect_project", "list_files", "read_file", "search_files", "read_artifact", "inspect_task_plan", "read_browser_result", "read_registered_skill", "inspect_engine_checks", "list_research_targets", "read_research_evidence" ]); DIAGNOSTIC_TOOLS.add("inspect_browser_tabs"); // src/shared/contracts/execution.mjs var CORE_KINDS = ["task", "run", "step", "tool", "artifact", "check_plan", "check_job", "delivery_plan", "delivery_job", "change_set", "context_plan", "workspace", "research_target", "research_job", "engine_job", "engine_run", "browser_plan", "browser_job", "task_plan", "task_proof", "memory", "task_checkpoint", "mcp_job", "collaboration", "worker", "input_attachment"]; CORE_KINDS.push("resume_plan"); CORE_KINDS.push("evaluation"); CORE_KINDS.push("environment_diagnostic", "environment_plan", "environment_job"); CORE_KINDS.push("preview_plan", "preview_job"); CORE_KINDS.push("browsing_profile", "browsing_tab", "browsing_observation", "browsing_action"); CORE_KINDS.push("file_result"); // src/shared/contracts/engines.mjs var ENGINE_LIMITS = Object.freeze([ "\u5F53\u524D\u63A5\u5165\u6838\u9A8C\u542F\u52A8\u3001\u4F1A\u8BDD\u76EE\u5F55\u3001\u534F\u8BAE\u9519\u8BEF\u548C\u5173\u95ED\uFF1B\u5DE5\u7A0B\u6267\u884C\u63A5\u5165\u5F00\u53D1\u4E2D\u3002", "SDK\u6CA1\u6709\u5355\u4F1A\u8BDDcancel\u6216close\uFF1B\u505C\u6B62\u4EE5\u6240\u5C5E\u72EC\u7ACB\u8FDB\u7A0B\u4E3A\u5355\u4F4D\u3002", "SDK serverInfo.version\u4E0E\u53D1\u884C\u5305\u7248\u672C\u5206\u522B\u6838\u5BF9\uFF0C\u6CA1\u6709\u6709\u6548\u534F\u8BAE\u7248\u672C\u534F\u5546\u3002", "SDK\u4E8B\u4EF6\u8986\u76D6\u8FD0\u884C\u65F6\u4F1A\u8BDD\u6811\uFF0Cidle\u4E8B\u4EF6\u4E0D\u80FD\u76F4\u63A5\u5224\u9879\u76EE\u4EA4\u4ED8\u5B8C\u6210\u3002" ]); // src/core/tools/mcp-contract.mjs var MCP_LIMITS = Object.freeze({ registrations: 16, tools: 100, allowedTools: 12, pages: 4, catalogBytes: 262144, resultBytes: 1048576, argumentBytes: 16e3 }); // src/core/storage/state-database.mjs var import_node_sqlite = require("node:sqlite"); // src/shared/contracts/research.mjs var MAXIMUM_RESEARCH_BYTES = 512 * 1024 * 1024; // src/shared/contracts/browser.mjs var BROWSER_LIMITS = Object.freeze({ files: 512, bytes: 32 * 1024 * 1024, fileBytes: 8 * 1024 * 1024, steps: 20, durationMs: 45e3, stepTimeoutMs: 3e3, records: 200, text: 2e4 }); // src/server/files.mjs var secretName = /(^|\/)(\.env($|[./])|id_rsa($|[./])|id_ed25519($|[./])|credentials($|[./])|\.ssh($|\/)|\.secrets($|\/)|\.desktop-profile($|\/))/i; var normalize = (value) => process.platform === "win32" ? value.toLowerCase() : value; var inside = (root, target) => normalize(target) === normalize(root) || normalize(target).startsWith(normalize(root + import_node_path7.default.sep)); var restricted = (relative) => { const portable = relative.replaceAll("\\", "/"); return secretName.test(portable) || portable.split("/").some((part) => part.toLowerCase() === ".git" || process.platform === "win32" && part !== "." && /[. ]$/.test(part)); }; function safePath(project, relative = "", allowMissing = false) { assertWorkspacePath(project); if (typeof relative !== "string" || relative.includes("\0") || relative.includes(":") || import_node_path7.default.isAbsolute(relative) || import_node_path7.default.win32.isAbsolute(relative)) throw new Error("\u8DEF\u5F84\u5FC5\u987B\u76F8\u5BF9\u4E8E\u9879\u76EE\u6587\u4EF6\u5939\u3002"); const portable = relative.replaceAll("\\", "/"); if (portable.split("/").includes("..") || restricted(portable)) throw new Error("\u8BE5\u8DEF\u5F84\u4E0D\u5728\u53EF\u8BFB\u53D6\u7684\u9879\u76EE\u8303\u56F4\u5185\u3002"); const root = import_node_fs6.default.realpathSync.native(project.root); if (normalize(root) !== normalize(project.root)) throw new Error("\u9879\u76EE\u4F4D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u9879\u76EE\u3002"); const target = import_node_path7.default.resolve(root, portable || "."); if (!inside(root, target)) throw new Error("\u8DEF\u5F84\u8D85\u51FA\u9879\u76EE\u8303\u56F4\u3002"); let existing = target; while (!import_node_fs6.default.existsSync(existing)) { try { if (import_node_fs6.default.lstatSync(existing).isSymbolicLink()) throw new Error("\u76EE\u6807\u7ECF\u8FC7\u4E00\u4E2A\u5931\u6548\u7684\u94FE\u63A5\uFF0C\u8BF7\u5148\u6838\u5BF9\u9879\u76EE\u8DEF\u5F84\u3002"); } catch (error) { if (error.code !== "ENOENT") throw error; } if (!allowMissing) throw new Error("\u6587\u4EF6\u6216\u6587\u4EF6\u5939\u4E0D\u5B58\u5728\u3002"); const parent = import_node_path7.default.dirname(existing); if (parent === existing) throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76EE\u6807\u6587\u4EF6\u5939\u3002"); existing = parent; } const real = import_node_fs6.default.realpathSync.native(existing); if (!inside(root, real)) throw new Error("\u94FE\u63A5\u6307\u5411\u9879\u76EE\u4EE5\u5916\u7684\u4F4D\u7F6E\u3002"); if (restricted(import_node_path7.default.relative(root, real))) throw new Error("\u5B9E\u9645\u8DEF\u5F84\u6307\u5411\u53D7\u4FDD\u62A4\u7684\u9879\u76EE\u76EE\u5F55\u6216\u51ED\u636E\u3002"); const actual = import_node_fs6.default.statSync(real); if (actual.isFile() && actual.nlink !== 1) throw new Error("\u786C\u94FE\u63A5\u6587\u4EF6\u6709\u591A\u4E2A\u8DEF\u5F84\uFF0C\u65E0\u6CD5\u6838\u5BF9\u5B8C\u6574\u4F5C\u7528\u8303\u56F4\uFF1B\u8BF7\u4F7F\u7528\u72EC\u7ACB\u6587\u4EF6\u526F\u672C\u3002"); return target; } // src/shared/contracts/desktop-bridge.mjs var DESKTOP_CHANNELS = Object.freeze({ status: "awb:desktop-status", pickProject: "awb:desktop-pick-project", revealFile: "awb:desktop-reveal-file", openFilePreview: "awb:desktop-file-preview", projectFolder: "awb:desktop-project-folder", reviewTask: "awb:desktop-review-task", stopHost: "awb:desktop-stop-host" }); var desktopError = (message) => Object.assign(new Error(message), { code: "DESKTOP_SCOPE_REJECTED", status: 403 }); function desktopOrigin(value, origin) { try { const url = new URL(value); return url.origin === origin && url.protocol === "http:" && !url.username && !url.password; } catch { return false; } } function assertDesktopFrame(event, window2, origin) { if (!window2 || window2.isDestroyed() || event.sender !== window2.webContents || event.senderFrame !== window2.webContents.mainFrame || !desktopOrigin(event.senderFrame.url, origin)) throw desktopError("\u672C\u673A\u64CD\u4F5C\u53EA\u80FD\u7531\u5F53\u524D\u5DE5\u4F5C\u53F0\u4E3B\u7A97\u53E3\u53D1\u8D77\u3002"); } function desktopInput(action, input) { const fields = { status: [], pickProject: [], stopHost: [], projectFolder: ["projectId"], reviewTask: ["projectId", "sessionId", "taskId"], openFilePreview: ["projectId", "url"], revealFile: ["projectId", "sessionId", "taskId", "path", "sha256"] }[action]; if (!fields) throw desktopError("\u672C\u673A\u64CD\u4F5C\u4E0D\u5B58\u5728\u3002"); const value = input ?? {}; if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key2) => !fields.includes(key2))) throw desktopError("\u672C\u673A\u64CD\u4F5C\u5B57\u6BB5\u65E0\u6548\u3002"); for (const key2 of fields) { if (typeof value[key2] !== "string") throw desktopError("\u672C\u673A\u64CD\u4F5C\u7F3A\u5C11\u5F53\u524D\u5F52\u5C5E\u3002"); if (key2.endsWith("Id") && !/^[a-f0-9-]{36}$/i.test(value[key2])) throw desktopError("\u9879\u76EE\u6216\u4EFB\u52A1\u8EAB\u4EFD\u65E0\u6548\u3002"); } if (action === "revealFile" && (!/^[a-f0-9]{64}$/i.test(value.sha256) || value.path.length > 2e3 || !value.path || value.path.includes("\0") || value.path.includes(":") || /^[\/\\]/.test(value.path) || value.path.replaceAll("\\", "/").split("/").includes(".."))) throw desktopError("\u539F\u6587\u4EF6\u5165\u53E3\u9700\u8981\u6240\u5C5E\u76F8\u5BF9\u8DEF\u5F84\u53CA\u5F53\u524DSHA256\u3002"); return value; } // src/core/desktop/desktop-bridge.mjs var DesktopBridge = class { constructor(controller2, { dialog: dialog2, shell: shell2, getWindow, onStopped = () => { } }) { Object.assign(this, { controller: controller2, dialog: dialog2, shell: shell2, getWindow, onStopped }); this.pending = /* @__PURE__ */ new Set(); } async project(id) { const project = (await this.controller.api("/bootstrap")).projects.find((value) => value.id === id); if (!project) throw desktopError("\u9879\u76EE\u672A\u5728\u5F53\u524D\u5BBF\u4E3B\u767B\u8BB0\u3002"); assertLocalTree(project.root); if (!samePath(project.root, import_node_fs7.default.realpathSync.native(project.root))) throw desktopError("\u539F\u9879\u76EE\u76EE\u5F55\u5DF2\u53D8\u5316\u3002"); return project; } async task(input) { const session2 = await this.controller.api("/sessions/" + input.sessionId); if (session2.projectId !== input.projectId || session2.execution?.task?.id !== input.taskId) throw desktopError("\u8BE5\u5165\u53E3\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE\u4E0ETask\uFF0C\u8BF7\u5237\u65B0\u540E\u6838\u5BF9\u3002"); return session2; } async execute(event, action, input) { const window2 = this.getWindow(); assertDesktopFrame(event, window2, this.controller.url); const value = desktopInput(action, input); if (this.pending.has(action)) throw desktopError("\u540C\u4E00\u9879\u672C\u673A\u64CD\u4F5C\u6B63\u5728\u5904\u7406\uFF0C\u8BF7\u7B49\u5F85\u539F\u64CD\u4F5C\u3002"); this.pending.add(action); try { if (!await this.controller.connect()) throw desktopError("\u539F\u6267\u884C\u5BBF\u4E3B\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u5DE5\u4F5C\u53F0\u3002"); assertDesktopFrame(event, this.getWindow(), this.controller.url); if (action === "status") return this.controller.api("/host/status"); if (action === "pickProject") { const selected = await this.dialog.showOpenDialog(window2, { title: "\u9009\u62E9\u5DE5\u4F5C\u53F0\u9879\u76EE", properties: ["openDirectory"], buttonLabel: "\u6253\u5F00\u9879\u76EE" }); assertDesktopFrame(event, this.getWindow(), this.controller.url); if (selected.canceled) return null; if (selected.filePaths.length !== 1 || !import_node_path8.default.isAbsolute(selected.filePaths[0])) throw desktopError("\u8BF7\u9009\u62E9\u4E00\u4E2A\u5B9E\u9645\u9879\u76EE\u6587\u4EF6\u5939\u3002"); assertLocalTree(selected.filePaths[0]); return this.controller.api("/projects", { method: "POST", input: { root: selected.filePaths[0] } }); } if (action === "projectFolder") { const project = await this.project(value.projectId); const error = await this.shell.openPath(project.root); if (error) throw desktopError("\u7CFB\u7EDF\u65E0\u6CD5\u6253\u5F00\u6240\u5C5E\u9879\u76EE\u76EE\u5F55\u3002"); return { opened: true, projectId: project.id, root: project.root }; } if (action === "openFilePreview") { const access = await this.controller.api("/local-file-preview-access?url=" + encodeURIComponent(value.url)); if (!access.allowed || access.projectId !== value.projectId) throw desktopError("\u6B64\u9884\u89C8\u5DF2\u5173\u95ED\u6216\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE\u3002"); assertDesktopFrame(event, this.getWindow(), this.controller.url); await this.shell.openExternal(value.url); return { opened: true }; } if (action === "reviewTask") { const session2 = await this.task(value); await this.project(value.projectId); return { projectId: session2.projectId, sessionId: session2.id, taskId: value.taskId, eventSeq: session2.eventSeq }; } if (action === "revealFile") { await this.task(value); const project = await this.project(value.projectId), target = safePath(project, value.path); assertLocalTree(target); const stat = import_node_fs7.default.lstatSync(target); if (!stat.isFile() || stat.nlink !== 1 || stat.size > 1024 * 1024) throw desktopError("\u539F\u6587\u4EF6\u5165\u53E3\u53EA\u63A5\u53D7\u5F53\u524D\u5DE5\u7A0B\u7684\u666E\u901A\u6587\u672C\u6587\u4EF6\u3002"); const bytes = import_node_fs7.default.readFileSync(target); if (bytes.includes(0) || (0, import_node_crypto6.createHash)("sha256").update(bytes).digest("hex") !== value.sha256) throw desktopError("\u6587\u4EF6\u5185\u5BB9\u5DF2\u53D8\u5316\u6216\u4E0D\u662F\u6587\u672C\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u5B9A\u4F4D\u3002"); try { new TextDecoder("utf8", { fatal: true }).decode(bytes); } catch { throw desktopError("\u5F53\u524D\u6587\u4EF6\u4E0D\u662FUTF-8\u6587\u672C\uFF0C\u8BF7\u5148\u6838\u5BF9\u7F16\u7801\u3002"); } await this.task(value); assertLocalTree(target); if ((0, import_node_crypto6.createHash)("sha256").update(import_node_fs7.default.readFileSync(target)).digest("hex") !== value.sha256) throw desktopError("\u6838\u5BF9\u671F\u95F4\u539F\u6587\u4EF6\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u5B9A\u4F4D\u3002"); this.shell.showItemInFolder(target); return { revealed: true, projectId: project.id, sessionId: value.sessionId, taskId: value.taskId, path: value.path, sha256: value.sha256 }; } if (action === "stopHost") { const status = await this.controller.status(); const choice = await this.dialog.showMessageBox(window2, { type: "warning", title: "\u9000\u51FA\u6267\u884C\u5BBF\u4E3B", message: "\u505C\u6B62\u5F53\u524D\u6267\u884C\u5BBF\u4E3B\uFF1F", detail: "\u6240\u5C5E\u4EFB\u52A1\u3001\u6A21\u578B\u8BF7\u6C42\u548C\u5DE5\u5177\u8FDB\u7A0B\u4F1A\u5148\u7ED3\u675F\u3002\u5173\u95ED\u666E\u901A\u7A97\u53E3\u4F1A\u4FDD\u7559\u540E\u53F0\u4EFB\u52A1\u3002", buttons: ["\u4FDD\u7559\u540E\u53F0\u4EFB\u52A1", "\u505C\u6B62\u5E76\u9000\u51FA"], defaultId: 0, cancelId: 0, noLink: true }); assertDesktopFrame(event, this.getWindow(), this.controller.url); if (choice.response !== 1) return { cancelled: true }; const current = await this.controller.connect(); if (!current || current.identity.instanceId !== status.identity.instanceId || current.identity.runtimeIdentity !== status.identity.runtimeIdentity) throw desktopError("\u505C\u6B62\u786E\u8BA4\u671F\u95F4\u539F\u5BBF\u4E3B\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u6838\u5BF9\u3002"); const result = await this.controller.stop(); this.onStopped(); return result; } } finally { this.pending.delete(action); } } }; // src/core/desktop/launch-options.mjs var import_node_path9 = __toESM(require("node:path"), 1); function desktopLaunchOptions(argv, { defaultApp = false, mainFile } = {}) { const args = argv.slice(1), options2 = {}; while (/^--(?:inspect|remote-debugging-port)=\d+$/.test(args[0] ?? "")) args.shift(); if (defaultApp && (!args.length || !mainFile || !samePath(import_node_path9.default.resolve(args.shift()), mainFile))) throw new Error("Desktop entry does not match the compiled main program."); while (args.length) { const flag = args.shift(); if (flag === "--hidden-window" && !options2.hidden) { options2.hidden = true; continue; } if (!["--app-root", "--data-root", "--node", "--port"].includes(flag) || !args.length || options2[flag] !== void 0) throw new Error("Unsupported desktop option."); options2[flag] = args.shift(); } return options2; } // src/desktop/browsing-view.mjs var import_electron = require("electron"); var import_promises2 = require("node:dns/promises"); var import_node_net = require("node:net"); // src/shared/contracts/browsing.mjs var browsingError = (message) => Object.assign(new Error(message), { status: 409, code: "BROWSING_SCOPE_REJECTED" }); function browsingUrl(value, { origins = null, previewOrigin = null, allowHttpLoopback = false, workbenchOrigin = null } = {}) { let url; try { url = new URL(value); } catch { throw browsingError("\u8BF7\u586B\u5199\u660E\u786E\u7684\u7F51\u7AD9\u5730\u5740\u3002"); } const local = url.hostname === "127.0.0.1" && (url.origin === previewOrigin || allowHttpLoopback); if (url.username || url.password || url.href.length > 2e3 || url.protocol !== "https:" && !(local && url.protocol === "http:") || url.origin === workbenchOrigin || !local && /^(localhost|.*\.localhost|.*\.local|\[.*\]|\d+(?:\.\d+){0,3})$/i.test(url.hostname)) throw browsingError("\u53EA\u63A5\u53D7HTTPS\u7F51\u7AD9\u6216\u660E\u786E\u6240\u5C5E\u9884\u89C8\uFF1B\u4E0D\u80FD\u8BBF\u95EE\u5DE5\u4F5C\u53F0\u3001\u51ED\u636E\u5730\u5740\u6216\u5176\u5B83\u672C\u5730\u670D\u52A1\u3002"); if (origins && !origins.includes(url.origin)) throw browsingError("\u7F51\u7AD9\u6765\u6E90\u8D85\u51FA\u539F\u6388\u6743\u8303\u56F4\uFF0C\u8BF7\u91CD\u65B0\u660E\u786E\u6388\u6743\u3002"); return url; } // src/desktop/browsing-view.mjs function pageOperation(operation, input) { const visible = (element) => { const style = getComputedStyle(element), rect = element.getBoundingClientRect(); return rect.width > 0 && rect.height > 0 && style.display !== "none" && style.visibility !== "hidden"; }; let state = globalThis.__awbPageObservation; if (!state || state.document !== document) { state = { document, epoch: crypto.randomUUID(), revision: 0, elements: /* @__PURE__ */ new Map() }; state.observer = new MutationObserver(() => state.revision++); state.observer.observe(document, { subtree: true, attributes: true, childList: true, characterData: true }); globalThis.__awbPageObservation = state; } if (state.observer.takeRecords().length) state.revision++; const revision = () => state.epoch + ":" + state.revision; if (operation === "revision") return { revision: revision(), url: location.href }; if (operation === "act") { if (revision() !== input.revision) return { stale: true, reason: "\u9875\u9762\u5728\u539F\u89C2\u5BDF\u540E\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u89C2\u5BDF\u3002" }; if (input.action === "scroll") { scrollBy(0, input.amount); return { performed: true }; } if (!["click", "fill"].includes(input.action)) return { performed: false }; const element = state.elements.get(input.ref); if (!element || !element.isConnected || !visible(element) || element.disabled) return { stale: true, reason: "\u539F\u53EF\u89C1\u63A7\u4EF6\u5DF2\u5931\u6548\u3002" }; if (input.action === "click") { element.click(); return { performed: true }; } if (!(element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) || element.readOnly || element instanceof HTMLInputElement && !["text", "search", "email", "tel", "url", "number"].includes(element.type)) return { stale: true, reason: "\u53EA\u652F\u6301\u666E\u901A\u6587\u672C\u5B57\u6BB5\uFF0C\u5BC6\u7801\u3001\u6587\u4EF6\u548C\u53D7\u9650\u63A7\u4EF6\u4E0D\u901A\u8FC7\u4EE3\u7406\u8F93\u5165\u3002" }; const prototype = element instanceof HTMLInputElement ? HTMLInputElement.prototype : HTMLTextAreaElement.prototype; Object.getOwnPropertyDescriptor(prototype, "value").set.call(element, input.value); element.dispatchEvent(new Event("input", { bubbles: true })); element.dispatchEvent(new Event("change", { bubbles: true })); return { performed: true }; } state.elements.clear(); const candidates = document.querySelectorAll('a[href],button,input,textarea,select,[role="button"],[role="link"]'), controls = []; let visited = 0; for (const element of candidates) { if (++visited > 6e3 || controls.length === 120) break; if (!visible(element) || element.type === "hidden") continue; const ref = "e" + (controls.length + 1); state.elements.set(ref, element); const label = element.labels?.[0]?.innerText || element.getAttribute("aria-label") || element.innerText || element.getAttribute("placeholder") || element.getAttribute("name") || element.tagName; controls.push({ ref, tag: element.tagName.toLowerCase(), type: element.type || "", label: label.slice(0, 180), disabled: !!element.disabled, ...element instanceof HTMLAnchorElement ? { href: element.href.slice(0, 2e3) } : {}, ...element instanceof HTMLInputElement && ["password", "file"].includes(element.type) ? { restricted: true } : {} }); } const text = document.body?.innerText ?? ""; return { revision: revision(), url: location.href, title: document.title.slice(0, 300), text: text.slice(0, 16e3), controls, scope: { textCharacters: text.length, controlsSeen: candidates.length, complete: text.length <= 16e3 && candidates.length <= 6e3 && controls.length < 120 }, sampledAt: (/* @__PURE__ */ new Date()).toISOString() }; } var publicAddress = (address) => { if ((0, import_node_net.isIP)(address) === 4) { const [a, b] = address.split(".").map(Number); return !(a === 0 || a === 10 || a === 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a >= 224 || a === 100 && b >= 64 && b <= 127); } return (0, import_node_net.isIP)(address) === 6 && !/^(::|fe[89ab]|f[cd]|::ffff:)/i.test(address); }; var BrowsingView = class { constructor({ window: window2, controller: controller2, windowOwner: windowOwner2 }) { Object.assign(this, { window: window2, controller: controller2, windowOwner: windowOwner2 }); this.views = /* @__PURE__ */ new Map(); this.partitions = /* @__PURE__ */ new Map(); this.current = null; this.disposed = false; for (const event of ["minimize", "resize", "blur"]) window2.on(event, () => this.hide()); window2.webContents.on("did-start-loading", () => this.hide()); void this.loop(); } async loop() { while (!this.disposed && !this.window.isDestroyed()) { try { const states = [...this.views.values()].map((value) => ({ id: value.tab.id, url: value.view.webContents.getURL(), title: value.view.webContents.getTitle() })); const next = await this.controller.api("/browsing-desktop/poll", { method: "POST", input: { owner: this.windowOwner, states } }); for (const [id] of this.views) if (!next.retainedTabs.includes(id) && !next.commands.some((command) => command.tab.id === id && ["close", "clear"].includes(command.kind))) this.destroy(id); for (const command of next.commands) { if (this.disposed) break; let reply; try { await this.controller.api("/browsing-desktop/validate", { method: "POST", input: { owner: this.windowOwner, id: command.id, nonce: command.nonce } }); reply = { result: await this.execute(command) }; } catch (error) { reply = { error: error.message, uncertain: command.kind === "act" && error.noEffect !== true }; } await this.controller.api("/browsing-desktop/complete", { method: "POST", input: { owner: this.windowOwner, id: command.id, nonce: command.nonce, ...reply }, timeoutMs: 15e3 }); } } catch { this.hide(); } await new Promise((resolve) => setTimeout(resolve, 350)); } } policy(tab, value) { return browsingUrl(value, { ...tab.scope, workbenchOrigin: this.controller.url }); } async permitted(tab, value) { if (value === "about:blank") return false; try { const resource = new URL(value); if (resource.protocol === "ws:" || resource.protocol === "wss:") { resource.protocol = resource.protocol === "ws:" ? "http:" : "https:"; value = resource.href; } } catch { return false; } let url; try { url = this.policy(tab, value); } catch { return false; } if (url.origin === tab.previewOrigin || tab.scope.allowHttpLoopback && url.hostname === "127.0.0.1") return true; try { const addresses = await (0, import_promises2.lookup)(url.hostname, { all: true }); return addresses.length > 0 && addresses.every((item) => publicAddress(item.address)); } catch { return false; } } async create(tab) { if (this.views.has(tab.id)) throw new Error("\u539F\u6807\u7B7E\u9875\u5DF2\u6253\u5F00\uFF0C\u4E0D\u80FD\u91CD\u653E\u6253\u5F00\u3002"); let partition = this.partitions.get(tab.profileId); if (!partition) { const partitionName = (tab.persistent ? "persist:" : "") + "awb-browsing-" + tab.profileId; partition = import_electron.session.fromPartition(partitionName, { cache: true }); await partition.setProxy({ mode: "direct" }); partition.setPermissionRequestHandler((_contents, _permission, callback) => callback(false)); partition.setPermissionCheckHandler(() => false); partition.on("will-download", (event, item) => { event.preventDefault(); item.cancel(); }); partition.webRequest.onBeforeRequest((details, callback) => { void this.permitted(tab, details.url).then((allowed) => callback({ cancel: !allowed }), () => callback({ cancel: true })); }); this.partitions.set(tab.profileId, partition); } const view = new import_electron.WebContentsView({ webPreferences: { session: partition, sandbox: true, contextIsolation: true, nodeIntegration: false, webSecurity: true, allowRunningInsecureContent: false, navigateOnDragDrop: false, spellcheck: false, backgroundThrottling: false } }); const value = { tab, view, history: [], historyIndex: -1, historyTarget: null }; this.views.set(tab.id, value); view.setBounds({ x: 0, y: 0, width: 800, height: 600 }); view.setVisible(false); this.window.contentView.addChildView(view); const contents = view.webContents; contents.setWindowOpenHandler(() => ({ action: "deny" })); for (const name of ["did-navigate", "did-navigate-in-page"]) contents.on(name, () => this.recordNavigation(value)); contents.on("will-attach-webview", (event) => event.preventDefault()); for (const name of ["will-navigate", "will-frame-navigate", "will-redirect"]) contents.on(name, (event, url) => { try { this.policy(tab, typeof url === "string" ? url : event.url); } catch { event.preventDefault(); } }); contents.on("render-process-gone", () => { this.hide(); this.destroy(tab.id); }); return value; } async script(contents, operation, input = {}) { return contents.executeJavaScriptInIsolatedWorld(999, [{ code: "(" + pageOperation.toString() + ")(" + JSON.stringify(operation) + "," + JSON.stringify(input) + ")" }]); } async load(contents, url) { let timer; try { await Promise.race([contents.loadURL(url), new Promise((_, reject) => { timer = setTimeout(() => { contents.stop(); reject(new Error("\u6240\u5C5E\u9875\u9762\u52A0\u8F7D\u8D85\u8FC715\u79D2\uFF0C\u8BF7\u6838\u5BF9\u539F\u7F51\u5740\u548C\u8BF7\u6C42\u3002")); }, 15e3); })]); } finally { clearTimeout(timer); } } async observe(value) { const contents = value.view.webContents; this.recordNavigation(value); const observation = await this.script(contents, "observe"); this.policy(value.tab, observation.url); const png = (await contents.capturePage()).toPNG(); if (png.length > 6 * 1024 * 1024) throw new Error("\u9875\u9762\u622A\u56FE\u8D85\u8FC76MiB\u4E0A\u9650\uFF0C\u8BF7\u7F29\u5C0F\u6D4F\u89C8\u533A\u3002"); const after = await this.script(contents, "revision"); if (after.revision !== observation.revision || after.url !== observation.url) throw Object.assign(new Error("\u9875\u9762\u5728\u89C2\u5BDF/\u622A\u56FE\u671F\u95F4\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u89C2\u5BDF\u3002"), { noEffect: true }); observation.navigation = { mode: "owned-url-history", canGoBack: value.historyIndex > 0, canGoForward: value.historyIndex < value.history.length - 1 }; return { observation, png: png.toString("base64") }; } recordNavigation(value) { const url = value.view.webContents.getURL(); if (!url || url === "about:blank") return; this.policy(value.tab, url); if (value.historyTarget !== null) { value.historyIndex = value.historyTarget; value.history[value.historyTarget] = url; return; } if (value.history[value.historyIndex] === url) return; value.history.splice(value.historyIndex + 1); value.history.push(url); if (value.history.length > 100) value.history.shift(); value.historyIndex = value.history.length - 1; } async execute(command) { const { tab, kind, input } = command; if (kind === "clear") { for (const [id, value2] of this.views) if (value2.tab.profileId === tab.profileId) this.destroy(id); let partition = this.partitions.get(tab.profileId); if (!partition) partition = import_electron.session.fromPartition((tab.persistent ? "persist:" : "") + "awb-browsing-" + tab.profileId); await partition.clearStorageData(); await partition.clearCache(); this.partitions.delete(tab.profileId); return { cleared: true }; } if (kind === "close") { this.destroy(tab.id); if (!tab.persistent) { const partition = this.partitions.get(tab.profileId); if (partition) { await partition.clearStorageData(); await partition.clearCache(); this.partitions.delete(tab.profileId); } } return { closed: true }; } let value = this.views.get(tab.id); if (kind === "open") { this.policy(tab, input.url); value = await this.create(tab); await this.load(value.view.webContents, input.url); return this.observe(value); } if (!value || value.view.webContents.isDestroyed()) throw Object.assign(new Error("\u539F\u684C\u9762\u6807\u7B7E\u9875\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u660E\u786E\u6253\u5F00\u65B0\u9875\u9762\u3002"), { noEffect: true }); if (value.tab.grantRevision !== tab.grantRevision) throw Object.assign(new Error("\u539F\u6388\u6743\u5DF2\u53D8\u5316\u3002"), { noEffect: true }); if (kind === "observe") return this.observe(value); const contents = value.view.webContents, current = await this.script(contents, "revision"); if (current.revision !== input.revision || current.url !== tab.url) throw Object.assign(new Error("\u9875\u9762\u5728\u539F\u89C2\u5BDF\u540E\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u89C2\u5BDF\u3002"), { noEffect: true }); if (["click", "fill", "scroll"].includes(input.action)) { const result = await this.script(contents, "act", input); if (result.stale) throw Object.assign(new Error(result.reason), { noEffect: true }); } else if (input.action === "navigate") { this.policy(tab, input.url); await this.load(contents, input.url); } else if (input.action === "reload") { await this.load(contents, current.url); } else if (["back", "forward"].includes(input.action)) { const target = value.historyIndex + (input.action === "back" ? -1 : 1); if (target < 0 || target >= value.history.length) throw Object.assign(new Error("\u6CA1\u6709\u5BF9\u5E94\u7684\u9875\u9762\u5386\u53F2\u3002"), { noEffect: true }); const url = value.history[target]; this.policy(tab, url); value.historyTarget = target; try { await this.load(contents, url); } finally { value.historyTarget = null; } } else if (input.action === "wait") await new Promise((resolve) => setTimeout(resolve, input.milliseconds)); else if (input.action === "download") { this.policy(tab, input.url); const response = await contents.session.fetch(input.url, { redirect: "error", signal: AbortSignal.timeout(1e4) }); if (!response.ok) throw new Error("\u4E0B\u8F7D\u8FD4\u56DEHTTP " + response.status); let length = 0; const chunks = []; for await (const chunk of response.body) { length += chunk.length; if (length > 6 * 1024 * 1024) throw new Error("\u4E0B\u8F7D\u8D85\u8FC76MiB\u4E0A\u9650\u3002"); chunks.push(Buffer.from(chunk)); } return { download: { url: input.url, bytes: Buffer.concat(chunks).toString("base64"), mediaType: response.headers.get("content-type") } }; } await new Promise((resolve) => setTimeout(resolve, 150)); return this.observe(value); } layout(event, input) { assertDesktopFrame(event, this.window, this.controller.url); const reject = (message) => { this.hide(); throw new Error(message); }; const fields = ["projectId", "sessionId", "taskId", "tabId", "bounds", "visible"]; if (!input || Array.isArray(input) || Object.keys(input).some((key2) => !fields.includes(key2)) || typeof input.visible !== "boolean") reject("\u6D4F\u89C8\u533A\u57DF\u5B57\u6BB5\u65E0\u6548\u3002"); if (!input.visible) { this.hide(); return { visible: false }; } const value = this.views.get(input.tabId), zoom = this.window.webContents.getZoomFactor(), available = this.window.getContentBounds(); const bounds = input.bounds && Object.fromEntries(Object.entries(input.bounds).map(([key2, value2]) => [key2, Math.round(value2 * zoom)])); if (!value || value.tab.projectId !== input.projectId || value.tab.sessionId !== input.sessionId || value.tab.taskId !== input.taskId) reject("\u539F\u6D4F\u89C8\u533A\u57DF\u5F52\u5C5E\u5DF2\u53D8\u5316\u3002"); if (!bounds || Object.keys(bounds).sort().join() !== "height,width,x,y" || Object.values(bounds).some((number) => !Number.isSafeInteger(number)) || bounds.x < 0 || bounds.y < 0 || bounds.width < 80 || bounds.height < 80 || bounds.x + bounds.width > available.width + 1 || bounds.y + bounds.height > available.height + 1) reject("\u539F\u751F\u6D4F\u89C8\u533A\u57DF\u8D85\u8FC7\u5F53\u524D\u7A97\u53E3\u3002"); if (this.window.isMinimized() || !this.window.isVisible()) { this.hide(); return { visible: false }; } if (this.current !== input.tabId) { this.hide(); this.window.contentView.addChildView(value.view); this.current = input.tabId; } value.view.setBounds(bounds); value.view.setVisible(true); return { visible: true }; } hide() { if (this.current) { const value = this.views.get(this.current); if (value) { value.view.setVisible(false); this.window.contentView.removeChildView(value.view); } this.current = null; } } destroy(id) { if (this.current === id) this.hide(); const value = this.views.get(id); this.views.delete(id); if (value) { this.window.contentView.removeChildView(value.view); if (!value.view.webContents.isDestroyed()) value.view.webContents.close(); } } dispose() { this.disposed = true; this.hide(); for (const id of [...this.views.keys()]) this.destroy(id); } }; // src/core/preview/local-file-preview.mjs var types = new Map(Object.entries({ ".html": "text/html; charset=utf-8", ".htm": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".json": "application/json; charset=utf-8", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".svg": "image/svg+xml", ".ico": "image/x-icon", ".avif": "image/avif", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf", ".otf": "font/otf", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".mp4": "video/mp4", ".webm": "video/webm", ".wasm": "application/wasm" })); function localPreviewAddress(value) { try { const url = new URL(value); return url.protocol === "http:" && url.hostname === "127.0.0.1" && !!url.port && !url.username && !url.password && /^\/[a-f0-9]{48}\//.test(url.pathname); } catch { return false; } } // src/desktop/main.mjs var options = desktopLaunchOptions(process.argv, { defaultApp: process.defaultApp, mainFile: __filename }); var appRoot = import_node_path10.default.resolve(options["--app-root"] || (import_electron2.app.isPackaged ? import_node_path10.default.resolve(import_node_path10.default.dirname(process.execPath), "..") : import_node_path10.default.resolve(__dirname, ".."))); var dataRoot = import_node_path10.default.resolve(options["--data-root"] || import_node_path10.default.join(process.env.LOCALAPPDATA || import_node_os.default.homedir(), "AgentWorkbench")); var port = Number(options["--port"] || 4318); assertLocalTree(dataRoot, { missing: true }); import_node_fs8.default.mkdirSync(dataRoot, { recursive: true }); var profile = ownedChild(dataRoot, ".desktop-profile", { missing: true }); import_node_fs8.default.mkdirSync(profile, { recursive: true }); protectUserDirectory(profile); import_electron2.app.setPath("userData", profile); import_electron2.app.setAppUserModelId("local.agent-workbench"); import_electron2.app.setName("Agent Workbench"); var window; var controller; var bridge; var browsingView; var windowId; var windowOwner; var quitting = false; var retained = import_electron2.app.requestSingleInstanceLock({ appRoot, dataRoot, port }); if (!retained) import_electron2.app.quit(); else { import_electron2.app.on("second-instance", (_event, _argv, _directory, incoming) => { if (!samePath(incoming?.appRoot ?? "", appRoot) || !samePath(incoming?.dataRoot ?? "", dataRoot) || incoming?.port !== port) return; if (window && !window.isDestroyed()) { if (window.isMinimized()) window.restore(); window.show(); window.focus(); } }); import_electron2.app.on("window-all-closed", () => import_electron2.app.quit()); import_electron2.app.on("before-quit", (event) => { if (quitting || !controller || !windowOwner) return; event.preventDefault(); quitting = true; browsingView?.dispose(); void controller.api("/host/windows/unregister", { method: "POST", input: windowOwner, timeoutMs: 5e3 }).catch(() => { }).finally(() => import_electron2.app.quit()); }); import_electron2.app.whenReady().then(async () => { controller = new HostController({ appRoot, dataRoot, port, nodePath: options["--node"], environment: Object.fromEntries(HOST_ENVIRONMENT.filter((key2) => process.env[key2]).map((key2) => [key2, process.env[key2]])) }); const host = await controller.start(), observed = observeWindowsProcess(process.pid); windowId = (0, import_node_crypto7.randomUUID)(); windowOwner = { windowId, pid: process.pid, createdAt: observed.createdAt, instanceId: host.identity.instanceId, runtimeIdentity: host.identity.runtimeIdentity }; await controller.api("/host/windows/register", { method: "POST", input: windowOwner }); const preload = import_node_path10.default.join(appRoot, "dist-desktop/preload.cjs"); window = new import_electron2.BrowserWindow({ title: "Agent Workbench", width: 1440, height: 1e3, minWidth: 390, minHeight: 600, show: false, backgroundColor: "#edf2f7", icon: import_node_path10.default.join(appRoot, "public/workbench-icon.png"), webPreferences: { preload, sandbox: true, contextIsolation: true, nodeIntegration: false, webSecurity: true, allowRunningInsecureContent: false } }); window.webContents.setWindowOpenHandler(() => ({ action: "deny" })); window.webContents.on("will-navigate", (details) => { if (!desktopOrigin(details.url, controller.url)) details.preventDefault(); }); window.webContents.on("will-frame-navigate", (details) => { if (!desktopOrigin(details.url, controller.url) && !(details.isMainFrame === false && localPreviewAddress(details.url))) details.preventDefault(); }); window.webContents.on("will-attach-webview", (event) => event.preventDefault()); const session2 = window.webContents.session; session2.setPermissionRequestHandler((_contents, _permission, callback) => callback(false)); session2.setPermissionCheckHandler(() => false); session2.webRequest.onBeforeRequest((details, callback) => { const permitted = desktopOrigin(details.url, controller.url) || details.url.startsWith("data:image/") || details.url.startsWith("blob:" + controller.url + "/"); if (permitted) return callback({ cancel: false }); if (!localPreviewAddress(details.url) || details.resourceType === "mainFrame") return callback({ cancel: true }); void controller.api("/local-file-preview-access?url=" + encodeURIComponent(details.url)).then((access) => callback({ cancel: !access.allowed })).catch(() => callback({ cancel: true })); }); bridge = new DesktopBridge(controller, { dialog: import_electron2.dialog, shell: import_electron2.shell, getWindow: () => window, onStopped: () => setTimeout(() => import_electron2.app.quit(), 150) }); for (const [action, channel] of Object.entries(DESKTOP_CHANNELS)) import_electron2.ipcMain.handle(channel, (event, input) => bridge.execute(event, action, input)); browsingView = new BrowsingView({ window, controller, windowOwner }); import_electron2.ipcMain.handle("awb:browsing-layout", (event, input) => browsingView.layout(event, input)); import_electron2.Menu.setApplicationMenu(import_electron2.Menu.buildFromTemplate([{ label: "\u5DE5\u4F5C\u53F0", submenu: [ { label: "\u5237\u65B0\u7A97\u53E3", role: "reload" }, { label: "\u5173\u95ED\u7A97\u53E3\uFF08\u540E\u53F0\u4EFB\u52A1\u7EE7\u7EED\uFF09", accelerator: "Alt+F4", click: () => window.close() } ] }, { label: "\u7F16\u8F91", submenu: [{ role: "undo" }, { role: "redo" }, { type: "separator" }, { role: "cut" }, { role: "copy" }, { role: "paste" }, { role: "selectAll" }] }])); window.on("close", () => browsingView?.dispose()); window.on("closed", () => { window = null; }); await window.loadURL(host.url + "/?desktop=1&release=" + host.identity.version); if (!options.hidden) window.show(); console.log(JSON.stringify({ app: "agent-workbench-desktop", ready: true, pid: process.pid, hostPid: host.identity.pid, instanceId: host.identity.instanceId, appRoot, dataRoot, url: host.url })); }).catch((error) => { console.error(JSON.stringify({ app: "agent-workbench-desktop", ready: false, message: error.message })); if (!options.hidden) import_electron2.dialog.showErrorBox("Agent Workbench \u65E0\u6CD5\u6253\u5F00", error.message); import_electron2.app.exit(1); }); } /*! Bundled license information: smol-toml/dist/error.js: smol-toml/dist/primitive.js: smol-toml/dist/date.js: smol-toml/dist/extract.js: smol-toml/dist/util.js: smol-toml/dist/struct.js: smol-toml/dist/parse.js: smol-toml/dist/stringify.js: smol-toml/dist/index.js: (*! * Copyright (c) Squirrel Chat et al., All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) */