Building AI agents, atomically
feat(claude-plugin): rewrite atomic-agents plugin as v2.0.0 skills-only pack
KennyVaneetvelde1fd9adb5011b
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex b9d57ff..70ecec3 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -9,8 +9,8 @@"plugins": [{"name": "atomic-agents",- "description": "Comprehensive development workflow for building well-organized Atomic Agents applications with specialized agents for schema design, architecture planning, code review, and tool development",- "version": "1.0.0",+ "description": "Skills for building and reviewing applications with the Atomic Agents Python framework. Progressive-disclosure references for schemas, agents, tools, context providers, prompts, orchestration, memory, hooks, providers, project structure, and testing — plus a reviewer skill and a new-app scaffolder.",+ "version": "2.0.0","author": {"name": "BrainBlend AI","email": "[email protected]"diff --git a/claude-plugin/atomic-agents/.claude-plugin/plugin.json b/claude-plugin/atomic-agents/.claude-plugin/plugin.jsonindex 909dc28..d741d7c 100644--- a/claude-plugin/atomic-agents/.claude-plugin/plugin.json+++ b/claude-plugin/atomic-agents/.claude-plugin/plugin.json@@ -1,23 +1,12 @@{"name": "atomic-agents",- "version": "1.0.0",- "description": "Comprehensive development workflow for building well-organized Atomic Agents applications with specialized sub-agents for schema design, agent creation, tool development, and code review",+ "version": "2.0.0",+ "description": "Skills for building and reviewing applications with the Atomic Agents Python framework. Progressive-disclosure reference material for schemas, agents, tools, context providers, prompts, orchestration, providers, project structure, and testing — plus a reviewer skill and a new-app scaffolder.","author": {"name": "BrainBlend AI",- "email": "[email protected]"+ "email": "[email protected]"},"homepage": "https://github.com/BrainBlend-AI/atomic-agents","repository": "https://github.com/BrainBlend-AI/atomic-agents",- "license": "MIT",- "keywords": [- "atomic-agents",- "ai-agents",- "llm",- "pydantic",- "instructor",- "multi-agent",- "orchestration",- "tools",- "schemas"- ]+ "license": "MIT"}diff --git a/claude-plugin/atomic-agents/CHANGELOG.md b/claude-plugin/atomic-agents/CHANGELOG.mdindex 9814a96..f1e8c01 100644--- a/claude-plugin/atomic-agents/CHANGELOG.md+++ b/claude-plugin/atomic-agents/CHANGELOG.md@@ -5,44 +5,50 @@ All notable changes to the Atomic Agents Claude Code Plugin will be documented iThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).-## [1.0.0] - 2025-12-21+## [2.0.0] - 2026-04-16++Full rewrite to match 2026 Claude Code plugin conventions. The plugin is now skills-only, with progressive-disclosure references instead of heavyweight subagents and rigid multi-phase commands.++### Changed++- Replaced four subagents (`atomic-architect`, `atomic-explorer`, `atomic-reviewer`, `schema-designer`) with two auto-triggered skills (`framework`, `review`) and one slash-invokable scaffolder (`new-app`).+- Retired the `/atomic-create`, `/atomic-agent`, `/atomic-tool` slash commands. The `framework` skill loads automatically when the user works in atomic-agents code; the `new-app` skill handles greenfield scaffolding via `/atomic-agents:new-app`.+- `skills/` directories now follow the standard Anthropic layout: a top-level `SKILL.md` plus a `references/` subdirectory loaded on demand.+- Skill descriptions rewritten in third person with concrete trigger terms, per Anthropic's skill authoring best practices.+- Plugin manifest trimmed to the core fields Anthropic's own plugins use (name, description, author, homepage, repository, license).++### Fixed++- Corrected all framework imports to the current top-level paths (`from atomic_agents import ...`, `from atomic_agents.context import ...`). Previous version referenced retired `atomic_agents.lib.*` and `atomic_agents.agents.base_agent` paths.+- Updated `BaseTool` examples to use PEP 695 generics (`class MyTool(BaseTool[In, Out])`) instead of the removed `input_schema = ...` / `output_schema = ...` class-attribute pattern.+- Updated default model references to current-generation models.+- Documented Gemini `assistant_role="model"` requirement, Anthropic `max_tokens` requirement, and per-provider Instructor `Mode` — previously missing or inaccurate.### Added-#### Agents-- **atomic-explorer** - Analyzes existing Atomic Agents applications by tracing configurations, schemas, tools, and orchestration patterns-- **atomic-architect** - Designs application architectures with pattern selection and implementation blueprints-- **atomic-reviewer** - Reviews code for bugs, anti-patterns, security issues with confidence-based filtering-- **schema-designer** - Generates well-structured Pydantic schemas with proper validation--#### Commands-- **/atomic-create** - 7-phase guided workflow for creating complete Atomic Agents applications- - Discovery, Exploration, Clarification, Architecture, Implementation, Review, Summary phases- - Parallel agent deployment for comprehensive analysis- - User approval gates at critical decision points-- **/atomic-agent** - Quick scaffolding for new agents with schemas and configuration-- **/atomic-tool** - Quick scaffolding for new tools with error handling patterns--#### Skills-- **atomic-schemas** - BaseIOSchema patterns, field definitions, validators, type constraints-- **atomic-agents** - Agent configuration, ChatHistory, provider setup, execution methods-- **atomic-tools** - BaseTool development, configuration, error handling, orchestration-- **atomic-context** - Context providers, dynamic prompt injection, RAG patterns-- **atomic-prompts** - SystemPromptGenerator structure, prompt engineering best practices-- **atomic-structure** - Project organization patterns from simple to complex applications--### Framework Support-- Full coverage of Atomic Agents core components-- Support for multiple LLM providers (OpenAI, Anthropic, Groq, Ollama)-- Patterns for synchronous, asynchronous, and streaming execution-- Multi-agent orchestration patterns (sequential, parallel, router, supervisor)-------## [Unreleased]--### Planned-- Hook for automatic schema validation on file save-- MCP server integration for external tool discovery-- Additional skills for advanced patterns (MCP, testing, deployment)-- Example templates for common application types+- `framework/references/testing.md` — new dedicated testing guide (pytest, async, streaming, integration gates).+- `framework/references/providers.md` — covers OpenAI, Anthropic, Groq, Ollama, Gemini, OpenRouter, MiniMax with correct modes and roles.+- `framework/references/memory.md` — `ChatHistory` turn model, persistence, overflow, multi-agent memory patterns (shared, independent, agent-to-agent messaging addressing GH issue #58, supervisor-worker).+- `framework/references/hooks.md` — the five events, telemetry, validation-error inspection, retry patterns, production logging.+- Orchestration guide includes the search+execute pattern for large tool surfaces, with per-pattern pointers to working `atomic-examples/` projects.+- Inline links from reference files to real example projects (`hooks-example`, `deep-research`, `progressive-disclosure`, `orchestration-agent`, `mcp-agent`, `quickstart`).+- `tools.md` distinguishes in-project tools from distributable Forge tools and links to `atomic-forge/guides/tool_structure.md`.+- MCP interop coverage in `framework/references/tools.md`.++### Fixed (post-review)++- `agents.md`: `ChatHistory.load(saved)` is an instance method, not a classmethod. `dump()` returns a JSON **string**, not "JSON-serializable data". Added missing `completion:kwargs` hook event. `TokenCountResult` now lists all seven fields (`total`, `system_prompt`, `history`, `tools`, `model`, `max_tokens`, `utilization`).+- `tools.md`: `MCPTransportType.STREAMABLE_HTTP` does not exist — correct value is `HTTP_STREAM` (alongside `SSE` and `STDIO`). Async tools expose `run_async`, not `arun`.+- `new-app/SKILL.md`: explicit `AgentConfig.mode` per provider (must match the Instructor factory `mode`).+- All SKILL.md bodies and reference files converted from second-person "you" to imperative/third-person per Anthropic's skill-authoring guide (quoted prompt strings and template placeholders retained as-is).+- `framework` skill description trimmed from 574 chars to 343 chars using a hybrid short-lead + compact-trigger form for better discoverability.++### Removed++- `agents/` directory — no subagents.+- `commands/` directory — slash commands are now skills with `disable-model-invocation: true` where user-only invocation is desired.+- Per-skill `examples/` directories — Anthropic's skill-authoring guide recommends `references/` over `examples/` for progressive disclosure.++## [1.0.0] - 2025-12-21++Initial release with subagents (`atomic-explorer`, `atomic-architect`, `atomic-reviewer`, `schema-designer`), three slash commands (`/atomic-create`, `/atomic-agent`, `/atomic-tool`), and six progressive-disclosure skills.diff --git a/claude-plugin/atomic-agents/README.md b/claude-plugin/atomic-agents/README.mdindex dd46678..348a420 100644--- a/claude-plugin/atomic-agents/README.md+++ b/claude-plugin/atomic-agents/README.md@@ -1,251 +1,77 @@# Atomic Agents Plugin for Claude Code-A comprehensive Claude Code plugin for building well-organized [Atomic Agents](https://github.com/BrainBlend-AI/atomic-agents) applications. This plugin provides specialized sub-agents, guided workflows, and progressive-disclosure skills to help you create production-ready AI agent systems.+A Claude Code plugin that gives Claude deep, just-in-time knowledge of the [Atomic Agents](https://github.com/BrainBlend-AI/atomic-agents) Python framework. When you work on an Atomic Agents codebase, Claude picks up the right patterns for schemas, agents, tools, context providers, prompts, orchestration, and provider wiring — without you having to paste documentation or repeat conventions.-## Overview+## What you get-The Atomic Agents framework is a lightweight, modular system for building AI agents using Pydantic schemas and the Instructor library. This plugin brings that power into Claude Code with:+Three skills, loaded on demand:-- **4 Specialized Agents** for analysis, design, review, and schema generation-- **3 Workflow Commands** from guided creation to quick scaffolding-- **6 Progressive-Disclosure Skills** for just-in-time knowledge+- **`framework`** — auto-triggered when Claude sees atomic-agents code. Gives Claude an orientation to the framework, decision guidance, and eight focused reference files it can pull into context as the task requires (schemas, agents, tools, context providers, prompts, orchestration, providers, project structure, testing).+- **`review`** — auto-triggered when you ask for a review, audit, or check of atomic-agents code. Focuses only on framework-specific concerns (correct imports, `BaseIOSchema` docstring invariant, Instructor wrapping, per-provider role and mode, context-provider I/O hygiene, orchestration hazards). Complements generic code review; does not replace it.+- **`new-app`** — slash-invokable scaffolder (`/atomic-agents:new-app`). Asks four short questions and produces a runnable project with the right `pyproject.toml`, environment file, and first agent.-## Installation+No subagents, no rigid multi-phase workflow. Skills load what they need, when they need it.-### From a Marketplace+## Install-```bash-# If published to a marketplace-/plugin install atomic-agents@marketplace-name-```--### Local Installation--```bash-# Clone or copy the plugin to a directory-claude --plugin-dir /path/to/atomic-agents-```+### Claude Code marketplace-### Validate Installation--```bash-# Check that the plugin loads correctly-/plugin validate /path/to/atomic-agents```--## Commands--### `/atomic-create` - Guided Application Workflow--The master command for building complete Atomic Agents applications through a 7-phase workflow:--```bash-/atomic-create A research agent that summarizes academic papers+/plugin install atomic-agents@<marketplace-name>```-**Phases:**-1. **Discovery** - Understand requirements-2. **Exploration** - Analyze existing code (if applicable)-3. **Clarification** - Resolve ambiguities-4. **Architecture** - Design the application-5. **Implementation** - Build components-6. **Review** - Validate against best practices-7. **Summary** - Document what was created--### `/atomic-agent` - Quick Agent Creation--Rapidly scaffold a new agent with proper configuration:+### Local```bash-/atomic-agent A customer support agent that handles refund requests+claude --plugin-dir /path/to/atomic-agents/claude-plugin/atomic-agents```-Creates:-- Input/output schemas-- Agent configuration with SystemPromptGenerator-- Usage examples--### `/atomic-tool` - Quick Tool Creation--Scaffold a new tool for external integrations:+### Validate```bash-/atomic-tool A weather API tool that fetches current conditions-```--Creates:-- Input/output/error schemas-- Tool configuration with environment variables-- Error handling patterns-- Usage examples--## Agents--### atomic-explorer (Yellow)--Deeply analyzes existing Atomic Agents applications:-- Maps agent configurations and purposes-- Catalogs schemas, tools, and context providers-- Traces orchestration patterns and data flow-- Identifies architecture patterns--**Triggered by:** Exploring codebases, understanding existing implementations--### atomic-architect (Green)--Designs application architectures:-- Analyzes requirements-- Selects appropriate orchestration patterns-- Creates implementation blueprints-- Specifies component designs--**Triggered by:** Planning new applications, designing multi-agent systems--### atomic-reviewer (Red)--Reviews code for quality and best practices:-- Schema quality and type safety-- Agent configuration correctness-- Security and error handling-- Performance considerations--**Triggered by:** Code review, pre-commit validation, quality audits--### schema-designer (Blue)--Generates well-structured Pydantic schemas:-- Input/output schemas for agents-- Tool parameter schemas-- Complex nested structures-- Validators for business rules--**Triggered by:** Schema design, data contract definition--## Skills--Skills provide progressive-disclosure knowledge, loading only when needed to keep context lean:--| Skill | Trigger Phrases | Purpose |-|-------|----------------|---------|-| `atomic-schemas` | "create schema", "BaseIOSchema", "field validation" | Pydantic schema patterns |-| `atomic-agents` | "create agent", "AgentConfig", "ChatHistory" | Agent configuration |-| `atomic-tools` | "create tool", "BaseTool", "tool orchestration" | Tool development |-| `atomic-context` | "context provider", "dynamic context", "share data" | Context providers |-| `atomic-prompts` | "system prompt", "SystemPromptGenerator" | Prompt engineering |-| `atomic-structure` | "project structure", "pyproject.toml" | Project organization |--## Usage Examples--### Create a Complete Application--```-You: /atomic-create A RAG chatbot that answers questions from PDF documents--Claude: I'll guide you through creating this application...-[7-phase workflow begins]-```--### Quick Agent Scaffolding--```-You: /atomic-agent A sentiment analysis agent--Claude: [Creates schemas and agent configuration]-```--### Explore Existing Code-+/plugin validate /path/to/claude-plugin/atomic-agents```-You: Help me understand how the agents in this project work-Claude: [Deploys atomic-explorer to analyze the codebase]-```--### Review Implementation--```-You: Review my Atomic Agents code for issues--Claude: [Deploys atomic-reviewer with confidence-based filtering]-```--## Framework Reference--This plugin targets the [Atomic Agents](https://github.com/BrainBlend-AI/atomic-agents) framework:+## How it works-### Core Components+This plugin follows Anthropic's 2026 skill-authoring conventions:-- **AtomicAgent** - Main agent class with structured I/O-- **AgentConfig** - Configuration for model, history, prompts-- **BaseIOSchema** - Base class for Pydantic schemas-- **SystemPromptGenerator** - Structured prompt builder-- **BaseTool** - Base class for tools-- **BaseDynamicContextProvider** - Dynamic context injection-- **ChatHistory** - Conversation state management+- Each skill is a folder with a `SKILL.md` file (≤500 lines) plus an optional `references/` directory.+- YAML frontmatter has two fields: `name` and `description`. The description is what Claude reads to decide when the skill applies.+- Reference files are one level deep from `SKILL.md`, each ≤ a few pages. Claude loads only the ones relevant to the current task.+- No README, CHANGELOG, or auxiliary docs inside skill folders — those live at the plugin root.-### Supported Providers+Read the `framework` skill's `SKILL.md` if you want to see the routing table and minimum-viable-agent template up front.-- OpenAI (GPT-4, GPT-4o, etc.)-- Anthropic (Claude)-- Groq-- Ollama (local models)-- OpenRouter-- Any OpenAI-compatible API+## Typical flows-## Best Practices+**Writing new atomic-agents code.** Open your project. Claude notices imports from `atomic_agents`, loads the `framework` skill, and pulls in `references/schemas.md`, `references/agents.md`, etc. as the conversation progresses.-### When Using This Plugin+**Before committing.** Ask "review my changes for atomic-agents issues." The `review` skill fires, produces a confidence-filtered list of framework-specific issues with ready-to-apply fixes.-1. **Start with /atomic-create** for new projects - it ensures proper structure-2. **Use skills for quick reference** - they load just-in-time knowledge-3. **Let agents do deep analysis** - atomic-explorer for understanding, atomic-reviewer for validation-4. **Follow the workflow** - the 7-phase process prevents common mistakes+**Starting from nothing.** Run `/atomic-agents:new-app my-project`. Four questions, one scaffolded project, one runnable agent.-### Atomic Agents Best Practices+## Framework compatibility-1. **Always use BaseIOSchema** - never plain Pydantic BaseModel-2. **Describe all fields** - descriptions are used in prompt generation-3. **Use environment variables** - never hardcode API keys-4. **Wrap with instructor** - required for structured outputs-5. **Handle errors gracefully** - tools should return error schemas, not raise+- Python 3.12+ (PEP 695 generics).+- Atomic Agents 2.7+.+- Instructor 1.14+ with provider extras (`instructor[openai]`, `instructor[anthropic]`, `instructor[groq]`, `instructor[google-genai]`).+- Pydantic 2.-## Troubleshooting+## Development-### Plugin Not Loading+Edit files in place and re-run `/reload-plugins` in Claude Code to pick up changes without restarting. `--plugin-dir` loads take precedence over installed marketplace copies for the current session.-1. Verify plugin structure: `.claude-plugin/plugin.json` exists-2. Run validation: `/plugin validate /path/to/plugin`-3. Check for JSON syntax errors in plugin.json--### Skills Not Triggering--1. Use explicit trigger phrases from skill descriptions-2. Manually load: "Load the atomic-schemas skill"--### Agents Not Found--1. Check agents/ directory exists with .md files-2. Verify YAML frontmatter is valid in agent files--## Contributing--Contributions are welcome! Please:--1. Follow the existing plugin structure-2. Add tests for new components-3. Update documentation-4. Follow semantic versioning+Skill-authoring guidance comes from Anthropic's [skill-creator](https://github.com/anthropics/skills) and [skill authoring best practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices). Keep descriptions in third person with concrete trigger terms, keep SKILL.md bodies under 500 lines, and push detail into `references/` files so progressive disclosure works.## License-MIT License - See [LICENSE](LICENSE) file.+MIT — see `LICENSE`.## Links-- **Atomic Agents Framework**: https://github.com/BrainBlend-AI/atomic-agents-- **Documentation**: https://github.com/BrainBlend-AI/atomic-agents/tree/main/docs-- **Examples**: https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples-----+- Framework: https://github.com/BrainBlend-AI/atomic-agents+- Examples: https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples+- Changelog: `CHANGELOG.md`-Built with care for the Atomic Agents community by [BrainBlend AI](https://github.com/BrainBlend-AI).+Built by [BrainBlend AI](https://github.com/BrainBlend-AI).diff --git a/claude-plugin/atomic-agents/agents/atomic-architect.md b/claude-plugin/atomic-agents/agents/atomic-architect.mddeleted file mode 100644index be903c1..0000000--- a/claude-plugin/atomic-agents/agents/atomic-architect.md+++ /dev/null@@ -1,275 +0,0 @@-----name: atomic-architect-description: Designs Atomic Agents application architectures by analyzing requirements, selecting appropriate patterns, and creating comprehensive implementation blueprints. Use this agent when planning a new Atomic Agents application, designing multi-agent orchestration, choosing between architectural approaches, or creating implementation roadmaps.-model: sonnet-color: green-tools:- - Glob- - Grep- - LS- - Read- - TodoWrite- - WebFetch------# Atomic Agents Application Architect--You are an expert software architect specializing in the Atomic Agents framework. Your role is to design well-structured, maintainable, and efficient Atomic Agents applications based on requirements analysis and framework best practices.--## Core Mission--Design Atomic Agents applications that are:-- **Modular**: Each component has a single, clear responsibility-- **Type-Safe**: Leveraging Pydantic schemas for validation-- **Extensible**: Easy to add new agents, tools, or providers-- **Production-Ready**: Following security, performance, and monitoring best practices--## Architecture Design Process--### 1. Requirements Analysis--Before designing, understand:-- What problem is being solved?-- What are the inputs and outputs?-- What external services are needed?-- What are the performance requirements?-- Is streaming or async needed?-- Will multiple agents collaborate?--### 2. Pattern Selection--Choose the appropriate orchestration pattern:--**Single Agent** - When:-- Simple request-response workflow-- No need for specialized sub-tasks-- Direct transformation of input to output--**Sequential Pipeline** - When:-- Multi-stage processing required-- Each stage transforms data for the next-- Clear input → processing → output flow--**Parallel Execution** - When:-- Independent tasks can run simultaneously-- Need to aggregate results from multiple sources-- Performance optimization is critical--**Router Pattern** - When:-- Different query types need different handling-- Specialized agents for specific domains-- Classification before processing--**Supervisor Pattern** - When:-- Quality validation is required-- Iterative refinement of outputs-- Complex multi-step reasoning--**Tool Orchestration** - When:-- Agent needs to use external capabilities-- Dynamic tool selection based on input-- Integration with APIs or databases--### 3. Component Design--Design each component with clear specifications:--**Agents**-```python-# Design template-Agent: [Name]-Purpose: [Single sentence]-Input Schema: [Fields and types]-Output Schema: [Fields and types]-System Prompt:- - Background: [Role and expertise]- - Steps: [Processing instructions]- - Output Instructions: [Format requirements]-Context Providers: [Dynamic data sources]-Model: [Selection rationale]-```--**Schemas**-```python-# Design template-Schema: [Name]-Purpose: [What data it represents]-Fields:- - name: type = Field(..., description="...")-Validators: [Business rules]-```--**Tools**-```python-# Design template-Tool: [Name]-Purpose: [What capability it provides]-Input: [Required parameters]-Output: [Return data]-Dependencies: [External services]-Error Handling: [Failure modes]-```--**Context Providers**-```python-# Design template-Provider: [Name]-Title: [Display title]-Data Source: [Where data comes from]-Format: [How get_info() structures output]-Update Frequency: [When data refreshes]-```--### 4. Project Structure--Recommend appropriate structure based on complexity:--**Simple Application** (1-2 agents):-```-project_name/-├── pyproject.toml-├── .env-├── README.md-└── project_name/- ├── __init__.py- ├── main.py- ├── schemas.py- └── config.py-```--**Medium Application** (3-5 agents with tools):-```-project_name/-├── pyproject.toml-├── .env-├── README.md-└── project_name/- ├── __init__.py- ├── main.py- ├── config.py- ├── schemas.py- ├── agents/- │ ├── __init__.py- │ └── [agent files]- └── tools/- ├── __init__.py- └── [tool files]-```--**Complex Application** (multi-agent with services):-```-project_name/-├── pyproject.toml-├── .env-├── README.md-└── project_name/- ├── __init__.py- ├── main.py- ├── config.py- ├── agents/- │ ├── __init__.py- │ └── [agent files]- ├── tools/- │ ├── __init__.py- │ └── [tool files]- ├── schemas/- │ ├── __init__.py- │ └── [schema files]- ├── services/- │ ├── __init__.py- │ └── [service files]- ├── context_providers/- │ ├── __init__.py- │ └── [provider files]- └── presentation/- ├── __init__.py- └── [UI/output files]-```--## Output Format--Provide your architecture design as:--### 1. Architecture Overview-- High-level description-- Chosen orchestration pattern(s) with rationale-- Key design decisions--### 2. Component Specifications--For each agent:-```-## Agent: [Name]--**Purpose**: [Description]--**Input Schema**:-```python-class [Name]InputSchema(BaseIOSchema):- field: type = Field(..., description="...")-```--**Output Schema**:-```python-class [Name]OutputSchema(BaseIOSchema):- field: type = Field(..., description="...")-```--**System Prompt**:-- Background: [...]-- Steps: [...]-- Output Instructions: [...]--**Configuration**:-- Model: [recommendation]-- Context Providers: [list]-- Hooks: [if needed]-```--### 3. Data Flow Diagram-```-[Input] → [Agent1] → [Agent2] → [Output]- ↓- [Tool/Service]-```--### 4. Implementation Sequence--Phased checklist for building:-- [ ] Phase 1: Core schemas-- [ ] Phase 2: Configuration-- [ ] Phase 3: Tools (if needed)-- [ ] Phase 4: Context providers (if needed)-- [ ] Phase 5: Agents-- [ ] Phase 6: Orchestration-- [ ] Phase 7: Entry point--### 5. Files to Create/Modify--Specific file list with purposes:-1. `path/file.py` - [purpose]-2. ...--### 6. Critical Considerations--- Error handling strategy-- Security considerations-- Performance optimizations-- Testing approach-- Monitoring/logging--## Design Principles--1. **Make Confident Choices**: Present a clear recommendation rather than multiple options. Include rationale and trade-offs.--2. **Start Simple**: Recommend the simplest architecture that meets requirements. Complexity can be added later.--3. **Schema-First Design**: Define schemas before agents - they are the contracts between components.--4. **Single Responsibility**: Each agent should do one thing well. Split complex tasks into multiple agents.--5. **Explicit Over Implicit**: Prefer clear, explicit configurations over magic or conventions.--6. **Production-Ready**: Include error handling, logging, and monitoring from the start.--7. **Provider-Agnostic**: Design to work with multiple LLM providers when possible.diff --git a/claude-plugin/atomic-agents/agents/atomic-explorer.md b/claude-plugin/atomic-agents/agents/atomic-explorer.mddeleted file mode 100644index 6f15ae4..0000000--- a/claude-plugin/atomic-agents/agents/atomic-explorer.md+++ /dev/null@@ -1,175 +0,0 @@-----name: atomic-explorer-description: Deeply analyzes existing Atomic Agents applications by tracing agent configurations, schema definitions, tool implementations, context providers, and orchestration patterns. Use this agent when exploring an existing Atomic Agents codebase, understanding how agents are configured, tracing data flow between components, or mapping the architecture of a multi-agent system.-model: sonnet-color: yellow-tools:- - Glob- - Grep- - LS- - Read- - TodoWrite- - WebFetch------# Atomic Agents Codebase Explorer--You are an expert analyst specializing in the Atomic Agents framework. Your role is to deeply understand existing Atomic Agents applications by systematically exploring their structure, patterns, and implementation details.--## Core Mission--Analyze Atomic Agents codebases to provide comprehensive understanding of:-- Agent configurations and their purposes-- Schema definitions (input/output)-- Tool implementations-- Context providers and their data flow-- Orchestration patterns between agents-- System prompt structures--## Analysis Approach--### 1. Project Discovery--Start by identifying the project structure:-- Locate `pyproject.toml` for dependencies and project metadata-- Find all Python files with agent-related imports-- Identify configuration files (`.env`, `config.py`)-- Map the directory structure--Search patterns to use:-```-# Find agent definitions-Grep: "AtomicAgent\[" or "from atomic_agents"-Grep: "AgentConfig"--# Find schemas-Grep: "BaseIOSchema" or "class.*Schema"--# Find tools-Grep: "BaseTool" or "class.*Tool"--# Find context providers-Grep: "BaseDynamicContextProvider" or "get_info"-```--### 2. Component Mapping--For each component type, document:--**Agents:**-- Name and purpose-- Input/output schema types-- Model configuration-- System prompt structure (background, steps, output_instructions)-- Registered context providers-- Registered hooks--**Schemas:**-- Class name and inheritance-- All fields with types and descriptions-- Validators (field_validator, model_validator)-- Relationships to other schemas--**Tools:**-- Tool name and purpose-- Input/output schemas-- Configuration class if present-- External dependencies (APIs, databases)--**Context Providers:**-- Provider name and title-- Data sources-- How `get_info()` formats context--### 3. Orchestration Analysis--Trace how agents work together:-- Sequential pipelines (output of one feeds to next)-- Parallel execution patterns (asyncio.gather)-- Router patterns (query classification)-- Supervisor patterns (validation loops)-- Shared context providers--### 4. Configuration Analysis--Document:-- Environment variables used-- Model selections and parameters-- API clients and providers-- History management patterns-- Token counting usage--## Output Format--Provide your analysis in this structure:--### Project Overview-- Project name and purpose-- Main entry points-- Key dependencies--### Agent Inventory-For each agent:-```-Agent: [Name]-File: [path:line]-Purpose: [description]-Input Schema: [SchemaName] - [brief description]-Output Schema: [SchemaName] - [brief description]-Model: [model identifier]-Context Providers: [list]-Special Features: [hooks, streaming, async, etc.]-```--### Schema Catalog-For each schema:-```-Schema: [Name]-File: [path:line]-Type: [Input/Output/Both]-Fields:- - field_name: type - description-Used By: [list of agents/tools]-```--### Tool Inventory-For each tool:-```-Tool: [Name]-File: [path:line]-Purpose: [description]-Input: [schema]-Output: [schema]-Dependencies: [external services]-```--### Orchestration Patterns-- Pattern name and description-- Agents involved-- Data flow diagram (text-based)--### Architecture Insights-- Design patterns observed-- Strengths of the implementation-- Areas for improvement-- Notable techniques--### Essential Files List-Provide a prioritized list of files the orchestrator should read to understand this codebase:-1. [file path] - [reason]-2. [file path] - [reason]-...--## Best Practices--1. **Be Thorough**: Don't stop at surface-level analysis. Trace imports, follow type hints, understand the full picture.--2. **Use File:Line References**: Always include specific file paths and line numbers so findings can be verified.--3. **Identify Patterns**: Look for consistent patterns the developers use - these inform future development.--4. **Note Anomalies**: Flag any unusual patterns, potential issues, or deviations from Atomic Agents best practices.--5. **Map Dependencies**: Understand what external services, APIs, or databases the application connects to.--6. **Token Efficiency**: Use `get_symbols_overview` and targeted reads rather than reading entire files when possible.diff --git a/claude-plugin/atomic-agents/agents/atomic-reviewer.md b/claude-plugin/atomic-agents/agents/atomic-reviewer.mddeleted file mode 100644index 2910107..0000000--- a/claude-plugin/atomic-agents/agents/atomic-reviewer.md+++ /dev/null@@ -1,220 +0,0 @@-----name: atomic-reviewer-description: Reviews Atomic Agents code for bugs, anti-patterns, security issues, and adherence to framework best practices. Use this agent after implementing Atomic Agents code, before committing changes, or when auditing existing applications for quality improvements.-model: sonnet-color: red-tools:- - Glob- - Grep- - LS- - Read- - TodoWrite------# Atomic Agents Code Reviewer--You are an expert code reviewer specializing in the Atomic Agents framework. Your role is to identify bugs, anti-patterns, security vulnerabilities, and deviations from best practices in Atomic Agents applications.--## Core Mission--Review Atomic Agents code to ensure:-- **Correctness**: Code works as intended-- **Best Practices**: Follows Atomic Agents conventions-- **Security**: No vulnerabilities or exposed secrets-- **Performance**: Efficient use of resources-- **Maintainability**: Clean, readable, well-organized code--## Review Scope--By default, review recent changes via `git diff`. If no diff is available or the user specifies otherwise, review the files they indicate.--## Review Checklist--### 1. Schema Quality--**Must Check:**-- [ ] Schemas inherit from `BaseIOSchema` (not plain Pydantic BaseModel)-- [ ] All fields have descriptions (used in prompt generation)-- [ ] Field types are appropriate and constrained-- [ ] Validators handle edge cases properly-- [ ] Input schemas validate user-provided data-- [ ] Output schemas match agent's actual outputs--**Common Issues:**-- Missing Field descriptions → LLM doesn't understand field purpose-- Using `BaseModel` instead of `BaseIOSchema` → Missing framework features-- Overly permissive types → Validation gaps-- No validators for business rules → Invalid data passes through--### 2. Agent Configuration--**Must Check:**-- [ ] `client` is properly wrapped with `instructor`-- [ ] `model` is appropriate for the task complexity-- [ ] `history` is initialized when conversation state is needed-- [ ] `system_prompt_generator` has clear background, steps, output_instructions-- [ ] Type parameters match actual schemas: `AtomicAgent[InputSchema, OutputSchema]`--**Common Issues:**-- Raw OpenAI client without instructor → Structured output fails-- Wrong model for task → Cost/quality mismatch-- Missing history when needed → Context lost between turns-- Vague system prompts → Inconsistent agent behavior--### 3. Tool Implementation--**Must Check:**-- [ ] Tools inherit from `BaseTool`-- [ ] `input_schema` and `output_schema` class attributes are set-- [ ] `run()` method handles errors gracefully-- [ ] External API calls have timeouts and retries-- [ ] Sensitive data (API keys) not hardcoded--**Common Issues:**-- Missing schema attributes → Runtime errors-- No error handling → Crashes on API failures-- Hardcoded credentials → Security vulnerability-- No input validation → Injection risks--### 4. Context Providers--**Must Check:**-- [ ] Providers inherit from `BaseDynamicContextProvider`-- [ ] `get_info()` returns formatted string-- [ ] Title is descriptive and unique-- [ ] Provider is registered before agent.run()-- [ ] Provider doesn't make blocking calls if async needed--**Common Issues:**-- Provider not registered → Context missing from prompts-- `get_info()` returns wrong type → Runtime error-- Slow providers blocking execution → Performance issues--### 5. Orchestration Patterns--**Must Check:**-- [ ] Data flows correctly between agents-- [ ] Schema types align between connected agents-- [ ] Async patterns use proper await/gather-- [ ] Error handling between agents is robust-- [ ] No circular dependencies--**Common Issues:**-- Schema mismatch between agents → Type errors-- Missing await → Coroutines not executed-- No error handling → Failures cascade-- Tight coupling → Hard to modify--### 6. Security Review--**Must Check:**-- [ ] API keys from environment variables, not hardcoded-- [ ] No secrets in code, logs, or error messages-- [ ] Input sanitization for user data-- [ ] Output validation before external actions-- [ ] Rate limiting considerations-- [ ] No prompt injection vulnerabilities--**Red Flags:**-- `api_key = "sk-..."` → Hardcoded secret-- `print(error)` with full context → Potential data leak-- `eval()` or `exec()` on user input → Code injection-- Unvalidated tool inputs → Injection attacks--### 7. Performance Considerations--**Must Check:**-- [ ] Streaming used for long responses-- [ ] Async used for concurrent operations-- [ ] Token usage is reasonable (check with get_context_token_count)-- [ ] History is bounded or pruned-- [ ] Caching for repeated operations--**Common Issues:**-- Sync when async needed → Blocking operations-- Unbounded history → Token limit exceeded-- No streaming → Poor user experience-- Repeated API calls → Unnecessary cost--### 8. Code Quality--**Must Check:**-- [ ] Consistent naming conventions-- [ ] Proper type hints throughout-- [ ] Docstrings for public interfaces-- [ ] Logical file organization-- [ ] No dead code or commented blocks--## Confidence Scoring--Rate each issue on a 0-100 confidence scale:--| Score | Meaning |-|-------|---------|-| 0-25 | Might be intentional or false positive |-| 26-50 | Possible issue, worth checking |-| 51-75 | Likely issue, should address |-| 76-100 | Confirmed issue, must fix |--**Only report issues with confidence >= 75**--## Output Format--### Review Summary--**Files Reviewed**: [list]-**Issues Found**: [count by severity]-**Overall Assessment**: [brief summary]--### Critical Issues (Must Fix)--```-Issue: [Title]-File: [path:line]-Confidence: [score]%-Category: [Security/Bug/Anti-Pattern]--Problem:-[Description of what's wrong]--Current Code:-```python-[problematic code]-```--Recommended Fix:-```python-[corrected code]-```--Rationale:-[Why this is important]-```--### Important Issues (Should Fix)--[Same format as above]--### Suggestions (Consider)--[Same format, but for lower-priority improvements]--### Positive Observations--Note well-implemented patterns that follow best practices.--## Review Principles--1. **Quality Over Quantity**: Report fewer, high-confidence issues rather than flooding with possibilities.--2. **Actionable Feedback**: Every issue should have a clear fix.--3. **Context Awareness**: Consider the project's stage and constraints.--4. **Framework Focus**: Prioritize Atomic Agents-specific issues over general Python style.--5. **Security First**: Always flag security issues, even if confidence is moderate.--6. **Be Constructive**: Frame feedback to help improve, not criticize.--7. **Check Pre-existing**: Don't report issues that existed before the changes being reviewed.diff --git a/claude-plugin/atomic-agents/agents/schema-designer.md b/claude-plugin/atomic-agents/agents/schema-designer.mddeleted file mode 100644index 9664a00..0000000--- a/claude-plugin/atomic-agents/agents/schema-designer.md+++ /dev/null@@ -1,291 +0,0 @@-----name: schema-designer-description: Generates well-structured Pydantic schemas for Atomic Agents applications, including input schemas, output schemas, tool schemas, and complex nested structures. Use this agent when designing data contracts between agents, creating tool interfaces, or converting requirements into typed schemas.-model: sonnet-color: blue-tools:- - Read- - Write- - Glob- - Grep------# Atomic Agents Schema Designer--You are an expert in Pydantic schema design for the Atomic Agents framework. Your role is to create type-safe, well-documented schemas that serve as contracts between agents, tools, and external systems.--## Core Mission--Design schemas that are:-- **Type-Safe**: Leverage Python typing for IDE support and validation-- **Self-Documenting**: Field descriptions inform LLM behavior-- **Validated**: Business rules encoded as validators-- **Reusable**: Composable for complex data structures--## Schema Design Principles--### 1. Always Inherit from BaseIOSchema--```python-from atomic_agents.lib.base.base_io_schema import BaseIOSchema-from pydantic import Field--class MySchema(BaseIOSchema):- """Schema description for documentation."""-- field_name: str = Field(- ...,- description="Clear description of what this field represents"- )-```--**Never use plain `BaseModel`** - `BaseIOSchema` provides Atomic Agents integration.--### 2. Field Descriptions are Critical--The description is used in prompt generation. Be specific:--```python-# BAD - vague description-query: str = Field(..., description="The query")--# GOOD - specific and actionable-query: str = Field(- ...,- description="The user's search query. Should be a natural language question or keyword phrase."-)-```--### 3. Constrain Types Appropriately--Use Pydantic's validation features:--```python-from pydantic import Field, field_validator-from typing import Literal, Optional, List--class SearchSchema(BaseIOSchema):- # Literal for fixed options- sort_order: Literal["asc", "desc"] = Field(- default="desc",- description="Sort order for results"- )-- # Numeric constraints- limit: int = Field(- default=10,- ge=1,- le=100,- description="Maximum results to return (1-100)"- )-- # Optional with default- filter_category: Optional[str] = Field(- default=None,- description="Optional category to filter by"- )-- # List with constraints- tags: List[str] = Field(- default_factory=list,- max_length=10,- description="Tags to filter by (max 10)"- )-```--### 4. Add Validators for Business Rules--```python-from pydantic import field_validator, model_validator--class DateRangeSchema(BaseIOSchema):- start_date: str = Field(..., description="Start date in YYYY-MM-DD format")- end_date: str = Field(..., description="End date in YYYY-MM-DD format")-- @field_validator("start_date", "end_date")- @classmethod- def validate_date_format(cls, v: str) -> str:- from datetime import datetime- try:- datetime.strptime(v, "%Y-%m-%d")- except ValueError:- raise ValueError("Date must be in YYYY-MM-DD format")- return v-- @model_validator(mode="after")- def validate_date_range(self) -> "DateRangeSchema":- from datetime import datetime- start = datetime.strptime(self.start_date, "%Y-%m-%d")- end = datetime.strptime(self.end_date, "%Y-%m-%d")- if end < start:- raise ValueError("end_date must be after start_date")- return self-```--### 5. Compose Complex Schemas--```python-class AddressSchema(BaseIOSchema):- """Mailing address."""- street: str = Field(..., description="Street address")- city: str = Field(..., description="City name")- country: str = Field(..., description="Country code (ISO 3166-1 alpha-2)")--class PersonSchema(BaseIOSchema):- """Person with contact information."""- name: str = Field(..., description="Full name")- email: str = Field(..., description="Email address")- address: AddressSchema = Field(..., description="Mailing address")-```--### 6. Use Union Types for Polymorphism--```python-from typing import Union--class TextContentSchema(BaseIOSchema):- content_type: Literal["text"] = "text"- text: str = Field(..., description="Text content")--class ImageContentSchema(BaseIOSchema):- content_type: Literal["image"] = "image"- url: str = Field(..., description="Image URL")- alt_text: str = Field(..., description="Alt text for accessibility")--class MessageSchema(BaseIOSchema):- content: Union[TextContentSchema, ImageContentSchema] = Field(- ...,- description="Message content (text or image)"- )-```--## Common Schema Patterns--### Input Schema for Chat Agent-```python-class ChatInputSchema(BaseIOSchema):- """User message for chat interaction."""-- message: str = Field(- ...,- min_length=1,- max_length=10000,- description="The user's message or question"- )-```--### Output Schema with Structured Response-```python-class AnalysisOutputSchema(BaseIOSchema):- """Structured analysis result."""-- summary: str = Field(- ...,- description="Brief summary of the analysis (1-2 sentences)"- )-- findings: List[str] = Field(- default_factory=list,- description="Key findings from the analysis"- )-- confidence: float = Field(- ...,- ge=0.0,- le=1.0,- description="Confidence score between 0 and 1"- )-- recommendations: List[str] = Field(- default_factory=list,- description="Actionable recommendations based on findings"- )-```--### Tool Input/Output Schemas-```python-class CalculatorInputSchema(BaseIOSchema):- """Input for calculator tool."""-- expression: str = Field(- ...,- description="Mathematical expression to evaluate (e.g., '2 + 2 * 3')"- )--class CalculatorOutputSchema(BaseIOSchema):- """Calculator tool result."""-- result: float = Field(..., description="Computed result")- expression: str = Field(..., description="Original expression")- steps: Optional[List[str]] = Field(- default=None,- description="Calculation steps if available"- )-```--### Schema with Enums-```python-from enum import Enum--class Priority(str, Enum):- LOW = "low"- MEDIUM = "medium"- HIGH = "high"- CRITICAL = "critical"--class TaskSchema(BaseIOSchema):- """Task with priority level."""-- title: str = Field(..., description="Task title")- priority: Priority = Field(- default=Priority.MEDIUM,- description="Task priority level"- )-```--## Output Format--When generating schemas, provide:--### Schema Definition-```python-# Complete, copy-paste ready code-from atomic_agents.lib.base.base_io_schema import BaseIOSchema-from pydantic import Field, field_validator-from typing import List, Optional, Literal--class [SchemaName](BaseIOSchema):- """[Docstring]"""-- [fields...]-- [validators if needed...]-```--### Usage Example-```python-# Example instantiation-schema = SchemaName(- field1="value1",- field2=123-)--# Example with agent-agent = AtomicAgent[SchemaName, OutputSchema](config=config)-```--### Design Rationale-- Why each field is included-- Why specific types/constraints were chosen-- How validators enforce business rules--## Best Practices Summary--1. **Always use BaseIOSchema** - Never plain BaseModel-2. **Describe every field** - LLM uses descriptions-3. **Constrain appropriately** - Use ge, le, min_length, max_length, Literal-4. **Validate business rules** - Use field_validator and model_validator-5. **Compose for complexity** - Nest schemas for structured data-6. **Use Optional wisely** - Only when truly optional-7. **Default sensibly** - Provide defaults when there's a clear sensible value-8. **Document with docstrings** - Explain the schema's purposediff --git a/claude-plugin/atomic-agents/commands/atomic-agent.md b/claude-plugin/atomic-agents/commands/atomic-agent.mddeleted file mode 100644index 3be4d26..0000000--- a/claude-plugin/atomic-agents/commands/atomic-agent.md+++ /dev/null@@ -1,136 +0,0 @@-----description: Quickly create a new Atomic Agents agent with proper configuration, schemas, and system prompt-argument-hint: Description of the agent to create (e.g., "a research agent that summarizes articles")-allowed-tools:- - Read- - Write- - Edit- - Glob- - Grep- - Skill- - Task- - AskUserQuestion------# Quick Agent Creation--Create a new Atomic Agents agent based on the user's description.--## Process--### 1. Understand Requirements--If `$ARGUMENTS` is provided, parse the agent description. Otherwise, ask:-- What should this agent do?-- What input does it need?-- What output should it produce?--### 2. Load Knowledge--```-Use the Skill tool to load: atomic-agents-Use the Skill tool to load: atomic-schemas-Use the Skill tool to load: atomic-prompts-```--### 3. Identify Target Location--- Check if there's an existing project structure-- Look for `agents/` directory or determine where to create the agent-- Identify existing schemas to potentially reuse--### 4. Design the Agent--Use the `schema-designer` agent for complex schemas:-```-Task(subagent_type="schema-designer", prompt="Design input and output schemas for an agent that: [description]. Use ultrathink.")-```--### 5. Create Files--Create the following:--**schemas.py** (or add to existing):-```python-from atomic_agents.lib.base.base_io_schema import BaseIOSchema-from pydantic import Field--class [Agent]InputSchema(BaseIOSchema):- """Input for [agent purpose]."""- # fields...--class [Agent]OutputSchema(BaseIOSchema):- """Output from [agent purpose]."""- # fields...-```--**[agent_name].py**:-```python-import instructor-import openai-from atomic_agents.agents.base_agent import AtomicAgent, AgentConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator-from atomic_agents.lib.components.chat_history import ChatHistory--from .schemas import [Agent]InputSchema, [Agent]OutputSchema--# Initialize client-client = instructor.from_openai(openai.OpenAI())--# Configure agent-config = AgentConfig(- client=client,- model="gpt-4o-mini",- history=ChatHistory(),- system_prompt_generator=SystemPromptGenerator(- background=[- "You are an expert [role].",- "Your purpose is to [purpose].",- ],- steps=[- "1. [First step]",- "2. [Second step]",- "3. [Third step]",- ],- output_instructions=[- "Provide [format instructions].",- "Ensure [quality requirements].",- ],- ),-)--# Create agent-agent = AtomicAgent[InputSchema, OutputSchema](config=config)-```--### 6. Provide Usage Example--Show how to use the created agent:-```python-from [module] import agent, [Agent]InputSchema--# Run the agent-input_data = [Agent]InputSchema(field="value")-output = agent.run(input_data)-print(output)-```--### 7. Quick Review--Perform a quick validation:-- [ ] Schemas inherit from BaseIOSchema-- [ ] All fields have descriptions-- [ ] SystemPromptGenerator has background, steps, output_instructions-- [ ] Client is wrapped with instructor-- [ ] Type parameters match schemas--Report any issues found.-------## Output--Provide:-1. Created files with their paths-2. Usage example-3. Any suggestions for enhancementdiff --git a/claude-plugin/atomic-agents/commands/atomic-create.md b/claude-plugin/atomic-agents/commands/atomic-create.mddeleted file mode 100644index 5bde173..0000000--- a/claude-plugin/atomic-agents/commands/atomic-create.md+++ /dev/null@@ -1,264 +0,0 @@-----description: Guided workflow for creating well-organized Atomic Agents applications with schema design, agent configuration, tool implementation, and best practices-argument-hint: Optional description of the application to build-allowed-tools:- - Read- - Write- - Edit- - Glob- - Grep- - Bash- - TodoWrite- - AskUserQuestion- - Skill- - Task------# Atomic Agents Application Development Workflow--You are guiding the user through creating a well-organized Atomic Agents application. Follow this systematic 7-phase workflow, using specialized sub-agents for deep analysis and design.--## Workflow Overview--| Phase | Goal | Key Actions |-|-------|------|-------------|-| 1 | Discovery | Understand what the user wants to build |-| 2 | Exploration | Analyze existing code if applicable |-| 3 | Clarification | Resolve ambiguities before design |-| 4 | Architecture | Design the application structure |-| 5 | Implementation | Build the components |-| 6 | Review | Validate against best practices |-| 7 | Summary | Document what was created |-------## Phase 1: Discovery--**Goal**: Understand what the user wants to build.--**Actions**:-1. If the user provided an application description in `$ARGUMENTS`, acknowledge it-2. If not, ask them to describe what they want to build-3. Identify key requirements:- - What is the primary purpose?- - What are the inputs and outputs?- - Will it need tools (external APIs, databases)?- - Is multi-agent orchestration needed?- - Does it need streaming or async?- - What LLM provider(s) will be used?-4. Summarize understanding and confirm with the user--**Skill to Load**:-```-Use the Skill tool to load: atomic-structure-```-This will provide context on project organization patterns.--**Wait for user confirmation before proceeding.**-------## Phase 2: Exploration (If Existing Codebase)--**Goal**: Understand existing code patterns and constraints.--**Actions**:-1. Check if this is a new project or extending an existing one-2. If existing codebase has Atomic Agents code:- - Deploy 2-3 `atomic-explorer` agents in parallel to analyze different aspects:- - Agent 1: Map existing agents, their purposes, and schemas- - Agent 2: Catalog existing tools and context providers- - Agent 3: Trace orchestration patterns and data flow--**Agent Deployment**:-```-Task(subagent_type="atomic-explorer", prompt="Analyze the existing Atomic Agents codebase. Focus on: [specific aspect]. Return a list of essential files I should read to understand this codebase. Use ultrathink.")-```--3. Read the essential files identified by the explorers-4. Synthesize findings into a codebase overview--**Skip this phase if creating a new project from scratch.**-------## Phase 3: Clarification--**Goal**: Resolve ambiguities before designing.--**Actions**:-1. Based on Phase 1 (and Phase 2 if applicable), identify questions:- - Schema design choices (what fields, what types?)- - Orchestration pattern preferences- - External service integrations- - Error handling requirements- - Performance considerations--2. Use AskUserQuestion tool for critical decisions:-```-AskUserQuestion with 2-4 specific questions about their requirements-```--3. Document answers for use in Phase 4--**Skills to Load** (as needed):-- `atomic-schemas` - for schema design questions-- `atomic-agents` - for agent configuration questions-- `atomic-tools` - for tool integration questions-- `atomic-context` - for context provider questions--**Wait for user answers before proceeding.**-------## Phase 4: Architecture Design--**Goal**: Design the application structure.--**Actions**:-1. Deploy 2-3 `atomic-architect` agents to design different approaches:- - Architect 1: Conservative approach (simplest that meets requirements)- - Architect 2: Comprehensive approach (includes nice-to-haves)- - Architect 3: (Optional) Alternative pattern if applicable--**Agent Deployment**:-```-Task(subagent_type="atomic-architect", prompt="Design an Atomic Agents application for: [requirements]. Focus on: [approach type]. Include specific schemas, agent configurations, and file structure. Use ultrathink.")-```--2. Synthesize the architectural recommendations-3. Present 2-3 approaches with trade-offs:- - Approach 1: [Name] - [Description]- - Pros: ...- - Cons: ...- - Approach 2: [Name] - [Description]- - Pros: ...- - Cons: ...-4. Make a clear recommendation for which approach to use--**Wait for user to select an approach before proceeding.**-------## Phase 5: Implementation--**DO NOT START THIS PHASE WITHOUT EXPLICIT USER APPROVAL**--**Goal**: Build the application components.--**Actions**:-1. Create a TodoWrite list with all components to implement:- - [ ] Project structure (directories, pyproject.toml)- - [ ] Configuration (config.py, .env.example)- - [ ] Schemas (input/output for each agent)- - [ ] Tools (if needed)- - [ ] Context providers (if needed)- - [ ] Agents- - [ ] Orchestration logic (main.py)- - [ ] Entry point--2. Implement each component in order:--**For Schemas** - Load the atomic-schemas skill:-```-Use the Skill tool to load: atomic-schemas-```-Then use the `schema-designer` agent if complex:-```-Task(subagent_type="schema-designer", prompt="Design schemas for: [description]. Requirements: [specific needs]. Use ultrathink.")-```--**For Agents** - Load the atomic-agents skill:-```-Use the Skill tool to load: atomic-agents-```--**For Tools** - Load the atomic-tools skill:-```-Use the Skill tool to load: atomic-tools-```--**For Context Providers** - Load the atomic-context skill:-```-Use the Skill tool to load: atomic-context-```--**For System Prompts** - Load the atomic-prompts skill:-```-Use the Skill tool to load: atomic-prompts-```--3. Write each file using the Write or Edit tool-4. Mark each todo as completed when done-------## Phase 6: Quality Review--**Goal**: Validate the implementation against best practices.--**Actions**:-1. Deploy `atomic-reviewer` agents to review different aspects:- - Reviewer 1: Schema quality and type safety- - Reviewer 2: Agent configuration and prompts- - Reviewer 3: Security and error handling--**Agent Deployment**:-```-Task(subagent_type="atomic-reviewer", prompt="Review the Atomic Agents code in [path]. Focus on: [aspect]. Report issues with confidence >= 75 only. Use ultrathink.")-```--2. Synthesize review findings-3. Present issues to user, grouped by severity:- - Critical (must fix)- - Important (should fix)- - Suggestions (consider)--**Wait for user to decide which issues to address.**--4. Fix approved issues-------## Phase 7: Summary--**Goal**: Document what was created.--**Actions**:-1. Summarize the application:- - Purpose and capabilities- - Components created (agents, tools, schemas)- - Architecture pattern used- - Key design decisions--2. Provide usage instructions:- - How to install dependencies- - How to configure (.env setup)- - How to run the application--3. Suggest next steps:- - Testing recommendations- - Potential enhancements- - Documentation to add--4. Celebrate the successful creation!-------## Critical Guidelines--1. **Always Load Skills**: Use the Skill tool to load relevant skills before implementing. This ensures you have the latest Atomic Agents patterns.--2. **Use Agents for Depth**: Deploy specialized agents for analysis, design, and review. Don't try to do everything yourself.--3. **Wait at Decision Points**: Phases 1, 3, 4, and 6 require user input. Don't proceed without it.--4. **Track Progress**: Use TodoWrite to track what's been done and what remains.--5. **Follow Framework Patterns**: Always use BaseIOSchema, proper instructor wrapping, and SystemPromptGenerator.--6. **Include Error Handling**: Every agent and tool should handle failures gracefully.--7. **Security First**: Never hardcode secrets. Use environment variables.--8. **Document As You Go**: Include docstrings and comments for complex logic.diff --git a/claude-plugin/atomic-agents/commands/atomic-tool.md b/claude-plugin/atomic-agents/commands/atomic-tool.mddeleted file mode 100644index 7f0a850..0000000--- a/claude-plugin/atomic-agents/commands/atomic-tool.md+++ /dev/null@@ -1,244 +0,0 @@-----description: Quickly create a new Atomic Agents tool with proper input/output schemas and error handling-argument-hint: Description of the tool to create (e.g., "a weather API tool that fetches current conditions")-allowed-tools:- - Read- - Write- - Edit- - Glob- - Grep- - Skill- - Task- - AskUserQuestion------# Quick Tool Creation--Create a new Atomic Agents tool based on the user's description.--## Process--### 1. Understand Requirements--If `$ARGUMENTS` is provided, parse the tool description. Otherwise, ask:-- What should this tool do?-- What external service does it interact with (API, database, file system)?-- What input parameters does it need?-- What output should it return?-- What error conditions should be handled?--### 2. Load Knowledge--```-Use the Skill tool to load: atomic-tools-Use the Skill tool to load: atomic-schemas-```--### 3. Identify Target Location--- Check if there's an existing project structure-- Look for `tools/` directory or determine where to create the tool-- Check for existing config patterns for API keys--### 4. Design the Tool--Use the `schema-designer` agent for the schemas:-```-Task(subagent_type="schema-designer", prompt="Design input and output schemas for a tool that: [description]. Include error handling schema if applicable. Use ultrathink.")-```--### 5. Create Files--**[tool_name]_tool.py**:-```python-from atomic_agents.lib.base.base_tool import BaseTool, BaseToolConfig-from atomic_agents.lib.base.base_io_schema import BaseIOSchema-from pydantic import Field-from typing import Optional-import os--# ============================================================-# Input/Output Schemas-# ============================================================--class [Tool]InputSchema(BaseIOSchema):- """Input for [tool purpose]."""-- param: str = Field(- ...,- description="Description of this parameter"- )---class [Tool]OutputSchema(BaseIOSchema):- """Successful output from [tool purpose]."""-- result: str = Field(- ...,- description="The result from the tool"- )---class [Tool]ErrorSchema(BaseIOSchema):- """Error output from [tool purpose]."""-- error: str = Field(- ...,- description="Error message describing what went wrong"- )- error_code: Optional[str] = Field(- default=None,- description="Error code if available"- )---# ============================================================-# Tool Configuration-# ============================================================--class [Tool]Config(BaseToolConfig):- """Configuration for [Tool]."""-- api_key: str = Field(- default_factory=lambda: os.getenv("[SERVICE]_API_KEY", ""),- description="API key for [service]"- )- base_url: str = Field(- default="https://api.example.com",- description="Base URL for API requests"- )- timeout: int = Field(- default=30,- description="Request timeout in seconds"- )---# ============================================================-# Tool Implementation-# ============================================================--class [Tool](BaseTool):- """- Tool for [purpose].-- This tool [detailed description of what it does].- """-- input_schema = [Tool]InputSchema- output_schema = [Tool]OutputSchema-- def __init__(self, config: [Tool]Config = None):- """Initialize the tool with configuration."""- super().__init__(config or [Tool]Config())- self.config: [Tool]Config = self.config-- def run(self, params: [Tool]InputSchema) -> [Tool]OutputSchema | [Tool]ErrorSchema:- """- Execute the tool.-- Args:- params: Input parameters for the tool-- Returns:- [Tool]OutputSchema on success, [Tool]ErrorSchema on failure- """- try:- # Validate configuration- if not self.config.api_key:- return [Tool]ErrorSchema(- error="API key not configured",- error_code="CONFIG_ERROR"- )-- # Implement tool logic here- # Example:- # response = requests.get(- # f"{self.config.base_url}/endpoint",- # params={"q": params.param},- # headers={"Authorization": f"Bearer {self.config.api_key}"},- # timeout=self.config.timeout- # )- # response.raise_for_status()- # data = response.json()-- result = f"Processed: {params.param}" # Replace with actual logic-- return [Tool]OutputSchema(result=result)-- except Exception as e:- return [Tool]ErrorSchema(- error=str(e),- error_code="EXECUTION_ERROR"- )---# ============================================================-# Convenience Instance-# ============================================================--# Default tool instance (can be overridden with custom config)-tool = [Tool]()-```--### 6. Provide Usage Examples--**Direct Usage**:-```python-from [module].[tool_name]_tool import tool, [Tool]InputSchema--# Run the tool-input_data = [Tool]InputSchema(param="value")-result = tool.run(input_data)--if isinstance(result, [Tool]ErrorSchema):- print(f"Error: {result.error}")-else:- print(f"Result: {result.result}")-```--**With Custom Config**:-```python-from [module].[tool_name]_tool import [Tool], [Tool]Config, [Tool]InputSchema--# Custom configuration-config = [Tool]Config(- api_key="your-api-key",- timeout=60-)--# Create tool with custom config-custom_tool = [Tool](config=config)-result = custom_tool.run([Tool]InputSchema(param="value"))-```--**With Agent**:-```python-from atomic_agents.agents.base_agent import AtomicAgent, AgentConfig-from [module].[tool_name]_tool import tool--# Agent can use the tool-# (Show how to integrate with agent's tool orchestration)-```--### 7. Quick Review--Perform a quick validation:-- [ ] Schemas inherit from BaseIOSchema-- [ ] All fields have descriptions-- [ ] Tool inherits from BaseTool-- [ ] input_schema and output_schema class attributes are set-- [ ] Error handling returns ErrorSchema, not raising exceptions-- [ ] Configuration uses environment variables for secrets-- [ ] Timeout is set for external calls--Report any issues found.-------## Output--Provide:-1. Created files with their paths-2. Required environment variables-3. Usage examples (direct and with agent)-4. Any suggestions for enhancementdiff --git a/claude-plugin/atomic-agents/skills/atomic-agents/SKILL.md b/claude-plugin/atomic-agents/skills/atomic-agents/SKILL.mddeleted file mode 100644index c854686..0000000--- a/claude-plugin/atomic-agents/skills/atomic-agents/SKILL.md+++ /dev/null@@ -1,227 +0,0 @@-----description: This skill should be used when the user asks to "create an agent", "configure AtomicAgent", "set up agent", "agent configuration", "AgentConfig", "ChatHistory", or needs guidance on agent initialization, model selection, history management, and agent execution patterns for Atomic Agents applications.------# Atomic Agents Agent Configuration--The `AtomicAgent` is the core class for LLM interactions in the Atomic Agents framework. It handles structured input/output, conversation history, and system prompt management.--## Basic Agent Setup--```python-import instructor-import openai-from atomic_agents.agents.base_agent import AtomicAgent, AgentConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator-from atomic_agents.lib.components.chat_history import ChatHistory--# 1. Create instructor-wrapped client-client = instructor.from_openai(openai.OpenAI())--# 2. Configure the agent-config = AgentConfig(- client=client,- model="gpt-4o-mini",- history=ChatHistory(),- system_prompt_generator=SystemPromptGenerator(- background=["You are an expert assistant."],- steps=["1. Analyze the input.", "2. Generate response."],- output_instructions=["Be concise and helpful."],- ),-)--# 3. Create the agent with type parameters-agent = AtomicAgent[InputSchema, OutputSchema](config=config)-```--## AgentConfig Parameters--| Parameter | Type | Required | Description |-|-----------|------|----------|-------------|-| `client` | Instructor client | Yes | Instructor-wrapped LLM client |-| `model` | str | Yes | Model identifier (e.g., "gpt-4o-mini") |-| `history` | ChatHistory | No | Conversation history manager |-| `system_prompt_generator` | SystemPromptGenerator | No | System prompt configuration |-| `input_schema` | BaseIOSchema | No | Override input schema |-| `output_schema` | BaseIOSchema | No | Override output schema |-| `model_api_parameters` | dict | No | Additional API parameters |--## LLM Provider Setup--### OpenAI-```python-import instructor-import openai--client = instructor.from_openai(openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY")))-model = "gpt-4o-mini" # or "gpt-4o", "gpt-4-turbo"-```--### Anthropic-```python-import instructor-import anthropic--client = instructor.from_anthropic(anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY")))-model = "claude-sonnet-4-20250514"-```--### Groq-```python-import instructor-from groq import Groq--client = instructor.from_groq(Groq(api_key=os.getenv("GROQ_API_KEY")), mode=instructor.Mode.JSON)-model = "llama-3.1-70b-versatile"-```--### Ollama (Local)-```python-import instructor-import openai--client = instructor.from_openai(- openai.OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")-)-model = "llama3.1"-```--## Agent Execution Methods--### Synchronous-```python-output = agent.run(InputSchema(message="Hello"))-```--### Asynchronous-```python-output = await agent.run_async(InputSchema(message="Hello"))-```--### Streaming (Sync)-```python-for partial in agent.run_stream(InputSchema(message="Hello")):- print(partial) # Partial responses as they arrive-```--### Streaming (Async)-```python-async for partial in agent.run_async_stream(InputSchema(message="Hello")):- print(partial)-```--## ChatHistory Management--```python-from atomic_agents.lib.components.chat_history import ChatHistory--# Create history-history = ChatHistory()--# Use with agent-config = AgentConfig(client=client, model=model, history=history)-agent = AtomicAgent[InputSchema, OutputSchema](config=config)--# Run multiple turns (history accumulates)-agent.run(InputSchema(message="Hello"))-agent.run(InputSchema(message="Tell me more"))--# Reset history-agent.reset_history()--# Save/load history-history_data = history.to_dict()-new_history = ChatHistory.from_dict(history_data)-```--## Context Providers--Dynamic context injection into system prompts:--```python-from atomic_agents.lib.components.system_prompt_generator import BaseDynamicContextProvider--class UserContextProvider(BaseDynamicContextProvider):- def __init__(self):- super().__init__(title="User Context")- self.user_name = ""-- def get_info(self) -> str:- return f"Current user: {self.user_name}"--# Register with agent-provider = UserContextProvider()-agent.register_context_provider("user", provider)--# Update context dynamically-provider.user_name = "Alice"-agent.run(input_data) # System prompt now includes user context-```--## Token Counting--```python-# Get token usage-token_info = agent.get_context_token_count()--print(f"Total: {token_info.total}")-print(f"System prompt: {token_info.system_prompt}")-print(f"History: {token_info.history}")-print(f"Utilization: {token_info.utilization:.1%}")-```--## Hooks for Monitoring--```python-def on_response(response):- print(f"Got response: {response}")--def on_error(error):- print(f"Error: {error}")--agent.register_hook("completion:response", on_response)-agent.register_hook("completion:error", on_error)-agent.register_hook("parse:error", on_error)-```--Hook events:-- `completion:kwargs` - Before API call-- `completion:response` - After successful response-- `completion:error` - On API error-- `parse:error` - On parsing/validation error--## Model API Parameters--Pass additional parameters to the LLM:--```python-config = AgentConfig(- client=client,- model="gpt-4o",- model_api_parameters={- "max_tokens": 1000,- "temperature": 0.7,- "top_p": 0.9,- },-)-```--## Best Practices--1. **Always wrap with instructor** - Required for structured outputs-2. **Use environment variables** - Never hardcode API keys-3. **Initialize history when needed** - Only if conversation state matters-4. **Type your agents** - `AtomicAgent[Input, Output]` for type safety-5. **Use streaming for long responses** - Better user experience-6. **Monitor with hooks** - Track errors and performance-7. **Reset history appropriately** - Prevent context overflow--## References--See `references/` for:-- `multi-provider.md` - Detailed provider configurations-- `async-patterns.md` - Async and streaming patterns--See `examples/` for:-- `basic-agent.py` - Minimal agent setup-- `streaming-agent.py` - Streaming implementationdiff --git a/claude-plugin/atomic-agents/skills/atomic-agents/examples/basic-agent.py b/claude-plugin/atomic-agents/skills/atomic-agents/examples/basic-agent.pydeleted file mode 100644index 43d32c7..0000000--- a/claude-plugin/atomic-agents/skills/atomic-agents/examples/basic-agent.py+++ /dev/null@@ -1,132 +0,0 @@-"""Basic Atomic Agent example with complete setup."""--import os-import instructor-import openai-from dotenv import load_dotenv--from atomic_agents.agents.base_agent import AtomicAgent, AgentConfig-from atomic_agents.lib.base.base_io_schema import BaseIOSchema-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator-from atomic_agents.lib.components.chat_history import ChatHistory-from pydantic import Field--# Load environment variables-load_dotenv()---# ============================================================-# Schemas-# ============================================================--class QuestionInputSchema(BaseIOSchema):- """User question input."""-- question: str = Field(- ...,- min_length=1,- description="The user's question to answer"- )---class AnswerOutputSchema(BaseIOSchema):- """Agent answer output."""-- answer: str = Field(- ...,- description="The answer to the user's question"- )- confidence: str = Field(- default="medium",- description="Confidence level: low, medium, or high"- )---# ============================================================-# Agent Configuration-# ============================================================--def create_qa_agent() -> AtomicAgent[QuestionInputSchema, AnswerOutputSchema]:- """Create and configure the Q&A agent."""-- # Get API key from environment- api_key = os.getenv("OPENAI_API_KEY")- if not api_key:- raise ValueError("OPENAI_API_KEY environment variable not set")-- # Create instructor-wrapped client- client = instructor.from_openai(openai.OpenAI(api_key=api_key))-- # Configure system prompt- system_prompt = SystemPromptGenerator(- background=[- "You are a helpful assistant that answers questions clearly and accurately.",- "You provide concise answers while being thorough.",- "You acknowledge when you're unsure about something.",- ],- steps=[- "1. Carefully read and understand the question.",- "2. Consider what information is needed to answer it.",- "3. Formulate a clear, accurate response.",- "4. Assess your confidence in the answer.",- ],- output_instructions=[- "Provide direct answers without unnecessary preamble.",- "Use simple language when possible.",- "If uncertain, set confidence to 'low' and explain why.",- ],- )-- # Create agent config- config = AgentConfig(- client=client,- model="gpt-4o-mini",- history=ChatHistory(),- system_prompt_generator=system_prompt,- )-- # Return typed agent- return AtomicAgent[QuestionInputSchema, AnswerOutputSchema](config=config)---# ============================================================-# Usage-# ============================================================--def main():- """Run the Q&A agent."""- from rich.console import Console- from rich.panel import Panel-- console = Console()-- # Create agent- agent = create_qa_agent()-- console.print(Panel("Q&A Agent Ready! Type 'quit' to exit.", style="bold green"))-- while True:- # Get user input- question = console.input("\n[bold blue]Question:[/bold blue] ").strip()-- if question.lower() in ("quit", "exit", "q"):- console.print("[yellow]Goodbye![/yellow]")- break-- if not question:- continue-- try:- # Run agent- response = agent.run(QuestionInputSchema(question=question))-- # Display response- console.print(f"\n[bold green]Answer:[/bold green] {response.answer}")- console.print(f"[dim]Confidence: {response.confidence}[/dim]")-- except Exception as e:- console.print(f"[bold red]Error:[/bold red] {e}")---if __name__ == "__main__":- main()diff --git a/claude-plugin/atomic-agents/skills/atomic-context/SKILL.md b/claude-plugin/atomic-agents/skills/atomic-context/SKILL.mddeleted file mode 100644index 8a38fac..0000000--- a/claude-plugin/atomic-agents/skills/atomic-context/SKILL.md+++ /dev/null@@ -1,234 +0,0 @@-----description: This skill should be used when the user asks to "create context provider", "dynamic context", "inject context", "BaseDynamicContextProvider", "share data between agents", or needs guidance on context providers, dynamic prompt injection, and sharing information across agents in Atomic Agents applications.------# Atomic Agents Context Providers--Context providers dynamically inject information into agent system prompts at runtime. They enable agents to access current data without modifying the base prompt.--## Core Concept--```-┌─────────────────────────────────────────────────────────┐-│ System Prompt │-├─────────────────────────────────────────────────────────┤-│ Background: [static content] │-│ Steps: [static content] │-│ Output Instructions: [static content] │-│ │-│ ┌─────────────────────────────────────────────────────┐ │-│ │ Dynamic Context: │ │-│ │ - User Context: Current user is Alice │ │-│ │ - RAG Context: [retrieved documents] │ │-│ │ - Time Context: Current time is 2025-01-15 │ │-│ └─────────────────────────────────────────────────────┘ │-└─────────────────────────────────────────────────────────┘-```--## Basic Context Provider--```python-from atomic_agents.lib.components.system_prompt_generator import BaseDynamicContextProvider--class UserContextProvider(BaseDynamicContextProvider):- """Provides current user information to the agent."""-- def __init__(self):- super().__init__(title="User Context")- self.user_name: str = ""- self.user_role: str = ""-- def get_info(self) -> str:- if not self.user_name:- return "No user logged in."- return f"Current user: {self.user_name} (Role: {self.user_role})"-```--## Registering Providers--```python-from atomic_agents.agents.base_agent import AtomicAgent, AgentConfig--# Create agent-agent = AtomicAgent[InputSchema, OutputSchema](config=config)--# Create and register provider-user_provider = UserContextProvider()-agent.register_context_provider("user", user_provider)--# Update context before running-user_provider.user_name = "Alice"-user_provider.user_role = "Admin"--# Run agent - system prompt now includes user context-output = agent.run(input_data)-```--## Common Context Provider Patterns--### RAG Context Provider-```python-class RAGContextProvider(BaseDynamicContextProvider):- """Provides retrieved documents to the agent."""-- def __init__(self):- super().__init__(title="Retrieved Documents")- self.documents: list[dict] = []-- def set_documents(self, docs: list[dict]):- """Set retrieved documents."""- self.documents = docs-- def get_info(self) -> str:- if not self.documents:- return "No relevant documents found."-- sections = []- for i, doc in enumerate(self.documents, 1):- sections.append(f"Document {i}:\n{doc['content']}\nSource: {doc['source']}")-- return "\n\n".join(sections)---# Usage-rag_provider = RAGContextProvider()-agent.register_context_provider("rag", rag_provider)--# Before each query, update with relevant docs-relevant_docs = vector_db.search(query)-rag_provider.set_documents(relevant_docs)-output = agent.run(query_input)-```--### Time Context Provider-```python-from datetime import datetime--class TimeContextProvider(BaseDynamicContextProvider):- """Provides current time information."""-- def __init__(self):- super().__init__(title="Current Time")-- def get_info(self) -> str:- now = datetime.now()- return f"Current date and time: {now.strftime('%Y-%m-%d %H:%M:%S')}"-```--### Session Context Provider-```python-class SessionContextProvider(BaseDynamicContextProvider):- """Provides session-specific context."""-- def __init__(self):- super().__init__(title="Session Context")- self.session_data: dict = {}-- def set(self, key: str, value: str):- self.session_data[key] = value-- def get_info(self) -> str:- if not self.session_data:- return "No session context available."-- lines = [f"- {k}: {v}" for k, v in self.session_data.items()]- return "Session information:\n" + "\n".join(lines)-```--### Database Context Provider-```python-class DatabaseContextProvider(BaseDynamicContextProvider):- """Provides database schema or recent data."""-- def __init__(self, db_connection):- super().__init__(title="Database Context")- self.db = db_connection- self._cache = None- self._cache_time = None-- def get_info(self) -> str:- # Cache for 5 minutes- if self._cache and (time.time() - self._cache_time) < 300:- return self._cache-- tables = self.db.get_table_names()- schema_info = []- for table in tables:- columns = self.db.get_columns(table)- schema_info.append(f"Table: {table}\n Columns: {', '.join(columns)}")-- self._cache = "Database Schema:\n" + "\n".join(schema_info)- self._cache_time = time.time()- return self._cache-```--## Managing Providers--```python-# Register-agent.register_context_provider("name", provider)--# Unregister-agent.unregister_context_provider("name")--# Check if registered-if "name" in agent.context_providers:- print("Provider is registered")-```--## Sharing Context Between Agents--```python-# Create shared provider-shared_context = SharedContextProvider()--# Register with multiple agents-agent1.register_context_provider("shared", shared_context)-agent2.register_context_provider("shared", shared_context)--# Update once, both agents see the change-shared_context.update_data(new_data)-```--## Context Provider Best Practices--1. **Keep get_info() fast** - It's called on every agent.run()-2. **Cache when appropriate** - Avoid repeated expensive operations-3. **Return strings** - get_info() must return a string-4. **Use descriptive titles** - Title appears in system prompt-5. **Handle empty state** - Return helpful message when no data-6. **Update before run** - Set context before calling agent.run()-7. **Don't block** - Use async providers for slow operations--## Advanced: Async Context Provider--For providers that need async data fetching:--```python-class AsyncContextProvider(BaseDynamicContextProvider):- def __init__(self):- super().__init__(title="Async Data")- self._cached_data = ""-- async def refresh(self):- """Call this before agent.run_async()"""- data = await fetch_external_data()- self._cached_data = format_data(data)-- def get_info(self) -> str:- return self._cached_data--# Usage-await context_provider.refresh()-output = await agent.run_async(input_data)-```--## References--See `references/` for:-- `rag-patterns.md` - RAG context provider patterns-- `caching-strategies.md` - Context caching approaches--See `examples/` for:-- `user-context.py` - User session provider-- `rag-context.py` - Document retrieval providerdiff --git a/claude-plugin/atomic-agents/skills/atomic-context/examples/rag-context.py b/claude-plugin/atomic-agents/skills/atomic-context/examples/rag-context.pydeleted file mode 100644index 6224802..0000000--- a/claude-plugin/atomic-agents/skills/atomic-context/examples/rag-context.py+++ /dev/null@@ -1,212 +0,0 @@-"""RAG Context Provider example for document-based Q&A."""--from typing import List, Optional-from dataclasses import dataclass--from atomic_agents.lib.components.system_prompt_generator import BaseDynamicContextProvider---@dataclass-class Document:- """A retrieved document chunk."""-- content: str- source: str- score: float- metadata: Optional[dict] = None---class RAGContextProvider(BaseDynamicContextProvider):- """- Context provider for Retrieval-Augmented Generation.-- Provides retrieved document chunks to the agent's system prompt,- enabling it to answer questions based on specific documents.-- Usage:- provider = RAGContextProvider()- agent.register_context_provider("documents", provider)-- # Before each query, set relevant documents- documents = vector_db.search(query, top_k=5)- provider.set_documents(documents)-- # Run agent - it now has document context- response = agent.run(query_input)- """-- def __init__(self, max_documents: int = 5, include_scores: bool = False):- """- Initialize the RAG context provider.-- Args:- max_documents: Maximum documents to include in context- include_scores: Whether to show relevance scores- """- super().__init__(title="Retrieved Documents")- self.documents: List[Document] = []- self.max_documents = max_documents- self.include_scores = include_scores-- def set_documents(self, documents: List[Document]) -> None:- """- Set the documents to include in context.-- Args:- documents: List of retrieved documents, sorted by relevance- """- self.documents = documents[:self.max_documents]-- def clear(self) -> None:- """Clear all documents from context."""- self.documents = []-- def get_info(self) -> str:- """- Format documents for inclusion in system prompt.-- Returns:- Formatted string with document contents and sources- """- if not self.documents:- return "No relevant documents found. Answer based on general knowledge only."-- sections = []- for i, doc in enumerate(self.documents, 1):- header = f"Document {i}"- if self.include_scores:- header += f" (relevance: {doc.score:.2f})"-- section = f"### {header}\n"- section += f"Source: {doc.source}\n"- section += f"Content:\n{doc.content}"-- sections.append(section)-- return "\n\n".join(sections)---class SessionContextProvider(BaseDynamicContextProvider):- """- Context provider for session-specific information.-- Tracks user preferences, conversation context, and other- session-specific data that should inform agent responses.- """-- def __init__(self):- super().__init__(title="Session Context")- self._data: dict = {}-- def set(self, key: str, value: str) -> None:- """Set a session value."""- self._data[key] = value-- def get(self, key: str, default: str = "") -> str:- """Get a session value."""- return self._data.get(key, default)-- def update(self, data: dict) -> None:- """Update multiple session values."""- self._data.update(data)-- def clear(self) -> None:- """Clear all session data."""- self._data = {}-- def get_info(self) -> str:- if not self._data:- return "No session context available."-- lines = [f"- {key}: {value}" for key, value in self._data.items()]- return "Current session information:\n" + "\n".join(lines)---# ============================================================-# Example Usage-# ============================================================--if __name__ == "__main__":- import os- import instructor- import openai- from dotenv import load_dotenv-- from atomic_agents.agents.base_agent import AtomicAgent, AgentConfig- from atomic_agents.lib.base.base_io_schema import BaseIOSchema- from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator- from atomic_agents.lib.components.chat_history import ChatHistory- from pydantic import Field-- load_dotenv()-- # Define schemas- class QuestionInput(BaseIOSchema):- question: str = Field(..., description="Question to answer from documents")-- class AnswerOutput(BaseIOSchema):- answer: str = Field(..., description="Answer based on documents")- sources_used: List[str] = Field(default_factory=list, description="Document sources cited")-- # Create agent- client = instructor.from_openai(openai.OpenAI())-- config = AgentConfig(- client=client,- model="gpt-4o-mini",- history=ChatHistory(),- system_prompt_generator=SystemPromptGenerator(- background=[- "You are a helpful assistant that answers questions based on provided documents.",- "Only use information from the documents to answer.",- "If the documents don't contain the answer, say so clearly.",- ],- steps=[- "1. Read the provided documents carefully.",- "2. Find information relevant to the question.",- "3. Synthesize an answer from the documents.",- "4. List which document sources you used.",- ],- output_instructions=[- "Base your answer only on the provided documents.",- "Cite the sources you used.",- "If no relevant information exists, acknowledge it.",- ],- ),- )-- agent = AtomicAgent[QuestionInput, AnswerOutput](config=config)-- # Create and register context provider- rag_provider = RAGContextProvider(max_documents=3, include_scores=True)- agent.register_context_provider("rag", rag_provider)-- # Simulate retrieved documents- sample_docs = [- Document(- content="The Atomic Agents framework uses Pydantic for schema validation. All input and output schemas should inherit from BaseIOSchema.",- source="atomic-agents-docs/schemas.md",- score=0.95- ),- Document(- content="AtomicAgent is the core class for LLM interactions. It handles structured input/output, conversation history, and system prompt management.",- source="atomic-agents-docs/agents.md",- score=0.89- ),- Document(- content="Context providers dynamically inject information into system prompts at runtime.",- source="atomic-agents-docs/context.md",- score=0.82- ),- ]-- # Set documents before running- rag_provider.set_documents(sample_docs)-- # Run agent- response = agent.run(QuestionInput(- question="How do I define schemas in Atomic Agents?"- ))-- print(f"Answer: {response.answer}")- print(f"Sources: {response.sources_used}")diff --git a/claude-plugin/atomic-agents/skills/atomic-prompts/SKILL.md b/claude-plugin/atomic-agents/skills/atomic-prompts/SKILL.mddeleted file mode 100644index 802c512..0000000--- a/claude-plugin/atomic-agents/skills/atomic-prompts/SKILL.md+++ /dev/null@@ -1,315 +0,0 @@-----description: This skill should be used when the user asks to "write system prompt", "configure SystemPromptGenerator", "prompt engineering", "background steps output_instructions", "improve agent prompt", or needs guidance on structuring system prompts, writing effective instructions, and optimizing agent behavior in Atomic Agents applications.------# Atomic Agents System Prompt Design--The `SystemPromptGenerator` creates structured, effective system prompts for agents. It combines static instructions with dynamic context from providers.--## SystemPromptGenerator Structure--```python-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator--system_prompt = SystemPromptGenerator(- background=[- # WHO the agent is- "You are an expert data analyst.",- "You specialize in financial data interpretation.",- ],- steps=[- # HOW to process requests- "1. Understand the user's question about the data.",- "2. Identify relevant data points and trends.",- "3. Analyze patterns and correlations.",- "4. Formulate clear, actionable insights.",- ],- output_instructions=[- # WHAT to produce- "Provide insights in clear, non-technical language.",- "Include specific numbers and percentages.",- "Highlight key takeaways at the beginning.",- ],-)-```--## Three-Part Structure--### Background (WHO)-Establishes the agent's identity, expertise, and role:--```python-background=[- "You are an expert [role] with deep knowledge in [domain].",- "Your purpose is to [primary function].",- "You have experience with [relevant experience].",- "You approach problems with [methodology/style].",-]-```--**Examples by domain:**-```python-# Customer Support-background=[- "You are a helpful customer support specialist.",- "You represent [Company] and embody its values of helpfulness and clarity.",- "You have comprehensive knowledge of our products and policies.",-]--# Code Assistant-background=[- "You are an expert software engineer specializing in Python.",- "You write clean, maintainable, well-documented code.",- "You follow best practices and design patterns.",-]--# Research Assistant-background=[- "You are a research analyst with expertise in synthesizing information.",- "You excel at finding patterns across multiple sources.",- "You prioritize accuracy and cite sources when possible.",-]-```--### Steps (HOW)-Defines the processing workflow:--```python-steps=[- "1. [First action to take]",- "2. [Second action to take]",- "3. [Third action to take]",- "4. [Final action to take]",-]-```--**Effective step patterns:**--```python-# Analysis Pattern-steps=[- "1. Parse and understand the input data.",- "2. Identify key elements and relationships.",- "3. Apply relevant analysis techniques.",- "4. Synthesize findings into coherent insights.",- "5. Validate conclusions against the data.",-]--# Q&A Pattern-steps=[- "1. Understand the user's question fully.",- "2. Retrieve relevant information from context.",- "3. Formulate a clear, accurate answer.",- "4. Provide supporting details if helpful.",-]--# Task Execution Pattern-steps=[- "1. Parse the task requirements.",- "2. Break down into subtasks if complex.",- "3. Execute each subtask systematically.",- "4. Validate the output meets requirements.",-]-```--### Output Instructions (WHAT)-Specifies the response format and quality:--```python-output_instructions=[- "Format your response as [format].",- "Include [required elements].",- "Ensure [quality requirements].",- "Avoid [things to exclude].",-]-```--**Format examples:**--```python-# Structured Output-output_instructions=[- "Provide your response with a summary first.",- "Use bullet points for key findings.",- "Include confidence level (high/medium/low).",- "End with actionable recommendations.",-]--# Conversational Output-output_instructions=[- "Respond in a friendly, conversational tone.",- "Keep responses concise but complete.",- "Ask clarifying questions if needed.",-]--# Technical Output-output_instructions=[- "Include code examples where appropriate.",- "Explain technical concepts clearly.",- "Reference documentation or sources.",-]-```--## Integrating Context Providers--Context providers add dynamic sections:--```python-from atomic_agents.lib.components.system_prompt_generator import (- SystemPromptGenerator,- BaseDynamicContextProvider,-)--class RAGProvider(BaseDynamicContextProvider):- def __init__(self):- super().__init__(title="Relevant Documents")- self.docs = []-- def get_info(self) -> str:- return "\n".join(self.docs)--# Create generator-generator = SystemPromptGenerator(- background=["You answer questions using provided documents."],- steps=["1. Read the documents.", "2. Answer based on them."],- output_instructions=["Cite document sources."],-)--# Register provider-rag = RAGProvider()-agent.register_context_provider("rag", rag)-```--The generated prompt will include:-```-[Background section]-[Steps section]-[Output Instructions section]--## Relevant Documents-[Dynamic content from provider]-```--## Prompt Engineering Tips--### Be Specific-```python-# Bad-background=["You are helpful."]--# Good-background=[- "You are a Python code reviewer.",- "You identify bugs, security issues, and style violations.",- "You follow PEP 8 and common best practices.",-]-```--### Use Action Verbs-```python-# Bad-steps=["Think about the problem."]--# Good-steps=[- "1. Identify the core issue.",- "2. List possible solutions.",- "3. Evaluate trade-offs.",- "4. Recommend the best approach.",-]-```--### Constrain Output-```python-# Bad-output_instructions=["Give a good answer."]--# Good-output_instructions=[- "Limit response to 3 paragraphs maximum.",- "Start with the most important point.",- "Include one specific example.",-]-```--### Handle Edge Cases-```python-background=[- "If you cannot answer with certainty, say so clearly.",- "If the question is ambiguous, ask for clarification.",- "If the request is outside your expertise, acknowledge it.",-]-```--## Common Prompt Patterns--### Expert Assistant-```python-SystemPromptGenerator(- background=[- "You are an expert [domain] assistant.",- "You provide accurate, helpful information.",- "You acknowledge when you're uncertain.",- ],- steps=[- "1. Understand the user's need.",- "2. Provide relevant information.",- "3. Offer follow-up suggestions.",- ],- output_instructions=[- "Be concise but thorough.",- "Use examples when helpful.",- ],-)-```--### Analyst-```python-SystemPromptGenerator(- background=[- "You are a data analyst.",- "You find insights in data.",- ],- steps=[- "1. Examine the data carefully.",- "2. Identify patterns and anomalies.",- "3. Draw conclusions.",- "4. Suggest actions.",- ],- output_instructions=[- "Include specific numbers.",- "Highlight key findings first.",- "Use simple language.",- ],-)-```--### Code Generator-```python-SystemPromptGenerator(- background=[- "You are an expert programmer.",- "You write clean, efficient code.",- ],- steps=[- "1. Understand the requirements.",- "2. Plan the implementation.",- "3. Write the code.",- "4. Add comments and documentation.",- ],- output_instructions=[- "Include complete, runnable code.",- "Add comments for complex logic.",- "Follow language conventions.",- ],-)-```--## References--See `references/` for:-- `prompt-patterns.md` - More prompt templates-- `optimization.md` - Token-efficient prompts--See `examples/` for:-- `domain-prompts.py` - Domain-specific examplesdiff --git a/claude-plugin/atomic-agents/skills/atomic-schemas/SKILL.md b/claude-plugin/atomic-agents/skills/atomic-schemas/SKILL.mddeleted file mode 100644index 80275e6..0000000--- a/claude-plugin/atomic-agents/skills/atomic-schemas/SKILL.md+++ /dev/null@@ -1,189 +0,0 @@-----description: This skill should be used when the user asks to "create a schema", "define input/output", "add fields", "validate data", "Pydantic schema", "BaseIOSchema", or needs guidance on schema design patterns, field definitions, validators, and type constraints for Atomic Agents applications.------# Atomic Agents Schema Design--Schemas are the foundation of Atomic Agents applications. They define the contracts between agents, tools, and external systems using Pydantic models.--## Core Principle: Always Use BaseIOSchema--```python-from atomic_agents.lib.base.base_io_schema import BaseIOSchema-from pydantic import Field--class MySchema(BaseIOSchema):- """Schema description."""- field: str = Field(..., description="Field description")-```--**Never use plain `BaseModel`** - `BaseIOSchema` provides Atomic Agents integration features.--## Field Definitions--### Required Fields-```python-name: str = Field(..., description="The user's full name")-```--### Optional Fields-```python-from typing import Optional-nickname: Optional[str] = Field(default=None, description="Optional nickname")-```--### Fields with Defaults-```python-count: int = Field(default=10, description="Number of items to return")-```--### Constrained Fields-```python-# Numeric constraints-age: int = Field(..., ge=0, le=150, description="Age in years")-score: float = Field(..., ge=0.0, le=1.0, description="Score between 0 and 1")--# String constraints-name: str = Field(..., min_length=1, max_length=100, description="Name")--# List constraints-tags: List[str] = Field(default_factory=list, max_length=10, description="Tags")-```--### Literal Types (Fixed Options)-```python-from typing import Literal-status: Literal["pending", "approved", "rejected"] = Field(..., description="Status")-```--### Enums-```python-from enum import Enum--class Priority(str, Enum):- LOW = "low"- MEDIUM = "medium"- HIGH = "high"--priority: Priority = Field(default=Priority.MEDIUM, description="Priority level")-```--## Validators--### Field Validators-```python-from pydantic import field_validator--class EmailSchema(BaseIOSchema):- email: str = Field(..., description="Email address")-- @field_validator("email")- @classmethod- def validate_email(cls, v: str) -> str:- if "@" not in v:- raise ValueError("Invalid email format")- return v.lower()-```--### Model Validators-```python-from pydantic import model_validator--class DateRangeSchema(BaseIOSchema):- start: str = Field(..., description="Start date")- end: str = Field(..., description="End date")-- @model_validator(mode="after")- def validate_range(self) -> "DateRangeSchema":- if self.end < self.start:- raise ValueError("end must be after start")- return self-```--## Common Patterns--### Chat Input/Output-```python-class ChatInputSchema(BaseIOSchema):- """User message input."""- message: str = Field(..., min_length=1, description="User's message")--class ChatOutputSchema(BaseIOSchema):- """Agent response output."""- response: str = Field(..., description="Agent's response")-```--### Structured Analysis Output-```python-class AnalysisOutputSchema(BaseIOSchema):- """Structured analysis result."""- summary: str = Field(..., description="Brief summary")- findings: List[str] = Field(default_factory=list, description="Key findings")- confidence: float = Field(..., ge=0, le=1, description="Confidence score")- recommendations: List[str] = Field(default_factory=list, description="Recommendations")-```--### Tool Schemas-```python-class ToolInputSchema(BaseIOSchema):- """Tool input parameters."""- query: str = Field(..., description="Search query")--class ToolOutputSchema(BaseIOSchema):- """Successful tool result."""- result: str = Field(..., description="Tool result")--class ToolErrorSchema(BaseIOSchema):- """Tool error result."""- error: str = Field(..., description="Error message")- code: Optional[str] = Field(default=None, description="Error code")-```--### Nested Schemas-```python-class AddressSchema(BaseIOSchema):- """Mailing address."""- street: str = Field(..., description="Street address")- city: str = Field(..., description="City")- country: str = Field(..., description="Country code")--class PersonSchema(BaseIOSchema):- """Person with address."""- name: str = Field(..., description="Full name")- address: AddressSchema = Field(..., description="Mailing address")-```--### Union Types-```python-from typing import Union--class TextContent(BaseIOSchema):- type: Literal["text"] = "text"- text: str = Field(..., description="Text content")--class ImageContent(BaseIOSchema):- type: Literal["image"] = "image"- url: str = Field(..., description="Image URL")--class MessageSchema(BaseIOSchema):- content: Union[TextContent, ImageContent] = Field(..., description="Content")-```--## Best Practices--1. **Always provide descriptions** - LLMs use them to understand field purpose-2. **Constrain appropriately** - Use ge, le, min_length, max_length, Literal-3. **Validate business rules** - Use field_validator and model_validator-4. **Use Optional sparingly** - Only when truly optional-5. **Provide sensible defaults** - When there's a clear default value-6. **Document with docstrings** - Explain the schema's purpose-7. **Compose for complexity** - Nest schemas for structured data--## References--See `references/` for:-- `advanced-patterns.md` - Complex schema patterns-- `validation-patterns.md` - Advanced validator examples--See `examples/` for:-- `common-schemas.py` - Ready-to-use schema templatesdiff --git a/claude-plugin/atomic-agents/skills/atomic-schemas/examples/common-schemas.py b/claude-plugin/atomic-agents/skills/atomic-schemas/examples/common-schemas.pydeleted file mode 100644index 1228338..0000000--- a/claude-plugin/atomic-agents/skills/atomic-schemas/examples/common-schemas.py+++ /dev/null@@ -1,232 +0,0 @@-"""Common schema patterns for Atomic Agents applications."""--from atomic_agents.lib.base.base_io_schema import BaseIOSchema-from pydantic import Field, field_validator, model_validator-from typing import List, Optional, Literal, Union-from enum import Enum---# ============================================================-# Basic Chat Schemas-# ============================================================--class ChatInputSchema(BaseIOSchema):- """Standard chat input."""-- message: str = Field(- ...,- min_length=1,- max_length=10000,- description="The user's message or question"- )---class ChatOutputSchema(BaseIOSchema):- """Standard chat output."""-- response: str = Field(- ...,- description="The agent's response to the user"- )---# ============================================================-# Structured Analysis Output-# ============================================================--class AnalysisOutputSchema(BaseIOSchema):- """Structured analysis with findings and recommendations."""-- summary: str = Field(- ...,- description="Brief summary of the analysis (1-2 sentences)"- )- findings: List[str] = Field(- default_factory=list,- description="Key findings from the analysis"- )- confidence: float = Field(- ...,- ge=0.0,- le=1.0,- description="Confidence score between 0 and 1"- )- recommendations: List[str] = Field(- default_factory=list,- description="Actionable recommendations"- )---# ============================================================-# Classification Schema-# ============================================================--class Intent(str, Enum):- QUESTION = "question"- COMMAND = "command"- FEEDBACK = "feedback"- GREETING = "greeting"- OTHER = "other"---class ClassificationOutputSchema(BaseIOSchema):- """Intent classification result."""-- intent: Intent = Field(- ...,- description="The classified intent of the input"- )- confidence: float = Field(- ...,- ge=0.0,- le=1.0,- description="Classification confidence"- )- reasoning: str = Field(- ...,- description="Brief explanation of the classification"- )---# ============================================================-# Search Schemas-# ============================================================--class SearchInputSchema(BaseIOSchema):- """Search query input."""-- query: str = Field(- ...,- min_length=1,- description="Search query text"- )- max_results: int = Field(- default=10,- ge=1,- le=100,- description="Maximum number of results to return"- )- filters: Optional[dict] = Field(- default=None,- description="Optional filters to apply"- )---class SearchResultSchema(BaseIOSchema):- """Single search result."""-- title: str = Field(..., description="Result title")- snippet: str = Field(..., description="Text snippet")- url: Optional[str] = Field(default=None, description="Source URL")- score: float = Field(..., ge=0, le=1, description="Relevance score")---class SearchOutputSchema(BaseIOSchema):- """Search results collection."""-- results: List[SearchResultSchema] = Field(- default_factory=list,- description="List of search results"- )- total_found: int = Field(- ...,- ge=0,- description="Total number of matching results"- )- query_time_ms: Optional[int] = Field(- default=None,- description="Query execution time in milliseconds"- )---# ============================================================-# Error Schemas-# ============================================================--class ErrorSchema(BaseIOSchema):- """Standard error response."""-- error: str = Field(..., description="Error message")- code: Optional[str] = Field(default=None, description="Error code")- details: Optional[dict] = Field(default=None, description="Additional details")---# ============================================================-# Validation Example-# ============================================================--class EmailInputSchema(BaseIOSchema):- """Input with email validation."""-- email: str = Field(..., description="Email address")- name: str = Field(..., min_length=1, description="Person's name")-- @field_validator("email")- @classmethod- def validate_email(cls, v: str) -> str:- if "@" not in v or "." not in v.split("@")[-1]:- raise ValueError("Invalid email format")- return v.lower().strip()---class DateRangeSchema(BaseIOSchema):- """Date range with cross-field validation."""-- start_date: str = Field(..., description="Start date (YYYY-MM-DD)")- end_date: str = Field(..., description="End date (YYYY-MM-DD)")-- @field_validator("start_date", "end_date")- @classmethod- def validate_date_format(cls, v: str) -> str:- from datetime import datetime- try:- datetime.strptime(v, "%Y-%m-%d")- except ValueError:- raise ValueError("Date must be in YYYY-MM-DD format")- return v-- @model_validator(mode="after")- def validate_range(self) -> "DateRangeSchema":- from datetime import datetime- start = datetime.strptime(self.start_date, "%Y-%m-%d")- end = datetime.strptime(self.end_date, "%Y-%m-%d")- if end < start:- raise ValueError("end_date must be after start_date")- return self---# ============================================================-# Polymorphic Content-# ============================================================--class TextContentSchema(BaseIOSchema):- """Text content block."""-- content_type: Literal["text"] = "text"- text: str = Field(..., description="Text content")---class ImageContentSchema(BaseIOSchema):- """Image content block."""-- content_type: Literal["image"] = "image"- url: str = Field(..., description="Image URL")- alt_text: Optional[str] = Field(default=None, description="Alt text")---class CodeContentSchema(BaseIOSchema):- """Code content block."""-- content_type: Literal["code"] = "code"- code: str = Field(..., description="Code content")- language: str = Field(default="python", description="Programming language")---ContentType = Union[TextContentSchema, ImageContentSchema, CodeContentSchema]---class MessageSchema(BaseIOSchema):- """Message with polymorphic content."""-- role: Literal["user", "assistant"] = Field(..., description="Message role")- content: List[ContentType] = Field(..., description="Message content blocks")diff --git a/claude-plugin/atomic-agents/skills/atomic-structure/SKILL.md b/claude-plugin/atomic-agents/skills/atomic-structure/SKILL.mddeleted file mode 100644index c0b617b..0000000--- a/claude-plugin/atomic-agents/skills/atomic-structure/SKILL.md+++ /dev/null@@ -1,311 +0,0 @@-----description: This skill should be used when the user asks to "create project structure", "organize atomic agents project", "pyproject.toml", "project layout", "directory structure", or needs guidance on organizing files, configuring dependencies, and structuring Atomic Agents applications for maintainability.------# Atomic Agents Project Structure--Proper project organization is essential for maintainable Atomic Agents applications. Structure scales from simple scripts to complex multi-agent systems.--## Project Structure Patterns--### Simple Application (1-2 agents)--```-my_project/-├── pyproject.toml # Project metadata and dependencies-├── .env # Environment variables (API keys)-├── .env.example # Template for .env-├── .gitignore # Git ignore patterns-├── README.md # Documentation-└── my_project/- ├── __init__.py- ├── main.py # Entry point- ├── config.py # Configuration- └── schemas.py # Input/output schemas-```--### Medium Application (3-5 agents with tools)--```-my_project/-├── pyproject.toml-├── .env-├── .env.example-├── .gitignore-├── README.md-└── my_project/- ├── __init__.py- ├── main.py # Entry point and orchestration- ├── config.py # Configuration- ├── schemas.py # Shared schemas- ├── agents/- │ ├── __init__.py- │ ├── query_agent.py # Agent 1- │ └── response_agent.py # Agent 2- └── tools/- ├── __init__.py- ├── search_tool.py- └── calculator_tool.py-```--### Complex Application (multi-agent with services)--```-my_project/-├── pyproject.toml-├── .env-├── .env.example-├── .gitignore-├── README.md-├── tests/-│ ├── __init__.py-│ ├── test_agents.py-│ └── test_tools.py-└── my_project/- ├── __init__.py- ├── main.py- ├── config.py- ├── agents/- │ ├── __init__.py- │ ├── query_agent.py- │ ├── synthesis_agent.py- │ └── validation_agent.py- ├── tools/- │ ├── __init__.py- │ └── api_tool.py- ├── schemas/- │ ├── __init__.py- │ ├── inputs.py- │ └── outputs.py- ├── services/- │ ├── __init__.py- │ ├── database.py- │ └── external_api.py- ├── context_providers/- │ ├── __init__.py- │ └── rag_provider.py- └── presentation/- ├── __init__.py- └── console.py-```--## pyproject.toml Template--```toml-[project]-name = "my-project"-version = "0.1.0"-description = "An Atomic Agents application for [purpose]"-readme = "README.md"-requires-python = ">=3.11"-license = { text = "MIT" }-authors = [{ name = "Your Name", email = "[email protected]" }]--dependencies = [- "atomic-agents>=1.0.0",- "instructor>=1.0.0",- "openai>=1.0.0",- "python-dotenv>=1.0.0",- "pydantic>=2.0.0",- "rich>=13.0.0",-]--[project.optional-dependencies]-dev = [- "pytest>=7.0.0",- "pytest-asyncio>=0.21.0",- "black>=23.0.0",- "ruff>=0.1.0",-]--[build-system]-requires = ["hatchling"]-build-backend = "hatchling.build"--[tool.hatch.build.targets.wheel]-packages = ["my_project"]-```--## Configuration Pattern--**config.py**:-```python-import os-from dataclasses import dataclass-from dotenv import load_dotenv--load_dotenv()---def get_api_key() -> str:- """Get OpenAI API key from environment."""- key = os.getenv("OPENAI_API_KEY")- if not key:- raise ValueError("OPENAI_API_KEY environment variable not set")- return key---@dataclass-class Config:- """Application configuration."""-- api_key: str = None- model: str = "gpt-4o-mini"- max_tokens: int = 1000- temperature: float = 0.7-- def __post_init__(self):- if self.api_key is None:- self.api_key = get_api_key()---# Global config instance-config = Config()-```--## Environment Variables--**.env.example** (commit this):-```bash-# LLM Provider-OPENAI_API_KEY=sk-your-key-here-# ANTHROPIC_API_KEY=your-key-here--# Application Settings-MODEL=gpt-4o-mini-MAX_TOKENS=1000-TEMPERATURE=0.7--# External Services-# DATABASE_URL=postgresql://...-# REDIS_URL=redis://...-```--**.gitignore** additions:-```gitignore-# Environment-.env-.env.local-.env.*.local--# Python-__pycache__/-*.py[cod]-.venv/-venv/--# IDE-.idea/-.vscode/-*.swp--# Testing-.pytest_cache/-.coverage-htmlcov/-```--## Entry Point Pattern--**main.py**:-```python-"""Main entry point for the application."""--import instructor-import openai-from rich.console import Console--from .config import config-from .agents.query_agent import create_query_agent-from .schemas import UserInput--console = Console()---def main():- """Run the application."""- # Initialize client- client = instructor.from_openai(openai.OpenAI(api_key=config.api_key))-- # Create agent- agent = create_query_agent(client, config.model)-- # Main loop- console.print("[bold green]Ready![/bold green]")- while True:- try:- user_input = console.input("[bold blue]You:[/bold blue] ")- if user_input.lower() in ("exit", "quit"):- break-- response = agent.run(UserInput(message=user_input))- console.print(f"[bold green]Agent:[/bold green] {response.message}")-- except KeyboardInterrupt:- break-- console.print("\n[yellow]Goodbye![/yellow]")---if __name__ == "__main__":- main()-```--## Agent Module Pattern--**agents/query_agent.py**:-```python-"""Query processing agent."""--from atomic_agents.agents.base_agent import AtomicAgent, AgentConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator-from atomic_agents.lib.components.chat_history import ChatHistory--from ..schemas import QueryInput, QueryOutput---def create_query_agent(client, model: str) -> AtomicAgent[QueryInput, QueryOutput]:- """Create and configure the query agent."""- config = AgentConfig(- client=client,- model=model,- history=ChatHistory(),- system_prompt_generator=SystemPromptGenerator(- background=["You are a helpful query processor."],- steps=["1. Understand the query.", "2. Generate response."],- output_instructions=["Be concise and helpful."],- ),- )- return AtomicAgent[QueryInput, QueryOutput](config=config)-```--## File Naming Conventions--| Component | File Pattern | Class Pattern |-|-----------|--------------|---------------|-| Agents | `*_agent.py` | `*Agent` |-| Tools | `*_tool.py` | `*Tool` |-| Schemas | `schemas.py` or `*.py` | `*Schema` |-| Providers | `*_provider.py` | `*Provider` |-| Config | `config.py` | `Config`, `*Config` |-| Services | `*_service.py` | `*Service` |--## Best Practices--1. **One agent per file** - Easier to maintain and test-2. **Shared schemas in schemas.py** - Or schemas/ directory for many-3. **Factory functions** - `create_*_agent()` for configurable agents-4. **Type hints everywhere** - IDE support and documentation-5. **Docstrings** - Document purpose of each module-6. **Tests alongside code** - tests/ directory mirroring src-7. **Rich for output** - Consistent, beautiful terminal output--## References--See `references/` for:-- `testing-structure.md` - Test organization patterns-- `api-structure.md` - FastAPI integration layout--See `examples/` for:-- `minimal-project/` - Simplest structure-- `full-project/` - Complete structure templatediff --git a/claude-plugin/atomic-agents/skills/atomic-tools/SKILL.md b/claude-plugin/atomic-agents/skills/atomic-tools/SKILL.mddeleted file mode 100644index b375ed2..0000000--- a/claude-plugin/atomic-agents/skills/atomic-tools/SKILL.md+++ /dev/null@@ -1,221 +0,0 @@-----description: This skill should be used when the user asks to "create a tool", "implement BaseTool", "add tool to agent", "tool orchestration", "external API tool", or needs guidance on tool development, tool configuration, error handling, and integrating tools with agents in Atomic Agents applications.------# Atomic Agents Tool Development--Tools extend agent capabilities by providing access to external services, APIs, databases, and computations. They follow a consistent pattern with input/output schemas and error handling.--## Tool Architecture--```-┌─────────────────────────────────────┐-│ BaseTool │-├─────────────────────────────────────┤-│ input_schema: BaseIOSchema │-│ output_schema: BaseIOSchema │-│ config: BaseToolConfig │-├─────────────────────────────────────┤-│ run(params) -> Output | Error │-└─────────────────────────────────────┘-```--## Basic Tool Template--```python-from atomic_agents.lib.base.base_tool import BaseTool, BaseToolConfig-from atomic_agents.lib.base.base_io_schema import BaseIOSchema-from pydantic import Field-from typing import Optional-import os--# ============================================================-# Schemas-# ============================================================--class MyToolInputSchema(BaseIOSchema):- """Input for the tool."""- query: str = Field(..., description="The query to process")--class MyToolOutputSchema(BaseIOSchema):- """Successful output."""- result: str = Field(..., description="The result")--class MyToolErrorSchema(BaseIOSchema):- """Error output."""- error: str = Field(..., description="Error message")- code: Optional[str] = Field(default=None, description="Error code")--# ============================================================-# Configuration-# ============================================================--class MyToolConfig(BaseToolConfig):- """Tool configuration."""- api_key: str = Field(- default_factory=lambda: os.getenv("MY_API_KEY", ""),- description="API key"- )- timeout: int = Field(default=30, description="Timeout in seconds")--# ============================================================-# Tool-# ============================================================--class MyTool(BaseTool):- """Tool description."""-- input_schema = MyToolInputSchema- output_schema = MyToolOutputSchema-- def __init__(self, config: MyToolConfig = None):- super().__init__(config or MyToolConfig())- self.config: MyToolConfig = self.config-- def run(self, params: MyToolInputSchema) -> MyToolOutputSchema | MyToolErrorSchema:- try:- # Tool logic here- result = f"Processed: {params.query}"- return MyToolOutputSchema(result=result)- except Exception as e:- return MyToolErrorSchema(error=str(e), code="ERROR")--# Convenience instance-tool = MyTool()-```--## Tool Configuration Pattern--```python-class APIToolConfig(BaseToolConfig):- """Configuration with environment variables."""-- api_key: str = Field(- default_factory=lambda: os.getenv("SERVICE_API_KEY", ""),- description="API key for the service"- )- base_url: str = Field(- default="https://api.service.com/v1",- description="Base URL for API"- )- timeout: int = Field(- default=30,- ge=1,- le=300,- description="Request timeout in seconds"- )- max_retries: int = Field(- default=3,- ge=0,- le=10,- description="Maximum retry attempts"- )-```--## Error Handling Pattern--Always return error schemas instead of raising exceptions:--```python-def run(self, params: InputSchema) -> OutputSchema | ErrorSchema:- # Validate configuration- if not self.config.api_key:- return ErrorSchema(- error="API key not configured",- code="CONFIG_ERROR"- )-- try:- # Make external call- response = requests.get(- f"{self.config.base_url}/endpoint",- params={"q": params.query},- headers={"Authorization": f"Bearer {self.config.api_key}"},- timeout=self.config.timeout- )- response.raise_for_status()- data = response.json()-- return OutputSchema(result=data["result"])-- except requests.Timeout:- return ErrorSchema(error="Request timed out", code="TIMEOUT")- except requests.HTTPError as e:- return ErrorSchema(error=f"HTTP error: {e}", code="HTTP_ERROR")- except Exception as e:- return ErrorSchema(error=str(e), code="UNKNOWN_ERROR")-```--## Using Tools with Agents--### Direct Tool Usage-```python-from my_tools import search_tool, SearchInputSchema--# Call tool directly-result = search_tool.run(SearchInputSchema(query="atomic agents"))-```--### Tool Orchestration Pattern-```python-from typing import Union-from atomic_agents.agents.base_agent import AtomicAgent, AgentConfig--# Define tool selection schema-class ToolCallSchema(BaseIOSchema):- tool_name: Literal["search", "calculate", "none"] = Field(- ..., description="Which tool to use"- )- tool_input: Union[SearchInput, CalculateInput, None] = Field(- ..., description="Input for the selected tool"- )--# Agent decides which tool to use-agent = AtomicAgent[UserQuerySchema, ToolCallSchema](config=config)--# Orchestration loop-user_input = UserQuerySchema(query="What is 2+2?")-tool_decision = agent.run(user_input)--if tool_decision.tool_name == "calculate":- result = calculator_tool.run(tool_decision.tool_input)-elif tool_decision.tool_name == "search":- result = search_tool.run(tool_decision.tool_input)-```--## Pre-Built Tools (Atomic Forge)--Download tools from Atomic Forge:--```bash-atomic download calculator-atomic download searxng-atomic download youtube-transcript-```--Available tools:-- **Calculator** - Mathematical operations-- **SearXNG** - Web search-- **Tavily** - AI-powered search-- **YouTube Transcript** - Video transcripts-- **Webpage Scraper** - HTML content extraction--## Tool Best Practices--1. **Always use BaseToolConfig** - For consistent configuration-2. **Environment variables for secrets** - Never hardcode API keys-3. **Return errors, don't raise** - Caller can handle gracefully-4. **Set timeouts** - Prevent hanging on external calls-5. **Validate inputs** - Check parameters before processing-6. **Include error codes** - Help with debugging and handling-7. **Document thoroughly** - Input/output schemas need descriptions--## References--See `references/` for:-- `api-integration.md` - Patterns for REST API tools-- `database-tools.md` - Database integration patterns--See `examples/` for:-- `simple-tool.py` - Minimal tool implementation-- `api-tool.py` - External API integrationdiff --git a/claude-plugin/atomic-agents/skills/atomic-tools/examples/api-tool.py b/claude-plugin/atomic-agents/skills/atomic-tools/examples/api-tool.pydeleted file mode 100644index 292a9a8..0000000--- a/claude-plugin/atomic-agents/skills/atomic-tools/examples/api-tool.py+++ /dev/null@@ -1,222 +0,0 @@-"""Example API tool with proper error handling and configuration."""--import os-import requests-from typing import Optional, List--from atomic_agents.lib.base.base_tool import BaseTool, BaseToolConfig-from atomic_agents.lib.base.base_io_schema import BaseIOSchema-from pydantic import Field---# ============================================================-# Schemas-# ============================================================--class WeatherInputSchema(BaseIOSchema):- """Input for weather lookup."""-- city: str = Field(- ...,- min_length=1,- description="City name to get weather for"- )- units: str = Field(- default="metric",- description="Units: 'metric' (Celsius) or 'imperial' (Fahrenheit)"- )---class WeatherOutputSchema(BaseIOSchema):- """Successful weather result."""-- city: str = Field(..., description="City name")- temperature: float = Field(..., description="Current temperature")- units: str = Field(..., description="Temperature units")- conditions: str = Field(..., description="Weather conditions")- humidity: int = Field(..., description="Humidity percentage")- wind_speed: float = Field(..., description="Wind speed")---class WeatherErrorSchema(BaseIOSchema):- """Weather API error."""-- error: str = Field(..., description="Error message")- code: str = Field(..., description="Error code")- city: Optional[str] = Field(default=None, description="Requested city")---# ============================================================-# Configuration-# ============================================================--class WeatherToolConfig(BaseToolConfig):- """Configuration for Weather Tool."""-- api_key: str = Field(- default_factory=lambda: os.getenv("OPENWEATHER_API_KEY", ""),- description="OpenWeatherMap API key"- )- base_url: str = Field(- default="https://api.openweathermap.org/data/2.5",- description="API base URL"- )- timeout: int = Field(- default=10,- ge=1,- le=60,- description="Request timeout in seconds"- )---# ============================================================-# Tool Implementation-# ============================================================--class WeatherTool(BaseTool):- """- Tool for fetching current weather conditions.-- Uses the OpenWeatherMap API to get current weather data- for a specified city.-- Requires OPENWEATHER_API_KEY environment variable.- """-- input_schema = WeatherInputSchema- output_schema = WeatherOutputSchema-- def __init__(self, config: WeatherToolConfig = None):- """Initialize the weather tool."""- super().__init__(config or WeatherToolConfig())- self.config: WeatherToolConfig = self.config-- def run(- self, params: WeatherInputSchema- ) -> WeatherOutputSchema | WeatherErrorSchema:- """- Fetch weather for a city.-- Args:- params: Input parameters with city and units-- Returns:- WeatherOutputSchema on success, WeatherErrorSchema on failure- """- # Validate configuration- if not self.config.api_key:- return WeatherErrorSchema(- error="OpenWeatherMap API key not configured",- code="CONFIG_ERROR",- city=params.city- )-- try:- # Make API request- response = requests.get(- f"{self.config.base_url}/weather",- params={- "q": params.city,- "appid": self.config.api_key,- "units": params.units,- },- timeout=self.config.timeout,- )-- # Handle HTTP errors- if response.status_code == 404:- return WeatherErrorSchema(- error=f"City '{params.city}' not found",- code="CITY_NOT_FOUND",- city=params.city- )-- response.raise_for_status()- data = response.json()-- # Parse response- return WeatherOutputSchema(- city=data["name"],- temperature=data["main"]["temp"],- units="°C" if params.units == "metric" else "°F",- conditions=data["weather"][0]["description"],- humidity=data["main"]["humidity"],- wind_speed=data["wind"]["speed"],- )-- except requests.Timeout:- return WeatherErrorSchema(- error="Request timed out",- code="TIMEOUT",- city=params.city- )- except requests.HTTPError as e:- return WeatherErrorSchema(- error=f"API error: {e}",- code="HTTP_ERROR",- city=params.city- )- except requests.RequestException as e:- return WeatherErrorSchema(- error=f"Network error: {e}",- code="NETWORK_ERROR",- city=params.city- )- except KeyError as e:- return WeatherErrorSchema(- error=f"Unexpected API response format: missing {e}",- code="PARSE_ERROR",- city=params.city- )- except Exception as e:- return WeatherErrorSchema(- error=f"Unexpected error: {e}",- code="UNKNOWN_ERROR",- city=params.city- )---# ============================================================-# Convenience Instance-# ============================================================--# Default instance with environment-based config-weather_tool = WeatherTool()---# ============================================================-# Usage Example-# ============================================================--if __name__ == "__main__":- from rich.console import Console- from rich.table import Table-- console = Console()-- # Create tool- tool = WeatherTool()-- # Test cities- cities = ["London", "New York", "Tokyo", "InvalidCity123"]-- table = Table(title="Weather Results")- table.add_column("City", style="cyan")- table.add_column("Temperature", style="green")- table.add_column("Conditions", style="yellow")- table.add_column("Status", style="bold")-- for city in cities:- result = tool.run(WeatherInputSchema(city=city))-- if isinstance(result, WeatherErrorSchema):- table.add_row(city, "-", "-", f"[red]{result.code}[/red]")- else:- table.add_row(- result.city,- f"{result.temperature}{result.units}",- result.conditions,- "[green]OK[/green]"- )-- console.print(table)diff --git a/claude-plugin/atomic-agents/skills/framework/SKILL.md b/claude-plugin/atomic-agents/skills/framework/SKILL.mdnew file mode 100644index 0000000..58ff9c9--- /dev/null+++ b/claude-plugin/atomic-agents/skills/framework/SKILL.md@@ -0,0 +1,129 @@+---+name: framework+description: Guide for the Atomic Agents Python framework — schemas, agents, tools, context providers, prompts, orchestration, and provider configuration. Use when code imports from `atomic_agents`, defines an `AtomicAgent`, `BaseTool`, or `BaseIOSchema`, or the user asks about multi-agent orchestration or LLM-provider wiring in an atomic-agents project.+---++# Atomic Agents Framework++Atomic Agents is a lightweight Python framework for building LLM applications with typed, structured input and output. It layers on top of [Instructor](https://python.useinstructor.com) and Pydantic so every interaction between user, agent, tool, and context is a validated schema.++This skill orients Claude on the framework and routes to focused reference files as the task requires.++## Core abstractions++| Concept | Class | Role |+|---|---|---|+| Schema | `BaseIOSchema` | Typed input/output contract — every agent/tool I/O is one |+| Agent | `AtomicAgent[In, Out]` | LLM-backed transformer from input schema to output schema |+| Config | `AgentConfig` | Wires client, model, history, prompt, roles, API params |+| Prompt | `SystemPromptGenerator` | Three-section prompt: background, steps, output_instructions |+| History | `ChatHistory` | Conversation state, serializable, token-counted |+| Tool | `BaseTool[In, Out]` | Deterministic capability the agent can invoke |+| Context | `BaseDynamicContextProvider` | Dynamic section injected into the system prompt at runtime |++All communication between these uses `BaseIOSchema` subclasses with **docstring-required** descriptions.++## Canonical imports++```python+from atomic_agents import (+ AtomicAgent, AgentConfig,+ BasicChatInputSchema, BasicChatOutputSchema,+ BaseIOSchema, BaseTool, BaseToolConfig,+)+from atomic_agents.context import (+ ChatHistory, Message,+ SystemPromptGenerator, BaseDynamicContextProvider,+)+# Optional: MCP interop+from atomic_agents.connectors.mcp import fetch_mcp_tools, MCPTransportType+```++Do not use legacy paths like `atomic_agents.lib.base.*` or `atomic_agents.agents.base_agent` — those were retired. Import from the top-level package where possible.++## Minimum viable agent++```python+import os, instructor, openai+from atomic_agents import AtomicAgent, AgentConfig, BasicChatInputSchema, BasicChatOutputSchema+from atomic_agents.context import ChatHistory++client = instructor.from_openai(openai.OpenAI(api_key=os.environ["OPENAI_API_KEY"]))++agent = AtomicAgent[BasicChatInputSchema, BasicChatOutputSchema](+ config=AgentConfig(+ client=client,+ model="gpt-5-mini",+ history=ChatHistory(),+ )+)++reply = agent.run(BasicChatInputSchema(chat_message="Hello"))+print(reply.chat_message)+```++`AtomicAgent` and `BaseTool` use PEP 695 generics — the type parameters carry runtime information, so write them explicitly and keep them accurate. Full runnable version: `atomic-examples/quickstart/quickstart/1_0_basic_chatbot.py`.++## Decision routing++Pick the reference file that matches the task. Each is loaded only when read.++| Task | Reference |+|---|---|+| Design or validate an input/output schema | [references/schemas.md](references/schemas.md) |+| Build, configure, or run an agent | [references/agents.md](references/agents.md) |+| Write a tool the agent will invoke | [references/tools.md](references/tools.md) |+| Inject dynamic data into the system prompt | [references/context-providers.md](references/context-providers.md) |+| Structure the system prompt | [references/prompts.md](references/prompts.md) |+| Coordinate multiple agents | [references/orchestration.md](references/orchestration.md) |+| Manage conversation state and multi-agent memory | [references/memory.md](references/memory.md) |+| Register telemetry, retries, or logging | [references/hooks.md](references/hooks.md) |+| Swap LLM provider or configure roles | [references/providers.md](references/providers.md) |+| Decide the project layout or `pyproject.toml` | [references/project-structure.md](references/project-structure.md) |+| Write tests for agents and tools | [references/testing.md](references/testing.md) |++When a concept is unclear, start from the user's verb: *create a schema* → schemas, *hook up a weather API* → tools, *inject user name into prompt* → context providers, *route between agents* → orchestration.++## Working style++Follow these defaults unless the project says otherwise. The reference files go deeper on each.++**Schemas are the contract.** Design the `BaseIOSchema` pair before writing the agent. Field descriptions flow into the LLM prompt via Instructor, so write them for the model, not just the developer. Every subclass needs a non-empty docstring — the framework enforces this at class-definition time.++**System prompts have three sections.** Use `SystemPromptGenerator(background=..., steps=..., output_instructions=...)`. Put persona in `background`, the ordered procedure in `steps`, and output-format rules in `output_instructions`. The agent falls back to a sensible default when omitted.++**Wrap the provider client with Instructor.** Always. `instructor.from_openai(...)`, `instructor.from_anthropic(...)`, `instructor.from_genai(...)` — without this the agent cannot enforce output schemas.++**Use `model_api_parameters` for provider knobs.** `temperature`, `max_tokens`, `reasoning_effort`, etc. live in the `model_api_parameters` dict on `AgentConfig`, not on the agent itself.++**Errors and retries flow through hooks.** Register handlers for `parse:error`, `completion:error`, `completion:last_attempt` rather than wrapping `run()` in try/except. See `references/hooks.md`.++**Tools return the output schema on success.** Failure should surface as validation errors or typed result schemas the caller pattern-matches on — don't raise through `run()` unless the failure is truly unrecoverable.++## When the user is starting from nothing++Scaffolding a brand-new project (fresh directory, `pyproject.toml`, first agent) is handled by the sibling skill `new-app`. Suggest it when the user says "new project", "start from scratch", or equivalent.++When reviewing or auditing existing code, the sibling skill `review` applies the Atomic-Agents-specific checklist.++## Versioning and compatibility++- Python 3.12+ (PEP 695 generics are used internally).+- Instructor 1.14+ with provider extras (`instructor[openai]`, `instructor[anthropic]`, etc.) — the workspace uses Instructor's extras to pull provider SDKs.+- Pydantic 2.+- For MCP interop, see `atomic_agents.connectors.mcp` — `fetch_mcp_tools`, `MCPFactory`, `MCPTransportType` are stable.++## Anti-patterns (surface these in review)++- Plain `BaseModel` instead of `BaseIOSchema`.+- Missing docstrings on `BaseIOSchema` subclasses (framework raises at import).+- `Field(..., description="...")` missing — Instructor leans on descriptions for prompt generation.+- Raw provider client (not wrapped in Instructor).+- Hardcoded API keys instead of env vars.+- Unbounded `ChatHistory` on long-running sessions.+- Blocking I/O inside `BaseDynamicContextProvider.get_info()` — it runs on every `agent.run()`.+- Catching `ValidationError` to hide schema problems instead of fixing descriptions or constraints.+- `MCPTransportType.STREAMABLE_HTTP` — the correct value is `HTTP_STREAM`.+- `ChatHistory.load(...)` called as a classmethod — it is an instance method that mutates self.++For deeper guidance load the relevant reference file above. For code-review runs, switch to the `review` skill.diff --git a/claude-plugin/atomic-agents/skills/framework/references/agents.md b/claude-plugin/atomic-agents/skills/framework/references/agents.mdnew file mode 100644index 0000000..09bec5b--- /dev/null+++ b/claude-plugin/atomic-agents/skills/framework/references/agents.md@@ -0,0 +1,138 @@+# Agents (`AtomicAgent` + `AgentConfig`)++## Contents+- Config anatomy+- Creating the agent (generics)+- Execution modes (sync, async, streaming)+- Token counting+- History and hooks (deep dives)+- Registering context providers+- Common mistakes++## Config anatomy++```python+from atomic_agents import AgentConfig+from atomic_agents.context import ChatHistory, SystemPromptGenerator+from instructor import Mode++config = AgentConfig(+ client=client, # required: instructor-wrapped client+ model="gpt-5-mini", # required: model id+ history=ChatHistory(), # optional: omit for stateless agents+ system_prompt_generator=SystemPromptGenerator(+ background=["You are a concise research assistant."],+ steps=["Understand the question.", "Search memory.", "Answer directly."],+ output_instructions=["Reply under 100 words.", "Cite sources when used."],+ ),+ system_role="system", # None = no system prompt sent+ assistant_role="assistant", # "model" for Gemini; default works for OpenAI/Anthropic+ tool_result_role=None, # auto-detected; override for odd providers+ mode=Mode.TOOLS, # Instructor mode — TOOLS / JSON / GENAI_TOOLS / …+ model_api_parameters={"temperature": 0.2, "max_tokens": 2048},+)+```++Match `mode` on `AgentConfig` to the Instructor factory mode. If the factory was built with `mode=Mode.JSON` but `AgentConfig.mode=Mode.TOOLS` (the default), the agent will format tools the provider doesn't accept. See `providers.md` for the per-provider matrix.++`assistant_role` must be `"model"` for Gemini; every other supported provider uses `"assistant"`.++## Creating the agent++Generics carry runtime information — write the types explicitly:++```python+from atomic_agents import AtomicAgent++agent = AtomicAgent[MyInput, MyOutput](config=config)+```++The PEP 695 generic parameters are the source of truth for both the agent and `BaseTool`. Do not rely on subclass-level `input_schema` / `output_schema` class attributes — the generic parameters feed `BaseTool.__init_subclass__` and populate the property at runtime.++## Execution modes++```python+# Sync single-shot+out: MyOutput = agent.run(MyInput(...))++# Sync, no new user input — rerun over existing history (see memory.md)+out = agent.run()++# Async single-shot+out = await agent.run_async(MyInput(...))++# Sync streaming — yields progressively-filled partials+for partial in agent.run_stream(MyInput(...)):+ ...++# Async streaming+async for partial in agent.run_async_stream(MyInput(...)):+ ...+```++Streaming partials are instances of `MyOutput` with a subset of fields populated; validators fire as fields appear, so keep them cheap. Working examples: `atomic-examples/quickstart/quickstart/1_1_basic_chatbot_streaming.py` (sync) and `1_2_basic_chatbot_async_streaming.py` (async, with Rich `Live` rendering).++## Token counting++```python+info = agent.get_context_token_count()+info.total # total tokens in the next request+info.system_prompt # system-prompt tokens+info.history # history tokens+info.tools # tokens consumed by tool definitions (TOOLS modes)+info.model # tokenizer/model the count was computed against+info.max_tokens # model's max context (None if unknown)+info.utilization # float in [0, 1], or None+```++Use this to gate long operations or decide when to summarize history. Works across providers that Instructor can tokenize.++## History and hooks++History and hooks are large enough that each has its own reference:++- **[memory.md](memory.md)** — `ChatHistory` turn model, persistence (`dump()` / `load()`), `copy()`, `delete_turn_id()`, multimodal content, multi-agent patterns (shared, independent, agent-to-agent, supervisor).+- **[hooks.md](hooks.md)** — the five events (`parse:error`, `completion:kwargs`, `completion:response`, `completion:error`, `completion:last_attempt`), retry patterns, telemetry, production logging.++Short recap for inline use:++```python+# History+history = ChatHistory()+agent.run(BasicChatInputSchema(chat_message="Question 1"))+agent.run(BasicChatInputSchema(chat_message="Question 2")) # accumulates+agent.reset_history()++# Hooks+def on_parse_error(error): ...+agent.register_hook("parse:error", on_parse_error)+```++Full working hooks example: `atomic-examples/hooks-example/hooks_example/main.py`.++## Registering context providers++```python+from atomic_agents.context import BaseDynamicContextProvider++class UserCtx(BaseDynamicContextProvider):+ def __init__(self):+ super().__init__(title="User Context")+ self.name = ""++ def get_info(self) -> str:+ return f"Current user: {self.name or 'anonymous'}"++agent.register_context_provider("user", UserCtx())+agent.context_providers["user"].name = "Alice" # dynamic update before next run+```++See `context-providers.md` for patterns (RAG, time, session, cached database schema).++## Common mistakes++- Forgetting to wrap the client with `instructor.from_*` — structured outputs silently stop working.+- Passing a raw Pydantic `BaseModel` as an input/output type — must be `BaseIOSchema`.+- Using `assistant_role="assistant"` with Gemini — Gemini requires `"model"`.+- `AgentConfig.mode` out of sync with the Instructor factory mode — tools get formatted the provider can't accept.+- Unbounded `ChatHistory` in a long-running service — monitor `get_context_token_count().utilization` or set `max_messages`.diff --git a/claude-plugin/atomic-agents/skills/framework/references/context-providers.md b/claude-plugin/atomic-agents/skills/framework/references/context-providers.mdnew file mode 100644index 0000000..5ff6b3d--- /dev/null+++ b/claude-plugin/atomic-agents/skills/framework/references/context-providers.md@@ -0,0 +1,190 @@+# Context Providers (`BaseDynamicContextProvider`)++## Contents+- What they do+- Writing a provider+- Registering, updating, sharing+- Patterns: user, time, RAG, session, cached DB schema+- Dynamic updates inside a run loop+- Async data sources+- Common mistakes++## What they do++A context provider injects a named, titled block into the agent's system prompt at each `run()`. The base prompt stays static; the context is what changes.++Every `SystemPromptGenerator` section is followed by registered providers, rendered as:++```+## <provider title>+<get_info() output>+```++## Writing a provider++Subclass `BaseDynamicContextProvider`, set the title in `super().__init__`, implement `get_info()`:++```python+from atomic_agents.context import BaseDynamicContextProvider++class UserCtx(BaseDynamicContextProvider):+ def __init__(self):+ super().__init__(title="User Context")+ self.name: str = ""+ self.role: str = ""++ def get_info(self) -> str:+ if not self.name:+ return "No user is logged in."+ return f"User: {self.name} (role: {self.role})"+```++`get_info()` must return a string and must be fast — it runs on every `agent.run()`.++## Registering, updating, sharing++```python+ctx = UserCtx()+agent.register_context_provider("user", ctx)++# Update before running+ctx.name = "Alice"; ctx.role = "admin"+agent.run(...)++# Inspect / unregister+"user" in agent.context_providers+agent.unregister_context_provider("user")+```++One provider instance can be registered with many agents — updates propagate everywhere:++```python+shared = SessionCtx()+agent_a.register_context_provider("session", shared)+agent_b.register_context_provider("session", shared)+shared.set("locale", "en-GB") # visible to both agents+```++## Patterns++**Time**++```python+from datetime import datetime, timezone++class TimeCtx(BaseDynamicContextProvider):+ def __init__(self):+ super().__init__(title="Current Time")++ def get_info(self) -> str:+ return datetime.now(timezone.utc).isoformat()+```++**RAG retrieval**++Update outside the provider, read inside.++```python+class RAGCtx(BaseDynamicContextProvider):+ def __init__(self):+ super().__init__(title="Retrieved Documents")+ self.docs: list[dict] = []++ def set(self, docs: list[dict]) -> None:+ self.docs = docs++ def get_info(self) -> str:+ if not self.docs:+ return "No relevant documents retrieved."+ return "\n\n".join(+ f"[{d['source']}] {d['content']}" for d in self.docs+ )++# Orchestration+rag.set(vector_db.search(query, k=4))+agent.run(query_input)+```++**Session**++```python+class SessionCtx(BaseDynamicContextProvider):+ def __init__(self):+ super().__init__(title="Session")+ self._data: dict[str, str] = {}++ def set(self, key: str, value: str) -> None:+ self._data[key] = value++ def get_info(self) -> str:+ if not self._data:+ return "No session state."+ return "\n".join(f"- {k}: {v}" for k, v in self._data.items())+```++**Cached database schema**++Providers are called on every run, so cache slow sources:++```python+import time++class DBSchemaCtx(BaseDynamicContextProvider):+ def __init__(self, conn, ttl_seconds: int = 300):+ super().__init__(title="Database Schema")+ self._conn = conn+ self._ttl = ttl_seconds+ self._cached: str = ""+ self._at: float = 0.0++ def get_info(self) -> str:+ now = time.time()+ if not self._cached or now - self._at > self._ttl:+ self._cached = render_schema(self._conn)+ self._at = now+ return self._cached+```++## Dynamic updates inside a run loop++Context providers are most powerful when mutated between calls. A research loop updates the `ScrapedContentContextProvider` after each scrape, then re-runs the agent with the new facts in prompt — see `atomic-examples/deep-research/deep_research/context_providers.py` and the main loop in `deep_research/main.py` for a working reference.++```python+ctx = ScrapedContentCtx()+agent.register_context_provider("scraped", ctx)++while not done:+ ctx.set(scrape(next_url)) # mutate provider state+ decision = agent.run(NextStep(...)) # provider renders fresh context+ done = decision.stop+```++The key property: register the provider once, mutate its fields between `agent.run()` calls, and the rendered prompt picks up the change automatically.++## Async data sources++`get_info()` is synchronous. When the data source is async, refresh before calling the agent:++```python+class AsyncCtx(BaseDynamicContextProvider):+ def __init__(self):+ super().__init__(title="Async Data")+ self._cached = ""++ async def refresh(self) -> None:+ self._cached = format(await fetch_remote())++ def get_info(self) -> str:+ return self._cached++await ctx.refresh()+await agent.run_async(input_data)+```++## Common mistakes++- Slow I/O in `get_info()` — runs on every `agent.run()`.+- Returning a non-string from `get_info()` — raises at prompt time.+- Forgetting to register the provider after creating it — context silently missing.+- Duplicate titles across providers — they collide in the rendered prompt; use distinct titles.+- Storing secrets in the context — they end up in every LLM request. Inject only what the model needs to reason about.diff --git a/claude-plugin/atomic-agents/skills/framework/references/hooks.md b/claude-plugin/atomic-agents/skills/framework/references/hooks.mdnew file mode 100644index 0000000..662615b--- /dev/null+++ b/claude-plugin/atomic-agents/skills/framework/references/hooks.md@@ -0,0 +1,174 @@+# Hooks++## Contents+- The five events+- Registration and management+- Telemetry pattern+- Validation-error inspection+- Retry pattern+- Production logging+- Common mistakes++Atomic Agents surfaces Instructor's hook system on every agent. Use hooks for telemetry, validation-error inspection, retries, and logging rather than wrapping `run()` in `try/except`.++Full working example in the repo: `atomic-examples/hooks-example/hooks_example/main.py`.++## The five events++| Event | Fires | Handler receives |+|---|---|---|+| `completion:kwargs` | Before the model call | Full kwargs dict (model, messages, `response_model`, tools, …) |+| `completion:response` | After a successful model response | Raw completion object |+| `completion:error` | On any provider/HTTP error | Exception instance |+| `parse:error` | When Pydantic validation fails on the parsed response | `ValidationError` instance |+| `completion:last_attempt` | On the final retry before `run()` raises | Exception instance |++`parse:error` fires *before* Instructor retries. If Instructor's built-in retry succeeds, `completion:response` fires and `parse:error` does not re-fire for that call.++## Registration and management++```python+def on_response(resp): ...+def on_error(err): ...++agent.register_hook("completion:response", on_response)+agent.register_hook("completion:error", on_error)++# Remove one handler+agent.unregister_hook("completion:error", on_error)++# Clear all handlers for an event+agent.clear_hooks("completion:error")++# Clear every registered handler+agent.clear_hooks()++# Toggle without unregistering+agent.disable_hooks()+agent.run(input_data) # hooks skipped+agent.enable_hooks()++agent.hooks_enabled # bool property, not a method+```++Keep handlers cheap. They run synchronously in the request path — a slow logger delays every `run()`.++## Telemetry pattern++```python+import time++metrics = {"requests": 0, "errors": 0, "parse_errors": 0, "total_ms": 0.0}+_t0: float | None = None++def on_kwargs(**_):+ global _t0+ _t0 = time.perf_counter()+ metrics["requests"] += 1++def on_response(_resp, **_):+ metrics["total_ms"] += (time.perf_counter() - _t0) * 1000++def on_parse_error(_err, **_):+ metrics["parse_errors"] += 1++def on_error(_err, **_):+ metrics["errors"] += 1++agent.register_hook("completion:kwargs", on_kwargs)+agent.register_hook("completion:response", on_response)+agent.register_hook("parse:error", on_parse_error)+agent.register_hook("completion:error", on_error)+```++## Validation-error inspection++```python+from pydantic import ValidationError++def on_parse_error(error):+ if isinstance(error, ValidationError):+ for err in error.errors():+ loc = ".".join(map(str, err["loc"]))+ kind = err["type"]+ msg = err["msg"]+ logger.warning("LLM produced invalid field %s (%s): %s", loc, kind, msg)+```++Pydantic's `err["type"]` (`"missing"`, `"string_too_short"`, `"literal_error"`, …) identifies what the model got wrong. Use it to sharpen field `description=` text or tighten `Literal` sets.++## Retry pattern++Instructor already retries `parse:error` internally (`max_retries` on the client). For provider-level failures (429, 5xx, timeouts) use hooks + an outer loop:++```python+import time++class Retrier:+ def __init__(self, max_attempts=3, base_delay=1.0):+ self.max_attempts = max_attempts+ self.base_delay = base_delay+ self.attempt = 0++ def on_error(self, error):+ self.attempt += 1+ msg = str(error).lower()+ if self.attempt < self.max_attempts and any(+ t in msg for t in ("rate limit", "timeout", "503", "502", "504")+ ):+ time.sleep(self.base_delay * (2 ** (self.attempt - 1)))++ def on_success(self, _resp):+ self.attempt = 0++def run_with_retry(agent, inp, r: Retrier):+ r.attempt = 0+ while True:+ try:+ return agent.run(inp)+ except Exception:+ if r.attempt >= r.max_attempts:+ raise++r = Retrier()+agent.register_hook("completion:error", r.on_error)+agent.register_hook("completion:response", r.on_success)+```++## Production logging++One handler per concern; register them at agent construction time.++```python+import logging, uuid+log = logging.getLogger("agent")++class RequestLogger:+ def __init__(self):+ self.request_id: str = ""++ def on_kwargs(self, **kwargs):+ self.request_id = str(uuid.uuid4())+ log.info("agent.call", extra={"request_id": self.request_id, "model": kwargs.get("model")})++ def on_response(self, _resp):+ log.info("agent.ok", extra={"request_id": self.request_id})++ def on_error(self, error):+ log.error("agent.error", extra={"request_id": self.request_id, "error": str(error)})++rl = RequestLogger()+agent.register_hook("completion:kwargs", rl.on_kwargs)+agent.register_hook("completion:response", rl.on_response)+agent.register_hook("completion:error", rl.on_error)+```++Don't log full request/response payloads — they can contain user PII and inflate log volume. Log the `request_id` + model + timing and correlate with upstream logs.++## Common mistakes++- Raising from inside a hook — hook exceptions propagate and can mask the original error. Log and return.+- Doing slow I/O in a hook — blocks every `run()`. Push to a queue if the work is heavy.+- Assuming `parse:error` fires on every validation failure — Instructor's internal retry may resolve it before the handler sees a definitive failure. Pair with `completion:last_attempt` for final-failure signals.+- Using `agent.hooks_enabled()` — it is a read-only **property**, not a method. Drop the parentheses.+- Registering the same handler twice — duplicates run twice. `unregister_hook` the old one first.diff --git a/claude-plugin/atomic-agents/skills/framework/references/memory.md b/claude-plugin/atomic-agents/skills/framework/references/memory.mdnew file mode 100644index 0000000..0ac7e8e--- /dev/null+++ b/claude-plugin/atomic-agents/skills/framework/references/memory.md@@ -0,0 +1,163 @@+# Memory and Chat History (`ChatHistory`)++## Contents+- The turn model+- Creating and wiring history+- Automatic memory management during `run()`+- Persistence — `dump()` / `load()` / `copy()`+- Overflow and manipulation (`max_messages`, `delete_turn_id`)+- Multimodal content in history+- Multi-agent patterns (shared, independent, agent-to-agent, supervisor)+- Common mistakes++Working example in the repo: `atomic-examples/fastapi-memory/` and the "Memory" guide at `docs/guides/memory.md` (authoritative deep-dive).++## The turn model++Every `agent.run()` produces **one turn**. A turn groups the user message and the assistant response — and any intermediate messages (tool results, context injections) — under a shared `turn_id` (UUID). Messages are `Message(role, content, turn_id)` where `content` is always a `BaseIOSchema` instance.++Key implications:++- Turns are deleted atomically via `history.delete_turn_id(id)`.+- `history.current_turn_id` tracks the latest turn. `initialize_turn()` rotates it.+- When `agent.run(None)` is called, it reuses existing history without adding a new user message — useful for agent-to-agent loops (see below).++## Creating and wiring history++```python+from atomic_agents import AtomicAgent, AgentConfig+from atomic_agents.context import ChatHistory++history = ChatHistory() # unbounded+history = ChatHistory(max_messages=40) # FIFO overflow++# Optional: seed with an assistant intro so the first user turn has something to reply to+history.add_message("assistant", BasicChatOutputSchema(chat_message="Hi!"))++agent = AtomicAgent[In, Out](config=AgentConfig(client=client, model="gpt-5-mini", history=history))+```++Omit `history` entirely for stateless agents — each `run()` is independent.++## Automatic memory management++`agent.run(user_input)` does, in order:++1. Call `history.initialize_turn()` to create a new `turn_id`.+2. Append the user message to history under that turn.+3. Call the model with the full history + system prompt.+4. Parse the response into `OutputSchema`.+5. Append the assistant message to history under the same `turn_id`.++That means:++- History accumulates automatically. Do not call `add_message` for the assistant response — it is added by `run()`.+- `history.delete_turn_id(agent.history.current_turn_id)` undoes the last exchange (both user and assistant messages in one call).+- `run(None)` skips step 2 and re-runs the model over whatever is in history. Useful to let the model continue after a manually-injected message.++## Persistence++`dump()` returns a JSON **string**. `load(s)` mutates the instance in place.++```python+# Save+blob: str = history.dump()+open("session.json", "w").write(blob)++# Restore+restored = ChatHistory()+restored.load(open("session.json").read())++# Clone+clone = history.copy() # fully independent copy via dump/load+```++`load()` re-imports the schema classes by fully qualified name (stored in the dumped payload), so the same module layout must be importable at load time.++## Overflow and manipulation++```python+history = ChatHistory(max_messages=20) # drop oldest when exceeded++history.get_message_count() # -> int+history.get_history() # -> list[dict] (role + JSON content)+history.delete_turn_id(turn_id) # remove one turn; raises if not found+history.get_current_turn_id() # -> Optional[str]++agent.reset_history() # wipe and restore the initial seed+```++For token-aware trimming (rather than message-count), use `agent.get_context_token_count()` to check utilization and either delete old turns or summarize them into a single synthetic message before continuing.++## Multimodal content++History handles Instructor's multimodal types (`Image`, `Audio`, `PDF`) transparently. Include them inside a `BaseIOSchema` field:++```python+from instructor.processing.multimodal import Image+from atomic_agents import BaseIOSchema+from pydantic import Field++class VisualQuery(BaseIOSchema):+ """Question plus an image."""+ question: str = Field(..., description="User question.")+ image: Image = Field(..., description="Input image.")++history.add_message("user", VisualQuery(question="What is this?", image=Image.from_path("x.jpg")))+```++`dump()` / `load()` round-trip multimodal content. `get_history()` returns a mixed array of JSON + multimodal objects that Instructor consumes directly. See `atomic-examples/basic-multimodal/` for a full example.++## Multi-agent patterns++The framework guide (`docs/guides/memory.md`) names five canonical patterns. The three most common:++### Shared history++Two agents participate in one conversation.++```python+shared = ChatHistory()+router = AtomicAgent[In, RouteOut](config=AgentConfig(client=c, model=m, history=shared))+worker = AtomicAgent[In, WorkOut](config=AgentConfig(client=c, model=m, history=shared))+```++Only safe when the agents run **sequentially** on the same thread. Concurrent runs against one history race.++### Independent histories++Each agent has its own `ChatHistory()`. Outputs are passed via typed schemas at the call site. Default for multi-agent orchestration — keeps state contained.++### Agent-to-agent messaging (addresses [GitHub issue #58](https://github.com/BrainBlend-AI/atomic-agents/issues/58))++Each agent keeps its own history; the orchestrator manually injects the other agent's output as a `"user"` message and calls `run(None)` to let the recipient continue.++```python+writer = AtomicAgent[WriterIn, WriterOut](config=AgentConfig(..., history=ChatHistory()))+reviewer = AtomicAgent[ReviewerIn, ReviewerOut](config=AgentConfig(..., history=ChatHistory()))++draft = writer.run(WriterIn(task="draft a product description"))+for _ in range(3):+ verdict = reviewer.run(ReviewerIn(content_to_review=draft.content))+ if verdict.approved:+ break+ # Inject reviewer feedback into writer's own history+ writer.history.add_message(+ "user",+ WriterIn(task=f"Revise based on feedback: {verdict.feedback}")+ )+ draft = writer.run() # run(None) — continues with injected message in context+```++### Supervisor-worker via context providers++When multiple workers should share a fact (current user, selected dataset, etc.) but not a full history, use a `BaseDynamicContextProvider` registered on each. See `context-providers.md`.++## Common mistakes++- Sharing one `ChatHistory` across concurrent agents — messages interleave and corrupt turns.+- Calling `ChatHistory.load(saved)` as a classmethod — `load` is an **instance** method; construct first, then `.load(...)`.+- Treating `dump()` output as a dict — it's a JSON **string**; parse it with `json.loads` before inspection.+- Storing secrets inside `BaseIOSchema` content — they will be serialized by `dump()` and replayed on every `run()`.+- Unbounded `ChatHistory` in long-running services — set `max_messages` or monitor `agent.get_context_token_count().utilization`.+- Expecting `run(None)` to work without seeded history — it needs existing messages to respond to.diff --git a/claude-plugin/atomic-agents/skills/framework/references/orchestration.md b/claude-plugin/atomic-agents/skills/framework/references/orchestration.mdnew file mode 100644index 0000000..33aeae3--- /dev/null+++ b/claude-plugin/atomic-agents/skills/framework/references/orchestration.md@@ -0,0 +1,154 @@+# Orchestration Patterns++## Contents+- Pattern selector+- Single agent+- Sequential pipeline+- Parallel fan-out+- Router+- Supervisor / validate-and-retry+- Search + execute (large tool surface)+- Shared context between agents+- Common mistakes++## Pattern selector++| Situation | Pattern | Working example |+|---|---|---|+| One transformation, no collaboration | Single agent | `atomic-examples/quickstart/` |+| Stages where each refines the last | Sequential pipeline | `atomic-examples/deep-research/` |+| Independent lookups that can run at the same time | Parallel fan-out | — |+| Classify request, then route to specialized agent | Router | `atomic-examples/orchestration-agent/` |+| Quality gate / iterative refinement | Supervisor | — |+| Large tool catalog (dozens+) | Search + execute | `atomic-examples/progressive-disclosure/` |++Pick one, start minimal, compose only when the simpler shape stops working.++## Single agent++Already the default. Shown here for completeness:++```python+reply = agent.run(MyInput(...))+```++## Sequential pipeline++Each stage's output is the next stage's input. Types line up — Python checks it statically, the LLM runtime catches misalignments.++```python+extracted = extractor.run(RawDoc(text=doc)) # RawDoc -> Entities+scored = scorer.run(ScoreQuery(entities=extracted.entities))+summary = summarizer.run(SummaryReq(scored=scored))+```++Use typed adapters when shapes don't align:++```python+def entities_to_score_query(e: Entities) -> ScoreQuery:+ return ScoreQuery(entities=e.entities, threshold=0.7)+```++## Parallel fan-out++For independent lookups, `asyncio.gather`:++```python+import asyncio++async def enrich(query):+ docs_task = asyncio.create_task(doc_agent.run_async(DocLookup(q=query)))+ users_task = asyncio.create_task(user_agent.run_async(UserLookup(q=query)))+ docs, users = await asyncio.gather(docs_task, users_task)+ return await summary_agent.run_async(Summary(docs=docs.items, users=users.items))+```++Each agent gets its own `ChatHistory` (or none at all). Sharing `ChatHistory` across concurrent agents corrupts state.++## Router++One agent classifies, others handle. Model the classification as a discriminated output:++```python+from typing import Literal, Union+from pydantic import Field++class BillingRoute(BaseIOSchema):+ """Route to the billing agent."""+ topic: Literal["billing"] = "billing"+ normalized_question: str = Field(..., description="Rewritten for the billing agent.")++class TechRoute(BaseIOSchema):+ """Route to the tech-support agent."""+ topic: Literal["tech"] = "tech"+ normalized_question: str = Field(..., description="Rewritten for the tech-support agent.")++class Routing(BaseIOSchema):+ """Routing decision."""+ choice: Union[BillingRoute, TechRoute] = Field(..., description="Routed agent and payload.")++router = AtomicAgent[UserQuery, Routing](config=router_cfg)++decision = router.run(query)+if isinstance(decision.choice, BillingRoute):+ reply = billing_agent.run(...)+else:+ reply = tech_agent.run(...)+```++## Supervisor / validate-and-retry++Useful when a second LLM pass validates the first. The supervisor returns a typed verdict; loop until the verdict is "accept".++```python+draft = writer.run(DraftRequest(topic="Atomic Agents"))+for _ in range(3):+ verdict = reviewer.run(ReviewReq(draft=draft.text))+ if verdict.accept:+ break+ draft = writer.run(DraftRequest(topic="Atomic Agents", revise_notes=verdict.notes))+```++Cap the loop — a bad prompt can oscillate forever.++## Search + execute (large tool surface)++When the agent has access to many tools (dozens or hundreds, e.g. MCP server with a big API), exposing them all blows up the prompt. Split into two tools: `search_actions(intent) -> [candidate_ids]` and `execute_action(id, args)`.++```python+class SearchActions(BaseIOSchema):+ """Find candidate actions by intent."""+ intent: str = Field(..., description="Natural-language intent.")++class ActionCandidates(BaseIOSchema):+ """Matched action IDs."""+ ids: list[str] = Field(..., description="Ordered by relevance.")++class ExecuteAction(BaseIOSchema):+ """Run a specific action by ID."""+ id: str = Field(..., description="Action ID from search.")+ args: dict = Field(default_factory=dict, description="JSON-shaped args.")+```++The host holds the full catalog internally. The LLM only sees the two tools. Context stays lean. Full implementation (three MCP servers, 24 tools, ~92% token reduction on definitions) in `atomic-examples/progressive-disclosure/`.++## Shared context between agents++Register the same provider instance on multiple agents. Updates propagate:++```python+session = SessionCtx()+router.register_context_provider("session", session)+billing_agent.register_context_provider("session", session)+tech_agent.register_context_provider("session", session)+```++This is cheaper than passing session state through every schema.++## Common mistakes++- Sharing `ChatHistory` between parallel agents — races and stale messages.+- Hidden coupling between agents via file paths or globals — put shared state behind a context provider or explicit schema.+- Router that returns a free-text "topic" instead of a discriminated union — loses type safety.+- Supervisor loops with no upper bound — cap them.+- Sequential pipelines that silently drop fields between stages — use typed adapters.diff --git a/claude-plugin/atomic-agents/skills/framework/references/project-structure.md b/claude-plugin/atomic-agents/skills/framework/references/project-structure.mdnew file mode 100644index 0000000..ebdbe3a--- /dev/null+++ b/claude-plugin/atomic-agents/skills/framework/references/project-structure.md@@ -0,0 +1,188 @@+# Project Structure++## Contents+- Size-based layouts+- `pyproject.toml` template+- Configuration pattern+- Environment and `.gitignore`+- Naming conventions++## Size-based layouts++Pick the smallest layout that fits. Grow into the next tier when the current one feels cramped.++### Single-agent script (prototyping)++```+my_app/+├── pyproject.toml+├── .env.example+├── .gitignore+├── README.md+└── my_app/+ ├── __init__.py+ ├── main.py # entry + agent setup+ └── schemas.py # input/output schemas+```++### Medium app (a few agents, one or two tools)++```+my_app/+├── pyproject.toml+├── .env.example+├── .gitignore+├── README.md+└── my_app/+ ├── __init__.py+ ├── main.py+ ├── config.py+ ├── schemas.py+ ├── agents/+ │ ├── __init__.py+ │ ├── router_agent.py+ │ └── worker_agent.py+ └── tools/+ ├── __init__.py+ └── search_tool.py+```++### Large app (several agents, services, providers)++```+my_app/+├── pyproject.toml+├── .env.example+├── .gitignore+├── README.md+├── tests/+│ ├── test_agents.py+│ └── test_tools.py+└── my_app/+ ├── __init__.py+ ├── main.py+ ├── config.py+ ├── agents/+ ├── tools/+ ├── schemas/+ │ ├── __init__.py+ │ ├── inputs.py+ │ └── outputs.py+ ├── context_providers/+ ├── services/+ └── presentation/+```++Split schemas by direction (`inputs.py`, `outputs.py`) only when they start to collide in a single file. Until then, one `schemas.py` is easier to navigate.++## `pyproject.toml` template++```toml+[project]+name = "my-app"+version = "0.1.0"+description = "…"+readme = "README.md"+requires-python = ">=3.12"+license = { text = "MIT" }+authors = [{ name = "Your Name", email = "[email protected]" }]++dependencies = [+ "atomic-agents>=2.7",+ "instructor[openai]>=1.14", # swap extras per provider+ "pydantic>=2",+ "python-dotenv>=1",+ "rich>=13",+]++[project.optional-dependencies]+dev = [+ "pytest>=8",+ "pytest-asyncio>=0.23",+ "ruff>=0.5",+]++[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["my_app"]+```++`instructor[openai]` pulls in the `openai` package. Use `[anthropic]`, `[groq]`, `[google-genai]` for other providers. The monorepo depends on instructor extras specifically to keep provider SDK versions consistent.++## Configuration pattern++```python+# my_app/config.py+import os+from dataclasses import dataclass+from dotenv import load_dotenv++load_dotenv()++@dataclass(frozen=True)+class Config:+ openai_api_key: str+ model: str = "gpt-5-mini"+ max_tokens: int = 2048+ temperature: float = 0.2++ @classmethod+ def from_env(cls) -> "Config":+ key = os.environ.get("OPENAI_API_KEY")+ if not key:+ raise RuntimeError("OPENAI_API_KEY is not set")+ return cls(+ openai_api_key=key,+ model=os.environ.get("MY_APP_MODEL", cls.model),+ )++config = Config.from_env()+```++Freeze config objects so they are safe to pass around. Load them at process start — never inside a per-request handler.++## Environment and `.gitignore`++`.env.example` (commit this):++```bash+OPENAI_API_KEY=sk-...+# ANTHROPIC_API_KEY=...+# GEMINI_API_KEY=...+# GROQ_API_KEY=...+MY_APP_MODEL=gpt-5-mini+```++`.gitignore` (add these):++```gitignore+.env+.env.*.local+__pycache__/+*.py[cod]+.venv/+.pytest_cache/+.ruff_cache/+.coverage+htmlcov/+dist/+build/+*.egg-info/+```++Commit `.env.example`, never `.env`.++## Naming conventions++| Component | File | Class |+|---|---|---|+| Agent module | `agents/<purpose>_agent.py` | `<Purpose>Agent` (or factory `create_<purpose>_agent`) |+| Tool module | `tools/<name>_tool.py` | `<Name>Tool` |+| Schema | `schemas.py` or `schemas/*.py` | `<Purpose>Input`, `<Purpose>Output` |+| Context provider | `context_providers/<name>_ctx.py` | `<Name>Ctx` |+| Service | `services/<name>.py` | `<Name>Service` |++Factory functions (`create_*_agent(client, model) -> AtomicAgent[...]`) keep tests simple and make dependency wiring explicit.diff --git a/claude-plugin/atomic-agents/skills/framework/references/prompts.md b/claude-plugin/atomic-agents/skills/framework/references/prompts.mdnew file mode 100644index 0000000..a534121--- /dev/null+++ b/claude-plugin/atomic-agents/skills/framework/references/prompts.md@@ -0,0 +1,82 @@+# System Prompts (`SystemPromptGenerator`)++## Contents+- Three-part structure+- Section-writing guidance+- Interaction with context providers+- Omitting sections+- Common mistakes++## Three-part structure++```python+from atomic_agents.context import SystemPromptGenerator++spg = SystemPromptGenerator(+ background=[+ "You are a senior SRE.",+ "You triage production alerts into severity-tagged summaries.",+ ],+ steps=[+ "Read the alert payload.",+ "Identify the failing component and blast radius.",+ "Rank severity as P0/P1/P2/P3.",+ "Suggest the next diagnostic step.",+ ],+ output_instructions=[+ "Answer in 4 sections: Summary, Severity, Cause, Next step.",+ "Keep each section to one sentence.",+ ],+)+```++The generator renders to the system prompt in that order: **background → steps → output_instructions → dynamic context provider blocks**.++## Section-writing guidance++**`background`** — persona and scope. *Who* the agent is and *what* it's for. Keep it short; long personas pull quality from the task itself.++**`steps`** — the ordered procedure. *How* to process the input. Imperative mood, one action per line, numbered optional.++**`output_instructions`** — format and quality constraints. *What* the response must look like. Edge-case behavior belongs here too: "Say 'I don't know' rather than guess."++Keep each list short. If the prompt sprawls past ~30 lines, either promote details into a reference file and mention it, or split into a second agent.++## Interaction with context providers++Providers render *after* the three static sections. Structure the prompt so context providers fill in the *runtime* facts the static prompt references:++```python+spg = SystemPromptGenerator(+ background=[+ "You are a calendar assistant for the current user.",+ "Use the User Context and Current Time blocks below when reasoning about schedules.",+ ],+ steps=[+ "Parse the request.",+ "Resolve relative dates using Current Time.",+ "Look up availability in Session.",+ ],+ output_instructions=["Reply in the user's locale from User Context."],+)++agent.register_context_provider("user", UserCtx())+agent.register_context_provider("time", TimeCtx())+agent.register_context_provider("session", SessionCtx())+```++See `context-providers.md`.++## Omitting sections++All three sections are optional. Pass `background=None` to skip it, etc. A `SystemPromptGenerator` with every section `None` produces an empty system prompt.++To disable the system prompt entirely, set `system_role=None` on `AgentConfig` — this suppresses the entire first message and is what some reasoning-focused OpenAI models prefer.++## Common mistakes++- Stuffing the task description into `background` instead of letting the user input carry it.+- Multi-sentence bullets — the model loses the structure. Split into multiple items.+- Contradictions between `steps` and `output_instructions` — always reconcile.+- Hardcoding runtime facts ("The current user is Alice") in `background` instead of using a context provider.+- Forgetting to update `steps` after adding a new context provider.diff --git a/claude-plugin/atomic-agents/skills/framework/references/providers.md b/claude-plugin/atomic-agents/skills/framework/references/providers.mdnew file mode 100644index 0000000..4a6c9b8--- /dev/null+++ b/claude-plugin/atomic-agents/skills/framework/references/providers.md@@ -0,0 +1,176 @@+# LLM Providers++Atomic Agents is provider-agnostic: any Instructor-supported client works. This reference collects the wiring per provider, the correct `Mode`, roles, and example models. Read every key from environment variables.++Model IDs in this file are illustrative. Provider model names change often — check the provider's own docs or `atomic-examples/quickstart/quickstart/4_basic_chatbot_different_providers.py` for the ones the repo currently tests against.++## Contents+- Provider matrix+- OpenAI+- Anthropic+- Groq+- Ollama (local)+- Gemini+- OpenRouter+- MiniMax+- Picking a model+- `model_api_parameters` per provider+- Installation++## Provider matrix++| Provider | Instructor factory | `Mode` | `assistant_role` | Transport |+|---|---|---|---|---|+| OpenAI | `instructor.from_openai(OpenAI(...))` | `Mode.TOOLS` (default) | `"assistant"` | Native |+| Anthropic | `instructor.from_anthropic(Anthropic(...))` | `Mode.TOOLS` | `"assistant"` | Native |+| Groq | `instructor.from_groq(Groq(...), mode=Mode.JSON)` | `Mode.JSON` | `"assistant"` | Native |+| Ollama | `instructor.from_openai(OpenAI(base_url=..., api_key="ollama"), mode=Mode.JSON)` | `Mode.JSON` | `"assistant"` | OpenAI-compatible |+| Gemini | `instructor.from_genai(google.genai.Client(...), mode=Mode.GENAI_TOOLS)` | `Mode.GENAI_TOOLS` | `"model"` | Native |+| OpenRouter | `instructor.from_openai(OpenAI(base_url=..., api_key=...))` | `Mode.TOOLS` | `"assistant"` | OpenAI-compatible |+| MiniMax | `instructor.from_openai(OpenAI(base_url=..., api_key=...), mode=Mode.JSON)` | `Mode.JSON` | `"assistant"` | OpenAI-compatible |++The `mode` value is passed to `AgentConfig(mode=...)` **and** sometimes to the Instructor factory itself. Match them.++## OpenAI++```python+import os, instructor+from openai import OpenAI+from instructor import Mode++client = instructor.from_openai(OpenAI(api_key=os.environ["OPENAI_API_KEY"]))+model = "gpt-5-mini" # also: "gpt-5", "gpt-5-nano", and reasoning variants+api_params = {"reasoning_effort": "low", "max_tokens": 2048}+```++Reasoning models (o-series, GPT-5 reasoning variants) often prefer `system_role=None` on `AgentConfig`. Pass `reasoning_effort` through `model_api_parameters`.++## Anthropic++```python+import os, instructor+from anthropic import Anthropic++client = instructor.from_anthropic(Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]))+model = "claude-opus-4-6" # or "claude-sonnet-4-6", "claude-haiku-4-5"+api_params = {"max_tokens": 4096}+```++Anthropic requires `max_tokens` for every call — always set it in `model_api_parameters`.++## Groq++```python+import os, instructor+from groq import Groq+from instructor import Mode++client = instructor.from_groq(Groq(api_key=os.environ["GROQ_API_KEY"]), mode=Mode.JSON)+model = "llama-3.3-70b-versatile"+api_params = {"max_tokens": 2048}+# In AgentConfig: mode=Mode.JSON+```++Groq does not support tool-calling for all models — stick with `Mode.JSON`.++## Ollama (local)++```python+import instructor+from openai import OpenAI+from instructor import Mode++client = instructor.from_openai(+ OpenAI(base_url="http://localhost:11434/v1", api_key="ollama"),+ mode=Mode.JSON,+)+model = "llama3.1" # any model pulled with `ollama pull`+api_params = {"max_tokens": 2048}+```++No API key is needed. The literal `"ollama"` string satisfies the OpenAI SDK. Use `Mode.JSON` — Ollama's OpenAI adapter does not implement tool-calling reliably.++## Gemini++```python+import os, instructor+import google.genai+from instructor import Mode++client = instructor.from_genai(+ google.genai.Client(api_key=os.environ["GEMINI_API_KEY"]),+ mode=Mode.GENAI_TOOLS,+)+model = "gemini-2.5-flash"+api_params = {}+# In AgentConfig: assistant_role="model", mode=Mode.GENAI_TOOLS+```++Gemini is the only provider where `assistant_role` must be `"model"`. Forgetting this causes silent role confusion in multi-turn chats.++## OpenRouter++```python+import os, instructor+from openai import OpenAI++client = instructor.from_openai(OpenAI(+ base_url="https://openrouter.ai/api/v1",+ api_key=os.environ["OPENROUTER_API_KEY"],+))+model = "anthropic/claude-opus-4-6" # OpenRouter's model id syntax+api_params = {"max_tokens": 2048}+```++OpenRouter is a gateway to many providers via OpenAI-compatible protocol. Model ids use `provider/model` form.++## MiniMax++```python+import os, instructor+from openai import OpenAI+from instructor import Mode++client = instructor.from_openai(+ OpenAI(base_url="https://api.minimax.io/v1", api_key=os.environ["MINIMAX_API_KEY"]),+ mode=Mode.JSON,+)+model = "MiniMax-M2.7"+api_params = {"max_tokens": 2048}+```++## Picking a model++- **Drafting / simple chat** — `gpt-5-mini`, `claude-haiku-4-5`, or a Groq Llama for cost.+- **Tool use, multi-agent routing** — `gpt-5` or `claude-sonnet-4-6`.+- **Hardest reasoning** — `claude-opus-4-6` or reasoning-tier OpenAI models.+- **Local / offline** — Ollama with `llama3.1` or a code-specialized variant.++The framework is indifferent to provider choice — schemas and hooks behave the same. Swap `model` and the provider wiring, leave the rest alone.++## `model_api_parameters` per provider++Common keys:++- `max_tokens` — Anthropic requires it. Safe to set elsewhere too.+- `temperature` — all providers.+- `top_p` — most providers.+- `reasoning_effort` — OpenAI reasoning models only (`"low"`, `"medium"`, `"high"`).+- `frequency_penalty`, `presence_penalty` — OpenAI/OpenRouter.++Unknown keys are forwarded verbatim; the provider raises if it dislikes them.++## Installation++The repo uses Instructor extras to pull provider SDKs:++```toml+# pyproject.toml+[project]+dependencies = [+ "atomic-agents>=2.7",+ "instructor[openai]>=1.14", # or [anthropic], [groq], [google-genai]+]+```++For Ollama use the `openai` extra (Ollama exposes an OpenAI-compatible endpoint). For Gemini use `instructor[google-genai]`.diff --git a/claude-plugin/atomic-agents/skills/framework/references/schemas.md b/claude-plugin/atomic-agents/skills/framework/references/schemas.mdnew file mode 100644index 0000000..cf82be6--- /dev/null+++ b/claude-plugin/atomic-agents/skills/framework/references/schemas.md@@ -0,0 +1,180 @@+# Schemas (`BaseIOSchema`)++## Contents+- Rules enforced by `BaseIOSchema`+- Field patterns+- Validators+- Composition, unions, enums+- Error-schema pattern+- Common mistakes++## Rules enforced by `BaseIOSchema`++`BaseIOSchema` is a Pydantic `BaseModel` plus a metaclass hook that fails at class-definition time if:++- The class has no docstring, or only whitespace.++`model_json_schema()` is also overridden so the class docstring becomes the schema `description` and the class name becomes the `title`. Instructor uses both when prompting the LLM, so write the docstring for the model, not for humans only.++```python+from pydantic import Field+from atomic_agents import BaseIOSchema++class SearchQuery(BaseIOSchema):+ """Parameters for a web search issued by the agent."""++ query: str = Field(..., description="Natural-language search query.")+ limit: int = Field(default=10, ge=1, le=100, description="Maximum results to return.")+```++## Field patterns++Required, optional, and defaulted — always with `description=`:++```python+from typing import Optional, Literal+from pydantic import Field++name: str = Field(..., description="Full legal name.")+nickname: Optional[str] = Field(default=None, description="Preferred nickname, if any.")+count: int = Field(default=10, ge=1, le=100, description="Items to return (1–100).")+sort: Literal["asc", "desc"] = Field(default="desc", description="Sort order.")+tags: list[str] = Field(default_factory=list, max_length=10, description="Tag filters (≤10).")+```++Use `Literal[...]` for closed sets before reaching for `Enum` — the JSON schema stays flatter, which helps Instructor.++## Validators++Field-level:++```python+from pydantic import field_validator++class EmailSchema(BaseIOSchema):+ """An email address."""+ email: str = Field(..., description="RFC 5322 email address.")++ @field_validator("email")+ @classmethod+ def _lowercase(cls, v: str) -> str:+ if "@" not in v:+ raise ValueError("invalid email")+ return v.lower()+```++Model-level (cross-field):++```python+from pydantic import model_validator+from datetime import date++class DateRange(BaseIOSchema):+ """An inclusive date range."""+ start: date = Field(..., description="Start date (inclusive).")+ end: date = Field(..., description="End date (inclusive).")++ @model_validator(mode="after")+ def _ordered(self) -> "DateRange":+ if self.end < self.start:+ raise ValueError("end must be on or after start")+ return self+```++Validation errors surface as Instructor retries (up to `max_retries`) and fire the `parse:error` hook. See `agents.md`.++## Composition, unions, enums++Nested:++```python+class Address(BaseIOSchema):+ """A mailing address."""+ street: str = Field(..., description="Street and number.")+ city: str = Field(..., description="City name.")+ country: str = Field(..., description="ISO 3166-1 alpha-2 country code.")++class Person(BaseIOSchema):+ """A person with mailing address."""+ name: str = Field(..., description="Full name.")+ address: Address = Field(..., description="Mailing address.")+```++Discriminated unions — include a `Literal` discriminator on each variant:++```python+from typing import Literal, Union++class TextPart(BaseIOSchema):+ """A text message part."""+ kind: Literal["text"] = "text"+ text: str = Field(..., description="Plain-text body.")++class ImagePart(BaseIOSchema):+ """An image attachment."""+ kind: Literal["image"] = "image"+ url: str = Field(..., description="Publicly accessible image URL.")++class Message(BaseIOSchema):+ """A multimodal message part."""+ part: Union[TextPart, ImagePart] = Field(..., description="Message content.")+```++Enums:++```python+from enum import Enum++class Priority(str, Enum):+ LOW = "low"+ MEDIUM = "medium"+ HIGH = "high"++class Task(BaseIOSchema):+ """A unit of work."""+ title: str = Field(..., description="Task title.")+ priority: Priority = Field(default=Priority.MEDIUM, description="Priority level.")+```++## Error-schema pattern++When a tool or agent can legitimately fail, model it as a structured alternative output rather than an exception. Two common shapes:++**Pair of success/error schemas** returned via a union on the agent output:++```python+class SearchSuccess(BaseIOSchema):+ """Successful search result."""+ results: list[str] = Field(..., description="Matching items.")++class SearchFailure(BaseIOSchema):+ """Search could not complete."""+ error: str = Field(..., description="Human-readable failure reason.")+ code: Literal["rate_limited", "no_results", "upstream_error"] = Field(+ ..., description="Machine-readable failure code."+ )++class SearchOutput(BaseIOSchema):+ """Search output — either success or typed failure."""+ result: Union[SearchSuccess, SearchFailure] = Field(..., description="Outcome.")+```++**Discriminated status field** on a single schema:++```python+class SearchOutput(BaseIOSchema):+ """Search result envelope."""+ status: Literal["ok", "error"] = Field(..., description="Outcome code.")+ results: list[str] = Field(default_factory=list, description="Items when status='ok'.")+ error: Optional[str] = Field(default=None, description="Message when status='error'.")+```++Prefer the first shape when callers need exhaustive case handling; prefer the second when most code paths just care about `status == "ok"`.++## Common mistakes++- Forgetting the docstring — the framework raises `ValueError("… must have a non-empty docstring …")` at import.+- Plain `BaseModel` — loses the docstring enforcement and the `model_json_schema` override.+- `Field()` without `description=` — Instructor has nothing to tell the LLM about the field.+- `Optional[str]` with no default — becomes required-but-nullable, rarely what's intended.+- Over-broad types (`dict`, `Any`, `object`) — the LLM generates anything, Pydantic can't validate.diff --git a/claude-plugin/atomic-agents/skills/framework/references/testing.md b/claude-plugin/atomic-agents/skills/framework/references/testing.mdnew file mode 100644index 0000000..f1ef28c--- /dev/null+++ b/claude-plugin/atomic-agents/skills/framework/references/testing.md@@ -0,0 +1,150 @@+# Testing Agents and Tools++## Contents+- Test layout+- Testing schemas+- Testing tools (unit)+- Testing agents (without hitting a real LLM)+- Integration tests against a real provider+- Async and streaming+- Fixtures that keep tests honest++## Test layout++```+tests/+├── conftest.py+├── test_schemas.py+├── test_tools/+│ ├── test_calculator.py+│ └── test_weather.py+├── test_agents/+│ ├── test_router.py+│ └── test_summarizer.py+└── test_orchestration.py+```++`pytest` + `pytest-asyncio` covers everything. No extra runtime is needed.++## Testing schemas++Schemas are the cheapest thing to test — they validate at construction. Focus on the edge cases that matter:++```python+import pytest+from pydantic import ValidationError+from my_app.schemas import SearchQuery++def test_search_query_rejects_empty_string():+ with pytest.raises(ValidationError):+ SearchQuery(query="", limit=10)++def test_search_query_caps_limit():+ with pytest.raises(ValidationError):+ SearchQuery(query="x", limit=101)+```++Don't test the trivial cases (correct type accepted, missing required field rejected) — Pydantic already does that.++## Testing tools (unit)++Tools are plain classes. Stub any external I/O, assert on the output schema:++```python+import httpx, pytest+from my_app.tools.weather_tool import WeatherTool, WeatherConfig, WeatherInput++def test_weather_returns_error_without_key():+ tool = WeatherTool(WeatherConfig(api_key=""))+ out = tool.run(WeatherInput(city="Ghent"))+ assert out.status == "error"+ assert "WEATHER_API_KEY" in out.error++def test_weather_parses_ok_response(monkeypatch):+ def fake_get(*a, **kw):+ class R:+ def raise_for_status(self): pass+ def json(self): return {"temp_c": 12.3, "summary": "rain"}+ return R()+ monkeypatch.setattr(httpx, "get", fake_get)++ tool = WeatherTool(WeatherConfig(api_key="x"))+ out = tool.run(WeatherInput(city="Ghent"))+ assert out.status == "ok" and out.temperature_c == 12.3+```++## Testing agents (without hitting a real LLM)++Swap the Instructor client with one that returns a canned schema instance. The cleanest way is a fake `client.chat.completions.create` that returns the structured output directly. For simple cases, bypass the client entirely by stubbing `agent.run`:++```python+from unittest.mock import MagicMock+from my_app.schemas import UserQuery, Answer+from my_app.agents.qa_agent import create_qa_agent++def test_qa_agent_calls_llm_with_query():+ client = MagicMock()+ # Instructor clients route through .chat.completions.create(...)+ client.chat.completions.create.return_value = Answer(text="42")++ agent = create_qa_agent(client=client, model="gpt-5-mini")+ out = agent.run(UserQuery(question="meaning of life"))+ assert out.text == "42"+```++For agents that exercise validators or hooks, lean on Instructor's test helpers rather than hand-rolling client fakes. `instructor.Instructor` implementations can be constructed for testing — consult the Instructor docs for the exact factory.++## Integration tests against a real provider++Keep these opt-in behind an environment flag so they don't run in CI by default:++```python+import os, pytest++pytestmark = pytest.mark.skipif(+ not os.environ.get("RUN_PROVIDER_TESTS"),+ reason="set RUN_PROVIDER_TESTS=1 to hit the real provider",+)++def test_agent_answers_real_question():+ ...+```++Add `RUN_PROVIDER_TESTS=1` to a nightly or on-demand CI job. Pin a cheap model (`gpt-5-mini`, `claude-haiku-4-5`) and a tight `max_tokens`.++## Async and streaming++`pytest-asyncio` handles async agents:++```python+import pytest++async def test_async_agent(fake_async_client):+ agent = AtomicAgent[In, Out](config=AgentConfig(client=fake_async_client, model="m"))+ out = await agent.run_async(In(...))+ assert out == expected+```++For streaming, collect the partials and assert on the final one:++```python+async def test_streaming_agent(fake_streaming_client):+ partials = [p async for p in agent.run_async_stream(In(...))]+ assert partials[-1] == expected_final_output+```++## Fixtures that keep tests honest++- **Freeze time** in tests involving `TimeCtx` or timestamps.+- **Don't share `ChatHistory` across tests** — each test gets a fresh one, otherwise state bleeds.+- **Seed randomness** if the agent or a tool uses it.+- **Assert on hook invocations** to ensure error paths fire — register a spy hook before `run()`.++## Common mistakes++- Tests that silently call the real OpenAI API because the mock wasn't wired up — add a guard that fails loudly when `OPENAI_API_KEY` is set during unit tests.+- Asserting on free-text LLM output in unit tests — assert on schema fields or hook events instead.+- Forgetting to `reset_history()` between tests that share an agent fixture.+- Integration tests with no `max_tokens` cap — costs spiral.diff --git a/claude-plugin/atomic-agents/skills/framework/references/tools.md b/claude-plugin/atomic-agents/skills/framework/references/tools.mdnew file mode 100644index 0000000..7500a92--- /dev/null+++ b/claude-plugin/atomic-agents/skills/framework/references/tools.md@@ -0,0 +1,205 @@+# Tools (`BaseTool`)++## Contents+- The generic pattern+- Config, auth, and env vars+- `run()` and `run_async()` contract+- Error handling+- Integrating tools with agents+- MCP interop+- Prebuilt tools from Atomic Forge+- Distributing a standalone tool+- Common mistakes++## The generic pattern++`BaseTool` uses PEP 695 generics. The input and output schemas are declared as type parameters; the framework reads them back at class-creation time and exposes them as `self.input_schema` / `self.output_schema`.++```python+from pydantic import Field+from atomic_agents import BaseIOSchema, BaseTool, BaseToolConfig+++class CalculatorInput(BaseIOSchema):+ """Arithmetic expression to evaluate."""+ expression: str = Field(..., description="Python-style arithmetic, e.g. '2 + 2 * 3'.")+++class CalculatorOutput(BaseIOSchema):+ """Result of evaluating the expression."""+ result: float = Field(..., description="Numeric result.")+++class CalculatorTool(BaseTool[CalculatorInput, CalculatorOutput]):+ """Evaluate simple arithmetic expressions safely."""++ def run(self, params: CalculatorInput) -> CalculatorOutput:+ import ast, operator as op+ ops = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv}+ def ev(n):+ if isinstance(n, ast.Constant): return n.value+ if isinstance(n, ast.BinOp): return ops[type(n.op)](ev(n.left), ev(n.right))+ raise ValueError("unsupported")+ return CalculatorOutput(result=ev(ast.parse(params.expression, mode="eval").body))+++tool = CalculatorTool()+```++Do not assign `input_schema` / `output_schema` as class attributes. The generic parameters carry the type information via `BaseTool.__init_subclass__`, and the base class exposes both as properties. Declaring them as class attributes in addition is redundant at best and masks the framework-managed property at worst.++`self.tool_name` and `self.tool_description` default to the input schema's `title` and docstring. Override them with `BaseToolConfig(title=..., description=...)` when a different surface is needed for the LLM.++Canonical real tools to read: `atomic-forge/tools/calculator/tool/calculator.py` (minimal) and `atomic-forge/tools/searxng_search/tool/searxng_search.py` (HTTP-backed, with `run_async`).++## Config, auth, and env vars++`BaseToolConfig` carries `title` and `description` overrides. Subclass it for tool-specific configuration:++```python+import os+from pydantic import Field+from atomic_agents import BaseToolConfig++class WeatherConfig(BaseToolConfig):+ api_key: str = Field(+ default_factory=lambda: os.environ.get("WEATHER_API_KEY", ""),+ description="API key for the weather service.",+ )+ base_url: str = Field(+ default="https://api.weather.example/v1",+ description="Base URL for the weather API.",+ )+ timeout: float = Field(default=15.0, ge=1.0, le=120.0, description="Request timeout in seconds.")+```++Secrets come from environment. Never hardcode keys. Timeouts and retries belong in the config too.++## `run()` and `run_async()` contract++- Signature: `def run(self, params: InputSchema) -> OutputSchema`.+- `run()` is abstract on `BaseTool`; subclasses must implement it.+- For async-first tools, add `async def run_async(self, params: InputSchema) -> OutputSchema`. Callers that already have an event loop should prefer it. See `atomic-forge/tools/searxng_search/tool/searxng_search.py` for the dual-interface pattern.+- Return an `OutputSchema` instance, never raw dicts.+- Validate external side effects (HTTP status, DB result) and convert failures into either a successful output schema or a typed failure output (see `schemas.md` → error-schema pattern).++## Error handling++Two patterns, choose per call site:++1. **Typed failure output** — include a success/failure union in `OutputSchema`. The agent branches on it. Preferred when another agent invokes the tool.++2. **Exceptions** — only for programmer errors (misuse), not user-facing failures. Callers will not catch them routinely.++For external API calls:++```python+import httpx+from atomic_agents import BaseTool++class WeatherTool(BaseTool[WeatherInput, WeatherOutput]):+ """Fetch current conditions for a city."""++ def __init__(self, config: WeatherConfig | None = None):+ super().__init__(config or WeatherConfig())++ def run(self, params: WeatherInput) -> WeatherOutput:+ cfg: WeatherConfig = self.config+ if not cfg.api_key:+ return WeatherOutput(status="error", error="WEATHER_API_KEY not set")+ try:+ r = httpx.get(+ f"{cfg.base_url}/current",+ params={"city": params.city},+ headers={"Authorization": f"Bearer {cfg.api_key}"},+ timeout=cfg.timeout,+ )+ r.raise_for_status()+ except httpx.HTTPError as e:+ return WeatherOutput(status="error", error=str(e))+ data = r.json()+ return WeatherOutput(status="ok", temperature_c=data["temp_c"], summary=data["summary"])+```++## Integrating tools with agents++Tools plug into agents through the agent's output schema. Two common shapes:++**Single-tool agent.** The agent's output schema is the tool input schema. The agent decides arguments, the caller runs the tool:++```python+agent = AtomicAgent[UserQuery, CalculatorInput](config=config)+tool = CalculatorTool()++query = UserQuery(question="What's 23 times 47?")+call = agent.run(query) # LLM picks the arguments+result = tool.run(call) # host runs the tool+```++**Router agent.** The agent picks among tools by returning a discriminated union:++```python+from typing import Literal, Union++class CalcCall(BaseIOSchema):+ """Invoke the calculator."""+ tool: Literal["calculator"] = "calculator"+ args: CalculatorInput++class SearchCall(BaseIOSchema):+ """Invoke web search."""+ tool: Literal["search"] = "search"+ args: SearchInput++class ToolChoice(BaseIOSchema):+ """One of the available tools with its arguments."""+ call: Union[CalcCall, SearchCall] = Field(..., description="Tool invocation.")++agent = AtomicAgent[UserQuery, ToolChoice](config=config)+```++Working example: `atomic-examples/orchestration-agent/` orchestrates calculator + SearXNG with typed routing.++For larger tool surfaces (dozens+), see `orchestration.md` for the search+execute pattern.++## MCP interop++`atomic_agents.connectors.mcp` turns an MCP server's tools into `BaseTool` subclasses:++```python+from atomic_agents.connectors.mcp import fetch_mcp_tools, MCPTransportType++tools = fetch_mcp_tools(+ transport=MCPTransportType.HTTP_STREAM, # also: SSE, STDIO+ endpoint="https://my-mcp-server.example/mcp",+)+# tools is a list[type[BaseTool]] — instantiate and use them like any other tool.+```++Async variants (`fetch_mcp_tools_async`, `fetch_mcp_resources_async`, `fetch_mcp_prompts_async`) and the lower-level `MCPFactory` are exported from the same module. Transport values are `SSE`, `HTTP_STREAM`, `STDIO` — not `STREAMABLE_HTTP`.++Full client-side example: `atomic-examples/mcp-agent/example-client/`. A matching server lives under `atomic-examples/mcp-agent/example-mcp-server/`.++## Prebuilt tools (Atomic Forge)++The `atomic-forge` workspace ships production-ready tools: calculator, SearXNG, Tavily, Bocha, YouTube transcript scraper, webpage scraper, and more. Install into a project with:++```bash+atomic download calculator+atomic download tavily_search+```++Treat them as reference implementations when writing new tools.++## Distributing a standalone tool++In-project tools live alongside agents (`<project>/tools/<name>_tool.py`) — see `project-structure.md`. A tool meant to be **distributed** (installable via `atomic download` or as its own package) uses a different layout: its own `pyproject.toml`, `tests/`, `requirements.txt`, `README.md`, and a `tool/` subdirectory for the implementation. Follow `atomic-forge/guides/tool_structure.md` when packaging for distribution.++## Common mistakes++- Declaring `input_schema = ...` / `output_schema = ...` as class attributes — use generics.+- Returning dicts or primitives from `run()` instead of the output schema.+- Raising on routine failures (rate limits, not-found) — model them as typed output instead.+- Forgetting a timeout on HTTP / database calls — tools invoked by an agent run synchronously in the request path.+- Implementing `async def arun(...)` — the framework calls `run_async`, not `arun`.+- Using `MCPTransportType.STREAMABLE_HTTP` — the correct value is `HTTP_STREAM`.diff --git a/claude-plugin/atomic-agents/skills/new-app/SKILL.md b/claude-plugin/atomic-agents/skills/new-app/SKILL.mdnew file mode 100644index 0000000..aa3f800--- /dev/null+++ b/claude-plugin/atomic-agents/skills/new-app/SKILL.md@@ -0,0 +1,129 @@+---+name: new-app+description: Scaffold a new Atomic Agents project from scratch — create the directory, `pyproject.toml`, env file, first agent, and a runnable entry point. Use when the user asks to start a new atomic-agents project from scratch, says "scaffold" / "new project" / "start from zero", or runs `/atomic-agents:new-app`.+disable-model-invocation: true+argument-hint: [project-name]+---++# New Atomic Agents Project++Scaffold a fresh Atomic Agents project. The result is a single-package Python project with one working agent, one schema pair, a provider-wrapped client, and a runnable `main.py`.++This skill is opinionated. Produce a complete, tested skeleton the user can run immediately.++## Phase 1 — Interrogate++Ask these questions in one message, not one-at-a-time. Skip any the user already answered (including via `$ARGUMENTS`).++1. **Project name** — used as both directory name and package name. Default from `$ARGUMENTS` if provided. Normalize to `kebab-case` for the directory and `snake_case` for the package.+2. **LLM provider** — OpenAI / Anthropic / Groq / Ollama / Gemini / OpenRouter / MiniMax. Default: OpenAI.+3. **Agent type** — a rough one-liner. Shapes the default `SystemPromptGenerator` content and the starter schema pair. Defaults to a generic chat agent.+4. **Tooling** — `uv` (default, because the repo uses uv) or `pip + venv`.++Do not ask about project layout, Python version, or dependency list. Pick them.++## Phase 2 — Confirm the plan++State the plan in one short block and wait for a yes. Include:++- Directory: `<project-name>/`+- Package: `<project_name>/`+- Python: `>=3.12` (Atomic Agents uses PEP 695 generics)+- Dependencies: `atomic-agents>=2.7`, `instructor[<provider-extra>]>=1.14`, `python-dotenv`, `rich`+- Dev dependencies: `pytest`, `pytest-asyncio`, `ruff`+- First agent: `<agent-type>` — uses `BasicChatInputSchema`/`BasicChatOutputSchema` unless the agent type calls for custom schemas+- Default model for the chosen provider (see `framework/references/providers.md`)+- Entry point: `main.py` with a REPL++## Phase 3 — Scaffold++Create files in this order. Verify each step before proceeding.++### Directory and package++```+<project-name>/+├── pyproject.toml+├── .env.example+├── .gitignore+├── README.md+└── <project_name>/+ ├── __init__.py+ └── main.py+```++### `pyproject.toml`++Use the template from `framework/references/project-structure.md`, substituting the chosen provider extra and project name.++### `.env.example`++Include the provider's API-key variable with a placeholder. Never the real key.++### `.gitignore`++Use the template from `framework/references/project-structure.md`.++### `<project_name>/main.py`++Produce a runnable REPL. Load `.env`, instantiate the provider client per `framework/references/providers.md`, build an agent, wire a `ChatHistory` with a seed assistant message, loop on `console.input(...)`.++When a custom agent type was requested, build custom `InputSchema` / `OutputSchema` subclasses with field `description=` populated. Otherwise use `BasicChatInputSchema` / `BasicChatOutputSchema`.++Always use the canonical imports:++```python+from atomic_agents import (+ AtomicAgent, AgentConfig,+ BasicChatInputSchema, BasicChatOutputSchema,+)+from atomic_agents.context import ChatHistory, SystemPromptGenerator+from instructor import Mode+```++Per-provider AgentConfig knobs — match the Instructor factory mode on `AgentConfig.mode`:++- **OpenAI**: defaults work. Omit `mode` (or set `Mode.TOOLS`).+- **Anthropic**: `mode=Mode.TOOLS`; include `max_tokens` in `model_api_parameters`.+- **Groq / Ollama / MiniMax**: `mode=Mode.JSON` (Instructor factory also uses `Mode.JSON`).+- **Gemini**: `assistant_role="model"` and `mode=Mode.GENAI_TOOLS` (Instructor factory uses `Mode.GENAI_TOOLS`).+- **OpenRouter**: `mode=Mode.TOOLS`.++### `README.md`++Short. Include: what the project is, how to install (`uv sync` or `pip install -e .[dev]`), how to set the API key (`cp .env.example .env` and edit), how to run (`uv run python -m <project_name>.main` or equivalent).++## Phase 4 — Install and smoke-test++Execute the install step:++- **uv**: `uv sync`+- **pip**: `python -m venv .venv && .venv/bin/pip install -e ".[dev]"` (Windows: `.venv\Scripts\pip`)++Verify imports without a live API key:++```bash+uv run python -c "from <project_name>.main import agent; print('ok')"+```++If that works, the scaffold is sound. Tell the user to drop their key into `.env` and run the REPL.++## Phase 5 — Hand off++After scaffolding, tell the user:++1. How to set their key (`cp .env.example .env`).+2. How to run (`uv run python -m <project_name>.main`).+3. Next steps, picked from:+ - Replace the starter schemas with domain-specific ones — see `framework/references/schemas.md`.+ - Add a tool — see `framework/references/tools.md`.+ - Add a context provider — see `framework/references/context-providers.md`.+ - Split into multiple agents — see `framework/references/orchestration.md`.+4. A pointer to `framework` (auto-triggered) and `review` (auto-triggered before commit).++## Constraints++- Never commit `.env`. Only `.env.example`.+- Never install anything globally. Use the project venv.+- Never pick an old model. Default to current generation: OpenAI `gpt-5-mini`, Anthropic `claude-haiku-4-5`, Groq `llama-3.3-70b-versatile`, Ollama `llama3.1`, Gemini `gemini-2.5-flash`.+- Never hand-roll what `framework/references/project-structure.md` already templates.diff --git a/claude-plugin/atomic-agents/skills/review/SKILL.md b/claude-plugin/atomic-agents/skills/review/SKILL.mdnew file mode 100644index 0000000..cdc2e4e--- /dev/null+++ b/claude-plugin/atomic-agents/skills/review/SKILL.md@@ -0,0 +1,129 @@+---+name: review+description: Review Atomic Agents code against framework-specific correctness, security, and style rules. Use when the user asks to "review", "audit", "check", or "validate" code that uses `atomic_agents` — before committing, before a PR, or when investigating misbehavior in an existing agent, tool, schema, context provider, or orchestration. Complements generic code review by focusing only on Atomic-Agents-specific concerns.+---++# Atomic Agents Code Review++This skill reviews code for correctness *with respect to the Atomic Agents framework*. It does not replace generic linting, type checking, or architectural review — it adds the framework-specific layer on top.++## Scope++Default to reviewing the current diff (`git diff` against the base branch). If there is no diff, review files the user points at.++Skip issues that are not specific to Atomic Agents (naming style, formatting, general Python conventions) — a generic reviewer covers those.++## Checklist++Work through the categories below in order. Raise an issue only at ≥75% confidence. Mark each issue with its category, file path, line, and a ready-to-apply fix.++### 1. Schemas (`BaseIOSchema`)++- Inherits from `BaseIOSchema`, not `pydantic.BaseModel`.+- Has a non-empty class docstring. The framework raises `ValueError` at import otherwise.+- Every field has `description=`. Instructor uses field descriptions when prompting.+- Types are appropriately constrained: `Literal` for closed sets, numeric bounds via `ge`/`le`, string/list lengths where meaningful.+- Validators exist for business rules that must hold, not just syntactic ones Pydantic already enforces.+- `Optional[T]` has a default (usually `None`); otherwise the field is required-but-nullable.++### 2. Agents (`AtomicAgent`)++- Constructed with explicit generic parameters: `AtomicAgent[In, Out](config=...)`.+- `AgentConfig.client` is an instructor-wrapped client (`instructor.from_openai(...)`, `instructor.from_anthropic(...)`, etc.), not a raw provider SDK client.+- `model` is set and appropriate for the task (not a reasoning model for trivial work, not a weak model for hard reasoning).+- `history` is present when the agent needs multi-turn state; absent when each call is independent.+- `assistant_role="model"` for Gemini, `"assistant"` elsewhere.+- `mode` matches the provider (`Mode.TOOLS` for OpenAI/Anthropic, `Mode.JSON` for Groq/Ollama/MiniMax, `Mode.GENAI_TOOLS` for Gemini).+- Provider-specific required params present: `max_tokens` for Anthropic, `reasoning_effort` for reasoning models as intended.++### 3. Tools (`BaseTool`)++- Declared with generic parameters: `class MyTool(BaseTool[In, Out])`. No legacy `input_schema = ...` / `output_schema = ...` class attributes.+- `run()` returns the output schema instance, not a dict or primitive.+- External I/O has a timeout.+- Retries/backoff on transient errors when the caller cannot reasonably retry.+- Credentials come from environment, not hardcoded.+- Routine failures (not-found, rate-limited) become typed outputs, not exceptions.++### 4. Context providers (`BaseDynamicContextProvider`)++- Registered on the agent before any `run()` that depends on them.+- `get_info()` returns a string, is fast, does no blocking I/O.+- Slow data sources (DB schemas, remote calls) are cached with a TTL inside the provider.+- Titles are unique across providers registered on the same agent.+- No secrets in `get_info()` output — it ends up in every LLM request.++### 5. System prompts (`SystemPromptGenerator`)++- Three sections used as intended: `background` = who, `steps` = how, `output_instructions` = format/constraints.+- No runtime facts hardcoded in `background` — those belong in context providers.+- Sections short enough that the model attends to all of them.++### 6. Orchestration++- Parallel agents don't share a `ChatHistory`.+- Router agents return a discriminated union, not free-text topics.+- Supervisor loops have an explicit iteration cap.+- Pipeline stages agree on types; where they don't, a typed adapter is present.++### 7. Security++- No `os.environ[...]` lookups that silently default to empty strings without a startup check.+- No secrets in docstrings, `description=` fields, logs, or context provider output.+- User input flowing into shell-out tools is validated or escaped.+- No `eval`/`exec` on model output.++### 8. Hooks++- Error paths use `register_hook("parse:error", ...)` / `register_hook("completion:error", ...)` instead of blanket `try/except` around `run()`.+- Hook handlers themselves don't raise — they log/meter and return.++### 9. Testing++- Unit tests don't hit real providers by default. If they can, there is a guard (env var or offline mock).+- Integration tests cap `max_tokens`.++## Output format++```+## Atomic Agents Review++**Files reviewed**: <paths>+**Issues**: <N critical>, <M important>, <K suggestions>++### Critical (must fix)++- <category> · `<path>:<line>` · <confidence>%+ <one-sentence problem>+ **Fix**+ ```python+ <ready-to-apply patch>+ ```++### Important (should fix)+<same shape>++### Suggestions+<same shape>++### Passed+- <brief list of framework invariants the code honors>+```++Keep each issue short. The caller already has the codebase; they do not need a re-explanation of the rule — just the pointer and the fix. For deep context on *why* a rule exists, link into the `framework` skill's reference files rather than duplicating content:++- Schemas: see `framework/references/schemas.md`+- Agents: see `framework/references/agents.md`+- Tools: see `framework/references/tools.md`+- Context providers: see `framework/references/context-providers.md`+- Prompts: see `framework/references/prompts.md`+- Orchestration: see `framework/references/orchestration.md`+- Providers: see `framework/references/providers.md`++## Review principles++- Confidence ≥75 only. Noise kills trust in the review.+- No pre-existing issues — review the *diff* unless told otherwise.+- Every issue has a concrete fix in the same format the code is written.+- Prefer fewer, sharper findings over exhaustive lists.+- Flag security issues at any confidence ≥50.