desktopRuntimeEnv.ts 24 KB

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