import path from 'node:path' import { isDeepStrictEqual } from 'node:util' import { ensureDir, pathExists, readJson, readTextOrEmpty, removeIfExists, writeJsonAtomic } from '../core/fs.js' import { toChangedEntry, writeManagedFile } from '../core/managedFiles.js' import { mergeCodexConfig, removeCodexManagedBlock } from '../core/codexConfig.js' import { getLegacyAntigravityGlobalMcpPath, normalizeAntigravityMcpPayload, readAntigravityMcp } from '../core/antigravity.js' import { getWindsurfGlobalMcpPath, normalizeWindsurfMcpPayload, readWindsurfMcp } from '../core/windsurf.js' import { adoptOpencodeEntries, hasOpencodeServersMap, isReservedOpencodeName, locateOpencodeEntries, normalizeOpencodeConfig, ownedOpencodeEntries, readOpencodeOwnership, removeOpencodeEntries, writeOpencodeOwnership, type OpencodeEntryNames, type OpencodeLayout, type OpencodeOwnership } from '../core/opencode.js' import { needsOpencodeServersLayout, renderVscodeMcp, toLegacyOpencodeServer, type OpencodeServerEntry } from '../core/renderers.js' import { findLegacyManagedNames, formatForeignLegacyWarnings, scopeManagedEntries } from '../core/globalScope.js' import { acquireSyncLock } from '../core/syncLock.js' import { buildAntigravityPayload } from './antigravity.js' import { buildCodexConfig } from './codex.js' import { buildCopilotCliPayload } from './copilotCli.js' import { buildVscodeMcpPayload } from './copilotVscode.js' import { buildCursorPayload } from './cursor.js' import { buildGeminiPayload } from './gemini.js' import { buildOpencodePayload } from './opencode.js' import { buildWindsurfPayload } from './windsurf.js' import { buildJuniePayload } from './junie.js' import { buildGrokConfig } from './grok.js' import { AMP_MCP_KEY, buildAmpPayload } from './amp.js' import { buildDroidPayload } from './droid.js' import { buildKiloPayload } from './kilo.js' import { buildDevinPayload } from './devin.js' import { ZED_CONTEXT_SERVERS_KEY, buildZedPayload } from './zed.js' import { buildGoosePayload } from './goose.js' import { readGooseDocument, readGooseExtensions, setGooseExtensions, writeGooseConfig } from '../core/goose.js' import { applyEdits, modify, parse as parseJsonc } from 'jsonc-parser' import type { ProjectPaths } from '../core/paths.js' import type { AgentsConfig, IntegrationName, ResolvedMcpServer } from '../types.js' interface BuildGeneratedResult { content: string warnings: string[] } interface HookContext { projectRoot: string paths: ProjectPaths check: boolean changed: string[] warnings: string[] config: AgentsConfig generatedByIntegration: Partial> enabled: boolean previousGeneratedByIntegration?: Partial> } export interface IntegrationSyncHook { id: IntegrationName generatedPath: (paths: ProjectPaths) => string buildGenerated: (servers: ResolvedMcpServer[]) => BuildGeneratedResult shouldMaterialize?: (config: AgentsConfig) => boolean materializeWhenDisabled?: boolean materialize?: (context: HookContext) => Promise } export const INTEGRATION_SYNC_HOOKS: IntegrationSyncHook[] = [ { id: 'codex', generatedPath: (paths) => paths.generatedCodex, buildGenerated: (servers) => { const codex = buildCodexConfig(servers) return { content: codex.content, warnings: codex.warnings } }, materializeWhenDisabled: true, materialize: async (context) => { await materializeTomlConfig({ context, targetPath: context.paths.codexConfig, generatedContent: context.generatedByIntegration.codex ?? '', label: 'Codex' }) } }, { id: 'gemini', generatedPath: (paths) => paths.generatedGemini, buildGenerated: (servers) => { const gemini = buildGeminiPayload(servers) return { content: `${JSON.stringify(gemini.payload, null, 2)}\n`, warnings: gemini.warnings } }, materializeWhenDisabled: true, materialize: async (context) => { await mergeJsonKey({ context, targetPath: context.paths.geminiSettings, rawGenerated: context.generatedByIntegration.gemini ?? '', previousGenerated: context.previousGeneratedByIntegration?.gemini, key: 'mcpServers', label: 'Gemini', statePath: context.paths.generatedGeminiState, transform: (merged) => context.enabled ? { ...merged, context: { ...recordFrom(merged.context), fileName: 'AGENTS.md' }, contextFileName: 'AGENTS.md' } : merged }) } }, { id: 'copilot_vscode', generatedPath: (paths) => paths.generatedCopilot, buildGenerated: (servers) => { const copilot = buildVscodeMcpPayload(servers) return { content: `${JSON.stringify(copilot.payload, null, 2)}\n`, warnings: copilot.warnings } }, materializeWhenDisabled: true, materialize: async (context) => { await mergeJsonKey({ context, targetPath: context.paths.vscodeMcp, rawGenerated: context.generatedByIntegration.copilot_vscode ?? '', previousGenerated: context.previousGeneratedByIntegration?.copilot_vscode, key: 'servers', label: 'Copilot VS Code', statePath: context.paths.generatedCopilotState, removeEmptyFile: true }) } }, { id: 'copilot_cli', generatedPath: (paths) => paths.generatedCopilotCli, buildGenerated: (servers) => { const copilot = buildCopilotCliPayload(servers) return { content: `${JSON.stringify(copilot.payload, null, 2)}\n`, warnings: copilot.warnings } }, // `.mcp.json` is shared with Claude Code's project scope, so both writers are // merged in core/sync.ts instead of materialising here. }, { id: 'cursor', generatedPath: (paths) => paths.generatedCursor, buildGenerated: (servers) => { const cursor = buildCursorPayload(servers) return { content: `${JSON.stringify(cursor.payload, null, 2)}\n`, warnings: cursor.warnings } }, materializeWhenDisabled: true, materialize: async (context) => { await mergeJsonKey({ context, targetPath: context.paths.cursorMcp, rawGenerated: context.generatedByIntegration.cursor ?? '', previousGenerated: context.previousGeneratedByIntegration?.cursor, key: 'mcpServers', label: 'Cursor', statePath: context.paths.generatedCursorMcpState, removeEmptyFile: true }) } }, { id: 'antigravity', generatedPath: (paths) => paths.generatedAntigravity, buildGenerated: (servers) => { const antigravity = buildAntigravityPayload(servers) return { content: `${JSON.stringify(antigravity.payload, null, 2)}\n`, warnings: antigravity.warnings } }, materializeWhenDisabled: true, materialize: async (context) => { const rawGenerated = context.generatedByIntegration.antigravity ?? '' const legacyProjectPath = context.paths.antigravityProjectMcp const legacyGlobalPath = getLegacyAntigravityGlobalMcpPath() const mcpSyncEnabled = context.config.integrations.options.antigravityGlobalSync !== false const legacyExists = await pathExists(legacyProjectPath) if (context.enabled && mcpSyncEnabled && legacyExists) { context.warnings.push('Found legacy .antigravity/mcp.json. Antigravity now uses .agents/mcp_config.json for workspace MCP.') } const statePath = context.paths.generatedAntigravityState const previousManagedNames = [...new Set([ ...await readManagedGlobalNames(statePath), ...await readManagedGlobalNames(statePath, 'pendingLegacyNames') ])] let legacyError: unknown try { await cleanupLegacyAntigravityGlobal({ globalPath: legacyGlobalPath, previousManagedNames, projectRoot: context.projectRoot, check: context.check, changed: context.changed, warnings: context.warnings }) } catch (error) { legacyError = error } await syncManagedAntigravityWorkspace({ enabled: context.enabled && mcpSyncEnabled, workspacePath: context.paths.antigravityWorkspaceMcp, statePath: context.paths.generatedAntigravityState, rawGenerated, projectRoot: context.projectRoot, check: context.check, changed: context.changed, warnings: context.warnings }) if (!context.check) { await writeJsonAtomic(statePath, { managedNames: await readManagedGlobalNames(statePath), ...(legacyError ? { pendingLegacyNames: previousManagedNames } : {}) }) } if (legacyError) throw legacyError } }, { id: 'windsurf', generatedPath: (paths) => paths.generatedWindsurf, buildGenerated: (servers) => { const windsurf = buildWindsurfPayload(servers) return { content: `${JSON.stringify(windsurf.payload, null, 2)}\n`, warnings: windsurf.warnings } }, materializeWhenDisabled: true, materialize: async (context) => { const rawGenerated = context.generatedByIntegration.windsurf ?? '' const globalPath = getWindsurfGlobalMcpPath() await syncManagedWindsurfGlobal({ enabled: context.enabled, globalPath, statePath: context.paths.generatedWindsurfState, rawGenerated, projectRoot: context.projectRoot, check: context.check, changed: context.changed, warnings: context.warnings }) } }, { id: 'opencode', generatedPath: (paths) => paths.generatedOpencode, buildGenerated: (servers) => { const opencode = buildOpencodePayload(servers) return { content: `${JSON.stringify(opencode.payload, null, 2)}\n`, warnings: opencode.warnings } }, materializeWhenDisabled: true, materialize: async (context) => { const targetPath = context.paths.opencodeConfig let sourcePath = targetPath if (!(await pathExists(targetPath)) && context.paths.isHome) { const legacyPath = path.join(context.projectRoot, 'opencode.json') if (await pathExists(legacyPath)) sourcePath = legacyPath } await syncOpencodeConfig({ context, targetPath, sourcePath, statePath: context.paths.generatedOpencodeState }) if (sourcePath !== targetPath) { context.warnings.push('Migrated existing OpenCode settings from legacy ~/opencode.json to ~/.config/opencode/opencode.json.') } } }, { id: 'junie', generatedPath: (paths) => paths.generatedJunie, buildGenerated: (servers) => { const junie = buildJuniePayload(servers) return { content: `${JSON.stringify(junie.payload, null, 2)}\n`, warnings: junie.warnings } }, materializeWhenDisabled: true, materialize: async (context) => { await mergeJsonKey({ context, targetPath: context.paths.junieMcp, rawGenerated: context.generatedByIntegration.junie ?? '', previousGenerated: context.previousGeneratedByIntegration?.junie, key: 'mcpServers', label: 'Junie', statePath: context.paths.generatedJunieState, removeEmptyFile: true }) } }, { id: 'claude', generatedPath: (paths) => paths.generatedClaude, buildGenerated: (servers) => { const claude = renderVscodeMcp(servers) return { content: `${JSON.stringify({ mcpServers: claude.servers }, null, 2)}\n`, warnings: claude.warnings } } }, { id: 'grok', generatedPath: (paths) => paths.generatedGrok, buildGenerated: (servers) => { const grok = buildGrokConfig(servers) return { content: grok.content, warnings: grok.warnings } }, materializeWhenDisabled: true, materialize: async (context) => { await materializeTomlConfig({ context, targetPath: context.paths.grokConfig, generatedContent: context.generatedByIntegration.grok ?? '', label: 'Grok' }) } }, { id: 'amp', materializeWhenDisabled: true, generatedPath: (paths) => paths.generatedAmp, buildGenerated: (servers) => { const amp = buildAmpPayload(servers) return { content: `${JSON.stringify(amp.payload, null, 2)}\n`, warnings: amp.warnings } }, materialize: async (context) => { await mergeJsonKey({ context, targetPath: context.paths.ampSettings, rawGenerated: context.generatedByIntegration.amp ?? '', key: AMP_MCP_KEY, label: 'Amp', statePath: context.paths.generatedAmpState, removeEmptyFile: true }) } }, { id: 'droid', generatedPath: (paths) => paths.generatedDroid, buildGenerated: (servers) => { const droid = buildDroidPayload(servers) return { content: `${JSON.stringify(droid.payload, null, 2)}\n`, warnings: droid.warnings } }, materializeWhenDisabled: true, materialize: async (context) => { await mergeJsonKey({ context, targetPath: context.paths.droidMcp, rawGenerated: context.generatedByIntegration.droid ?? '', key: 'mcpServers', label: 'Droid', statePath: context.paths.generatedDroidState, removeEmptyFile: true }) } }, { id: 'kilo', materializeWhenDisabled: true, generatedPath: (paths) => paths.generatedKilo, buildGenerated: (servers) => { const kilo = buildKiloPayload(servers) return { content: `${JSON.stringify(kilo.payload, null, 2)}\n`, warnings: kilo.warnings } }, materialize: async (context) => { await mergeJsoncKey({ context, targetPath: context.paths.kiloConfig, rawGenerated: context.generatedByIntegration.kilo ?? '', key: 'mcp', label: 'Kilo', statePath: context.paths.generatedKiloState, removeEmptyFile: true }) } }, { id: 'devin', generatedPath: (paths) => paths.generatedDevin, buildGenerated: (servers) => { const devin = buildDevinPayload(servers) return { content: `${JSON.stringify(devin.payload, null, 2)}\n`, warnings: devin.warnings } }, materializeWhenDisabled: true, materialize: async (context) => { await mergeJsonKey({ context, targetPath: context.paths.devinMcp, rawGenerated: context.generatedByIntegration.devin ?? '', key: 'mcpServers', label: 'Devin', statePath: context.paths.generatedDevinState, removeEmptyFile: true }) } }, { id: 'zed', materializeWhenDisabled: true, generatedPath: (paths) => paths.generatedZed, buildGenerated: (servers) => { const zed = buildZedPayload(servers) return { content: `${JSON.stringify(zed.payload, null, 2)}\n`, warnings: zed.warnings } }, materialize: async (context) => { // Zed ships settings.json with comments, so it has to be edited as JSONC. await mergeJsoncKey({ context, targetPath: context.paths.zedSettings, rawGenerated: context.generatedByIntegration.zed ?? '', key: ZED_CONTEXT_SERVERS_KEY, label: 'Zed', statePath: context.paths.generatedZedState, removeEmptyFile: true }) } }, { id: 'goose', generatedPath: (paths) => paths.generatedGoose, buildGenerated: (servers) => { const goose = buildGoosePayload(servers) return { content: `${JSON.stringify(goose.payload, null, 2)}\n`, warnings: goose.warnings } }, materializeWhenDisabled: true, materialize: async (context) => { await syncManagedGooseGlobal(context) } } ] function parseJsonObject(raw: string, label: string): Record { try { return JSON.parse(raw) as Record } catch (error) { throw new Error(`Failed to parse ${label}: ${error instanceof Error ? error.message : String(error)}`) } } interface ManagedGlobalState { managedNames: string[] } /** * Update the workspace Antigravity MCP file with the set of managed servers derived from the generated config and persist the list of managed server names. * * Reads the previous managed server names from `statePath`, merges them with the newly generated servers (removing any previously-managed entries that are no longer produced), writes the resulting MCP JSON to `workspacePath`, and updates the state file with the current managed server names. Operates in a no-op mode when `check` is true (no files are modified) but still computes warnings and records changed paths. * * @param enabled - Whether the integration is enabled; if false, generated servers are not applied but previously-managed names will be removed. * @param workspacePath - Absolute path to the workspace Antigravity MCP file to read and write. * @param statePath - Path to the JSON file that tracks previously-managed server names. * @param rawGenerated - Raw generated Antigravity MCP JSON produced by the integration (may be empty or whitespace). * @param projectRoot - Repository root used for recording relative changes when writing managed files. * @param check - If true, perform a dry run: compute changes and warnings without modifying files. * @param changed - Mutable array to which paths of files that would be or were changed will be appended. * @param warnings - Mutable array to which human-readable warning messages will be appended. */ async function syncManagedAntigravityWorkspace(args: { enabled: boolean workspacePath: string statePath: string rawGenerated: string projectRoot: string check: boolean changed: string[] warnings: string[] }): Promise { const previousNames = await readManagedGlobalNames(args.statePath) if (!args.enabled && previousNames.length === 0) return const lockPath = path.join(path.dirname(args.workspacePath), '.agents-antigravity-mcp.lock') const releaseLock = args.check ? null : await acquireSyncLock(lockPath) try { let existing: Record = {} if (await pathExists(args.workspacePath)) { try { existing = normalizeAntigravityMcpPayload(await readAntigravityMcp(args.workspacePath) ?? {}) } catch (error) { throw new Error( `Failed to read existing Antigravity MCP at ${args.workspacePath}; skipped Antigravity workspace sync. ${error instanceof Error ? error.message : String(error)}`) } } const generated = args.enabled && args.rawGenerated.trim().length > 0 ? normalizeAntigravityMcpPayload(parseJsonObject(args.rawGenerated, 'generated Antigravity config')) : normalizeAntigravityMcpPayload({}) const managedServers = recordFrom(generated.mcpServers) const existingServers = recordFrom(existing.mcpServers) const takenOver: string[] = [] const nextServers = mergeManagedServers(existingServers, previousNames, managedServers, takenOver) args.warnings.push(...formatTakenOverWarnings('.agents/mcp_config.json', takenOver)) const nextPayload = normalizeAntigravityMcpPayload({ ...existing, mcpServers: nextServers }) await writeManagedFile({ absolutePath: args.workspacePath, content: `${JSON.stringify(nextPayload, null, 2)}\n`, projectRoot: args.projectRoot, check: args.check, changed: args.changed }) if (!args.check) { await writeManagedGlobalNames(args.statePath, args.enabled ? Object.keys(managedServers) : []) } } finally { if (releaseLock) await releaseLock() } } /** * Remove previously-managed Antigravity MCP servers from a legacy global MCP file if it exists. * * Reads the legacy global MCP at `globalPath`, removes any servers whose names are listed in * `previousManagedNames`, and writes the updated MCP back to `globalPath`. If the legacy file * cannot be read or parsed, a warning is appended to `warnings` and no changes are written. * * @param globalPath - Absolute path to the legacy global Antigravity MCP file to update * @param previousManagedNames - Server names previously managed by this tool that should be removed * @param projectRoot - Repository root used when writing the managed file metadata * @param check - When true, operate in dry-run mode (do not acquire locks or persist changes) * @param changed - Mutable list that will be updated with paths that were or would be changed * @param warnings - Mutable list to which human-readable warning messages are appended on error */ async function cleanupLegacyAntigravityGlobal(args: { globalPath: string previousManagedNames: string[] projectRoot: string check: boolean changed: string[] warnings: string[] }): Promise { if (args.previousManagedNames.length === 0) return if (!(await pathExists(args.globalPath))) return const lockPath = path.join(path.dirname(args.globalPath), '.agents-antigravity-legacy-mcp.lock') const releaseLock = args.check ? null : await acquireSyncLock(lockPath) try { let existing: Record try { existing = normalizeAntigravityMcpPayload(await readAntigravityMcp(args.globalPath) ?? {}) } catch (error) { throw new Error( `Failed to read legacy Antigravity MCP at ${args.globalPath}; skipped legacy cleanup. ${error instanceof Error ? error.message : String(error)}`) } const existingServers = recordFrom(existing.mcpServers) const nextServers = mergeManagedServers(existingServers, args.previousManagedNames, {}) const nextPayload = normalizeAntigravityMcpPayload({ ...existing, mcpServers: nextServers }) await writeManagedFile({ absolutePath: args.globalPath, content: `${JSON.stringify(nextPayload, null, 2)}\n`, projectRoot: args.projectRoot, check: args.check, changed: args.changed }) } finally { if (releaseLock) await releaseLock() } } /** * Synchronizes the Windsurf global MCP by merging generated managed servers into the existing global MCP and updating the managed-server state. * * Merges `rawGenerated` (when `enabled`) into the existing MCP's `mcpServers`, removes previously-managed entries, writes the resulting MCP to `globalPath`, and updates `statePath` with the current set of managed server names. Uses a filesystem lock to avoid concurrent writes and appends any warnings to `warnings` and file-change paths to `changed`. * * @param args.enabled - Whether generated MCP entries should be applied (if false, previously-managed names are only removed) * @param args.globalPath - Absolute path to the Windsurf global MCP file to read and/or write * @param args.statePath - Path to the JSON file that records currently managed server names; will be updated when not in `check` mode * @param args.rawGenerated - Raw JSON string produced for Windsurf; parsed when `enabled` and non-empty * @param args.projectRoot - Project root used when writing managed files * @param args.check - If true, perform a dry run (no state update) while still validating and computing the resulting content * @param args.changed - Array that will be appended with paths that were written or would be written * @param args.warnings - Array that will be appended with human-readable warnings encountered during processing */ async function syncManagedWindsurfGlobal(args: { enabled: boolean globalPath: string statePath: string rawGenerated: string projectRoot: string check: boolean changed: string[] warnings: string[] }): Promise { const previousNames = await readManagedGlobalNames(args.statePath) if (!args.enabled && previousNames.length === 0) return const lockPath = path.join(path.dirname(args.globalPath), '.agents-windsurf-mcp.lock') const releaseLock = args.check ? null : await acquireSyncLock(lockPath) try { let existing: Record = {} if (await pathExists(args.globalPath)) { try { existing = normalizeWindsurfMcpPayload(await readWindsurfMcp(args.globalPath) ?? {}) } catch (error) { throw new Error( `Failed to read existing Windsurf MCP at ${args.globalPath}; skipped Windsurf global sync. ${error instanceof Error ? error.message : String(error)}`) } } const generated = args.enabled && args.rawGenerated.trim().length > 0 ? normalizeWindsurfMcpPayload(parseJsonObject(args.rawGenerated, 'generated Windsurf config')) : normalizeWindsurfMcpPayload({}) // The Windsurf config is shared by every project on the machine, so entries carry the // project they came from. Entries written before that rule are recognized by content // rather than by the state file, which a fresh clone does not have. const unscopedServers = recordFrom(generated.mcpServers) const existingServers = recordFrom(existing.mcpServers) const legacy = findLegacyManagedNames(existingServers, unscopedServers) args.warnings.push( ...formatForeignLegacyWarnings(toChangedEntry(args.projectRoot, args.globalPath), legacy.foreign), ) const managedServers = scopeManagedEntries(args.projectRoot, unscopedServers) const takenOver: string[] = [] const nextServers = mergeManagedServers( existingServers, [...previousNames, ...legacy.migrated], managedServers, takenOver, ) args.warnings.push(...formatTakenOverWarnings(toChangedEntry(args.projectRoot, args.globalPath), takenOver)) const nextPayload = normalizeWindsurfMcpPayload({ ...existing, mcpServers: nextServers }) await writeManagedFile({ absolutePath: args.globalPath, content: `${JSON.stringify(nextPayload, null, 2)}\n`, projectRoot: args.projectRoot, check: args.check, changed: args.changed }) if (!args.check) { await writeManagedGlobalNames(args.statePath, args.enabled ? Object.keys(managedServers) : []) } } finally { if (releaseLock) await releaseLock() } } async function readManagedGlobalNames(statePath: string, key: 'managedNames' | 'pendingLegacyNames' = 'managedNames'): Promise { if (!(await pathExists(statePath))) return [] try { const parsed = await readJson(statePath) return Array.isArray(parsed[key]) ? parsed[key].filter((name): name is string => typeof name === 'string') : [] } catch { return [] } } async function writeManagedGlobalNames(statePath: string, managedNames: string[]): Promise { await ensureDir(path.dirname(statePath)) await writeJsonAtomic(statePath, { managedNames: [...new Set(managedNames)].sort((a, b) => a.localeCompare(b)) }) } function mergeManagedServers( existingServers: Record, previousManagedNames: string[], nextManagedServers: Record, takenOver?: string[], ): Record { const next = { ...existingServers } const previous = new Set(previousManagedNames) for (const name of previousManagedNames) { delete next[name] } for (const [name, server] of Object.entries(nextManagedServers)) { // An entry already in the file that this CLI never wrote belongs to the user, and // names like `developer`, `memory` or `github` collide easily. Replacing it silently // makes their own configuration disappear with no way to tell what happened. if (name in next && !previous.has(name)) { takenOver?.push(name) } next[name] = server } return next } /** One warning per entry the sync replaced although it had not written it before. */ function formatTakenOverWarnings(label: string, names: string[]): string[] { return names.map( (name) => `${label}: entry "${name}" was already there and not written by this CLI; it now holds the MCP server of the ` + 'same name from .agents/agents.json. Rename one of them to keep both.', ) } function recordFrom(value: unknown): Record { return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record : {} } /** Return whether a value is a non-array object. */ function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } /** * Write the agents-managed MCP block into a TOML config (Codex, Grok). * * When the integration is disabled the block is removed instead, and a file that held * nothing else is deleted, so turning an integration off actually stops the servers. */ async function materializeTomlConfig(args: { context: HookContext targetPath: string generatedContent: string label: string }): Promise { const { context, targetPath, generatedContent, label } = args const existingText = await readTextOrEmpty(targetPath) if (!context.enabled) { if (existingText.trim().length === 0) return let cleaned: string try { cleaned = removeCodexManagedBlock(existingText) } catch (error) { const message = error instanceof Error ? error.message : String(error) throw new Error(`Failed to clean ${label} config at ${targetPath}; left unchanged. ${message}`) } if (cleaned === existingText) return if (cleaned.trim().length === 0) { context.changed.push(toChangedEntry(context.projectRoot, targetPath)) if (!context.check) await removeIfExists(targetPath) return } await writeManagedFile({ absolutePath: targetPath, content: cleaned, projectRoot: context.projectRoot, check: context.check, changed: context.changed }) return } let content: string try { content = mergeCodexConfig(existingText, generatedContent) } catch (error) { const message = error instanceof Error ? error.message : String(error) throw new Error(`Failed to merge ${label} config at ${targetPath}; skipped ${label} sync. ${message}`) } await writeManagedFile({ absolutePath: targetPath, content, projectRoot: context.projectRoot, check: context.check, changed: context.changed }) } /** * Merge the agents-managed entries into one top-level key of a settings file the tool * also owns (Amp, Zed, Kilo, Droid, Devin). * * Entries a user added by hand stay; entries agents wrote on a previous run and no * longer needs are removed, which is what the state file records. */ async function mergeManagedKey(args: { context: HookContext targetPath: string rawGenerated: string key: string label: string statePath: string jsonc: boolean removeEmptyFile?: boolean previousGenerated?: string sourcePath?: string transform?: (config: Record) => Record }): Promise { const { context, targetPath, rawGenerated, key, label, statePath, jsonc, removeEmptyFile } = args const hasState = await pathExists(statePath) let previousNames = await readManagedGlobalNames(statePath) if (!context.enabled && previousNames.length === 0 && (hasState || !args.previousGenerated)) return let generated: Record = {} if (context.enabled && rawGenerated.trim()) { generated = parseJsonObject(rawGenerated, `generated ${label} config`) } const managed = recordFrom(generated[key]) const existingText = await readTextOrEmpty(args.sourcePath ?? targetPath) let existing: Record = {} if (existingText.trim().length > 0) { if (jsonc) { const errors: { error: number; offset: number; length: number }[] = [] const parsed = parseJsonc(existingText, errors, { allowTrailingComma: true }) as unknown if (errors.length > 0 || (parsed !== undefined && !isRecord(parsed))) { throw new Error(`Existing ${label} config at ${targetPath} is not valid JSONC; skipped ${label} sync.`) } existing = isRecord(parsed) ? parsed : {} } else { try { const parsed = JSON.parse(existingText) as unknown if (!isRecord(parsed)) { throw new Error(`Existing ${label} config at ${targetPath} is not a JSON object; skipped ${label} sync.`) } existing = parsed } catch (error) { // A preview alone does not establish ownership of a disabled tool's file. if (!context.enabled && previousNames.length === 0) return const message = error instanceof Error ? error.message : String(error) throw new Error(`Failed to read existing ${label} config at ${targetPath}; skipped ${label} sync. ${message}`) } } } // Older releases recorded only the preview. Adopt matching entries without // claiming unrelated manual servers when introducing the ownership state. if (!hasState && args.previousGenerated?.trim()) { try { const previous = recordFrom(parseJsonObject(args.previousGenerated, 'previous generated config')[key]) const current = recordFrom(existing[key]) previousNames = Object.keys(previous).filter(name => isDeepStrictEqual(current[name], previous[name])) } catch { // An unreadable preview is not evidence of ownership. } } if (!context.enabled && previousNames.length === 0) return const takenOver: string[] = [] const nextEntries = mergeManagedServers(recordFrom(existing[key]), previousNames, managed, takenOver) context.warnings.push(...formatTakenOverWarnings(label, takenOver)) const otherKeys = Object.keys(existing).filter((item) => item !== key) // A JSONC file can hold comments that never appear in the parsed object, so an // "empty" object is not proof that the file is ours to delete. const safeToRemove = removeEmptyFile && !jsonc && !hasNonWhitespaceOutsideKey(existingText, key) if (safeToRemove && Object.keys(nextEntries).length === 0 && otherKeys.length === 0) { if (await pathExists(targetPath)) { context.changed.push(toChangedEntry(context.projectRoot, targetPath)) if (!context.check) await removeIfExists(targetPath) } if (!context.check) await writeManagedGlobalNames(statePath, []) return } let content: string if (jsonc) { const base = existingText.trim().length > 0 ? existingText : '{}\n' const edits = modify(base, [key], nextEntries, { formattingOptions: { insertSpaces: true, tabSize: 2 } }) const applied = applyEdits(base, edits) content = applied.endsWith('\n') ? applied : `${applied}\n` } else { const merged = { ...existing, [key]: nextEntries } content = `${JSON.stringify(args.transform ? args.transform(merged) : merged, null, 2)}\n` } await writeManagedFile({ absolutePath: targetPath, content, projectRoot: context.projectRoot, check: context.check, changed: context.changed }) if (!context.check) { await writeManagedGlobalNames(statePath, Object.keys(managed)) } } /** * Merge managed servers into opencode.json in the shape that file already uses. * * OpenCode 1.x reads only `mcp.`; OpenCode 2.x reads `mcp.servers` and still * accepts the legacy shape. The V2 shape is written when the file already has * `mcp.servers` or a server sets an option only V2 can express. Previously managed * entries move with the shape, and entries the user wrote stay where they are. */ async function syncOpencodeConfig(args: { context: HookContext targetPath: string sourcePath: string statePath: string }): Promise { const { context, targetPath, sourcePath, statePath } = args const previousPreview = context.previousGeneratedByIntegration?.opencode let ownership: OpencodeOwnership | null try { ownership = await readOpencodeOwnership(statePath) } catch { // Same as the other tools: an unreadable record proves no ownership. ownership = { layout: 'legacy', managedNames: [] } } const hasRecordedNames = (ownership?.managedNames.length ?? 0) > 0 if (!context.enabled && !hasRecordedNames && (ownership || !previousPreview?.trim())) return const existingText = await readTextOrEmpty(sourcePath) let existing: Record = {} if (existingText.trim()) { try { const parsed = JSON.parse(existingText) as unknown if (!isRecord(parsed)) throw new Error('not a JSON object') existing = parsed } catch (error) { if (!context.enabled && !hasRecordedNames) return const message = error instanceof Error ? error.message : String(error) throw new Error(`Failed to read existing OpenCode config at ${sourcePath}; skipped OpenCode sync. ${message}`) } } const mcp = recordFrom(existing.mcp) let owned: OpencodeEntryNames = { legacy: [], servers: [] } if (ownership) { owned = ownedOpencodeEntries(ownership) } else if (previousPreview?.trim()) { try { owned = adoptOpencodeEntries(mcp, parseJsonObject(previousPreview, 'previous OpenCode preview')) } catch { // An unreadable preview is not evidence of ownership. } } if (!context.enabled && owned.legacy.length === 0 && owned.servers.length === 0) return const generated: Record = {} const rawGenerated = context.generatedByIntegration.opencode ?? '' if (context.enabled && rawGenerated.trim()) { const preview = parseJsonObject(rawGenerated, 'generated OpenCode config') for (const [name, entry] of Object.entries(recordFrom(recordFrom(preview.mcp).servers))) { generated[name] = recordFrom(entry) } } const layout: OpencodeLayout = hasOpencodeServersMap(mcp) || Object.values(generated).some(needsOpencodeServersLayout) ? 'servers' : 'legacy' const entries = layout === 'servers' ? generated : toLegacyOpencodeEntries(generated, context.warnings) // A user entry with the same name in the other map is taken over as well: // left in place, it would give OpenCode 2 two definitions of one server. const withoutOwned = removeOpencodeEntries(mcp, owned) const otherLayout: OpencodeLayout = layout === 'servers' ? 'legacy' : 'servers' const inOtherMap = locateOpencodeEntries(withoutOwned, Object.keys(entries))[otherLayout] const cleaned = removeOpencodeEntries(withoutOwned, { legacy: [], servers: [], [otherLayout]: inOtherMap }) const takenOver = [...inOtherMap] let merged: Record if (layout === 'servers') { const hadMap = hasOpencodeServersMap(cleaned) const servers = mergeManagedServers(hadMap ? recordFrom(cleaned.servers) : {}, [], entries, takenOver) merged = hadMap || Object.keys(servers).length > 0 ? { ...cleaned, servers } : cleaned } else { merged = mergeManagedServers(cleaned, [], entries, takenOver) } context.warnings.push(...formatTakenOverWarnings('OpenCode', [...new Set(takenOver)])) const content = `${JSON.stringify(normalizeOpencodeConfig({ ...existing, mcp: merged }), null, 2)}\n` await writeManagedFile({ absolutePath: targetPath, content, projectRoot: context.projectRoot, check: context.check, changed: context.changed }) if (!context.check) { await writeOpencodeOwnership(statePath, { layout, managedNames: Object.keys(entries) }) } } /** Convert preview entries to the legacy shape, warning about settings it cannot hold. */ function toLegacyOpencodeEntries( entries: Record, warnings: string[], ): Record { const out: Record = {} for (const [name, entry] of Object.entries(entries)) { if (isReservedOpencodeName(name)) { warnings.push(`OpenCode server "${name}" was skipped: OpenCode 2 reads mcp.${name} as a setting. Rename the server.`) continue } const legacy = toLegacyOpencodeServer(entry) if (legacy.dropped.length > 0) { warnings.push(`OpenCode server "${name}": the legacy mcp. shape has no ${legacy.dropped.join(', ')}; omitted. Add "servers": {} under "mcp" in opencode.json to use the OpenCode 2 shape.`) } out[name] = legacy.entry } return out } /** Merge managed entries into one key of a plain JSON settings file. */ async function mergeJsonKey(args: { context: HookContext targetPath: string rawGenerated: string key: string label: string statePath: string removeEmptyFile?: boolean previousGenerated?: string sourcePath?: string transform?: (config: Record) => Record }): Promise { await mergeManagedKey({ ...args, jsonc: false }) } /** Merge managed entries into one key of a JSONC file, keeping comments intact. */ async function mergeJsoncKey(args: { context: HookContext targetPath: string rawGenerated: string key: string label: string statePath: string removeEmptyFile?: boolean }): Promise { await mergeManagedKey({ ...args, jsonc: true }) } /** * Goose keeps a single global config file, so agents owns only the extension * entries it created and leaves everything else (providers, models) alone. */ async function syncManagedGooseGlobal(context: HookContext): Promise { // The preview used to be called goose.config.yaml although it holds JSON. Removing the // old name keeps a file that is neither read nor regenerated out of .agents/generated. const legacyGoosePreview = path.join(path.dirname(context.paths.generatedGoose), 'goose.config.yaml') if (!context.check && (await pathExists(legacyGoosePreview))) { await removeIfExists(legacyGoosePreview) } const statePath = context.paths.generatedGooseState const previousNames = await readManagedGlobalNames(statePath) if (!context.enabled && previousNames.length === 0) return const configPath = context.paths.gooseConfig const lockPath = path.join(path.dirname(configPath), '.agents-goose.lock') const releaseLock = context.check ? null : await acquireSyncLock(lockPath) try { let doc try { doc = await readGooseDocument(configPath) } catch (error) { const message = error instanceof Error ? error.message : String(error) throw new Error(`Failed to read existing Goose config at ${configPath}; skipped Goose sync. ${message}`) } const rawGenerated = context.generatedByIntegration.goose ?? '' const generated = context.enabled && rawGenerated.trim().length > 0 ? parseJsonObject(rawGenerated, 'generated Goose config') : {} // Goose repeats the extension name inside the entry, so both sides are scoped to the // project. Without it, two projects with a server called `fetch` overwrite each other. const unscopedExtensions = recordFrom(generated.extensions) const existingExtensions = readGooseExtensions(doc) const legacy = findLegacyManagedNames(existingExtensions, unscopedExtensions) context.warnings.push( ...formatForeignLegacyWarnings(toChangedEntry(context.projectRoot, configPath), legacy.foreign), ) const managedExtensions = scopeManagedEntries( context.projectRoot, unscopedExtensions, (value, scopedName) => (typeof value === 'object' && value !== null ? { ...value, name: scopedName } : value) as typeof value, ) const takenOver: string[] = [] const nextExtensions = mergeManagedServers( existingExtensions, [...previousNames, ...legacy.migrated], managedExtensions, takenOver, ) context.warnings.push(...formatTakenOverWarnings(toChangedEntry(context.projectRoot, configPath), takenOver)) const content = setGooseExtensions(doc, nextExtensions) const previousContent = await readTextOrEmpty(configPath) if (previousContent !== content) { context.changed.push(toChangedEntry(context.projectRoot, configPath)) if (!context.check) { if (content.trim().length === 0) { await removeIfExists(configPath) } else { await writeGooseConfig(configPath, content) } } } if (!context.check) { await writeManagedGlobalNames(statePath, context.enabled ? Object.keys(managedExtensions) : []) } } finally { if (releaseLock) await releaseLock() } } /** * Check whether a JSON document carries anything besides the given top-level key. * * Used before deleting a settings file: the parsed object hides comments, so the raw * text is what decides whether the file was only ever this CLI's to write. */ function hasNonWhitespaceOutsideKey(rawText: string, key: string): boolean { const trimmed = rawText.trim() if (trimmed.length === 0) return false try { const parsed = JSON.parse(trimmed) as unknown if (!isRecord(parsed)) return true const keys = Object.keys(parsed) if (keys.some((item) => item !== key)) return true // Re-serialising only the managed key must reproduce the file, otherwise something // else (a comment, a stray value) is in there. const rebuilt = JSON.stringify({ [key]: parsed[key] }, null, 2) return trimmed !== rebuilt.trim() } catch { return true } }