docs(agents): regenerate all AGENTS.md with deep codebase analysis

This commit is contained in:
YeonGyu-Kim 2026-02-10 14:53:39 +09:00
parent b538806d5e
commit 83f1304e01
13 changed files with 633 additions and 685 deletions

195
AGENTS.md
View File

@ -1,7 +1,7 @@
# PROJECT KNOWLEDGE BASE # PROJECT KNOWLEDGE BASE
**Generated:** 2026-02-09T14:16:00+09:00 **Generated:** 2026-02-10T14:44:00+09:00
**Commit:** f22f14d9 **Commit:** b538806d
**Branch:** dev **Branch:** dev
--- ---
@ -77,11 +77,6 @@ Oh-My-OpenCode is a **plugin for OpenCode**. You will frequently need to examine
| Debugging plugin issues | Fire `librarian` to find relevant OpenCode internals | | Debugging plugin issues | Fire `librarian` to find relevant OpenCode internals |
| Answering "how does OpenCode do X?" | Fire `librarian` FIRST | | Answering "how does OpenCode do X?" | Fire `librarian` FIRST |
**The `librarian` agent is specialized for:**
- Searching remote codebases (GitHub)
- Retrieving official documentation
- Finding implementation examples in open source
**DO NOT guess or hallucinate about OpenCode internals.** Always verify by examining actual source code via `librarian` or direct clone. **DO NOT guess or hallucinate about OpenCode internals.** Always verify by examining actual source code via `librarian` or direct clone.
--- ---
@ -92,8 +87,6 @@ Oh-My-OpenCode is a **plugin for OpenCode**. You will frequently need to examine
### All Project Communications MUST Be in English ### All Project Communications MUST Be in English
This is an **international open-source project**. To ensure accessibility and maintainability:
| Context | Language Requirement | | Context | Language Requirement |
|---------|---------------------| |---------|---------------------|
| **GitHub Issues** | English ONLY | | **GitHub Issues** | English ONLY |
@ -103,67 +96,74 @@ This is an **international open-source project**. To ensure accessibility and ma
| **Documentation** | English ONLY | | **Documentation** | English ONLY |
| **AGENTS.md files** | English ONLY | | **AGENTS.md files** | English ONLY |
### Why This Matters **If you're not comfortable writing in English, use translation tools. Broken English is fine. Non-English is not acceptable.**
- **Global Collaboration**: Contributors from all countries can participate
- **Searchability**: English keywords are universally searchable
- **AI Agent Compatibility**: AI tools work best with English content
- **Consistency**: Mixed languages create confusion and fragmentation
### Enforcement
- Issues/PRs with non-English content may be closed with a request to resubmit in English
- Commit messages must be in English - CI may reject non-English commits
- Translated READMEs exist (README.ko.md, README.ja.md, etc.) but the primary docs are English
**If you're not comfortable writing in English, use translation tools. Broken English is fine - we'll help fix it. Non-English is not acceptable.**
--- ---
## OVERVIEW ## OVERVIEW
OpenCode plugin: multi-model agent orchestration (Claude Opus 4.6, GPT-5.3 Codex, Gemini 3 Flash). 40+ lifecycle hooks, 25+ tools (LSP, AST-Grep, delegation), 11 specialized agents, full Claude Code compatibility. "oh-my-zsh" for OpenCode. OpenCode plugin (v3.4.0): multi-model agent orchestration with 11 specialized agents (Claude Opus 4.6, GPT-5.3 Codex, Gemini 3 Flash, GLM-4.7, Grok). 41 lifecycle hooks across 7 event types, 25+ tools (LSP, AST-Grep, delegation, task management), full Claude Code compatibility layer. "oh-my-zsh" for OpenCode.
## STRUCTURE ## STRUCTURE
``` ```
oh-my-opencode/ oh-my-opencode/
├── src/ ├── src/
│ ├── agents/ # 11 AI agents - see src/agents/AGENTS.md │ ├── agents/ # 11 AI agents - see src/agents/AGENTS.md
│ ├── hooks/ # 40+ lifecycle hooks - see src/hooks/AGENTS.md │ ├── hooks/ # 41 lifecycle hooks - see src/hooks/AGENTS.md
│ ├── tools/ # 25+ tools - see src/tools/AGENTS.md │ ├── tools/ # 25+ tools - see src/tools/AGENTS.md
│ ├── features/ # Background agents, skills, Claude Code compat - see src/features/AGENTS.md │ ├── features/ # Background agents, skills, CC compat - see src/features/AGENTS.md
│ ├── shared/ # 88 cross-cutting utilities - see src/shared/AGENTS.md │ ├── shared/ # 84 cross-cutting utilities - see src/shared/AGENTS.md
│ ├── cli/ # CLI installer, doctor - see src/cli/AGENTS.md │ ├── cli/ # CLI installer, doctor - see src/cli/AGENTS.md
│ ├── mcp/ # Built-in MCPs - see src/mcp/AGENTS.md │ ├── mcp/ # Built-in MCPs - see src/mcp/AGENTS.md
│ ├── config/ # Zod schema (schema.ts 455 lines) - see src/config/AGENTS.md │ ├── config/ # Zod schema - see src/config/AGENTS.md
│ ├── plugin-handlers/ # Plugin config loading - see src/plugin-handlers/AGENTS.md │ ├── plugin-handlers/ # Config loading - see src/plugin-handlers/AGENTS.md
│ ├── plugin/ # Plugin SDK types │ ├── plugin/ # Plugin interface composition (21 files)
│ ├── index.ts # Main plugin entry (999 lines) │ ├── index.ts # Main plugin entry (88 lines)
│ ├── create-hooks.ts # Hook creation coordination (core, continuation, skill) │ ├── create-hooks.ts # Hook creation coordination (62 lines)
│ ├── plugin-config.ts # Config loading orchestration │ ├── create-managers.ts # Manager initialization (80 lines)
│ └── plugin-state.ts # Model cache state │ ├── create-tools.ts # Tool registry composition (54 lines)
├── script/ # build-schema.ts, build-binaries.ts, publish.ts, generate-changelog.ts │ ├── plugin-interface.ts # Plugin interface assembly (66 lines)
├── packages/ # 11 platform-specific binaries (darwin-*, linux-*, windows-*) │ ├── plugin-config.ts # Config loading orchestration
└── dist/ # Build output (ESM + .d.ts) │ └── plugin-state.ts # Model cache state
├── script/ # build-schema.ts, build-binaries.ts, publish.ts, generate-changelog.ts
├── packages/ # 7 platform-specific binary packages
└── dist/ # Build output (ESM + .d.ts)
```
## INITIALIZATION FLOW
```
OhMyOpenCodePlugin(ctx)
1. injectServerAuthIntoClient(ctx.client)
2. startTmuxCheck()
3. loadPluginConfig(ctx.directory, ctx) → OhMyOpenCodeConfig
4. createFirstMessageVariantGate()
5. createModelCacheState()
6. createManagers(ctx, config, tmux, cache) → TmuxSessionManager, BackgroundManager, SkillMcpManager, ConfigHandler
7. createTools(ctx, config, managers) → filteredTools, mergedSkills, availableSkills, availableCategories
8. createHooks(ctx, config, backgroundMgr) → 41 hooks (core + continuation + skill)
9. createPluginInterface(...) → tool, chat.params, chat.message, event, tool.execute.before/after
10. Return plugin with experimental.session.compacting
``` ```
## WHERE TO LOOK ## WHERE TO LOOK
| Task | Location | Notes | | Task | Location | Notes |
|------|----------|-------| |------|----------|-------|
| Add agent | `src/agents/` | Create .ts with factory, add to `agentSources` in builtin-agents.ts | | Add agent | `src/agents/` | Create .ts with factory, add to `agentSources` in builtin-agents/ |
| Add hook | `src/hooks/` | Create dir with `createXXXHook()`, register in create-hooks.ts | | Add hook | `src/hooks/` | Create dir, register in `src/plugin/hooks/create-*-hooks.ts` |
| Add tool | `src/tools/` | Dir with index/types/constants/tools.ts | | Add tool | `src/tools/` | Dir with index/types/constants/tools.ts |
| Add MCP | `src/mcp/` | Create config, add to `createBuiltinMcps()` | | Add MCP | `src/mcp/` | Create config, add to `createBuiltinMcps()` |
| Add skill | `src/features/builtin-skills/` | Create dir with SKILL.md | | Add skill | `src/features/builtin-skills/` | Create .ts in skills/ |
| Add command | `src/features/builtin-commands/` | Add template + register in commands.ts | | Add command | `src/features/builtin-commands/` | Add template + register in commands.ts |
| Config schema | `src/config/schema.ts` | Zod schema, run `bun run build:schema` | | Config schema | `src/config/schema/` | 21 schema component files, run `bun run build:schema` |
| Plugin config | `src/plugin-handlers/config-handler.ts` | JSONC loading, merging, migration | | Plugin config | `src/plugin-handlers/config-handler.ts` | JSONC loading, merging, migration |
| Background agents | `src/features/background-agent/` | manager.ts (1646 lines) | | Background agents | `src/features/background-agent/` | manager.ts (1646 lines) |
| Orchestrator | `src/hooks/atlas/` | Main orchestration hook | | Orchestrator | `src/hooks/atlas/` | Main orchestration hook (1976 lines) |
| Delegation | `src/tools/delegate-task/` | Category routing (constants.ts 569 lines) | | Delegation | `src/tools/delegate-task/` | Category routing (constants.ts 569 lines) |
| Task system | `src/features/claude-tasks/` | Task schema, storage, todo sync | | Task system | `src/features/claude-tasks/` | Task schema, storage, todo sync |
| Plugin interface | `src/plugin/` | 21 files composing hooks, handlers, registries |
## TDD (Test-Driven Development) ## TDD (Test-Driven Development)
@ -175,7 +175,7 @@ oh-my-opencode/
**Rules:** **Rules:**
- NEVER write implementation before test - NEVER write implementation before test
- NEVER delete failing tests - fix the code - NEVER delete failing tests - fix the code
- Test file: `*.test.ts` alongside source (163+ test files) - Test file: `*.test.ts` alongside source (176 test files)
- BDD comments: `//#given`, `//#when`, `//#then` - BDD comments: `//#given`, `//#when`, `//#then`
## CONVENTIONS ## CONVENTIONS
@ -185,8 +185,9 @@ oh-my-opencode/
- **Build**: `bun build` (ESM) + `tsc --emitDeclarationOnly` - **Build**: `bun build` (ESM) + `tsc --emitDeclarationOnly`
- **Exports**: Barrel pattern via index.ts - **Exports**: Barrel pattern via index.ts
- **Naming**: kebab-case dirs, `createXXXHook`/`createXXXTool` factories - **Naming**: kebab-case dirs, `createXXXHook`/`createXXXTool` factories
- **Testing**: BDD comments, 163+ test files, 115k+ lines TypeScript - **Testing**: BDD comments, 176 test files, 117k+ lines TypeScript
- **Temperature**: 0.1 for code agents, max 0.3 - **Temperature**: 0.1 for code agents, max 0.3
- **Modular architecture**: 200 LOC hard limit per file (prompt strings exempt)
## ANTI-PATTERNS ## ANTI-PATTERNS
@ -209,22 +210,57 @@ oh-my-opencode/
| Git | Skip hooks (--no-verify), force push without request | | Git | Skip hooks (--no-verify), force push without request |
| Bash | `sleep N` - use conditional waits | | Bash | `sleep N` - use conditional waits |
| Bash | `cd dir && cmd` - use workdir parameter | | Bash | `cd dir && cmd` - use workdir parameter |
| Files | Catch-all utils.ts/helpers.ts - name by purpose |
## AGENT MODELS ## AGENT MODELS
| Agent | Model | Purpose | | Agent | Model | Temp | Purpose |
|-------|-------|---------| |-------|-------|------|---------|
| Sisyphus | anthropic/claude-opus-4-6 | Primary orchestrator (fallback: kimi-k2.5 → glm-4.7 → gpt-5.3-codex → gemini-3-pro) | | Sisyphus | anthropic/claude-opus-4-6 | 0.1 | Primary orchestrator (fallback: kimi-k2.5 → glm-4.7 → gpt-5.3-codex → gemini-3-pro) |
| Hephaestus | openai/gpt-5.3-codex | Autonomous deep worker, "The Legitimate Craftsman" (requires gpt-5.3-codex, no fallback) | | Hephaestus | openai/gpt-5.3-codex | 0.1 | Autonomous deep worker (NO fallback) |
| Atlas | anthropic/claude-sonnet-4-5 | Master orchestrator (fallback: kimi-k2.5 → gpt-5.2) | | Atlas | anthropic/claude-sonnet-4-5 | 0.1 | Master orchestrator (fallback: kimi-k2.5 → gpt-5.2) |
| oracle | openai/gpt-5.2 | Consultation, debugging | | Prometheus | anthropic/claude-opus-4-6 | 0.1 | Strategic planning (fallback: kimi-k2.5 → gpt-5.2) |
| librarian | zai-coding-plan/glm-4.7 | Docs, GitHub search (fallback: glm-4.7-free) | | oracle | openai/gpt-5.2 | 0.1 | Consultation, debugging (fallback: claude-opus-4-6) |
| explore | xai/grok-code-fast-1 | Fast codebase grep (fallback: claude-haiku-4-5 → gpt-5-mini → gpt-5-nano) | | librarian | zai-coding-plan/glm-4.7 | 0.1 | Docs, GitHub search (fallback: glm-4.7-free) |
| multimodal-looker | google/gemini-3-flash | PDF/image analysis | | explore | xai/grok-code-fast-1 | 0.1 | Fast codebase grep (fallback: claude-haiku-4-5 → gpt-5-mini → gpt-5-nano) |
| Prometheus | anthropic/claude-opus-4-6 | Strategic planning (fallback: kimi-k2.5 → gpt-5.2) | | multimodal-looker | google/gemini-3-flash | 0.1 | PDF/image analysis |
| Metis | anthropic/claude-opus-4-6 | Pre-planning analysis (temp 0.3, fallback: kimi-k2.5 → gpt-5.2) | | Metis | anthropic/claude-opus-4-6 | 0.3 | Pre-planning analysis (fallback: kimi-k2.5 → gpt-5.2) |
| Momus | openai/gpt-5.2 | Plan validation (temp 0.1, fallback: claude-opus-4-6) | | Momus | openai/gpt-5.2 | 0.1 | Plan validation (fallback: claude-opus-4-6) |
| Sisyphus-Junior | anthropic/claude-sonnet-4-5 | Category-spawned executor (temp 0.1) | | Sisyphus-Junior | anthropic/claude-sonnet-4-5 | 0.1 | Category-spawned executor |
## OPENCODE PLUGIN API
Plugin SDK from `@opencode-ai/plugin` (v1.1.19). Plugin = `async (PluginInput) => Hooks`.
| Hook | Purpose |
|------|---------|
| `tool` | Register custom tools (Record<string, ToolDefinition>) |
| `chat.message` | Intercept user messages (can modify parts) |
| `chat.params` | Modify LLM parameters (temperature, topP, options) |
| `tool.execute.before` | Pre-tool interception (can modify args) |
| `tool.execute.after` | Post-tool processing (can modify output) |
| `event` | Session lifecycle events (session.created, session.stop, etc.) |
| `config` | Config modification (register agents, MCPs, commands) |
| `experimental.chat.messages.transform` | Transform message history |
| `experimental.session.compacting` | Session compaction customization |
## DEPENDENCIES
| Package | Purpose |
|---------|---------|
| `@opencode-ai/plugin` + `sdk` | OpenCode integration SDK |
| `@ast-grep/cli` + `napi` | AST pattern matching (search/replace) |
| `@code-yeongyu/comment-checker` | AI comment detection/prevention |
| `@modelcontextprotocol/sdk` | MCP client for remote HTTP servers |
| `@clack/prompts` | Interactive CLI TUI |
| `commander` | CLI argument parsing |
| `zod` (v4) | Schema validation for config |
| `jsonc-parser` | JSONC config with comments |
| `picocolors` | Terminal colors |
| `picomatch` | Glob pattern matching |
| `vscode-jsonrpc` | LSP communication |
| `js-yaml` | YAML parsing (tasks, skills) |
| `detect-libc` | Platform binary selection |
## COMMANDS ## COMMANDS
@ -232,7 +268,8 @@ oh-my-opencode/
bun run typecheck # Type check bun run typecheck # Type check
bun run build # ESM + declarations + schema bun run build # ESM + declarations + schema
bun run rebuild # Clean + Build bun run rebuild # Clean + Build
bun test # 163+ test files bun test # 176 test files
bun run build:schema # Regenerate JSON schema
``` ```
## DEPLOYMENT ## DEPLOYMENT
@ -247,35 +284,37 @@ bun test # 163+ test files
| File | Lines | Description | | File | Lines | Description |
|------|-------|-------------| |------|-------|-------------|
| `src/features/background-agent/manager.ts` | 1646 | Task lifecycle, concurrency | | `src/features/background-agent/manager.ts` | 1646 | Task lifecycle, concurrency |
| `src/features/builtin-skills/skills/git-master.ts` | 1111 | Git master skill definition | | `src/hooks/anthropic-context-window-limit-recovery/` | 2232 | Multi-strategy context recovery |
| `src/index.ts` | 999 | Main plugin entry | | `src/hooks/claude-code-hooks/` | 2110 | Claude Code settings.json compat |
| `src/tools/delegate-task/tools.test.ts` | 3582 | Delegation tool tests | | `src/hooks/todo-continuation-enforcer/` | 2061 | Core boulder mechanism |
| `src/features/background-agent/manager.test.ts` | 2843 | Background manager tests | | `src/hooks/atlas/` | 1976 | Session orchestration |
| `src/hooks/atlas/index.test.ts` | 1182 | Atlas hook tests | | `src/hooks/ralph-loop/` | 1687 | Self-referential dev loop |
| `src/agents/hephaestus.ts` | 618 | Autonomous deep worker agent | | `src/hooks/keyword-detector/` | 1665 | Mode detection (ultrawork/search) |
| `src/features/builtin-commands/templates/refactor.ts` | 619 | Refactor command template | | `src/hooks/rules-injector/` | 1604 | Conditional rules injection |
| `src/hooks/think-mode/` | 1365 | Model/variant switching |
| `src/hooks/session-recovery/` | 1279 | Auto error recovery |
| `src/features/builtin-skills/skills/git-master.ts` | 1111 | Git master skill |
| `src/tools/delegate-task/constants.ts` | 569 | Category routing configs | | `src/tools/delegate-task/constants.ts` | 569 | Category routing configs |
| `src/agents/sisyphus.ts` | 530 | Main orchestrator agent |
| `src/agents/utils.ts` | 571 | Agent creation, model fallback resolution |
| `src/plugin-handlers/config-handler.ts` | 563 | Plugin config loading |
## MCP ARCHITECTURE ## MCP ARCHITECTURE
Three-tier system: Three-tier system:
1. **Built-in**: websearch (Exa/Tavily), context7 (docs), grep_app (GitHub) 1. **Built-in** (src/mcp/): websearch (Exa/Tavily), context7 (docs), grep_app (GitHub)
2. **Claude Code compat**: .mcp.json with `${VAR}` expansion 2. **Claude Code compat** (features/claude-code-mcp-loader/): .mcp.json with `${VAR}` expansion
3. **Skill-embedded**: YAML frontmatter in skills 3. **Skill-embedded** (features/opencode-skill-loader/): YAML frontmatter in SKILL.md
## CONFIG SYSTEM ## CONFIG SYSTEM
- **Zod validation**: `src/config/schema.ts` (455 lines) - **Zod validation**: 21 schema component files in `src/config/schema/`
- **JSONC support**: Comments, trailing commas - **JSONC support**: Comments, trailing commas
- **Multi-level**: Project (`.opencode/`) → User (`~/.config/opencode/`) - **Multi-level**: Project (`.opencode/`) → User (`~/.config/opencode/`) → Defaults
- **Loading**: `src/plugin-handlers/config-handler.ts` → merge → validate - **Migration**: Legacy config auto-migration in `src/shared/migration/`
## NOTES ## NOTES
- **OpenCode**: Requires >= 1.0.150 - **OpenCode**: Requires >= 1.0.150
- **1069 TypeScript files**, 176 test files, 117k+ lines
- **Flaky tests**: ralph-loop (CI timeout), session-state (parallel pollution) - **Flaky tests**: ralph-loop (CI timeout), session-state (parallel pollution)
- **Trusted deps**: @ast-grep/cli, @ast-grep/napi, @code-yeongyu/comment-checker - **Trusted deps**: @ast-grep/cli, @ast-grep/napi, @code-yeongyu/comment-checker
- **No linter/formatter**: No ESLint, Prettier, or Biome configured - **No linter/formatter**: No ESLint, Prettier, or Biome configured
- **License**: SUL-1.0 (Sisyphus Use License)

