From 36e5ae804e4bf0c96a0ce6cca90029e88c2da9b3 Mon Sep 17 00:00:00 2001 From: adamdottv <2363879+adamdottv@users.noreply.github.com> Date: Mon, 12 May 2025 14:32:27 -0500 Subject: chore: rename coder -> primary --- README.md | 2 +- cmd/root.go | 6 +- cmd/schema/README.md | 5 +- cmd/schema/main.go | 2 +- internal/app/app.go | 10 +- internal/config/config.go | 22 +-- internal/llm/agent/agent.go | 4 +- internal/llm/agent/tools.go | 2 +- internal/llm/prompt/coder.go | 222 ------------------------------- internal/llm/prompt/primary.go | 222 +++++++++++++++++++++++++++++++ internal/llm/prompt/prompt.go | 6 +- internal/pubsub/broker_test.go | 6 +- internal/tui/components/chat/editor.go | 4 +- internal/tui/components/chat/list.go | 4 +- internal/tui/components/core/status.go | 4 +- internal/tui/components/dialog/models.go | 4 +- internal/tui/page/chat.go | 8 +- internal/tui/tui.go | 10 +- opencode-schema.json | 2 +- 19 files changed, 273 insertions(+), 272 deletions(-) delete mode 100644 internal/llm/prompt/coder.go create mode 100644 internal/llm/prompt/primary.go diff --git a/README.md b/README.md index b3eb37777..5db86c74b 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,7 @@ You can configure OpenCode using environment variables: } }, "agents": { - "coder": { + "primary": { "model": "claude-3.7-sonnet", "maxTokens": 5000 }, diff --git a/cmd/root.go b/cmd/root.go index 1b8c4c574..d18c87854 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -86,7 +86,7 @@ to assist developers in writing, debugging, and understanding code directly from app, err := app.New(ctx, conn) if err != nil { - slog.Error("Failed to create app: %v", err) + slog.Error("Failed to create app", "error", err) return err } @@ -152,11 +152,11 @@ to assist developers in writing, debugging, and understanding code directly from cleanup() if err != nil { - slog.Error("TUI error: %v", err) + slog.Error("TUI error", "error", err) return fmt.Errorf("TUI error: %v", err) } - slog.Info("TUI exited with result: %v", result) + slog.Info("TUI exited", "result", result) return nil }, } diff --git a/cmd/schema/README.md b/cmd/schema/README.md index 93ebe9f03..e448ea0cb 100644 --- a/cmd/schema/README.md +++ b/cmd/schema/README.md @@ -46,7 +46,7 @@ Here's an example configuration that conforms to the schema: } }, "agents": { - "coder": { + "primary": { "model": "claude-3.7-sonnet", "maxTokens": 5000, "reasoningEffort": "medium" @@ -61,4 +61,5 @@ Here's an example configuration that conforms to the schema: } } } -``` \ No newline at end of file +``` + diff --git a/cmd/schema/main.go b/cmd/schema/main.go index 6340cb32f..f5786a7c0 100644 --- a/cmd/schema/main.go +++ b/cmd/schema/main.go @@ -274,7 +274,7 @@ func generateSchema() map[string]any { // Add specific agent properties agentProperties := map[string]any{} knownAgents := []string{ - string(config.AgentCoder), + string(config.AgentPrimary), string(config.AgentTask), string(config.AgentTitle), } diff --git a/internal/app/app.go b/internal/app/app.go index 283b311c8..d4110ac7c 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -29,7 +29,7 @@ type App struct { Permissions permission.Service Status status.Service - CoderAgent agent.Service + PrimaryAgent agent.Service LSPClients map[string]*lsp.Client @@ -88,11 +88,11 @@ func New(ctx context.Context, conn *sql.DB) (*App, error) { // Initialize LSP clients in the background go app.initLSPClients(ctx) - app.CoderAgent, err = agent.NewAgent( - config.AgentCoder, + app.PrimaryAgent, err = agent.NewAgent( + config.AgentPrimary, app.Sessions, app.Messages, - agent.CoderAgentTools( + agent.PrimaryAgentTools( app.Permissions, app.Sessions, app.Messages, @@ -101,7 +101,7 @@ func New(ctx context.Context, conn *sql.DB) (*App, error) { ), ) if err != nil { - slog.Error("Failed to create coder agent", err) + slog.Error("Failed to create primary agent", "error", err) return nil, err } diff --git a/internal/config/config.go b/internal/config/config.go index bb9ec447c..3f80456f6 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -36,9 +36,9 @@ type MCPServer struct { type AgentName string const ( - AgentCoder AgentName = "coder" - AgentTask AgentName = "task" - AgentTitle AgentName = "title" + AgentPrimary AgentName = "primary" + AgentTask AgentName = "task" + AgentTitle AgentName = "title" ) // Agent defines configuration for different LLM models and their token limits. @@ -238,7 +238,7 @@ func setProviderDefaults() { // Anthropic configuration if key := viper.GetString("providers.anthropic.apiKey"); strings.TrimSpace(key) != "" { - viper.SetDefault("agents.coder.model", models.Claude37Sonnet) + viper.SetDefault("agents.primary.model", models.Claude37Sonnet) viper.SetDefault("agents.task.model", models.Claude37Sonnet) viper.SetDefault("agents.title.model", models.Claude37Sonnet) return @@ -246,7 +246,7 @@ func setProviderDefaults() { // OpenAI configuration if key := viper.GetString("providers.openai.apiKey"); strings.TrimSpace(key) != "" { - viper.SetDefault("agents.coder.model", models.GPT41) + viper.SetDefault("agents.primary.model", models.GPT41) viper.SetDefault("agents.task.model", models.GPT41Mini) viper.SetDefault("agents.title.model", models.GPT41Mini) return @@ -254,7 +254,7 @@ func setProviderDefaults() { // Google Gemini configuration if key := viper.GetString("providers.gemini.apiKey"); strings.TrimSpace(key) != "" { - viper.SetDefault("agents.coder.model", models.Gemini25) + viper.SetDefault("agents.primary.model", models.Gemini25) viper.SetDefault("agents.task.model", models.Gemini25Flash) viper.SetDefault("agents.title.model", models.Gemini25Flash) return @@ -262,7 +262,7 @@ func setProviderDefaults() { // Groq configuration if key := viper.GetString("providers.groq.apiKey"); strings.TrimSpace(key) != "" { - viper.SetDefault("agents.coder.model", models.QWENQwq) + viper.SetDefault("agents.primary.model", models.QWENQwq) viper.SetDefault("agents.task.model", models.QWENQwq) viper.SetDefault("agents.title.model", models.QWENQwq) return @@ -270,7 +270,7 @@ func setProviderDefaults() { // OpenRouter configuration if key := viper.GetString("providers.openrouter.apiKey"); strings.TrimSpace(key) != "" { - viper.SetDefault("agents.coder.model", models.OpenRouterClaude37Sonnet) + viper.SetDefault("agents.primary.model", models.OpenRouterClaude37Sonnet) viper.SetDefault("agents.task.model", models.OpenRouterClaude37Sonnet) viper.SetDefault("agents.title.model", models.OpenRouterClaude35Haiku) return @@ -278,7 +278,7 @@ func setProviderDefaults() { // XAI configuration if key := viper.GetString("providers.xai.apiKey"); strings.TrimSpace(key) != "" { - viper.SetDefault("agents.coder.model", models.XAIGrok3Beta) + viper.SetDefault("agents.primary.model", models.XAIGrok3Beta) viper.SetDefault("agents.task.model", models.XAIGrok3Beta) viper.SetDefault("agents.title.model", models.XAiGrok3MiniFastBeta) return @@ -286,7 +286,7 @@ func setProviderDefaults() { // AWS Bedrock configuration if hasAWSCredentials() { - viper.SetDefault("agents.coder.model", models.BedrockClaude37Sonnet) + viper.SetDefault("agents.primary.model", models.BedrockClaude37Sonnet) viper.SetDefault("agents.task.model", models.BedrockClaude37Sonnet) viper.SetDefault("agents.title.model", models.BedrockClaude37Sonnet) return @@ -294,7 +294,7 @@ func setProviderDefaults() { // Azure OpenAI configuration if os.Getenv("AZURE_OPENAI_ENDPOINT") != "" { - viper.SetDefault("agents.coder.model", models.AzureGPT41) + viper.SetDefault("agents.primary.model", models.AzureGPT41) viper.SetDefault("agents.task.model", models.AzureGPT41Mini) viper.SetDefault("agents.title.model", models.AzureGPT41Mini) return diff --git a/internal/llm/agent/agent.go b/internal/llm/agent/agent.go index 415fce3f0..e45411df7 100644 --- a/internal/llm/agent/agent.go +++ b/internal/llm/agent/agent.go @@ -74,7 +74,7 @@ func NewAgent( } var titleProvider provider.Provider // Only generate titles for the coder agent - if agentName == config.AgentCoder { + if agentName == config.AgentPrimary { titleProvider, err = createAgentProvider(config.AgentTitle) if err != nil { return nil, err @@ -673,7 +673,7 @@ func createAgentProvider(agentName config.AgentName) (provider.Provider, error) provider.WithReasoningEffort(agentConfig.ReasoningEffort), ), ) - } else if model.Provider == models.ProviderAnthropic && model.CanReason && agentName == config.AgentCoder { + } else if model.Provider == models.ProviderAnthropic && model.CanReason && agentName == config.AgentPrimary { opts = append( opts, provider.WithAnthropicOptions( diff --git a/internal/llm/agent/tools.go b/internal/llm/agent/tools.go index b337efb59..7a23b723b 100644 --- a/internal/llm/agent/tools.go +++ b/internal/llm/agent/tools.go @@ -11,7 +11,7 @@ import ( "github.com/opencode-ai/opencode/internal/session" ) -func CoderAgentTools( +func PrimaryAgentTools( permissions permission.Service, sessions session.Service, messages message.Service, diff --git a/internal/llm/prompt/coder.go b/internal/llm/prompt/coder.go deleted file mode 100644 index 639679328..000000000 --- a/internal/llm/prompt/coder.go +++ /dev/null @@ -1,222 +0,0 @@ -package prompt - -import ( - "context" - "fmt" - "os" - "path/filepath" - "runtime" - "time" - - "github.com/opencode-ai/opencode/internal/config" - "github.com/opencode-ai/opencode/internal/llm/models" - "github.com/opencode-ai/opencode/internal/llm/tools" -) - -func CoderPrompt(provider models.ModelProvider) string { - basePrompt := baseAnthropicCoderPrompt - switch provider { - case models.ProviderOpenAI: - basePrompt = baseOpenAICoderPrompt - } - envInfo := getEnvironmentInfo() - - return fmt.Sprintf("%s\n\n%s\n%s", basePrompt, envInfo, lspInformation()) -} - -const baseOpenAICoderPrompt = ` -You are operating as and within the OpenCode CLI, a terminal-based agentic coding assistant built by OpenAI. It wraps OpenAI models to enable natural language interaction with a local codebase. You are expected to be precise, safe, and helpful. - -You can: -- Receive user prompts, project context, and files. -- Stream responses and emit function calls (e.g., shell commands, code edits). -- Apply patches, run commands, and manage user approvals based on policy. -- Work inside a sandboxed, git-backed workspace with rollback support. -- Log telemetry so sessions can be replayed or inspected later. -- More details on your functionality are available at "opencode --help" - - -You are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. If you are not sure about file content or codebase structure pertaining to the user's request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer. - -Please resolve the user's task by editing and testing the code files in your current code execution session. You are a deployed coding agent. Your session allows for you to modify and run code. The repo(s) are already cloned in your working directory, and you must fully solve the problem for your answer to be considered correct. - -You MUST adhere to the following criteria when executing the task: -- Working on the repo(s) in the current environment is allowed, even if they are proprietary. -- Analyzing code for vulnerabilities is allowed. -- Showing user code and tool call details is allowed. -- User instructions may overwrite the *CODING GUIDELINES* section in this developer message. -- If completing the user's task requires writing or modifying files: - - Your code and final answer should follow these *CODING GUIDELINES*: - - Fix the problem at the root cause rather than applying surface-level patches, when possible. - - Avoid unneeded complexity in your solution. - - Ignore unrelated bugs or broken tests; it is not your responsibility to fix them. - - Update documentation as necessary. - - Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task. - - Use "git log" and "git blame" to search the history of the codebase if additional context is required; internet access is disabled. - - NEVER add copyright or license headers unless specifically requested. - - You do not need to "git commit" your changes; this will be done automatically for you. - - Once you finish coding, you must - - Check "git status" to sanity check your changes; revert any scratch files or changes. - - Remove all inline comments you added as much as possible, even if they look normal. Check using "git diff". Inline comments must be generally avoided, unless active maintainers of the repo, after long careful study of the code and the issue, will still misinterpret the code without the comments. - - Check if you accidentally add copyright or license headers. If so, remove them. - - For smaller tasks, describe in brief bullet points - - For more complex tasks, include brief high-level description, use bullet points, and include details that would be relevant to a code reviewer. -- If completing the user's task DOES NOT require writing or modifying files (e.g., the user asks a question about the code base): - - Respond in a friendly tune as a remote teammate, who is knowledgeable, capable and eager to help with coding. -- When your task involves writing or modifying files: - - Do NOT tell the user to "save the file" or "copy the code into a file" if you already created or modified the file using "apply_patch". Instead, reference the file as already saved. - - Do NOT show the full contents of large files you have already written, unless the user explicitly asks for them. -- When doing things with paths, always use use the full path, if the working directory is /abc/xyz and you want to edit the file abc.go in the working dir refer to it as /abc/xyz/abc.go. -- If you send a path not including the working dir, the working dir will be prepended to it. -- Remember the user does not see the full output of tools -` - -const baseAnthropicCoderPrompt = `You are OpenCode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user. - -IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. - -# Memory -If the current working directory contains a file called OpenCode.md, it will be automatically added to your context. This file serves multiple purposes: -1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time -2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.) -3. Maintaining useful information about the codebase structure and organization - -When you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to CONTEXT.md. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to CONTEXT.md so you can remember it for next time. - -# Tone and style -You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system). -Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification. -Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session. -If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences. -IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do. -IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to. -IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is .", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity: - -user: 2 + 2 -assistant: 4 - - - -user: what is 2+2? -assistant: 4 - - - -user: is 11 a prime number? -assistant: yes - - - -user: what command should I run to list files in the current directory? -assistant: ls - - - -user: what command should I run to watch files in the current directory? -assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files] -npm run dev - - - -user: How many golf balls fit inside a jetta? -assistant: 150000 - - - -user: what files are in the directory src/? -assistant: [runs ls and sees foo.c, bar.c, baz.c] -user: which file contains the implementation of foo? -assistant: src/foo.c - - - -user: write tests for new feature -assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit/patch file tool to write new tests] - - -# Proactiveness -You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between: -1. Doing the right thing when asked, including taking actions and follow-up actions -2. Not surprising the user with actions you take without asking -For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions. -3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did. - -# Following conventions -When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns. -- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language). -- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions. -- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic. -- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository. - -# Code style -- Do not add comments to the code you write, unless the user asks you to, or the code is complex and requires additional context. - -# Doing tasks -The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended: -1. Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially. -2. Implement the solution using all tools available to you -3. Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach. -4. VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to opencode.md so that you will know to run it next time. - -NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive. - -# Tool usage policy -- When doing file search, prefer to use the Agent tool in order to reduce context usage. -- If you intend to call multiple tools and there are no dependencies between the calls, make all of the independent calls in the same function_calls block. -- IMPORTANT: The user does not see the full output of the tool responses, so if you need the output of the tool for the response make sure to summarize it for the user. - -You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.` - -func getEnvironmentInfo() string { - cwd := config.WorkingDirectory() - isGit := isGitRepo(cwd) - platform := runtime.GOOS - date := time.Now().Format("1/2/2006") - ls := tools.NewLsTool() - r, _ := ls.Run(context.Background(), tools.ToolCall{ - Input: `{"path":"."}`, - }) - return fmt.Sprintf(`Here is useful information about the environment you are running in: - -Working directory: %s -Is directory a git repo: %s -Platform: %s -Today's date: %s - - -%s - - `, cwd, boolToYesNo(isGit), platform, date, r.Content) -} - -func isGitRepo(dir string) bool { - _, err := os.Stat(filepath.Join(dir, ".git")) - return err == nil -} - -func lspInformation() string { - cfg := config.Get() - hasLSP := false - for _, v := range cfg.LSP { - if !v.Disabled { - hasLSP = true - break - } - } - if !hasLSP { - return "" - } - return `# LSP Information -Tools that support it will also include useful diagnostics such as linting and typechecking. -- These diagnostics will be automatically enabled when you run the tool, and will be displayed in the output at the bottom within the and tags. -- Take necessary actions to fix the issues. -- You should ignore diagnostics of files that you did not change or are not related or caused by your changes unless the user explicitly asks you to fix them. -` -} - -func boolToYesNo(b bool) string { - if b { - return "Yes" - } - return "No" -} diff --git a/internal/llm/prompt/primary.go b/internal/llm/prompt/primary.go new file mode 100644 index 000000000..c67e6d7a3 --- /dev/null +++ b/internal/llm/prompt/primary.go @@ -0,0 +1,222 @@ +package prompt + +import ( + "context" + "fmt" + "os" + "path/filepath" + "runtime" + "time" + + "github.com/opencode-ai/opencode/internal/config" + "github.com/opencode-ai/opencode/internal/llm/models" + "github.com/opencode-ai/opencode/internal/llm/tools" +) + +func PrimaryPrompt(provider models.ModelProvider) string { + basePrompt := baseAnthropicPrimaryPrompt + switch provider { + case models.ProviderOpenAI: + basePrompt = baseOpenAIPrimaryPrompt + } + envInfo := getEnvironmentInfo() + + return fmt.Sprintf("%s\n\n%s\n%s", basePrompt, envInfo, lspInformation()) +} + +const baseOpenAIPrimaryPrompt = ` +You are operating as and within the OpenCode CLI, a terminal-based agentic coding assistant built by OpenAI. It wraps OpenAI models to enable natural language interaction with a local codebase. You are expected to be precise, safe, and helpful. + +You can: +- Receive user prompts, project context, and files. +- Stream responses and emit function calls (e.g., shell commands, code edits). +- Apply patches, run commands, and manage user approvals based on policy. +- Work inside a sandboxed, git-backed workspace with rollback support. +- Log telemetry so sessions can be replayed or inspected later. +- More details on your functionality are available at "opencode --help" + + +You are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. If you are not sure about file content or codebase structure pertaining to the user's request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer. + +Please resolve the user's task by editing and testing the code files in your current code execution session. You are a deployed coding agent. Your session allows for you to modify and run code. The repo(s) are already cloned in your working directory, and you must fully solve the problem for your answer to be considered correct. + +You MUST adhere to the following criteria when executing the task: +- Working on the repo(s) in the current environment is allowed, even if they are proprietary. +- Analyzing code for vulnerabilities is allowed. +- Showing user code and tool call details is allowed. +- User instructions may overwrite the *CODING GUIDELINES* section in this developer message. +- If completing the user's task requires writing or modifying files: + - Your code and final answer should follow these *CODING GUIDELINES*: + - Fix the problem at the root cause rather than applying surface-level patches, when possible. + - Avoid unneeded complexity in your solution. + - Ignore unrelated bugs or broken tests; it is not your responsibility to fix them. + - Update documentation as necessary. + - Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task. + - Use "git log" and "git blame" to search the history of the codebase if additional context is required; internet access is disabled. + - NEVER add copyright or license headers unless specifically requested. + - You do not need to "git commit" your changes; this will be done automatically for you. + - Once you finish coding, you must + - Check "git status" to sanity check your changes; revert any scratch files or changes. + - Remove all inline comments you added as much as possible, even if they look normal. Check using "git diff". Inline comments must be generally avoided, unless active maintainers of the repo, after long careful study of the code and the issue, will still misinterpret the code without the comments. + - Check if you accidentally add copyright or license headers. If so, remove them. + - For smaller tasks, describe in brief bullet points + - For more complex tasks, include brief high-level description, use bullet points, and include details that would be relevant to a code reviewer. +- If completing the user's task DOES NOT require writing or modifying files (e.g., the user asks a question about the code base): + - Respond in a friendly tune as a remote teammate, who is knowledgeable, capable and eager to help with coding. +- When your task involves writing or modifying files: + - Do NOT tell the user to "save the file" or "copy the code into a file" if you already created or modified the file using "apply_patch". Instead, reference the file as already saved. + - Do NOT show the full contents of large files you have already written, unless the user explicitly asks for them. +- When doing things with paths, always use use the full path, if the working directory is /abc/xyz and you want to edit the file abc.go in the working dir refer to it as /abc/xyz/abc.go. +- If you send a path not including the working dir, the working dir will be prepended to it. +- Remember the user does not see the full output of tools +` + +const baseAnthropicPrimaryPrompt = `You are OpenCode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user. + +IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. + +# Memory +If the current working directory contains a file called OpenCode.md, it will be automatically added to your context. This file serves multiple purposes: +1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time +2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.) +3. Maintaining useful information about the codebase structure and organization + +When you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to CONTEXT.md. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to CONTEXT.md so you can remember it for next time. + +# Tone and style +You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system). +Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification. +Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session. +If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences. +IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do. +IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to. +IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is .", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity: + +user: 2 + 2 +assistant: 4 + + + +user: what is 2+2? +assistant: 4 + + + +user: is 11 a prime number? +assistant: yes + + + +user: what command should I run to list files in the current directory? +assistant: ls + + + +user: what command should I run to watch files in the current directory? +assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files] +npm run dev + + + +user: How many golf balls fit inside a jetta? +assistant: 150000 + + + +user: what files are in the directory src/? +assistant: [runs ls and sees foo.c, bar.c, baz.c] +user: which file contains the implementation of foo? +assistant: src/foo.c + + + +user: write tests for new feature +assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit/patch file tool to write new tests] + + +# Proactiveness +You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between: +1. Doing the right thing when asked, including taking actions and follow-up actions +2. Not surprising the user with actions you take without asking +For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions. +3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did. + +# Following conventions +When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns. +- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language). +- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions. +- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic. +- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository. + +# Code style +- Do not add comments to the code you write, unless the user asks you to, or the code is complex and requires additional context. + +# Doing tasks +The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended: +1. Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially. +2. Implement the solution using all tools available to you +3. Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach. +4. VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to opencode.md so that you will know to run it next time. + +NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive. + +# Tool usage policy +- When doing file search, prefer to use the Agent tool in order to reduce context usage. +- If you intend to call multiple tools and there are no dependencies between the calls, make all of the independent calls in the same function_calls block. +- IMPORTANT: The user does not see the full output of the tool responses, so if you need the output of the tool for the response make sure to summarize it for the user. + +You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.` + +func getEnvironmentInfo() string { + cwd := config.WorkingDirectory() + isGit := isGitRepo(cwd) + platform := runtime.GOOS + date := time.Now().Format("1/2/2006") + ls := tools.NewLsTool() + r, _ := ls.Run(context.Background(), tools.ToolCall{ + Input: `{"path":"."}`, + }) + return fmt.Sprintf(`Here is useful information about the environment you are running in: + +Working directory: %s +Is directory a git repo: %s +Platform: %s +Today's date: %s + + +%s + + `, cwd, boolToYesNo(isGit), platform, date, r.Content) +} + +func isGitRepo(dir string) bool { + _, err := os.Stat(filepath.Join(dir, ".git")) + return err == nil +} + +func lspInformation() string { + cfg := config.Get() + hasLSP := false + for _, v := range cfg.LSP { + if !v.Disabled { + hasLSP = true + break + } + } + if !hasLSP { + return "" + } + return `# LSP Information +Tools that support it will also include useful diagnostics such as linting and typechecking. +- These diagnostics will be automatically enabled when you run the tool, and will be displayed in the output at the bottom within the and tags. +- Take necessary actions to fix the issues. +- You should ignore diagnostics of files that you did not change or are not related or caused by your changes unless the user explicitly asks you to fix them. +` +} + +func boolToYesNo(b bool) string { + if b { + return "Yes" + } + return "No" +} diff --git a/internal/llm/prompt/prompt.go b/internal/llm/prompt/prompt.go index 769fd51ab..660142320 100644 --- a/internal/llm/prompt/prompt.go +++ b/internal/llm/prompt/prompt.go @@ -15,8 +15,8 @@ import ( func GetAgentPrompt(agentName config.AgentName, provider models.ModelProvider) string { basePrompt := "" switch agentName { - case config.AgentCoder: - basePrompt = CoderPrompt(provider) + case config.AgentPrimary: + basePrompt = PrimaryPrompt(provider) case config.AgentTitle: basePrompt = TitlePrompt(provider) case config.AgentTask: @@ -25,7 +25,7 @@ func GetAgentPrompt(agentName config.AgentName, provider models.ModelProvider) s basePrompt = "You are a helpful assistant" } - if agentName == config.AgentCoder || agentName == config.AgentTask { + if agentName == config.AgentPrimary || agentName == config.AgentTask { // Add context from project-specific instruction files if they exist contextContent := getContextFromPaths() slog.Debug("Context content", "Context", contextContent) diff --git a/internal/pubsub/broker_test.go b/internal/pubsub/broker_test.go index 1a82011fc..b4caa98f3 100644 --- a/internal/pubsub/broker_test.go +++ b/internal/pubsub/broker_test.go @@ -51,12 +51,12 @@ func TestBrokerPublish(t *testing.T) { ch := broker.Subscribe(ctx) // Publish a message - broker.Publish("created", "test message") + broker.Publish(EventTypeCreated, "test message") // Verify message is received select { case event := <-ch: - assert.Equal(t, "created", event.Type) + assert.Equal(t, EventTypeCreated, event.Type) assert.Equal(t, "test message", event.Payload) case <-time.After(100 * time.Millisecond): t.Fatal("timeout waiting for message") @@ -122,7 +122,7 @@ func TestBrokerConcurrency(t *testing.T) { // Publish messages to all subscribers for i := range numSubscribers { - broker.Publish("created", i) + broker.Publish(EventTypeCreated, i) } // Wait for all subscribers to finish diff --git a/internal/tui/components/chat/editor.go b/internal/tui/components/chat/editor.go index 99991cdf7..e96e6df3d 100644 --- a/internal/tui/components/chat/editor.go +++ b/internal/tui/components/chat/editor.go @@ -124,7 +124,7 @@ func (m *editorCmp) Init() tea.Cmd { } func (m *editorCmp) send() tea.Cmd { - if m.app.CoderAgent.IsSessionBusy(m.session.ID) { + if m.app.PrimaryAgent.IsSessionBusy(m.session.ID) { status.Warn("Agent is working, please wait...") return nil } @@ -189,7 +189,7 @@ func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } if key.Matches(msg, editorMaps.OpenEditor) { - if m.app.CoderAgent.IsSessionBusy(m.session.ID) { + if m.app.PrimaryAgent.IsSessionBusy(m.session.ID) { status.Warn("Agent is working, please wait...") return m, nil } diff --git a/internal/tui/components/chat/list.go b/internal/tui/components/chat/list.go index bce6f50e1..bf72e74b5 100644 --- a/internal/tui/components/chat/list.go +++ b/internal/tui/components/chat/list.go @@ -170,7 +170,7 @@ func (m *messagesCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } func (m *messagesCmp) IsAgentWorking() bool { - return m.app.CoderAgent.IsSessionBusy(m.session.ID) + return m.app.PrimaryAgent.IsSessionBusy(m.session.ID) } func formatTimeDifference(unixTime1, unixTime2 int64) string { @@ -376,7 +376,7 @@ func (m *messagesCmp) help() string { text := "" - if m.app.CoderAgent.IsBusy() { + if m.app.PrimaryAgent.IsBusy() { text += lipgloss.JoinHorizontal( lipgloss.Left, baseStyle.Foreground(t.TextMuted()).Bold(true).Render("press "), diff --git a/internal/tui/components/core/status.go b/internal/tui/components/core/status.go index d6612fed4..be2f39432 100644 --- a/internal/tui/components/core/status.go +++ b/internal/tui/components/core/status.go @@ -140,7 +140,7 @@ func formatTokensAndCost(tokens int64, contextWindow int64, cost float64) string func (m statusCmp) View() string { t := theme.CurrentTheme() - modelID := config.Get().Agents[config.AgentCoder].Model + modelID := config.Get().Agents[config.AgentPrimary].Model model := models.SupportedModels[modelID] // Initialize the help widget @@ -283,7 +283,7 @@ func (m statusCmp) model() string { cfg := config.Get() - coder, ok := cfg.Agents[config.AgentCoder] + coder, ok := cfg.Agents[config.AgentPrimary] if !ok { return "Unknown" } diff --git a/internal/tui/components/dialog/models.go b/internal/tui/components/dialog/models.go index 9dc2fdffe..67c4fdfa1 100644 --- a/internal/tui/components/dialog/models.go +++ b/internal/tui/components/dialog/models.go @@ -283,7 +283,7 @@ func (m *modelDialogCmp) setupModels() { func GetSelectedModel(cfg *config.Config) models.Model { - agentCfg := cfg.Agents[config.AgentCoder] + agentCfg := cfg.Agents[config.AgentPrimary] selectedModelId := agentCfg.Model return models.SupportedModels[selectedModelId] } @@ -325,7 +325,7 @@ func findProviderIndex(providers []models.ModelProvider, provider models.ModelPr func (m *modelDialogCmp) setupModelsForProvider(provider models.ModelProvider) { cfg := config.Get() - agentCfg := cfg.Agents[config.AgentCoder] + agentCfg := cfg.Agents[config.AgentPrimary] selectedModelId := agentCfg.Model m.provider = provider diff --git a/internal/tui/page/chat.go b/internal/tui/page/chat.go index b4984c511..fe71d6f7a 100644 --- a/internal/tui/page/chat.go +++ b/internal/tui/page/chat.go @@ -67,7 +67,7 @@ func (p *chatPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } case dialog.CommandRunCustomMsg: // Check if the agent is busy before executing custom commands - if p.app.CoderAgent.IsBusy() { + if p.app.PrimaryAgent.IsBusy() { status.Warn("Agent is busy, please wait before executing a command...") return p, nil } @@ -92,7 +92,7 @@ func (p *chatPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // Run compaction in background go func(sessionID string) { - err := p.app.CoderAgent.CompactSession(context.Background(), sessionID) + err := p.app.PrimaryAgent.CompactSession(context.Background(), sessionID) if err != nil { status.Error(fmt.Sprintf("Compaction failed: %v", err)) } else { @@ -113,7 +113,7 @@ func (p *chatPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if p.session.ID != "" { // Cancel the current session's generation process // This allows users to interrupt long-running operations - p.app.CoderAgent.Cancel(p.session.ID) + p.app.PrimaryAgent.Cancel(p.session.ID) return p, nil } case key.Matches(msg, keyMap.ToggleTools): @@ -158,7 +158,7 @@ func (p *chatPage) sendMessage(text string, attachments []message.Attachment) te cmds = append(cmds, util.CmdHandler(chat.SessionSelectedMsg(newSession))) } - _, err := p.app.CoderAgent.Run(context.Background(), p.session.ID, text, attachments...) + _, err := p.app.PrimaryAgent.Run(context.Background(), p.session.ID, text, attachments...) if err != nil { status.Error(err.Error()) return nil diff --git a/internal/tui/tui.go b/internal/tui/tui.go index 84fbcfdea..a0430faf7 100644 --- a/internal/tui/tui.go +++ b/internal/tui/tui.go @@ -266,7 +266,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case dialog.ModelSelectedMsg: a.showModelDialog = false - model, err := a.app.CoderAgent.Update(config.AgentCoder, msg.Model.ID) + model, err := a.app.PrimaryAgent.Update(config.AgentPrimary, msg.Model.ID) if err != nil { status.Error(err.Error()) return a, nil @@ -460,7 +460,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { a.showHelp = !a.showHelp return a, nil case key.Matches(msg, helpEsc): - if a.app.CoderAgent.IsBusy() { + if a.app.PrimaryAgent.IsBusy() { if a.showQuit { return a, nil } @@ -574,7 +574,7 @@ func (a *appModel) RegisterCommand(cmd dialog.Command) { func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd { // Allow navigating to logs page even when agent is busy - if a.app.CoderAgent.IsBusy() && pageID != page.LogsPage { + if a.app.PrimaryAgent.IsBusy() && pageID != page.LogsPage { // Don't move to other pages if the agent is busy status.Warn("Agent is busy, please wait...") return nil @@ -641,7 +641,7 @@ func (a appModel) View() string { } - if !a.app.CoderAgent.IsBusy() { + if !a.app.PrimaryAgent.IsBusy() { a.status.SetHelpWidgetMsg("ctrl+? help") } else { a.status.SetHelpWidgetMsg("? help") @@ -658,7 +658,7 @@ func (a appModel) View() string { if a.currentPage == page.LogsPage { bindings = append(bindings, logsKeyReturnKey) } - if !a.app.CoderAgent.IsBusy() { + if !a.app.PrimaryAgent.IsBusy() { bindings = append(bindings, helpEsc) } a.help.SetBindings(bindings) diff --git a/opencode-schema.json b/opencode-schema.json index e9665eab5..d6af65cf0 100644 --- a/opencode-schema.json +++ b/opencode-schema.json @@ -179,7 +179,7 @@ }, "description": "Agent configurations", "properties": { - "coder": { + "primary": { "$ref": "#/definitions/agent" }, "task": { -- cgit v1.2.3