runtime-config.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. import type { ConfigResult } from "@zcode/adapters/config";
  2. import { GEN_UI_OUTPUT_ROOT_ENV } from "@zcode/shared/node";
  3. import { resolveInitialModelSelection, type ModelSelectionOptions } from "@zcode/provider";
  4. import { resolveBashTimeoutPolicy, type AgentProfile, type AgentRuntimeConfig } from "@zcode/core";
  5. import { type BuiltInSubagentModelSelectionOverrides } from "@zcode/shared";
  6. import {
  7. type CollaborationMode,
  8. type HookConfigSource,
  9. type HookEventName,
  10. type HookMatcherConfig,
  11. type HooksRuntimeConfig,
  12. type McpConfigurationSnapshot,
  13. } from "@zcode/contracts";
  14. import { resolveDefaultEmbeddedSearchBackend } from "./embedded-search-backend.js";
  15. import { getProjectMemoryRoot } from "./paths.js";
  16. import type { ZCodeAppOptions } from "./types.js";
  17. import {
  18. resolveRegistryOwnedModelSelection,
  19. resolveRegistryModelSelection,
  20. type ResolvedRegistrySelection,
  21. } from "./provider-registry-selection.js";
  22. interface ResolvedAppRuntimeConfig {
  23. runtimeConfig: AgentRuntimeConfig;
  24. untrustedProjectMcpServers: Set<string>;
  25. }
  26. interface ResolvedInitialRegistrySelection extends ResolvedRegistrySelection {
  27. readonly selectionOptions?: ModelSelectionOptions;
  28. }
  29. export function resolveAppRuntimeConfig(input: {
  30. cliStorageRoot: string;
  31. configResult: ConfigResult;
  32. options: ZCodeAppOptions;
  33. persistedMode?: CollaborationMode;
  34. mcpConfiguration: Partial<McpConfigurationSnapshot>;
  35. builtInSubagentModelSelectionOverrides?: BuiltInSubagentModelSelectionOverrides;
  36. pluginHooks?: Partial<Record<HookEventName, HookMatcherConfig[]>>;
  37. pluginRuntimeFeatures?: AgentRuntimeConfig["runtimeFeatures"];
  38. subagentOutputRootDir: string;
  39. subagentProfiles?: readonly AgentProfile[];
  40. storageRoot?: string;
  41. workingDirectory: string;
  42. workspaceIdentity?: string;
  43. }): ResolvedAppRuntimeConfig {
  44. const {
  45. cliStorageRoot,
  46. configResult,
  47. options,
  48. persistedMode,
  49. pluginRuntimeFeatures,
  50. subagentOutputRootDir,
  51. subagentProfiles = [],
  52. workingDirectory,
  53. workspaceIdentity,
  54. } = input;
  55. const userInstructions = options.runtimeConfig?.userInstructions ?? { workingDirectory };
  56. const registrySelection = resolveInitialRegistrySelection(options);
  57. // 恢复历史不等于开始执行:失效/缺失选择保持未绑定,不能借 configured default 补齐。
  58. const initialModelSelection = options.resume
  59. ? registrySelection?.selection
  60. : (options.runtimeConfig?.modelSelection ?? registrySelection?.selection);
  61. // 空白会话先创建、再应用本次 Submission 的选择;强制初始默认模型会
  62. // 让未配置 default 的用户在 switch/send 前就创建失败。未绑定 Runtime 可以存在,
  63. // 真正执行仍由 admission/ModelFactory 校验完整选择,不能在这里偷偷选择 Registry 首项。
  64. const requestedTitleGeneration = options.runtimeConfig?.titleGeneration;
  65. const requestedTitleModelSelection = requestedTitleGeneration?.modelSelection;
  66. const titleGeneration =
  67. requestedTitleGeneration === undefined
  68. ? undefined
  69. : {
  70. ...requestedTitleGeneration,
  71. // 标题生成 sidecar 默认 15s 在慢模型/代理链路下容易超时,
  72. // 入口层统一补 60s,避免旧 core 默认值或空配置让桌面端继续回落到 15s。
  73. timeoutMs: requestedTitleGeneration.timeoutMs ?? 60_000,
  74. // 空 titleGeneration 表示启用默认标题生成,模型必须跟随会话当前模型。
  75. // 如果这里在草稿 session 创建时固化另一份标题模型,之后切模型只会更新主链路,
  76. // 首发时的 generate title sidecar 会继续使用切换前的旧 provider/model。
  77. ...(requestedTitleModelSelection
  78. ? {
  79. modelSelection: requestedTitleModelSelection,
  80. }
  81. : {}),
  82. };
  83. // 配置合并与磁盘 server 的来源标记都在 MCP 配置源完成;这里把 workspace 来源计入待信任集合,
  84. // 并按 createConfig 的来源给没有标记的显式 server 补标。
  85. const mcpServers = { ...input.mcpConfiguration.servers };
  86. const untrustedProjectMcpServers = new Set<string>();
  87. for (const [name, config] of Object.entries(mcpServers)) {
  88. if (
  89. config.source?.kind === "workspace" ||
  90. (!config.source && configResult.sources.mcp.serverSources[name] === "project")
  91. ) {
  92. mcpServers[name] = { ...config, source: { kind: "workspace" } };
  93. untrustedProjectMcpServers.add(name);
  94. } else if (!config.source && configResult.sources.mcp.serverSources[name] === "user") {
  95. // headless 配置也保留用户来源,项目文件损坏不能把用户 MCP 当成待信任声明。
  96. mcpServers[name] = { ...config, source: { kind: "user" } };
  97. }
  98. }
  99. const runtimeBuiltInModelSelectionOverrides =
  100. options.runtimeConfig?.subagents?.builtInModelSelectionOverrides ?? {};
  101. const runtimeConfig: AgentRuntimeConfig = {
  102. ...options.runtimeConfig,
  103. genUiOutputRoot: (options.env ?? process.env)[GEN_UI_OUTPUT_ROOT_ENV],
  104. bashTimeoutPolicy:
  105. options.runtimeConfig?.bashTimeoutPolicy ??
  106. resolveBashTimeoutPolicy(options.env ?? process.env),
  107. mode: options.runtimeConfig?.mode ?? persistedMode ?? configResult.config.permission.mode,
  108. modelSelection: initialModelSelection,
  109. // 仅接受显式传入的会话级工具面(ZCode Protocol session/create 或 CLI
  110. // --allowed-tools/--disallowed-tools)。不要从 config.permission.allowedTools
  111. // 回落:那个键的既有语义是“免审批清单”,把它投影到注册面会让老配置里
  112. // 只写了几个 allowedTools 的用户突然丢失其余全部工具。
  113. toolAllowlist: options.runtimeConfig?.toolAllowlist,
  114. toolDisallowlist: options.runtimeConfig?.toolDisallowlist,
  115. embeddedSearchBackend:
  116. options.runtimeConfig?.embeddedSearchBackend ??
  117. resolveDefaultEmbeddedSearchBackend({
  118. env: options.env,
  119. }),
  120. runtimeFeatures: pluginRuntimeFeatures,
  121. titleGeneration,
  122. workingDirectory,
  123. additionalDirectories: options.additionalDirectories,
  124. userInstructions: {
  125. ...userInstructions,
  126. workingDirectory: userInstructions.workingDirectory ?? workingDirectory,
  127. },
  128. skillMetadataBudget:
  129. options.runtimeConfig?.skillMetadataBudget ?? configResult.config.skills.metadataBudget,
  130. toolConcurrency: {
  131. maxConcurrency:
  132. options.runtimeConfig?.toolConcurrency?.maxConcurrency ??
  133. configResult.config.toolConcurrency.maxConcurrency,
  134. },
  135. modelAnomalyGuard: {
  136. ...configResult.config.modelAnomalyGuard,
  137. ...options.runtimeConfig?.modelAnomalyGuard,
  138. },
  139. mcp: { ...input.mcpConfiguration, servers: mcpServers },
  140. hooks: mergeRuntimeHooks(
  141. options.runtimeConfig?.hooks
  142. ? withHookConfigSource(options.runtimeConfig.hooks, { kind: "internal" })
  143. : configResult.config.hooks,
  144. input.pluginHooks,
  145. ),
  146. subagents: {
  147. ...readSubagentStallNotifyOverride(options.env ?? process.env),
  148. ...options.runtimeConfig?.subagents,
  149. enabled: options.runtimeConfig?.subagents?.enabled ?? configResult.config.features.subagent,
  150. outputRootDir: options.runtimeConfig?.subagents?.outputRootDir ?? subagentOutputRootDir,
  151. builtInModelSelectionOverrides: {
  152. ...(input.builtInSubagentModelSelectionOverrides ?? {}),
  153. ...runtimeBuiltInModelSelectionOverrides,
  154. },
  155. profiles: [...(options.runtimeConfig?.subagents?.profiles ?? []), ...subagentProfiles],
  156. },
  157. memory: {
  158. cliStorageRoot,
  159. enabled: options.runtimeConfig?.memory?.enabled ?? configResult.config.features.memory,
  160. ...(options.runtimeConfig?.memory?.extractionEnabled === undefined
  161. ? {}
  162. : { extractionEnabled: options.runtimeConfig.memory.extractionEnabled }),
  163. ...(input.storageRoot ? { storageRoot: input.storageRoot } : {}),
  164. use: options.runtimeConfig?.memory?.use ?? configResult.config.memory.use,
  165. workspaceIdentity: workspaceIdentity?.trim() || undefined,
  166. },
  167. };
  168. return {
  169. runtimeConfig,
  170. untrustedProjectMcpServers,
  171. };
  172. }
  173. function withHookConfigSource(
  174. config: HooksRuntimeConfig,
  175. source: HookConfigSource,
  176. ): HooksRuntimeConfig {
  177. return {
  178. ...config,
  179. events: Object.fromEntries(
  180. Object.entries(config.events).map(([eventName, matchers]) => [
  181. eventName,
  182. matchers?.map((matcher) => ({
  183. ...matcher,
  184. hooks: matcher.hooks.map((hook) => ({ ...hook, source: hook.source ?? source })),
  185. })),
  186. ]),
  187. ) as HooksRuntimeConfig["events"],
  188. };
  189. }
  190. function resolveInitialRegistrySelection(
  191. options: ZCodeAppOptions,
  192. ): ResolvedInitialRegistrySelection | undefined {
  193. const registry = options.providerRegistry;
  194. if (!registry) return undefined;
  195. if (options.runtimeConfig?.modelSelection) {
  196. const selection = options.runtimeConfig.modelSelection;
  197. if (options.resume && !registry.validateSelection(selection).ok) return undefined;
  198. const resolved = resolveRegistryOwnedModelSelection(registry, selection);
  199. return resolved
  200. ? {
  201. ...resolved,
  202. ...(selection.options ? { selectionOptions: selection.options } : {}),
  203. }
  204. : undefined;
  205. }
  206. if (options.resume) return undefined;
  207. const initial = resolveInitialModelSelection({
  208. configuredDefault: options.configuredDefaultModelSelection,
  209. registry: registry.getView(),
  210. });
  211. if (initial.source === "none") return undefined;
  212. const resolved = resolveRegistryOwnedModelSelection(registry, initial.selection);
  213. return resolved
  214. ? {
  215. ...resolved,
  216. ...(initial.selection.options ? { selectionOptions: initial.selection.options } : {}),
  217. }
  218. : undefined;
  219. }
  220. function mergeRuntimeHooks(
  221. base: HooksRuntimeConfig | undefined,
  222. pluginHooks: Partial<Record<HookEventName, HookMatcherConfig[]>> | undefined,
  223. ): HooksRuntimeConfig | undefined {
  224. if (!pluginHooks || Object.values(pluginHooks).every((matchers) => !matchers?.length)) {
  225. return base;
  226. }
  227. const mergedEvents: HooksRuntimeConfig["events"] = {
  228. ...base?.events,
  229. };
  230. for (const [eventName, matchers] of Object.entries(pluginHooks) as Array<
  231. [HookEventName, HookMatcherConfig[]]
  232. >) {
  233. if (matchers.length === 0) continue;
  234. mergedEvents[eventName] = [...(mergedEvents[eventName] ?? []), ...matchers];
  235. }
  236. return {
  237. enabled: true,
  238. events: mergedEvents,
  239. maxOutputBytes: base?.maxOutputBytes ?? 32768,
  240. timeoutMs: base?.timeoutMs ?? 60000,
  241. };
  242. }
  243. export function runtimeConfigLogContext(
  244. runtimeConfig: AgentRuntimeConfig,
  245. workingDirectory: string,
  246. ) {
  247. const memoryRoot = runtimeConfig.memory?.cliStorageRoot
  248. ? getProjectMemoryRoot(
  249. runtimeConfig.memory.cliStorageRoot,
  250. workingDirectory,
  251. runtimeConfig.memory.workspaceIdentity,
  252. )
  253. : undefined;
  254. return {
  255. mcpEnabled: runtimeConfig.mcp?.enabled !== false,
  256. memoryEnabled: runtimeConfig.memory?.enabled !== false,
  257. memoryExtractionEnabled: runtimeConfig.memory?.extractionEnabled !== false,
  258. memoryRoot,
  259. memoryUse: runtimeConfig.memory?.use !== false,
  260. mcsMode: runtimeConfig.midConversationSystem?.mode,
  261. mode: runtimeConfig.mode,
  262. model: runtimeConfig.modelSelection
  263. ? `${runtimeConfig.modelSelection.providerId}/${runtimeConfig.modelSelection.modelId}`
  264. : undefined,
  265. runtimeFeatureBrowserUse: runtimeConfig.runtimeFeatures?.browserUse === true,
  266. runtimeFeatureNodeRepl: runtimeConfig.runtimeFeatures?.nodeRepl === true,
  267. // 评测时据此确认 runtime 实际用的 token 预算提醒开关。
  268. totalTokensReminder: runtimeConfig.totalTokensReminder?.enabled === true,
  269. // 评测时据此确认 Agent 是否总在后台运行(缺省开启)。
  270. agentAlwaysBackground: runtimeConfig.subagents?.alwaysBackground !== false,
  271. // 只在被改过(开发环境变量或 runtimeConfig)时出现,便于确认 ZCODE_SUBAGENT_STALL_NOTIFY_MS 生效值。
  272. ...(runtimeConfig.subagents?.backgroundStallNotifyMs !== undefined
  273. ? { subagentStallNotifyMs: runtimeConfig.subagents.backgroundStallNotifyMs }
  274. : {}),
  275. workingDirectory,
  276. };
  277. }
  278. /**
  279. * 开发与验收用:缩短后台 Agent 无进展提醒的首次阈值(毫秒),便于在真实会话里复现提醒、唤醒与
  280. * 间隔加倍(07-subagent.md「后台 Agent 无进展提醒」)。
  281. * - 未设置、不是整数或 ≤ 0:不覆盖,使用 core 的默认值(15 分钟);
  282. * - 低于 10 秒:按 10 秒算。每次提醒都会在父会话空闲时开一轮模型调用,间隔从 1 ms 起加倍要几十轮
  283. * 才到分钟级,误设会短时间内烧掉大量 token(!3563 评审 SG-03);
  284. * - 优先级低于 `runtimeConfig.subagents.backgroundStallNotifyMs`(展开顺序在前)。
  285. * 生效值出现在 runtimeConfigLogContext 的 `subagentStallNotifyMs`。
  286. */
  287. export const SUBAGENT_STALL_NOTIFY_MS_ENV = "ZCODE_SUBAGENT_STALL_NOTIFY_MS";
  288. export const SUBAGENT_STALL_NOTIFY_MIN_MS = 10_000;
  289. function readSubagentStallNotifyOverride(env: NodeJS.ProcessEnv): {
  290. backgroundStallNotifyMs?: number;
  291. } {
  292. const raw = env[SUBAGENT_STALL_NOTIFY_MS_ENV]?.trim() ?? "";
  293. if (!/^\d+$/.test(raw)) return {};
  294. const value = Number(raw);
  295. if (!Number.isSafeInteger(value) || value <= 0) return {};
  296. return { backgroundStallNotifyMs: Math.max(SUBAGENT_STALL_NOTIFY_MIN_MS, value) };
  297. }