desktopRuntimeEnv.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. /* eslint-disable max-lines -- desktop runtime/env 解析需要集中维护 main/host/remote assets 的启动边界,拆分会扩大远程连接回归面。 */
  2. import { existsSync, readFileSync } from "node:fs";
  3. import { homedir } from "node:os";
  4. import { join, resolve, win32 } from "node:path";
  5. import type { ConnectOptions } from "@zcode/server/remote";
  6. import { listSSHConfigAliasesFromLocalConfig } from "@zcode/services/node";
  7. import { DEV_HELPER_APP_NAME, HELPER_APP_NAME } from "@zcode/zcode-cua/broker/helperConstants";
  8. import {
  9. ZCODE_APP_VERSION_ENV,
  10. ZCODE_BUILD_COMMIT_ID_ENV,
  11. ZCODE_AGENT_RUNTIME,
  12. ZCODE_COMMIT,
  13. ZCODE_DYNAMIC_WORKFLOW_MODE_ENV,
  14. ZCODE_ENV,
  15. ZCODE_PRODUCT_FLAVOR,
  16. ZCODE_RUNTIME_ENV_KEY,
  17. ZCODE_VERSION,
  18. buildZCodeToolEnvPassthroughEnv,
  19. resolveRuntimeZCodeEndpointOrigin,
  20. resolveZaiBusinessBaseUrl,
  21. resolveZaiOAuthClientId,
  22. resolveZaiOAuthOrigin,
  23. normalizeDynamicWorkflowMode,
  24. readZCodeAgentTelemetryEnv,
  25. sanitizeZCodeRuntimeEnv,
  26. type SourceServerArtifactPolicy,
  27. type ZCodeRuntimeEnv,
  28. } from "@zcode/shared";
  29. import { resolvePlatformKeyForPackagedApp } from "../../scripts/target-platform.mjs";
  30. import {
  31. getAppConfigDir,
  32. getDataBaseDir,
  33. ZCODE_CUA_BUNDLED_HELPER_APP_PATH_ENV,
  34. ZCODE_WINDOWS_APP_INSTALL_DIR_ENV,
  35. } from "@zcode/services/node";
  36. import {
  37. resolveRemoteCdnBaseUrls as resolveOrderedRemoteCdnBaseUrls,
  38. type ResolveRemoteCdnOptions,
  39. } from "./remoteCdn.js";
  40. import { getElectronAppPath, isElectronAppPackaged } from "./desktopElectronApp.js";
  41. declare const __ZCODE_PACKAGED_AGENT_TELEMETRY_ENV__: Readonly<Record<string, string>> | undefined;
  42. const isLocalDevelopmentRuntime = !isElectronAppPackaged();
  43. export const desktopRuntimeEnv: ZCodeRuntimeEnv = isLocalDevelopmentRuntime
  44. ? "development"
  45. : "production";
  46. // 身份看编译期 flavor 而不是 ZCODE_ENV:ZCODE_PREVIEW_IDENTITY=1 的生产后端构建同样是 Preview,
  47. // 需要独立的应用名、Electron 数据目录和 Helper 安装子目录才能与正式版并排运行。
  48. export const isPreviewPackagedRuntime =
  49. !isLocalDevelopmentRuntime && ZCODE_PRODUCT_FLAVOR === "preview";
  50. function readRuntimeEnvOverride(name: string): string | undefined {
  51. return process.env[name]?.trim() || undefined;
  52. }
  53. function isTruthyRuntimeEnvOverride(name: string): boolean {
  54. const value = readRuntimeEnvOverride(name)?.toLowerCase();
  55. return value === "1" || value === "true" || value === "yes" || value === "on";
  56. }
  57. // e2e 运行的是生产构建,默认会和本机正式版 ZCode 共用 app name / userData,
  58. // 触发 Electron 单实例锁后只激活已有窗口,Chromedriver 无法接管测试进程。
  59. // 这里允许测试显式隔离运行时身份,正常桌面/远控路径保持原来的默认值。
  60. export const runtimeApplicationName =
  61. readRuntimeEnvOverride("ZCODE_DESKTOP_APPLICATION_NAME") ??
  62. (isLocalDevelopmentRuntime ? "ZCode Dev" : isPreviewPackagedRuntime ? "ZCode Preview" : "ZCode");
  63. // Electron 的 app.getPath("home") 不一定跟随测试进程里的 HOME 覆盖。
  64. // e2e 默认工作区依赖 home 路径,因此提供显式覆盖,避免测试写到开发者真实 ~/ZCodeProject。
  65. export const runtimeHomePath = readRuntimeEnvOverride("ZCODE_DESKTOP_HOME_DIR");
  66. // Chromedriver 管理 Electron 时会注入临时 userData;e2e 默认路径模式下导入期不能提前读取 appData。
  67. export const shouldUseElectronDefaultUserDataPath = isTruthyRuntimeEnvOverride(
  68. "ZCODE_DESKTOP_USE_ELECTRON_DEFAULT_USER_DATA",
  69. );
  70. export const runtimeUserDataPath =
  71. readRuntimeEnvOverride("ZCODE_DESKTOP_USER_DATA_DIR") ??
  72. (shouldUseElectronDefaultUserDataPath
  73. ? undefined
  74. : join(getElectronAppPath("appData"), runtimeApplicationName));
  75. export const runtimeSessionDataPath =
  76. readRuntimeEnvOverride("ZCODE_DESKTOP_SESSION_DATA_DIR") ??
  77. (runtimeUserDataPath ? join(runtimeUserDataPath, "session") : undefined);
  78. // Chromedriver 会注入临时 --user-data-dir,并在该目录等待 DevToolsActivePort。
  79. // e2e 如果再用 app.setPath 覆盖 userData/sessionData,端口文件会被写到另一个目录,
  80. // 导致 Electron 已启动但 WebDriver session 一直创建失败。测试态打开该开关后保留 Chromedriver 的目录。
  81. export const hostModulePath = join(import.meta.dirname, "../host/index.js");
  82. export const schedulerModulePath = join(import.meta.dirname, "../scheduler/index.js");
  83. // 全 App 唯一的扩展进程(docs/plugins/extension-host.md §12.1)。
  84. export const extensionHostModulePath = join(import.meta.dirname, "../extension-host/index.js");
  85. export function getCredentialsDir() {
  86. return getAppConfigDir();
  87. }
  88. export type RemoteAssetDirs = Pick<
  89. ConnectOptions,
  90. "mockCdnDir" | "remoteCdnBaseUrl" | "remoteCdnBaseUrls" | "remoteCacheDir"
  91. > & {
  92. sourceServerArtifactPolicy?: SourceServerArtifactPolicy;
  93. };
  94. type LocalRuntimeEnv = Record<string, string | undefined>;
  95. export async function isDockerDaemonAvailable(): Promise<boolean> {
  96. const { isDockerAvailable } = await import("@zcode/server/remote");
  97. return isDockerAvailable();
  98. }
  99. export async function listAvailableWSLDistros() {
  100. const { listWSLDistros } = await import("@zcode/server/remote");
  101. return listWSLDistros();
  102. }
  103. export async function listAvailableDockerContainers() {
  104. const { listDockerContainers } = await import("@zcode/server/remote");
  105. return listDockerContainers();
  106. }
  107. export async function listSSHConfigAliases() {
  108. return await listSSHConfigAliasesFromLocalConfig();
  109. }
  110. function parseDotenv(content: string): Record<string, string> {
  111. const values: Record<string, string> = {};
  112. for (const rawLine of content.split("\n")) {
  113. const line = rawLine.trim();
  114. if (line === "" || line.startsWith("#")) {
  115. continue;
  116. }
  117. const normalized = line.startsWith("export ") ? line.slice("export ".length).trim() : line;
  118. const equalsIndex = normalized.indexOf("=");
  119. if (equalsIndex <= 0) {
  120. continue;
  121. }
  122. const key = normalized.slice(0, equalsIndex).trim();
  123. if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
  124. continue;
  125. }
  126. let value = normalized.slice(equalsIndex + 1).trim();
  127. if (
  128. (value.startsWith('"') && value.endsWith('"')) ||
  129. (value.startsWith("'") && value.endsWith("'"))
  130. ) {
  131. value = value.slice(1, -1);
  132. }
  133. values[key] = value;
  134. }
  135. return values;
  136. }
  137. function resolveWorkspaceRootForEnvFiles(): string | null {
  138. const workspaceRootCandidate = resolve(import.meta.dirname, "../../../..");
  139. return existsSync(join(workspaceRootCandidate, "pnpm-workspace.yaml"))
  140. ? workspaceRootCandidate
  141. : null;
  142. }
  143. export function loadHostProcessEnvFromLocalFiles(): Record<string, string> {
  144. if (isElectronAppPackaged()) {
  145. return resolvePackagedAgentTelemetryEnv();
  146. }
  147. const desktopRoot = resolve(import.meta.dirname, "../..");
  148. const workspaceRoot = resolveWorkspaceRootForEnvFiles();
  149. const fileCandidates = [
  150. ...(workspaceRoot
  151. ? [resolve(workspaceRoot, ".env"), resolve(workspaceRoot, ".env.local")]
  152. : []),
  153. // 开发态 host process 不经过 Vite,自行加载相同的 .env 文件以保持 OAuth 配置一致。
  154. ...(workspaceRoot && isLocalDevelopmentRuntime
  155. ? [
  156. resolve(workspaceRoot, ".env.development"),
  157. resolve(workspaceRoot, ".env.development.local"),
  158. ]
  159. : []),
  160. resolve(desktopRoot, ".env"),
  161. resolve(desktopRoot, ".env.local"),
  162. ...(isLocalDevelopmentRuntime
  163. ? [resolve(desktopRoot, ".env.development"), resolve(desktopRoot, ".env.development.local")]
  164. : []),
  165. ];
  166. const merged: Record<string, string> = {};
  167. const seen = new Set<string>();
  168. for (const candidate of fileCandidates) {
  169. if (seen.has(candidate)) {
  170. continue;
  171. }
  172. seen.add(candidate);
  173. if (!existsSync(candidate)) {
  174. continue;
  175. }
  176. // 之前按 cwd 向上级目录泛搜 .env,容易误读到工作区外的同名文件。
  177. // 这里将加载范围收敛为 workspace 根与 desktop 包目录,避免配置来源漂移。
  178. const parsed = parseDotenv(readFileSync(candidate, "utf-8"));
  179. Object.assign(merged, parsed);
  180. }
  181. return applySelectedZCodeEnvLinks(merged);
  182. }
  183. export function resolvePackagedAgentTelemetryEnv(
  184. compiledEnv:
  185. | Readonly<Record<string, string>>
  186. | undefined = typeof __ZCODE_PACKAGED_AGENT_TELEMETRY_ENV__ === "undefined"
  187. ? undefined
  188. : __ZCODE_PACKAGED_AGENT_TELEMETRY_ENV__,
  189. ): Record<string, string> {
  190. if (!compiledEnv) {
  191. return {};
  192. }
  193. // 修复原因:开发版通过启动进程继承 OTLP 配置,正式安装包从 Finder/开始菜单启动时没有
  194. // 这组运行时环境,Agent 因而静默落入 Noop。构建默认值只允许连接字段进入 Main;
  195. // UID、Device MID 和 runtime surface 仍由 Host 的可信运行时上下文生成。
  196. return readZCodeAgentTelemetryEnv({
  197. OTEL_EXPORTER_OTLP_ENDPOINT: compiledEnv.OTEL_EXPORTER_OTLP_ENDPOINT,
  198. OTEL_EXPORTER_OTLP_HEADERS: compiledEnv.OTEL_EXPORTER_OTLP_HEADERS,
  199. OTEL_SERVICE_NAME: compiledEnv.OTEL_SERVICE_NAME,
  200. ZCODE_TELEMETRY_RUNTIME_DISTRIBUTION: compiledEnv.ZCODE_TELEMETRY_RUNTIME_DISTRIBUTION,
  201. });
  202. }
  203. function resolveDevelopmentMockCdnDir(): string {
  204. return join(import.meta.dirname, "../../mock-cdn");
  205. }
  206. function resolveAvailableDevelopmentMockCdnDir(): string | undefined {
  207. const mockCdnDir = resolveDevelopmentMockCdnDir();
  208. const releaseDir = join(mockCdnDir, "releases", ZCODE_VERSION);
  209. // 开发态 mock-cdn 是可选离线缓存。当前版本目录不存在时继续传 mockCdnDir,
  210. // 会让 WSL/SSH 重连先命中一个必然缺失的本地路径,遮蔽已有的 CDN/cache fallback。
  211. return existsSync(releaseDir) ? mockCdnDir : undefined;
  212. }
  213. function isTruthyEnvFlag(value: string | undefined): boolean {
  214. if (!value) {
  215. return false;
  216. }
  217. const normalized = value.trim().toLowerCase();
  218. return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
  219. }
  220. function shouldUseRemoteCdnInDevelopment(localEnv: LocalRuntimeEnv = {}): boolean {
  221. return isTruthyEnvFlag(resolveEnvValue("ZCODE_DEV_REMOTE_ASSET_USE_CDN", localEnv));
  222. }
  223. function resolveRemoteCdnBaseUrls(
  224. options: ResolveRemoteCdnOptions = {},
  225. localEnv: LocalRuntimeEnv = {},
  226. ): string[] {
  227. const raw = resolveEnvValue("ZCODE_REMOTE_ASSET_CDN_BASE_URL", localEnv);
  228. return resolveOrderedRemoteCdnBaseUrls({
  229. ...options,
  230. env: ZCODE_ENV,
  231. overrideBaseUrl: raw,
  232. version: ZCODE_VERSION,
  233. });
  234. }
  235. function resolveEnvValue(envName: string, localEnv: LocalRuntimeEnv = {}): string | undefined {
  236. return process.env[envName]?.trim() || localEnv[envName]?.trim() || undefined;
  237. }
  238. export function resolveZCodeEndpointEnvBaseOrigin(
  239. localEnv: LocalRuntimeEnv = {},
  240. ): string | undefined {
  241. const scopedEnvName =
  242. ZCODE_ENV === "production" ? "ZCODE_PRODUCTION_BASE_URL" : "ZCODE_TEST_BASE_URL";
  243. // Bugfix: main 进程临时验证更新服务时不会重新写 .env,命令行传入的 endpoint 必须优先于本地文件。
  244. return (
  245. process.env["ZCODE_BASE_URL"]?.trim() ||
  246. process.env["ZCODE_ENDPOINT_ORIGIN"]?.trim() ||
  247. process.env[scopedEnvName]?.trim() ||
  248. localEnv.ZCODE_BASE_URL?.trim() ||
  249. localEnv.ZCODE_ENDPOINT_ORIGIN?.trim() ||
  250. localEnv[scopedEnvName]?.trim() ||
  251. undefined
  252. );
  253. }
  254. function readDefinedProcessEnv(): Record<string, string> {
  255. const values: Record<string, string> = {};
  256. for (const [key, value] of Object.entries(process.env)) {
  257. if (typeof value === "string") {
  258. values[key] = value;
  259. }
  260. }
  261. return values;
  262. }
  263. function applySelectedZCodeEnvLinks(env: Record<string, string>): Record<string, string> {
  264. const endpointEnv = {
  265. ...env,
  266. ZCODE_ENV,
  267. };
  268. return {
  269. ...env,
  270. ZCODE_BASE_URL: env.ZCODE_BASE_URL ?? resolveRuntimeZCodeEndpointOrigin(endpointEnv),
  271. ZAI_OAUTH_ORIGIN: env.ZAI_OAUTH_ORIGIN ?? resolveZaiOAuthOrigin(endpointEnv),
  272. ZAI_BUSINESS_BASE_URL: env.ZAI_BUSINESS_BASE_URL ?? resolveZaiBusinessBaseUrl(endpointEnv),
  273. ZAI_OAUTH_CLIENT_ID: env.ZAI_OAUTH_CLIENT_ID ?? resolveZaiOAuthClientId(endpointEnv),
  274. };
  275. }
  276. function resolveHostProcessNodeEnv(): ZCodeRuntimeEnv {
  277. return desktopRuntimeEnv;
  278. }
  279. function resolveRemoteAssetCacheDir(localEnv: LocalRuntimeEnv = {}): string {
  280. const overrideCacheDir = resolveEnvValue("ZCODE_REMOTE_ASSET_CACHE_DIR", localEnv);
  281. if (overrideCacheDir) {
  282. // 开发态需要复用正式版 remote cache 验证下载判断,但不能整体切换 Electron userData。
  283. // 因此只允许覆盖 remote assets cache 目录,避免污染登录态、窗口状态等其它开发数据。
  284. return resolve(overrideCacheDir);
  285. }
  286. return join(getElectronAppPath("userData"), "remote-assets-cache");
  287. }
  288. export function resolveRemoteAssetDirs(
  289. options: ResolveRemoteCdnOptions = {},
  290. localEnv: LocalRuntimeEnv = {},
  291. ): RemoteAssetDirs {
  292. const remoteCdnBaseUrls = resolveRemoteCdnBaseUrls(options, localEnv);
  293. const remoteCdnBaseUrl = remoteCdnBaseUrls[0];
  294. // remote 资源之前和 desktop 本地 provider 资源共用安装包内路径,
  295. // 结果打包后会把整套 Linux 远程运行时一起塞进 .app,和“remote 资源走 CDN / mock-cdn”的职责边界冲突。
  296. // 这里改成显式分流:开发态只读仓库里的 mock-cdn;生产态统一走 CDN + 本地缓存目录,
  297. // 不再暴露任何安装包内 remote-assets 路径,避免 remote 资源再次被塞回安装包。
  298. // 功能开关:开发态默认继续走 mock-cdn,只有显式打开开关才切到公网 CDN。
  299. // 这样能兼容离线开发场景,同时允许在开发环境提前验证真实 CDN 下载链路。
  300. if (isElectronAppPackaged() || shouldUseRemoteCdnInDevelopment(localEnv)) {
  301. return {
  302. remoteCdnBaseUrl,
  303. remoteCdnBaseUrls,
  304. remoteCacheDir: resolveRemoteAssetCacheDir(localEnv),
  305. };
  306. }
  307. const developmentMockCdnDir = resolveAvailableDevelopmentMockCdnDir();
  308. return {
  309. ...(developmentMockCdnDir ? { mockCdnDir: developmentMockCdnDir } : {}),
  310. // Bug 原因:ZCODE_ENV 表示测试/生产产品环境,dev:desktop 也可能取 production;
  311. // 同版本开发制品刷新必须由未打包 Electron 这一运行形态显式授权。
  312. sourceServerArtifactPolicy: "development-content-addressed",
  313. remoteCdnBaseUrl,
  314. remoteCdnBaseUrls,
  315. remoteCacheDir: resolveRemoteAssetCacheDir(localEnv),
  316. };
  317. }
  318. function resolveBundledZCodeAgentBinaryPath(): string | undefined {
  319. const runtime = ZCODE_AGENT_RUNTIME;
  320. const entrySegments = runtime.resolveEntrySegments(process.platform);
  321. const platformKey = resolvePlatformKeyForPackagedApp();
  322. const candidates = [
  323. isElectronAppPackaged()
  324. ? join(process.resourcesPath, runtime.bundledResourceDir, ...entrySegments)
  325. : null,
  326. // desktop 开发态的启动 cwd 可能是 packages/desktop,也可能是仓库根,
  327. // 之前这里只按 import.meta.dirname 的相对路径推导 bundled-agents,
  328. // 这里补齐和 services 侧一致的多候选根目录,避免开发/构建/重启入口不同导致资源解析漂移。
  329. join(
  330. process.cwd(),
  331. "bundled-agents",
  332. platformKey,
  333. runtime.bundledResourceDir,
  334. ...entrySegments,
  335. ),
  336. join(
  337. process.cwd(),
  338. "packages",
  339. "desktop",
  340. "bundled-agents",
  341. platformKey,
  342. runtime.bundledResourceDir,
  343. ...entrySegments,
  344. ),
  345. join(
  346. import.meta.dirname,
  347. "../../bundled-agents",
  348. platformKey,
  349. runtime.bundledResourceDir,
  350. ...entrySegments,
  351. ),
  352. ].filter((candidate): candidate is string => Boolean(candidate));
  353. return candidates.find((candidate) => existsSync(candidate));
  354. }
  355. function resolveBundledRuntimeToolBinaryPath(
  356. toolDir: string,
  357. binaryName: string,
  358. ): string | undefined {
  359. const candidateBinaryName = process.platform === "win32" ? `${binaryName}.exe` : binaryName;
  360. const candidates = [
  361. isElectronAppPackaged()
  362. ? join(process.resourcesPath, "tools", toolDir, candidateBinaryName)
  363. : null,
  364. join(
  365. import.meta.dirname,
  366. "../../bundled-tools",
  367. resolvePlatformKeyForPackagedApp(),
  368. toolDir,
  369. candidateBinaryName,
  370. ),
  371. ].filter((candidate): candidate is string => Boolean(candidate));
  372. return candidates.find((candidate) => existsSync(candidate));
  373. }
  374. function resolveBundledLarkCliBinaryPath(): string | undefined {
  375. return resolveBundledRuntimeToolBinaryPath("lark-cli", "lark-cli");
  376. }
  377. export function resolveBundledGlmBinaryPath(): string | undefined {
  378. return resolveBundledZCodeAgentBinaryPath();
  379. }
  380. function resolveHostProcessBinaryEnv(
  381. envVar: string,
  382. hostProcessLocalEnv: Record<string, string>,
  383. bundledPath: string | undefined,
  384. ): string | undefined {
  385. // ZCode Agent 与 app 协议适配强绑定版本,生产包必须优先使用随包携带的固定 runtime。
  386. // 用户机器或本地 .env 里残留的 GLM_BINARY_PATH 即使存在,也可能版本不兼容。
  387. // 只有 bundled runtime 缺失时才把显式路径作为兜底,避免用户本机 CLI 覆盖内嵌版本。
  388. if (bundledPath) {
  389. return bundledPath;
  390. }
  391. const explicitPath = process.env[envVar]?.trim() || hostProcessLocalEnv[envVar]?.trim();
  392. if (explicitPath && existsSync(explicitPath)) {
  393. return explicitPath;
  394. }
  395. return undefined;
  396. }
  397. export function resolveWindowsAppInstallDirForDataBaseDirGuard(
  398. options: {
  399. platform?: NodeJS.Platform | string;
  400. isPackaged?: boolean;
  401. resourcesPath?: string;
  402. } = {},
  403. ): string | undefined {
  404. const platform = options.platform ?? process.platform;
  405. const packaged = options.isPackaged ?? isElectronAppPackaged();
  406. const resourcesPath = options.resourcesPath ?? process.resourcesPath;
  407. if (platform !== "win32" || !packaged) {
  408. return undefined;
  409. }
  410. const trimmedResourcesPath = resourcesPath?.trim();
  411. if (!trimmedResourcesPath) {
  412. return undefined;
  413. }
  414. return win32.dirname(trimmedResourcesPath);
  415. }
  416. /**
  417. * Dynamic Workflow 灰度的本地覆盖按构建档位分三层
  418. *
  419. * - 未打包 dev:透传 shell 里的合法取值,方便手工切档;非法值直接丢弃而不是转发给 Host,
  420. * Host 因此不必再判一次来源;
  421. * - 打包 preview:固定写入 `alwaysOn`,忽略 shell,preview 用户始终拥有该功能;
  422. * - 打包 production:不写入,且继承值必须被删除,否则本机环境变量就能自行打开灰度。
  423. * Main 是唯一决策者:对这个键只有「写」和「删」两种动作,绝不原样透传,
  424. * Host 端的 resolveDynamicWorkflowClientConfig 才能无条件相信读到的值。
  425. */
  426. export function resolveDynamicWorkflowModeHostEnv(options: {
  427. inheritedValue: string | undefined;
  428. isPackaged: boolean;
  429. isPreview: boolean;
  430. }): Record<string, string> {
  431. if (!options.isPackaged) {
  432. const mode = normalizeDynamicWorkflowMode(options.inheritedValue);
  433. return mode ? { [ZCODE_DYNAMIC_WORKFLOW_MODE_ENV]: mode } : {};
  434. }
  435. if (options.isPreview) {
  436. return { [ZCODE_DYNAMIC_WORKFLOW_MODE_ENV]: "alwaysOn" };
  437. }
  438. return {};
  439. }
  440. export function buildHostProcessEnv(hostProcessLocalEnv: Record<string, string>) {
  441. const glmBinaryPath = resolveBundledGlmBinaryPath();
  442. const larkCliBinaryPath = resolveBundledLarkCliBinaryPath();
  443. const resolvedGlmBinaryPath = resolveHostProcessBinaryEnv(
  444. "GLM_BINARY_PATH",
  445. hostProcessLocalEnv,
  446. glmBinaryPath,
  447. );
  448. const resolvedLarkCliBinaryPath = resolveHostProcessBinaryEnv(
  449. "ZCODE_LARK_CLI_BINARY",
  450. hostProcessLocalEnv,
  451. larkCliBinaryPath,
  452. );
  453. const dataBaseDir = getDataBaseDir();
  454. const rawInheritedEnv = {
  455. ...hostProcessLocalEnv,
  456. ...readDefinedProcessEnv(),
  457. };
  458. const packagedDesktop = isElectronAppPackaged();
  459. const bundledCuaHelperAppPath =
  460. process.platform !== "darwin"
  461. ? undefined
  462. : packagedDesktop
  463. ? join(process.resourcesPath, "cua-helper", HELPER_APP_NAME)
  464. : // Truthy grammar must match the producer's isUnsignedHelperLocalDevRequested
  465. // (1|true|on, case-insensitive). Accepting only the literal "1" silently
  466. // ignored `true`/`on` set by scripts following the documented dev flow.
  467. ["1", "true", "on"].includes(
  468. rawInheritedEnv.ZCODE_CUA_HELPER_ALLOW_UNSIGNED_LOCAL?.trim().toLowerCase() ?? "",
  469. )
  470. ? rawInheritedEnv.ZCODE_CUA_BUNDLED_HELPER_APP_PATH?.trim() ||
  471. join(
  472. rawInheritedEnv.ZCODE_HOME?.trim() || join(homedir(), ".zcode"),
  473. "computer-use",
  474. "dev",
  475. DEV_HELPER_APP_NAME,
  476. )
  477. : undefined;
  478. const windowsAppInstallDir = resolveWindowsAppInstallDirForDataBaseDirGuard();
  479. const agentTelemetryEnv = readZCodeAgentTelemetryEnv(rawInheritedEnv);
  480. // Desktop 身份由 host 从凭据仓库和本机状态读取后可信注入;外部环境只能配置 OTLP 连接,
  481. // 不能伪造 uid/device/runtime surface 或绕过本地 identity state 的隔离边界。
  482. for (const key of [
  483. "ZCODE_TELEMETRY_USER_ID",
  484. "ZCODE_TELEMETRY_USER_ID_HASH",
  485. "ZCODE_TELEMETRY_USER_SUBJECT_ID",
  486. "ZCODE_TELEMETRY_IDENTITY_STATE",
  487. "ZCODE_TELEMETRY_DEVICE_MID",
  488. "ZCODE_TELEMETRY_RUNTIME_SURFACE",
  489. ]) {
  490. delete agentTelemetryEnv[key];
  491. }
  492. const inheritedEnv = applySelectedZCodeEnvLinks({
  493. ...sanitizeZCodeRuntimeEnv(rawInheritedEnv),
  494. ...buildZCodeToolEnvPassthroughEnv(rawInheritedEnv),
  495. });
  496. // A release app must never inherit the local unsigned-Helper escape hatch.
  497. // Otherwise a developer shell/launchctl variable can make the signed app
  498. // reject its verified bundled Helper and route onboarding to a stale dev app.
  499. if (packagedDesktop) {
  500. delete inheritedEnv.ZCODE_CUA_HELPER_ALLOW_UNSIGNED_LOCAL;
  501. }
  502. const dynamicWorkflowModeHostEnv = resolveDynamicWorkflowModeHostEnv({
  503. inheritedValue: rawInheritedEnv[ZCODE_DYNAMIC_WORKFLOW_MODE_ENV],
  504. isPackaged: packagedDesktop,
  505. isPreview: isPreviewPackagedRuntime,
  506. });
  507. // 三层里有两层不写这个键,空对象无法覆盖 inheritedEnv,所以先无条件删掉继承值再按决策 spread 回去。
  508. // 少了这一行,production 包和 dev 的非法取值都会原样穿透到 Host。
  509. delete inheritedEnv[ZCODE_DYNAMIC_WORKFLOW_MODE_ENV];
  510. return {
  511. ...inheritedEnv,
  512. // OTLP 凭据只定向传到 host;host 初始化 services 时会立即捕获并从 process.env 清除,
  513. // 后续只在启动 Agent 时短暂注入,不会进入 Bash/MCP/tool env。
  514. ...agentTelemetryEnv,
  515. // ZCode 运行时不再使用 NODE_ENV;它会被用户 shell、包管理器和测试框架复用。
  516. // 这里显式下发 ZCODE_RUNTIME_ENV,并在继承环境里清掉 NODE_ENV,避免 host/agent/Bash 被污染。
  517. [ZCODE_RUNTIME_ENV_KEY]: resolveHostProcessNodeEnv(),
  518. // 显式注入编译期产品身份,保证主进程与 host 的身份语义一致;地址独立解析。
  519. // inheritedEnv 从 .env 通用变量补齐 ZCode/ZAI 链接,未覆盖时统一使用线上默认值。
  520. ZCODE_ENV,
  521. // Preview 与生产版共享任务、配置和凭据,但不同版本的 Helper 不能互相覆盖或触发降级保护。
  522. // 只隔离 computer-use 下的运行组件,不改写 ZCODE_HOME / ZCODE_DATA_BASE_DIR 业务数据根。
  523. ...(isPreviewPackagedRuntime ? { ZCODE_CUA_HELPER_INSTALL_VARIANT: "preview" } : {}),
  524. // Dynamic Workflow 灰度的本地覆盖:Main 决策后写入,production 包为空对象(继承值已在上面删除)。
  525. ...dynamicWorkflowModeHostEnv,
  526. // 模型请求默认 header 由 agent 进程构造,过去只继承 shell env 导致桌面启动时拿不到 app 版本。
  527. // 这里从 main 进程显式下发,agent 子进程继承 host env 后即可稳定写入请求 header。
  528. [ZCODE_APP_VERSION_ENV]: ZCODE_VERSION,
  529. // Telemetry 的构建身份必须来自 Desktop 编译期元数据,不能让 Agent 在运行时读取
  530. // 工作树或根据安装路径猜测;否则同一产品版本的不同修复包无法在 ARMS 中区分。
  531. [ZCODE_BUILD_COMMIT_ID_ENV]: ZCODE_COMMIT,
  532. ...(dataBaseDir !== homedir() ? { ZCODE_DATA_BASE_DIR: dataBaseDir } : {}),
  533. ...(windowsAppInstallDir ? { [ZCODE_WINDOWS_APP_INSTALL_DIR_ENV]: windowsAppInstallDir } : {}),
  534. ...(bundledCuaHelperAppPath
  535. ? { [ZCODE_CUA_BUNDLED_HELPER_APP_PATH_ENV]: bundledCuaHelperAppPath }
  536. : {}),
  537. ...(resolvedGlmBinaryPath ? { GLM_BINARY_PATH: resolvedGlmBinaryPath } : {}),
  538. ...(resolvedLarkCliBinaryPath ? { ZCODE_LARK_CLI_BINARY: resolvedLarkCliBinaryPath } : {}),
  539. };
  540. }