provider-runtime-env.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. import { existsSync, realpathSync } from "node:fs";
  2. import { homedir } from "node:os";
  3. import { dirname, join, resolve } from "node:path";
  4. import {
  5. materializeZCodeBuiltinProviderConfig,
  6. NodeZCodeBuiltinProviderConfigSource,
  7. PERSONAL_PROVIDER_CONFIG_FILE_NAME,
  8. resolveZCodeBuiltinCachePaths,
  9. resolveZCodeBuiltinClientPlatform,
  10. ZCODE_BUILTIN_PROVIDER_BUNDLED_CONFIG_FILE_ENV,
  11. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV,
  12. ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV,
  13. type ZCodeBuiltinRefreshEvent,
  14. } from "@zcode/provider-node";
  15. import { resolveRuntimeZCodeEndpointOrigin, ZCODE_VERSION } from "@zcode/shared";
  16. import type { CliEnv } from "./env.js";
  17. export const SEA_ZCODE_BUILTIN_PROVIDER_CONFIG_ASSET_KEY = "zcode-provider/zcode-builtin.json";
  18. export function createCliProviderRefreshReporter(
  19. stderr: Pick<NodeJS.WriteStream, "write"> = process.stderr,
  20. ) {
  21. return {
  22. onBuiltinRefreshError(error: unknown) {
  23. stderr.write(
  24. `ZCode Built-in 刷新失败: ${error instanceof Error ? error.message : "unknown error"}\n`,
  25. );
  26. },
  27. onBuiltinRefreshResult(event: ZCodeBuiltinRefreshEvent) {
  28. // TTL 检查不是生产事件;成功更新才默认留痕,不能输出 CDN URL 查询参数或内容。
  29. if (event.result === "updated" || process.env.NODE_ENV !== "production") {
  30. stderr.write(
  31. `ZCode Built-in ${event.result}${event.reason ? ` (${event.reason})` : ""}${event.revision === undefined ? "" : ` revision=${event.revision} source=CDN`}\n`,
  32. );
  33. }
  34. },
  35. };
  36. }
  37. type SeaProviderConfigAssets = Pick<typeof import("node:sea"), "getAsset" | "isSea">;
  38. interface PrepareCliProviderRuntimeEnvOptions {
  39. readonly argv: readonly string[];
  40. readonly env: CliEnv;
  41. readonly dataBaseDir?: string;
  42. readonly entrypoint?: string;
  43. readonly sea?: SeaProviderConfigAssets;
  44. readonly appVersion?: string;
  45. readonly platform?: string;
  46. }
  47. /** 为运行 Core 或写入模型选择的 CLI Entry 定位同一 Environment 的 Provider Config。 */
  48. export async function prepareCliProviderRuntimeEnv(
  49. options: PrepareCliProviderRuntimeEnvOptions,
  50. ): Promise<Record<string, string>> {
  51. if (!requiresProviderRuntime(options.argv)) return {};
  52. const explicitZCodeBuiltin = options.env[ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]?.trim();
  53. const explicitPersonal = options.env[ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]?.trim();
  54. const dataBaseDir = options.dataBaseDir ?? options.env.ZCODE_DATA_BASE_DIR?.trim() ?? homedir();
  55. if (explicitZCodeBuiltin && explicitPersonal) {
  56. return {
  57. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: explicitZCodeBuiltin,
  58. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: explicitPersonal,
  59. };
  60. }
  61. const zcodeBuiltinFilePath =
  62. explicitZCodeBuiltin ??
  63. (await resolveBundledZCodeBuiltinProviderConfig({
  64. dataBaseDir,
  65. entrypoint: options.entrypoint ?? process.argv[1],
  66. sea: options.sea ?? getSeaProviderConfigAssets(),
  67. }));
  68. const personalFilePath =
  69. explicitPersonal ?? join(dataBaseDir, ".zcode", "v2", PERSONAL_PROVIDER_CONFIG_FILE_NAME);
  70. const appVersion = options.appVersion ?? ZCODE_VERSION;
  71. const platform = options.platform ?? resolveZCodeBuiltinClientPlatform();
  72. const zcodeEndpointOrigin = resolveRuntimeZCodeEndpointOrigin(options.env);
  73. const cachePaths = resolveZCodeBuiltinCachePaths({
  74. environmentConfigRoot: join(dataBaseDir, ".zcode", "v2"),
  75. platform,
  76. appVersion,
  77. zcodeEndpointOrigin,
  78. });
  79. const source = new NodeZCodeBuiltinProviderConfigSource({
  80. bundledFilePath: zcodeBuiltinFilePath,
  81. activeFilePath: cachePaths.activeFilePath,
  82. watch: false,
  83. });
  84. // 入口只准备资源和路径;下载由 Prompt/TUI 长生命周期 Runtime 持有并取消。
  85. try {
  86. await source.read();
  87. } finally {
  88. source.dispose();
  89. }
  90. return {
  91. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: cachePaths.activeFilePath,
  92. [ZCODE_BUILTIN_PROVIDER_BUNDLED_CONFIG_FILE_ENV]: zcodeBuiltinFilePath,
  93. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: personalFilePath,
  94. };
  95. }
  96. function requiresProviderRuntime(argv: readonly string[]): boolean {
  97. if (argv.some((arg) => arg === "--help" || arg === "-h" || arg === "--version" || arg === "-v")) {
  98. return false;
  99. }
  100. if (
  101. argv.some(
  102. (arg) =>
  103. arg === "--prompt" ||
  104. arg.startsWith("--prompt=") ||
  105. arg === "--target" ||
  106. arg.startsWith("--target="),
  107. )
  108. ) {
  109. return true;
  110. }
  111. const command = argv[0];
  112. if (command === undefined || command.startsWith("-")) return true;
  113. return (
  114. command === "tui" ||
  115. command === "app-server" ||
  116. command === "agent-server" ||
  117. command === "login" ||
  118. command === "logout"
  119. );
  120. }
  121. async function resolveBundledZCodeBuiltinProviderConfig(input: {
  122. readonly dataBaseDir: string;
  123. readonly entrypoint: string | undefined;
  124. readonly sea: SeaProviderConfigAssets | undefined;
  125. }): Promise<string> {
  126. if (input.sea?.isSea()) {
  127. const content = input.sea.getAsset(SEA_ZCODE_BUILTIN_PROVIDER_CONFIG_ASSET_KEY, "utf8");
  128. return materializeZCodeBuiltinProviderConfig({
  129. environmentConfigRoot: join(input.dataBaseDir, ".zcode", "v2"),
  130. content,
  131. });
  132. }
  133. const entrypoint = input.entrypoint?.trim();
  134. if (!entrypoint) throw new Error("无法定位 CLI ZCode Built-in Provider Config:缺少入口路径");
  135. // 全局 bin 可以是软链接,随包配置必须相对真实入口定位。
  136. const entryDirectory = dirname(realpathSync(resolve(entrypoint)));
  137. const candidates = [
  138. join(entryDirectory, "provider", "zcode-builtin.json"),
  139. resolve(entryDirectory, "../../../../../config/provider/zcode-builtin.json"),
  140. ];
  141. const candidate = candidates.find((filePath) => existsSync(filePath));
  142. if (candidate) return candidate;
  143. throw new Error(`无法定位 CLI ZCode Built-in Provider Config:${candidates.join(", ")}`);
  144. }
  145. function getSeaProviderConfigAssets(): SeaProviderConfigAssets | undefined {
  146. const getBuiltinModule = process.getBuiltinModule as
  147. | ((id: "node:sea") => typeof import("node:sea"))
  148. | undefined;
  149. return getBuiltinModule?.("node:sea");
  150. }