docs: regenerate hierarchical AGENTS.md with deep investigation

- Root: 181 lines with agent models, complexity hotspots, CI pipeline
- Hooks: 31 lifecycle hooks, execution order, patterns
- Tools: 20+ tools, LSP/AST-Grep specifics, registration
- Features: Background agents, Claude Code compat, skill MCP
- Agents: 10 agents with models, tool restrictions
- Shared: 43 utilities with usage patterns
- CLI: Commander.js entry, doctor checks, TUI framework

Generated via /init-deep with 12 parallel explore agents
This commit is contained in:
justsisyphus
2026-01-17 22:01:56 +09:00
parent 255f535a50
commit 6d99b5c1fc
7 changed files with 385 additions and 280 deletions
+58 -37
View File
@@ -1,50 +1,71 @@
# AGENTS KNOWLEDGE BASE
## OVERVIEW
AI agent definitions for multi-model orchestration, delegating tasks to specialized experts.
10 AI agents for multi-model orchestration. Sisyphus (primary), oracle, librarian, explore, frontend, document-writer, multimodal-looker, Prometheus, Metis, Momus.
## STRUCTURE
```
agents/
├── orchestrator-sisyphus.ts # Orchestrator agent (1531 lines) - 7-section delegation, wisdom
├── sisyphus.ts # Main Sisyphus prompt (640 lines)
├── sisyphus-junior.ts # Junior variant for delegated tasks
├── oracle.ts # Strategic advisor (GPT-5.2)
├── librarian.ts # Multi-repo research (GLM-4.7-free)
├── explore.ts # Fast codebase grep (Grok Code)
├── frontend-ui-ux-engineer.ts # UI generation (Gemini 3 Pro Preview)
├── document-writer.ts # Technical docs (Gemini 3 Pro Preview)
├── multimodal-looker.ts # PDF/image analysis (Gemini 3 Flash)
├── prometheus-prompt.ts # Planning agent prompt (1196 lines) - interview mode
├── metis.ts # Plan Consultant agent - pre-planning analysis
├── momus.ts # Plan Reviewer agent - plan validation
├── build-prompt.ts # Shared build agent prompt
├── plan-prompt.ts # Shared plan agent prompt
├── sisyphus-prompt-builder.ts # Factory for orchestrator prompts
── types.ts # AgentModelConfig interface
├── utils.ts # createBuiltinAgents(), getAgentName()
└── index.ts # builtinAgents export
├── orchestrator-sisyphus.ts # Orchestrator (1531 lines) - 7-phase delegation
├── sisyphus.ts # Main prompt (640 lines)
├── sisyphus-junior.ts # Delegated task executor
├── sisyphus-prompt-builder.ts # Dynamic prompt generation
├── oracle.ts # Strategic advisor (GPT-5.2)
├── librarian.ts # Multi-repo research (GLM-4.7-free)
├── explore.ts # Fast grep (Grok Code)
├── frontend-ui-ux-engineer.ts # UI specialist (Gemini 3 Pro)
├── document-writer.ts # Technical writer (Gemini 3 Flash)
├── multimodal-looker.ts # Media analyzer (Gemini 3 Flash)
├── prometheus-prompt.ts # Planning (1196 lines) - interview mode
├── metis.ts # Plan consultant - pre-planning analysis
├── momus.ts # Plan reviewer - validation
├── types.ts # AgentModelConfig interface
├── utils.ts # createBuiltinAgents(), getAgentName()
── index.ts # builtinAgents export
```
## HOW TO ADD AN AGENT
1. Create `src/agents/my-agent.ts` exporting `AgentConfig`.
2. Add to `builtinAgents` in `src/agents/index.ts`.
3. Update `types.ts` if adding new config interfaces.
## AGENT MODELS
## MODEL FALLBACK LOGIC
`createBuiltinAgents()` handles resolution:
1. User config override (`agents.{name}.model`).
2. Environment-specific settings (max20, antigravity).
3. Hardcoded defaults in `index.ts`.
| Agent | Model | Temperature | Purpose |
|-------|-------|-------------|---------|
| Sisyphus | anthropic/claude-opus-4-5 | 0.1 | Primary orchestrator, todo-driven |
| oracle | openai/gpt-5.2 | 0.1 | Read-only consultation, debugging |
| librarian | opencode/glm-4.7-free | 0.1 | Docs, GitHub search, OSS examples |
| explore | opencode/grok-code | 0.1 | Fast contextual grep |
| frontend-ui-ux-engineer | google/gemini-3-pro-preview | 0.7 | UI generation, visual design |
| document-writer | google/gemini-3-flash | 0.3 | Technical documentation |
| multimodal-looker | google/gemini-3-flash | 0.1 | PDF/image analysis |
| Prometheus | anthropic/claude-opus-4-5 | 0.1 | Strategic planning, interview mode |
| Metis | anthropic/claude-sonnet-4-5 | 0.1 | Pre-planning gap analysis |
| Momus | anthropic/claude-sonnet-4-5 | 0.1 | Plan validation |
## SHARED PROMPTS
- **7-Section Delegation**: `orchestrator-sisyphus.ts` uses strict phases (0-6) for classification, research, planning, validation.
- **Wisdom Notepad**: Persistent scratchpad preserving project-specific learnings across turns.
- **Interview Mode**: `Prometheus` defaults to conversational consultant mode for requirement extraction.
- **build-prompt.ts**: Unified base for Sisyphus and Builder variants.
- **plan-prompt.ts**: Core planning logic shared across planning agents.
## HOW TO ADD
1. Create `src/agents/my-agent.ts` exporting `AgentConfig`
2. Add to `builtinAgents` in `src/agents/index.ts`
3. Update `AgentNameSchema` in `src/config/schema.ts`
4. Register in `src/index.ts` initialization
## TOOL RESTRICTIONS
| Agent | Denied Tools |
|-------|-------------|
| oracle | write, edit, task, delegate_task |
| librarian | write, edit, task, delegate_task, call_omo_agent |
| explore | write, edit, task, delegate_task, call_omo_agent |
| multimodal-looker | Allowlist: read, glob, grep |
## KEY PATTERNS
- **Factory**: `createXXXAgent(model?: string): AgentConfig`
- **Metadata**: `XXX_PROMPT_METADATA: AgentPromptMetadata`
- **Tool restrictions**: `permission: { edit: "deny", bash: "ask" }`
- **Thinking**: 32k budget tokens for Sisyphus, Oracle, Prometheus
## ANTI-PATTERNS
- **Trusting reports**: NEVER trust subagent self-reports; always verify outputs.
- **High temp**: Don't use >0.3 for code agents (Sisyphus/Prometheus use 0.1).
- **Sequential calls**: Prefer `delegate_task` with `run_in_background` for parallelism.
- **Trust reports**: NEVER trust subagent "I'm done" - verify outputs
- **High temp**: Don't use >0.3 for code agents
- **Sequential calls**: Use `delegate_task` with `run_in_background`
+71 -37
View File
@@ -1,57 +1,91 @@
# CLI KNOWLEDGE BASE
## OVERVIEW
CLI for oh-my-opencode: interactive installer, health diagnostics (doctor), runtime launcher. Entry: `bunx oh-my-opencode`.
CLI entry point: `bunx oh-my-opencode`. Interactive installer, doctor diagnostics, session runner. Uses Commander.js + @clack/prompts TUI.
## STRUCTURE
```
cli/
├── index.ts # Commander.js entry, subcommand routing
├── index.ts # Commander.js entry, 5 subcommands
├── install.ts # Interactive TUI installer (462 lines)
├── config-manager.ts # JSONC parsing, env detection (730 lines)
├── types.ts # CLI-specific types
├── doctor/ # Health check system
├── config-manager.ts # JSONC parsing, multi-level merge (730 lines)
├── types.ts # InstallArgs, InstallConfig, DetectedConfig
├── doctor/
│ ├── index.ts # Doctor command entry
│ ├── runner.ts # Health check orchestration
│ ├── constants.ts # Check categories
│ ├── types.ts # Check result interfaces
── checks/ # 10 check modules (14 individual checks)
├── get-local-version/ # Version detection
└── run/ # OpenCode session launcher
├── completion.ts # Completion logic
└── events.ts # Event handling
│ ├── runner.ts # Check orchestration
│ ├── formatter.ts # Colored output, symbols
│ ├── constants.ts # Check IDs, categories, symbols
── types.ts # CheckResult, CheckDefinition
│ └── checks/ # 14 checks across 6 categories
│ ├── version.ts # OpenCode + plugin version
├── config.ts # JSONC validity, Zod validation
│ ├── auth.ts # Anthropic, OpenAI, Google
│ ├── dependencies.ts # AST-Grep, Comment Checker
│ ├── lsp.ts # LSP server connectivity
│ ├── mcp.ts # MCP server validation
│ └── gh.ts # GitHub CLI availability
├── run/
│ ├── index.ts # Run command entry
│ └── runner.ts # Session launcher
└── get-local-version/
├── index.ts # Version detection
└── formatter.ts # Version output
```
## CLI COMMANDS
| Command | Purpose |
|---------|---------|
| `install` | Interactive setup wizard with subscription detection |
| `doctor` | Environment health checks (LSP, Auth, Config, Deps) |
| `run` | Launch OpenCode session with todo/background completion enforcement |
| `get-local-version` | Detect and return local plugin version & update status |
| `install` | Interactive setup, subscription detection |
| `doctor` | 14 health checks, `--verbose`, `--json`, `--category` |
| `run` | Launch OpenCode session with completion enforcement |
| `get-local-version` | Version detection, update checking |
## DOCTOR CHECKS
14 checks in `doctor/checks/`:
- `version.ts`: OpenCode >= 1.0.150 & plugin update status
- `config.ts`: Plugin registration & JSONC validity
- `dependencies.ts`: AST-Grep (CLI/NAPI), Comment Checker
- `auth.ts`: Anthropic, OpenAI, Google (Antigravity)
- `lsp.ts`, `mcp.ts`: Tool connectivity checks
- `gh.ts`: GitHub CLI availability
## DOCTOR CHECK CATEGORIES
## CONFIG-MANAGER
- **JSONC**: Supports comments and trailing commas via `parseJsonc`
- **Multi-source**: Merges User (`~/.config/opencode/`) + Project (`.opencode/`)
- **Validation**: Strict Zod schema with error aggregation for `doctor`
- **Env**: Detects `OPENCODE_CONFIG_DIR` for profile isolation
| Category | Checks |
|----------|--------|
| installation | opencode, plugin registration |
| configuration | config validity, Zod validation |
| authentication | anthropic, openai, google |
| dependencies | ast-grep CLI/NAPI, comment-checker |
| tools | LSP, MCP connectivity |
| updates | version comparison |
## HOW TO ADD CHECK
1. Create `src/cli/doctor/checks/my-check.ts` returning `DoctorCheck`
2. Export from `checks/index.ts` and add to `getAllCheckDefinitions()`
3. Use `CheckContext` for shared utilities (LSP, Auth)
1. Create `src/cli/doctor/checks/my-check.ts`:
```typescript
export function getMyCheckDefinition(): CheckDefinition {
return {
id: "my-check",
name: "My Check",
category: "configuration",
check: async () => ({ status: "pass", message: "OK" })
}
}
```
2. Export from `checks/index.ts`
3. Add to `getAllCheckDefinitions()`
## TUI FRAMEWORK
- **@clack/prompts**: `select()`, `spinner()`, `intro()`, `outro()`, `note()`
- **picocolors**: Colored terminal output
- **Symbols**: ✓ (pass), ✗ (fail), ⚠ (warn), ○ (skip)
## CONFIG-MANAGER
- **JSONC**: Comments (`// ...`), block comments, trailing commas
- **Multi-source**: User (`~/.config/opencode/`) + Project (`.opencode/`)
- **Env override**: `OPENCODE_CONFIG_DIR` for profile isolation
- **Validation**: Zod schema with error aggregation
## ANTI-PATTERNS
- Blocking prompts in non-TTY (check `process.stdout.isTTY`)
- Direct `JSON.parse` (breaks JSONC compatibility)
- Silent failures (always return `warn` or `fail` in `doctor`)
- Environment-specific hardcoding (use `ConfigManager`)
- **Blocking in non-TTY**: Check `process.stdout.isTTY`
- **Direct JSON.parse**: Use `parseJsonc()` for config
- **Silent failures**: Always return warn/fail in doctor
- **Hardcoded paths**: Use `ConfigManager`
+44 -32
View File
@@ -1,39 +1,62 @@
# FEATURES KNOWLEDGE BASE
## OVERVIEW
Claude Code compatibility layer + core feature modules. Commands, skills, agents, MCPs, hooks from Claude Code work seamlessly.
Core feature modules + Claude Code compatibility layer. Background agents, skill MCP, builtin skills/commands, and 5 loaders for Claude Code compat.
## STRUCTURE
```
features/
├── background-agent/ # Task lifecycle, notifications (1165 lines manager.ts)
├── boulder-state/ # Boulder/Todo state persistence
├── builtin-commands/ # Built-in slash commands (ralph-loop, refactor, init-deep)
├── builtin-skills/ # Built-in skills (1203 lines skills.ts)
│ ├── git-master/ # Atomic commits, history search
│ ├── playwright/ # Browser automation
│ └── frontend-ui-ux/ # Designer-developer skill
├── background-agent/ # Task lifecycle (1165 lines manager.ts)
│ ├── manager.ts # Launch → poll → complete orchestration
│ ├── concurrency.ts # Per-provider/model limits
│ └── types.ts # BackgroundTask, LaunchInput
├── skill-mcp-manager/ # MCP client lifecycle
│ ├── manager.ts # Lazy loading, idle cleanup
│ └── types.ts # SkillMcpConfig, transports
├── builtin-skills/ # Playwright, git-master, frontend-ui-ux
│ └── skills.ts # 1203 lines of skill definitions
├── builtin-commands/ # ralph-loop, refactor, init-deep
│ └── templates/ # Command implementations
├── claude-code-agent-loader/ # ~/.claude/agents/*.md
├── claude-code-command-loader/ # ~/.claude/commands/*.md
├── claude-code-mcp-loader/ # .mcp.json files with ${VAR} expansion
├── claude-code-mcp-loader/ # .mcp.json with ${VAR} expansion
├── claude-code-plugin-loader/ # installed_plugins.json
├── claude-code-session-state/ # Session state persistence
├── context-injector/ # AGENTS.md/README.md/Rules injection
├── opencode-skill-loader/ # Skills from OpenCode + Claude paths
├── skill-mcp-manager/ # MCP servers in skill YAML (stdio/http transports)
├── task-toast-manager/ # Task status toast notifications
└── hook-message-injector/ # Message injection into conversation streams
├── opencode-skill-loader/ # Skills from 6 directories
├── context-injector/ # AGENTS.md/README.md injection
├── boulder-state/ # Todo state persistence
├── task-toast-manager/ # Toast notifications
└── hook-message-injector/ # Message injection
```
## LOADER PRIORITY
| Loader | Priority (highest first) |
|--------|--------------------------|
| Type | Priority (highest first) |
|------|--------------------------|
| Commands | `.opencode/command/` > `~/.config/opencode/command/` > `.claude/commands/` > `~/.claude/commands/` |
| Skills | `.opencode/skill/` > `~/.config/opencode/skill/` > `.claude/skills/` > `~/.claude/skills/` |
| Agents | `.claude/agents/` > `~/.claude/agents/` |
| MCPs | `.claude/.mcp.json` > `.mcp.json` > `~/.claude/.mcp.json` |
## BACKGROUND AGENT
- **Lifecycle**: `launch``poll` (2s interval) → `complete`
- **Stability**: 3 consecutive polls with same message count = idle
- **Concurrency**: Per-provider/model limits (e.g., max 3 Opus, max 10 Gemini)
- **Notification**: Batched system reminders to parent session
- **Cleanup**: 30m TTL, 3m stale timeout, signal handlers
## SKILL MCP
- **Lazy**: Clients created on first tool call
- **Transports**: stdio (local process), http (SSE/Streamable)
- **Environment**: `${VAR}` expansion in config
- **Lifecycle**: 5m idle cleanup, session-scoped
## CONFIG TOGGLES
```jsonc
{
"claude_code": {
@@ -46,20 +69,9 @@ features/
}
```
## BACKGROUND AGENT
- **Lifecycle**: `launch``poll` (idle/stability detection) → `complete`.
- **Concurrency**: Per-provider/model limits in `concurrency.ts`.
- **Notification**: Auto-injects system reminders into parent session on task completion.
- **Cleanup**: Shutdown handler cancels pending waiters; idle tasks pruning (30m TTL).
## SKILL MCP
- **Lazy Loading**: Clients connect on first tool call via `SkillMcpManager`.
- **Transports**: `stdio` (local process) or `http` (SSE/Streamable HTTP).
- **Environment**: `${VAR}` expansion in config via `env-expander.ts`.
- **Lifecycle**: Session-scoped clients; auto-cleanup after 5m idle.
## ANTI-PATTERNS
- **Sequential Delegation**: Calling agents one-by-one; use `delegate_task` for parallel runs.
- **Self-Report Trust**: Trusting agent's "I'm done" without verifying against session state.
- **Main Thread Blocks**: Heavy I/O or long-running logic during loader initialization.
- **Manual Versioning**: Updating `package.json` version field; managed exclusively by CI.
- **Sequential delegation**: Use `delegate_task` for parallel
- **Trust self-reports**: ALWAYS verify agent outputs
- **Main thread blocks**: No heavy I/O in loader init
- **Manual versioning**: CI manages package.json version
+53 -33
View File
@@ -1,53 +1,73 @@
# HOOKS KNOWLEDGE BASE
## OVERVIEW
22+ lifecycle hooks intercepting/modifying agent behavior via PreToolUse, PostToolUse, UserPromptSubmit, and more.
31 lifecycle hooks intercepting/modifying agent behavior. Events: PreToolUse, PostToolUse, UserPromptSubmit, Stop, onSummarize.
## STRUCTURE
```
hooks/
├── sisyphus-orchestrator/ # Main orchestration & agent delegation (771 lines)
├── anthropic-context-window-limit-recovery/ # Auto-summarize at token limit (14 files)
├── todo-continuation-enforcer.ts # Force completion of [ ] items
├── ralph-loop/ # Self-referential dev loop (7 files)
├── claude-code-hooks/ # settings.json hook compatibility layer (13 files)
├── comment-checker/ # Prevents AI slop/excessive comments (13 files)
├── auto-slash-command/ # Detects and executes /command patterns
├── sisyphus-orchestrator/ # Main orchestration & delegation (771 lines)
├── anthropic-context-window-limit-recovery/ # Auto-summarize at token limit
├── todo-continuation-enforcer.ts # Force TODO completion
├── ralph-loop/ # Self-referential dev loop until done
├── claude-code-hooks/ # settings.json hook compat layer (13 files)
├── comment-checker/ # Prevents AI slop/excessive comments
├── auto-slash-command/ # Detects /command patterns
├── rules-injector/ # Conditional rules from .claude/rules/
├── directory-agents-injector/ # Auto-injects local AGENTS.md files
├── directory-readme-injector/ # Auto-injects local README.md files
├── preemptive-compaction/ # Triggers summary at 85% usage
├── edit-error-recovery/ # Recovers from tool execution failures
├── directory-agents-injector/ # Auto-injects AGENTS.md files
├── directory-readme-injector/ # Auto-injects README.md files
├── preemptive-compaction/ # Triggers summary at 85% context
├── edit-error-recovery/ # Recovers from tool failures
├── thinking-block-validator/ # Ensures valid <thinking> format
├── context-window-monitor.ts # Reminds agents of remaining headroom
├── session-recovery/ # Auto-recovers from session crashes
├── think-mode/ # Dynamic thinking budget adjustment
├── session-recovery/ # Auto-recovers from crashes
├── think-mode/ # Dynamic thinking budget
├── keyword-detector/ # ultrawork/search/analyze modes
├── background-notification/ # OS notification on task completion
└── tool-output-truncator.ts # Prevents context bloat from verbose tools
└── tool-output-truncator.ts # Prevents context bloat
```
## HOOK EVENTS
| Event | Timing | Can Block | Description |
|-------|--------|-----------|-------------|
| PreToolUse | Before tool | Yes | Validate/modify inputs (e.g., directory-agents-injector) |
| PostToolUse | After tool | No | Append context/warnings (e.g., edit-error-recovery) |
| UserPromptSubmit | On prompt | Yes | Filter/modify user input (e.g., keyword-detector) |
| Stop | Session idle | No | Auto-continue tasks (e.g., todo-continuation-enforcer) |
| onSummarize | Compaction | No | State preservation (e.g., compaction-context-injector) |
| Event | Timing | Can Block | Use Case |
|-------|--------|-----------|----------|
| PreToolUse | Before tool | Yes | Validate/modify inputs, inject context |
| PostToolUse | After tool | No | Append warnings, truncate output |
| UserPromptSubmit | On prompt | Yes | Keyword detection, mode switching |
| Stop | Session idle | No | Auto-continue (todo-continuation, ralph-loop) |
| onSummarize | Compaction | No | Preserve critical state |
## EXECUTION ORDER
**chat.message**: keywordDetector → claudeCodeHooks → autoSlashCommand → startWork → ralphLoop
**tool.execute.before**: claudeCodeHooks → nonInteractiveEnv → commentChecker → directoryAgentsInjector → directoryReadmeInjector → rulesInjector
**tool.execute.after**: editErrorRecovery → delegateTaskRetry → commentChecker → toolOutputTruncator → emptyTaskResponseDetector → claudeCodeHooks
## HOW TO ADD
1. Create `src/hooks/name/` with `index.ts` factory (e.g., `createMyHook`).
2. Implement `PreToolUse`, `PostToolUse`, `UserPromptSubmit`, `Stop`, or `onSummarize`.
3. Register in `src/hooks/index.ts`.
1. Create `src/hooks/name/` with `index.ts` exporting `createMyHook(ctx)`
2. Implement event handlers: `"tool.execute.before"`, `"tool.execute.after"`, etc.
3. Add hook name to `HookNameSchema` in `src/config/schema.ts`
4. Register in `src/index.ts`:
```typescript
const myHook = isHookEnabled("my-hook") ? createMyHook(ctx) : null
// Add to event handlers
```
## PATTERNS
- **Context Injection**: Use `PreToolUse` to prepend instructions to tool inputs.
- **Resilience**: Implement `edit-error-recovery` style logic to retry failed tools.
- **Telegraphic UI**: Use `PostToolUse` to add brief warnings without bloating transcript.
- **Statelessness**: Prefer local file storage for state that must persist across sessions.
- **Session-scoped state**: `Map<sessionID, Set<string>>` for tracking per-session
- **Conditional execution**: Check `input.tool` before processing
- **Output modification**: `output.output += "\n${REMINDER}"` to append context
- **Async state**: Use promises for CLI path resolution, cache results
## ANTI-PATTERNS
- **Blocking**: Avoid blocking tools unless critical (use warnings in `PostToolUse` instead).
- **Latency**: No heavy computation in `PreToolUse`; it slows every interaction.
- **Redundancy**: Don't inject the same file multiple times; track state in session storage.
- **Prose**: Never use verbose prose in hook outputs; keep it technical and brief.
- **Blocking non-critical**: Use PostToolUse warnings instead of PreToolUse blocks
- **Heavy computation**: Keep PreToolUse light - slows every tool call
- **Redundant injection**: Track injected files to prevent duplicates
- **Verbose output**: Keep hook messages technical, brief
+42 -31
View File
@@ -1,52 +1,63 @@
# SHARED UTILITIES KNOWLEDGE BASE
## OVERVIEW
Core cross-cutting utilities for path resolution, token-safe text processing, and Claude Code compatibility.
43 cross-cutting utilities: path resolution, token truncation, config parsing, Claude Code compatibility.
## STRUCTURE
```
shared/
├── logger.ts # Persistent file-based logging (tmpdir/oh-my-opencode.log)
├── logger.ts # File-based logging (tmpdir/oh-my-opencode.log)
├── permission-compat.ts # Agent tool restrictions (ask/allow/deny)
├── dynamic-truncator.ts # Token-aware truncation with context headroom
├── frontmatter.ts # YAML frontmatter parsing with JSON_SCHEMA safety
├── jsonc-parser.ts # JSON with Comments support for config files
├── data-path.ts # XDG-compliant storage paths (~/.local/share)
├── opencode-config-dir.ts # Resolve ~/.config/opencode for CLI/Desktop
├── claude-config-dir.ts # Resolve ~/.claude for compatibility
├── migration.ts # Legacy name mapping (omo -> Sisyphus)
── opencode-version.ts # Version comparison logic (e.g., >= 1.0.150)
├── dynamic-truncator.ts # Token-aware truncation (50% headroom)
├── frontmatter.ts # YAML frontmatter parsing
├── jsonc-parser.ts # JSON with Comments support
├── data-path.ts # XDG-compliant storage (~/.local/share)
├── opencode-config-dir.ts # ~/.config/opencode resolution
├── claude-config-dir.ts # ~/.claude resolution
├── migration.ts # Legacy config migration (omo Sisyphus)
── opencode-version.ts # Version comparison (>= 1.0.150)
├── external-plugin-detector.ts # OAuth spoofing detection
├── env-expander.ts # ${VAR} expansion in configs
├── system-directive.ts # System directive types
├── hook-utils.ts # Hook helper functions
└── *.test.ts # Test files (colocated)
```
## WHEN TO USE
| Task | Utility |
|------|---------|
| Debugging/Auditing | `log(message, data)` in `logger.ts` |
| Limit agent context | `dynamicTruncate(ctx, sessionId, output)` |
| Parse rule meta | `parseFrontmatter(content)` |
| Load user configs | `parseJsonc(text)` or `readJsoncFile(path)` |
| Restrict tools | `createAgentToolAllowlist(tools)` |
| Resolve app paths | `getOpenCodeConfigDir()` or `getClaudeConfigDir()` |
| Update legacy config | `migrateConfigFile(path, rawConfig)` |
| Debug logging | `log(message, data)` in `logger.ts` |
| Limit context | `dynamicTruncate(ctx, sessionId, output)` |
| Parse frontmatter | `parseFrontmatter(content)` |
| Load JSONC config | `parseJsonc(text)` or `readJsoncFile(path)` |
| Restrict agent tools | `createAgentToolAllowlist(tools)` |
| Resolve paths | `getOpenCodeConfigDir()`, `getClaudeConfigDir()` |
| Migrate config | `migrateConfigFile(path, rawConfig)` |
| Compare versions | `isOpenCodeVersionAtLeast("1.1.0")` |
## KEY PATTERNS
## CRITICAL PATTERNS
```typescript
// Truncate large output based on 50% remaining context window
const { result } = await dynamicTruncate(ctx, sessionID, largeBuffer);
// Token-aware truncation
const { result } = await dynamicTruncate(ctx, sessionID, largeBuffer)
// Safe config loading with comment/trailing comma support
const settings = readJsoncFile<Settings>(configPath);
// JSONC config loading
const settings = readJsoncFile<Settings>(configPath)
// Version-gated logic for OpenCode 1.1.0+
if (isOpenCodeVersionAtLeast("1.1.0")) { /* ... */ }
// Version-gated features
if (isOpenCodeVersionAtLeast("1.1.0")) { /* new feature */ }
// Permission normalization for agent tools
const permissions = migrateToolsToPermission(legacyTools);
// Tool permission normalization
const permissions = migrateToolsToPermission(legacyTools)
```
## ANTI-PATTERNS
- Raw `JSON.parse` for configs (use `jsonc-parser.ts`)
- Hardcoded `~/.claude` (use `claude-config-dir.ts`)
- `console.log` for background agents (use `logger.ts`)
- Unbounded tool output (always use `dynamic-truncator.ts`)
- Manual version parsing (use `opencode-version.ts`)
- **Raw JSON.parse**: Use `jsonc-parser.ts` for config files
- **Hardcoded paths**: Use `*-config-dir.ts` utilities
- **console.log**: Use `logger.ts` for background agents
- **Unbounded output**: Always use `dynamic-truncator.ts`
- **Manual version parse**: Use `opencode-version.ts`
+55 -31
View File
@@ -1,50 +1,74 @@
# TOOLS KNOWLEDGE BASE
## OVERVIEW
Core toolset implementing LSP, structural search, and system orchestration. Extends OpenCode with high-performance C++ bindings and multi-agent delegation.
20+ tools: LSP (11), AST-Grep (2), Search (2), Session (4), Agent delegation (3), System (2). High-performance C++ bindings via @ast-grep/napi.
## STRUCTURE
```
tools/
├── [tool-name]/
│ ├── index.ts # Tool factory entry
│ ├── tools.ts # Business logic & implementation
│ ├── types.ts # Zod schemas & TS types
│ └── constants.ts # Tool-specific fixed values
├── lsp/ # 11 tools via JSON-RPC client (596 lines client.ts)
├── ast-grep/ # Structural search (NAPI bindings)
├── delegate-task/ # Category-based agent routing (770 lines tools.ts)
├── session-manager/ # OpenCode session history (9 files)
── interactive-bash/ # Tmux session management (5 files)
│ ├── index.ts # Barrel export
│ ├── tools.ts # Business logic, ToolDefinition
│ ├── types.ts # Zod schemas
│ └── constants.ts # Fixed values, descriptions
├── lsp/ # 11 tools: goto_definition, references, symbols, diagnostics, rename
├── ast-grep/ # 2 tools: search, replace (25 languages via NAPI)
├── delegate-task/ # Category-based agent routing (761 lines)
├── session-manager/ # 4 tools: list, read, search, info
── grep/ # Custom grep with timeout/truncation
├── glob/ # Custom glob with 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
```
## TOOL CATEGORIES
| Category | Purpose | Key Implementations |
|----------|---------|---------------------|
| **LSP** | Semantic code intelligence | `lsp_goto_definition`, `lsp_find_references`, `lsp_rename` |
| **Search** | Fast discovery & matching | `glob`, `grep`, `ast_grep_search`, `ast_grep_replace` |
| **System** | CLI & Environment | `bash`, `interactive_bash` (tmux), `look_at` (vision) |
| **Session** | History & Context | `session_read`, `session_search`, `session_select` |
| **Agent** | Task Orchestration | `delegate_task`, `call_omo_agent` |
| Category | Tools | Purpose |
|----------|-------|---------|
| **LSP** | lsp_goto_definition, lsp_find_references, lsp_symbols, lsp_diagnostics, lsp_prepare_rename, lsp_rename | Semantic code intelligence |
| **Search** | ast_grep_search, ast_grep_replace, grep, glob | Pattern discovery |
| **Session** | session_list, session_read, session_search, session_info | History navigation |
| **Agent** | delegate_task, call_omo_agent, background_output, background_cancel | Task orchestration |
| **System** | interactive_bash, look_at | CLI, multimodal |
| **Skill** | skill, skill_mcp, slashcommand | Skill execution |
## HOW TO ADD
1. **Directory**: Create `src/tools/[name]/` with standard files.
2. **Factory**: Use `tool()` from `@opencode-ai/plugin/tool`.
3. **Parameters**: Define strict Zod schemas in `types.ts`.
4. **Registration**: Export from `src/tools/index.ts` and add to `builtinTools`.
1. Create `src/tools/[name]/` with standard files
2. Use `tool()` from `@opencode-ai/plugin/tool`:
```typescript
export const myTool: ToolDefinition = tool({
description: "...",
args: { param: tool.schema.string() },
execute: async (args) => { /* ... */ }
})
```
3. Export from `src/tools/index.ts`
4. Add to `builtinTools` object
## LSP SPECIFICS
- **Client**: `lsp/client.ts` manages stdio lifecycle and JSON-RPC.
- **Capabilities**: Supports definition, references, symbols, diagnostics, and workspace-wide rename.
- **Protocol**: Maps standard LSP methods to tool-compatible responses.
- **Client**: `client.ts` manages stdio lifecycle, JSON-RPC
- **Singleton**: `LSPServerManager` with ref counting
- **Protocol**: Standard LSP methods mapped to tool responses
- **Capabilities**: definition, references, symbols, diagnostics, rename
## AST-GREP SPECIFICS
- **Engine**: Uses `@ast-grep/napi` for 25+ language support.
- **Patterns**: Supports meta-variables (`$VAR`) and multi-node matching (`$$$`).
- **Performance**: Structural matching executed in Rust/C++ layer.
- **Engine**: `@ast-grep/napi` for 25+ languages
- **Patterns**: Meta-variables `$VAR` (single), `$$$` (multiple)
- **Performance**: Rust/C++ layer for structural matching
## ANTI-PATTERNS
- **Sequential Calls**: Don't call `bash` in loops; use `&&` or delegation.
- **Raw File Ops**: Never use `mkdir/touch` inside tool logic.
- **Heavy Sync**: Keep `PreToolUse` light; heavy computation belongs in `tools.ts`.
- **Sleep**: Never use `sleep N`; use polling loops or tool-specific wait flags.
- **Sequential bash**: Use `&&` or delegation, not loops
- **Raw file ops**: Never mkdir/touch in tool logic
- **Sleep**: Use polling loops, tool-specific wait flags
- **Heavy sync**: Keep PreToolUse light, computation in tools.ts