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
**Generated:** 2026-02-09T14:16:00+09:00
**Commit:** f22f14d9
**Generated:** 2026-02-10T14:44:00+09:00
**Commit:** b538806d
**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 |
| 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.
---
@@ -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
This is an **international open-source project**. To ensure accessibility and maintainability:
| Context | Language Requirement |
|---------|---------------------|
| **GitHub Issues** | English ONLY |
@@ -103,67 +96,74 @@ This is an **international open-source project**. To ensure accessibility and ma
| **Documentation** | English ONLY |
| **AGENTS.md files** | English ONLY |
### Why This Matters
- **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.**
**If you're not comfortable writing in English, use translation tools. Broken English is fine. Non-English is not acceptable.**
---
## 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
```
oh-my-opencode/
├── src/
│ ├── agents/ # 11 AI agents - see src/agents/AGENTS.md
│ ├── hooks/ # 40+ lifecycle hooks - see src/hooks/AGENTS.md
│ ├── tools/ # 25+ tools - see src/tools/AGENTS.md
│ ├── features/ # Background agents, skills, Claude Code compat - see src/features/AGENTS.md
│ ├── shared/ # 88 cross-cutting utilities - see src/shared/AGENTS.md
│ ├── cli/ # CLI installer, doctor - see src/cli/AGENTS.md
│ ├── mcp/ # Built-in MCPs - see src/mcp/AGENTS.md
│ ├── config/ # Zod schema (schema.ts 455 lines) - see src/config/AGENTS.md
│ ├── plugin-handlers/ # Plugin config loading - see src/plugin-handlers/AGENTS.md
│ ├── plugin/ # Plugin SDK types
│ ├── index.ts # Main plugin entry (999 lines)
│ ├── create-hooks.ts # Hook creation coordination (core, continuation, skill)
│ ├── plugin-config.ts # Config loading orchestration
── plugin-state.ts # Model cache state
├── script/ # build-schema.ts, build-binaries.ts, publish.ts, generate-changelog.ts
├── packages/ # 11 platform-specific binaries (darwin-*, linux-*, windows-*)
└── dist/ # Build output (ESM + .d.ts)
│ ├── agents/ # 11 AI agents - see src/agents/AGENTS.md
│ ├── hooks/ # 41 lifecycle hooks - see src/hooks/AGENTS.md
│ ├── tools/ # 25+ tools - see src/tools/AGENTS.md
│ ├── features/ # Background agents, skills, CC compat - see src/features/AGENTS.md
│ ├── shared/ # 84 cross-cutting utilities - see src/shared/AGENTS.md
│ ├── cli/ # CLI installer, doctor - see src/cli/AGENTS.md
│ ├── mcp/ # Built-in MCPs - see src/mcp/AGENTS.md
│ ├── config/ # Zod schema - see src/config/AGENTS.md
│ ├── plugin-handlers/ # Config loading - see src/plugin-handlers/AGENTS.md
│ ├── plugin/ # Plugin interface composition (21 files)
│ ├── index.ts # Main plugin entry (88 lines)
│ ├── create-hooks.ts # Hook creation coordination (62 lines)
│ ├── create-managers.ts # Manager initialization (80 lines)
── create-tools.ts # Tool registry composition (54 lines)
│ ├── plugin-interface.ts # Plugin interface assembly (66 lines)
├── plugin-config.ts # Config loading orchestration
│ └── 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
| Task | Location | Notes |
|------|----------|-------|
| Add agent | `src/agents/` | Create .ts with factory, add to `agentSources` in builtin-agents.ts |
| Add hook | `src/hooks/` | Create dir with `createXXXHook()`, register in create-hooks.ts |
| Add agent | `src/agents/` | Create .ts with factory, add to `agentSources` in builtin-agents/ |
| 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 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 |
| 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 |
| 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) |
| 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)
@@ -175,7 +175,7 @@ oh-my-opencode/
**Rules:**
- NEVER write implementation before test
- 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`
## CONVENTIONS
@@ -185,8 +185,9 @@ oh-my-opencode/
- **Build**: `bun build` (ESM) + `tsc --emitDeclarationOnly`
- **Exports**: Barrel pattern via index.ts
- **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
- **Modular architecture**: 200 LOC hard limit per file (prompt strings exempt)
## ANTI-PATTERNS
@@ -209,22 +210,57 @@ oh-my-opencode/
| Git | Skip hooks (--no-verify), force push without request |
| Bash | `sleep N` - use conditional waits |
| Bash | `cd dir && cmd` - use workdir parameter |
| Files | Catch-all utils.ts/helpers.ts - name by purpose |
## AGENT MODELS
| Agent | Model | Purpose |
|-------|-------|---------|
| Sisyphus | anthropic/claude-opus-4-6 | 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) |
| Atlas | anthropic/claude-sonnet-4-5 | Master orchestrator (fallback: kimi-k2.5 → gpt-5.2) |
| oracle | openai/gpt-5.2 | Consultation, debugging |
| librarian | zai-coding-plan/glm-4.7 | Docs, GitHub search (fallback: glm-4.7-free) |
| explore | xai/grok-code-fast-1 | Fast codebase grep (fallback: claude-haiku-4-5 → gpt-5-mini → gpt-5-nano) |
| multimodal-looker | google/gemini-3-flash | PDF/image analysis |
| Prometheus | anthropic/claude-opus-4-6 | Strategic planning (fallback: kimi-k2.5 → gpt-5.2) |
| Metis | anthropic/claude-opus-4-6 | Pre-planning analysis (temp 0.3, fallback: kimi-k2.5 → gpt-5.2) |
| Momus | openai/gpt-5.2 | Plan validation (temp 0.1, fallback: claude-opus-4-6) |
| Sisyphus-Junior | anthropic/claude-sonnet-4-5 | Category-spawned executor (temp 0.1) |
| 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 (NO fallback) |
| Atlas | anthropic/claude-sonnet-4-5 | 0.1 | Master orchestrator (fallback: kimi-k2.5 → gpt-5.2) |
| Prometheus | anthropic/claude-opus-4-6 | 0.1 | Strategic planning (fallback: kimi-k2.5 → gpt-5.2) |
| oracle | openai/gpt-5.2 | 0.1 | Consultation, debugging (fallback: claude-opus-4-6) |
| 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 codebase grep (fallback: claude-haiku-4-5 → gpt-5-mini → gpt-5-nano) |
| multimodal-looker | google/gemini-3-flash | 0.1 | PDF/image analysis |
| 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 |
## 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
@@ -232,7 +268,8 @@ oh-my-opencode/
bun run typecheck # Type check
bun run build # ESM + declarations + schema
bun run rebuild # Clean + Build
bun test # 163+ test files
bun test # 176 test files
bun run build:schema # Regenerate JSON schema
```
## DEPLOYMENT
@@ -247,35 +284,37 @@ bun test # 163+ test files
| File | Lines | Description |
|------|-------|-------------|
| `src/features/background-agent/manager.ts` | 1646 | Task lifecycle, concurrency |
| `src/features/builtin-skills/skills/git-master.ts` | 1111 | Git master skill definition |
| `src/index.ts` | 999 | Main plugin entry |
| `src/tools/delegate-task/tools.test.ts` | 3582 | Delegation tool tests |
| `src/features/background-agent/manager.test.ts` | 2843 | Background manager tests |
| `src/hooks/atlas/index.test.ts` | 1182 | Atlas hook tests |
| `src/agents/hephaestus.ts` | 618 | Autonomous deep worker agent |
| `src/features/builtin-commands/templates/refactor.ts` | 619 | Refactor command template |
| `src/hooks/anthropic-context-window-limit-recovery/` | 2232 | Multi-strategy context recovery |
| `src/hooks/claude-code-hooks/` | 2110 | Claude Code settings.json compat |
| `src/hooks/todo-continuation-enforcer/` | 2061 | Core boulder mechanism |
| `src/hooks/atlas/` | 1976 | Session orchestration |
| `src/hooks/ralph-loop/` | 1687 | Self-referential dev loop |
| `src/hooks/keyword-detector/` | 1665 | Mode detection (ultrawork/search) |
| `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/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
Three-tier system:
1. **Built-in**: websearch (Exa/Tavily), context7 (docs), grep_app (GitHub)
2. **Claude Code compat**: .mcp.json with `${VAR}` expansion
3. **Skill-embedded**: YAML frontmatter in skills
1. **Built-in** (src/mcp/): websearch (Exa/Tavily), context7 (docs), grep_app (GitHub)
2. **Claude Code compat** (features/claude-code-mcp-loader/): .mcp.json with `${VAR}` expansion
3. **Skill-embedded** (features/opencode-skill-loader/): YAML frontmatter in SKILL.md
## 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
- **Multi-level**: Project (`.opencode/`) → User (`~/.config/opencode/`)
- **Loading**: `src/plugin-handlers/config-handler.ts` → merge → validate
- **Multi-level**: Project (`.opencode/`) → User (`~/.config/opencode/`) → Defaults
- **Migration**: Legacy config auto-migration in `src/shared/migration/`
## NOTES
- **OpenCode**: Requires >= 1.0.150
- **1069 TypeScript files**, 176 test files, 117k+ lines
- **Flaky tests**: ralph-loop (CI timeout), session-state (parallel pollution)
- **Trusted deps**: @ast-grep/cli, @ast-grep/napi, @code-yeongyu/comment-checker
- **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
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
```
src/
├── index.ts # Main plugin entry (999 lines)
├── create-hooks.ts # Hook coordination: core, continuation, skill
├── plugin-config.ts # Config loading orchestration
├── plugin-state.ts # Model cache state
├── agents/ # 11 AI agents (20 files) - see agents/AGENTS.md
├── cli/ # CLI installer, doctor (100+ files) - see cli/AGENTS.md
├── config/ # Zod schema (21 files) - see config/AGENTS.md
├── features/ # Background agents, skills, commands (17 dirs) - see features/AGENTS.md
├── hooks/ # 40+ lifecycle hooks (30+ dirs) - see hooks/AGENTS.md
├── mcp/ # Built-in MCPs (8 files) - see mcp/AGENTS.md
├── plugin/ # Plugin SDK types
├── plugin-handlers/ # Plugin config loading (5 files) - see plugin-handlers/AGENTS.md
├── index.ts # Main plugin entry (88 lines) — OhMyOpenCodePlugin factory
├── create-hooks.ts # Hook coordination: core, continuation, skill (62 lines)
├── create-managers.ts # Manager initialization: Tmux, Background, SkillMcp, Config (80 lines)
├── create-tools.ts # Tool registry + skill context composition (54 lines)
├── plugin-interface.ts # Plugin interface assembly — 7 OpenCode hooks (66 lines)
├── plugin-config.ts # Config loading orchestration (user + project merge)
├── plugin-state.ts # Model cache state (context limits, anthropic 1M flag)
├── agents/ # 11 AI agents (32 files) - see agents/AGENTS.md
├── cli/ # CLI installer, doctor (107+ files) - see cli/AGENTS.md
├── config/ # Zod schema (21 component files) - see config/AGENTS.md
├── features/ # Background agents, skills, commands (18 dirs) - see features/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
└── tools/ # 25+ tools (14 dirs) - see tools/AGENTS.md
```
## KEY COMPONENTS
## PLUGIN INITIALIZATION (10 steps)
**Plugin Initialization:**
- `OhMyOpenCodePlugin()`: Main plugin factory
- Configuration loading via `loadPluginConfig()`
- Hook registration with safe creation patterns
- Tool composition and disabled tool filtering
1. `injectServerAuthIntoClient(ctx.client)` — Auth injection
2. `startTmuxCheck()` — Tmux availability
3. `loadPluginConfig(ctx.directory, ctx)` — User + project config merge → Zod validation
4. `createFirstMessageVariantGate()` — First message variant override gate
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:**
- 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`
## HOOK REGISTRATION (3 tiers)
**Tool Ecosystem:**
- 25+ tools: LSP, AST-grep, delegation, background tasks, skills
- Tool filtering based on agent permissions and user config
- Metadata restoration for tool outputs
**Core Hooks** (`create-core-hooks.ts`):
- Session (20): context-window-monitor, session-recovery, think-mode, ralph-loop, anthropic-effort, ...
- Tool Guard (8): comment-checker, tool-output-truncator, rules-injector, write-existing-file-guard, ...
- 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
const hook = isHookEnabled("hook-name")
? safeCreateHook("hook-name", () => createHookFactory(ctx), { enabled: safeHookEnabled })
: null;
```
**Hook Categories:**
- **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
All hooks use this pattern for graceful degradation on failure.

