opencode.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /**
  2. * opencode target.
  3. *
  4. * - MCP server entry to `~/.config/opencode/opencode.jsonc` (global,
  5. * XDG-style on EVERY platform, Windows included — see below) 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. *
  10. * opencode resolves its config dir with the `xdg-basedir` package
  11. * (sst/opencode `packages/core/src/global.ts`): `XDG_CONFIG_HOME`
  12. * if set, else `~/.config` — unconditionally, on all platforms. It
  13. * never reads `%APPDATA%`; that layout belonged to the discontinued
  14. * Go fork. We previously wrote there on Windows, so opencode never
  15. * saw the entry (#535) — install/uninstall now also sweep a stale
  16. * codegraph entry out of the legacy `%APPDATA%/opencode` location.
  17. * - Instructions to `~/.config/opencode/AGENTS.md` (global) or
  18. * `./AGENTS.md` (local). opencode reads AGENTS.md for agent
  19. * instructions — same convention Codex CLI uses.
  20. * - No permissions concept.
  21. *
  22. * Config shape uses OpenCode 2's native wrapper (also read by 1.18+):
  23. * {
  24. * "$schema": "https://opencode.ai/config.json",
  25. * "mcp": {
  26. * "servers": {
  27. * "codegraph": {
  28. * "type": "local",
  29. * "command": [...],
  30. * "disabled": false,
  31. * "codemode": false
  32. * }
  33. * }
  34. * }
  35. * }
  36. *
  37. * OpenCode 2 puts servers under `mcp.servers` (not `mcp.<name>`), uses
  38. * `disabled` instead of `enabled`, and defaults tools through Code Mode —
  39. * `codemode: false` keeps `codegraph_explore` on the provider's native
  40. * tool list (#1698). Pre-#1698 installs wrote the v1 `mcp.codegraph` +
  41. * `enabled` shape; re-install migrates, uninstall removes either.
  42. *
  43. * Reads + writes go through `jsonc-parser` so any `//` and `/* *\/`
  44. * comments the user has added to their `.jsonc` survive idempotent
  45. * re-runs.
  46. */
  47. import * as fs from 'fs';
  48. import * as path from 'path';
  49. import * as os from 'os';
  50. import { parse as parseJsonc, modify, applyEdits } from 'jsonc-parser';
  51. import {
  52. AgentTarget,
  53. DetectionResult,
  54. InstallOptions,
  55. Location,
  56. WriteResult,
  57. } from './types';
  58. import {
  59. atomicWriteFileSync,
  60. jsonDeepEqual,
  61. removeMarkedSection,
  62. upsertInstructionsEntry,
  63. } from './shared';
  64. import {
  65. CODEGRAPH_SECTION_END,
  66. CODEGRAPH_SECTION_START,
  67. } from '../instructions-template';
  68. function globalConfigDir(): string {
  69. // XDG_CONFIG_HOME if set, else ~/.config — on every platform, matching
  70. // opencode's own `xdg-basedir` resolution (no Windows special case; #535).
  71. const xdg = process.env.XDG_CONFIG_HOME && process.env.XDG_CONFIG_HOME.trim().length > 0
  72. ? process.env.XDG_CONFIG_HOME
  73. : path.join(os.homedir(), '.config');
  74. return path.join(xdg, 'opencode');
  75. }
  76. /**
  77. * Pre-#535 installs wrote the global entry to `%APPDATA%/opencode` — a dir
  78. * today's opencode never reads. Returns that legacy dir when it could hold
  79. * stale state (APPDATA set and resolving somewhere other than the real config
  80. * dir). Gated on the env var rather than `process.platform` so the cleanup
  81. * logic runs under the cross-platform test suite; on POSIX, APPDATA is unset
  82. * in real life and this is a no-op.
  83. */
  84. function legacyWindowsConfigDir(): string | null {
  85. const appData = process.env.APPDATA;
  86. if (!appData || !appData.trim()) return null;
  87. const legacy = path.join(appData, 'opencode');
  88. return path.resolve(legacy) === path.resolve(globalConfigDir()) ? null : legacy;
  89. }
  90. function configBaseDir(loc: Location): string {
  91. return loc === 'global' ? globalConfigDir() : process.cwd();
  92. }
  93. // Pick existing .jsonc, then .json, default to .jsonc for new files.
  94. // opencode auto-creates .jsonc on first run, so that's the dominant
  95. // real-world case and the sensible default for greenfield installs.
  96. function configPath(loc: Location): string {
  97. const dir = configBaseDir(loc);
  98. const jsonc = path.join(dir, 'opencode.jsonc');
  99. const json = path.join(dir, 'opencode.json');
  100. if (fs.existsSync(jsonc)) return jsonc;
  101. if (fs.existsSync(json)) return json;
  102. return jsonc;
  103. }
  104. function instructionsPath(loc: Location): string {
  105. return path.join(configBaseDir(loc), 'AGENTS.md');
  106. }
  107. function readConfigText(file: string): string {
  108. if (!fs.existsSync(file)) return '';
  109. return fs.readFileSync(file, 'utf-8');
  110. }
  111. function parseConfig(text: string): Record<string, any> {
  112. if (!text.trim()) return {};
  113. const errors: any[] = [];
  114. const result = parseJsonc(text, errors, { allowTrailingComma: true });
  115. if (result == null || typeof result !== 'object' || Array.isArray(result)) {
  116. return {};
  117. }
  118. return result as Record<string, any>;
  119. }
  120. function getOpencodeServerEntry(): {
  121. type: string;
  122. command: string[];
  123. disabled: boolean;
  124. codemode: boolean;
  125. } {
  126. return {
  127. type: 'local',
  128. command: ['codegraph', 'serve', '--mcp'],
  129. disabled: false,
  130. // Keep codegraph_explore on the native tool list — OpenCode 2's
  131. // default Code Mode would otherwise hide the one-tool server (#1698).
  132. codemode: false,
  133. };
  134. }
  135. /** True when either the OpenCode 2 native entry or a pre-#1698 v1 entry is present. */
  136. function hasCodegraphEntry(config: Record<string, any>): boolean {
  137. return !!(config.mcp?.servers?.codegraph || config.mcp?.codegraph);
  138. }
  139. const FORMATTING = { tabSize: 2, insertSpaces: true, eol: '\n' };
  140. class OpencodeTarget implements AgentTarget {
  141. readonly id = 'opencode' as const;
  142. readonly displayName = 'opencode';
  143. readonly docsUrl = 'https://opencode.ai/docs/config';
  144. supportsLocation(_loc: Location): boolean {
  145. return true;
  146. }
  147. detect(loc: Location): DetectionResult {
  148. const file = configPath(loc);
  149. const config = parseConfig(readConfigText(file));
  150. const alreadyConfigured = hasCodegraphEntry(config);
  151. // Global: the XDG dir is what current opencode creates on first run; the
  152. // legacy %APPDATA% dir still counts as "opencode present" so a re-install
  153. // can sweep the stale pre-#535 entry out of it.
  154. const legacy = legacyWindowsConfigDir();
  155. const installed = loc === 'global'
  156. ? fs.existsSync(globalConfigDir()) || (!!legacy && fs.existsSync(legacy))
  157. : fs.existsSync(file);
  158. return { installed, alreadyConfigured, configPath: file };
  159. }
  160. install(loc: Location, _opts: InstallOptions): WriteResult {
  161. const files: WriteResult['files'] = [];
  162. files.push(writeMcpEntry(loc));
  163. // AGENTS.md gets the short marker-fenced CodeGraph block (#704):
  164. // subagents and non-MCP harnesses read AGENTS.md but never the MCP
  165. // initialize instructions. Upsert self-heals a stale pre-#529 block.
  166. files.push(upsertInstructionsEntry(instructionsPath(loc)));
  167. // Self-heal a pre-#535 install that wrote to %APPDATA%/opencode —
  168. // opencode never reads it, so anything of ours there is stale.
  169. if (loc === 'global') files.push(...cleanupLegacyWindowsState());
  170. return { files };
  171. }
  172. uninstall(loc: Location): WriteResult {
  173. const files: WriteResult['files'] = [];
  174. files.push(removeMcpEntryAt(configPath(loc)));
  175. files.push(removeInstructionsEntry(loc));
  176. if (loc === 'global') files.push(...cleanupLegacyWindowsState());
  177. return { files };
  178. }
  179. printConfig(loc: Location): string {
  180. const target = configPath(loc);
  181. const snippet = JSON.stringify({
  182. $schema: 'https://opencode.ai/config.json',
  183. mcp: { servers: { codegraph: getOpencodeServerEntry() } },
  184. }, null, 2);
  185. return `# Add to ${target}\n\n${snippet}\n`;
  186. }
  187. describePaths(loc: Location): string[] {
  188. return [configPath(loc), instructionsPath(loc)];
  189. }
  190. }
  191. function writeMcpEntry(loc: Location): WriteResult['files'][number] {
  192. const file = configPath(loc);
  193. const existed = fs.existsSync(file);
  194. let text = readConfigText(file);
  195. // Seed a minimal opencode config when the file is brand-new so
  196. // the result is a complete, schema-tagged file (not just a bare
  197. // `{ "mcp": {...} }`).
  198. if (!text.trim()) {
  199. text = '{\n "$schema": "https://opencode.ai/config.json"\n}\n';
  200. }
  201. const config = parseConfig(text);
  202. const before = config.mcp?.servers?.codegraph;
  203. const after = getOpencodeServerEntry();
  204. const hasLegacy = !!config.mcp?.codegraph;
  205. // Native entry already matches and no v1 leftover → nothing to do.
  206. if (jsonDeepEqual(before, after) && !hasLegacy) {
  207. return { path: file, action: 'unchanged' };
  208. }
  209. // Add $schema if the user's existing file is missing it.
  210. if (!config.$schema) {
  211. const schemaEdits = modify(text, ['$schema'], 'https://opencode.ai/config.json', {
  212. formattingOptions: FORMATTING,
  213. });
  214. text = applyEdits(text, schemaEdits);
  215. }
  216. // Migrate pre-#1698 `mcp.codegraph` (+ enabled) off the file so OpenCode 2
  217. // keeps only the native entry where `codemode` survives normalization.
  218. if (hasLegacy) {
  219. const legacyEdits = modify(text, ['mcp', 'codegraph'], undefined, {
  220. formattingOptions: FORMATTING,
  221. });
  222. text = applyEdits(text, legacyEdits);
  223. }
  224. // Surgical edit — preserves comments, formatting, and order of
  225. // every key we don't touch.
  226. const edits = modify(text, ['mcp', 'servers', 'codegraph'], after, {
  227. formattingOptions: FORMATTING,
  228. });
  229. const updated = applyEdits(text, edits);
  230. atomicWriteFileSync(file, updated);
  231. return { path: file, action: existed ? 'updated' : 'created' };
  232. }
  233. /**
  234. * Surgically drop our CodeGraph entry from one config file — either the
  235. * OpenCode 2 native `mcp.servers.codegraph` or a pre-#1698 `mcp.codegraph`.
  236. * Leaves sibling servers, comments, and formatting untouched; drops emptied
  237. * `mcp.servers` / `mcp` wrappers too. Shared by uninstall and the
  238. * legacy-%APPDATA% sweep.
  239. */
  240. function removeMcpEntryAt(file: string): WriteResult['files'][number] {
  241. if (!fs.existsSync(file)) return { path: file, action: 'not-found' };
  242. let text = readConfigText(file);
  243. const config = parseConfig(text);
  244. if (!hasCodegraphEntry(config)) return { path: file, action: 'not-found' };
  245. let updated = text;
  246. if (config.mcp?.servers?.codegraph) {
  247. const edits = modify(updated, ['mcp', 'servers', 'codegraph'], undefined, {
  248. formattingOptions: FORMATTING,
  249. });
  250. updated = applyEdits(updated, edits);
  251. }
  252. // Re-parse after the native removal so a file that held BOTH shapes
  253. // (unusual, but possible mid-migration) still drops the v1 leftover.
  254. const mid = parseConfig(updated);
  255. if (mid.mcp?.codegraph) {
  256. const edits = modify(updated, ['mcp', 'codegraph'], undefined, {
  257. formattingOptions: FORMATTING,
  258. });
  259. updated = applyEdits(updated, edits);
  260. }
  261. // If `mcp.servers` is now an empty object, drop that wrapper.
  262. let afterParsed = parseConfig(updated);
  263. if (afterParsed.mcp?.servers && typeof afterParsed.mcp.servers === 'object' &&
  264. Object.keys(afterParsed.mcp.servers).length === 0) {
  265. const edits = modify(updated, ['mcp', 'servers'], undefined, {
  266. formattingOptions: FORMATTING,
  267. });
  268. updated = applyEdits(updated, edits);
  269. afterParsed = parseConfig(updated);
  270. }
  271. // If `mcp` is now an empty object, drop the wrapper too.
  272. if (afterParsed.mcp && typeof afterParsed.mcp === 'object' &&
  273. Object.keys(afterParsed.mcp).length === 0) {
  274. const edits = modify(updated, ['mcp'], undefined, { formattingOptions: FORMATTING });
  275. updated = applyEdits(updated, edits);
  276. }
  277. atomicWriteFileSync(file, updated);
  278. return { path: file, action: 'removed' };
  279. }
  280. /**
  281. * Remove whatever a pre-#535 install left in `%APPDATA%/opencode` — an MCP
  282. * entry opencode never reads, plus our marker-fenced AGENTS.md block. Returns
  283. * only files actually changed, so install output stays quiet when there is
  284. * nothing to heal. Never touches anything else in the legacy dir: a user may
  285. * genuinely keep other tools' state under %APPDATA%.
  286. */
  287. function cleanupLegacyWindowsState(): WriteResult['files'] {
  288. const dir = legacyWindowsConfigDir();
  289. if (!dir || !fs.existsSync(dir)) return [];
  290. const out: WriteResult['files'] = [];
  291. for (const name of ['opencode.jsonc', 'opencode.json']) {
  292. const res = removeMcpEntryAt(path.join(dir, name));
  293. if (res.action === 'removed') out.push(res);
  294. }
  295. const agents = path.join(dir, 'AGENTS.md');
  296. const action = removeMarkedSection(agents, CODEGRAPH_SECTION_START, CODEGRAPH_SECTION_END);
  297. if (action === 'removed') out.push({ path: agents, action });
  298. return out;
  299. }
  300. /**
  301. * Strip the marker-delimited CodeGraph block from AGENTS.md if a prior
  302. * install wrote one. Used by both install (self-heal on upgrade) and
  303. * uninstall — see issue #529.
  304. */
  305. function removeInstructionsEntry(loc: Location): WriteResult['files'][number] {
  306. const file = instructionsPath(loc);
  307. const action = removeMarkedSection(file, CODEGRAPH_SECTION_START, CODEGRAPH_SECTION_END);
  308. return { path: file, action };
  309. }
  310. export const opencodeTarget: AgentTarget = new OpencodeTarget();