View File

@ -1,88 +1,80 @@
# AGENTS KNOWLEDGE BASE # SRC KNOWLEDGE BASE
## OVERVIEW ## OVERVIEW
Main plugin entry point and orchestration layer. Plugin initialization, hook registration, tool composition, and lifecycle management. Main plugin entry point and orchestration layer. Plugin initialization, hook registration, tool composition, and lifecycle management.
**Core Responsibilities:**
- Plugin initialization via `OhMyOpenCodePlugin()` factory
- Hook registration: `createCoreHooks()`, `createContinuationHooks()`, `createSkillHooks()`
- Tool composition with filtering
- Background agent management via `BackgroundManager`
- MCP lifecycle via `SkillMcpManager`
## STRUCTURE ## STRUCTURE
``` ```
src/ src/
├── index.ts # Main plugin entry (999 lines) ├── index.ts # Main plugin entry (88 lines) — OhMyOpenCodePlugin factory
├── create-hooks.ts # Hook coordination: core, continuation, skill ├── create-hooks.ts # Hook coordination: core, continuation, skill (62 lines)
├── plugin-config.ts # Config loading orchestration ├── create-managers.ts # Manager initialization: Tmux, Background, SkillMcp, Config (80 lines)
├── plugin-state.ts # Model cache state ├── create-tools.ts # Tool registry + skill context composition (54 lines)
├── agents/ # 11 AI agents (20 files) - see agents/AGENTS.md ├── plugin-interface.ts # Plugin interface assembly — 7 OpenCode hooks (66 lines)
├── cli/ # CLI installer, doctor (100+ files) - see cli/AGENTS.md ├── plugin-config.ts # Config loading orchestration (user + project merge)
├── config/ # Zod schema (21 files) - see config/AGENTS.md ├── plugin-state.ts # Model cache state (context limits, anthropic 1M flag)
├── features/ # Background agents, skills, commands (17 dirs) - see features/AGENTS.md ├── agents/ # 11 AI agents (32 files) - see agents/AGENTS.md
├── hooks/ # 40+ lifecycle hooks (30+ dirs) - see hooks/AGENTS.md ├── cli/ # CLI installer, doctor (107+ files) - see cli/AGENTS.md
├── mcp/ # Built-in MCPs (8 files) - see mcp/AGENTS.md ├── config/ # Zod schema (21 component files) - see config/AGENTS.md
├── plugin/ # Plugin SDK types ├── features/ # Background agents, skills, commands (18 dirs) - see features/AGENTS.md
├── plugin-handlers/ # Plugin config loading (5 files) - see plugin-handlers/AGENTS.md ├── hooks/ # 41 lifecycle hooks (36 dirs) - see hooks/AGENTS.md
├── mcp/ # Built-in MCPs (6 files) - see mcp/AGENTS.md
├── plugin/ # Plugin interface composition (21 files)
├── plugin-handlers/ # Config loading, plan inheritance (15 files) - see plugin-handlers/AGENTS.md
├── shared/ # Cross-cutting utilities (84 files) - see shared/AGENTS.md ├── shared/ # Cross-cutting utilities (84 files) - see shared/AGENTS.md
└── tools/ # 25+ tools (14 dirs) - see tools/AGENTS.md └── tools/ # 25+ tools (14 dirs) - see tools/AGENTS.md
``` ```
## KEY COMPONENTS ## PLUGIN INITIALIZATION (10 steps)
**Plugin Initialization:** 1. `injectServerAuthIntoClient(ctx.client)` — Auth injection
- `OhMyOpenCodePlugin()`: Main plugin factory 2. `startTmuxCheck()` — Tmux availability
- Configuration loading via `loadPluginConfig()` 3. `loadPluginConfig(ctx.directory, ctx)` — User + project config merge → Zod validation
- Hook registration with safe creation patterns 4. `createFirstMessageVariantGate()` — First message variant override gate
- Tool composition and disabled tool filtering 5. `createModelCacheState()` — Model context limits cache
6. `createManagers(...)` → 4 managers:
- `TmuxSessionManager` — Multi-pane tmux sessions
- `BackgroundManager` — Parallel subagent execution
- `SkillMcpManager` — MCP server lifecycle
- `ConfigHandler` — Plugin config API to OpenCode
7. `createTools(...)``createSkillContext()` + `createAvailableCategories()` + `createToolRegistry()`
8. `createHooks(...)``createCoreHooks()` + `createContinuationHooks()` + `createSkillHooks()`
9. `createPluginInterface(...)` → 7 OpenCode hook handlers
10. Return plugin with `experimental.session.compacting`
**Lifecycle Management:** ## HOOK REGISTRATION (3 tiers)
- 40+ hooks: session recovery, continuation enforcers, compaction, context injection
- Background agent coordination via `BackgroundManager`
- Tmux session management for multi-pane workflows
- MCP server lifecycle via `SkillMcpManager`
**Tool Ecosystem:** **Core Hooks** (`create-core-hooks.ts`):
- 25+ tools: LSP, AST-grep, delegation, background tasks, skills - Session (20): context-window-monitor, session-recovery, think-mode, ralph-loop, anthropic-effort, ...
- Tool filtering based on agent permissions and user config - Tool Guard (8): comment-checker, tool-output-truncator, rules-injector, write-existing-file-guard, ...
- Metadata restoration for tool outputs - Transform (4): claude-code-hooks, keyword-detector, context-injector, thinking-block-validator
## HOOK REGISTRATION **Continuation Hooks** (`create-continuation-hooks.ts`):
- 7 hooks: stop-continuation-guard, compaction-context-injector, todo-continuation-enforcer, atlas, ...
**Skill Hooks** (`create-skill-hooks.ts`):
- 2 hooks: category-skill-reminder, auto-slash-command
## PLUGIN INTERFACE (7 OpenCode handlers)
| Handler | Source | Purpose |
|---------|--------|---------|
| `tool` | filteredTools | All registered tools |
| `chat.params` | createChatParamsHandler | Anthropic effort level |
| `chat.message` | createChatMessageHandler | First message variant, session setup |
| `experimental.chat.messages.transform` | createMessagesTransformHandler | Context injection, keyword detection |
| `config` | configHandler | Agent/MCP/command registration |
| `event` | createEventHandler | Session lifecycle |
| `tool.execute.before` | createToolExecuteBeforeHandler | Pre-tool hooks |
| `tool.execute.after` | createToolExecuteAfterHandler | Post-tool hooks |
## SAFE HOOK CREATION PATTERN
**Safe Hook Creation:**
```typescript ```typescript
const hook = isHookEnabled("hook-name") const hook = isHookEnabled("hook-name")
? safeCreateHook("hook-name", () => createHookFactory(ctx), { enabled: safeHookEnabled }) ? safeCreateHook("hook-name", () => createHookFactory(ctx), { enabled: safeHookEnabled })
: null; : null;
``` ```
**Hook Categories:** All hooks use this pattern for graceful degradation on failure.
- **Session Management**: recovery, notification, compaction
- **Continuation**: todo/task enforcers, stop guards
- **Context**: injection, rules, directory content
- **Tool Enhancement**: output truncation, error recovery
- **Agent Coordination**: usage reminders, babysitting, delegation
## TOOL COMPOSITION
```typescript
const allTools: Record<string, ToolDefinition> = {
...builtinTools,
...createGrepTools(ctx),
...createAstGrepTools(ctx),
task: delegateTask,
skill: skillTool,
};
```
**Filtering:** Agent permissions, user `disabled_tools`, session state.
## LIFECYCLE FLOW
1. User message triggers agent selection
2. Model/variant resolution applied
3. Tools execute with hook interception
4. Continuation enforcers monitor completion
5. Session compaction preserves context