View File

@@ -2,89 +2,99 @@
## OVERVIEW
32 files containing AI agents and utilities for multi-model orchestration. Each agent has factory function + metadata + fallback chains.
**Primary Agents** (respect UI model selection):
- Sisyphus, Atlas, Prometheus
**Subagents** (use own fallback chains):
- Hephaestus, Oracle, Librarian, Explore, Multimodal-Looker, Metis, Momus, Sisyphus-Junior
11 AI agents with factory functions, fallback chains, and model-specific prompt variants. Each agent has metadata (category, cost, triggers) and configurable tool restrictions.
## STRUCTURE
```
agents/
├── atlas/ # Master Orchestrator (holds todo list)
│ ├── index.ts
│ ├── default.ts # Claude-optimized prompt (390 lines)
│ ├── gpt.ts # GPT-optimized prompt (330 lines)
├── sisyphus.ts # Main orchestrator (530 lines)
├── hephaestus.ts # Autonomous deep worker (624 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 (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
├── prometheus/ # Planning Agent (Interview/Consultant mode)
├── prometheus/ # Planning agent
│ ├── index.ts
│ ├── system-prompt.ts # 6-section prompt assembly
│ ├── plan-template.ts # Work plan structure (423 lines)
│ ├── interview-mode.ts # Interview flow (335 lines)
│ ├── plan-generation.ts
│ ├── high-accuracy-mode.ts
│ ├── identity-constraints.ts # Identity rules (301 lines)
│ └── behavioral-summary.ts
├── sisyphus-junior/ # Delegated task executor (category-spawned)
│ ├── index.ts
│ ├── default.ts
│ └── gpt.ts
├── 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)
├── sisyphus-junior/ # Delegated task executor
│ ├── agent.ts
│ ├── default.ts # Claude prompt
│ └── gpt.ts # GPT prompt
├── dynamic-agent-prompt-builder.ts # Dynamic prompt generation (431 lines)
├── builtin-agents.ts # Agent registry (179 lines)
├── types.ts # AgentModelConfig, AgentPromptMetadata
├── builtin-agents/ # Agent registry (8 files)
├── utils.ts # Agent creation, model fallback resolution (571 lines)
├── types.ts # AgentModelConfig, AgentPromptMetadata
└── index.ts # Exports
```
## 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
1. Create `src/agents/my-agent.ts` exporting factory + metadata.
2. Add to `agentSources` in `src/agents/builtin-agents.ts`.
3. Update `AgentNameSchema` in `src/config/schema.ts`.
4. Register in `src/index.ts` initialization.
| Agent | Model | Temp | Fallback Chain | Cost |
|-------|-------|------|----------------|------|
| Sisyphus | claude-opus-4-6 | 0.1 | kimi-k2.5 → glm-4.7 → gpt-5.3-codex → gemini-3-pro | EXPENSIVE |
| Hephaestus | gpt-5.3-codex | 0.1 | NONE (required) | EXPENSIVE |
| 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
| 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
- **Factory**: `createXXXAgent(model: string): AgentConfig`
| Agent | Denied | Allowed |
|-------|--------|---------|
| 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
- **Tool restrictions**: `createAgentToolRestrictions(tools)` or `createAgentToolAllowlist(tools)`
- **Thinking**: 32k budget tokens for Sisyphus, Oracle, Prometheus, Atlas
- **Model-specific routing**: Atlas, Sisyphus-Junior have GPT vs Claude prompt variants
- **Model-specific prompts**: Atlas, Sisyphus-Junior have GPT vs Claude variants
- **Dynamic prompts**: Sisyphus, Hephaestus use `dynamic-agent-prompt-builder.ts` to inject available tools/skills/categories
## 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
- **Prometheus writing code**: Planner only - never implements
- **Prometheus writing code**: Planner only never implements

