verify-opencode-host-smoke.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import { spawn, spawnSync } from 'node:child_process';
  2. import {
  3. copyFileSync,
  4. existsSync,
  5. mkdirSync,
  6. mkdtempSync,
  7. rmSync,
  8. writeFileSync,
  9. } from 'node:fs';
  10. import { createServer } from 'node:net';
  11. import { tmpdir } from 'node:os';
  12. import path from 'node:path';
  13. import { fileURLToPath } from 'node:url';
  14. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  15. const repoRoot = path.resolve(__dirname, '..');
  16. const distEntry = path.join(repoRoot, 'dist', 'index.js');
  17. function fail(message: string): never {
  18. throw new Error(message);
  19. }
  20. function run(
  21. command: string,
  22. args: string[],
  23. options: { cwd?: string; env?: Record<string, string> } = {},
  24. ) {
  25. const result = spawnSync(command, args, {
  26. cwd: options.cwd ?? repoRoot,
  27. env: {
  28. ...process.env,
  29. ...options.env,
  30. },
  31. encoding: 'utf8',
  32. stdio: ['ignore', 'pipe', 'pipe'],
  33. });
  34. if (result.status !== 0) {
  35. const detail = [result.stdout, result.stderr].filter(Boolean).join('\n');
  36. fail(
  37. `Command failed: ${command} ${args.join(' ')}${detail ? `\n${detail}` : ''}`,
  38. );
  39. }
  40. return result.stdout.trim();
  41. }
  42. function parsePackJson(output: string) {
  43. const start = output.indexOf('[');
  44. const end = output.lastIndexOf(']');
  45. if (start === -1 || end === -1 || end < start) {
  46. fail(`Could not locate npm pack JSON output:\n${output}`);
  47. }
  48. return JSON.parse(output.slice(start, end + 1)) as Array<{
  49. filename?: string;
  50. }>;
  51. }
  52. function packArtifact() {
  53. const output = run('npm', ['pack', '--json', '--ignore-scripts']);
  54. const parsed = parsePackJson(output);
  55. const tarball = parsed[0]?.filename;
  56. if (!tarball) fail(`npm pack did not return a tarball filename:\n${output}`);
  57. return path.join(repoRoot, tarball);
  58. }
  59. async function getFreePort() {
  60. const server = createServer();
  61. return await new Promise<number>((resolve, reject) => {
  62. server.once('error', reject);
  63. server.listen(0, '127.0.0.1', () => {
  64. const address = server.address();
  65. if (!address || typeof address === 'string') {
  66. server.close();
  67. reject(new Error('Failed to allocate free port'));
  68. return;
  69. }
  70. const { port } = address;
  71. server.close((error) => {
  72. if (error) reject(error);
  73. else resolve(port);
  74. });
  75. });
  76. });
  77. }
  78. async function waitForHealth(url: string, timeoutMs: number) {
  79. const deadline = Date.now() + timeoutMs;
  80. let lastError = 'health check did not succeed';
  81. while (Date.now() < deadline) {
  82. try {
  83. const response = await fetch(url);
  84. if (response.ok) return;
  85. lastError = `health check returned ${response.status}`;
  86. } catch (error) {
  87. lastError = error instanceof Error ? error.message : String(error);
  88. }
  89. await new Promise((resolve) => setTimeout(resolve, 250));
  90. }
  91. fail(`OpenCode server did not become healthy: ${lastError}`);
  92. }
  93. async function stopProcess(child: ReturnType<typeof spawn>) {
  94. if (child.exitCode !== null) return;
  95. child.kill('SIGTERM');
  96. const exited = await Promise.race([
  97. new Promise<boolean>((resolve) => child.once('exit', () => resolve(true))),
  98. new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 5000)),
  99. ]);
  100. if (!exited && child.exitCode === null) {
  101. child.kill('SIGKILL');
  102. await new Promise((resolve) => child.once('exit', resolve));
  103. }
  104. }
  105. function assertNoPluginLoadErrors(logs: string) {
  106. const badPatterns = [
  107. /failed to load plugin/i,
  108. /cannot find module/i,
  109. /error=.*failed to load plugin/i,
  110. ];
  111. const match = badPatterns.find((pattern) => pattern.test(logs));
  112. if (!match) return;
  113. const relevantLines = logs
  114. .split(/\r?\n/)
  115. .filter((line) =>
  116. /plugin|failed to load|cannot find module|error=/i.test(line),
  117. )
  118. .slice(-20)
  119. .join('\n');
  120. fail(
  121. `OpenCode logs contain plugin load errors:${relevantLines ? `\n${relevantLines}` : ''}`,
  122. );
  123. }
  124. async function verifyHostSmoke(tarballPath: string) {
  125. const tempRoot = mkdtempSync(path.join(tmpdir(), 'omos-opencode-smoke-'));
  126. const homeDir = path.join(tempRoot, 'home');
  127. const configDir = path.join(tempRoot, 'config');
  128. const cacheDir = path.join(tempRoot, 'cache');
  129. const dataDir = path.join(tempRoot, 'data');
  130. const hostDir = path.join(tempRoot, 'host');
  131. const workspaceDir = path.join(tempRoot, 'workspace');
  132. const tarballTarget = path.join(tempRoot, path.basename(tarballPath));
  133. const port = await getFreePort();
  134. try {
  135. console.log('Packing plugin tarball into isolated test root...');
  136. copyFileSync(tarballPath, tarballTarget);
  137. for (const dir of [
  138. homeDir,
  139. configDir,
  140. cacheDir,
  141. dataDir,
  142. hostDir,
  143. workspaceDir,
  144. ]) {
  145. mkdirSync(dir, { recursive: true });
  146. }
  147. const pluginDir = path.join(configDir, 'plugins');
  148. mkdirSync(pluginDir, { recursive: true });
  149. writeFileSync(
  150. path.join(hostDir, 'package.json'),
  151. JSON.stringify(
  152. { name: 'verify-opencode-host-smoke', private: true },
  153. null,
  154. 2,
  155. ),
  156. );
  157. console.log('Installing opencode-ai into isolated test root...');
  158. run('bun', ['add', 'opencode-ai@latest'], { cwd: hostDir });
  159. const opencodeBin = path.join(hostDir, 'node_modules', '.bin', 'opencode');
  160. if (!existsSync(opencodeBin)) {
  161. fail(`Expected opencode binary at ${opencodeBin}`);
  162. }
  163. writeFileSync(
  164. path.join(configDir, 'package.json'),
  165. JSON.stringify(
  166. {
  167. type: 'module',
  168. dependencies: {
  169. 'oh-my-opencode-slim': `file:${tarballTarget}`,
  170. },
  171. },
  172. null,
  173. 2,
  174. ),
  175. );
  176. writeFileSync(
  177. path.join(pluginDir, 'load-oh-my-opencode-slim.js'),
  178. "export { default } from 'oh-my-opencode-slim';\n",
  179. );
  180. const config = JSON.stringify({
  181. $schema: 'https://opencode.ai/config.json',
  182. autoupdate: false,
  183. share: 'disabled',
  184. snapshot: false,
  185. });
  186. const env = {
  187. HOME: homeDir,
  188. XDG_CONFIG_HOME: configDir,
  189. XDG_CACHE_HOME: cacheDir,
  190. XDG_DATA_HOME: dataDir,
  191. OPENCODE_CONFIG_DIR: configDir,
  192. OPENCODE_CONFIG_CONTENT: config,
  193. OPENCODE_DISABLE_AUTOUPDATE: 'true',
  194. OPENCODE_DISABLE_MODELS_FETCH: 'true',
  195. OPENCODE_DISABLE_DEFAULT_PLUGINS: 'true',
  196. };
  197. console.log('Starting opencode serve with packaged plugin...');
  198. const child = spawn(
  199. opencodeBin,
  200. [
  201. 'serve',
  202. '--print-logs',
  203. '--log-level',
  204. 'DEBUG',
  205. '--hostname',
  206. '127.0.0.1',
  207. '--port',
  208. String(port),
  209. ],
  210. {
  211. cwd: workspaceDir,
  212. env: {
  213. ...process.env,
  214. ...env,
  215. },
  216. stdio: ['ignore', 'pipe', 'pipe'],
  217. },
  218. );
  219. let stdout = '';
  220. let stderr = '';
  221. child.stdout?.on('data', (chunk) => {
  222. stdout += String(chunk);
  223. });
  224. child.stderr?.on('data', (chunk) => {
  225. stderr += String(chunk);
  226. });
  227. const exitPromise = new Promise<never>((_, reject) => {
  228. child.once('exit', (code, signal) => {
  229. reject(
  230. new Error(
  231. `opencode serve exited before smoke test completed (code=${code}, signal=${signal})\n${stdout}\n${stderr}`,
  232. ),
  233. );
  234. });
  235. });
  236. await Promise.race([
  237. waitForHealth(`http://127.0.0.1:${port}/health`, 30000),
  238. exitPromise,
  239. ]);
  240. await new Promise((resolve) => setTimeout(resolve, 1500));
  241. assertNoPluginLoadErrors(`${stdout}\n${stderr}`);
  242. await stopProcess(child);
  243. } finally {
  244. rmSync(tempRoot, { recursive: true, force: true });
  245. }
  246. }
  247. function cleanupTarball(tarballPath: string) {
  248. rmSync(tarballPath, { force: true });
  249. }
  250. async function main() {
  251. if (!existsSync(distEntry)) {
  252. fail(
  253. 'dist/index.js is missing. Run `bun run build` before verify:host-smoke.',
  254. );
  255. }
  256. const tarballPath = packArtifact();
  257. try {
  258. await verifyHostSmoke(tarballPath);
  259. } finally {
  260. cleanupTarball(tarballPath);
  261. }
  262. console.log('OpenCode host smoke verification passed.');
  263. }
  264. await main();
  265. process.exit(0);