From 433c2da50d511269f14e136384b62341f27bd893 Mon Sep 17 00:00:00 2001 From: Chris Scott Date: Fri, 12 Dec 2025 23:38:14 -0500 Subject: [PATCH] Add global AGENTS.md editor and expose dev server ports 5100-5103 --- Dockerfile | 2 +- README.md | 43 ++++++ backend/src/index.ts | 45 +++++- backend/src/routes/settings.ts | 48 ++++++- docker-compose.yml | 4 + frontend/src/api/settings.ts | 15 ++ .../components/settings/AgentsMdEditor.tsx | 133 ++++++++++++++++++ .../settings/OpenCodeConfigManager.tsx | 32 ++++- shared/src/config/env.ts | 1 + 9 files changed, 317 insertions(+), 6 deletions(-) create mode 100644 frontend/src/components/settings/AgentsMdEditor.tsx diff --git a/Dockerfile b/Dockerfile index 658692ea..8d03c859 100644 --- a/Dockerfile +++ b/Dockerfile @@ -76,7 +76,7 @@ RUN chmod +x /docker-entrypoint.sh RUN mkdir -p /workspace /app/data && \ chown -R node:node /workspace /app/data -EXPOSE 5003 +EXPOSE 5003 5100 5101 5102 5103 HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \ CMD curl -f http://localhost:5003/api/health || exit 1 diff --git a/README.md b/README.md index 033ee5da..a200f96e 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,49 @@ docker-compose restart docker exec -it opencode-manager sh ``` +### Dev Server Ports + +The Docker container exposes ports `5100-5103` for running dev servers inside your repositories. Configure your project's dev server to use one of these ports and access it directly from your browser. + +**Example usage:** +```bash +# Vite (vite.config.ts) +server: { port: 5100, host: '0.0.0.0' } + +# Next.js +next dev -p 5100 -H 0.0.0.0 + +# Express/Node +app.listen(5100, '0.0.0.0') +``` + +Access your dev server at `http://localhost:5100` (or your Docker host IP). + +To customize the exposed ports, edit `docker-compose.yml`: +```yaml +ports: + - "5003:5003" # OpenCode Manager + - "5100:5100" # Dev server 1 + - "5101:5101" # Dev server 2 + - "5102:5102" # Dev server 3 + - "5103:5103" # Dev server 4 +``` + +### Global Agent Instructions (AGENTS.md) + +OpenCode Manager creates a default `AGENTS.md` file in the workspace config directory (`/workspace/.config/opencode/AGENTS.md`). This file provides global instructions to AI agents working within the container. + +**Default instructions include:** +- Reserved ports (5003 for OpenCode Manager, 5551 for OpenCode server) +- Available dev server ports (5100-5103) +- Guidelines for binding to `0.0.0.0` for Docker accessibility + +**Editing AGENTS.md:** +- Via UI: Settings > OpenCode > Global Agent Instructions +- Via file: Edit `/workspace/.config/opencode/AGENTS.md` directly + +This file is merged with any repository-specific `AGENTS.md` files, with repository instructions taking precedence for their respective codebases. + ### Option 2: Local Development ```bash diff --git a/backend/src/index.ts b/backend/src/index.ts index 98610b24..68ce7cee 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -10,7 +10,7 @@ import { createTTSRoutes, cleanupExpiredCache } from './routes/tts' import { createFileRoutes } from './routes/files' import { createProvidersRoutes } from './routes/providers' import { createOAuthRoutes } from './routes/oauth' -import { ensureDirectoryExists, writeFileContent } from './services/file-operations' +import { ensureDirectoryExists, writeFileContent, fileExists } from './services/file-operations' import { SettingsService } from './services/settings' import { opencodeServerManager } from './services/opencode-single-server' import { cleanupOrphanedDirectories } from './services/repo' @@ -21,6 +21,7 @@ import { getReposPath, getConfigPath, getOpenCodeConfigFilePath, + getAgentsMdPath, getDatabasePath, ENV } from '@opencode-manager/shared' @@ -38,6 +39,37 @@ app.use('/*', cors({ const db = initializeDatabase(DB_PATH) +export const DEFAULT_AGENTS_MD = `# OpenCode Manager - Global Agent Instructions + +## Critical System Constraints + +- **DO NOT** use ports 5003 or 5551 - these are reserved for OpenCode Manager +- **DO NOT** kill or stop processes on ports 5003 or 5551 +- **DO NOT** modify files in the \`.config/opencode\` directory unless explicitly requested + +## Dev Server Ports + +When starting dev servers, use the pre-allocated ports 5100-5103: +- Port 5100: Primary dev server (frontend) +- Port 5101: Secondary dev server (API/backend) +- Port 5102: Additional service +- Port 5103: Additional service + +Always bind to \`0.0.0.0\` to allow external access from the Docker host. + +## Package Management + +Prefer **pnpm** or **bun** over npm for installing dependencies to save disk space: +- Use \`pnpm install\` instead of \`npm install\` +- Use \`bun install\` as an alternative +- Both are pre-installed in the container + +## General Guidelines + +- This file is merged with any AGENTS.md files in individual repositories +- Repository-specific instructions take precedence for their respective codebases +` + const DEFAULT_OPENCODE_CONFIG = { $schema: 'https://opencode.ai/config.json', theme: 'opencode', @@ -122,6 +154,16 @@ async function syncDefaultConfigToDisk(): Promise { } } +async function ensureDefaultAgentsMdExists(): Promise { + const agentsMdPath = getAgentsMdPath() + const exists = await fileExists(agentsMdPath) + + if (!exists) { + await writeFileContent(agentsMdPath, DEFAULT_AGENTS_MD) + logger.info(`Created default AGENTS.md at: ${agentsMdPath}`) + } +} + try { await ensureDirectoryExists(getWorkspacePath()) await ensureDirectoryExists(getReposPath()) @@ -135,6 +177,7 @@ try { await ensureDefaultConfigExists() await syncDefaultConfigToDisk() + await ensureDefaultAgentsMdExists() opencodeServerManager.setDatabase(db) await opencodeServerManager.start() diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index bf77f5c3..d759c0ea 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -2,15 +2,16 @@ import { Hono } from 'hono' import { z } from 'zod' import type { Database } from 'bun:sqlite' import { SettingsService } from '../services/settings' -import { writeFileContent } from '../services/file-operations' +import { writeFileContent, readFileContent, fileExists } from '../services/file-operations' import { patchOpenCodeConfig } from '../services/proxy' -import { getOpenCodeConfigFilePath } from '@opencode-manager/shared' +import { getOpenCodeConfigFilePath, getAgentsMdPath } from '@opencode-manager/shared' import { UserPreferencesSchema, OpenCodeConfigSchema, } from '../types/settings' import { logger } from '../utils/logger' import { opencodeServerManager } from '../services/opencode-single-server' +import { DEFAULT_AGENTS_MD } from '../index' const UpdateSettingsSchema = z.object({ preferences: UserPreferencesSchema.partial(), @@ -326,5 +327,48 @@ export function createSettingsRoutes(db: Database) { } }) + app.get('/agents-md', async (c) => { + try { + const agentsMdPath = getAgentsMdPath() + const exists = await fileExists(agentsMdPath) + + if (!exists) { + return c.json({ content: '' }) + } + + const content = await readFileContent(agentsMdPath) + return c.json({ content }) + } catch (error) { + logger.error('Failed to get AGENTS.md:', error) + return c.json({ error: 'Failed to get AGENTS.md' }, 500) + } + }) + + app.get('/agents-md/default', async (c) => { + return c.json({ content: DEFAULT_AGENTS_MD }) + }) + + app.put('/agents-md', async (c) => { + try { + const body = await c.req.json() + const { content } = z.object({ content: z.string() }).parse(body) + + const agentsMdPath = getAgentsMdPath() + await writeFileContent(agentsMdPath, content) + logger.info(`Updated AGENTS.md at: ${agentsMdPath}`) + + await opencodeServerManager.restart() + logger.info('Restarted OpenCode server after AGENTS.md update') + + return c.json({ success: true }) + } catch (error) { + logger.error('Failed to update AGENTS.md:', error) + if (error instanceof z.ZodError) { + return c.json({ error: 'Invalid request data', details: error.issues }, 400) + } + return c.json({ error: 'Failed to update AGENTS.md' }, 500) + } + }) + return app } diff --git a/docker-compose.yml b/docker-compose.yml index 58ae52fe..2657ec35 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -6,6 +6,10 @@ services: container_name: opencode-manager ports: - "5003:5003" + - "5100:5100" + - "5101:5101" + - "5102:5102" + - "5103:5103" environment: - NODE_ENV=production - HOST=0.0.0.0 diff --git a/frontend/src/api/settings.ts b/frontend/src/api/settings.ts index 3a7698b7..01c164fe 100644 --- a/frontend/src/api/settings.ts +++ b/frontend/src/api/settings.ts @@ -102,4 +102,19 @@ export const settingsApi = { const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-restart`) return data }, + + getAgentsMd: async (): Promise<{ content: string }> => { + const { data } = await axios.get(`${API_BASE_URL}/api/settings/agents-md`) + return data + }, + + getDefaultAgentsMd: async (): Promise<{ content: string }> => { + const { data } = await axios.get(`${API_BASE_URL}/api/settings/agents-md/default`) + return data + }, + + updateAgentsMd: async (content: string): Promise<{ success: boolean }> => { + const { data } = await axios.put(`${API_BASE_URL}/api/settings/agents-md`, { content }) + return data + }, } diff --git a/frontend/src/components/settings/AgentsMdEditor.tsx b/frontend/src/components/settings/AgentsMdEditor.tsx new file mode 100644 index 00000000..fd2af439 --- /dev/null +++ b/frontend/src/components/settings/AgentsMdEditor.tsx @@ -0,0 +1,133 @@ +import { useState, useEffect } from 'react' +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { Loader2, Save, RotateCcw } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Textarea } from '@/components/ui/textarea' +import { settingsApi } from '@/api/settings' +import { showToast } from '@/lib/toast' + +export function AgentsMdEditor() { + const queryClient = useQueryClient() + const [content, setContent] = useState('') + const [hasChanges, setHasChanges] = useState(false) + + const { data, isLoading, error } = useQuery({ + queryKey: ['agents-md'], + queryFn: () => settingsApi.getAgentsMd(), + }) + + useEffect(() => { + if (data?.content !== undefined) { + setContent(data.content) + setHasChanges(false) + } + }, [data?.content]) + + const updateMutation = useMutation({ + mutationFn: (newContent: string) => settingsApi.updateAgentsMd(newContent), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['agents-md'] }) + setHasChanges(false) + showToast.success('AGENTS.md saved successfully') + }, + onError: () => { + showToast.error('Failed to save AGENTS.md') + }, + }) + + const resetToDefaultMutation = useMutation({ + mutationFn: async () => { + const { content: defaultContent } = await settingsApi.getDefaultAgentsMd() + await settingsApi.updateAgentsMd(defaultContent) + return defaultContent + }, + onSuccess: (defaultContent) => { + queryClient.invalidateQueries({ queryKey: ['agents-md'] }) + setContent(defaultContent) + setHasChanges(false) + showToast.success('AGENTS.md reset to default') + }, + onError: () => { + showToast.error('Failed to reset AGENTS.md') + }, + }) + + const handleContentChange = (value: string) => { + setContent(value) + setHasChanges(value !== data?.content) + } + + const handleSave = () => { + updateMutation.mutate(content) + } + + const handleResetToDefault = () => { + resetToDefaultMutation.mutate() + } + + if (isLoading) { + return ( +
+ +
+ ) + } + + if (error) { + return ( +
+ Failed to load AGENTS.md +
+ ) + } + + return ( +
+
+
+

+ Global instructions for AI agents. This file is merged with repository-specific AGENTS.md files. +

+
+
+ + +
+
+ +