View File

@@ -2,68 +2,71 @@
## 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
```
cli/
├── index.ts # Commander.js entry (5 commands)
├── install.ts # TTY routing to TUI or CLI installer
├── index.ts # Entry point (5 lines)
├── 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)
├── tui-installer.ts # Interactive TUI with @clack/prompts (140 lines)
├── config-manager/ # Config management utilities (17 files)
├── model-fallback.ts # Model fallback configuration
├── model-fallback.test.ts # Fallback tests (523 lines)
├── doctor/
├── config-manager/ # 17 config utilities
│ ├── add-plugin-to-opencode-config.ts # Plugin registration
│ ├── add-provider-config.ts # Provider setup
├── detect-current-config.ts # Project vs user config
│ ├── write-omo-config.ts # JSONC writing
│ └── ...
├── doctor/ # 14 health checks
│ ├── runner.ts # Check orchestration
│ ├── 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)
│ ├── events.ts # CLI run events
── runner.ts # Run orchestration
├── mcp-oauth/ # OAuth flow
└── get-local-version/ # Version detection
│ ├── runner.ts # Run orchestration (126 lines)
── agent-resolver.ts # Agent selection: flag → env → config → fallback
│ ├── session-resolver.ts # Session creation or resume
│ ├── 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
| Command | Purpose |
|---------|---------|
| `install` | Interactive setup with provider selection |
| `doctor` | 14 health checks for diagnostics |
| `run` | Launch session with todo enforcement |
| `get-local-version` | Version detection and update check |
| `mcp-oauth` | MCP OAuth authentication flow |
| Command | Purpose | Key Logic |
|---------|---------|-----------|
| `install` | Interactive setup | Provider selection → config generation → plugin registration |
| `run` | Session launcher | Agent: flag → env → config → Sisyphus. Enforces todo completion. |
| `doctor` | 14 health checks | installation, config, auth, deps, tools, updates |
| `get-local-version` | Version check | Detects installed, compares with npm latest |
| `mcp-oauth` | OAuth tokens | login (PKCE flow), logout, status |
## DOCTOR CATEGORIES (14 Checks)
## DOCTOR CHECK CATEGORIES
| Category | Checks |
|----------|--------|
| installation | opencode, plugin |
| configuration | config validity, Zod, model-resolution |
| configuration | config validity, Zod, model-resolution (6 sub-checks) |
| authentication | anthropic, openai, google |
| dependencies | ast-grep, comment-checker, gh-cli |
| tools | LSP, MCP |
| tools | LSP, MCP, MCP-OAuth |
| updates | version comparison |
## HOW TO ADD CHECK
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`
## 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
- **Blocking in non-TTY**: Always check `process.stdout.isTTY`
- **Direct JSON.parse**: Use `parseJsonc()` from shared utils
- **Silent failures**: Return `warn` or `fail` in doctor instead of throwing
- **Hardcoded paths**: Use `getOpenCodeConfigPaths()` from `config-manager`
- **Blocking in non-TTY**: Check `process.stdout.isTTY`
- **Direct JSON.parse**: Use `parseJsonc()` from shared
- **Silent failures**: Return `warn` or `fail` in doctor, don't throw
- **Hardcoded paths**: Use `getOpenCodeConfigPaths()` from config-manager

