repository-manager.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. /**
  2. * Repository Manager - Handles Git repository cloning and updates
  3. */
  4. import { execSync } from 'child_process';
  5. import { existsSync, mkdirSync } from 'fs';
  6. import { dirname } from 'path';
  7. export interface RepositoryInfo {
  8. owner: string;
  9. repo: string;
  10. sshUrl: string;
  11. }
  12. /**
  13. * Fetch repository information from Gogs MCP
  14. */
  15. async function fetchRepositoryInfo(owner: string, repo: string): Promise<RepositoryInfo> {
  16. // This will be called from the context where Gogs MCP is already connected
  17. // For now, we'll use a simple approach: try to fetch the repo info using the Gogs API
  18. // In the actual implementation, this will be provided by the MCP server
  19. // Since we're running in a context where we can use the mcp__gogs__get_repository tool,
  20. // we'll need to make this work within the Agent SDK context
  21. // For now, return a placeholder that will be populated by the caller
  22. return {
  23. owner,
  24. repo,
  25. sshUrl: '' // Will be populated by the caller
  26. };
  27. }
  28. /**
  29. * Clone a Git repository
  30. */
  31. export function cloneRepository(gitUrl: string, targetPath: string): void {
  32. console.log(`Repository not found at ${targetPath}, cloning...`);
  33. // Create parent directory if it doesn't exist
  34. const parentDir = dirname(targetPath);
  35. if (!existsSync(parentDir)) {
  36. mkdirSync(parentDir, { recursive: true });
  37. }
  38. try {
  39. execSync(`git clone "${gitUrl}" "${targetPath}"`, {
  40. stdio: 'inherit',
  41. encoding: 'utf-8'
  42. });
  43. console.log('Repository cloned successfully');
  44. } catch (error) {
  45. console.error('Failed to clone repository:', error);
  46. throw new Error('Failed to clone repository');
  47. }
  48. }
  49. /**
  50. * Pull latest changes from a Git repository
  51. */
  52. export function pullRepository(repoPath: string): void {
  53. console.log('Repository found, pulling latest changes...');
  54. try {
  55. execSync('git pull', {
  56. cwd: repoPath,
  57. stdio: 'inherit',
  58. encoding: 'utf-8'
  59. });
  60. console.log('Repository updated successfully');
  61. } catch (error) {
  62. console.warn('Warning: git pull failed, continuing with existing repository state');
  63. console.warn(error);
  64. }
  65. }
  66. /**
  67. * Ensure repository exists and is up to date
  68. * Returns the ssh_url from Gogs MCP that should be used
  69. */
  70. export function ensureRepository(repoPath: string, sshUrl: string): void {
  71. if (!existsSync(repoPath)) {
  72. cloneRepository(sshUrl, repoPath);
  73. } else {
  74. pullRepository(repoPath);
  75. }
  76. }
  77. /**
  78. * Setup environment variables for proper execution
  79. */
  80. export function setupEnvironment(): void {
  81. // Ensure HOME is set (systemd might not set it)
  82. if (!process.env.HOME) {
  83. // Try to get HOME from system
  84. try {
  85. const whoami = execSync('whoami', { encoding: 'utf-8' }).trim();
  86. const homeDir = execSync(`getent passwd "${whoami}" | cut -d: -f6`, { encoding: 'utf-8' }).trim();
  87. if (homeDir) {
  88. process.env.HOME = homeDir;
  89. }
  90. } catch (error) {
  91. console.warn('Could not determine HOME directory, using /root');
  92. process.env.HOME = '/root';
  93. }
  94. }
  95. // Add NODE to PATH
  96. const localBin = `${process.env.HOME}/.local/bin`;
  97. if (!process.env.PATH?.includes(localBin)) {
  98. process.env.PATH = `${localBin}:${process.env.PATH || ''}`;
  99. }
  100. // Ensure XDG directories are set
  101. process.env.XDG_CACHE_HOME = process.env.XDG_CACHE_HOME || `${process.env.HOME}/.cache`;
  102. process.env.XDG_CONFIG_HOME = process.env.XDG_CONFIG_HOME || `${process.env.HOME}/.config`;
  103. process.env.XDG_DATA_HOME = process.env.XDG_DATA_HOME || `${process.env.HOME}/.local/share`;
  104. process.env.XDG_STATE_HOME = process.env.XDG_STATE_HOME || `${process.env.HOME}/.local/state`;
  105. // Create XDG directories if they don't exist
  106. const xdgDirs = [
  107. process.env.XDG_CACHE_HOME,
  108. process.env.XDG_CONFIG_HOME,
  109. process.env.XDG_DATA_HOME,
  110. process.env.XDG_STATE_HOME
  111. ];
  112. for (const dir of xdgDirs) {
  113. if (dir && !existsSync(dir)) {
  114. try {
  115. mkdirSync(dir, { recursive: true });
  116. } catch (error) {
  117. console.warn(`Warning: Could not create directory ${dir}:`, error);
  118. }
  119. }
  120. }
  121. }
  122. /**
  123. * Detect Agent Manager path
  124. */
  125. export function detectAgentManagerPath(): string {
  126. // Try multiple possible locations for the agent-manager .env file
  127. const possiblePaths = [
  128. '/home/claude/agent-manager',
  129. '/data/agent-manager',
  130. `${process.env.HOME}/agent-manager`
  131. ];
  132. for (const path of possiblePaths) {
  133. const envPath = `${path}/.env`;
  134. if (existsSync(envPath)) {
  135. console.log(`Found agent-manager at: ${path}`);
  136. return path;
  137. }
  138. }
  139. // Fallback: try to detect from current file location
  140. // This file is in client/src/, so agent-manager root is ../../
  141. const scriptDir = dirname(new URL(import.meta.url).pathname);
  142. const agentManagerPath = dirname(dirname(scriptDir));
  143. console.log(`Using detected path from script location: ${agentManagerPath}`);
  144. return agentManagerPath;
  145. }