vite.config.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import { readdir, readFile, stat, open } from "node:fs/promises";
  2. import { homedir } from "node:os";
  3. import { dirname, extname, join, resolve } from "node:path";
  4. import { defineConfig, type Plugin } from "vite";
  5. import react from "@vitejs/plugin-react";
  6. import tailwindcss from "@tailwindcss/vite";
  7. import { parse as parseYaml } from "yaml";
  8. import { normalizeFeatureBoundaryGraph } from "./src/data/featureBoundaryGraphSource.js";
  9. const STDIO_TRAFFIC_API_PATH = "/api/dev/stdio-traffic";
  10. const STDIO_TRAFFIC_LOG_DIR = join(homedir(), ".zcode", "v2", "dev", "stdio-traffic");
  11. const MAX_TAIL_BYTES = 2 * 1024 * 1024;
  12. const DEFAULT_RECORD_LIMIT = 300;
  13. const FEATURE_BOUNDARY_GRAPH_MODULE_ID = "virtual:zcode-feature-boundary-graph";
  14. const FEATURE_BOUNDARY_GRAPH_RESOLVED_ID = `\0${FEATURE_BOUNDARY_GRAPH_MODULE_ID}`;
  15. const FEATURE_BOUNDARY_GRAPH_SOURCE_PATH = resolve(
  16. __dirname,
  17. "../../.agents/skills/feature-boundary-planner/references/zcode-feature-graph.yaml",
  18. );
  19. interface StdioTrafficFile {
  20. filePath: string;
  21. mtimeMs: number;
  22. workspaceHash: string;
  23. }
  24. function sendJson(
  25. response: { setHeader: (name: string, value: string) => void; end: (body: string) => void },
  26. body: unknown,
  27. ) {
  28. response.setHeader("Content-Type", "application/json");
  29. response.end(JSON.stringify(body));
  30. }
  31. async function fileExists(path: string) {
  32. try {
  33. await stat(path);
  34. return true;
  35. } catch {
  36. return false;
  37. }
  38. }
  39. async function readLatestPointer(workspaceDir: string) {
  40. const latestPath = join(workspaceDir, "latest.txt");
  41. if (!(await fileExists(latestPath))) {
  42. return null;
  43. }
  44. const filePath = (await readFile(latestPath, "utf-8")).trim().split(/\r?\n/u)[0] ?? "";
  45. if (!filePath || extname(filePath) !== ".ndjson" || dirname(filePath) !== workspaceDir) {
  46. return null;
  47. }
  48. return filePath;
  49. }
  50. async function findWorkspaceLatestFile(logDir: string, workspaceHash: string) {
  51. const workspaceDir = join(logDir, workspaceHash);
  52. const latestFilePath = await readLatestPointer(workspaceDir);
  53. const candidates: StdioTrafficFile[] = [];
  54. if (latestFilePath && (await fileExists(latestFilePath))) {
  55. const fileStat = await stat(latestFilePath);
  56. candidates.push({ filePath: latestFilePath, mtimeMs: fileStat.mtimeMs, workspaceHash });
  57. }
  58. if (candidates.length === 0) {
  59. const entries = await readdir(workspaceDir, { withFileTypes: true });
  60. for (const entry of entries) {
  61. if (!entry.isFile() || !entry.name.endsWith(".ndjson")) {
  62. continue;
  63. }
  64. const filePath = join(workspaceDir, entry.name);
  65. const fileStat = await stat(filePath);
  66. candidates.push({ filePath, mtimeMs: fileStat.mtimeMs, workspaceHash });
  67. }
  68. }
  69. return candidates.sort((first, second) => second.mtimeMs - first.mtimeMs)[0] ?? null;
  70. }
  71. async function findLatestTrafficFile(logDir: string) {
  72. if (!(await fileExists(logDir))) {
  73. return null;
  74. }
  75. const entries = await readdir(logDir, { withFileTypes: true });
  76. const candidates: StdioTrafficFile[] = [];
  77. for (const entry of entries) {
  78. if (!entry.isDirectory()) {
  79. continue;
  80. }
  81. const latestFile = await findWorkspaceLatestFile(logDir, entry.name);
  82. if (latestFile) {
  83. candidates.push(latestFile);
  84. }
  85. }
  86. return candidates.sort((first, second) => second.mtimeMs - first.mtimeMs)[0] ?? null;
  87. }
  88. async function readTailLines(filePath: string, limit: number) {
  89. const fileStat = await stat(filePath);
  90. if (fileStat.size === 0) {
  91. return [];
  92. }
  93. const start = Math.max(0, fileStat.size - MAX_TAIL_BYTES);
  94. const length = fileStat.size - start;
  95. const buffer = Buffer.alloc(length);
  96. const file = await open(filePath, "r");
  97. try {
  98. await file.read(buffer, 0, length, start);
  99. } finally {
  100. await file.close();
  101. }
  102. let text = buffer.toString("utf-8");
  103. if (start > 0) {
  104. const firstLineBreak = text.indexOf("\n");
  105. text = firstLineBreak >= 0 ? text.slice(firstLineBreak + 1) : "";
  106. }
  107. return text.split(/\r?\n/u).filter(Boolean).slice(-limit);
  108. }
  109. async function buildFeatureBoundaryGraphModule() {
  110. const source = await readFile(FEATURE_BOUNDARY_GRAPH_SOURCE_PATH, "utf-8");
  111. const graph = normalizeFeatureBoundaryGraph(parseYaml(source));
  112. return `export default ${JSON.stringify(graph)};`;
  113. }
  114. function featureBoundaryGraphPlugin(): Plugin {
  115. let moduleSource = "";
  116. return {
  117. name: "zcode-dev-docs-feature-boundary-graph",
  118. configureServer(server) {
  119. server.watcher.add(FEATURE_BOUNDARY_GRAPH_SOURCE_PATH);
  120. },
  121. async buildStart() {
  122. moduleSource = await buildFeatureBoundaryGraphModule();
  123. },
  124. resolveId(id) {
  125. return id === FEATURE_BOUNDARY_GRAPH_MODULE_ID
  126. ? FEATURE_BOUNDARY_GRAPH_RESOLVED_ID
  127. : undefined;
  128. },
  129. async load(id) {
  130. if (id !== FEATURE_BOUNDARY_GRAPH_RESOLVED_ID) {
  131. return undefined;
  132. }
  133. if (!moduleSource) {
  134. moduleSource = await buildFeatureBoundaryGraphModule();
  135. }
  136. return moduleSource;
  137. },
  138. async handleHotUpdate({ file, server }) {
  139. if (resolve(file) !== FEATURE_BOUNDARY_GRAPH_SOURCE_PATH) {
  140. return undefined;
  141. }
  142. moduleSource = await buildFeatureBoundaryGraphModule();
  143. const module = server.moduleGraph.getModuleById(FEATURE_BOUNDARY_GRAPH_RESOLVED_ID);
  144. if (module) {
  145. server.moduleGraph.invalidateModule(module);
  146. return [module];
  147. }
  148. return undefined;
  149. },
  150. };
  151. }
  152. function parseRecordLines(lines: string[]) {
  153. return lines.flatMap((line, index) => {
  154. try {
  155. return [{ index, record: JSON.parse(line) as unknown }];
  156. } catch (error) {
  157. return [
  158. {
  159. index,
  160. record: {
  161. ts: new Date().toISOString(),
  162. direction: "agent-stderr",
  163. bytes: Buffer.byteLength(line),
  164. raw: line,
  165. parseError: error instanceof Error ? error.message : String(error),
  166. },
  167. },
  168. ];
  169. }
  170. });
  171. }
  172. function stdioTrafficApiPlugin(): Plugin {
  173. return {
  174. name: "zcode-dev-docs-stdio-traffic-api",
  175. configureServer(server) {
  176. server.middlewares.use(STDIO_TRAFFIC_API_PATH, async (request, response) => {
  177. try {
  178. const requestUrl = new URL(request.url ?? "", "http://localhost");
  179. const limit = Math.min(
  180. Number.parseInt(requestUrl.searchParams.get("limit") ?? "", 10) || DEFAULT_RECORD_LIMIT,
  181. 1000,
  182. );
  183. const latestFile = await findLatestTrafficFile(STDIO_TRAFFIC_LOG_DIR);
  184. if (!latestFile) {
  185. sendJson(response, {
  186. status: "missing",
  187. logDir: STDIO_TRAFFIC_LOG_DIR,
  188. records: [],
  189. });
  190. return;
  191. }
  192. const lines = await readTailLines(latestFile.filePath, limit);
  193. sendJson(response, {
  194. status: lines.length > 0 ? "ready" : "empty",
  195. logDir: STDIO_TRAFFIC_LOG_DIR,
  196. workspaceHash: latestFile.workspaceHash,
  197. filePath: latestFile.filePath,
  198. updatedAt: new Date(latestFile.mtimeMs).toISOString(),
  199. records: parseRecordLines(lines),
  200. });
  201. } catch (error) {
  202. sendJson(response, {
  203. status: "error",
  204. logDir: STDIO_TRAFFIC_LOG_DIR,
  205. records: [],
  206. error: error instanceof Error ? error.message : String(error),
  207. });
  208. }
  209. });
  210. },
  211. };
  212. }
  213. export default defineConfig({
  214. plugins: [stdioTrafficApiPlugin(), featureBoundaryGraphPlugin(), react(), tailwindcss()],
  215. resolve: {
  216. alias: {
  217. "@": resolve(__dirname, "src"),
  218. },
  219. },
  220. server: {
  221. port: 5186,
  222. },
  223. });