opencode.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /**
  2. * opencode target.
  3. *
  4. * - MCP server entry to `~/.config/opencode/opencode.jsonc` (global,
  5. * XDG-style; `%APPDATA%/opencode/opencode.jsonc` on Windows) or
  6. * `./opencode.jsonc` (local). Falls back to `opencode.json` when a
  7. * `.json` file already exists; defaults new installs to `.jsonc`
  8. * because that's what opencode itself creates on first run.
  9. * - Instructions to `~/.config/opencode/AGENTS.md` (global) or
  10. * `./AGENTS.md` (local). opencode reads AGENTS.md for agent
  11. * instructions — same convention Codex CLI uses.
  12. * - No permissions concept.
  13. *
  14. * Config shape uses opencode's wrapper:
  15. * {
  16. * "$schema": "https://opencode.ai/config.json",
  17. * "mcp": { "codegraph": { "type": "local", "command": [...], "enabled": true } }
  18. * }
  19. *
  20. * The shape differs from Claude/Cursor — opencode uses `mcp.<name>`
  21. * (not `mcpServers`), takes `command` as a string array combining
  22. * binary + args, and includes an explicit `enabled` flag.
  23. *
  24. * Reads + writes go through `jsonc-parser` so any `//` and `/* *\/`
  25. * comments the user has added to their `.jsonc` survive idempotent
  26. * re-runs.
  27. */
  28. import * as fs from 'fs';
  29. import * as path from 'path';
  30. import * as os from 'os';
  31. import { parse as parseJsonc, modify, applyEdits } from 'jsonc-parser';
  32. import {
  33. AgentTarget,
  34. DetectionResult,
  35. InstallOptions,
  36. Location,
  37. WriteResult,
  38. } from './types';
  39. import {
  40. atomicWriteFileSync,
  41. jsonDeepEqual,
  42. removeMarkedSection,
  43. } from './shared';
  44. import {
  45. CODEGRAPH_SECTION_END,
  46. CODEGRAPH_SECTION_START,
  47. } from '../instructions-template';
  48. function globalConfigDir(): string {
  49. if (process.platform === 'win32') {
  50. const appData = process.env.APPDATA ?? path.join(os.homedir(), 'AppData', 'Roaming');
  51. return path.join(appData, 'opencode');
  52. }
  53. // XDG_CONFIG_HOME if set, else ~/.config — matches opencode's docs.
  54. const xdg = process.env.XDG_CONFIG_HOME && process.env.XDG_CONFIG_HOME.trim().length > 0
  55. ? process.env.XDG_CONFIG_HOME
  56. : path.join(os.homedir(), '.config');
  57. return path.join(xdg, 'opencode');
  58. }
  59. function configBaseDir(loc: Location): string {
  60. return loc === 'global' ? globalConfigDir() : process.cwd();
  61. }
  62. // Pick existing .jsonc, then .json, default to .jsonc for new files.
  63. // opencode auto-creates .jsonc on first run, so that's the dominant
  64. // real-world case and the sensible default for greenfield installs.
  65. function configPath(loc: Location): string {
  66. const dir = configBaseDir(loc);
  67. const jsonc = path.join(dir, 'opencode.jsonc');
  68. const json = path.join(dir, 'opencode.json');
  69. if (fs.existsSync(jsonc)) return jsonc;
  70. if (fs.existsSync(json)) return json;
  71. return jsonc;
  72. }
  73. function instructionsPath(loc: Location): string {
  74. return path.join(configBaseDir(loc), 'AGENTS.md');
  75. }
  76. function readConfigText(file: string): string {
  77. if (!fs.existsSync(file)) return '';
  78. return fs.readFileSync(file, 'utf-8');
  79. }
  80. function parseConfig(text: string): Record<string, any> {
  81. if (!text.trim()) return {};
  82. const errors: any[] = [];
  83. const result = parseJsonc(text, errors, { allowTrailingComma: true });
  84. if (result == null || typeof result !== 'object' || Array.isArray(result)) {
  85. return {};
  86. }
  87. return result as Record<string, any>;
  88. }
  89. function getOpencodeServerEntry(): { type: string; command: string[]; enabled: boolean } {
  90. return {
  91. type: 'local',
  92. command: ['codegraph', 'serve', '--mcp'],
  93. enabled: true,
  94. };
  95. }
  96. const FORMATTING = { tabSize: 2, insertSpaces: true, eol: '\n' };
  97. class OpencodeTarget implements AgentTarget {
  98. readonly id = 'opencode' as const;
  99. readonly displayName = 'opencode';
  100. readonly docsUrl = 'https://opencode.ai/docs/config';
  101. supportsLocation(_loc: Location): boolean {
  102. return true;
  103. }
  104. detect(loc: Location): DetectionResult {
  105. const file = configPath(loc);
  106. const config = parseConfig(readConfigText(file));
  107. const alreadyConfigured = !!config.mcp?.codegraph;
  108. const installed = loc === 'global'
  109. ? fs.existsSync(globalConfigDir())
  110. : fs.existsSync(file);
  111. return { installed, alreadyConfigured, configPath: file };
  112. }
  113. install(loc: Location, _opts: InstallOptions): WriteResult {
  114. const files: WriteResult['files'] = [];
  115. files.push(writeMcpEntry(loc));
  116. // AGENTS.md is no longer written — the codegraph usage guidance
  117. // ships in the MCP server's `initialize` response (issue #529).
  118. // Strip a block a previous install left so an upgrade self-heals.
  119. const instrCleanup = removeInstructionsEntry(loc);
  120. if (instrCleanup.action === 'removed') files.push(instrCleanup);
  121. return { files };
  122. }
  123. uninstall(loc: Location): WriteResult {
  124. const files: WriteResult['files'] = [];
  125. const file = configPath(loc);
  126. if (!fs.existsSync(file)) {
  127. files.push({ path: file, action: 'not-found' });
  128. } else {
  129. const text = readConfigText(file);
  130. const config = parseConfig(text);
  131. if (!config.mcp?.codegraph) {
  132. files.push({ path: file, action: 'not-found' });
  133. } else {
  134. // Drop our key surgically. Leaves siblings + comments untouched.
  135. let edits = modify(text, ['mcp', 'codegraph'], undefined, {
  136. formattingOptions: FORMATTING,
  137. });
  138. let updated = applyEdits(text, edits);
  139. // If `mcp` is now an empty object, drop the wrapper too.
  140. const afterParsed = parseConfig(updated);
  141. if (afterParsed.mcp && typeof afterParsed.mcp === 'object' &&
  142. Object.keys(afterParsed.mcp).length === 0) {
  143. edits = modify(updated, ['mcp'], undefined, { formattingOptions: FORMATTING });
  144. updated = applyEdits(updated, edits);
  145. }
  146. atomicWriteFileSync(file, updated);
  147. files.push({ path: file, action: 'removed' });
  148. }
  149. }
  150. files.push(removeInstructionsEntry(loc));
  151. return { files };
  152. }
  153. printConfig(loc: Location): string {
  154. const target = configPath(loc);
  155. const snippet = JSON.stringify({
  156. $schema: 'https://opencode.ai/config.json',
  157. mcp: { codegraph: getOpencodeServerEntry() },
  158. }, null, 2);
  159. return `# Add to ${target}\n\n${snippet}\n`;
  160. }
  161. describePaths(loc: Location): string[] {
  162. return [configPath(loc), instructionsPath(loc)];
  163. }
  164. }
  165. function writeMcpEntry(loc: Location): WriteResult['files'][number] {
  166. const file = configPath(loc);
  167. const existed = fs.existsSync(file);
  168. let text = readConfigText(file);
  169. // Seed a minimal opencode config when the file is brand-new so
  170. // the result is a complete, schema-tagged file (not just a bare
  171. // `{ "mcp": {...} }`).
  172. if (!text.trim()) {
  173. text = '{\n "$schema": "https://opencode.ai/config.json"\n}\n';
  174. }
  175. const config = parseConfig(text);
  176. const before = config.mcp?.codegraph;
  177. const after = getOpencodeServerEntry();
  178. if (jsonDeepEqual(before, after)) {
  179. return { path: file, action: 'unchanged' };
  180. }
  181. // Add $schema if the user's existing file is missing it.
  182. if (!config.$schema) {
  183. const schemaEdits = modify(text, ['$schema'], 'https://opencode.ai/config.json', {
  184. formattingOptions: FORMATTING,
  185. });
  186. text = applyEdits(text, schemaEdits);
  187. }
  188. // Surgical edit — preserves comments, formatting, and order of
  189. // every key we don't touch.
  190. const edits = modify(text, ['mcp', 'codegraph'], after, {
  191. formattingOptions: FORMATTING,
  192. });
  193. const updated = applyEdits(text, edits);
  194. atomicWriteFileSync(file, updated);
  195. return { path: file, action: existed ? 'updated' : 'created' };
  196. }
  197. /**
  198. * Strip the marker-delimited CodeGraph block from AGENTS.md if a prior
  199. * install wrote one. Used by both install (self-heal on upgrade) and
  200. * uninstall — see issue #529.
  201. */
  202. function removeInstructionsEntry(loc: Location): WriteResult['files'][number] {
  203. const file = instructionsPath(loc);
  204. const action = removeMarkedSection(file, CODEGRAPH_SECTION_START, CODEGRAPH_SECTION_END);
  205. return { path: file, action };
  206. }
  207. export const opencodeTarget: AgentTarget = new OpencodeTarget();