index.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. // ============================================================
  2. // Node Context Source Adapter
  3. // ============================================================
  4. import { readFile, stat } from "node:fs/promises";
  5. import { arch, homedir, release } from "node:os";
  6. import { basename, dirname, join, resolve } from "node:path";
  7. import { formatLocalIsoDate } from "@zcode/contracts";
  8. import type {
  9. ContextSourceDiagnostic,
  10. ContextSourcePort,
  11. ContextSourceRequest,
  12. ContextSourceSnapshot,
  13. EnvInfo,
  14. PackageManager,
  15. ProjectContext,
  16. ProjectType,
  17. ResolvedUserInstructionSource,
  18. ResolvedUserInstructions,
  19. UserInstructionsOptions,
  20. } from "@zcode/contracts";
  21. import { resolveGitSnapshot } from "./git-snapshot.js";
  22. const DEFAULT_PRIORITY_FILES = ["AGENTS.md"];
  23. const DEFAULT_MAX_BYTES = 100 * 1024;
  24. export interface NodeContextSourceAdapterOptions {
  25. env?: NodeJS.ProcessEnv;
  26. }
  27. export class NodeContextSourceAdapter implements ContextSourcePort {
  28. private readonly env: NodeJS.ProcessEnv;
  29. constructor(options: NodeContextSourceAdapterOptions = {}) {
  30. this.env = options.env ?? process.env;
  31. }
  32. async resolveContextSources(request: ContextSourceRequest): Promise<ContextSourceSnapshot> {
  33. const workingDirectory = resolve(request.workingDirectory);
  34. const diagnostics: ContextSourceDiagnostic[] = [];
  35. const projectRoot = await findProjectRoot(workingDirectory);
  36. const envInfo =
  37. request.envInfo ??
  38. (await this.detectEnvInfo(workingDirectory, request.effectiveShellDisplayName));
  39. const userInstructions = request.userInstructions
  40. ? await resolveUserInstructions(
  41. {
  42. ...request.userInstructions,
  43. workingDirectory: request.userInstructions.workingDirectory ?? workingDirectory,
  44. projectRoot: request.userInstructions.projectRoot ?? projectRoot ?? undefined,
  45. },
  46. diagnostics,
  47. this.env,
  48. )
  49. : undefined;
  50. const projectContext =
  51. request.projectContext ?? (projectRoot ? await detectProjectContext(projectRoot) : undefined);
  52. return {
  53. workingDirectory,
  54. envInfo,
  55. currentDate: request.currentDate ?? formatLocalIsoDate(new Date()),
  56. userInstructions,
  57. projectContext,
  58. diagnostics,
  59. };
  60. }
  61. private async detectEnvInfo(
  62. workingDirectory: string,
  63. effectiveShellDisplayName?: string,
  64. ): Promise<EnvInfo> {
  65. const shellPath = this.env.SHELL ?? this.env.ComSpec ?? this.env.COMSPEC ?? "";
  66. const shell = effectiveShellDisplayName ?? (shellPath ? basename(shellPath) : "unknown");
  67. const gitSnapshot = await resolveGitSnapshot(workingDirectory);
  68. return {
  69. cwd: workingDirectory,
  70. platform: process.platform,
  71. shell,
  72. osVersion: `${process.platform} ${release()} ${arch()}`,
  73. nodeVersion: process.version,
  74. ...gitSnapshot,
  75. };
  76. }
  77. }
  78. export function createNodeContextSourceAdapter(
  79. options: NodeContextSourceAdapterOptions = {},
  80. ): NodeContextSourceAdapter {
  81. return new NodeContextSourceAdapter(options);
  82. }
  83. async function resolveUserInstructions(
  84. options: UserInstructionsOptions,
  85. diagnostics: ContextSourceDiagnostic[],
  86. env: NodeJS.ProcessEnv = process.env,
  87. ): Promise<ResolvedUserInstructions | undefined> {
  88. const priorityFiles = options.priorityFiles ?? DEFAULT_PRIORITY_FILES;
  89. const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
  90. const projectRoot = options.projectRoot ?? (await findProjectRoot(options.workingDirectory));
  91. const defaultUserInstructionFile = await findDefaultUserInstructionFile(priorityFiles, env);
  92. const workspaceInstructionFile = await findInstructionFile(
  93. options.workingDirectory,
  94. projectRoot,
  95. priorityFiles,
  96. );
  97. const candidates = dedupeInstructionFileCandidates([
  98. defaultUserInstructionFile
  99. ? { ...defaultUserInstructionFile, scope: "user" as const }
  100. : undefined,
  101. workspaceInstructionFile
  102. ? { ...workspaceInstructionFile, scope: "workspace" as const }
  103. : undefined,
  104. ]);
  105. const sources: ResolvedUserInstructionSource[] = [];
  106. for (const candidate of candidates) {
  107. const source = await readInstructionSource(candidate, maxBytes, diagnostics);
  108. if (source) {
  109. sources.push(source);
  110. }
  111. }
  112. if (sources.length === 0) return undefined;
  113. return mergeInstructionSources(sources);
  114. }
  115. async function readFirstTextBytes(path: string, maxBytes: number): Promise<string> {
  116. const content = await readFile(path);
  117. return content.subarray(0, maxBytes).toString("utf8");
  118. }
  119. type InstructionFileCandidate = {
  120. filePath: string;
  121. fileName: string;
  122. scope: ResolvedUserInstructionSource["scope"];
  123. };
  124. function dedupeInstructionFileCandidates(
  125. candidates: Array<InstructionFileCandidate | undefined>,
  126. ): InstructionFileCandidate[] {
  127. const seen = new Set<string>();
  128. const deduped: InstructionFileCandidate[] = [];
  129. for (const candidate of candidates) {
  130. if (!candidate) continue;
  131. const key = resolve(candidate.filePath);
  132. if (seen.has(key)) continue;
  133. seen.add(key);
  134. deduped.push(candidate);
  135. }
  136. return deduped;
  137. }
  138. async function readInstructionSource(
  139. candidate: InstructionFileCandidate,
  140. maxBytes: number,
  141. diagnostics: ContextSourceDiagnostic[],
  142. ): Promise<ResolvedUserInstructionSource | undefined> {
  143. try {
  144. const info = await stat(candidate.filePath);
  145. const bytesToRead = Math.min(info.size, maxBytes);
  146. const content = await readFirstTextBytes(candidate.filePath, bytesToRead);
  147. return {
  148. scope: candidate.scope,
  149. filePath: candidate.filePath,
  150. fileName: candidate.fileName,
  151. content,
  152. bytesRead: Buffer.byteLength(content),
  153. sizeBytes: info.size,
  154. truncated: info.size > maxBytes,
  155. };
  156. } catch (error) {
  157. diagnostics.push({
  158. code: "user_instructions_read_failed",
  159. message: error instanceof Error ? error.message : "Failed to read user instructions",
  160. path: candidate.filePath,
  161. });
  162. return undefined;
  163. }
  164. }
  165. function mergeInstructionSources(
  166. sources: ResolvedUserInstructionSource[],
  167. ): ResolvedUserInstructions {
  168. const primary = sources.find((source) => source.scope === "workspace") ?? sources[0];
  169. const content = sources.map((source) => source.content).join("\n\n");
  170. return {
  171. filePath: primary.filePath,
  172. fileName: primary.fileName,
  173. content,
  174. bytesRead: sources.reduce((sum, source) => sum + source.bytesRead, 0),
  175. sizeBytes: sources.reduce((sum, source) => sum + source.sizeBytes, 0),
  176. truncated: sources.some((source) => source.truncated),
  177. sources,
  178. };
  179. }
  180. async function findInstructionFile(
  181. startDir: string,
  182. projectRoot: string | null,
  183. priorityFiles: string[],
  184. ): Promise<{ filePath: string; fileName: string } | undefined> {
  185. let current = resolve(startDir);
  186. while (true) {
  187. for (const fileName of priorityFiles) {
  188. const filePath = join(current, fileName);
  189. if (await isFile(filePath)) {
  190. return { filePath, fileName };
  191. }
  192. }
  193. if (current === projectRoot || current === dirname(current)) {
  194. break;
  195. }
  196. current = dirname(current);
  197. }
  198. return undefined;
  199. }
  200. async function findDefaultUserInstructionFile(
  201. priorityFiles: string[],
  202. env: NodeJS.ProcessEnv,
  203. ): Promise<{ filePath: string; fileName: string } | undefined> {
  204. if (!priorityFiles.includes("AGENTS.md")) {
  205. return undefined;
  206. }
  207. const filePath = join(resolveUserHomeDir(env), ".zcode", "AGENTS.md");
  208. if (await isFile(filePath)) {
  209. return { filePath, fileName: "AGENTS.md" };
  210. }
  211. return undefined;
  212. }
  213. function resolveUserHomeDir(env: NodeJS.ProcessEnv): string {
  214. const envHome = env.HOME?.trim() || env.USERPROFILE?.trim();
  215. return envHome && envHome.length > 0 ? envHome : homedir();
  216. }
  217. async function detectProjectContext(projectRoot: string): Promise<ProjectContext> {
  218. let type: ProjectType = "unknown";
  219. let packageManager: PackageManager | undefined;
  220. let scripts: Record<string, string> | undefined;
  221. const buildFiles: string[] = [];
  222. const packageJsonPath = join(projectRoot, "package.json");
  223. if (await isFile(packageJsonPath)) {
  224. try {
  225. const pkg = JSON.parse(await readFile(packageJsonPath, "utf8")) as {
  226. scripts?: unknown;
  227. };
  228. type = "node";
  229. if (pkg.scripts && typeof pkg.scripts === "object") {
  230. scripts = pkg.scripts as Record<string, string>;
  231. }
  232. } catch {
  233. type = "node";
  234. }
  235. }
  236. if (type === "unknown") {
  237. const pythonIndicators = ["requirements.txt", "pyproject.toml", "setup.py", "Pipfile"];
  238. for (const file of pythonIndicators) {
  239. if (await isFile(join(projectRoot, file))) {
  240. type = "python";
  241. break;
  242. }
  243. }
  244. }
  245. if (type === "unknown" && (await isFile(join(projectRoot, "Cargo.toml")))) {
  246. type = "rust";
  247. }
  248. if (type === "unknown" && (await isFile(join(projectRoot, "go.mod")))) {
  249. type = "go";
  250. }
  251. if (type === "unknown") {
  252. for (const file of ["pom.xml", "build.gradle", "build.gradle.kts"]) {
  253. if (await isFile(join(projectRoot, file))) {
  254. type = "java";
  255. break;
  256. }
  257. }
  258. }
  259. if (await isFile(join(projectRoot, "pnpm-lock.yaml"))) {
  260. packageManager = "pnpm";
  261. } else if (await isFile(join(projectRoot, "yarn.lock"))) {
  262. packageManager = "yarn";
  263. } else if (await isFile(join(projectRoot, "bun.lockb"))) {
  264. packageManager = "bun";
  265. } else if (await isFile(join(projectRoot, "package-lock.json"))) {
  266. packageManager = "npm";
  267. }
  268. for (const file of ["Makefile", "docker-compose.yml", "docker-compose.yaml", "Dockerfile"]) {
  269. if (await isFile(join(projectRoot, file))) {
  270. buildFiles.push(file);
  271. }
  272. }
  273. return {
  274. type,
  275. packageManager,
  276. scripts,
  277. buildFiles: buildFiles.length > 0 ? buildFiles : undefined,
  278. };
  279. }
  280. async function findProjectRoot(startDir: string): Promise<string | null> {
  281. let current = resolve(startDir);
  282. while (current !== dirname(current)) {
  283. if (await hasGitMarker(current)) return current;
  284. current = dirname(current);
  285. }
  286. return null;
  287. }
  288. async function hasGitMarker(directory: string): Promise<boolean> {
  289. try {
  290. await stat(join(directory, ".git"));
  291. return true;
  292. } catch {
  293. return false;
  294. }
  295. }
  296. async function isFile(path: string): Promise<boolean> {
  297. try {
  298. const info = await stat(path);
  299. return info.isFile();
  300. } catch {
  301. return false;
  302. }
  303. }