subagents.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import { readFileSync } from "node:fs";
  2. import { readFile, readdir } from "node:fs/promises";
  3. import { basename, join, resolve } from "node:path";
  4. import { parseRuntimeSubagentConfig } from "./runtime-subagents/index.js";
  5. import { migrateUserSubagentMarkdown, migrateSubagentStateFile } from "@zcode/shared/node";
  6. import {
  7. parseAgentProfileFromMarkdown,
  8. type AgentProfile,
  9. type AgentProfileParseDiagnostic,
  10. } from "@zcode/core";
  11. import type { Logger, PluginMetadata } from "@zcode/contracts";
  12. import {
  13. createPluginAgentStateId,
  14. parsePluginSubagentModelSelectionOverrides,
  15. modelSelectionSchema,
  16. type BuiltInSubagentModelSelectionOverrides,
  17. type PluginSubagentModelSelectionOverrides,
  18. } from "@zcode/shared";
  19. interface LoadZCodeAgentProfilesInput {
  20. logger?: Logger;
  21. storageRoot: string;
  22. workingDirectory: string;
  23. additionalDirectories?: readonly string[];
  24. }
  25. interface LoadZCodeAgentProfilesResult {
  26. builtInModelSelectionOverrides: BuiltInSubagentModelSelectionOverrides;
  27. pluginAgentModelSelectionOverrides: PluginSubagentModelSelectionOverrides;
  28. diagnostics: AgentProfileParseDiagnostic[];
  29. profiles: AgentProfile[];
  30. }
  31. interface LoadPluginAgentProfilesInput {
  32. logger?: Logger;
  33. plugins: readonly PluginMetadata[];
  34. reservedProfileNames?: Iterable<string>;
  35. /** 来自已完成存储迁移的启动快照;不在插件 loader 另读磁盘或查询账号。 */
  36. modelSelectionOverrides?: PluginSubagentModelSelectionOverrides;
  37. }
  38. interface ParsedPluginAgentProfile {
  39. bareName: string;
  40. plugin: PluginMetadata;
  41. profile: AgentProfile;
  42. }
  43. const RESERVED_AGENT_NAMES = new Set(["general-purpose", "Explore"]);
  44. export async function loadZCodeAgentProfiles(
  45. input: LoadZCodeAgentProfilesInput,
  46. ): Promise<LoadZCodeAgentProfilesResult> {
  47. const migration = await migrateUserSubagentMarkdown(join(input.storageRoot, "agents"));
  48. await migrateSubagentStateFile(join(input.storageRoot, "v2", "agents-state.json"));
  49. const roots: Array<{ path: string; source: "user" | "project"; namespace?: string }> = [
  50. { path: join(input.storageRoot, "agents"), source: "user" as const },
  51. { path: join(input.workingDirectory, ".zcode", "agents"), source: "project" as const },
  52. ];
  53. for (const directory of new Set(
  54. (input.additionalDirectories ?? []).map((path) => resolve(path)),
  55. )) {
  56. if (directory === resolve(input.workingDirectory)) continue;
  57. roots.push({
  58. path: join(directory, ".zcode", "agents"),
  59. source: "project",
  60. namespace: basename(directory),
  61. });
  62. }
  63. const diagnostics: AgentProfileParseDiagnostic[] = [];
  64. for (const failure of migration.failures) {
  65. diagnostics.push({
  66. code: "agent_read_failed",
  67. message: "Subagent Markdown migration failed; original file preserved",
  68. path: failure.path,
  69. });
  70. input.logger?.warn("Subagent Markdown migration failed", {
  71. module: "bootstrap.subagents",
  72. path: failure.path,
  73. error: String(failure.error),
  74. });
  75. }
  76. const agentState = await readAgentState(input.storageRoot);
  77. const documents = (
  78. await Promise.all(
  79. roots.map(async (root) =>
  80. Promise.all(
  81. (await listMarkdownFiles(root.path)).map(async (path) => ({
  82. path,
  83. source: root.source,
  84. namespace: root.namespace,
  85. content: await readFile(path, "utf8"),
  86. })),
  87. ),
  88. ),
  89. )
  90. ).flat();
  91. const parsed = parseRuntimeSubagentConfig({
  92. documents,
  93. state: { ...agentState, disabledAgentIds: [...agentState.disabledAgentIds] },
  94. });
  95. for (const diagnostic of parsed.diagnostics)
  96. input.logger?.warn("Agent profile diagnostic", {
  97. ...diagnostic,
  98. module: "bootstrap.subagents",
  99. });
  100. return { ...parsed, diagnostics: [...diagnostics, ...parsed.diagnostics] };
  101. }
  102. export function loadPluginAgentTemplates(
  103. input: Pick<LoadPluginAgentProfilesInput, "plugins" | "logger">,
  104. ): { profiles: ParsedPluginAgentProfile[]; diagnostics: AgentProfileParseDiagnostic[] } {
  105. const parsedProfiles: ParsedPluginAgentProfile[] = [];
  106. const diagnostics: AgentProfileParseDiagnostic[] = [];
  107. for (const plugin of input.plugins) {
  108. if (!plugin.enabled) continue;
  109. const agents = plugin.components.find((group) => group.kind === "agent")?.items ?? [];
  110. for (const agent of agents) {
  111. // 名称可能来自 frontmatter,不能还原文件位置;只读取发现阶段保留的源路径。
  112. if (!agent.path) continue;
  113. const result = parsePluginAgentProfile({
  114. filePath: agent.path,
  115. logger: input.logger,
  116. plugin,
  117. });
  118. if (result.diagnostic) diagnostics.push(result.diagnostic);
  119. if (result.parsed) parsedProfiles.push(result.parsed);
  120. }
  121. }
  122. return { profiles: parsedProfiles, diagnostics };
  123. }
  124. export function resolvePluginAgentProfiles(
  125. input: LoadPluginAgentProfilesInput,
  126. templates: ReturnType<typeof loadPluginAgentTemplates>,
  127. ): LoadZCodeAgentProfilesResult {
  128. const diagnostics = [...templates.diagnostics];
  129. const parsedProfiles = templates.profiles;
  130. const reservedProfileNames = new Set([
  131. ...RESERVED_AGENT_NAMES,
  132. ...(input.reservedProfileNames ?? []),
  133. ]);
  134. const bareNameCounts = countBareProfileNames(parsedProfiles);
  135. const profiles: AgentProfile[] = [];
  136. for (const parsed of parsedProfiles) {
  137. const override =
  138. input.modelSelectionOverrides?.[createPluginAgentStateId(parsed.plugin.id, parsed.bareName)];
  139. // 先替换完整选择再展开别名,避免同一插件的两个调用入口使用不同模型/档位。
  140. const canonical = {
  141. ...namespacePluginAgentProfile(parsed),
  142. ...(override ? { modelSelection: override } : {}),
  143. };
  144. profiles.push(canonical);
  145. const bareName = parsed.bareName.trim();
  146. if (bareNameCounts.get(bareName) === 1 && !reservedProfileNames.has(bareName)) {
  147. profiles.push({ ...canonical, name: bareName });
  148. } else if (reservedProfileNames.has(bareName)) {
  149. diagnostics.push({
  150. code: "agent_ambiguous_name",
  151. message: `Plugin agent bare name conflicts with an existing profile; use ${canonical.name}: ${bareName}`,
  152. path: canonical.path,
  153. });
  154. } else if ((bareNameCounts.get(bareName) ?? 0) > 1) {
  155. diagnostics.push({
  156. code: "agent_ambiguous_name",
  157. message: `Plugin agent bare name is ambiguous; use ${canonical.name}: ${bareName}`,
  158. path: canonical.path,
  159. });
  160. }
  161. }
  162. input.logger?.debug("Plugin agent profiles loaded", {
  163. diagnosticCount: diagnostics.length,
  164. module: "bootstrap.subagents",
  165. profileCount: profiles.length,
  166. });
  167. return {
  168. builtInModelSelectionOverrides: {},
  169. pluginAgentModelSelectionOverrides: {},
  170. diagnostics,
  171. profiles,
  172. };
  173. }
  174. function parsePluginAgentProfile(input: {
  175. filePath: string;
  176. logger?: Logger;
  177. plugin: PluginMetadata;
  178. }): { diagnostic?: AgentProfileParseDiagnostic; parsed?: ParsedPluginAgentProfile } {
  179. try {
  180. const content = readFileSync(input.filePath, "utf8");
  181. const result = parseAgentProfileFromMarkdown({
  182. content,
  183. path: input.filePath,
  184. source: "user",
  185. });
  186. if (result.diagnostic) {
  187. input.logger?.warn("Plugin agent profile diagnostic", {
  188. code: result.diagnostic.code,
  189. message: result.diagnostic.message,
  190. module: "bootstrap.subagents",
  191. path: input.filePath,
  192. pluginId: input.plugin.id,
  193. });
  194. if (!result.profile) return { diagnostic: result.diagnostic };
  195. }
  196. if (!result.profile) return {};
  197. return {
  198. ...(result.diagnostic ? { diagnostic: result.diagnostic } : {}),
  199. parsed: {
  200. bareName: result.profile.name,
  201. plugin: input.plugin,
  202. // 修复原因:插件 profile 按 user 解析,permissionMode 原样生效;bypassPermissions 会让
  203. // 被委派的子会话在父会话 build 时以 yolo 运行。官方与第三方插件同一规则:声明只能收紧父会话模式。
  204. profile: { ...result.profile, permissionModeRestrictOnly: true },
  205. },
  206. };
  207. } catch (error) {
  208. return {
  209. diagnostic: {
  210. code: "agent_read_failed",
  211. message:
  212. error instanceof Error ? error.message : `Failed to read plugin agent: ${input.filePath}`,
  213. path: input.filePath,
  214. },
  215. };
  216. }
  217. }
  218. function namespacePluginAgentProfile(parsed: ParsedPluginAgentProfile): AgentProfile {
  219. return {
  220. ...parsed.profile,
  221. name: `${parsed.plugin.name}:${parsed.bareName}`,
  222. };
  223. }
  224. function isRecord(value: unknown): value is Record<string, unknown> {
  225. return typeof value === "object" && value !== null && !Array.isArray(value);
  226. }
  227. function countBareProfileNames(
  228. parsedProfiles: readonly ParsedPluginAgentProfile[],
  229. ): Map<string, number> {
  230. const counts = new Map<string, number>();
  231. for (const parsed of parsedProfiles) {
  232. const name = parsed.bareName.trim();
  233. counts.set(name, (counts.get(name) ?? 0) + 1);
  234. }
  235. return counts;
  236. }
  237. async function readAgentState(storageRoot: string): Promise<{
  238. builtInModelSelectionOverrides: BuiltInSubagentModelSelectionOverrides;
  239. pluginAgentModelSelectionOverrides: PluginSubagentModelSelectionOverrides;
  240. disabledAgentIds: Set<string>;
  241. }> {
  242. try {
  243. const raw = await readFile(join(storageRoot, "v2", "agents-state.json"), "utf8");
  244. const parsed = JSON.parse(raw) as {
  245. builtInModelSelectionOverrides?: unknown;
  246. pluginAgentModelSelectionOverrides?: unknown;
  247. disabledAgentIds?: unknown;
  248. };
  249. return {
  250. pluginAgentModelSelectionOverrides: parsePluginSubagentModelSelectionOverrides(
  251. parsed.pluginAgentModelSelectionOverrides,
  252. ),
  253. builtInModelSelectionOverrides: normalizeBuiltInSelectionOverrides(
  254. parsed.builtInModelSelectionOverrides,
  255. ),
  256. disabledAgentIds: new Set(
  257. Array.isArray(parsed.disabledAgentIds)
  258. ? parsed.disabledAgentIds.filter(
  259. (id): id is string => typeof id === "string" && id.trim().length > 0,
  260. )
  261. : [],
  262. ),
  263. };
  264. } catch {
  265. return {
  266. builtInModelSelectionOverrides: {},
  267. pluginAgentModelSelectionOverrides: {},
  268. disabledAgentIds: new Set(),
  269. };
  270. }
  271. }
  272. function normalizeBuiltInSelectionOverrides(
  273. structured: unknown,
  274. ): BuiltInSubagentModelSelectionOverrides {
  275. const result: BuiltInSubagentModelSelectionOverrides = {};
  276. const structuredRecord = isRecord(structured) ? structured : {};
  277. const generalPurpose = modelSelectionSchema.safeParse(structuredRecord["general-purpose"]);
  278. const explore = modelSelectionSchema.safeParse(structuredRecord.Explore);
  279. if (generalPurpose.success) result["general-purpose"] = generalPurpose.data;
  280. if (explore.success) result.Explore = explore.data;
  281. return result;
  282. }
  283. async function listMarkdownFiles(root: string): Promise<string[]> {
  284. const entries = await readdir(root, { withFileTypes: true }).catch(
  285. (error: NodeJS.ErrnoException) => {
  286. if (error.code === "ENOENT" || error.code === "ENOTDIR") return [];
  287. throw error;
  288. },
  289. );
  290. const result: string[] = [];
  291. for (const entry of entries) {
  292. const path = join(root, entry.name);
  293. // 与 Host / Settings 一致,只加载根目录直接文件;插件使用独立发现入口。
  294. if (entry.isFile() && /\.(md|markdown)$/iu.test(entry.name)) {
  295. result.push(path);
  296. }
  297. }
  298. return result.sort((left, right) => left.localeCompare(right));
  299. }