View File

@ -2,89 +2,99 @@
## OVERVIEW ## OVERVIEW
32 files containing AI agents and utilities for multi-model orchestration. Each agent has factory function + metadata + fallback chains. 11 AI agents with factory functions, fallback chains, and model-specific prompt variants. Each agent has metadata (category, cost, triggers) and configurable tool restrictions.
**Primary Agents** (respect UI model selection):
- Sisyphus, Atlas, Prometheus
**Subagents** (use own fallback chains):
- Hephaestus, Oracle, Librarian, Explore, Multimodal-Looker, Metis, Momus, Sisyphus-Junior
## STRUCTURE ## STRUCTURE
``` ```
agents/ agents/
├── atlas/ # Master Orchestrator (holds todo list) ├── sisyphus.ts # Main orchestrator (530 lines)
│ ├── index.ts ├── hephaestus.ts # Autonomous deep worker (624 lines)
│ ├── default.ts # Claude-optimized prompt (390 lines) ├── oracle.ts # Strategic advisor (170 lines)
│ ├── gpt.ts # GPT-optimized prompt (330 lines) ├── librarian.ts # Multi-repo research (328 lines)
├── explore.ts # Fast codebase grep (124 lines)
├── multimodal-looker.ts # Media analyzer (58 lines)
├── metis.ts # Pre-planning analysis (347 lines)
├── momus.ts # Plan validator (244 lines)
├── atlas/ # Master orchestrator
│ ├── agent.ts # Atlas factory
│ ├── default.ts # Claude-optimized prompt
│ ├── gpt.ts # GPT-optimized prompt
│ └── utils.ts │ └── utils.ts
├── prometheus/ # Planning Agent (Interview/Consultant mode) ├── prometheus/ # Planning agent
│ ├── index.ts │ ├── index.ts
│ ├── system-prompt.ts # 6-section prompt assembly
│ ├── plan-template.ts # Work plan structure (423 lines) │ ├── plan-template.ts # Work plan structure (423 lines)
│ ├── interview-mode.ts # Interview flow (335 lines) │ ├── interview-mode.ts # Interview flow (335 lines)
│ ├── plan-generation.ts │ ├── plan-generation.ts
│ ├── high-accuracy-mode.ts │ ├── high-accuracy-mode.ts
│ ├── identity-constraints.ts # Identity rules (301 lines) │ ├── identity-constraints.ts # Identity rules (301 lines)
│ └── behavioral-summary.ts │ └── behavioral-summary.ts
├── sisyphus-junior/ # Delegated task executor (category-spawned) ├── sisyphus-junior/ # Delegated task executor
│ ├── index.ts │ ├── agent.ts
│ ├── default.ts │ ├── default.ts # Claude prompt
│ └── gpt.ts │ └── gpt.ts # GPT prompt
├── sisyphus.ts # Main orchestrator (530 lines)
├── hephaestus.ts # Autonomous deep worker (618 lines)
├── oracle.ts # Strategic advisor (170 lines)
├── librarian.ts # Multi-repo research (328 lines)
├── explore.ts # Fast codebase grep (124 lines)
├── multimodal-looker.ts # Media analyzer (58 lines)
├── metis.ts # Pre-planning analysis (346 lines)
├── momus.ts # Plan validator (243 lines)
├── dynamic-agent-prompt-builder.ts # Dynamic prompt generation (431 lines) ├── dynamic-agent-prompt-builder.ts # Dynamic prompt generation (431 lines)
├── builtin-agents.ts # Agent registry (179 lines) ├── builtin-agents/ # Agent registry (8 files)
├── types.ts # AgentModelConfig, AgentPromptMetadata
├── utils.ts # Agent creation, model fallback resolution (571 lines) ├── utils.ts # Agent creation, model fallback resolution (571 lines)
├── types.ts # AgentModelConfig, AgentPromptMetadata
└── index.ts # Exports └── index.ts # Exports
``` ```
## AGENT MODELS ## AGENT MODELS
| Agent | Model | Temp | Purpose |
|-------|-------|------|---------|
| Sisyphus | anthropic/claude-opus-4-6 | 0.1 | Primary orchestrator (fallback: kimi-k2.5 → glm-4.7 → gpt-5.3-codex → gemini-3-pro) |
| Hephaestus | openai/gpt-5.3-codex | 0.1 | Autonomous deep worker, "The Legitimate Craftsman" (requires gpt-5.3-codex, no fallback) |
| Atlas | anthropic/claude-sonnet-4-5 | 0.1 | Master orchestrator (fallback: kimi-k2.5 → gpt-5.2) |
| oracle | openai/gpt-5.2 | 0.1 | Consultation, debugging |
| librarian | zai-coding-plan/glm-4.7 | 0.1 | Docs, GitHub search (fallback: glm-4.7-free) |
| explore | xai/grok-code-fast-1 | 0.1 | Fast contextual grep (fallback: claude-haiku-4-5 → gpt-5-mini → gpt-5-nano) |
| multimodal-looker | google/gemini-3-flash | 0.1 | PDF/image analysis |
| Prometheus | anthropic/claude-opus-4-6 | 0.1 | Strategic planning (fallback: kimi-k2.5 → gpt-5.2) |
| Metis | anthropic/claude-opus-4-6 | 0.3 | Pre-planning analysis (fallback: kimi-k2.5 → gpt-5.2) |
| Momus | openai/gpt-5.2 | 0.1 | Plan validation (fallback: claude-opus-4-6) |
| Sisyphus-Junior | anthropic/claude-sonnet-4-5 | 0.1 | Category-spawned executor |
## HOW TO ADD | Agent | Model | Temp | Fallback Chain | Cost |
1. Create `src/agents/my-agent.ts` exporting factory + metadata. |-------|-------|------|----------------|------|
2. Add to `agentSources` in `src/agents/builtin-agents.ts`. | Sisyphus | claude-opus-4-6 | 0.1 | kimi-k2.5 → glm-4.7 → gpt-5.3-codex → gemini-3-pro | EXPENSIVE |
3. Update `AgentNameSchema` in `src/config/schema.ts`. | Hephaestus | gpt-5.3-codex | 0.1 | NONE (required) | EXPENSIVE |
4. Register in `src/index.ts` initialization. | Atlas | claude-sonnet-4-5 | 0.1 | kimi-k2.5 → gpt-5.2 | EXPENSIVE |
| Prometheus | claude-opus-4-6 | 0.1 | kimi-k2.5 → gpt-5.2 | EXPENSIVE |
| oracle | gpt-5.2 | 0.1 | claude-opus-4-6 | EXPENSIVE |
| librarian | glm-4.7 | 0.1 | glm-4.7-free | CHEAP |
| explore | grok-code-fast-1 | 0.1 | claude-haiku-4-5 → gpt-5-mini → gpt-5-nano | FREE |
| multimodal-looker | gemini-3-flash | 0.1 | NONE | CHEAP |
| Metis | claude-opus-4-6 | 0.3 | kimi-k2.5 → gpt-5.2 | EXPENSIVE |
| Momus | gpt-5.2 | 0.1 | claude-opus-4-6 | EXPENSIVE |
| Sisyphus-Junior | claude-sonnet-4-5 | 0.1 | (user-configurable) | EXPENSIVE |
## TOOL RESTRICTIONS ## TOOL RESTRICTIONS
| Agent | Denied Tools |
|-------|-------------|
| oracle | write, edit, task, task |
| librarian | write, edit, task, task, call_omo_agent |
| explore | write, edit, task, task, call_omo_agent |
| multimodal-looker | Allowlist: read only |
| Sisyphus-Junior | task, task |
| Atlas | task, call_omo_agent |
## PATTERNS | Agent | Denied | Allowed |
- **Factory**: `createXXXAgent(model: string): AgentConfig` |-------|--------|---------|
| oracle | write, edit, task, call_omo_agent | Read-only consultation |
| librarian | write, edit, task, call_omo_agent | Research tools only |
| explore | write, edit, task, call_omo_agent | Search tools only |
| multimodal-looker | ALL except `read` | Vision-only |
| Sisyphus-Junior | task | No delegation |
| Atlas | task, call_omo_agent | Orchestration only |
## THINKING / REASONING
| Agent | Claude | GPT |
|-------|--------|-----|
| Sisyphus | 32k budget tokens | reasoningEffort: "medium" |
| Hephaestus | — | reasoningEffort: "medium" |
| Oracle | 32k budget tokens | reasoningEffort: "medium" |
| Metis | 32k budget tokens | — |
| Momus | 32k budget tokens | reasoningEffort: "medium" |
| Sisyphus-Junior | 32k budget tokens | reasoningEffort: "medium" |
## HOW TO ADD
1. Create `src/agents/my-agent.ts` exporting factory + metadata
2. Add to `agentSources` in `src/agents/builtin-agents/`
3. Update `AgentNameSchema` in `src/config/schema/agent-names.ts`
4. Register in `src/plugin-handlers/agent-config-handler.ts`
## KEY PATTERNS
- **Factory**: `createXXXAgent(model): AgentConfig`
- **Metadata**: `XXX_PROMPT_METADATA` with category, cost, triggers - **Metadata**: `XXX_PROMPT_METADATA` with category, cost, triggers
- **Tool restrictions**: `createAgentToolRestrictions(tools)` or `createAgentToolAllowlist(tools)` - **Model-specific prompts**: Atlas, Sisyphus-Junior have GPT vs Claude variants
- **Thinking**: 32k budget tokens for Sisyphus, Oracle, Prometheus, Atlas - **Dynamic prompts**: Sisyphus, Hephaestus use `dynamic-agent-prompt-builder.ts` to inject available tools/skills/categories
- **Model-specific routing**: Atlas, Sisyphus-Junior have GPT vs Claude prompt variants
## ANTI-PATTERNS ## ANTI-PATTERNS
- **Trust reports**: NEVER trust "I'm done" - verify outputs
- **High temp**: Don't use >0.3 for code agents - **Trust agent self-reports**: NEVER — always verify outputs
- **High temperature**: Don't use >0.3 for code agents
- **Sequential calls**: Use `task` with `run_in_background` for exploration - **Sequential calls**: Use `task` with `run_in_background` for exploration
- **Prometheus writing code**: Planner only - never implements - **Prometheus writing code**: Planner only never implements