View File

@@ -1,87 +1,52 @@
**Generated:** 2026-02-09T14:16:00+09:00
**Commit:** f22f14d9
**Branch:** dev
# CONFIG KNOWLEDGE BASE
## 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
```
config/
├── schema/ # Schema components (21 files)
│ ├── index.ts # Main schema composition
── [module].ts # Agent names, overrides, categories, hooks, etc.
├── schema.ts # Main Zod schema (455 lines)
├── schema.test.ts # Schema validation tests (735 lines)
├── types.ts # TypeScript types
└── index.ts # Barrel export
├── schema/ # 21 schema component files
│ ├── oh-my-opencode-config.ts # Root schema composition (57 lines)
── agent-names.ts # BuiltinAgentNameSchema (11 agents), BuiltinSkillNameSchema
│ ├── agent-overrides.ts # AgentOverrideConfigSchema (model, variant, temp, thinking...)
│ ├── categories.ts # 8 categories: visual-engineering, ultrabrain, deep, artistry, quick, ...
│ ├── hooks.ts # HookNameSchema (100+ hook names)
│ ├── 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`
**Category Config:** `CategoryConfigSchema`, `CategoriesConfigSchema` (visual-engineering, ultrabrain, deep)
**Experimental:** `ExperimentalConfigSchema`, `DynamicContextPruningConfigSchema`
**Built-in Enums:** `AgentNameSchema` (11 agents), `HookNameSchema` (100+ hooks), `BuiltinCommandNameSchema`, `BuiltinSkillNameSchema`
`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`
## CONFIGURATION HIERARCHY
1. **Project config** (`.opencode/oh-my-opencode.json`)
2. **User config** (`~/.config/opencode/oh-my-opencode.json`)
3. **Defaults** (hardcoded fallbacks)
Project (`.opencode/oh-my-opencode.json`) → User (`~/.config/opencode/oh-my-opencode.json`) → Defaults
**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
- **Type safety**: Full TypeScript inference
- **Migration support**: Legacy config compatibility
- **Schema versioning**: $schema field for validation
## AFTER SCHEMA CHANGES
## KEY SCHEMAS
| 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"
}
}
```
Run `bun run build:schema` to regenerate `dist/oh-my-opencode.schema.json`

View File

@@ -2,53 +2,70 @@
## 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
```
features/
├── background-agent/ # Task lifecycle, concurrency (manager.ts 1646 lines, concurrency.ts)
├── boulder-state/ # Persistent state for multi-step operations
├── builtin-commands/ # Command templates: refactor (619 lines), ralph-loop, handoff, init-deep
├── builtin-skills/ # Skills: git-master (1111 lines), playwright, dev-browser, frontend-ui-ux
├── claude-code-agent-loader/ # CC agent loading from .opencode/agents/
├── claude-code-command-loader/ # CC command loading from .opencode/commands/
├── claude-code-mcp-loader/ # CC MCP loading from .opencode/mcp/
├── claude-code-plugin-loader/ # CC plugin discovery from .opencode/plugins/
├── claude-code-session-state/ # Subagent session state tracking
├── claude-tasks/ # Task schema + storage (has own AGENTS.md)
├── context-injector/ # Auto-injects AGENTS.md, README.md, rules
├── hook-message-injector/ # System message injection
├── mcp-oauth/ # OAuth flow for MCP servers
├── opencode-skill-loader/ # YAML frontmatter skill loading
├── skill-mcp-manager/ # MCP client lifecycle per session (manager.ts 150 lines)
├── task-toast-manager/ # Task progress notifications
├── tmux-subagent/ # Tmux integration (manager.ts 350 lines)
── tool-metadata-store/ # Tool execution metadata caching
├── background-agent/ # Task lifecycle, concurrency (50 files, 8330 LOC)
│ ├── manager.ts # Main task orchestration (1646 lines)
│ ├── concurrency.ts # Parallel execution limits per provider/model
│ └── spawner/ # Task spawning utilities (8 files)
├── tmux-subagent/ # Tmux integration (28 files, 3303 LOC)
│ └── manager.ts # Pane management, grid planning (350 lines)
├── opencode-skill-loader/ # YAML frontmatter skill loading (28 files, 2967 LOC)
│ ├── loader.ts # Skill discovery (4 scopes)
│ ├── skill-directory-loader.ts # Recursive directory scanning
│ ├── skill-discovery.ts # getAllSkills() with caching
│ └── merger/ # Skill merging with scope priority
├── mcp-oauth/ # OAuth 2.0 flow for MCP (18 files, 2164 LOC)
│ ├── provider.ts # McpOAuthProvider class
├── oauth-authorization-flow.ts # PKCE, callback handling
│ └── dcr.ts # Dynamic Client Registration (RFC 7591)
├── skill-mcp-manager/ # MCP client lifecycle per session (12 files, 1769 LOC)
│ └── manager.ts # SkillMcpManager class (150 lines)
── 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
**Background Agent Lifecycle:**
- Task creation -> Queue -> Concurrency check -> Execute -> Monitor -> Cleanup
- Manager.ts handles full lifecycle with 1646 lines of task orchestration
- Concurrency.ts manages parallel execution limits per provider/model
- Tasks survive session restarts via persistent storage
Task creation Queue Concurrency check Execute Monitor/Poll → Notification → Cleanup
**Skill Loading Pipeline (4-scope priority):**
opencode-project (`.opencode/skills/`) > opencode (`~/.config/opencode/skills/`) > project (`.claude/skills/`) > user (`~/.claude/skills/`)
**Claude Code Compatibility Layer:**
5 directories provide full CC compatibility:
- 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
5 loaders: agent-loader, command-loader, mcp-loader, plugin-loader, session-state
**Skill Loading Pipeline:**
1. opencode-skill-loader: Parses YAML frontmatter from skill files
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
4. Hook message injector: Injects system messages for skill activation
**SKILL.md Format:**
```yaml
---
name: my-skill
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

View File

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

View File

@@ -2,48 +2,40 @@
## OVERVIEW
163 lifecycle hooks intercepting/modifying agent behavior across 5 events.
**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
41 lifecycle hooks intercepting/modifying agent behavior across 7 event types. Three-tier registration: Core (32) → Continuation (7) → Skill (2).
## STRUCTURE
```
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-effort/ # Anthropic effort level management (272 lines)
├── anthropic-effort/ # Effort=max for Opus max variant (56 lines)
├── atlas/ # Main orchestration hook (1976 lines)
├── auto-slash-command/ # Detects /command patterns (1134 lines)
├── auto-update-checker/ # Plugin update check (1140 lines)
├── background-notification/ # OS notifications (33 lines)
├── category-skill-reminder/ # Reminds of category skills (597 lines)
├── claude-code-hooks/ # settings.json compat - see AGENTS.md (2110 lines)
├── category-skill-reminder/ # Category+skill delegation reminders (597 lines)
├── claude-code-hooks/ # settings.json compat (2110 lines) - see AGENTS.md
├── comment-checker/ # Prevents AI slop comments (710 lines)
├── compaction-context-injector/ # Injects context on compaction (128 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)
├── directory-agents-injector/ # Auto-injects AGENTS.md (195 lines)
├── directory-readme-injector/ # Auto-injects README.md (190 lines)
├── edit-error-recovery/ # Recovers from edit failures (188 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)
├── keyword-detector/ # ultrawork/search/analyze modes (1665 lines)
├── non-interactive-env/ # Non-TTY environment handling (483 lines)
├── preemptive-compaction.ts # Preemptive context compaction (108 lines)
├── non-interactive-env/ # Non-TTY handling (483 lines)
├── preemptive-compaction.ts # Auto-compact at 78% usage (108 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)
├── rules-injector/ # Conditional rules injection (1604 lines)
├── session-notification.ts # Session event notifications (108 lines)
├── rules-injector/ # Conditional .sisyphus/rules injection (1604 lines)
├── session-notification.ts # OS idle notifications (108 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)
├── stop-continuation-guard/ # Guards stop continuation (214 lines)
├── subagent-question-blocker/ # Blocks subagent questions (112 lines)
@@ -51,54 +43,53 @@ hooks/
├── task-resume-info/ # Resume info for cancelled tasks (39 lines)
├── tasks-todowrite-disabler/ # Disables TodoWrite when tasks active (202 lines)
├── think-mode/ # Dynamic thinking budget (1365 lines)
├── thinking-block-validator/ # Ensures valid <thinking> blocks (169 lines)
├── todo-continuation-enforcer/ # Force TODO completion (2061 lines)
├── thinking-block-validator/ # Validates thinking blocks (169 lines)
├── todo-continuation-enforcer/ # Force TODO completion — boulder mechanism (2061 lines)
├── tool-output-truncator.ts # Prevents context bloat (62 lines)
├── unstable-agent-babysitter/ # Monitors unstable agent behavior (451 lines)
└── write-existing-file-guard/ # Guards against overwriting files (356 lines)
├── unstable-agent-babysitter/ # Monitors unstable behavior (451 lines)
└── write-existing-file-guard/ # Guards against file overwrite (356 lines)
```
## HOOK EVENTS
| Event | Timing | Can Block | Use Case |
|-------|--------|-----------|----------|
| UserPromptSubmit | `chat.message` | Yes | Keyword detection, slash commands |
| PreToolUse | `tool.execute.before` | Yes | Validate/modify inputs, inject context |
| PostToolUse | `tool.execute.after` | No | Truncate output, error recovery |
| Stop | `event` (session.stop) | No | Auto-continue, notifications |
| onSummarize | Compaction | No | Preserve state, inject summary context |
## EVENT TYPES
| Event | Hook Method | Can Block | Count |
|-------|-------------|-----------|-------|
| UserPromptSubmit | `chat.message` | Yes | 4 |
| ChatParams | `chat.params` | No | 2 |
| PreToolUse | `tool.execute.before` | Yes | 13 |
| 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
- **UserPromptSubmit**: keywordDetector → claudeCodeHooks → autoSlashCommand → startWork
- **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
**UserPromptSubmit**: keywordDetector → claudeCodeHooks → autoSlashCommand → startWork
**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
1. Create `src/hooks/name/` with `index.ts` exporting `createMyHook(ctx)`
2. Add hook name to `HookNameSchema` in `src/config/schema.ts`
3. Register in `src/index.ts` and add to relevant lifecycle methods
## 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 */ }
}
}
```
2. Add hook name to `HookNameSchema` in `src/config/schema/hooks.ts`
3. Register in appropriate `src/plugin/hooks/create-*-hooks.ts`
## ANTI-PATTERNS
- **Heavy PreToolUse**: Runs before EVERY tool — keep light
- **Blocking non-critical**: Use PostToolUse warnings instead
- **Heavy computation**: Keep PreToolUse light to avoid latency
- **Redundant injection**: Track injected files to avoid context bloat
- **Direct state mutation**: Use `output.output +=` instead of replacing

