outputStyleService.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import type { OutputStyle, OutputStyleConfig } from "@zcode/shared";
  2. import type { IOutputStyleService } from "./outputStyle.js";
  3. import { access, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
  4. import { existsSync } from "node:fs";
  5. import { homedir } from "node:os";
  6. import { join } from "node:path";
  7. const DEFAULT_OUTPUT_STYLE = "default";
  8. const SETTINGS_FILE = "settings.json";
  9. const BUILT_IN_STYLES: OutputStyle[] = [
  10. {
  11. id: "default",
  12. name: "Default",
  13. description:
  14. "Completes coding tasks efficiently and provides concise responses",
  15. content: "",
  16. isBuiltIn: true,
  17. enabled: true,
  18. },
  19. {
  20. id: "explanatory",
  21. name: "Explanatory",
  22. description:
  23. "Explains implementation choices and codebase patterns",
  24. content: "",
  25. isBuiltIn: true,
  26. enabled: false,
  27. },
  28. {
  29. id: "learning",
  30. name: "Learning",
  31. description:
  32. "Pauses and asks you to write small pieces of code for hands-on practice",
  33. content: "",
  34. isBuiltIn: true,
  35. enabled: false,
  36. },
  37. ];
  38. function resolveUserHomeDir(): string {
  39. const envHome = process.env.HOME?.trim() || process.env.USERPROFILE?.trim();
  40. return envHome && envHome.length > 0 ? envHome : homedir();
  41. }
  42. function getUserOutputStylesDir(): string {
  43. return join(resolveUserHomeDir(), ".claude", "output-styles");
  44. }
  45. function getUserClaudeSettingsPath(): string {
  46. return join(resolveUserHomeDir(), ".claude", SETTINGS_FILE);
  47. }
  48. interface ClaudeSettingsConfig {
  49. outputStyle?: string;
  50. hooks?: unknown;
  51. [key: string]: unknown;
  52. }
  53. /**
  54. * Read JSON file safely
  55. */
  56. async function readJsonFile<T>(filePath: string): Promise<T | null> {
  57. try {
  58. if (!existsSync(filePath)) {
  59. return null;
  60. }
  61. const content = await readFile(filePath, "utf-8");
  62. return JSON.parse(content) as T;
  63. } catch (error) {
  64. console.error(`Failed to read JSON file ${filePath}:`, error);
  65. return null;
  66. }
  67. }
  68. /**
  69. * Write JSON file safely
  70. */
  71. async function writeJsonFile<T>(filePath: string, data: T): Promise<void> {
  72. try {
  73. await writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
  74. } catch (error) {
  75. console.error(`Failed to write JSON file ${filePath}:`, error);
  76. throw error;
  77. }
  78. }
  79. /**
  80. * 解析 markdown 格式的 output style 文件
  81. */
  82. function parseMarkdownStyle(
  83. content: string,
  84. filename?: string,
  85. ): { name: string; description: string } {
  86. const nameMatch = content.match(/^name:\s*(.+)$/m);
  87. const descMatch = content.match(/^description:\s*(.+)$/m);
  88. let name = nameMatch?.[1]?.trim() ?? "";
  89. if (!name && filename) {
  90. name = filename.replace(/\.md$/, "");
  91. }
  92. if (!name) {
  93. name = "Custom Style";
  94. }
  95. const description = descMatch?.[1]?.trim() ?? "";
  96. return { name, description };
  97. }
  98. /**
  99. * 创建 OutputStyle 服务实例
  100. */
  101. export function createOutputStyleService(): IOutputStyleService {
  102. async function getActiveStyle(): Promise<{ styleId: string | null }> {
  103. const settingsPath = getUserClaudeSettingsPath();
  104. const settings = await readJsonFile<ClaudeSettingsConfig>(settingsPath);
  105. return { styleId: settings?.outputStyle ?? null };
  106. }
  107. async function setActiveStyle(params: { styleId: string }): Promise<void> {
  108. const { styleId } = params;
  109. const settingsPath = getUserClaudeSettingsPath();
  110. const claudeDir = join(resolveUserHomeDir(), ".claude");
  111. // Ensure directory exists
  112. if (!existsSync(claudeDir)) {
  113. await mkdir(claudeDir, { recursive: true });
  114. }
  115. // Read existing settings.json
  116. const existingSettings = (await readJsonFile<ClaudeSettingsConfig>(settingsPath)) || {};
  117. // Update outputStyle
  118. const newSettings: ClaudeSettingsConfig = {
  119. ...existingSettings,
  120. outputStyle: styleId,
  121. };
  122. await writeJsonFile(settingsPath, newSettings);
  123. }
  124. async function listStyles(): Promise<{ styles: OutputStyle[] }> {
  125. const stylesDir = getUserOutputStylesDir();
  126. const customStyles: OutputStyle[] = [];
  127. // Get active style from settings.local.json, default to "default"
  128. const { styleId } = await getActiveStyle();
  129. const activeStyleId = styleId ?? "default";
  130. try {
  131. await access(stylesDir);
  132. const entries = await readdir(stylesDir, { withFileTypes: true });
  133. for (const entry of entries) {
  134. if (entry.isFile() && entry.name.endsWith(".md")) {
  135. try {
  136. const filePath = join(stylesDir, entry.name);
  137. const content = await readFile(filePath, "utf-8");
  138. const { name, description } = parseMarkdownStyle(content, entry.name);
  139. const styleId = `custom-${entry.name.replace(".md", "")}`;
  140. customStyles.push({
  141. id: styleId,
  142. name,
  143. description,
  144. content,
  145. isBuiltIn: false,
  146. enabled: styleId === activeStyleId,
  147. filePath,
  148. });
  149. } catch (error) {
  150. console.error(`Failed to read output style file ${entry.name}:`, error);
  151. }
  152. }
  153. }
  154. } catch {
  155. // 目录不存在或无法访问,返回内置 styles
  156. }
  157. // 按名称排序
  158. customStyles.sort((a, b) => a.name.localeCompare(b.name));
  159. // 合并内置和自定义 styles,标记激活状态
  160. const allStyles: OutputStyle[] = [
  161. ...BUILT_IN_STYLES.map((style) => ({
  162. ...style,
  163. enabled: style.id === activeStyleId,
  164. })),
  165. ...customStyles,
  166. ];
  167. return { styles: allStyles };
  168. }
  169. async function addStyle(params: { config: OutputStyleConfig }): Promise<void> {
  170. const { config } = params;
  171. const stylesDir = getUserOutputStylesDir();
  172. try {
  173. await mkdir(stylesDir, { recursive: true });
  174. } catch (error) {
  175. const err = error as NodeJS.ErrnoException;
  176. if (err.code !== "EEXIST") {
  177. throw error;
  178. }
  179. }
  180. const filename = `${config.name.toLowerCase().replace(/\s+/g, "-")}.md`;
  181. const filePath = join(stylesDir, filename);
  182. // 生成文件内容
  183. const content = `name: ${config.name}
  184. description: ${config.description}
  185. ${config.content}`;
  186. await writeFile(filePath, content, "utf-8");
  187. }
  188. async function updateStyle(params: {
  189. id: string;
  190. config: OutputStyleConfig;
  191. }): Promise<void> {
  192. const { id, config } = params;
  193. // 移除 'custom-' 前缀获取文件名
  194. const baseId = id.startsWith("custom-") ? id.slice(7) : id;
  195. const stylesDir = getUserOutputStylesDir();
  196. const filename = `${baseId}.md`;
  197. const filePath = join(stylesDir, filename);
  198. // 生成文件内容
  199. const content = `name: ${config.name}
  200. description: ${config.description}
  201. ${config.content}`;
  202. await writeFile(filePath, content, "utf-8");
  203. }
  204. async function deleteStyle(params: { id: string }): Promise<void> {
  205. const { id } = params;
  206. // 移除 'custom-' 前缀获取文件名
  207. const baseId = id.startsWith("custom-") ? id.slice(7) : id;
  208. const stylesDir = getUserOutputStylesDir();
  209. const filename = `${baseId}.md`;
  210. const filePath = join(stylesDir, filename);
  211. await rm(filePath, { force: true });
  212. }
  213. async function getUserStylesDirectory(): Promise<{ path: string }> {
  214. const stylesDir = getUserOutputStylesDir();
  215. try {
  216. await mkdir(stylesDir, { recursive: true });
  217. } catch {
  218. // 目录已存在
  219. }
  220. return { path: stylesDir };
  221. }
  222. return {
  223. listStyles,
  224. addStyle,
  225. updateStyle,
  226. deleteStyle,
  227. getUserStylesDirectory,
  228. setActiveStyle,
  229. getActiveStyle,
  230. };
  231. }