diff --git a/99 Daily/2026-04-17.md b/99 Daily/2026-04-17.md index 8f47c9b..9d7c715 100644 --- a/99 Daily/2026-04-17.md +++ b/99 Daily/2026-04-17.md @@ -122,3 +122,6 @@ tags: [daily] - 12:39 | `memory-compiler` - **Asked:** Compile a new article on MCP integration into the knowledge base wiki structure. - **Done:** Added `mcp-integration.md` to `agent-sdk/` topic with transport types, authentication patterns, and tool management documentation. +- 12:40 (1min) | `memory-compiler` + - **Asked:** Compile a raw wiki article about custom subagents into the structured knowledge base. + - **Done:** Filed article as `wiki/claude-code/custom-subagents.md` with sections on creation methods, frontmatter fields, scope priority, tool control, and persistent memory. diff --git a/raw/Create custom subagents.md b/raw/_processed/Create custom subagents.md similarity index 100% rename from raw/Create custom subagents.md rename to raw/_processed/Create custom subagents.md diff --git a/wiki/_master-index.md b/wiki/_master-index.md index 080b718..ce0fec2 100644 --- a/wiki/_master-index.md +++ b/wiki/_master-index.md @@ -32,7 +32,7 @@ This 3-hop pattern works for hundreds of articles without vector search. | [[wiki/agent-sdk/_index\|agent-sdk/]] | Claude Agent SDK (formerly Claude Code SDK) — build autonomous AI agents in Python and TypeScript | 8 | | [[wiki/llm-models/_index\|llm-models/]] | OpenAI model catalog — GPT-5.x, o-series reasoning, audio/realtime, embeddings, moderation | 1 | -| [[wiki/claude-code/_index\|claude-code/]] | Claude Code product docs — install, capabilities, surfaces, MCP, hooks, scheduling, multi-agent | 2 | +| [[wiki/claude-code/_index\|claude-code/]] | Claude Code product docs — install, capabilities, surfaces, MCP, hooks, scheduling, multi-agent | 3 | diff --git a/wiki/claude-code/_index.md b/wiki/claude-code/_index.md index 2f1fc20..72bbcda 100644 --- a/wiki/claude-code/_index.md +++ b/wiki/claude-code/_index.md @@ -16,3 +16,5 @@ Claude Code is Anthropic's agentic coding assistant. Works across terminal, IDE, |---------|---------|--------|---------| | [[wiki/claude-code/overview\|overview]] | Full product overview: install, capabilities (tasks, git, MCP, hooks, scheduling, multi-agent), all surfaces | raw/Claude Code overview.md | 2026-04-17 | | [[wiki/claude-code/mcp-integration\|mcp-integration]] | MCP setup, transports, scopes, OAuth, tool search, channels, managed enterprise config, 100+ server list | raw/Connect Claude Code to tools via MCP.md | 2026-04-17 | +| [[wiki/claude-code/custom-subagents\|custom-subagents]] | Custom subagents: creation, frontmatter fields, tool control, persistent memory, hooks, foreground/background, example patterns | raw/Create custom subagents.md | 2026-04-17 | +| [[wiki/claude-code/create-plugins\|create-plugins]] | Plugin authoring: manifest structure, skills/agents/hooks/LSP/monitors, local testing with --plugin-dir, migrating from standalone, marketplace distribution | raw/Create plugins.md | 2026-04-17 | diff --git a/wiki/claude-code/create-plugins.md b/wiki/claude-code/create-plugins.md new file mode 100644 index 0000000..307b512 --- /dev/null +++ b/wiki/claude-code/create-plugins.md @@ -0,0 +1,157 @@ +--- +title: "Creating Claude Code Plugins" +aliases: [claude-code-plugins, plugin-authoring, claude-plugins] +tags: [claude-code, plugins, skills, agents, hooks, mcp, extensibility] +sources: [raw/Create plugins.md] +created: 2026-04-17 +updated: 2026-04-17 +--- + +# Creating Claude Code Plugins + +Plugins package skills, agents, hooks, MCP servers, LSP servers, and background monitors into a shareable, versioned unit. They are the distribution mechanism for Claude Code extensions. + +## Standalone Config vs. Plugins + +| Approach | Skill names | Best for | +|----------|-------------|----------| +| **Standalone** (`.claude/` dir) | `/hello` | Personal workflows, single-project, quick experiments | +| **Plugin** (dir with `.claude-plugin/plugin.json`) | `/my-plugin:hello` | Team sharing, multi-project reuse, marketplace distribution | + +- Start standalone → convert to plugin when ready to share +- Plugins namespace skill names (`/plugin-name:skill`) to prevent conflicts + +## Plugin Directory Structure + +``` +my-plugin/ +├── .claude-plugin/ +│ └── plugin.json ← manifest (ONLY file inside .claude-plugin/) +├── skills/ +│ └── code-review/ +│ └── SKILL.md +├── commands/ ← legacy flat .md skills (use skills/ for new) +├── agents/ ← custom agent definitions +├── hooks/ +│ └── hooks.json +├── monitors/ +│ └── monitors.json +├── bin/ ← executables added to PATH +├── .mcp.json ← MCP server configs +├── .lsp.json ← LSP server configs +└── settings.json ← default settings when plugin enabled +``` + +**Critical mistake to avoid:** Never put `skills/`, `agents/`, `hooks/`, or `commands/` inside `.claude-plugin/`. Only `plugin.json` lives there. + +## Plugin Components + +### Skills +- Add `skills//SKILL.md` at plugin root +- Include `description:` in frontmatter so Claude knows when to invoke +- Model-invoked automatically based on task context +- Run `/reload-plugins` after changes + +```yaml +--- +description: Reviews code for best practices. Use when reviewing PRs or analyzing code quality. +--- + +When reviewing code, check for: +1. Error handling +2. Security concerns +3. Test coverage +``` + +### LSP Servers +- Add `.lsp.json` at plugin root for language intelligence +- Users must have the language server binary installed +- Use pre-built marketplace LSP plugins for common languages (TS, Python, Rust) + +```json +{ + "go": { + "command": "gopls", + "args": ["serve"], + "extensionToLanguage": { ".go": "go" } + } +} +``` + +### Background Monitors +- Add `monitors/monitors.json` — array of monitor entries +- Each stdout line from `command` is delivered to Claude as a notification +- Started automatically when plugin is active + +```json +[ + { + "name": "error-log", + "command": "tail -F ./logs/error.log", + "description": "Application error log" + } +] +``` + +### Default Settings +- `settings.json` at plugin root applies config when plugin is enabled +- Supported keys: `agent`, `subagentStatusLine` +- Setting `agent` activates a plugin agent as the main thread + +```json +{ "agent": "security-reviewer" } +``` + +## Testing Locally + +```shell +# Load one plugin +claude --plugin-dir ./my-plugin + +# Load multiple plugins +claude --plugin-dir ./plugin-one --plugin-dir ./plugin-two +``` + +- Local `--plugin-dir` takes precedence over installed marketplace plugins of the same name +- Run `/reload-plugins` during development to pick up changes without restart +- Test skills: `/plugin-name:skill-name` | Check agents: `/agents` + +## Migrating from Standalone to Plugin + +| Standalone (`.claude/`) | Plugin | +|-------------------------|--------| +| Available in one project | Shareable via marketplace | +| `commands/` in `.claude/` | `commands/` at plugin root | +| Hooks in `settings.json` | `hooks/hooks.json` | +| Manual copy to share | Install with `/plugin install` | + +After migrating, remove original `.claude/` files to avoid duplicates. + +## Distribution + +1. Add `README.md` with install + usage instructions +2. Use semantic versioning in `plugin.json` +3. Submit to official marketplace via `claude.ai/settings/plugins/submit` or `platform.claude.com/plugins/submit` +4. Distribute through a plugin marketplace (official or team-hosted) + +## Key Takeaways + +- Plugin root structure: manifest in `.claude-plugin/plugin.json`, everything else at root level +- Skills are model-invoked; slash commands are user-invoked — they live in different dirs (`skills/` vs `commands/`) +- Use `--plugin-dir` for local testing; run `/reload-plugins` to hot-reload changes +- Background monitors run automatically and stream stdout lines to Claude as notifications +- `settings.json` can activate a plugin agent as the default main-thread agent +- Start with standalone `.claude/` config, convert to plugin when ready to distribute +- Plugin skill names are always namespaced: `/plugin-name:skill-name` + +## Related + +- [[wiki/claude-code/custom-subagents|Custom Subagents]] — agent definitions used inside plugins +- [[wiki/claude-code/mcp-integration|MCP Integration]] — `.mcp.json` for adding MCP servers to a plugin +- [[wiki/claude-code/overview|Claude Code Overview]] — full product context +- [[wiki/agent-sdk/_index|Agent SDK]] — building agents that plugins can wrap + +## Sources + +- Source: `raw/Create plugins.md` +- Original: https://code.claude.com/docs/en/plugins diff --git a/wiki/claude-code/custom-subagents.md b/wiki/claude-code/custom-subagents.md new file mode 100644 index 0000000..da51051 --- /dev/null +++ b/wiki/claude-code/custom-subagents.md @@ -0,0 +1,304 @@ +--- +title: "Custom Subagents in Claude Code" +aliases: [subagents, claude-code-subagents, custom-agents] +tags: [claude-code, subagents, multi-agent, context-management, automation] +sources: [raw/Create custom subagents.md] +created: 2026-04-17 +updated: 2026-04-17 +--- + +# Custom Subagents in Claude Code + +Subagents are specialized AI assistants that run in their **own context window** with a custom system prompt, specific tool access, and independent permissions. Claude automatically delegates tasks to them based on description matching, or you can invoke them explicitly. + +**Primary use case:** isolate side tasks (search, test runs, log parsing) that would flood the main conversation with output you won't reference again — the subagent returns only the summary. + +See also: [[wiki/claude-code/overview|Claude Code Overview]], [[wiki/agent-sdk/configure-permissions|Permissions Guide]], [[wiki/claude-code/mcp-integration|MCP Integration]] + +--- + +## Built-in Subagents + +| Name | Model | Tools | Purpose | +|------|-------|-------|---------| +| **Explore** | Haiku | Read-only | Codebase search and analysis | +| **Plan** | inherit | Read-only | Architecture and implementation planning | +| **General-purpose** | inherit | All | Catch-all delegation | + +Explore takes a thoroughness hint: `quick`, `medium`, or `very thorough`. + +--- + +## Creating Subagents + +### Via `/agents` command (recommended) +Opens a tabbed UI: **Running** tab (live subagents) + **Library** tab (create/edit/delete). Loads the subagent immediately without restarting. + +### Via markdown file + +```markdown +--- +name: code-reviewer +description: Reviews code for quality and best practices +tools: Read, Glob, Grep +model: sonnet +--- + +You are a code reviewer. Analyze code and provide specific, actionable feedback. +``` + +Save to: +- `.claude/agents/` — project scope (check into git for team sharing) +- `~/.claude/agents/` — user scope (all projects) + +Manually added files require a session restart or `/agents` reload. + +### Via CLI flag (session-only) + +```shell +claude --agents '{ + "code-reviewer": { + "description": "Expert code reviewer. Use proactively after code changes.", + "prompt": "You are a senior code reviewer...", + "tools": ["Read", "Grep", "Glob", "Bash"], + "model": "sonnet" + } +}' +``` + +--- + +## Frontmatter Fields + +| Field | Required | Notes | +|-------|----------|-------| +| `name` | Yes | Lowercase with hyphens | +| `description` | Yes | Used by Claude to decide when to delegate | +| `tools` | No | Allowlist; inherits all if omitted | +| `disallowedTools` | No | Denylist applied before `tools` allowlist | +| `model` | No | `sonnet`, `opus`, `haiku`, full model ID, or `inherit` (default) | +| `permissionMode` | No | `default`, `acceptEdits`, `auto`, `dontAsk`, `bypassPermissions`, `plan` | +| `maxTurns` | No | Cap agentic turns | +| `skills` | No | Inject skill content at startup (not inherited from parent) | +| `mcpServers` | No | Inline or named server references | +| `hooks` | No | Lifecycle hooks scoped to this subagent | +| `memory` | No | `user`, `project`, or `local` — persistent cross-session memory | +| `background` | No | `true` to always run as background task | +| `isolation` | No | `worktree` — isolated git copy, auto-cleaned if no changes | +| `effort` | No | `low`, `medium`, `high`, `xhigh`, `max` | +| `color` | No | `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, `cyan` | +| `initialPrompt` | No | Auto-submitted first turn when used as main session agent | + +--- + +## Scope & Priority + +| Location | Scope | Priority | +|----------|-------|----------| +| Managed settings | Organization | 1 (highest) | +| `--agents` CLI flag | Current session | 2 | +| `.claude/agents/` | Current project | 3 | +| `~/.claude/agents/` | All user projects | 4 | +| Plugin `agents/` dir | Where plugin enabled | 5 (lowest) | + +When names collide, higher priority wins. Plugin subagents **cannot** use `hooks`, `mcpServers`, or `permissionMode`. + +--- + +## Model Selection + +Resolution order for a subagent's model: +1. `CLAUDE_CODE_SUBAGENT_MODEL` env var +2. Per-invocation `model` parameter +3. Subagent frontmatter `model` +4. Main conversation model + +--- + +## Tool Control + +**Allowlist** (`tools`): only these tools are available. +**Denylist** (`disallowedTools`): inherit all except these. +**Both**: denylist applied first, then allowlist from the remainder. + +To restrict which subagent types can be spawned (when running as main thread via `--agent`): +```yaml +tools: Agent(worker, researcher), Read, Bash +``` +Omit `Agent` entirely to prevent spawning any subagent. + +--- + +## Persistent Memory + +```yaml +memory: project # or user / local +``` + +| Scope | Location | Use when | +|-------|----------|----------| +| `user` | `~/.claude/agent-memory//` | Cross-project learnings | +| `project` | `.claude/agent-memory//` | Project-specific, shareable via git | +| `local` | `.claude/agent-memory-local//` | Project-specific, not in git | + +When enabled, the subagent gets Read/Write/Edit tools automatically and its system prompt includes first 200 lines of `MEMORY.md`. + +--- + +## Hooks in Subagents + +### Frontmatter hooks (subagent-scoped) +Fire only while that subagent is active. **Do not fire** when running as main session via `--agent`. + +```yaml +hooks: + PreToolUse: + - matcher: "Bash" + hooks: + - type: command + command: "./scripts/validate-command.sh" + PostToolUse: + - matcher: "Edit|Write" + hooks: + - type: command + command: "./scripts/run-linter.sh" +``` + +`Stop` hooks in frontmatter are converted to `SubagentStop` at runtime. + +### Session-level hooks (settings.json) + +```json +{ + "hooks": { + "SubagentStart": [{ "matcher": "db-agent", "hooks": [...] }], + "SubagentStop": [{ "hooks": [...] }] + } +} +``` + +--- + +## Invoking Subagents + +| Method | Effect | +|--------|--------| +| Natural language ("use the X subagent") | Claude decides whether to delegate | +| `@"subagent-name (agent)"` | Guarantees that subagent runs | +| `claude --agent code-reviewer` | Whole session uses that subagent's prompt + tools | +| `agent` key in `.claude/settings.json` | Default for every session in the project | + +--- + +## Foreground vs Background + +- **Foreground**: blocks main conversation; permission prompts pass through +- **Background**: concurrent; permissions approved upfront; `AskUserQuestion` fails silently +- Press **Ctrl+B** to background a running task +- Disable all background tasks: `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1` + +--- + +## Common Patterns + +### Isolate high-volume operations +```text +Use a subagent to run the test suite and report only failing tests with error messages +``` + +### Parallel research +```text +Research the auth, database, and API modules in parallel using separate subagents +``` + +### Chain subagents +```text +Use code-reviewer to find performance issues, then use optimizer to fix them +``` + +--- + +## When NOT to Use a Subagent + +- Task needs frequent back-and-forth or iterative refinement → main conversation +- Quick targeted change → main conversation +- Latency matters → main conversation (subagents start fresh) +- Reusable prompt/workflow in main context → [[wiki/agent-sdk/skills-in-sdk|Skills]] +- Nested delegation needed → Skills or chain from main conversation +- Quick question already in context → `/btw` command (no tools, answer discarded) + +**Note:** Subagents cannot spawn other subagents. + +--- + +## Example Subagents + +### Code Reviewer (read-only) +```markdown +--- +name: code-reviewer +description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code. +tools: Read, Grep, Glob, Bash +model: inherit +--- +You are a senior code reviewer... +``` + +### Debugger (read + write) +```markdown +--- +name: debugger +description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues. +tools: Read, Edit, Bash, Grep, Glob +--- +``` + +### DB Query Validator (hook-gated Bash) +```markdown +--- +name: db-reader +description: Execute read-only database queries. +tools: Bash +hooks: + PreToolUse: + - matcher: "Bash" + hooks: + - type: command + command: "./scripts/validate-readonly-query.sh" +--- +``` +Exit code 2 from the hook blocks the command and returns the error to Claude. + +--- + +## Disabling Subagents + +```json +{ + "permissions": { + "deny": ["Agent(Explore)", "Agent(my-custom-agent)"] + } +} +``` + +Or via CLI: `claude --disallowedTools "Agent(Explore)"` + +--- + +## Key Takeaways + +- Subagents run in **isolated context windows** — verbose output never pollutes your main conversation +- Define them as `.md` files in `.claude/agents/` (project) or `~/.claude/agents/` (user) +- The `description` field is the routing key — write it clearly so Claude knows when to delegate +- Use `tools` or `disallowedTools` to enforce least-privilege access +- `model: haiku` for fast/cheap research tasks; `model: opus` for deep analysis +- `memory: project` enables cross-session learning stored alongside the codebase +- `isolation: worktree` gives the subagent a throwaway git clone — safe for risky operations +- Subagents **cannot** spawn other subagents; use Skills or chain from main conversation +- Background subagents run concurrently; permissions must be approved upfront + +--- + +## Sources + +- [Create custom subagents — Claude Code docs](https://code.claude.com/docs/en/sub-agents)