View File

@ -2,68 +2,71 @@
## OVERVIEW ## OVERVIEW
CLI entry: `bunx oh-my-opencode`. 107 CLI utilities with Commander.js + @clack/prompts TUI. CLI entry: `bunx oh-my-opencode`. 107+ files with Commander.js + @clack/prompts TUI.
**Commands**: install (interactive setup), doctor (14 health checks), run (session launcher), get-local-version, mcp-oauth **Commands**: install, run, doctor, get-local-version, mcp-oauth
## STRUCTURE ## STRUCTURE
``` ```
cli/ cli/
├── index.ts # Commander.js entry (5 commands) ├── index.ts # Entry point (5 lines)
├── install.ts # TTY routing to TUI or CLI installer ├── cli-program.ts # Commander.js program (150+ lines, 5 commands)
├── install.ts # TTY routing (TUI or CLI installer)
├── cli-installer.ts # Non-interactive installer (164 lines) ├── cli-installer.ts # Non-interactive installer (164 lines)
├── tui-installer.ts # Interactive TUI with @clack/prompts (140 lines) ├── tui-installer.ts # Interactive TUI with @clack/prompts (140 lines)
├── config-manager/ # Config management utilities (17 files) ├── config-manager/ # 17 config utilities
├── model-fallback.ts # Model fallback configuration │ ├── add-plugin-to-opencode-config.ts # Plugin registration
├── model-fallback.test.ts # Fallback tests (523 lines) │ ├── add-provider-config.ts # Provider setup
├── doctor/ │ ├── detect-current-config.ts # Project vs user config
│ ├── write-omo-config.ts # JSONC writing
│ └── ...
├── doctor/ # 14 health checks
│ ├── runner.ts # Check orchestration │ ├── runner.ts # Check orchestration
│ ├── formatter.ts # Colored output │ ├── formatter.ts # Colored output
│ └── checks/ # 29 files with individual checks │ └── checks/ # 29 files: auth, config, dependencies, gh, lsp, mcp, opencode, plugin, version, model-resolution (6 sub-checks)
├── run/ # Session launcher (24 files) ├── run/ # Session launcher (24 files)
│ ├── events.ts # CLI run events │ ├── runner.ts # Run orchestration (126 lines)
│ └── runner.ts # Run orchestration │ ├── agent-resolver.ts # Agent selection: flag → env → config → fallback
├── mcp-oauth/ # OAuth flow │ ├── session-resolver.ts # Session creation or resume
└── get-local-version/ # Version detection │ ├── event-handlers.ts # Event processing (125 lines)
│ ├── completion.ts # Completion detection
│ └── poll-for-completion.ts # Polling with timeout
├── mcp-oauth/ # OAuth token management (login, logout, status)
├── get-local-version/ # Version detection + update check
├── model-fallback.ts # Model fallback configuration
└── provider-availability.ts # Provider availability checks
``` ```
## COMMANDS ## COMMANDS
| Command | Purpose | | Command | Purpose | Key Logic |
|---------|---------| |---------|---------|-----------|
| `install` | Interactive setup with provider selection | | `install` | Interactive setup | Provider selection → config generation → plugin registration |
| `doctor` | 14 health checks for diagnostics | | `run` | Session launcher | Agent: flag → env → config → Sisyphus. Enforces todo completion. |
| `run` | Launch session with todo enforcement | | `doctor` | 14 health checks | installation, config, auth, deps, tools, updates |
| `get-local-version` | Version detection and update check | | `get-local-version` | Version check | Detects installed, compares with npm latest |
| `mcp-oauth` | MCP OAuth authentication flow | | `mcp-oauth` | OAuth tokens | login (PKCE flow), logout, status |
## DOCTOR CATEGORIES (14 Checks) ## DOCTOR CHECK CATEGORIES
| Category | Checks | | Category | Checks |
|----------|--------| |----------|--------|
| installation | opencode, plugin | | installation | opencode, plugin |
| configuration | config validity, Zod, model-resolution | | configuration | config validity, Zod, model-resolution (6 sub-checks) |
| authentication | anthropic, openai, google | | authentication | anthropic, openai, google |
| dependencies | ast-grep, comment-checker, gh-cli | | dependencies | ast-grep, comment-checker, gh-cli |
| tools | LSP, MCP | | tools | LSP, MCP, MCP-OAuth |
| updates | version comparison | | updates | version comparison |
## HOW TO ADD CHECK ## HOW TO ADD CHECK
1. Create `src/cli/doctor/checks/my-check.ts` 1. Create `src/cli/doctor/checks/my-check.ts`
2. Export `getXXXCheckDefinition()` factory returning `CheckDefinition` 2. Export `getXXXCheckDefinition()` returning `CheckDefinition`
3. Add to `getAllCheckDefinitions()` in `checks/index.ts` 3. Add to `getAllCheckDefinitions()` in `checks/index.ts`
## TUI FRAMEWORK
- **@clack/prompts**: `select()`, `spinner()`, `intro()`, `outro()`
- **picocolors**: Terminal colors for status and headers
- **Symbols**: check (pass), cross (fail), warning (warn), info (info)
## ANTI-PATTERNS ## ANTI-PATTERNS
- **Blocking in non-TTY**: Always check `process.stdout.isTTY` - **Blocking in non-TTY**: Check `process.stdout.isTTY`
- **Direct JSON.parse**: Use `parseJsonc()` from shared utils - **Direct JSON.parse**: Use `parseJsonc()` from shared
- **Silent failures**: Return `warn` or `fail` in doctor instead of throwing - **Silent failures**: Return `warn` or `fail` in doctor, don't throw
- **Hardcoded paths**: Use `getOpenCodeConfigPaths()` from `config-manager` - **Hardcoded paths**: Use `getOpenCodeConfigPaths()` from config-manager

View File

@ -1,87 +1,52 @@
**Generated:** 2026-02-09T14:16:00+09:00 # CONFIG KNOWLEDGE BASE
**Commit:** f22f14d9
**Branch:** dev
## OVERVIEW ## OVERVIEW
Zod schema definitions for plugin configuration. 455+ lines of type-safe config validation with JSONC support, multi-level inheritance, and comprehensive agent/category overrides. Zod schema definitions for plugin configuration. 21 component files composing `OhMyOpenCodeConfigSchema` with multi-level inheritance and JSONC support.
## STRUCTURE ## STRUCTURE
``` ```
config/ config/
├── schema/ # Schema components (21 files) ├── schema/ # 21 schema component files
│ ├── index.ts # Main schema composition │ ├── oh-my-opencode-config.ts # Root schema composition (57 lines)
│ └── [module].ts # Agent names, overrides, categories, hooks, etc. │ ├── agent-names.ts # BuiltinAgentNameSchema (11 agents), BuiltinSkillNameSchema
├── schema.ts # Main Zod schema (455 lines) │ ├── agent-overrides.ts # AgentOverrideConfigSchema (model, variant, temp, thinking...)
├── schema.test.ts # Schema validation tests (735 lines) │ ├── categories.ts # 8 categories: visual-engineering, ultrabrain, deep, artistry, quick, ...
├── types.ts # TypeScript types │ ├── hooks.ts # HookNameSchema (100+ hook names)
└── index.ts # Barrel export │ ├── commands.ts # BuiltinCommandNameSchema
│ ├── experimental.ts # ExperimentalConfigSchema
│ ├── dynamic-context-pruning.ts # DynamicContextPruningConfigSchema (55 lines)
│ ├── background-task.ts # BackgroundTaskConfigSchema
│ ├── claude-code.ts # ClaudeCodeConfigSchema
│ ├── comment-checker.ts # CommentCheckerConfigSchema
│ ├── notification.ts # NotificationConfigSchema
│ ├── ralph-loop.ts # RalphLoopConfigSchema
│ ├── sisyphus.ts # SisyphusConfigSchema
│ ├── sisyphus-agent.ts # SisyphusAgentConfigSchema
│ ├── skills.ts # SkillsConfigSchema (45 lines)
│ ├── tmux.ts # TmuxConfigSchema, TmuxLayoutSchema
│ ├── websearch.ts # WebsearchConfigSchema
│ ├── browser-automation.ts # BrowserAutomationConfigSchema
│ ├── git-master.ts # GitMasterConfigSchema
│ └── babysitting.ts # BabysittingConfigSchema
├── schema.ts # Barrel export (24 lines)
├── schema.test.ts # Validation tests (735 lines)
├── types.ts # TypeScript types from schemas
└── index.ts # Barrel export (33 lines)
``` ```
## SCHEMA COMPONENTS ## ROOT SCHEMA
**Agent Config:** `AgentOverrideConfigSchema`, `AgentOverridesSchema`, `AgentPermissionSchema` `OhMyOpenCodeConfigSchema` composes: `$schema`, `new_task_system_enabled`, `default_run_agent`, `auto_update`, `disabled_{mcps,agents,skills,hooks,commands,tools}`, `agents` (14 agent keys), `categories` (8 built-in), `claude_code`, `sisyphus_agent`, `comment_checker`, `experimental`, `skills`, `ralph_loop`, `background_task`, `notification`, `babysitting`, `git_master`, `browser_automation_engine`, `websearch`, `tmux`, `sisyphus`
**Category Config:** `CategoryConfigSchema`, `CategoriesConfigSchema` (visual-engineering, ultrabrain, deep)
**Experimental:** `ExperimentalConfigSchema`, `DynamicContextPruningConfigSchema`
**Built-in Enums:** `AgentNameSchema` (11 agents), `HookNameSchema` (100+ hooks), `BuiltinCommandNameSchema`, `BuiltinSkillNameSchema`
## CONFIGURATION HIERARCHY ## CONFIGURATION HIERARCHY
1. **Project config** (`.opencode/oh-my-opencode.json`) Project (`.opencode/oh-my-opencode.json`) → User (`~/.config/opencode/oh-my-opencode.json`) → Defaults
2. **User config** (`~/.config/opencode/oh-my-opencode.json`)
3. **Defaults** (hardcoded fallbacks)
**Multi-level inheritance:** Project → User → Defaults ## AGENT OVERRIDE FIELDS
## VALIDATION FEATURES `model`, `variant`, `category`, `skills`, `temperature`, `top_p`, `maxTokens`, `thinking`, `reasoningEffort`, `textVerbosity`, `prompt`, `prompt_append`, `tools`, `permission`, `providerOptions`, `disable`, `description`, `mode`, `color`
- **JSONC support**: Comments and trailing commas ## AFTER SCHEMA CHANGES
- **Type safety**: Full TypeScript inference
- **Migration support**: Legacy config compatibility
- **Schema versioning**: $schema field for validation
## KEY SCHEMAS Run `bun run build:schema` to regenerate `dist/oh-my-opencode.schema.json`
| Schema | Purpose | Lines |
|--------|---------|-------|
| `OhMyOpenCodeConfigSchema` | Root config schema | 400+ |
| `AgentOverrideConfigSchema` | Agent customization | 50+ |
| `CategoryConfigSchema` | Task category defaults | 30+ |
| `ExperimentalConfigSchema` | Beta features | 40+ |
## USAGE PATTERNS
**Agent Override:**
```typescript
agents: {
sisyphus: {
model: "anthropic/claude-opus-4-6",
variant: "max",
temperature: 0.1
}
}
```
**Category Definition:**
```typescript
categories: {
"visual-engineering": {
model: "google/gemini-3-pro",
variant: "high"
}
}
```
**Experimental Features:**
```typescript
experimental: {
dynamic_context_pruning: {
enabled: true,
notification: "detailed"
}
}
```

