system.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import { spawnSync } from 'node:child_process';
  2. import { statSync } from 'node:fs';
  3. import { crossSpawn } from '../utils/compat';
  4. let cachedOpenCodePath: string | null = null;
  5. function resolvePathCommand(
  6. command: string,
  7. environment: NodeJS.ProcessEnv = process.env,
  8. ): string | null {
  9. try {
  10. const isWindows = process.platform === 'win32';
  11. const resolver = isWindows ? 'where' : 'which';
  12. const result = spawnSync(resolver, [command], {
  13. encoding: 'utf-8',
  14. stdio: ['ignore', 'pipe', 'ignore'],
  15. env: environment,
  16. // On Windows, `where opencode` returns multiple shims (opencode, opencode.cmd,
  17. // opencode.ps1). Node's spawnSync cannot execute an extensionless npm shim,
  18. // and since Node's CVE-2024-27980 patch .cmd/.bat files also require a shell.
  19. shell: isWindows,
  20. });
  21. if (result.status !== 0) {
  22. return null;
  23. }
  24. const lines = result.stdout
  25. .split(/\r?\n/)
  26. .map((line) => line.trim())
  27. .filter(Boolean);
  28. if (lines.length === 0) {
  29. return null;
  30. }
  31. // On Windows, prefer executable shims (.cmd, .exe, .ps1) over the
  32. // extensionless npm wrapper that Node cannot spawn directly.
  33. if (isWindows) {
  34. const executable = lines.find((line) =>
  35. /\.(cmd|exe|ps1|bat)$/i.test(line),
  36. );
  37. return executable ?? lines[0];
  38. }
  39. return lines[0];
  40. } catch {
  41. return null;
  42. }
  43. }
  44. function canExecute(
  45. command: string,
  46. args: string[],
  47. environment: NodeJS.ProcessEnv = process.env,
  48. ): boolean {
  49. try {
  50. const isWindows = process.platform === 'win32';
  51. const result = spawnSync(command, args, {
  52. stdio: 'ignore',
  53. env: environment,
  54. // Required on Windows to execute .cmd/.bat shims produced by npm/pnpm/yarn
  55. // (Node's CVE-2024-27980 patch blocks them without a shell).
  56. shell: isWindows && !/\.exe$/i.test(command),
  57. });
  58. return result.status === 0;
  59. } catch {
  60. return false;
  61. }
  62. }
  63. function getOpenCodePaths(
  64. environment: NodeJS.ProcessEnv = process.env,
  65. ): string[] {
  66. const home = environment.HOME || environment.USERPROFILE || '';
  67. const isWindows = process.platform === 'win32';
  68. const appData = environment.APPDATA || `${home}\\AppData\\Roaming`;
  69. const localAppData = environment.LOCALAPPDATA || `${home}\\AppData\\Local`;
  70. const windowsPaths = isWindows
  71. ? [
  72. // npm global shims (created as .cmd on Windows)
  73. `${appData}\\npm\\opencode.cmd`,
  74. `${appData}\\npm\\opencode.ps1`,
  75. // pnpm global
  76. `${localAppData}\\pnpm\\opencode.cmd`,
  77. // Yarn global
  78. `${localAppData}\\Yarn\\bin\\opencode.cmd`,
  79. // opencode.ai/install .exe location
  80. `${localAppData}\\Programs\\opencode\\opencode.exe`,
  81. // Scoop
  82. `${home}\\scoop\\shims\\opencode.exe`,
  83. `${home}\\scoop\\apps\\opencode\\current\\bin\\opencode.exe`,
  84. // Chocolatey
  85. `C:\\ProgramData\\chocolatey\\bin\\opencode.exe`,
  86. ]
  87. : [];
  88. return [
  89. // PATH (try this first)
  90. 'opencode',
  91. ...windowsPaths,
  92. // User local installations (Linux & macOS)
  93. `${home}/.local/bin/opencode`,
  94. `${home}/.opencode/bin/opencode`,
  95. `${home}/bin/opencode`,
  96. // System-wide installations
  97. '/usr/local/bin/opencode',
  98. '/opt/opencode/bin/opencode',
  99. '/usr/bin/opencode',
  100. '/bin/opencode',
  101. // macOS specific
  102. '/Applications/OpenCode.app/Contents/MacOS/opencode',
  103. `${home}/Applications/OpenCode.app/Contents/MacOS/opencode`,
  104. // Homebrew (macOS & Linux)
  105. '/opt/homebrew/bin/opencode',
  106. '/home/linuxbrew/.linuxbrew/bin/opencode',
  107. `${home}/homebrew/bin/opencode`,
  108. // macOS user Library
  109. `${home}/Library/Application Support/opencode/bin/opencode`,
  110. // Snap (Linux)
  111. '/snap/bin/opencode',
  112. '/var/snap/opencode/current/bin/opencode',
  113. // Flatpak (Linux)
  114. '/var/lib/flatpak/exports/bin/ai.opencode.OpenCode',
  115. `${home}/.local/share/flatpak/exports/bin/ai.opencode.OpenCode`,
  116. // Nix (Linux/macOS)
  117. '/nix/store/opencode/bin/opencode',
  118. `${home}/.nix-profile/bin/opencode`,
  119. '/run/current-system/sw/bin/opencode',
  120. // Cargo (Rust toolchain)
  121. `${home}/.cargo/bin/opencode`,
  122. // npm/npx global
  123. `${home}/.npm-global/bin/opencode`,
  124. '/usr/local/lib/node_modules/opencode/bin/opencode',
  125. // Yarn global
  126. `${home}/.yarn/bin/opencode`,
  127. // PNPM
  128. `${home}/.pnpm-global/bin/opencode`,
  129. ];
  130. }
  131. export function resolveOpenCodePath(
  132. environment: NodeJS.ProcessEnv = process.env,
  133. ): string {
  134. const useCache = environment === process.env;
  135. if (useCache && cachedOpenCodePath) {
  136. return cachedOpenCodePath;
  137. }
  138. const pathOpenCodePath = resolvePathCommand('opencode', environment);
  139. if (pathOpenCodePath) {
  140. if (useCache) {
  141. cachedOpenCodePath = pathOpenCodePath;
  142. }
  143. return pathOpenCodePath;
  144. }
  145. const paths = getOpenCodePaths(environment);
  146. for (const opencodePath of paths) {
  147. if (opencodePath === 'opencode') continue;
  148. try {
  149. const stat = statSync(opencodePath);
  150. if (stat.isFile()) {
  151. if (useCache) {
  152. cachedOpenCodePath = opencodePath;
  153. }
  154. return opencodePath;
  155. }
  156. } catch {
  157. // Try next path
  158. }
  159. }
  160. // Fallback to 'opencode' and hope it's in PATH
  161. return 'opencode';
  162. }
  163. export async function isOpenCodeInstalled(
  164. environment: NodeJS.ProcessEnv = process.env,
  165. ): Promise<boolean> {
  166. const useCache = environment === process.env;
  167. const pathOpenCodePath = resolvePathCommand('opencode', environment);
  168. if (
  169. pathOpenCodePath &&
  170. canExecute(pathOpenCodePath, ['--version'], environment)
  171. ) {
  172. if (useCache) {
  173. cachedOpenCodePath = pathOpenCodePath;
  174. }
  175. return true;
  176. }
  177. const paths = getOpenCodePaths(environment);
  178. for (const opencodePath of paths) {
  179. if (opencodePath === 'opencode') continue;
  180. if (canExecute(opencodePath, ['--version'], environment)) {
  181. if (useCache) {
  182. cachedOpenCodePath = opencodePath;
  183. }
  184. return true;
  185. }
  186. }
  187. return false;
  188. }
  189. export async function isTmuxInstalled(): Promise<boolean> {
  190. try {
  191. const proc = crossSpawn(['tmux', '-V'], {
  192. stdout: 'pipe',
  193. stderr: 'pipe',
  194. });
  195. await proc.exited;
  196. return proc.exitCode === 0;
  197. } catch {
  198. return false;
  199. }
  200. }
  201. export async function getOpenCodeVersion(): Promise<string | null> {
  202. const opencodePath = resolveOpenCodePath();
  203. try {
  204. const proc = crossSpawn([opencodePath, '--version'], {
  205. stdout: 'pipe',
  206. stderr: 'pipe',
  207. });
  208. const outputPromise = proc.stdout();
  209. await proc.exited;
  210. if (proc.exitCode === 0) {
  211. return (await outputPromise).trim();
  212. }
  213. } catch {
  214. // Failed
  215. }
  216. return null;
  217. }
  218. export function getOpenCodePath(): string | null {
  219. const path = resolveOpenCodePath();
  220. return path === 'opencode' ? null : path;
  221. }
  222. export async function fetchLatestVersion(
  223. packageName: string,
  224. ): Promise<string | null> {
  225. try {
  226. const res = await fetch(`https://registry.npmjs.org/${packageName}/latest`);
  227. if (!res.ok) return null;
  228. const data = (await res.json()) as { version: string };
  229. return data.version;
  230. } catch {
  231. return null;
  232. }
  233. }