coding-agent-patterns
Core patterns for AI coding agents based on analysis of Claude Code, Codex, Cline, Aider, OpenCode. Triggers when: Building an AI coding agent or assistant, implementing tool-calling loops, managing context windows for LLMs, setting up agent memory or skill systems, or designing multi-provider LLM abstraction. Commands: - /agent-patterns - View coding agent patterns and architecture (informational skill) Capabilities: Core agent loop with while(true) and tool execution, context management with pruning and compression and repo maps, tool safety with sandboxing and approval flows and doom loop detection, multi-provider abstraction with unified API for different LLMs, memory systems with project rules and auto-memory and skill loading, session persistence with SQLite vs JSONL patterns
What this skill does
## Safety Rules
**Critical**: Read and follow [global-rules/bash-safety.md](file:///Users/fred/.config/opencode/skills/global-rules/rules/bash-safety.md) for all bash/command execution.
Core rules:
1. **Always set explicit `timeout` on bash calls** — 30s for tests, 60s for installs, never default
2. **Never run unscoped full test suites** — use `-k` or file paths to limit scope
3. **Never use `rm -rf` without variable guards**, `curl|bash`, `sudo`, or `kill -9`
4. **Infinite loops must have hard timeout + budget limits** — no unbounded while(True)
5. **Redirect stdin** with `< /dev/null` for non-interactive commands
A bash timeout that triggers SIGKILL corrupts the terminal FD, crashes opencode's TUI, and forces a GUI restart.
## Quick Commands
| Command | Description |
|---------|-------------|
| `/agent-patterns` | View coding agent patterns (core loop, context management, tool safety, multi-provider, memory systems) |
# Coding Agent Development Patterns
Core patterns distilled from Claude Code (70k stars), Codex (62k), Cline (58k), Aider (41k), and OpenCode (114k).
## The Core Loop: while(true)
All AI coding agents share the same fundamental loop. The loop follows the pattern: ask LLM if it needs tools, use them, feed results back, and repeat until done. The implementation builds context with tools and conversation history, calls the LLM with messages and tool definitions, checks for tool calls and returns content if none, executes tools and appends results to history, then loops back with tool results.
Core Tools: All agents have six fundamental tools. The `read` tool reads file contents. The `write` tool creates or overwrites files. The `edit` tool performs precise string replacement in files. The `bash` tool executes shell commands. The `glob` tool finds files by pattern. The `grep` tool searches file contents. A minimal viable agent requires approximately 1000-2000 lines with these six tools plus the loop.
## Challenge 1: Context Window Management
The biggest engineering challenge. A real project has thousands of files, but LLMs have limited context (128K - 2M tokens).
Strategies: Different agents use different strategies. Aider uses Repo Map with tree-sitter scanning that only passes signatures and loads details on demand. Claude Code uses Auto-compaction where the LLM summarizes history when context fills. OpenCode uses a two-level approach that prunes old tool results (keeping 40K recent) and then compresses.
### Compression Pattern
```python
def compress_context(history: list, budget: int) -> list:
"""Compress history when approaching context limit."""
usage = count_tokens(history)
if usage < budget * 0.8:
return history
# Keep recent turns, summarize older ones
recent = history[-10:] # Last 10 turns
older = history[:-10]
summary = llm.summarize(older)
return [{"role": "system", "content": f"Previous context summary:\n{summary}"}] + recent
```
### Repo Map Pattern (Aider)
```python
def build_repo_map(repo_path: Path) -> str:
"""Build a 'map' of the codebase with just signatures."""
import tree_sitter
map_lines = []
for file in repo_path.rglob("*.py"):
# Parse and extract: class names, function signatures, imports
signatures = extract_signatures(file)
map_lines.append(f"{file}:\n{signatures}")
return "\n".join(map_lines) # Much smaller than full code
```
## Challenge 2: Tool Execution Safety
### Three Safety Models
Three safety models represent different trade-offs. The hard sandbox model used by Codex (Rust) provides maximum safety with OS-level isolation. The per-step approval model used by Cline is safe but tedious due to too many popups. The tiered plus hooks model used by Claude Code provides balance with read/write/execute tiers.
### Sandboxing (Codex/Rust approach)
```rust
// Use landlock + seccomp for OS-level sandboxing
fn sandbox_restrict(allowed_paths: &[PathBuf]) -> Result<()> {
// Limit file access to allowed paths
// Block dangerous syscalls
// Three modes: suggest-only, auto-edit, full-auto
}
```
### Tiered Tools (Claude Code approach)
```python
TOOL_TIERS = {
"read": "safe", # No approval needed
"write": "needs_approval", # User confirms
"bash": "restricted", # Blacklist + approval
}
def execute_tool(name: str, args: dict) -> Result:
tier = TOOL_TIERS.get(name, "safe")
if tier == "needs_approval":
if not user_approves(name, args):
return Result(cancelled=True)
if tier == "restricted":
if is_dangerous(args):
return Result(error="Command blocked")
return run_tool(name, args)
```
### Doom Loop Detection (OpenCode unique feature)
```python
def detect_doom_loop(history: list) -> bool:
"""Detect if agent is stuck repeating the same action."""
if len(history) < 3:
return False
last_three = history[-3:]
# Check if same tool called 3 times with identical args
if all_same_tool_and_args(last_three):
return True # Pause and ask user
return False
```
## Challenge 3: Multi-Provider Abstraction
Each LLM provider has different APIs for message formats, tool calling, and streaming. OpenAI uses `content: string` with `function_call` for tools. Anthropic uses `content: blocks[]` with `tool_use` for tools. Google uses `parts[]` with `function_call` for tools. Ollama is OpenAI-compatible.
Two approaches exist for multi-provider abstraction. OpenCode uses the Vercel AI SDK which provides free abstraction for over 20 providers. Cline uses manual adapters which supports 44 providers with full control.
### Unified Client Pattern
```python
class BaseLLMClient(ABC):
@abstractmethod
def chat(self, messages: list, tools: list) -> Response: ...
@abstractmethod
def chat_stream(self, messages: list, tools: list) -> Iterator[Chunk]: ...
class OpenAIClient(BaseLLMClient):
def chat(self, messages, tools):
return self.client.chat.completions.create(
model=self.model, messages=messages, tools=tools
)
class AnthropicClient(BaseLLMClient):
def chat(self, messages, tools):
return self.client.messages.create(
model=self.model, messages=messages, tools=tools
)
def get_client(provider: str, model: str) -> BaseLLMClient:
clients = {
"openai": OpenAIClient,
"anthropic": AnthropicClient,
"ollama": OllamaClient,
}
return clients[provider](model)
```
## Challenge 4: Error Recovery
Long execution chains fail often: API limits, expired keys, network, context overflow.
### Layered Retry Pattern
```python
async def agent_loop_with_retry(max_retries: int = 32):
for attempt in range(max_retries):
try:
return await agent_loop()
except RateLimitError:
await sleep(60 * (2 ** attempt)) # Exponential backoff
except AuthError:
rotate_api_key() # Inner retry
except ContextOverflowError:
compress_context() # Middle retry
except NetworkError:
continue # Immediate retry
except FatalError:
rebuild_session() # Outer retry
```
## Challenge 5: Session Persistence
Different agents use different storage approaches. OpenCode uses SQLite which provides ACID guarantees and no corruption on crash. Other agents use JSONL which is simple and human-readable.
### JSONL Pattern
```python
def save_session(session_id: str, event: dict):
"""Append event to session log file."""
log_file = Path.home() / ".agent" / "sessions" / f"{session_id}.jsonl"
with open(log_file, "a") as f:
f.write(json.dumps(event) + "\n")
def load_session(session_id: str) -> list:
"""Load all events from session."""
log_file = Path.home() / ".agent" / "sessions" / f"{session_id}.jsonl"
events = []
with open(log_file) as f:
for line in f:
events.append(json.loads(line))
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.