View File

@@ -28,24 +28,23 @@ claude-code-hooks/
```
## HOOK LIFECYCLE
| Event | Timing | Can Block | Context Provided |
|-------|--------|-----------|------------------|
| PreToolUse | Before tool exec | Yes | sessionId, toolName, toolInput, cwd |
| PostToolUse | After tool exec | Warn | + toolOutput, transcriptPath |
| UserPromptSubmit | On message send | Yes | sessionId, prompt, parts, cwd |
| Stop | Session idle/end | Inject | sessionId, parentSessionId, cwd |
| PreToolUse | Before exec | Yes (exit 2) | sessionId, toolName, toolInput, cwd |
| PostToolUse | After exec | Warn (exit 1) | + toolOutput, transcriptPath |
| UserPromptSubmit | On message | Yes (exit 2) | sessionId, prompt, parts, cwd |
| Stop | Session end | Inject | sessionId, parentSessionId, cwd |
| PreCompact | Before summarize | No | sessionId, cwd |
## HOOK EXECUTION
- **Matchers**: Hooks filter by tool name or event type via regex/glob
- **Commands**: Executed via subprocess with env vars (`$SESSION_ID`, `$TOOL_NAME`)
- **Exit Codes**:
- `0`: Pass (Success)
- `1`: Warn (Continue with system message)
- `2`: Block (Abort operation/prompt)
## EXIT CODES
- `0`: Pass (continue)
- `1`: Warn (continue + system message)
- `2`: Block (abort operation)
## ANTI-PATTERNS
- **Heavy PreToolUse**: Runs before EVERY tool; keep logic light to avoid latency
- **Blocking non-critical**: Prefer PostToolUse warnings for non-fatal issues
- **Direct state mutation**: Use `updatedInput` in PreToolUse instead of side effects
- **Ignoring Exit Codes**: Ensure scripts return `2` to properly block sensitive tools
- **Heavy PreToolUse**: Runs before EVERY tool — keep scripts fast
- **Blocking non-critical**: Prefer PostToolUse warnings
- **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**:
1. **Built-in** (this directory): websearch, context7, grep_app
2. **Claude Code compat**: `.mcp.json` with `${VAR}` expansion
3. **Skill-embedded**: YAML frontmatter in skills
2. **Claude Code compat** (`features/claude-code-mcp-loader/`): .mcp.json with `${VAR}` expansion
3. **Skill-embedded** (`features/opencode-skill-loader/`): YAML frontmatter in SKILL.md
## STRUCTURE
```
mcp/
├── index.ts # createBuiltinMcps() factory
├── index.test.ts # Tests
├── websearch.ts # Exa AI / Tavily web search
├── context7.ts # Library documentation
├── grep-app.ts # GitHub code search
── types.ts # McpNameSchema
└── index.test.ts # Tests
── types.ts # McpNameSchema
```
## MCP SERVERS
| Name | URL | Purpose | Auth |
|------|-----|---------|------|
| 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) |
| context7 | mcp.context7.com/mcp | Library docs | CONTEXT7_API_KEY (optional) |
| grep_app | mcp.grep.app | GitHub code search | None |
## 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)
}
}
```
| Name | URL | Auth | Purpose |
|------|-----|------|---------|
| 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 | CONTEXT7_API_KEY (optional) | Library docs lookup |
| grep_app | mcp.grep.app | None | GitHub code search |
## CONFIG PATTERN
@@ -58,13 +42,13 @@ export const mcp_name = {
## 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`
3. Add name to `McpNameSchema` in `types.ts`
## NOTES
- **Remote only**: HTTP/SSE, no stdio
- **Disable**: User can set `disabled_mcps: ["name"]` in config
- **Remote only**: HTTP/SSE transport, no stdio
- **Disable**: Set `disabled_mcps: ["name"]` in config
- **Exa**: Default provider, works without API key
- **Tavily**: Requires `TAVILY_API_KEY` env var

View File

@@ -1,96 +1,65 @@
**Generated:** 2026-02-09T14:16:00+09:00
**Commit:** f22f14d9
**Branch:** dev
# PLUGIN-HANDLERS KNOWLEDGE BASE
## 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
```
plugin-handlers/
├── config-handler.ts # Main config orchestrator (563 lines) - agent/skill/command loading
├── config-handler.test.ts # Config handler tests (1061 lines)
├── plan-model-inheritance.ts # Plan agent model inheritance logic (657 lines)
├── plan-model-inheritance.test.ts # Inheritance tests (3696 lines)
── index.ts # Barrel export
├── config-handler.ts # Main orchestrator (45 lines) — 6-phase loading
├── agent-config-handler.ts # Agent loading pipeline (197 lines)
├── plan-model-inheritance.ts # Plan demotion logic (28 lines)
├── prometheus-agent-config-builder.ts # Prometheus config builder (99 lines)
── 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`):**
- Loads all plugin components (agents, skills, commands, MCPs)
- Applies permission migrations for compatibility
- Merges user/project/global configurations
- Handles Claude Code plugin integration
1. `applyProviderConfig` → Cache model context limits, detect anthropic-beta headers
2. `loadPluginComponents` → Discover Claude Code plugins (10s timeout, error isolation)
3. `applyAgentConfig` → Load all agents, sisyphus/prometheus/plan demotion
4. `applyToolConfig` → Agent-specific tool permissions (grep_app, task, teammate)
5. `applyMcpConfig` → Merge builtin + Claude Code + plugin MCPs
6. `applyCommandConfig` → Merge builtin + user + project + opencode commands/skills
**Plan Model Inheritance:**
- Demotes plan agent to prometheus when planner enabled
- Preserves user overrides during migration
- Handles model/variant inheritance from categories
## PLAN MODEL INHERITANCE
## 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
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
## AGENT LOADING ORDER
## 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:**
- Concurrent discovery of user/project/global components
- Timeout protection for plugin loading (default: 10s)
- Error isolation (failed plugins don't break others)
**Reordered** by `reorderAgentsByPriority()`: sisyphus, hephaestus, prometheus, atlas first.
**Migration Support:**
- Agent name mapping (old → new names)
- Permission format conversion
- Config structure updates
## TOOL PERMISSIONS
**Claude Code Integration:**
- Plugin component loading
- MCP server discovery
- Agent/skill/command compatibility
| Agent | Special Permissions |
|-------|---------------------|
| librarian | grep_app_* allowed |
| atlas | task, task_*, teammate allowed |
| sisyphus | task, task_*, teammate, question allowed |
| hephaestus | task, question allowed |
| multimodal-looker | Denies task, look_at |
## CONFIGURATION FLOW
## INTEGRATION
```
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()
]);
```
Created in `create-managers.ts`, exposed as `config` hook in `plugin-interface.ts`. OpenCode calls it during session init.

View File

@@ -2,83 +2,92 @@
## OVERVIEW
88 cross-cutting utilities. Import via barrel pattern: `import { log, deepMerge } from "../../shared"`
**Categories**: Path resolution, Token truncation, Config parsing, Model resolution, System directives, Tool restrictions
84 cross-cutting utilities across 6 subdirectories. Import via barrel: `import { log, deepMerge } from "../../shared"`
## STRUCTURE
```
shared/
├── git-worktree/ # Git worktree operations (311 lines)
├── tmux/ # Tmux TUI integration (227 lines)
├── logger.ts # File-based logging (/tmp/oh-my-opencode.log) - 53 imports
├── dynamic-truncator.ts # Token-aware context window management (201 lines)
├── model-resolver.ts # 3-step resolution (Override → Fallback → Default)
├── model-requirements.ts # Agent/category model fallback chains (160 lines)
├── model-availability.ts # Provider model fetching & fuzzy matching (358 lines)
├── model-sanitizer.ts # Model name sanitization
├── model-suggestion-retry.ts # Model suggestion on failure
├── jsonc-parser.ts # JSONC parsing with comment support
├── frontmatter.ts # YAML frontmatter extraction (JSON_SCHEMA only) - 9 imports
├── data-path.ts # XDG-compliant storage resolution
├── opencode-config-dir.ts # ~/.config/opencode resolution (138 lines) - 9 imports
├── claude-config-dir.ts # ~/.claude resolution - 9 imports
├── migration.ts # Legacy config migration logic (341 lines across dir)
├── opencode-version.ts # Semantic version comparison
├── permission-compat.ts # Agent tool restriction enforcement - 6 imports
├── system-directive.ts # Unified system message prefix & types - 8 imports
├── session-utils.ts # Session cursor, orchestrator detection
├── session-cursor.ts # Session message cursor tracking
├── shell-env.ts # Cross-platform shell environment
├── agent-variant.ts # Agent variant from config
├── zip-extractor.ts # Binary/Resource ZIP extraction
├── deep-merge.ts # Recursive object merging (proto-pollution safe, MAX_DEPTH=50)
├── command-executor.ts # Shell command execution (213 lines across dir)
├── snake-case.ts # Case conversion utilities
├── tool-name.ts # Tool naming conventions
├── pattern-matcher.ts # Pattern matching utilities
├── port-utils.ts # Port management
├── file-utils.ts # File operation utilities
├── file-reference-resolver.ts # File reference resolution
├── connected-providers-cache.ts # Provider caching
├── external-plugin-detector.ts # Plugin detection
├── first-message-variant.ts # Message variant types
├── opencode-server-auth.ts # Authentication utilities
── index.ts # Barrel export for all utilities
├── logger.ts # File logging (/tmp/oh-my-opencode.log) — 62 imports
├── dynamic-truncator.ts # Token-aware context window management (201 lines)
├── model-resolver.ts # 3-step resolution (Override → Fallback → Default)
├── model-availability.ts # Provider model fetching & fuzzy matching (358 lines)
├── model-requirements.ts # Agent/category fallback chains (160 lines)
├── model-resolution-pipeline.ts # Pipeline orchestration (175 lines)
├── model-resolution-types.ts # Resolution request/provenance types
├── model-sanitizer.ts # Model name sanitization
├── model-name-matcher.ts # Model name matching (91 lines)
├── model-suggestion-retry.ts # Suggest models on failure (129 lines)
├── model-cache-availability.ts # Cache availability checking
├── fallback-model-availability.ts # Fallback model logic (67 lines)
├── available-models-fetcher.ts # Fetch models from providers (114 lines)
├── models-json-cache-reader.ts # Read models.json cache
├── provider-models-cache-model-reader.ts # Provider cache reader
├── connected-providers-cache.ts # Provider caching (196 lines)
├── system-directive.ts # Unified message prefix & types (61 lines) — 11 imports
├── session-utils.ts # Session cursor, orchestrator detection
├── session-cursor.ts # Message cursor tracking (85 lines)
├── session-injected-paths.ts # Injected file path tracking
├── permission-compat.ts # Tool restriction enforcement (86 lines)
├── agent-tool-restrictions.ts # Tool restriction definitions
├── agent-variant.ts # Agent variant from config (91 lines)
├── agent-display-names.ts # Agent display name mapping
├── first-message-variant.ts # First message variant types
├── opencode-config-dir.ts # ~/.config/opencode resolution (138 lines)
├── claude-config-dir.ts # ~/.claude resolution
├── data-path.ts # XDG-compliant storage (47 lines)
├── jsonc-parser.ts # JSONC with comment support (66 lines)
├── frontmatter.ts # YAML frontmatter extraction (31 lines) — 10 imports
├── deep-merge.ts # Recursive merge (proto-pollution safe, MAX_DEPTH=50)
├── shell-env.ts # Cross-platform shell environment (111 lines)
├── opencode-version.ts # Semantic version comparison (74 lines)
├── external-plugin-detector.ts # Plugin conflict detection (137 lines)
├── opencode-server-auth.ts # Authentication utilities (69 lines)
── 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
| Utility | Imports | Purpose |
|---------|---------|---------|
| logger.ts | 53 | Background task visibility |
| opencode-config-dir.ts | 9 | Path resolution |
| claude-config-dir.ts | 9 | Path resolution |
| frontmatter.ts | 9 | YAML parsing |
| system-directive.ts | 8 | Message filtering |
| permission-compat.ts | 6 | Tool restrictions |
## WHEN TO USE
| 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)` |
| logger.ts | 62 | Background task visibility |
| data-path.ts | 11 | XDG storage resolution |
| model-requirements.ts | 11 | Agent fallback chains |
| system-directive.ts | 11 | System message filtering |
| frontmatter.ts | 10 | YAML metadata extraction |
| permission-compat.ts | 9 | Tool restrictions |
| file-utils.ts | 9 | File operations |
| dynamic-truncator.ts | 7 | Token-aware truncation |
## KEY PATTERNS
**3-Step Resolution** (Override → Fallback → Default):
**3-Step Model Resolution** (Override → Fallback → Default):
```typescript
const model = resolveModelWithFallback({
userModel: config.agents.sisyphus.model,
fallbackChain: AGENT_MODEL_REQUIREMENTS.sisyphus.fallbackChain,
availableModels: fetchedModels,
})
resolveModelWithFallback({ userModel, fallbackChain, availableModels })
```
**System Directive Filtering**:
@@ -88,8 +97,9 @@ const directive = createSystemDirective("TODO CONTINUATION")
```
## ANTI-PATTERNS
- **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
- **Unbounded Output**: Use `dynamic-truncator.ts` to prevent overflow
- **Manual Version Check**: Use `opencode-version.ts` for semver safety
- **Unbounded output**: Use `dynamic-truncator.ts` to prevent overflow
- **Manual version check**: Use `opencode-version.ts` for semver safety

View File

@@ -2,91 +2,69 @@
## OVERVIEW
25+ 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)
24 tools across 14 directories. Two patterns: Direct ToolDefinition (static) and Factory Function (context-dependent).
## STRUCTURE
```
tools/
├── [tool-name]/
│ ├── index.ts # Barrel export
│ ├── tools.ts # ToolDefinition or factory
│ ├── types.ts # Zod schemas
│ └── constants.ts # Fixed values
├── lsp/ # 6 tools: goto_definition, find_references, symbols, diagnostics, prepare_rename, rename
├── delegate-task/ # Category routing (constants.ts 569 lines, tools.ts 213 lines)
├── task/ # Unified CRUD: create/list/get/update/delete (task.ts 58 lines)
├── lsp/ # 6 LSP tools: goto_definition, find_references, symbols, diagnostics, prepare_rename, rename
├── 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)
├── glob/ # 60s timeout, 100 file limit
├── interactive-bash/ # Tmux session management
├── look-at/ # Multimodal PDF/image analysis
├── skill/ # Skill execution
├── skill-mcp/ # Skill MCP operations
├── slashcommand/ # Slash command dispatch
├── call-omo-agent/ # Direct agent invocation
── background-task/ # background_output, background_cancel
├── glob/ # File search (60s timeout, 100 file limit)
├── session-manager/ # 4 tools: list, read, search, info (151 lines)
├── call-omo-agent/ # Direct agent invocation (57 lines)
├── background-task/ # background_output, background_cancel
├── interactive-bash/ # Tmux session management (135 lines)
├── look-at/ # Multimodal PDF/image analysis (156 lines)
├── skill/ # Skill execution with MCP support (211 lines)
── skill-mcp/ # MCP tool/resource/prompt operations (182 lines)
└── slashcommand/ # Slash command dispatch
```
## TOOL CATEGORIES
## TOOL INVENTORY
| Category | Tools | Pattern |
|----------|-------|---------|
| LSP | lsp_goto_definition, lsp_find_references, lsp_symbols, lsp_diagnostics, lsp_prepare_rename, lsp_rename | Direct |
| Search | ast_grep_search, ast_grep_replace, grep, glob | Direct |
| Session | session_list, session_read, session_search, session_info | Direct |
| Task | task_create, task_get, task_list, task_update | Factory |
| Agent | call_omo_agent | Factory |
| Background | background_output, background_cancel | Factory |
| System | interactive_bash, look_at | Mixed |
| Skill | skill, skill_mcp | Factory |
| Command | slashcommand | Factory |
| Tool | Category | Pattern | Key Logic |
|------|----------|---------|-----------|
| `task` | Task | Factory | Unified 5-action dispatch (create/list/get/update/delete) |
| `call_omo_agent` | Agent | Factory | Direct explore/librarian invocation |
| `background_output` | Background | Factory | Retrieve background task result |
| `background_cancel` | Background | Factory | Cancel running background tasks |
| `lsp_goto_definition` | LSP | Direct | Jump to symbol definition |
| `lsp_find_references` | LSP | Direct | Find all usages across workspace |
| `lsp_symbols` | LSP | Direct | Document or workspace symbol search |
| `lsp_diagnostics` | LSP | Direct | Get errors/warnings from language server |
| `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.
- **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`.
Each category defines: model, variant, temperature, max tokens, thinking/reasoning config, prompt append, stability flag.
## HOW TO ADD
1. Create `src/tools/[name]/` with standard files
2. Use `tool()` from `@opencode-ai/plugin/tool`
3. Export from `src/tools/index.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 */ } })
}
```
1. Create `src/tools/[name]/` with index.ts, tools.ts, types.ts, constants.ts
2. Static tools → `builtinTools` export, Factory → separate export
3. Register in `src/plugin/tool-registry.ts`
## NAMING
- **Tool names**: snake_case (`lsp_goto_definition`)
- **Functions**: camelCase (`createDelegateTask`)
- **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