### Parallel Tool Execution Prompt Example Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/LEARNING_FROM_OPEN_SOURCE.md Provides an example of a system prompt guiding an agent to execute multiple read/search tools in parallel for improved performance. It emphasizes that read operations can be parallelized, while write operations require sequential execution or locking to avoid conflicts. Validation steps should also run serially after modifications. This strategy can achieve significant speedups. ```text When gathering context information, call multiple read/search tools in parallel: - Example: readFile(A) + searchText(B) + listFiles(C) simultaneously - Only use sequential execution when later tools depend on earlier results - Parallel execution can achieve 3-5x speedup ``` -------------------------------- ### Same.dev Linter Loop Example Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/sources/notes-system-prompts.md This example illustrates a typical linting loop in Same.dev. It involves editing files, running the linter, fixing reported errors, and re-running the linter until no errors are found. It includes a failsafe to stop after multiple attempts. ```text 1. edit_file (or string_replace) 2. run_linter → finds 3 errors 3. Fix errors (clear plan) 4. run_linter → still 1 error 5. Fix again 6. run_linter → no errors → continue (If still failing after 3rd attempt → stop and ask user) ``` -------------------------------- ### API Examples: List Java Files, Read File, Search Pattern Source: https://github.com/cuipengfei/simple-coder/blob/main/CLAUDE.md Demonstrates how to interact with the Simple Coder API to perform common file operations. These examples use cURL to send POST requests with JSON payloads to the agent endpoint. ```bash # List Java files curl -X POST http://localhost:8080/api/agent \ -H "Content-Type: application/json" \ -d '{"prompt":"list all java files","toolType":"auto","contextHistory":[]}' ``` ```bash # Read file segment curl -X POST http://localhost:8080/api/agent \ -H "Content-Type: application/json" \ -d '{"prompt":"Read src/main/java/com/simplecoder/service/AgentService.java lines 1-40","toolType":"auto","contextHistory":[]}' ``` ```bash # Search pattern curl -X POST http://localhost:8080/api/agent \ -H "Content-Type: application/json" \ -d '{"prompt":"search for AgentService in src/main/java","toolType":"auto","contextHistory":[]}' ``` -------------------------------- ### Spring Boot: Running the Application Source: https://github.com/cuipengfei/simple-coder/blob/main/slides.html This command demonstrates how to run the Simple Coder project using Maven. Executing this command will start the Spring Boot application, making it accessible via a browser. ```bash mvn spring-boot:run ``` -------------------------------- ### Portable Shell Command Example Source: https://github.com/cuipengfei/simple-coder/blob/main/AGENTS.md Provides an example of a minimally portable shell command for finding Java files and limiting the output. This adheres to the policy of preferring `bash`/POSIX equivalents over PowerShell cmdlets. ```bash find . -name '*.java' | head -20 ``` -------------------------------- ### Application Configuration Example Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/IMPLEMENTATION.md Illustrates the configuration properties for the simple-coder application, including repository root, timeouts for shell commands, and AI service settings. This YAML excerpt defines essential parameters for the project's operation. ```yaml simple-coder: repo-root: ${user.dir} max-file-lines: 500 max-search-results: 50 max-list-results: 200 agent: max-steps: 10 bash: timeout: 60 powershell: timeout: 60 spring: ai: openai: api-key: dummy-local base-url: http://localhost:4141 chat: options: model: gpt-4.1 server: port: 8080 logging: level: org.springframework.ai: DEBUG com.simplecoder.config.SimpleLoggerAdvisor: INFO ``` -------------------------------- ### Project Dependencies Example Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/IMPLEMENTATION.md Lists the core dependencies required for the simple-coder project, including web starter, OpenAI AI starter, Lombok for boilerplate code reduction, and testing utilities. Dependency versions for spring-ai are managed by the spring-ai-bom. ```xml org.springframework.boot spring-boot-starter-web org.springframework.ai spring-ai-starter-model-openai org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test ``` -------------------------------- ### Example API Request to Simple Coder Source: https://github.com/cuipengfei/simple-coder/blob/main/slides.html This is an example of a JSON payload that can be sent to the Simple Coder API's `/api/agent` endpoint. It includes a user prompt and an empty `contextHistory`, suitable for initiating a new conversation. ```json { "prompt": "列出所有 Java 文件", "contextHistory": [] } ``` -------------------------------- ### Amp Build Fix Workflow Example Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/sources/notes-system-prompts.md This workflow demonstrates a sequence of steps for running a build process and fixing type errors. It involves running the build, identifying errors, marking tasks, fixing errors iteratively, and finally running diagnostics and rebuilding. ```text User: "Run the build and fix any type errors" 1. todo_write: ["Run the build", "Fix any type errors"] 2. npm run build → reports 10 type errors 3. todo_write: ["Fix error 1", "Fix error 2", ..., "Fix error 10"] 4. Mark each in_progress 5. Fix error 1 → mark completed 6. Fix error 2 → mark completed ... 7. After all fixed: run get_diagnostics + rebuild ``` -------------------------------- ### YAML Configuration for Agent Environment and Model Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/syntheses/architecture-patterns.md Provides an example of YAML configuration for defining an agent's environment and model. This configuration is used for protocol implementation and allows for runtime specification of components like DockerEnvironment and AnthropicModel. ```yaml environment: class: "DockerEnvironment" image: "sweagent/swe-bench:latest" model: class: "AnthropicModel" name: "claude-3-5-sonnet-20241022" ``` -------------------------------- ### JSON for Qoder Search Replace Tool Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/syntheses/code-modification.md Example JSON configuration for Qoder's 'search_replace' tool, demonstrating how to specify file paths and multiple replacement rules, including an option to replace all occurrences. ```json { "file_path": "design.md", "replacements": [ { "original_text": "## Old Section Title", "new_text": "## New Section Title" }, { "original_text": "- Feature A\n- Feature B", "new_text": "- Feature A (enhanced)\n- Feature B\n- Feature C (new)", "replace_all": false } ] } ``` -------------------------------- ### Task Management System Example (Amp's TODO) Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/LEARNING_FROM_OPEN_SOURCE.md Demonstrates a task management system, exemplified by Amp's TODO list, using YAML format. It outlines key principles such as immediately marking tasks as completed, decomposing errors into subtasks, and displaying progress in a UI for transparency. This system helps agents stay organized and provides users with visibility into the agent's reasoning and progress. ```yaml todo_write([ {id: 1, content: "Run the build", status: "in_progress"}, {id: 2, content: "Fix error 1", status: "todo"}, {id: 3, content: "Fix error 2", status: "todo"} ]) # Key principles - Mark task as completed IMMEDIATELY after finishing, not batched - When errors occur, decompose into specific subtasks - Display progress in UI so user sees what agent is doing ``` -------------------------------- ### Agent Communication Strategy Example Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/LEARNING_FROM_OPEN_SOURCE.md Illustrates the communication strategy for development agents, emphasizing conciseness and avoiding direct code output. Instead of naming tools, agents should describe their actions naturally. This improves user experience and maintains a clear separation between the agent's actions and the underlying tools. ```plaintext ❌ Bad: "I will use the edit_file tool to modify the code" ✅ Good: "I'll update the configuration to fix the issue" ``` -------------------------------- ### Simple Coder Java: Agent Execution Example Source: https://github.com/cuipengfei/simple-coder/blob/main/slides.html This Java snippet illustrates how Simple Coder might execute a tool call response. It shows a method that takes a tool name and arguments, then proceeds to execute the corresponding tool, returning a success response. ```java // Assuming AgentService.java handles tool execution public ToolResponse executeTool(String toolName, Map arguments) { // Logic to map toolName to a method in ToolsService and execute it if ("listFiles".equals(toolName)) { String path = arguments.get("path"); List files = toolsService.listFiles(path); return ToolResponse.success("Files found:", files.toString()); } // ... other tool implementations return ToolResponse.error("Unknown tool: " + toolName); } ``` -------------------------------- ### API Request and Response Examples Source: https://github.com/cuipengfei/simple-coder/blob/main/AGENTS.md Demonstrates a typical JSON API request to execute a command within the agent, and a successful JSON response indicating tool execution results, including potential truncation of output. This serves as a reference for interacting with the agent's execution API. ```json POST /api/agent { "prompt": "Read src/main/java/com/simplecoder/service/AgentService.java lines 1-40", "toolType": "auto", "contextHistory": [] } ``` ```json { "success": true, "message": "Tool execution result", "data": "Read ... (lines 1-40 of X total)\n\n", "error": null } ``` -------------------------------- ### Code Modification Placeholder Convention Example Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/LEARNING_FROM_OPEN_SOURCE.md This demonstrates a convention for marking modified code sections using placeholders. It helps to avoid returning the entire file, saving tokens, and clearly indicates which parts of the code have been changed, facilitating user review. ```javascript // ... keep existing code ... // unchanged code const result = newValue; // only this line changed // ... rest of code ... // subsequent code ``` -------------------------------- ### Bash Shell Execution Policy Example Source: https://github.com/cuipengfei/simple-coder/blob/main/AGENTS.md Illustrates the recommended way to execute shell commands that require shell features like pipes or environment variables. It specifies using `bash -lc` for multi-command invocations to ensure portability and avoid PowerShell-specific syntax. ```bash command:["bash","-lc",""] ``` -------------------------------- ### Apply Patch Virtual Command Example Source: https://github.com/cuipengfei/simple-coder/blob/main/AGENTS.md Demonstrates the mandatory use of the `apply_patch` virtual command for all repository file operations, including creation, modification, rename, or deletion. This ensures atomic and reviewable changes, prohibiting direct mutation via shell redirection or in-place editors. ```bash command:["apply_patch","*** Begin Patch\n...\n*** End Patch\n"] ``` -------------------------------- ### Execute Agent Request - Multi-step Task with History (Bash) Source: https://context7.com/cuipengfei/simple-coder/llms.txt Executes a multi-step agent request that utilizes context history. This example asks about available tools in 'ToolsService' after a previous request to list Java files. The agent uses the history to provide a detailed response about the identified tools. ```bash curl -X POST http://localhost:8080/api/agent \ -H "Content-Type: application/json" \ -d '{ \ "prompt": "What tools are available in ToolsService?", \ "toolType": "auto", \ "contextHistory": [ \ { \ "timestamp": "2025-10-29T10:00:00", \ "prompt": "list all java files", \ "result": "Found 14 Java files in the project" \ } \ ] \ }' ``` -------------------------------- ### Preserve Indentation with Python Example Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/syntheses/code-modification.md This Python example demonstrates how to correctly capture and use 'old_string' for code modification, emphasizing the preservation of exact indentation. Incorrect indentation can lead to failures, especially when 'old_string' is not unique and 'replace_all' is not used. It's crucial to maintain the indentation level present in the original code. ```python # Read tool output 1→def example(): 2→ result = old_value # note: 2 spaces indentation 3→ return result # old_string (correct) - preserves exact indentation old_string = " result = old_value" # 4 spaces (after line number) # old_string (incorrect) - indentation mismatch old_string = " result = old_value" # 2 spaces ``` -------------------------------- ### Python Function for Data Processing Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/syntheses/code-modification.md A Python function that processes data by first validating and transforming it, then saving the result. This serves as an example of the 'lov-line-replace' operation's output. ```python def process_data(data): # Data processing steps validate_and_transform(data) save(data) return data ``` -------------------------------- ### Python Example: String Replace Functionality Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/syntheses/code-modification.md Demonstrates a Python function for replacing all occurrences of a substring within a larger string. This is a fundamental operation used in various code modification strategies. ```python def string_replace(content: str, old_str: str, new_str: str) -> str: """Replaces all occurrences of old_str with new_str in the content.""" return content.replace(old_str, new_str) ``` -------------------------------- ### JavaScript Function with Placeholder Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/syntheses/code-modification.md A JavaScript function example demonstrating the use of placeholders for keeping existing code while inserting new functionality. This is a common convention across various code editing tools. ```javascript function example() { // ... keep existing code newCode(); // ... keep existing code } ``` -------------------------------- ### Bash Example: Sed for In-Place Replacement Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/syntheses/code-modification.md Shows how to use the `sed` command in Bash for in-place replacement of text within a file. This is often used when validation needs are lower or for quick, non-unique replacements. ```bash # Replace all occurrences of 'old_text' with 'new_text' in 'file.txt' sed -i 's/old_text/new_text/g' file.txt ``` -------------------------------- ### Common Maven Commands for Compilation, Testing, and Running Source: https://github.com/cuipengfei/simple-coder/blob/main/CLAUDE.md Provides a list of essential Maven commands for managing the project build lifecycle. These include compiling code, running tests (individually or in groups), and executing the Spring Boot application. ```bash mvn clean compile # Compile ``` ```bash mvn test # Run all tests ``` ```bash mvn test -Dtest=ToolRequestTest # Single test class ``` ```bash mvn test -Dtest="ToolRequestTest,ToolResponseTest" # Multiple test classes ``` ```bash mvn spring-boot:run # Run app (port 8080) ``` ```bash mvn clean package # Build jar ``` -------------------------------- ### Jinja2 Template System for Output Truncation Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/LEARNING_FROM_OPEN_SOURCE.md Demonstrates the use of Jinja2 templates for dynamic prompt generation and output truncation. This system allows for conditional formatting of output based on its length, ensuring that long outputs are presented in a truncated manner with clear indicators of elided content, useful for managing LLM responses. ```jinja2 {% if output|length < max_output_length %} {{ output }} {% else %} {{ output[:max_output_length//2] }} {{ output|length - max_output_length }} {{ output[-max_output_length//2:] }} {% endif %} ``` -------------------------------- ### Spring Boot: Running Tests Source: https://github.com/cuipengfei/simple-coder/blob/main/slides.html This command shows how to execute the project's tests using Maven. Running tests is crucial for verifying the functionality and stability of the Simple Coder application. ```bash mvn test ``` -------------------------------- ### Tool Invocation via cURL (Bash) Source: https://context7.com/cuipengfei/simple-coder/llms.txt Example of how to invoke the replaceText tool using a cURL command. This demonstrates sending a JSON payload with the prompt, tool type, and context history to an agent endpoint. ```bash # Safe replacement example curl -X POST http://localhost:8080/api/agent \ -H "Content-Type: application/json" \ -d '{ "prompt": "change max-file-lines from 500 to 1000 in application.yml", "toolType": "auto", "contextHistory": [] }' # Agent calls: replaceText("src/main/resources/application.yml", "max-file-lines: 500", "max-file-lines: 1000") ``` -------------------------------- ### DefaultAgent run() Method Implementation Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/sources/notes-mini-swe-agent.md Implements the main execution loop for the DefaultAgent. It initializes the message history with system and user prompts, then repeatedly calls the step() method to process tasks. Handles non-terminating and terminating exceptions, returning the final status and message upon termination. ```python def run(self) -> tuple[str, str]: # 1. initialize message history self.messages = [ {"role": "system", "content": self.render_template(system_template)}, {"role": "user", "content": self.render_template(instance_template)} ] # 2. main loop while True: try: self.step() # execute single step except NonTerminatingException as e: # append error to history, continue self.add_message("user", str(e)) except TerminatingException as e: # return exit status and message return (type(e).__name__, str(e))) ``` -------------------------------- ### Python Function with Placeholder (Recommended) Source: https://github.com/cuipengfei/simple-coder/blob/main/docs/syntheses/code-modification.md An example of a recommended placeholder usage in Python for editing large files. It uses '// ... existing code ...' to denote unchanged sections, improving readability and reducing token consumption. ```python # Large file edit (300 lines) def complex_function(): # ... existing code ... # Only this section changed new_logic = optimized_approach() # ... existing code ... ``` -------------------------------- ### Execute Agent Request - Error Handling (Bash) Source: https://context7.com/cuipengfei/simple-coder/llms.txt Demonstrates error handling for an agent request. This example attempts to replace text in a non-existent file. The response shows 'success: false' along with an error message indicating the file was not found. ```bash curl -X POST http://localhost:8080/api/agent \ -H "Content-Type: application/json" \ -d '{ \ "prompt": "replace \"foo\" with \"bar\" in nonexistent.txt", \ "toolType": "auto", \ "contextHistory": [] \ }' ``` -------------------------------- ### HTML Frontend - Single Page Application Source: https://github.com/cuipengfei/simple-coder/blob/main/README.md 前端代码实现了一个单页应用(SPA),提供用户输入、执行按钮、结果展示区以及交互记录功能。它使用原生 HTML、Fetch API 和 TailwindCDN 来构建用户界面,并处理加载和错误状态提示。 ```html Simple Coder

Simple Coder

Interact with the AI Coder Agent

Results:

Results will appear here...

Interaction History (Last 20):

History will be logged here...