View File

@ -2,53 +2,70 @@
## OVERVIEW ## OVERVIEW
Background systems that extend plugin capabilities: agents, skills, Claude Code compatibility layer, MCP managers, and task orchestration. 18 feature modules extending plugin capabilities: agent orchestration, skill loading, Claude Code compatibility, MCP management, task storage, and tmux integration.
## STRUCTURE ## STRUCTURE
``` ```
features/ features/
├── background-agent/ # Task lifecycle, concurrency (manager.ts 1646 lines, concurrency.ts) ├── background-agent/ # Task lifecycle, concurrency (50 files, 8330 LOC)
├── boulder-state/ # Persistent state for multi-step operations │ ├── manager.ts # Main task orchestration (1646 lines)
├── builtin-commands/ # Command templates: refactor (619 lines), ralph-loop, handoff, init-deep │ ├── concurrency.ts # Parallel execution limits per provider/model
├── builtin-skills/ # Skills: git-master (1111 lines), playwright, dev-browser, frontend-ui-ux │ └── spawner/ # Task spawning utilities (8 files)
├── claude-code-agent-loader/ # CC agent loading from .opencode/agents/ ├── tmux-subagent/ # Tmux integration (28 files, 3303 LOC)
├── claude-code-command-loader/ # CC command loading from .opencode/commands/ │ └── manager.ts # Pane management, grid planning (350 lines)
├── claude-code-mcp-loader/ # CC MCP loading from .opencode/mcp/ ├── opencode-skill-loader/ # YAML frontmatter skill loading (28 files, 2967 LOC)
├── claude-code-plugin-loader/ # CC plugin discovery from .opencode/plugins/ │ ├── loader.ts # Skill discovery (4 scopes)
├── claude-code-session-state/ # Subagent session state tracking │ ├── skill-directory-loader.ts # Recursive directory scanning
├── claude-tasks/ # Task schema + storage (has own AGENTS.md) │ ├── skill-discovery.ts # getAllSkills() with caching
├── context-injector/ # Auto-injects AGENTS.md, README.md, rules │ └── merger/ # Skill merging with scope priority
├── hook-message-injector/ # System message injection ├── mcp-oauth/ # OAuth 2.0 flow for MCP (18 files, 2164 LOC)
├── mcp-oauth/ # OAuth flow for MCP servers │ ├── provider.ts # McpOAuthProvider class
├── opencode-skill-loader/ # YAML frontmatter skill loading │ ├── oauth-authorization-flow.ts # PKCE, callback handling
├── skill-mcp-manager/ # MCP client lifecycle per session (manager.ts 150 lines) │ └── dcr.ts # Dynamic Client Registration (RFC 7591)
├── task-toast-manager/ # Task progress notifications ├── skill-mcp-manager/ # MCP client lifecycle per session (12 files, 1769 LOC)
├── tmux-subagent/ # Tmux integration (manager.ts 350 lines) │ └── manager.ts # SkillMcpManager class (150 lines)
└── tool-metadata-store/ # Tool execution metadata caching ├── builtin-skills/ # 5 built-in skills (10 files, 1921 LOC)
│ └── skills/ # git-master (1111), playwright, dev-browser, frontend-ui-ux
├── builtin-commands/ # 6 command templates (11 files, 1511 LOC)
│ └── templates/ # refactor, ralph-loop, init-deep, handoff, start-work, stop-continuation
├── claude-tasks/ # Task schema + storage (7 files, 1165 LOC)
├── context-injector/ # AGENTS.md, README.md, rules injection (6 files, 809 LOC)
├── claude-code-plugin-loader/ # Plugin discovery from .opencode/plugins/ (10 files)
├── claude-code-mcp-loader/ # .mcp.json with ${VAR} expansion (6 files)
├── claude-code-command-loader/ # Command loading from .opencode/commands/ (3 files)
├── claude-code-agent-loader/ # Agent loading from .opencode/agents/ (3 files)
├── claude-code-session-state/ # Subagent session state tracking (3 files)
├── hook-message-injector/ # System message injection (4 files)
├── task-toast-manager/ # Task progress notifications (4 files)
├── boulder-state/ # Persistent state for multi-step ops (5 files)
└── tool-metadata-store/ # Tool execution metadata caching (3 files)
``` ```
## KEY PATTERNS ## KEY PATTERNS
**Background Agent Lifecycle:** **Background Agent Lifecycle:**
- Task creation -> Queue -> Concurrency check -> Execute -> Monitor -> Cleanup Task creation → Queue → Concurrency check → Execute → Monitor/Poll → Notification → Cleanup
- Manager.ts handles full lifecycle with 1646 lines of task orchestration
- Concurrency.ts manages parallel execution limits per provider/model **Skill Loading Pipeline (4-scope priority):**
- Tasks survive session restarts via persistent storage opencode-project (`.opencode/skills/`) > opencode (`~/.config/opencode/skills/`) > project (`.claude/skills/`) > user (`~/.claude/skills/`)
**Claude Code Compatibility Layer:** **Claude Code Compatibility Layer:**
5 directories provide full CC compatibility: 5 loaders: agent-loader, command-loader, mcp-loader, plugin-loader, session-state
- agent-loader: Loads custom agents from .opencode/agents/
- command-loader: Loads slash commands from .opencode/commands/
- mcp-loader: Loads MCP servers from .opencode/mcp/
- plugin-loader: Discovers plugins from .opencode/plugins/
- session-state: Tracks subagent session state and recovery
**Skill Loading Pipeline:** **SKILL.md Format:**
1. opencode-skill-loader: Parses YAML frontmatter from skill files ```yaml
2. skill-mcp-manager: Manages MCP lifecycle per skill session (manager.ts 150 lines) ---
3. Context injection: Auto-loads AGENTS.md, README.md, rules into context name: my-skill
4. Hook message injector: Injects system messages for skill activation description: "..."
model: "claude-opus-4-6" # optional
agent: "sisyphus" # optional
mcp: # optional embedded MCPs
server-name:
type: http
url: https://...
---
# Skill instruction content
```
## HOW TO ADD ## HOW TO ADD

View File

@ -1,16 +1,15 @@
# CLAUDE TASKS FEATURE KNOWLEDGE BASE # CLAUDE TASKS KNOWLEDGE BASE
## OVERVIEW ## OVERVIEW
Claude Code compatible task schema and storage. Provides core task management utilities used by task-related tools and features. Claude Code compatible task schema and storage. Core task management with file-based persistence and atomic writes.
## STRUCTURE ## STRUCTURE
``` ```
claude-tasks/ claude-tasks/
├── types.ts # Task schema (Zod) ├── types.ts # Task schema (Zod)
├── types.test.ts # Schema validation tests (8 tests) ├── types.test.ts # Schema validation tests
├── storage.ts # File operations ├── storage.ts # File operations (atomic write, locking)
├── storage.test.ts # Storage tests (30 tests, 543 lines) ├── storage.test.ts # Storage tests (30 tests, 543 lines)
├── session-storage.ts # Session-scoped task storage ├── session-storage.ts # Session-scoped task storage
├── session-storage.test.ts ├── session-storage.test.ts
@ -21,44 +20,36 @@ claude-tasks/
```typescript ```typescript
type TaskStatus = "pending" | "in_progress" | "completed" | "deleted" type TaskStatus = "pending" | "in_progress" | "completed" | "deleted"
interface Task { interface Task {
id: string id: string // T-{uuid}
subject: string // Imperative: "Run tests" (was: title) subject: string // Imperative: "Run tests"
description: string description: string
status: TaskStatus status: TaskStatus
activeForm?: string // Present continuous: "Running tests" activeForm?: string // Present continuous: "Running tests"
blocks: string[] // Task IDs this task blocks blocks: string[] // Task IDs this task blocks
blockedBy: string[] // Task IDs blocking this task (was: dependsOn) blockedBy: string[] // Task IDs blocking this task
owner?: string // Agent name owner?: string // Agent name
metadata?: Record<string, unknown> metadata?: Record<string, unknown>
repoURL?: string
parentID?: string
threadID?: string
} }
``` ```
**Key Differences from Legacy**:
- `subject` (was `title`)
- `blockedBy` (was `dependsOn`)
- `blocks` (new field)
- `activeForm` (new field)
## STORAGE UTILITIES ## STORAGE UTILITIES
| Function | Purpose | | Function | Purpose |
|----------|---------| |----------|---------|
| `getTaskDir(config)` | Returns task storage directory path | | `getTaskDir(config)` | Task storage directory path |
| `resolveTaskListId(config)` | Resolves task list ID (env → config → cwd basename) | | `resolveTaskListId(config)` | Task list ID (env → config → cwd) |
| `readJsonSafe(path, schema)` | Parse + validate, returns null on failure | | `readJsonSafe(path, schema)` | Parse + validate, null on failure |
| `writeJsonAtomic(path, data)` | Atomic write via temp file + rename | | `writeJsonAtomic(path, data)` | Atomic write via temp + rename |
| `acquireLock(dirPath)` | File-based lock with 30s stale threshold | | `acquireLock(dirPath)` | File lock with 30s stale threshold |
| `generateTaskId()` | Generates `T-{uuid}` task ID | | `generateTaskId()` | `T-{uuid}` format |
| `listTaskFiles(config)` | Lists all task IDs in storage | | `findTaskAcrossSessions(config, taskId)` | Locate task in any session |
| `getSessionTaskDir(config, sessionID)` | Returns session-scoped task directory |
| `listSessionTaskFiles(config, sessionID)` | Lists tasks for specific session |
| `findTaskAcrossSessions(config, taskId)` | Locates task in any session directory |
## ANTI-PATTERNS ## ANTI-PATTERNS
- Direct fs operations (use storage utilities) - Direct fs operations (use storage utilities)
- Skipping lock acquisition for writes - Skipping lock acquisition for writes
- Ignoring null returns from readJsonSafe - Using old field names (title → subject, dependsOn → blockedBy)
- Using old schema field names (title, dependsOn)

View File

@ -2,48 +2,40 @@
## OVERVIEW ## OVERVIEW
163 lifecycle hooks intercepting/modifying agent behavior across 5 events. 41 lifecycle hooks intercepting/modifying agent behavior across 7 event types. Three-tier registration: Core (32) → Continuation (7) → Skill (2).
**Event Types**:
- `UserPromptSubmit` (`chat.message`) - Can block
- `PreToolUse` (`tool.execute.before`) - Can block
- `PostToolUse` (`tool.execute.after`) - Cannot block
- `Stop` (`event: session.stop`) - Cannot block
- `onSummarize` (Compaction) - Cannot block
## STRUCTURE ## STRUCTURE
``` ```
hooks/ hooks/
├── agent-usage-reminder/ # Specialized agent hints (212 lines) ├── agent-usage-reminder/ # Specialized agent hints (109 lines)
├── anthropic-context-window-limit-recovery/ # Auto-summarize on limit (2232 lines) ├── anthropic-context-window-limit-recovery/ # Auto-summarize on limit (2232 lines)
├── anthropic-effort/ # Anthropic effort level management (272 lines) ├── anthropic-effort/ # Effort=max for Opus max variant (56 lines)
├── atlas/ # Main orchestration hook (1976 lines) ├── atlas/ # Main orchestration hook (1976 lines)
├── auto-slash-command/ # Detects /command patterns (1134 lines) ├── auto-slash-command/ # Detects /command patterns (1134 lines)
├── auto-update-checker/ # Plugin update check (1140 lines) ├── auto-update-checker/ # Plugin update check (1140 lines)
├── background-notification/ # OS notifications (33 lines) ├── background-notification/ # OS notifications (33 lines)
├── category-skill-reminder/ # Reminds of category skills (597 lines) ├── category-skill-reminder/ # Category+skill delegation reminders (597 lines)
├── claude-code-hooks/ # settings.json compat - see AGENTS.md (2110 lines) ├── claude-code-hooks/ # settings.json compat (2110 lines) - see AGENTS.md
├── comment-checker/ # Prevents AI slop comments (710 lines) ├── comment-checker/ # Prevents AI slop comments (710 lines)
├── compaction-context-injector/ # Injects context on compaction (128 lines) ├── compaction-context-injector/ # Injects context on compaction (128 lines)
├── compaction-todo-preserver/ # Preserves todos during compaction (203 lines) ├── compaction-todo-preserver/ # Preserves todos during compaction (203 lines)
├── context-window-monitor.ts # Reminds of headroom (99 lines) ├── context-window-monitor.ts # Reminds of headroom at 70% (99 lines)
├── delegate-task-retry/ # Retries failed delegations (266 lines) ├── delegate-task-retry/ # Retries failed delegations (266 lines)
├── directory-agents-injector/ # Auto-injects AGENTS.md (195 lines) ├── directory-agents-injector/ # Auto-injects AGENTS.md (195 lines)
├── directory-readme-injector/ # Auto-injects README.md (190 lines) ├── directory-readme-injector/ # Auto-injects README.md (190 lines)
├── edit-error-recovery/ # Recovers from edit failures (188 lines) ├── edit-error-recovery/ # Recovers from edit failures (188 lines)
├── empty-task-response-detector.ts # Detects empty responses (27 lines) ├── empty-task-response-detector.ts # Detects empty responses (27 lines)
├── index.ts # Hook aggregation + registration (46 lines)
├── interactive-bash-session/ # Tmux session management (695 lines) ├── interactive-bash-session/ # Tmux session management (695 lines)
├── keyword-detector/ # ultrawork/search/analyze modes (1665 lines) ├── keyword-detector/ # ultrawork/search/analyze modes (1665 lines)
├── non-interactive-env/ # Non-TTY environment handling (483 lines) ├── non-interactive-env/ # Non-TTY handling (483 lines)
├── preemptive-compaction.ts # Preemptive context compaction (108 lines) ├── preemptive-compaction.ts # Auto-compact at 78% usage (108 lines)
├── prometheus-md-only/ # Planner read-only mode (955 lines) ├── prometheus-md-only/ # Planner read-only mode (955 lines)
├── question-label-truncator/ # Auto-truncates question labels (199 lines) ├── question-label-truncator/ # Truncates labels to 30 chars (199 lines)
├── ralph-loop/ # Self-referential dev loop (1687 lines) ├── ralph-loop/ # Self-referential dev loop (1687 lines)
├── rules-injector/ # Conditional rules injection (1604 lines) ├── rules-injector/ # Conditional .sisyphus/rules injection (1604 lines)
├── session-notification.ts # Session event notifications (108 lines) ├── session-notification.ts # OS idle notifications (108 lines)
├── session-recovery/ # Auto-recovers from crashes (1279 lines) ├── session-recovery/ # Auto-recovers from crashes (1279 lines)
├── sisyphus-junior-notepad/ # Sisyphus Junior notepad (76 lines) ├── sisyphus-junior-notepad/ # Junior notepad directive (76 lines)
├── start-work/ # Sisyphus work session starter (648 lines) ├── start-work/ # Sisyphus work session starter (648 lines)
├── stop-continuation-guard/ # Guards stop continuation (214 lines) ├── stop-continuation-guard/ # Guards stop continuation (214 lines)
├── subagent-question-blocker/ # Blocks subagent questions (112 lines) ├── subagent-question-blocker/ # Blocks subagent questions (112 lines)
@ -51,54 +43,53 @@ hooks/
├── task-resume-info/ # Resume info for cancelled tasks (39 lines) ├── task-resume-info/ # Resume info for cancelled tasks (39 lines)
├── tasks-todowrite-disabler/ # Disables TodoWrite when tasks active (202 lines) ├── tasks-todowrite-disabler/ # Disables TodoWrite when tasks active (202 lines)
├── think-mode/ # Dynamic thinking budget (1365 lines) ├── think-mode/ # Dynamic thinking budget (1365 lines)
├── thinking-block-validator/ # Ensures valid <thinking> blocks (169 lines) ├── thinking-block-validator/ # Validates thinking blocks (169 lines)
├── todo-continuation-enforcer/ # Force TODO completion (2061 lines) ├── todo-continuation-enforcer/ # Force TODO completion — boulder mechanism (2061 lines)
├── tool-output-truncator.ts # Prevents context bloat (62 lines) ├── tool-output-truncator.ts # Prevents context bloat (62 lines)
├── unstable-agent-babysitter/ # Monitors unstable agent behavior (451 lines) ├── unstable-agent-babysitter/ # Monitors unstable behavior (451 lines)
└── write-existing-file-guard/ # Guards against overwriting files (356 lines) └── write-existing-file-guard/ # Guards against file overwrite (356 lines)
``` ```
## HOOK EVENTS ## EVENT TYPES
| Event | Timing | Can Block | Use Case |
|-------|--------|-----------|----------| | Event | Hook Method | Can Block | Count |
| UserPromptSubmit | `chat.message` | Yes | Keyword detection, slash commands | |-------|-------------|-----------|-------|
| PreToolUse | `tool.execute.before` | Yes | Validate/modify inputs, inject context | | UserPromptSubmit | `chat.message` | Yes | 4 |
| PostToolUse | `tool.execute.after` | No | Truncate output, error recovery | | ChatParams | `chat.params` | No | 2 |
| Stop | `event` (session.stop) | No | Auto-continue, notifications | | PreToolUse | `tool.execute.before` | Yes | 13 |
| onSummarize | Compaction | No | Preserve state, inject summary context | | PostToolUse | `tool.execute.after` | No | 18 |
| SessionEvent | `event` | No | 17 |
| MessagesTransform | `experimental.chat.messages.transform` | No | 1 |
| Compaction | `onSummarize` | No | 1 |
## BLOCKING HOOKS (8)
| Hook | Event | Blocks When |
|------|-------|-------------|
| auto-slash-command | chat.message | Command execution fails |
| keyword-detector | chat.message | Keyword injection fails |
| non-interactive-env | tool.execute.before | Interactive command in non-TTY |
| prometheus-md-only | tool.execute.before | Write outside .sisyphus/*.md |
| subagent-question-blocker | tool.execute.before | Question tool in subagent |
| tasks-todowrite-disabler | tool.execute.before | TodoWrite with task system |
| write-existing-file-guard | tool.execute.before | Write to existing file |
| claude-code-hooks | tool.execute.before | Exit code 2 from settings.json hook |
## EXECUTION ORDER ## EXECUTION ORDER
- **UserPromptSubmit**: keywordDetector → claudeCodeHooks → autoSlashCommand → startWork
- **PreToolUse**: subagentQuestionBlocker → questionLabelTruncator → claudeCodeHooks → nonInteractiveEnv → commentChecker → directoryAgentsInjector → directoryReadmeInjector → rulesInjector → prometheusMdOnly → sisyphusJuniorNotepad → writeExistingFileGuard → atlasHook **UserPromptSubmit**: keywordDetector → claudeCodeHooks → autoSlashCommand → startWork
- **PostToolUse**: claudeCodeHooks → toolOutputTruncator → contextWindowMonitor → commentChecker → directoryAgentsInjector → directoryReadmeInjector → rulesInjector → emptyTaskResponseDetector → agentUsageReminder → interactiveBashSession → editErrorRecovery → delegateTaskRetry → atlasHook → taskResumeInfo → taskReminder **PreToolUse**: subagentQuestionBlocker → questionLabelTruncator → claudeCodeHooks → nonInteractiveEnv → commentChecker → directoryAgentsInjector → directoryReadmeInjector → rulesInjector → prometheusMdOnly → sisyphusJuniorNotepad → writeExistingFileGuard → atlasHook
**PostToolUse**: claudeCodeHooks → toolOutputTruncator → contextWindowMonitor → commentChecker → directoryAgentsInjector → directoryReadmeInjector → rulesInjector → emptyTaskResponseDetector → agentUsageReminder → interactiveBashSession → editErrorRecovery → delegateTaskRetry → atlasHook → taskResumeInfo → taskReminder
## HOW TO ADD ## HOW TO ADD
1. Create `src/hooks/name/` with `index.ts` exporting `createMyHook(ctx)` 1. Create `src/hooks/name/` with `index.ts` exporting `createMyHook(ctx)`
2. Add hook name to `HookNameSchema` in `src/config/schema.ts` 2. Add hook name to `HookNameSchema` in `src/config/schema/hooks.ts`
3. Register in `src/index.ts` and add to relevant lifecycle methods 3. Register in appropriate `src/plugin/hooks/create-*-hooks.ts`
## HOOK PATTERNS
**Simple Single-Event**:
```typescript
export function createToolOutputTruncatorHook(ctx) {
return { "tool.execute.after": async (input, output) => { ... } }
}
```
**Multi-Event with State**:
```typescript
export function createThinkModeHook() {
const state = new Map<string, ThinkModeState>()
return {
"chat.params": async (output, sessionID) => { ... },
"event": async ({ event }) => { /* cleanup */ }
}
}
```
## ANTI-PATTERNS ## ANTI-PATTERNS
- **Heavy PreToolUse**: Runs before EVERY tool — keep light
- **Blocking non-critical**: Use PostToolUse warnings instead - **Blocking non-critical**: Use PostToolUse warnings instead
- **Heavy computation**: Keep PreToolUse light to avoid latency
- **Redundant injection**: Track injected files to avoid context bloat - **Redundant injection**: Track injected files to avoid context bloat
- **Direct state mutation**: Use `output.output +=` instead of replacing - **Direct state mutation**: Use `output.output +=` instead of replacing

View File

@ -28,24 +28,23 @@ claude-code-hooks/
``` ```
## HOOK LIFECYCLE ## HOOK LIFECYCLE
| Event | Timing | Can Block | Context Provided | | Event | Timing | Can Block | Context Provided |
|-------|--------|-----------|------------------| |-------|--------|-----------|------------------|
| PreToolUse | Before tool exec | Yes | sessionId, toolName, toolInput, cwd | | PreToolUse | Before exec | Yes (exit 2) | sessionId, toolName, toolInput, cwd |
| PostToolUse | After tool exec | Warn | + toolOutput, transcriptPath | | PostToolUse | After exec | Warn (exit 1) | + toolOutput, transcriptPath |
| UserPromptSubmit | On message send | Yes | sessionId, prompt, parts, cwd | | UserPromptSubmit | On message | Yes (exit 2) | sessionId, prompt, parts, cwd |
| Stop | Session idle/end | Inject | sessionId, parentSessionId, cwd | | Stop | Session end | Inject | sessionId, parentSessionId, cwd |
| PreCompact | Before summarize | No | sessionId, cwd | | PreCompact | Before summarize | No | sessionId, cwd |
## HOOK EXECUTION ## EXIT CODES
- **Matchers**: Hooks filter by tool name or event type via regex/glob
- **Commands**: Executed via subprocess with env vars (`$SESSION_ID`, `$TOOL_NAME`) - `0`: Pass (continue)
- **Exit Codes**: - `1`: Warn (continue + system message)
- `0`: Pass (Success) - `2`: Block (abort operation)
- `1`: Warn (Continue with system message)
- `2`: Block (Abort operation/prompt)
## ANTI-PATTERNS ## ANTI-PATTERNS
- **Heavy PreToolUse**: Runs before EVERY tool; keep logic light to avoid latency
- **Blocking non-critical**: Prefer PostToolUse warnings for non-fatal issues - **Heavy PreToolUse**: Runs before EVERY tool — keep scripts fast
- **Direct state mutation**: Use `updatedInput` in PreToolUse instead of side effects - **Blocking non-critical**: Prefer PostToolUse warnings
- **Ignoring Exit Codes**: Ensure scripts return `2` to properly block sensitive tools - **Ignoring exit codes**: Return `2` to block sensitive tools

View File

@ -6,43 +6,27 @@ Tier 1 of three-tier MCP system: 3 built-in remote HTTP MCPs.
**Three-Tier System**: **Three-Tier System**:
1. **Built-in** (this directory): websearch, context7, grep_app 1. **Built-in** (this directory): websearch, context7, grep_app
2. **Claude Code compat**: `.mcp.json` with `${VAR}` expansion 2. **Claude Code compat** (`features/claude-code-mcp-loader/`): .mcp.json with `${VAR}` expansion
3. **Skill-embedded**: YAML frontmatter in skills 3. **Skill-embedded** (`features/opencode-skill-loader/`): YAML frontmatter in SKILL.md
## STRUCTURE ## STRUCTURE
``` ```
mcp/ mcp/
├── index.ts # createBuiltinMcps() factory ├── index.ts # createBuiltinMcps() factory
├── index.test.ts # Tests
├── websearch.ts # Exa AI / Tavily web search ├── websearch.ts # Exa AI / Tavily web search
├── context7.ts # Library documentation ├── context7.ts # Library documentation
├── grep-app.ts # GitHub code search ├── grep-app.ts # GitHub code search
├── types.ts # McpNameSchema └── types.ts # McpNameSchema
└── index.test.ts # Tests
``` ```
## MCP SERVERS ## MCP SERVERS
| Name | URL | Purpose | Auth | | Name | URL | Auth | Purpose |
|------|-----|---------|------| |------|-----|------|---------|
| websearch | mcp.exa.ai/mcp?tools=web_search_exa or mcp.tavily.com/mcp/ | Real-time web search | EXA_API_KEY (optional) / TAVILY_API_KEY (required) | | websearch | mcp.exa.ai/mcp (default) or mcp.tavily.com/mcp/ | EXA_API_KEY (optional) / TAVILY_API_KEY (required) | Real-time web search |
| context7 | mcp.context7.com/mcp | Library docs | CONTEXT7_API_KEY (optional) | | context7 | mcp.context7.com/mcp | CONTEXT7_API_KEY (optional) | Library docs lookup |
| grep_app | mcp.grep.app | GitHub code search | None | | grep_app | mcp.grep.app | None | GitHub code search |
## Websearch Provider Configuration
| Provider | URL | Auth | API Key Required |
|----------|-----|------|------------------|
| exa (default) | mcp.exa.ai/mcp?tools=web_search_exa | query param | No (optional) |
| tavily | mcp.tavily.com/mcp/ | Authorization Bearer | Yes |
```jsonc
{
"websearch": {
"provider": "tavily" // or "exa" (default)
}
}
```
## CONFIG PATTERN ## CONFIG PATTERN
@ -58,13 +42,13 @@ export const mcp_name = {
## HOW TO ADD ## HOW TO ADD
1. Create `src/mcp/my-mcp.ts` with MCP config object 1. Create `src/mcp/my-mcp.ts` with config object
2. Add conditional check in `createBuiltinMcps()` in `index.ts` 2. Add conditional check in `createBuiltinMcps()` in `index.ts`
3. Add name to `McpNameSchema` in `types.ts` 3. Add name to `McpNameSchema` in `types.ts`
## NOTES ## NOTES
- **Remote only**: HTTP/SSE, no stdio - **Remote only**: HTTP/SSE transport, no stdio
- **Disable**: User can set `disabled_mcps: ["name"]` in config - **Disable**: Set `disabled_mcps: ["name"]` in config
- **Exa**: Default provider, works without API key - **Exa**: Default provider, works without API key
- **Tavily**: Requires `TAVILY_API_KEY` env var - **Tavily**: Requires `TAVILY_API_KEY` env var

View File

@ -1,96 +1,65 @@
**Generated:** 2026-02-09T14:16:00+09:00 # PLUGIN-HANDLERS KNOWLEDGE BASE
**Commit:** f22f14d9
**Branch:** dev
## OVERVIEW ## OVERVIEW
Plugin component loading and configuration orchestration. 500+ lines of config merging, migration, and component discovery for Claude Code compatibility. Configuration orchestration layer. Runs once at plugin init — transforms raw OpenCode config into resolved agent/tool/permission structures.
## STRUCTURE ## STRUCTURE
``` ```
plugin-handlers/ plugin-handlers/
├── config-handler.ts # Main config orchestrator (563 lines) - agent/skill/command loading ├── config-handler.ts # Main orchestrator (45 lines) — 6-phase loading
├── config-handler.test.ts # Config handler tests (1061 lines) ├── agent-config-handler.ts # Agent loading pipeline (197 lines)
├── plan-model-inheritance.ts # Plan agent model inheritance logic (657 lines) ├── plan-model-inheritance.ts # Plan demotion logic (28 lines)
├── plan-model-inheritance.test.ts # Inheritance tests (3696 lines) ├── prometheus-agent-config-builder.ts # Prometheus config builder (99 lines)
└── index.ts # Barrel export ├── plugin-components-loader.ts # Claude Code plugin discovery (71 lines, 10s timeout)
├── provider-config-handler.ts # Provider config + model context limits cache
├── tool-config-handler.ts # Permission migration (101 lines)
├── mcp-config-handler.ts # Builtin + CC + plugin MCP merge
├── command-config-handler.ts # Command/skill parallel discovery
├── category-config-resolver.ts # Category lookup
├── agent-priority-order.ts # Agent ordering (sisyphus, hephaestus, prometheus, atlas first)
├── plan-model-inheritance.test.ts # 3696 lines of tests
├── config-handler.test.ts # 1061 lines of tests
└── index.ts # Barrel exports
``` ```
## CORE FUNCTIONS ## CONFIG LOADING FLOW (6 phases, sequential)
**Config Handler (`createConfigHandler`):** 1. `applyProviderConfig` → Cache model context limits, detect anthropic-beta headers
- Loads all plugin components (agents, skills, commands, MCPs) 2. `loadPluginComponents` → Discover Claude Code plugins (10s timeout, error isolation)
- Applies permission migrations for compatibility 3. `applyAgentConfig` → Load all agents, sisyphus/prometheus/plan demotion
- Merges user/project/global configurations 4. `applyToolConfig` → Agent-specific tool permissions (grep_app, task, teammate)
- Handles Claude Code plugin integration 5. `applyMcpConfig` → Merge builtin + Claude Code + plugin MCPs
6. `applyCommandConfig` → Merge builtin + user + project + opencode commands/skills
**Plan Model Inheritance:** ## PLAN MODEL INHERITANCE
- Demotes plan agent to prometheus when planner enabled
- Preserves user overrides during migration
- Handles model/variant inheritance from categories
## LOADING PHASES When `sisyphus_agent.planner_enabled === true`:
1. Prometheus config → extract model settings (model, variant, temperature, ...)
2. Apply user `agents.plan` overrides (plan override wins)
3. Set `mode: "subagent"` (plan becomes subagent, not primary)
4. Strip prompt/permission/description (only model settings inherited)
1. **Plugin Discovery**: Load Claude Code plugins with timeout protection ## AGENT LOADING ORDER
2. **Component Loading**: Parallel loading of agents, skills, commands
3. **Config Merging**: User → Project → Global → Defaults
4. **Migration**: Legacy config format compatibility
5. **Permission Application**: Tool access control per agent
## KEY FEATURES 1. Builtin agents (sisyphus, hephaestus, oracle, ...)
2. Sisyphus-Junior (if sisyphus enabled)
3. OpenCode-Builder (if `default_builder_enabled`)
4. Prometheus (if `planner_enabled`)
5. User agents → Project agents → Plugin agents → Custom agents
**Parallel Loading:** **Reordered** by `reorderAgentsByPriority()`: sisyphus, hephaestus, prometheus, atlas first.
- Concurrent discovery of user/project/global components
- Timeout protection for plugin loading (default: 10s)
- Error isolation (failed plugins don't break others)
**Migration Support:** ## TOOL PERMISSIONS
- Agent name mapping (old → new names)
- Permission format conversion
- Config structure updates
**Claude Code Integration:** | Agent | Special Permissions |
- Plugin component loading |-------|---------------------|
- MCP server discovery | librarian | grep_app_* allowed |
- Agent/skill/command compatibility | atlas | task, task_*, teammate allowed |
| sisyphus | task, task_*, teammate, question allowed |
| hephaestus | task, question allowed |
| multimodal-looker | Denies task, look_at |
## CONFIGURATION FLOW ## INTEGRATION
``` Created in `create-managers.ts`, exposed as `config` hook in `plugin-interface.ts`. OpenCode calls it during session init.
User Config → Migration → Merging → Validation → Agent Creation → Permission Application
```
## TESTING COVERAGE
- **Config Handler**: 1061 lines of tests
- **Plan Inheritance**: 3696 lines of tests
- **Migration Logic**: Legacy compatibility verification
- **Parallel Loading**: Timeout and error handling
## USAGE PATTERNS
**Config Handler Creation:**
```typescript
const handler = createConfigHandler({
ctx: { directory: projectDir },
pluginConfig: userConfig,
modelCacheState: cache
});
```
**Plan Demotion:**
```typescript
const demotedPlan = buildPlanDemoteConfig(
prometheusConfig,
userPlanOverrides
);
```
**Component Loading:**
```typescript
const [agents, skills, commands] = await Promise.all([
loadUserAgents(),
loadProjectSkills(),
loadGlobalCommands()
]);
```

View File

@ -2,83 +2,92 @@
## OVERVIEW ## OVERVIEW
88 cross-cutting utilities. Import via barrel pattern: `import { log, deepMerge } from "../../shared"` 84 cross-cutting utilities across 6 subdirectories. Import via barrel: `import { log, deepMerge } from "../../shared"`
**Categories**: Path resolution, Token truncation, Config parsing, Model resolution, System directives, Tool restrictions
## STRUCTURE ## STRUCTURE
``` ```
shared/ shared/
├── git-worktree/ # Git worktree operations (311 lines) ├── logger.ts # File logging (/tmp/oh-my-opencode.log) — 62 imports
├── tmux/ # Tmux TUI integration (227 lines) ├── dynamic-truncator.ts # Token-aware context window management (201 lines)
├── logger.ts # File-based logging (/tmp/oh-my-opencode.log) - 53 imports ├── model-resolver.ts # 3-step resolution (Override → Fallback → Default)
├── dynamic-truncator.ts # Token-aware context window management (201 lines) ├── model-availability.ts # Provider model fetching & fuzzy matching (358 lines)
├── model-resolver.ts # 3-step resolution (Override → Fallback → Default) ├── model-requirements.ts # Agent/category fallback chains (160 lines)
├── model-requirements.ts # Agent/category model fallback chains (160 lines) ├── model-resolution-pipeline.ts # Pipeline orchestration (175 lines)
├── model-availability.ts # Provider model fetching & fuzzy matching (358 lines) ├── model-resolution-types.ts # Resolution request/provenance types
├── model-sanitizer.ts # Model name sanitization ├── model-sanitizer.ts # Model name sanitization
├── model-suggestion-retry.ts # Model suggestion on failure ├── model-name-matcher.ts # Model name matching (91 lines)
├── jsonc-parser.ts # JSONC parsing with comment support ├── model-suggestion-retry.ts # Suggest models on failure (129 lines)
├── frontmatter.ts # YAML frontmatter extraction (JSON_SCHEMA only) - 9 imports ├── model-cache-availability.ts # Cache availability checking
├── data-path.ts # XDG-compliant storage resolution ├── fallback-model-availability.ts # Fallback model logic (67 lines)
├── opencode-config-dir.ts # ~/.config/opencode resolution (138 lines) - 9 imports ├── available-models-fetcher.ts # Fetch models from providers (114 lines)
├── claude-config-dir.ts # ~/.claude resolution - 9 imports ├── models-json-cache-reader.ts # Read models.json cache
├── migration.ts # Legacy config migration logic (341 lines across dir) ├── provider-models-cache-model-reader.ts # Provider cache reader
├── opencode-version.ts # Semantic version comparison ├── connected-providers-cache.ts # Provider caching (196 lines)
├── permission-compat.ts # Agent tool restriction enforcement - 6 imports ├── system-directive.ts # Unified message prefix & types (61 lines) — 11 imports
├── system-directive.ts # Unified system message prefix & types - 8 imports ├── session-utils.ts # Session cursor, orchestrator detection
├── session-utils.ts # Session cursor, orchestrator detection ├── session-cursor.ts # Message cursor tracking (85 lines)
├── session-cursor.ts # Session message cursor tracking ├── session-injected-paths.ts # Injected file path tracking
├── shell-env.ts # Cross-platform shell environment ├── permission-compat.ts # Tool restriction enforcement (86 lines)
├── agent-variant.ts # Agent variant from config ├── agent-tool-restrictions.ts # Tool restriction definitions
├── zip-extractor.ts # Binary/Resource ZIP extraction ├── agent-variant.ts # Agent variant from config (91 lines)
├── deep-merge.ts # Recursive object merging (proto-pollution safe, MAX_DEPTH=50) ├── agent-display-names.ts # Agent display name mapping
├── command-executor.ts # Shell command execution (213 lines across dir) ├── first-message-variant.ts # First message variant types
├── snake-case.ts # Case conversion utilities ├── opencode-config-dir.ts # ~/.config/opencode resolution (138 lines)
├── tool-name.ts # Tool naming conventions ├── claude-config-dir.ts # ~/.claude resolution
├── pattern-matcher.ts # Pattern matching utilities ├── data-path.ts # XDG-compliant storage (47 lines)
├── port-utils.ts # Port management ├── jsonc-parser.ts # JSONC with comment support (66 lines)
├── file-utils.ts # File operation utilities ├── frontmatter.ts # YAML frontmatter extraction (31 lines) — 10 imports
├── file-reference-resolver.ts # File reference resolution ├── deep-merge.ts # Recursive merge (proto-pollution safe, MAX_DEPTH=50)
├── connected-providers-cache.ts # Provider caching ├── shell-env.ts # Cross-platform shell environment (111 lines)
├── external-plugin-detector.ts # Plugin detection ├── opencode-version.ts # Semantic version comparison (74 lines)
├── first-message-variant.ts # Message variant types ├── external-plugin-detector.ts # Plugin conflict detection (137 lines)
├── opencode-server-auth.ts # Authentication utilities ├── opencode-server-auth.ts # Authentication utilities (69 lines)
└── index.ts # Barrel export for all utilities ├── safe-create-hook.ts # Hook error wrapper (24 lines)
├── pattern-matcher.ts # Pattern matching (40 lines)
├── file-utils.ts # File operations (40 lines) — 9 imports
├── file-reference-resolver.ts # File reference resolution (85 lines)
├── snake-case.ts # Case conversion (44 lines)
├── tool-name.ts # Tool naming conventions
├── truncate-description.ts # Description truncation
├── port-utils.ts # Port management (48 lines)
├── zip-extractor.ts # ZIP extraction (83 lines)
├── binary-downloader.ts # Binary download (60 lines)
├── skill-path-resolver.ts # Skill path resolution
├── hook-disabled.ts # Hook disable checking
├── config-errors.ts # Config error types
├── disabled-tools.ts # Disabled tools tracking
├── record-type-guard.ts # Record type guard
├── open-code-client-accessors.ts # Client accessor utilities
├── open-code-client-shapes.ts # Client shape types
├── command-executor/ # Shell execution (6 files, 213 lines)
├── git-worktree/ # Git status/diff parsing (8 files, 311 lines)
├── migration/ # Legacy config migration (5 files, 341 lines)
│ ├── config-migration.ts # Migration orchestration (126 lines)
│ ├── agent-names.ts # Agent name mapping (70 lines)
│ ├── hook-names.ts # Hook name mapping (36 lines)
│ └── model-versions.ts # Model version migration (49 lines)
└── tmux/ # Tmux TUI integration (12 files, 427 lines)
└── tmux-utils/ # Pane spawn, close, replace, layout, health
``` ```
## MOST IMPORTED ## MOST IMPORTED
| Utility | Imports | Purpose | | Utility | Imports | Purpose |
|---------|---------|---------| |---------|---------|---------|
| logger.ts | 53 | Background task visibility | | logger.ts | 62 | Background task visibility |
| opencode-config-dir.ts | 9 | Path resolution | | data-path.ts | 11 | XDG storage resolution |
| claude-config-dir.ts | 9 | Path resolution | | model-requirements.ts | 11 | Agent fallback chains |
| frontmatter.ts | 9 | YAML parsing | | system-directive.ts | 11 | System message filtering |
| system-directive.ts | 8 | Message filtering | | frontmatter.ts | 10 | YAML metadata extraction |
| permission-compat.ts | 6 | Tool restrictions | | permission-compat.ts | 9 | Tool restrictions |
| file-utils.ts | 9 | File operations |
## WHEN TO USE | dynamic-truncator.ts | 7 | Token-aware truncation |
| Task | Utility |
|------|---------|
| Path Resolution | `getOpenCodeConfigDir()`, `getDataPath()` |
| Token Truncation | `dynamicTruncate(ctx, sessionId, output)` |
| Config Parsing | `readJsoncFile<T>(path)`, `parseJsonc(text)` |
| Model Resolution | `resolveModelWithFallback(client, reqs, override)` |
| Version Gating | `isOpenCodeVersionAtLeast(version)` |
| YAML Metadata | `parseFrontmatter(content)` |
| Tool Security | `createAgentToolAllowlist(tools)` |
| System Messages | `createSystemDirective(type)`, `isSystemDirective(msg)` |
| Deep Merge | `deepMerge(target, source)` |
## KEY PATTERNS ## KEY PATTERNS
**3-Step Resolution** (Override → Fallback → Default): **3-Step Model Resolution** (Override → Fallback → Default):
```typescript ```typescript
const model = resolveModelWithFallback({ resolveModelWithFallback({ userModel, fallbackChain, availableModels })
userModel: config.agents.sisyphus.model,
fallbackChain: AGENT_MODEL_REQUIREMENTS.sisyphus.fallbackChain,
availableModels: fetchedModels,
})
``` ```
**System Directive Filtering**: **System Directive Filtering**:
@ -88,8 +97,9 @@ const directive = createSystemDirective("TODO CONTINUATION")
``` ```
## ANTI-PATTERNS ## ANTI-PATTERNS
- **Raw JSON.parse**: Use `jsonc-parser.ts` for comment support - **Raw JSON.parse**: Use `jsonc-parser.ts` for comment support
- **Hardcoded Paths**: Use `*-config-dir.ts` or `data-path.ts` - **Hardcoded paths**: Use `opencode-config-dir.ts` or `data-path.ts`
- **console.log**: Use `logger.ts` for background task visibility - **console.log**: Use `logger.ts` for background task visibility
- **Unbounded Output**: Use `dynamic-truncator.ts` to prevent overflow - **Unbounded output**: Use `dynamic-truncator.ts` to prevent overflow
- **Manual Version Check**: Use `opencode-version.ts` for semver safety - **Manual version check**: Use `opencode-version.ts` for semver safety

View File

@ -2,91 +2,69 @@
## OVERVIEW ## OVERVIEW
25+ tools across 14 directories. Two patterns: Direct ToolDefinition (static) and Factory Function (context-dependent). 24 tools across 14 directories. Two patterns: Direct ToolDefinition (static) and Factory Function (context-dependent).
**Categories**: LSP (6), AST-Grep (2), Search (2), Session (4), Task (4), Agent delegation (1), Background (2), Skill (2), System (2), MCP (1), Command (1)
## STRUCTURE ## STRUCTURE
``` ```
tools/ tools/
├── [tool-name]/ ├── delegate-task/ # Category routing (constants.ts 569 lines, tools.ts 213 lines)
│ ├── index.ts # Barrel export ├── task/ # Unified CRUD: create/list/get/update/delete (task.ts 58 lines)
│ ├── tools.ts # ToolDefinition or factory ├── lsp/ # 6 LSP tools: goto_definition, find_references, symbols, diagnostics, prepare_rename, rename
│ ├── types.ts # Zod schemas
│ └── constants.ts # Fixed values
├── lsp/ # 6 tools: goto_definition, find_references, symbols, diagnostics, prepare_rename, rename
├── ast-grep/ # 2 tools: search, replace (25 languages) ├── ast-grep/ # 2 tools: search, replace (25 languages)
├── delegate-task/ # Category routing (constants.ts 569 lines, tools.test.ts 3582 lines)
├── task/ # 4 tools: create, get, list, update (Claude Code compatible)
├── session-manager/ # 4 tools: list, read, search, info
├── grep/ # Custom grep (60s timeout, 10MB limit) ├── grep/ # Custom grep (60s timeout, 10MB limit)
├── glob/ # 60s timeout, 100 file limit ├── glob/ # File search (60s timeout, 100 file limit)
├── interactive-bash/ # Tmux session management ├── session-manager/ # 4 tools: list, read, search, info (151 lines)
├── look-at/ # Multimodal PDF/image analysis ├── call-omo-agent/ # Direct agent invocation (57 lines)
├── skill/ # Skill execution ├── background-task/ # background_output, background_cancel
├── skill-mcp/ # Skill MCP operations ├── interactive-bash/ # Tmux session management (135 lines)
├── slashcommand/ # Slash command dispatch ├── look-at/ # Multimodal PDF/image analysis (156 lines)
├── call-omo-agent/ # Direct agent invocation ├── skill/ # Skill execution with MCP support (211 lines)
└── background-task/ # background_output, background_cancel ├── skill-mcp/ # MCP tool/resource/prompt operations (182 lines)
└── slashcommand/ # Slash command dispatch
``` ```
## TOOL CATEGORIES ## TOOL INVENTORY
| Category | Tools | Pattern | | Tool | Category | Pattern | Key Logic |
|----------|-------|---------| |------|----------|---------|-----------|
| LSP | lsp_goto_definition, lsp_find_references, lsp_symbols, lsp_diagnostics, lsp_prepare_rename, lsp_rename | Direct | | `task` | Task | Factory | Unified 5-action dispatch (create/list/get/update/delete) |
| Search | ast_grep_search, ast_grep_replace, grep, glob | Direct | | `call_omo_agent` | Agent | Factory | Direct explore/librarian invocation |
| Session | session_list, session_read, session_search, session_info | Direct | | `background_output` | Background | Factory | Retrieve background task result |
| Task | task_create, task_get, task_list, task_update | Factory | | `background_cancel` | Background | Factory | Cancel running background tasks |
| Agent | call_omo_agent | Factory | | `lsp_goto_definition` | LSP | Direct | Jump to symbol definition |
| Background | background_output, background_cancel | Factory | | `lsp_find_references` | LSP | Direct | Find all usages across workspace |
| System | interactive_bash, look_at | Mixed | | `lsp_symbols` | LSP | Direct | Document or workspace symbol search |
| Skill | skill, skill_mcp | Factory | | `lsp_diagnostics` | LSP | Direct | Get errors/warnings from language server |
| Command | slashcommand | Factory | | `lsp_prepare_rename` | LSP | Direct | Validate rename is possible |
| `lsp_rename` | LSP | Direct | Rename symbol across workspace |
| `ast_grep_search` | Search | Factory | AST-aware code search (25 languages) |
| `ast_grep_replace` | Search | Factory | AST-aware code replacement |
| `grep` | Search | Factory | Regex content search with safety limits |
| `glob` | Search | Factory | File pattern matching |
| `session_list` | Session | Factory | List all sessions |
| `session_read` | Session | Factory | Read session messages |
| `session_search` | Session | Factory | Search across sessions |
| `session_info` | Session | Factory | Session metadata and stats |
| `interactive_bash` | System | Direct | Tmux session management |
| `look_at` | System | Factory | Multimodal PDF/image analysis |
| `skill` | Skill | Factory | Execute skill with MCP capabilities |
| `skill_mcp` | Skill | Factory | Call MCP tools/resources/prompts |
| `slashcommand` | Command | Factory | Slash command dispatch |
## TASK TOOLS ## DELEGATION SYSTEM (delegate-task)
Claude Code compatible task management. 8 built-in categories: `visual-engineering`, `ultrabrain`, `deep`, `artistry`, `quick`, `unspecified-low`, `unspecified-high`, `writing`
- **task_create**: Creates a new task. Auto-generates ID and syncs to Todo. Each category defines: model, variant, temperature, max tokens, thinking/reasoning config, prompt append, stability flag.
- **task_get**: Retrieves a task by ID.
- **task_list**: Lists active tasks. Filters out completed/deleted by default.
- **task_update**: Updates task fields. Supports additive `addBlocks`/`addBlockedBy`.
## HOW TO ADD ## HOW TO ADD
1. Create `src/tools/[name]/` with standard files 1. Create `src/tools/[name]/` with index.ts, tools.ts, types.ts, constants.ts
2. Use `tool()` from `@opencode-ai/plugin/tool` 2. Static tools → `builtinTools` export, Factory → separate export
3. Export from `src/tools/index.ts` 3. Register in `src/plugin/tool-registry.ts`
4. Static tools → `builtinTools`, Factory → separate export
## TOOL PATTERNS
**Direct ToolDefinition**:
```typescript
export const grep: ToolDefinition = tool({
description: "...",
args: { pattern: tool.schema.string() },
execute: async (args) => result,
})
```
**Factory Function** (context-dependent):
```typescript
export function createDelegateTask(ctx, manager): ToolDefinition {
return tool({ execute: async (args) => { /* uses ctx */ } })
}
```
## NAMING ## NAMING
- **Tool names**: snake_case (`lsp_goto_definition`) - **Tool names**: snake_case (`lsp_goto_definition`)
- **Functions**: camelCase (`createDelegateTask`) - **Functions**: camelCase (`createDelegateTask`)
- **Directories**: kebab-case (`delegate-task/`) - **Directories**: kebab-case (`delegate-task/`)
## ANTI-PATTERNS
- **Sequential bash**: Use `&&` or delegation
- **Raw file ops**: Never mkdir/touch in tool logic
- **Sleep**: Use polling loops