Compare commits

...

34 Commits

Author SHA1 Message Date
github-actions[bot]
2920d5fe65 release: v2.0.4 2025-12-15 00:06:49 +00:00
YeonGyu-Kim
7fd52e27ce refactor(non-interactive-env): use args.env instead of command prepending
🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-15 08:54:33 +09:00
YeonGyu-Kim
08481c046f refactor(non-interactive-env): remove regex-based TUI blocking
Keep only environment variable configuration and stdin redirection.

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-15 08:49:19 +09:00
YeonGyu-Kim
192e8adf18 refactor(hooks): rename interactive-bash-blocker to non-interactive-env
- Replace regex-based command blocking with environment configuration
- Add cross-platform null device support (NUL for Windows, /dev/null for Unix)
- Wrap all bash commands with non-interactive environment variables
- Only block TUI programs that require full PTY
- Update schema, README docs, and all imports/exports

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-15 08:49:19 +09:00
Junho Yeo
5dd4d97c94 fix(auto-update-checker): resolve unknown version display and improve JSONC parsing (#54) 2025-12-15 08:39:21 +09:00
YeonGyu-Kim
b1abb7999b refactor(interactive-bash-blocker): replace regex blocking with environment configuration
Instead of blocking commands via regex pattern matching (which caused false
positives like 'startup', 'support'), now wraps all bash commands with:
- CI=true
- DEBIAN_FRONTEND=noninteractive
- GIT_TERMINAL_PROMPT=0
- stdin redirected to /dev/null

TUI programs (text editors, system monitors, etc.) are still blocked as they
require full PTY. Other interactive commands now fail naturally when stdin
is unavailable.

Closes #55 via alternative approach.
2025-12-15 08:26:16 +09:00
YeonGyu-Kim
8618d57d95 add missing schema components 2025-12-14 22:34:55 +09:00
YeonGyu-Kim
4b6b725f13 feat(hooks): Add interactive-bash-blocker hook
- Prevent interactive bash commands from being executed automatically
- Block commands in tool.execute.before hook
- Register in schema and main plugin initialization
2025-12-14 22:27:19 +09:00
YeonGyu-Kim
1aaa6e6ba2 fix(session-recovery): Add placeholder message for thinking-only messages
- Add findMessagesWithThinkingOnly() to detect orphan thinking messages
- Inject [user interrupted] placeholder for thinking-only messages
- Expand index offset handling from 2 to 3 attempts for better error recovery
- Use constant PLACEHOLDER_TEXT for consistency across recovery functions
2025-12-14 22:26:58 +09:00
github-actions[bot]
7cb8210e65 release: v2.0.3 2025-12-14 13:22:43 +00:00
YeonGyu-Kim
7e4b633bbd feat(agents): add OmO and OmO-Plan as primary agents, demote build/plan
- OmO: Primary orchestrator (Claude Opus 4.5)
- OmO-Plan: Inherits ALL settings from OpenCode's plan agent at runtime
  - description appended with '(OhMyOpenCode version)'
  - Configurable via oh-my-opencode.json agents.OmO-Plan
- build/plan: Demoted to subagent when OmO enabled
- Add plan and OmO-Plan to OverridableAgentNameSchema

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 22:17:41 +09:00
YeonGyu-Kim
f44555a021 feat(agents): make OmO default agent via build name hack
- Set build agent's display name to 'OmO' (keeps builtIn: true priority)
- Add OmO as subagent (actual execution target when selected)
- Remove explicit tools list from OmO agent (inherit all)
- Rename omo_agent.disable_build to omo_agent.disabled

This hack works around OpenCode's agent selection by key name.
TODO: Use config.default_agent when PR #5313 is released.

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 21:59:17 +09:00
YeonGyu-Kim
cccc7b7443 docs: fix incorrect default value for disable_build option
The documentation incorrectly stated that disable_build defaults to false,
but the actual code behavior defaults to true (Build agent hidden by default).

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 21:45:29 +09:00
YeonGyu-Kim
056b144174 fix(session-notification): gracefully handle notify-send failures on WSL
Add .catch() to notify-send command to prevent GDBus.Error logs
when org.freedesktop.Notifications service is unavailable in WSL environments.

Fixes #47

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 21:36:57 +09:00
YeonGyu-Kim
7fef07da2e fix(config): normalize agent names to support case-insensitive config
🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 21:35:49 +09:00
YeonGyu-Kim
62307d987c docs: document missing hooks and permission options in README
- Add 5 undocumented hooks: Startup Toast, Session Notification,
  Empty Task Response Detector, Grep/Tool Output Truncators
- Add Permission Options section with detailed table (edit, bash,
  webfetch, doom_loop, external_directory)
- Fix JSON schema: add 'build' to agents propertyNames

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 20:26:08 +09:00
YeonGyu-Kim
24f2ee0c92 docs: document OmO and build agent override capability in README
🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 19:52:22 +09:00
github-actions[bot]
e836ad18ce release: v2.0.2 2025-12-14 10:26:14 +00:00
Nguyen Quang Huy
0c237064b5 feat: add OmO agent to config schema for model override support (#46) 2025-12-14 19:16:25 +09:00
YeonGyu-Kim
58279897ae docs: update README and schema for v2.0.0 changes
- Add OmO agent description as the default agent
- Update librarian model from anthropic/claude-sonnet-4-5 to opencode/big-pickle
- Add omo_agent configuration section with disable_build option
- Update both English and Korean README files
- Add omo_agent to JSON schema

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 18:53:03 +09:00
github-actions[bot]
3e4d3fafd2 release: v2.0.1 2025-12-14 09:39:08 +00:00
YeonGyu-Kim
f1b9a38698 fix(auto-update-checker): resolve version detection failing with JSONC configs
- Add stripJsonComments() to handle // comments in opencode.json
- Add findPackageJsonUp() for robust package.json discovery
- Replace import.meta.dirname with fileURLToPath(import.meta.url) for ESM compatibility
- Fix version showing 'unknown' when config contains JSONC comments

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 18:37:54 +09:00
github-actions[bot]
d1f6f9d41f release: v2.0.0 2025-12-14 08:50:07 +00:00
YeonGyu-Kim
4b35bf795a feat(command): add easter egg command /omomomo
Adds a fun easter egg command that explains what Oh My OpenCode is about.
Shows project overview, features, and credits when invoked.

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 17:48:51 +09:00
YeonGyu-Kim
3adedca810 feat(auto-update-checker): improve local dev version display
- Add getLocalDevPath() and getLocalDevVersion() functions
- Improve getCachedVersion() with fallback to bundled package.json
- Display correct version in startup toast for local dev mode

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 17:48:41 +09:00
YeonGyu-Kim
3dea568007 Update AGENTS.md 2025-12-14 17:18:09 +09:00
YeonGyu-Kim
00b938d20d docs: add missing features to README and Schema
- Add hooks documentation
- Add grep_app MCP documentation
- Add multimodal-looker agent documentation

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 17:17:02 +09:00
YeonGyu-Kim
35d53cc74a feat: add OmO config with build agent hiding and startup toast
- Add configurable build agent hiding (omo_agent.disable_build)
- Add startup-toast hook to show version on OpenCode startup
- Fix auto-update-checker to respect version pinning

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 17:16:52 +09:00
YeonGyu-Kim
9a1a22d1c5 chore(agents): update Librarian model to big-pickle (glm-4.6)
🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 17:16:42 +09:00
YeonGyu-Kim
96088381e2 feat(agents): add OmO orchestrator agent
- Add OmO agent: powerful AI orchestrator for complex task delegation
- Implements parallel background agent execution and todo-driven workflows
- Emphasizes aggressive subagent delegation with 7-section prompt structure

Co-authored-by: huynguyen03dev <huynguyen03dev@users.noreply.github.com>
🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 17:16:32 +09:00
YeonGyu-Kim
c2d6e03b92 refactor(agents): rewrite Oracle agent prompt
🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 17:16:00 +09:00
github-actions[bot]
7f27fbc890 release: v1.1.9 2025-12-14 05:05:19 +00:00
YeonGyu-Kim
2806c64675 refactor(grep): replace glob dependency with fs.readdirSync
- Add findFileRecursive function using native Node.js fs API
- Remove glob package from dependencies
- Add unit tests for findFileRecursive

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 14:00:49 +09:00
YeonGyu-Kim
ed76c502c3 feat(background-agent): restrict tool access in subagent execution to prevent recursive calls
- Disable 'task' and 'call_omo_agent' tools in BackgroundManager
- Disable recursive background operation tools in call_omo_agent sync execution
- Prevents agents from spawning background tasks or calling themselves

🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
2025-12-14 14:00:28 +09:00
33 changed files with 2357 additions and 380 deletions

View File

@@ -0,0 +1,37 @@
---
description: Easter egg command - about oh-my-opencode
---
<command-instruction>
You found an easter egg! 🥚✨
Print the following message to the user EXACTLY as written (in a friendly, celebratory tone):
---
# 🎉 oMoMoMoMoMo···
**You found the easter egg!** 🥚✨
## What is Oh My OpenCode?
**Oh My OpenCode** is a powerful OpenCode plugin that transforms your AI agent into a full development team:
- 🤖 **Multi-Agent Orchestration**: Oracle (GPT-5.2), Librarian (Claude), Explore (Grok), Frontend Engineer (Gemini), and more
- 🔧 **LSP Tools**: Full IDE capabilities for your agents - hover, goto definition, find references, rename, code actions
- 🔍 **AST-Grep**: Structural code search and replace across 25 languages
- 📚 **Built-in MCPs**: Context7 for docs, Exa for web search, grep.app for GitHub code search
- 🔄 **Background Agents**: Run multiple agents in parallel like a real dev team
- 🎯 **Claude Code Compatibility**: Your existing Claude Code config just works
## Who Made This?
Created with ❤️ by **[code-yeongyu](https://github.com/code-yeongyu)**
🔗 **GitHub**: https://github.com/code-yeongyu/oh-my-opencode
---
*Enjoy coding on steroids!* 🚀
</command-instruction>

111
AGENTS.md
View File

@@ -1,76 +1,88 @@
# PROJECT KNOWLEDGE BASE
**Generated:** 2025-12-05T01:16:20+09:00
**Commit:** 6c9a2ee
**Generated:** 2025-12-14T17:16:30+09:00
**Commit:** 7f27fbc
**Branch:** master
## OVERVIEW
OpenCode plugin distribution implementing Claude Code/AmpCode features. Provides multi-model agent orchestration, LSP tools, AST-Grep search, and safe-grep utilities.
OpenCode plugin implementing Claude Code/AmpCode features. Multi-model agent orchestration (GPT-5.2, Claude, Gemini, Grok), LSP tools (11), AST-Grep search, MCP integrations (context7, websearch_exa, grep_app). "oh-my-zsh" for OpenCode.
## STRUCTURE
```
oh-my-opencode/
├── src/
│ ├── agents/ # AI agent definitions (oracle, librarian, explore, etc.)
│ ├── hooks/ # Plugin lifecycle hooks
│ ├── tools/ # LSP, AST-Grep, Safe-Grep tool implementations
│ ├── lsp/ # 11 LSP tools (hover, definition, references, etc.)
│ ├── ast-grep/ # AST-aware code search
│ └── safe-grep/ # Safe grep with limits
── features/ # Terminal features
├── dist/ # Build output (bun + tsc declarations)
└── test-rule.yml # AST-Grep test rules
│ ├── agents/ # AI agents (OmO, oracle, librarian, explore, frontend, document-writer, multimodal-looker)
│ ├── hooks/ # 19 lifecycle hooks (comment-checker, rules-injector, keyword-detector, etc.)
│ ├── tools/ # LSP (11), AST-Grep, Grep, background-task, glob, look-at, skill, slashcommand
│ ├── mcp/ # MCP servers (context7, websearch_exa, grep_app)
│ ├── features/ # Terminal features, Claude Code loaders (agent, command, skill, mcp, session-state)
├── config/ # Zod schema, TypeScript types
── auth/ # Google Antigravity OAuth
│ ├── shared/ # Utilities (deep-merge, pattern-matcher, logger, etc.)
│ └── index.ts # Main plugin entry (OhMyOpenCodePlugin)
├── script/ # build-schema.ts, publish.ts
├── assets/ # JSON schema
└── dist/ # Build output (ESM + .d.ts)
```
## WHERE TO LOOK
| Task | Location | Notes |
|------|----------|-------|
| Add new agent | `src/agents/` | Export from index.ts |
| Add new hook | `src/hooks/` | Export from index.ts |
| Add new tool | `src/tools/` | Follow lsp/ pattern: index, types, tools, utils |
| Modify LSP behavior | `src/tools/lsp/` | client.ts for connection logic |
| AST-Grep patterns | `src/tools/ast-grep/` | napi.ts for @ast-grep/napi |
| Terminal features | `src/features/terminal/` | title.ts |
| Google Antigravity auth | `src/auth/antigravity/` | OAuth plugin for Google models |
| Add new agent | `src/agents/` | Create .ts file, add to builtinAgents in index.ts, update types.ts |
| Add new hook | `src/hooks/` | Create dir with createXXXHook(), export from index.ts |
| Add new tool | `src/tools/` | Dir with index/types/constants/tools.ts, add to builtinTools |
| Add MCP server | `src/mcp/` | Create config, add to index.ts |
| Modify LSP behavior | `src/tools/lsp/` | client.ts for connection, tools.ts for handlers |
| AST-Grep patterns | `src/tools/ast-grep/` | napi.ts for @ast-grep/napi binding |
| Google OAuth | `src/auth/antigravity/` | OAuth plugin for Google models |
| Config schema | `src/config/schema.ts` | Zod schema, run `bun run build:schema` after changes |
| Claude Code compat | `src/features/claude-code-*-loader/` | Command, skill, agent, mcp loaders |
## CONVENTIONS
- **Package manager**: Bun only (not npm/yarn)
- **Build**: Dual output - `bun build` + `tsc --emitDeclarationOnly`
- **Package manager**: Bun only (`bun run`, `bun build`, `bunx`)
- **Types**: bun-types (not @types/node)
- **Build**: Dual output - `bun build` (ESM) + `tsc --emitDeclarationOnly`
- **Exports**: Barrel pattern - `export * from "./module"` in index.ts
- **Module structure**: index.ts, types.ts, constants.ts, utils.ts, tools.ts per tool
- **Directory naming**: kebab-case (`ast-grep/`, `claude-code-hooks/`)
- **Tool structure**: Each tool has index.ts, types.ts, constants.ts, tools.ts, utils.ts
- **Hook pattern**: `createXXXHook(input: PluginInput)` returning event handlers
## ANTI-PATTERNS (THIS PROJECT)
- **Bash file operations**: Never use mkdir/touch/rm/cp/mv for file creation
- **npm/yarn**: Use bun exclusively
- **@types/node**: Use bun-types instead
- **@types/node**: Use bun-types
- **Bash file operations**: Never use mkdir/touch/rm/cp/mv for file creation in code
- **Generic AI aesthetics**: No Space Grotesk, avoid typical AI-generated UI patterns
- **Direct bun publish**: Use GitHub Actions workflow_dispatch only (OIDC provenance)
- **Local version bump**: Version managed by CI workflow, never modify locally
- **Rush completion**: Never mark tasks complete without verification
- **Interrupting work**: Complete tasks fully before stopping
## UNIQUE STYLES
- **Directory naming**: kebab-case (`ast-grep/`, `safe-grep/`)
- **Tool organization**: Each tool has cli.ts, constants.ts, index.ts, napi.ts/tools.ts, types.ts, utils.ts
- **Platform handling**: Union type `"darwin" | "linux" | "win32" | "unsupported"`
- **Error handling**: Consistent try/catch with async/await
- **Optional props**: Extensive use of `?` for optional interface properties
- **Flexible objects**: `Record<string, unknown>` for dynamic configs
- **Error handling**: Consistent try/catch with async/await in all tools
- **Agent tools restriction**: Use `tools: { include: [...] }` or `tools: { exclude: [...] }`
- **Temperature**: Most agents use `0.1` for consistency
- **Hook naming**: `createXXXHook` function naming convention
## AGENT MODELS
| Agent | Model | Purpose |
|-------|-------|---------|
| oracle | GPT-5.2 | Code review, strategic planning |
| librarian | Claude Haiku | Documentation, example lookup |
| explore | Grok | File/codebase exploration |
| frontend-ui-ux-engineer | Gemini | UI generation |
| document-writer | Gemini | Documentation writing |
| OmO | anthropic/claude-opus-4-5 | Primary orchestrator, team leader |
| oracle | openai/gpt-5.2 | Strategic advisor, code review, architecture |
| librarian | opencode/big-pickle | Multi-repo analysis, docs lookup, GitHub examples |
| explore | opencode/grok-code | Fast codebase exploration, file patterns |
| frontend-ui-ux-engineer | google/gemini-3-pro-preview | UI generation, design-focused |
| document-writer | google/gemini-3-pro-preview | Technical documentation |
| multimodal-looker | google/gemini-2.5-flash | PDF/image/diagram analysis |
## COMMANDS
@@ -78,38 +90,43 @@ oh-my-opencode/
# Type check
bun run typecheck
# Build
# Build (ESM + declarations + schema)
bun run build
# Clean + Build
bun run rebuild
# Build schema only
bun run build:schema
```
## DEPLOYMENT
**배포는 GitHub Actions workflow_dispatch로만 진행**
**GitHub Actions workflow_dispatch only**
1. package.json 버전은 수정하지 않음 (워크플로우에서 자동 bump)
2. 변경사항 커밋 & 푸시
3. GitHub Actions에서 `publish` 워크플로우 수동 실행
- `bump`: major | minor | patch 선택
- `version`: (선택) 특정 버전 지정 가능
1. package.json version NOT modified locally (auto-bumped by workflow)
2. Commit & push changes
3. Trigger `publish` workflow manually:
- `bump`: major | minor | patch
- `version`: (optional) specific version override
```bash
# 워크플로우 실행 (CLI)
# Trigger via CLI
gh workflow run publish -f bump=patch
# 워크플로우 상태 확인
# Check status
gh run list --workflow=publish
```
**주의사항**:
- `bun publish` 직접 실행 금지 (OIDC provenance 문제)
- 로컬에서 버전 bump 하지 말 것
**Critical**:
- Never run `bun publish` directly (OIDC provenance issue)
- Never bump version locally
## NOTES
- **No tests**: Test framework not configured
- **CI/CD**: GitHub Actions publish workflow 사용
- **Version requirement**: OpenCode >= 1.0.132 (earlier versions have config bugs)
- **Multi-language docs**: README.md, README.en.md, README.ko.md
- **OpenCode version**: Requires >= 1.0.132 (earlier versions have config bugs)
- **Multi-language docs**: README.md (EN), README.ko.md (KO)
- **Config locations**: `~/.config/opencode/oh-my-opencode.json` (user) or `.opencode/oh-my-opencode.json` (project)
- **Schema autocomplete**: Add `$schema` field in config for IDE support
- **Trusted dependencies**: @ast-grep/cli, @ast-grep/napi, @code-yeongyu/comment-checker

View File

@@ -261,8 +261,9 @@ opencode auth login
### Agents: 당신의 새로운 팀원들
- **OmO** (`anthropic/claude-opus-4-5`): **기본 에이전트입니다.** OpenCode를 위한 강력한 AI 오케스트레이터입니다. 전문 서브에이전트를 활용하여 복잡한 작업을 계획, 위임, 실행합니다. 백그라운드 태스크 위임과 todo 기반 워크플로우를 강조합니다. 최대 추론 능력을 위해 Claude Opus 4.5와 확장된 사고(32k 버짓)를 사용합니다.
- **oracle** (`openai/gpt-5.2`): 아키텍처, 코드 리뷰, 전략 수립을 위한 전문가 조언자. GPT-5.2의 뛰어난 논리적 추론과 깊은 분석 능력을 활용합니다. AmpCode 에서 영감을 받았습니다.
- **librarian** (`anthropic/claude-sonnet-4-5`): 멀티 레포 분석, 문서 조회, 구현 예제 담당. Claude Sonnet 4.5 의 뛰어난 지능, 훌륭한 도구 호출 능력을 활용합니다. AmpCode 에서 영감을 받았습니다.
- **librarian** (`opencode/big-pickle`): 멀티 레포 분석, 문서 조회, 구현 예제 담당. OpenCode Zen을 통해 GLM-4.6(big-pickle)을 사용합니다—무료이고 빠르며 문서 조사에 탁월합니다. AmpCode 에서 영감을 받았습니다.
- **explore** (`opencode/grok-code`): 빠른 코드베이스 탐색, 파일 패턴 매칭. Claude Code는 Haiku를 쓰지만, 우리는 Grok을 씁니다. 현재 무료이고, 극도로 빠르며, 파일 탐색 작업에 충분한 지능을 갖췄기 때문입니다. Claude Code 에서 영감을 받았습니다.
- **frontend-ui-ux-engineer** (`google/gemini-3-pro-preview`): 개발자로 전향한 디자이너라는 설정을 갖고 있습니다. 멋진 UI를 만듭니다. 아름답고 창의적인 UI 코드를 생성하는 데 탁월한 Gemini를 사용합니다.
- **document-writer** (`google/gemini-3-pro-preview`): 기술 문서 전문가라는 설정을 갖고 있습니다. Gemini 는 문학가입니다. 글을 기가막히게 씁니다.
@@ -452,13 +453,25 @@ Oh My OpenCode는 다음 위치의 훅을 읽고 실행합니다:
에이전트들이 행복해지면, 당신이 제일 행복해집니다, 그렇지만 저는 당신도 돕고싶습니다.
- **Ultrawork Mode**: 사용자가 "ultrawork" 또는 "ulw" 키워드를 입력하면 자동으로 에이전트 오케스트레이션 가이드를 주입합니다. 메인 에이전트가 모든 가용한 전문 에이전트(탐색, 사서, 계획, UI)를 백그라운드 작업을 통해 병렬로 최대한 활용하도록 강제하며, 엄격한 TODO 추적 및 검증 프로토콜을 따르게 합니다. 그냥 ultrawork 하세요. 말한 모든 기능이 최대로 활용되도록 에이전트가 최적화됩니다.
- **Keyword Detector**: 프롬프트의 키워드를 자동 감지하여 전문 모드를 활성화합니다:
- `ultrawork` / `ulw`: 병렬 에이전트 오케스트레이션으로 최대 성능 모드
- `search` / `find` / `찾아` / `検索`: 병렬 explore/librarian 에이전트로 검색 극대화
- `analyze` / `investigate` / `분석` / `調査`: 다단계 전문가 상담으로 심층 분석 모드
- **Todo Continuation Enforcer**: 에이전트가 멈추기 전 모든 TODO 항목을 완료하도록 강제합니다. LLM의 고질적인 "중도 포기" 문제를 방지합니다.
- **Comment Checker**: 학습 과정의 습관 때문일까요. LLM 들은 주석이 너무 많습니다. LLM 들이 쓸모없는 주석을 작성하지 않도록 상기시킵니다. BDD 패턴, 지시어, 독스트링 등 유효한 주석은 똑똑하게 제외하고, 그렇지 않는 주석들에 대해 해명을 요구하며 깔끔한 코드를 구성하게 합니다.
- **Think Mode**: 확장된 사고(Extended Thinking)가 필요한 상황을 자동으로 감지하고 모드를 전환합니다. 사용자가 깊은 사고를 요청하는 표현(예: "think deeply", "ultrathink")을 감지하면, 추론 능력을 극대화하도록 모델 설정을 동적으로 조정합니다.
- **Context Window Monitor**: [컨텍스트 윈도우 불안 관리](https://agentic-patterns.com/patterns/context-window-anxiety-management/) 패턴을 구현합니다.
- 사용량이 70%를 넘으면 에이전트에게 아직 토큰이 충분하다고 상기시켜, 급하게 불완전한 작업을 하는 것을 완화합니다.
- OpenCode 에서 누락되거나 부족하다고 느끼는 안정성 보강 기능들이 내장되어있습니다. 클로드 코드에서의 안정적인 경험을 그대로 가져갈 수 있습니다. 돌다가 세션이 망가지지 않습니다. 망가져도 복구됩니다.
- **Agent Usage Reminder**: 검색 도구를 직접 호출할 때, 백그라운드 작업을 통한 전문 에이전트 활용을 권장하는 리마인더를 표시합니다.
- **Anthropic Auto Compact**: Claude 모델이 토큰 제한에 도달하면 자동으로 세션을 요약하고 압축합니다. 수동 개입 없이 작업을 계속할 수 있습니다.
- **Session Recovery**: 세션 에러(누락된 도구 결과, thinking 블록 문제, 빈 메시지 등)에서 자동 복구합니다. 돌다가 세션이 망가지지 않습니다. 망가져도 복구됩니다.
- **Auto Update Checker**: oh-my-opencode의 새 버전이 출시되면 알림을 표시합니다.
- **Startup Toast**: OhMyOpenCode 로드 시 환영 메시지를 표시합니다. 세션을 제대로 시작하기 위한 작은 "oMoMoMo".
- **Background Notification**: 백그라운드 에이전트 작업이 완료되면 알림을 받습니다.
- **Session Notification**: 에이전트가 대기 상태가 되면 OS 알림을 보냅니다. macOS, Linux, Windows에서 작동—에이전트가 입력을 기다릴 때 놓치지 마세요.
- **Empty Task Response Detector**: Task 도구가 빈 응답을 반환하면 감지합니다. 이미 빈 응답이 왔는데 무한정 기다리는 상황을 방지합니다.
- **Grep Output Truncator**: grep은 산더미 같은 텍스트를 반환할 수 있습니다. 남은 컨텍스트 윈도우에 따라 동적으로 출력을 축소합니다—50% 여유 공간 유지, 최대 50k 토큰.
- **Tool Output Truncator**: 같은 아이디어, 더 넓은 범위. Grep, Glob, LSP 도구, AST-grep의 출력을 축소합니다. 한 번의 장황한 검색이 전체 컨텍스트를 잡아먹는 것을 방지합니다.
## 설정
@@ -508,6 +521,34 @@ Google Gemini 모델을 위한 내장 Antigravity OAuth를 활성화합니다:
각 에이전트에서 지원하는 옵션: `model`, `temperature`, `top_p`, `prompt`, `tools`, `disable`, `description`, `mode`, `color`, `permission`.
`OmO` (메인 오케스트레이터)와 `build` (기본 에이전트)도 동일한 옵션으로 설정을 오버라이드할 수 있습니다.
#### Permission 옵션
에이전트가 할 수 있는 작업을 세밀하게 제어합니다:
```json
{
"agents": {
"explore": {
"permission": {
"edit": "deny",
"bash": "ask",
"webfetch": "allow"
}
}
}
}
```
| Permission | 설명 | 값 |
|------------|------|-----|
| `edit` | 파일 편집 권한 | `ask` / `allow` / `deny` |
| `bash` | Bash 명령 실행 권한 | `ask` / `allow` / `deny` 또는 명령별: `{ "git": "allow", "rm": "deny" }` |
| `webfetch` | 웹 요청 권한 | `ask` / `allow` / `deny` |
| `doom_loop` | 무한 루프 감지 오버라이드 허용 | `ask` / `allow` / `deny` |
| `external_directory` | 프로젝트 루트 외부 파일 접근 | `ask` / `allow` / `deny` |
또는 ~/.config/opencode/oh-my-opencode.json 혹은 .opencode/oh-my-opencode.json 의 `disabled_agents` 를 사용하여 비활성화할 수 있습니다:
```json
@@ -516,7 +557,58 @@ Google Gemini 모델을 위한 내장 Antigravity OAuth를 활성화합니다:
}
```
사용 가능한 에이전트: `oracle`, `librarian`, `explore`, `frontend-ui-ux-engineer`, `document-writer`
사용 가능한 에이전트: `oracle`, `librarian`, `explore`, `frontend-ui-ux-engineer`, `document-writer`, `multimodal-looker`
### OmO Agent
활성화 시(기본값), OmO는 두 개의 primary 에이전트를 추가하고 내장 에이전트를 subagent로 강등합니다:
- **OmO**: Primary 오케스트레이터 에이전트 (Claude Opus 4.5)
- **OmO-Plan**: OpenCode plan 에이전트의 모든 설정을 런타임에 상속 (description에 "OhMyOpenCode version" 추가)
- **build**: subagent로 강등
- **plan**: subagent로 강등
OmO를 비활성화하고 원래 build/plan 에이전트를 복원하려면:
```json
{
"omo_agent": {
"disabled": true
}
}
```
다른 에이전트처럼 OmO와 OmO-Plan도 커스터마이징할 수 있습니다:
```json
{
"agents": {
"OmO": {
"model": "anthropic/claude-sonnet-4",
"temperature": 0.3
},
"OmO-Plan": {
"model": "openai/gpt-5.2"
}
}
}
```
| 옵션 | 기본값 | 설명 |
|------|--------|------|
| `disabled` | `false` | `true`면 OmO 에이전트를 비활성화하고 원래 build/plan을 primary로 복원합니다. `false`(기본값)면 OmO와 OmO-Plan이 primary 에이전트가 됩니다. |
### Hooks
`~/.config/opencode/oh-my-opencode.json` 또는 `.opencode/oh-my-opencode.json`의 `disabled_hooks`를 통해 특정 내장 훅을 비활성화할 수 있습니다:
```json
{
"disabled_hooks": ["comment-checker", "agent-usage-reminder"]
}
```
사용 가능한 훅: `todo-continuation-enforcer`, `context-window-monitor`, `session-recovery`, `session-notification`, `comment-checker`, `grep-output-truncator`, `tool-output-truncator`, `directory-agents-injector`, `directory-readme-injector`, `empty-task-response-detector`, `think-mode`, `anthropic-auto-compact`, `rules-injector`, `background-notification`, `auto-update-checker`, `startup-toast`, `keyword-detector`, `agent-usage-reminder`, `non-interactive-env`
### MCPs

100
README.md
View File

@@ -262,8 +262,9 @@ The plugin works perfectly with defaults. Aside from the recommended `google_aut
### Agents: Your Teammates
- **OmO** (`anthropic/claude-opus-4-5`): **The default agent.** A powerful AI orchestrator for OpenCode. Plans, delegates, and executes complex tasks using specialized subagents with aggressive parallel execution. Emphasizes background task delegation and todo-driven workflow. Uses Claude Opus 4.5 with extended thinking (32k budget) for maximum reasoning capability.
- **oracle** (`openai/gpt-5.2`): Architecture, code review, strategy. Uses GPT-5.2 for its stellar logical reasoning and deep analysis. Inspired by AmpCode.
- **librarian** (`anthropic/claude-sonnet-4-5`): Multi-repo analysis, doc lookup, implementation examples. Claude Sonnet 4 is fast, smart, great at tool calls, and excellent for documentation research. Inspired by AmpCode.
- **librarian** (`opencode/big-pickle`): Multi-repo analysis, doc lookup, implementation examples. Uses GLM-4.6 (big-pickle) via OpenCode Zen—free, fast, and excellent for documentation research. Inspired by AmpCode.
- **explore** (`opencode/grok-code`): Fast codebase exploration and pattern matching. Claude Code uses Haiku; we use Grok—it's free, blazing fast, and plenty smart for file traversal. Inspired by Claude Code.
- **frontend-ui-ux-engineer** (`google/gemini-3-pro-preview`): A designer turned developer. Builds gorgeous UIs. Gemini excels at creative, beautiful UI code.
- **document-writer** (`google/gemini-3-pro-preview`): Technical writing expert. Gemini is a wordsmith—writes prose that flows.
@@ -453,13 +454,25 @@ All toggles default to `true` (enabled). Omit the `claude_code` object for full
When agents thrive, you thrive. But I want to help you directly too.
- **Ultrawork Mode**: Type "ultrawork" or "ulw" and agent orchestration kicks in. Forces the main agent to max out all available specialists (explore, librarian, plan, UI) via background tasks in parallel, with strict TODO tracking and verification. Just ultrawork. Everything fires at full capacity.
- **Keyword Detector**: Automatically detects keywords in your prompts and activates specialized modes:
- `ultrawork` / `ulw`: Maximum performance mode with parallel agent orchestration
- `search` / `find` / `찾아` / `検索`: Maximized search effort with parallel explore and librarian agents
- `analyze` / `investigate` / `분석` / `調査`: Deep analysis mode with multi-phase expert consultation
- **Todo Continuation Enforcer**: Makes agents finish all TODOs before stopping. Kills the chronic LLM habit of quitting halfway.
- **Comment Checker**: LLMs love comments. Too many comments. This reminds them to cut the noise. Smartly ignores valid patterns (BDD, directives, docstrings) and demands justification for the rest. Clean code wins.
- **Think Mode**: Auto-detects when extended thinking is needed and switches modes. Catches phrases like "think deeply" or "ultrathink" and dynamically adjusts model settings for maximum reasoning.
- **Context Window Monitor**: Implements [Context Window Anxiety Management](https://agentic-patterns.com/patterns/context-window-anxiety-management/).
- At 70%+ usage, reminds agents there's still headroom—prevents rushed, sloppy work.
- Stability features that felt missing in OpenCode are built in. The Claude Code experience, transplanted. Sessions don't crash mid-run. Even if they do, they recover.
- **Agent Usage Reminder**: When you call search tools directly, reminds you to leverage specialized agents via background tasks for better results.
- **Anthropic Auto Compact**: When Claude models hit token limits, automatically summarizes and compacts the session—no manual intervention needed.
- **Session Recovery**: Automatically recovers from session errors (missing tool results, thinking block issues, empty messages). Sessions don't crash mid-run. Even if they do, they recover.
- **Auto Update Checker**: Notifies you when a new version of oh-my-opencode is available.
- **Startup Toast**: Shows a welcome message when OhMyOpenCode loads. A little "oMoMoMo" to start your session right.
- **Background Notification**: Get notified when background agent tasks complete.
- **Session Notification**: Sends OS notifications when agents go idle. Works on macOS, Linux, and Windows—never miss when your agent needs input.
- **Empty Task Response Detector**: Catches when Task tool returns nothing. Warns you about potential agent failures so you don't wait forever for a response that already came back empty.
- **Grep Output Truncator**: Grep can return mountains of text. This dynamically truncates output based on your remaining context window—keeps 50% headroom, caps at 50k tokens.
- **Tool Output Truncator**: Same idea, broader scope. Truncates output from Grep, Glob, LSP tools, and AST-grep. Prevents one verbose search from eating your entire context.
## Configuration
@@ -509,6 +522,34 @@ Override built-in agent settings:
Each agent supports: `model`, `temperature`, `top_p`, `prompt`, `tools`, `disable`, `description`, `mode`, `color`, `permission`.
You can also override settings for `OmO` (the main orchestrator) and `build` (the default agent) using the same options.
#### Permission Options
Fine-grained control over what agents can do:
```json
{
"agents": {
"explore": {
"permission": {
"edit": "deny",
"bash": "ask",
"webfetch": "allow"
}
}
}
}
```
| Permission | Description | Values |
|------------|-------------|--------|
| `edit` | File editing permission | `ask` / `allow` / `deny` |
| `bash` | Bash command execution | `ask` / `allow` / `deny` or per-command: `{ "git": "allow", "rm": "deny" }` |
| `webfetch` | Web request permission | `ask` / `allow` / `deny` |
| `doom_loop` | Allow infinite loop detection override | `ask` / `allow` / `deny` |
| `external_directory` | Access files outside project root | `ask` / `allow` / `deny` |
Or disable via `disabled_agents` in `~/.config/opencode/oh-my-opencode.json` or `.opencode/oh-my-opencode.json`:
```json
@@ -517,7 +558,58 @@ Or disable via `disabled_agents` in `~/.config/opencode/oh-my-opencode.json` or
}
```
Available agents: `oracle`, `librarian`, `explore`, `frontend-ui-ux-engineer`, `document-writer`
Available agents: `oracle`, `librarian`, `explore`, `frontend-ui-ux-engineer`, `document-writer`, `multimodal-looker`
### OmO Agent
When enabled (default), OmO adds two primary agents and demotes the built-in agents to subagents:
- **OmO**: Primary orchestrator agent (Claude Opus 4.5)
- **OmO-Plan**: Inherits all settings from OpenCode's plan agent at runtime (description appended with "OhMyOpenCode version")
- **build**: Demoted to subagent
- **plan**: Demoted to subagent
To disable OmO and restore the original build/plan agents:
```json
{
"omo_agent": {
"disabled": true
}
}
```
You can also customize OmO and OmO-Plan like other agents:
```json
{
"agents": {
"OmO": {
"model": "anthropic/claude-sonnet-4",
"temperature": 0.3
},
"OmO-Plan": {
"model": "openai/gpt-5.2"
}
}
}
```
| Option | Default | Description |
|--------|---------|-------------|
| `disabled` | `false` | When `true`, disables OmO agents and restores original build/plan as primary. When `false` (default), OmO and OmO-Plan become primary agents. |
### Hooks
Disable specific built-in hooks via `disabled_hooks` in `~/.config/opencode/oh-my-opencode.json` or `.opencode/oh-my-opencode.json`:
```json
{
"disabled_hooks": ["comment-checker", "agent-usage-reminder"]
}
```
Available hooks: `todo-continuation-enforcer`, `context-window-monitor`, `session-recovery`, `session-notification`, `comment-checker`, `grep-output-truncator`, `tool-output-truncator`, `directory-agents-injector`, `directory-readme-injector`, `empty-task-response-detector`, `think-mode`, `anthropic-auto-compact`, `rules-injector`, `background-notification`, `auto-update-checker`, `startup-toast`, `keyword-detector`, `agent-usage-reminder`, `non-interactive-env`
### MCPs

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,6 @@
"@code-yeongyu/comment-checker": "^0.5.0",
"@openauthjs/openauth": "^0.4.3",
"@opencode-ai/plugin": "^1.0.150",
"glob": "^13.0.0",
"hono": "^4.10.4",
"picomatch": "^4.0.2",
"xdg-basedir": "^5.1.0",
@@ -71,10 +70,6 @@
"@code-yeongyu/comment-checker": ["@code-yeongyu/comment-checker@0.5.0", "", { "os": [ "linux", "win32", "darwin", ], "cpu": [ "x64", "arm64", ], "bin": { "comment-checker": "bin/comment-checker" } }, "sha512-rKD2qQnTVUacsVQtpu3I5Sxi09X/XpOwS9fcmbUv1yfUL6llraaPuLmmxMBMRcmm7Zu31yEPVKCeUkVODfRL1g=="],
"@isaacs/balanced-match": ["@isaacs/balanced-match@4.0.1", "", {}, "sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ=="],
"@isaacs/brace-expansion": ["@isaacs/brace-expansion@5.0.0", "", { "dependencies": { "@isaacs/balanced-match": "^4.0.1" } }, "sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA=="],
"@openauthjs/openauth": ["@openauthjs/openauth@0.4.3", "", { "dependencies": { "@standard-schema/spec": "1.0.0-beta.3", "aws4fetch": "1.0.20", "jose": "5.9.6" }, "peerDependencies": { "arctic": "^2.2.2", "hono": "^4.0.0" } }, "sha512-RlnjqvHzqcbFVymEwhlUEuac4utA5h4nhSK/i2szZuQmxTIqbGUxZ+nM+avM+VV4Ing+/ZaNLKILoXS3yrkOOw=="],
"@opencode-ai/plugin": ["@opencode-ai/plugin@1.0.150", "", { "dependencies": { "@opencode-ai/sdk": "1.0.150", "zod": "4.1.8" } }, "sha512-XmY3yydk120GBv2KeLxSZlElFx4Zx9TYLa3bS9X1TxXot42UeoMLEi3Xa46yboYnWwp4bC9Fu+Gd1E7hypG8Jw=="],
@@ -129,22 +124,12 @@
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"glob": ["glob@13.0.0", "", { "dependencies": { "minimatch": "^10.1.1", "minipass": "^7.1.2", "path-scurry": "^2.0.0" } }, "sha512-tvZgpqk6fz4BaNZ66ZsRaZnbHvP/jG3uKJvAZOwEVUL4RTA5nJeeLYfyN9/VA8NX/V3IBG+hkeuGpKjvELkVhA=="],
"hono": ["hono@4.10.8", "", {}, "sha512-DDT0A0r6wzhe8zCGoYOmMeuGu3dyTAE40HHjwUsWFTEy5WxK1x2WDSsBPlEXgPbRIFY6miDualuUDbasPogIww=="],
"jose": ["jose@5.9.6", "", {}, "sha512-AMlnetc9+CV9asI19zHmrgS/WYsWUwCn2R7RzlbJWD7F9eWYUTGyBmU9o6PxngtLGOiDGPRu+Uc4fhKzbpteZQ=="],
"lru-cache": ["lru-cache@11.2.4", "", {}, "sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg=="],
"minimatch": ["minimatch@10.1.1", "", { "dependencies": { "@isaacs/brace-expansion": "^5.0.0" } }, "sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ=="],
"minipass": ["minipass@7.1.2", "", {}, "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw=="],
"oh-my-opencode": ["oh-my-opencode@0.1.30", "", { "dependencies": { "@ast-grep/cli": "^0.40.0", "@ast-grep/napi": "^0.40.0", "@code-yeongyu/comment-checker": "^0.4.1", "@opencode-ai/plugin": "^1.0.7", "xdg-basedir": "^5.1.0", "zod": "^4.1.8" }, "peerDependencies": { "bun": ">=1.0.0" } }, "sha512-pXGGgL/7Jcz3yuGJJTI72BKern2egwfRz2LQZTBq+jl+pNCybOvGvXtFmR+WGlF8O3ZjL1wIHypBbIVuHOBzxg=="],
"path-scurry": ["path-scurry@2.0.1", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-oWyT4gICAu+kaA7QWk/jvCHWarMKNs6pXOGWKDTr7cw4IGcUbW+PeTfbaQiLGheFRpjo6O9J0PmyMfQPjH71oA=="],
"picomatch": ["picomatch@4.0.3", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],

View File

@@ -1,6 +1,6 @@
{
"name": "oh-my-opencode",
"version": "1.1.8",
"version": "2.0.4",
"description": "OpenCode plugin - custom agents (oracle, librarian) and enhanced features",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@@ -51,7 +51,6 @@
"@code-yeongyu/comment-checker": "^0.5.0",
"@openauthjs/openauth": "^0.4.3",
"@opencode-ai/plugin": "^1.0.150",
"glob": "^13.0.0",
"hono": "^4.10.4",
"picomatch": "^4.0.2",
"xdg-basedir": "^5.1.0",

View File

@@ -1,4 +1,5 @@
import type { AgentConfig } from "@opencode-ai/sdk"
import { omoAgent } from "./omo"
import { oracleAgent } from "./oracle"
import { librarianAgent } from "./librarian"
import { exploreAgent } from "./explore"
@@ -7,6 +8,7 @@ import { documentWriterAgent } from "./document-writer"
import { multimodalLookerAgent } from "./multimodal-looker"
export const builtinAgents: Record<string, AgentConfig> = {
OmO: omoAgent,
oracle: oracleAgent,
librarian: librarianAgent,
explore: exploreAgent,
@@ -17,4 +19,3 @@ export const builtinAgents: Record<string, AgentConfig> = {
export * from "./types"
export { createBuiltinAgents } from "./utils"
export { BUILD_AGENT_PROMPT_EXTENSION } from "./build"

View File

@@ -4,7 +4,7 @@ export const librarianAgent: AgentConfig = {
description:
"Specialized codebase understanding agent for multi-repository analysis, searching remote codebases, retrieving official documentation, and finding implementation examples using GitHub CLI, Context7, and Web Search. MUST BE USED when users ask to look up code in remote repositories, explain library internals, or find usage examples in open source.",
mode: "subagent",
model: "anthropic/claude-sonnet-4-5",
model: "opencode/big-pickle",
temperature: 0.1,
tools: { write: false, edit: false, bash: true, read: true },
prompt: `# THE LIBRARIAN

371
src/agents/omo.ts Normal file
View File

@@ -0,0 +1,371 @@
import type { AgentConfig } from "@opencode-ai/sdk"
const OMO_SYSTEM_PROMPT = `You are OmO, a powerful AI orchestrator for OpenCode, introduced by OhMyOpenCode.
<Role>
Your mission: Complete software engineering tasks with excellence by orchestrating specialized agents and tools.
You are the TEAM LEAD. You work, delegate, verify, and deliver.
</Role>
<Intent_Gate>
## Phase 0 - Intent Classification (RUN ON EVERY MESSAGE)
Re-evaluate intent on EVERY new user message. Before ANY action, classify:
1. **EXPLORATION**: User wants to find/understand something
- Fire Explore + Librarian agents in parallel (3+ each)
- Do NOT edit files
- Provide evidence-based analysis grounded in actual code
2. **IMPLEMENTATION**: User wants to create/modify/fix code
- Create todos FIRST (obsessively detailed)
- MUST Fire async subagents (=Background Agents) (explore 3+ librarian 3+) in parallel to gather information
- Pass all Blocking Gates
- Edit → Verify → Mark complete → Repeat
- End with verification evidence
3. **ORCHESTRATION**: Complex multi-step task
- Break into detailed todos
- Delegate to specialized agents with 7-section prompts
- Coordinate and verify all results
If unclear, ask ONE clarifying question. NEVER guess intent.
After you have analyzed the intent, always delegate explore and librarian agents in parallel to gather information.
</Intent_Gate>
<Blocking_Gates>
## Mandatory Gates (BLOCKING - violation = STOP)
### GATE 1: Pre-Edit
- [BLOCKING] MUST read the file in THIS session before editing
- [BLOCKING] MUST understand existing code patterns/style
- [BLOCKING] NEVER speculate about code you haven't opened
### GATE 2: Pre-Delegation
- [BLOCKING] MUST use 7-section prompt structure
- [BLOCKING] MUST define clear deliverables
- [BLOCKING] Vague prompts = REJECTED
### GATE 3: Pre-Completion
- [BLOCKING] MUST have verification evidence (lsp_diagnostics, build, tests)
- [BLOCKING] MUST have all todos marked complete
- [BLOCKING] MUST address user's original request fully
### Single Source of Truth
- NEVER speculate about code you haven't opened
- NEVER assume file exists without checking
- If user references a file, READ it before responding
</Blocking_Gates>
<Agency>
You take initiative but maintain balance:
1. Do the right thing, including follow-up actions *until complete*
2. Don't surprise users with unexpected actions (if they ask how, answer first)
3. Don't add code explanation summaries unless requested
4. Don't be overly defensive—write aggressive, common-sense code
CRITICAL: If user asks to complete a task, NEVER ask whether to continue. ALWAYS iterate until done.
CRITICAL: There are no 'Optional' or 'Skippable' jobs. Complete everything.
</Agency>
<Todo_Management>
## Task Management (MANDATORY for 2+ steps)
Use todowrite and todoread ALWAYS for non-trivial tasks.
### Workflow:
1. User requests → Create todos immediately (obsessively specific)
2. Mark first item in_progress
3. Complete it → Gather evidence → Mark completed
4. Move to next item immediately
5. Repeat until ALL done
### Evidence Requirements:
| Action | Required Evidence |
|--------|-------------------|
| File edit | lsp_diagnostics clean |
| Build | Exit code 0 + summary |
| Test | Pass/fail count |
| Delegation | Agent confirmation |
NO evidence = NOT complete.
</Todo_Management>
<Delegation_Rules>
## Subagent Delegation
You MUST delegate to preserve context and increase speed.
### Specialized Agents
**Oracle** — \`task(subagent_type="oracle")\` or \`background_task(agent="oracle")\`
USE FREQUENTLY. Your most powerful advisor.
- **USE FOR:** Architecture, code review, debugging 3+ failures, second opinions
- **CONSULT WHEN:** Multi-file refactor, concurrency issues, performance, tradeoffs
- **SKIP WHEN:** Direct tool query <2 steps, trivial tasks
**Frontend Engineer** — \`task(subagent_type="frontend-ui-ux-engineer")\`
- **USE FOR:** UI/UX implementation, visual design, CSS, stunning interfaces
**Document Writer** — \`task(subagent_type="document-writer")\`
- **USE FOR:** README, API docs, user guides, architecture docs
**Explore** — \`background_task(agent="explore")\`
- **USE FOR:** Fast codebase exploration, pattern finding, structure understanding
- Specify: "quick", "medium", "very thorough"
**Librarian** — \`background_task(agent="librarian")\`
- **USE FOR:** External docs, GitHub examples, library internals
### 7-Section Prompt Structure (MANDATORY)
When delegating, ALWAYS use this structure. Vague prompts = agent goes rogue.
\`\`\`
TASK: Exactly what to do (be obsessively specific)
EXPECTED OUTCOME: Concrete deliverables
REQUIRED SKILLS: Which skills to invoke
REQUIRED TOOLS: Which tools to use
MUST DO: Exhaustive requirements (leave NOTHING implicit)
MUST NOT DO: Forbidden actions (anticipate rogue behavior)
CONTEXT: File paths, constraints, related info
\`\`\`
Example:
\`\`\`
Task("Fix auth bug", prompt="""
TASK: Fix JWT token expiration bug in auth service
EXPECTED OUTCOME:
- Token refresh works without logging out user
- All auth tests pass (pytest tests/auth/)
- No console errors in browser
REQUIRED SKILLS:
- python-programmer
REQUIRED TOOLS:
- context7: Look up JWT library docs
- grep: Search existing patterns
- ast_grep_search: Find token-related functions
MUST DO:
- Follow existing pattern in src/auth/token.py
- Use existing refreshToken() utility
- Add test case for edge case
MUST NOT DO:
- Do NOT modify unrelated files
- Do NOT refactor existing code
- Do NOT add new dependencies
CONTEXT:
- Bug in issue #123
- Files: src/auth/token.py, src/auth/middleware.py
""", subagent_type="executor")
\`\`\`
</Delegation_Rules>
<Parallel_Execution>
## Parallel Execution (NON-NEGOTIABLE)
**ALWAYS fire multiple independent operations simultaneously.**
\`\`\`
// GOOD: Fire all at once
background_task(agent="explore", prompt="Find auth files...")
background_task(agent="librarian", prompt="Look up JWT docs...")
background_task(agent="oracle", prompt="Review architecture...")
// Continue working while they run
// System notifies when complete
// Use background_output to collect results
\`\`\`
### Rules:
- Multiple file reads simultaneously
- Multiple searches (glob + grep + ast_grep) at once
- 3+ async subagents (=Background Agents) for research
- NEVER wait for one task before firing independent ones
- EXCEPTION: Do NOT edit same file in parallel
</Parallel_Execution>
<Tools>
## Code
Leverage LSP, ASTGrep tools as much as possible for understanding, exploring, and refactoring.
## MultiModal, MultiMedia
Use \`look_at\` tool to deal with all kind of media files.
Only use \`read\` tool when you need to read the raw content, or precise analysis for the raw content is required.
## Tool Selection Guide
| Need | Tool | Why |
|------|------|-----|
| Symbol usages | lsp_find_references | Semantic, cross-file |
| String/log search | grep | Text-based |
| Structural refactor | ast_grep_replace | AST-aware, safe |
| Many small edits | multiedit | Fewer round-trips |
| Single edit | edit | Simple, precise |
| Rename symbol | lsp_rename | All references |
| Architecture | Oracle | High-level reasoning |
| External docs | Librarian | Web/GitHub search |
ALWAYS prefer tools over Bash commands.
FILE EDITS MUST use edit tool. NO Bash. NO exceptions.
</Tools>
<Playbooks>
## Exploration Flow
1. Create todos (obsessively specific)
2. Analyze user's question intent
3. Fire 3+ Explore agents in parallel (background)
4. Fire 3+ Librarian agents in parallel (background)
5. Continue working on main task
6. Wait for agents (background_output). NEVER answer until ALL complete.
7. Synthesize findings. If unclear, consult Oracle.
8. Provide evidence-based answer
## New Feature Flow
1. Create detailed todos
2. MUST Fire async subagents (=Background Agents) (explore 3+ librarian 3+)
3. Search for similar patterns in the codebase
4. Implement incrementally (Edit → Verify → Mark todo)
5. Run diagnostics/tests after each change
6. Consult Oracle if design unclear
## Bugfix Flow
1. Create todos
2. Reproduce bug (failing test or trigger)
3. Locate root cause (LSP/grep → read code)
4. Implement minimal fix
5. Run lsp_diagnostics
6. Run targeted test
7. Run broader test suite if available
## Refactor Flow
1. Create todos
2. Use lsp_find_references to map usages
3. Use ast_grep_search for structural variants
4. Make incremental edits (lsp_rename, edit, multiedit)
5. Run lsp_diagnostics after each change
6. Run tests after related changes
7. Review for regressions
## Async Flow
1. Working on task A
2. User requests "extra B"
3. Add B to todos
4. If parallel-safe, fire async subagent (=Background Agent) for B
5. Continue task A
</Playbooks>
<Verification_Protocol>
## Verification (MANDATORY, BLOCKING)
ALWAYS verify before marking complete:
1. Run lsp_diagnostics on changed files
2. Run build/typecheck (check AGENTS.md or package.json)
3. Run tests (check AGENTS.md, README, or package.json)
4. Fix ONLY errors caused by your changes
5. Re-run verification after fixes
### Completion Criteria (ALL required):
- [ ] All todos marked completed WITH evidence
- [ ] lsp_diagnostics clean on changed files
- [ ] Build passes
- [ ] Tests pass (if applicable)
- [ ] User's original request fully addressed
Missing ANY = NOT complete. Keep iterating.
</Verification_Protocol>
<Failure_Handling>
## Failure Recovery
When verification fails 3+ times:
1. STOP all edits immediately
2. Minimize the diff / revert to last working state
3. Report: What failed, why, what you tried
4. Consult Oracle with full failure context
5. If Oracle fails, ask user for guidance
NEVER continue blindly after 3 failures.
NEVER suppress errors with \`as any\`, \`@ts-ignore\`, \`@ts-expect-error\`.
Fix the actual problem.
</Failure_Handling>
<Conventions>
## Code Conventions
- Mimic existing code style
- Use existing libraries and utilities
- Follow existing patterns
- Never introduce new patterns unless necessary or requested
## File Operations
- ALWAYS use absolute paths
- Prefer specialized tools over Bash
## Security
- Never expose or log secrets
- Never commit secrets to repository
</Conventions>
<Decision_Framework>
| Need | Use |
|------|-----|
| Find code in THIS codebase | Explore (3+ parallel) + LSP + ast-grep |
| External docs/examples | Librarian (3+ parallel) |
| Designing Architecture/reviewing Code/debugging | Oracle |
| Documentation | Document Writer |
| UI/visual work | Frontend Engineer |
| Simple file ops | Direct tools (read, write, edit) |
| Multiple independent ops | Fire all in parallel |
| Semantic code understanding | LSP tools |
| Structural code patterns | ast_grep_search |
</Decision_Framework>
<Anti_Patterns>
## NEVER Do These (BLOCKING)
- Speculating about code you haven't opened
- Editing files without reading first
- Delegating with vague prompts (no 7 sections)
- Skipping todo planning for "quick" tasks
- Forgetting to mark tasks complete
- Sequential execution when parallel possible
- Waiting for one async subagent (=Background Agent) before firing another
- Marking complete without evidence
- Continuing after 3+ failures without Oracle
- Asking user for permission on trivial steps
- Leaving "TODO" comments instead of implementing
- Editing files with bash commands
</Anti_Patterns>
<Final_Reminders>
## Remember
- You are the **team lead**, not the grunt worker
- Your context window is precious—delegate to preserve it
- Agents have specialized expertise—USE THEM
- TODO tracking = Your Key to Success
- Parallel execution = faster results
- **ALWAYS fire multiple independent operations simultaneously**
- Do not stop until the user's request is fully fulfilled
</Final_Reminders>
`
export const omoAgent: AgentConfig = {
description:
"Powerful AI orchestrator for OpenCode, introduced by OhMyOpenCode. Plans, delegates, and executes complex tasks using specialized subagents with aggressive parallel execution. Emphasizes background task delegation and todo-driven workflow.",
mode: "primary",
model: "anthropic/claude-opus-4-5",
thinking: {
type: "enabled",
budgetTokens: 32000,
},
maxTokens: 128000,
prompt: OMO_SYSTEM_PROMPT,
color: "#00CED1",
}

View File

@@ -2,56 +2,76 @@ import type { AgentConfig } from "@opencode-ai/sdk"
export const oracleAgent: AgentConfig = {
description:
"Expert AI advisor with advanced reasoning capabilities for high-quality technical guidance, code reviews, architectural advice, and strategic planning.",
"Expert technical advisor with deep reasoning for architecture decisions, code analysis, and engineering guidance.",
mode: "subagent",
model: "openai/gpt-5.2",
temperature: 0.1,
reasoningEffort: "medium",
textVerbosity: "high",
tools: { write: false, edit: false, read: true, call_omo_agent: true },
prompt: `You are the Oracle - an expert AI advisor with advanced reasoning capabilities.
prompt: `You are a strategic technical advisor with deep reasoning capabilities, operating as a specialized consultant within an AI-assisted development environment.
Your role is to provide high-quality technical guidance, code reviews, architectural advice, and strategic planning for software engineering tasks.
## Context
You are a subagent inside an AI coding system, called when the main agent needs a smarter, more capable model. You are invoked in a zero-shot manner, where no one can ask you follow-up questions, or provide you with follow-up answers.
You function as an on-demand specialist invoked by a primary coding agent when complex analysis or architectural decisions require elevated reasoning. Each consultation is standalone—treat every request as complete and self-contained since no clarifying dialogue is possible.
Key responsibilities:
- Analyze code and architecture patterns
- Provide specific, actionable technical recommendations
- Plan implementations and refactoring strategies
- Answer deep technical questions with clear reasoning
- Suggest best practices and improvements
- Identify potential issues and propose solutions
## What You Do
Operating principles (simplicity-first):
- Default to the simplest viable solution that meets the stated requirements and constraints.
- Prefer minimal, incremental changes that reuse existing code, patterns, and dependencies in the repo. Avoid introducing new services, libraries, or infrastructure unless clearly necessary.
- Optimize first for maintainability, developer time, and risk; defer theoretical scalability and "future-proofing" unless explicitly requested or clearly required by constraints.
- Apply YAGNI and KISS; avoid premature optimization.
- Provide one primary recommendation. Offer at most one alternative only if the trade-off is materially different and relevant.
- Calibrate depth to scope: keep advice brief for small tasks; go deep only when the problem truly requires it or the user asks.
- Include a rough effort/scope signal (e.g., S <1h, M 1-3h, L 1-2d, XL >2d) when proposing changes.
- Stop when the solution is "good enough." Note the signals that would justify revisiting with a more complex approach.
Your expertise covers:
- Dissecting codebases to understand structural patterns and design choices
- Formulating concrete, implementable technical recommendations
- Architecting solutions and mapping out refactoring roadmaps
- Resolving intricate technical questions through systematic reasoning
- Surfacing hidden issues and crafting preventive measures
Tool usage:
- Use attached files and provided context first. Use tools only when they materially improve accuracy or are required to answer.
- Use web tools only when local information is insufficient or a current reference is needed.
## Decision Framework
Response format (keep it concise and action-oriented):
1) TL;DR: 1-3 sentences with the recommended simple approach.
2) Recommended approach (simple path): numbered steps or a short checklist; include minimal diffs or code snippets only as needed.
3) Rationale and trade-offs: brief justification; mention why alternatives are unnecessary now.
4) Risks and guardrails: key caveats and how to mitigate them.
5) When to consider the advanced path: concrete triggers or thresholds that justify a more complex design.
6) Optional advanced path (only if relevant): a brief outline, not a full design.
Apply pragmatic minimalism in all recommendations:
Guidelines:
- Use your reasoning to provide thoughtful, well-structured, and pragmatic advice.
- When reviewing code, examine it thoroughly but report only the most important, actionable issues.
- For planning tasks, break down into minimal steps that achieve the goal incrementally.
- Justify recommendations briefly; avoid long speculative exploration unless explicitly requested.
- Consider alternatives and trade-offs, but limit them per the principles above.
- Be thorough but concise-focus on the highest-leverage insights.
**Bias toward simplicity**: The right solution is typically the least complex one that fulfills the actual requirements. Resist hypothetical future needs.
IMPORTANT: Only your last message is returned to the main agent and displayed to the user. Your last message should be comprehensive yet focused, with a clear, simple recommendation that helps the user act immediately.`,
**Leverage what exists**: Favor modifications to current code, established patterns, and existing dependencies over introducing new components. New libraries, services, or infrastructure require explicit justification.
**Prioritize developer experience**: Optimize for readability, maintainability, and reduced cognitive load. Theoretical performance gains or architectural purity matter less than practical usability.
**One clear path**: Present a single primary recommendation. Mention alternatives only when they offer substantially different trade-offs worth considering.
**Match depth to complexity**: Quick questions get quick answers. Reserve thorough analysis for genuinely complex problems or explicit requests for depth.
**Signal the investment**: Tag recommendations with estimated effort—use Quick(<1h), Short(1-4h), Medium(1-2d), or Large(3d+) to set expectations.
**Know when to stop**: "Working well" beats "theoretically optimal." Identify what conditions would warrant revisiting with a more sophisticated approach.
## Working With Tools
Exhaust provided context and attached files before reaching for tools. External lookups should fill genuine gaps, not satisfy curiosity.
## How To Structure Your Response
Organize your final answer in three tiers:
**Essential** (always include):
- **Bottom line**: 2-3 sentences capturing your recommendation
- **Action plan**: Numbered steps or checklist for implementation
- **Effort estimate**: Using the Quick/Short/Medium/Large scale
**Expanded** (include when relevant):
- **Why this approach**: Brief reasoning and key trade-offs
- **Watch out for**: Risks, edge cases, and mitigation strategies
**Edge cases** (only when genuinely applicable):
- **Escalation triggers**: Specific conditions that would justify a more complex solution
- **Alternative sketch**: High-level outline of the advanced path (not a full design)
## Guiding Principles
- Deliver actionable insight, not exhaustive analysis
- For code reviews: surface the critical issues, not every nitpick
- For planning: map the minimal path to the goal
- Support claims briefly; save deep exploration for when it's requested
- Dense and useful beats long and thorough
## Critical Note
Your response goes directly to the user with no intermediate processing. Make your final message self-contained: a clear recommendation they can act on immediately, covering both what to do and why.`,
}

View File

@@ -1,6 +1,7 @@
import type { AgentConfig } from "@opencode-ai/sdk"
export type BuiltinAgentName =
| "OmO"
| "oracle"
| "librarian"
| "explore"

View File

@@ -1,5 +1,6 @@
import type { AgentConfig } from "@opencode-ai/sdk"
import type { BuiltinAgentName, AgentOverrideConfig, AgentOverrides } from "./types"
import { omoAgent } from "./omo"
import { oracleAgent } from "./oracle"
import { librarianAgent } from "./librarian"
import { exploreAgent } from "./explore"
@@ -9,6 +10,7 @@ import { multimodalLookerAgent } from "./multimodal-looker"
import { deepMerge } from "../shared"
const allBuiltinAgents: Record<BuiltinAgentName, AgentConfig> = {
OmO: omoAgent,
oracle: oracleAgent,
librarian: librarianAgent,
explore: exploreAgent,

View File

@@ -5,6 +5,7 @@ export {
McpNameSchema,
AgentNameSchema,
HookNameSchema,
OmoAgentConfigSchema,
} from "./schema"
export type {
@@ -14,4 +15,5 @@ export type {
McpName,
AgentName,
HookName,
OmoAgentConfig,
} from "./schema"

View File

@@ -17,6 +17,7 @@ const AgentPermissionSchema = z.object({
})
export const BuiltinAgentNameSchema = z.enum([
"OmO",
"oracle",
"librarian",
"explore",
@@ -27,6 +28,9 @@ export const BuiltinAgentNameSchema = z.enum([
export const OverridableAgentNameSchema = z.enum([
"build",
"plan",
"OmO",
"OmO-Plan",
"oracle",
"librarian",
"explore",
@@ -53,8 +57,10 @@ export const HookNameSchema = z.enum([
"rules-injector",
"background-notification",
"auto-update-checker",
"startup-toast",
"keyword-detector",
"agent-usage-reminder",
"non-interactive-env",
])
export const AgentOverrideConfigSchema = z.object({
@@ -73,17 +79,18 @@ export const AgentOverrideConfigSchema = z.object({
permission: AgentPermissionSchema.optional(),
})
export const AgentOverridesSchema = z
.object({
build: AgentOverrideConfigSchema.optional(),
oracle: AgentOverrideConfigSchema.optional(),
librarian: AgentOverrideConfigSchema.optional(),
explore: AgentOverrideConfigSchema.optional(),
"frontend-ui-ux-engineer": AgentOverrideConfigSchema.optional(),
"document-writer": AgentOverrideConfigSchema.optional(),
"multimodal-looker": AgentOverrideConfigSchema.optional(),
})
.partial()
export const AgentOverridesSchema = z.object({
build: AgentOverrideConfigSchema.optional(),
plan: AgentOverrideConfigSchema.optional(),
OmO: AgentOverrideConfigSchema.optional(),
"OmO-Plan": AgentOverrideConfigSchema.optional(),
oracle: AgentOverrideConfigSchema.optional(),
librarian: AgentOverrideConfigSchema.optional(),
explore: AgentOverrideConfigSchema.optional(),
"frontend-ui-ux-engineer": AgentOverrideConfigSchema.optional(),
"document-writer": AgentOverrideConfigSchema.optional(),
"multimodal-looker": AgentOverrideConfigSchema.optional(),
})
export const ClaudeCodeConfigSchema = z.object({
mcp: z.boolean().optional(),
@@ -93,6 +100,10 @@ export const ClaudeCodeConfigSchema = z.object({
hooks: z.boolean().optional(),
})
export const OmoAgentConfigSchema = z.object({
disabled: z.boolean().optional(),
})
export const OhMyOpenCodeConfigSchema = z.object({
$schema: z.string().optional(),
disabled_mcps: z.array(McpNameSchema).optional(),
@@ -101,6 +112,7 @@ export const OhMyOpenCodeConfigSchema = z.object({
agents: AgentOverridesSchema.optional(),
claude_code: ClaudeCodeConfigSchema.optional(),
google_auth: z.boolean().optional(),
omo_agent: OmoAgentConfigSchema.optional(),
})
export type OhMyOpenCodeConfig = z.infer<typeof OhMyOpenCodeConfigSchema>
@@ -108,5 +120,6 @@ export type AgentOverrideConfig = z.infer<typeof AgentOverrideConfigSchema>
export type AgentOverrides = z.infer<typeof AgentOverridesSchema>
export type AgentName = z.infer<typeof AgentNameSchema>
export type HookName = z.infer<typeof HookNameSchema>
export type OmoAgentConfig = z.infer<typeof OmoAgentConfigSchema>
export { McpNameSchema, type McpName } from "../mcp/types"

View File

@@ -83,6 +83,7 @@ export class BackgroundManager {
agent: input.agent,
tools: {
task: false,
call_omo_agent: false,
background_task: false,
},
parts: [{ type: "text", text: input.prompt }],

View File

@@ -1,18 +1,47 @@
import * as fs from "node:fs"
import { VERSION_FILE } from "./constants"
import * as path from "node:path"
import { CACHE_DIR, PACKAGE_NAME } from "./constants"
import { log } from "../../shared/logger"
export function invalidateCache(): boolean {
export function invalidatePackage(packageName: string = PACKAGE_NAME): boolean {
try {
if (fs.existsSync(VERSION_FILE)) {
fs.unlinkSync(VERSION_FILE)
log(`[auto-update-checker] Cache invalidated: ${VERSION_FILE}`)
return true
const pkgDir = path.join(CACHE_DIR, "node_modules", packageName)
const pkgJsonPath = path.join(CACHE_DIR, "package.json")
let packageRemoved = false
let dependencyRemoved = false
if (fs.existsSync(pkgDir)) {
fs.rmSync(pkgDir, { recursive: true, force: true })
log(`[auto-update-checker] Package removed: ${pkgDir}`)
packageRemoved = true
}
log("[auto-update-checker] Version file not found, nothing to invalidate")
return false
if (fs.existsSync(pkgJsonPath)) {
const content = fs.readFileSync(pkgJsonPath, "utf-8")
const pkgJson = JSON.parse(content)
if (pkgJson.dependencies?.[packageName]) {
delete pkgJson.dependencies[packageName]
fs.writeFileSync(pkgJsonPath, JSON.stringify(pkgJson, null, 2))
log(`[auto-update-checker] Dependency removed from package.json: ${packageName}`)
dependencyRemoved = true
}
}
if (!packageRemoved && !dependencyRemoved) {
log(`[auto-update-checker] Package not found, nothing to invalidate: ${packageName}`)
return false
}
return true
} catch (err) {
log("[auto-update-checker] Failed to invalidate cache:", err)
log("[auto-update-checker] Failed to invalidate package:", err)
return false
}
}
/** @deprecated Use invalidatePackage instead - this nukes ALL plugins */
export function invalidateCache(): boolean {
log("[auto-update-checker] WARNING: invalidateCache is deprecated, use invalidatePackage")
return invalidatePackage()
}

View File

@@ -1,5 +1,6 @@
import * as fs from "node:fs"
import * as path from "node:path"
import { fileURLToPath } from "node:url"
import type { NpmDistTags, OpencodeConfig, PackageJson, UpdateCheckResult } from "./types"
import {
PACKAGE_NAME,
@@ -7,22 +8,44 @@ import {
NPM_FETCH_TIMEOUT,
INSTALLED_PACKAGE_JSON,
USER_OPENCODE_CONFIG,
USER_OPENCODE_CONFIG_JSONC,
} from "./constants"
import { log } from "../../shared/logger"
export function isLocalDevMode(directory: string): boolean {
const projectConfig = path.join(directory, ".opencode", "opencode.json")
return getLocalDevPath(directory) !== null
}
for (const configPath of [projectConfig, USER_OPENCODE_CONFIG]) {
function stripJsonComments(json: string): string {
return json
.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => (g ? "" : m))
.replace(/,(\s*[}\]])/g, "$1")
}
function getConfigPaths(directory: string): string[] {
return [
path.join(directory, ".opencode", "opencode.json"),
path.join(directory, ".opencode", "opencode.jsonc"),
USER_OPENCODE_CONFIG,
USER_OPENCODE_CONFIG_JSONC,
]
}
export function getLocalDevPath(directory: string): string | null {
for (const configPath of getConfigPaths(directory)) {
try {
if (!fs.existsSync(configPath)) continue
const content = fs.readFileSync(configPath, "utf-8")
const config = JSON.parse(content) as OpencodeConfig
const config = JSON.parse(stripJsonComments(content)) as OpencodeConfig
const plugins = config.plugin ?? []
for (const entry of plugins) {
if (entry.startsWith("file://") && entry.includes(PACKAGE_NAME)) {
return true
try {
return fileURLToPath(entry)
} catch {
return entry.replace("file://", "")
}
}
}
} catch {
@@ -30,22 +53,68 @@ export function isLocalDevMode(directory: string): boolean {
}
}
return false
return null
}
export function findPluginEntry(directory: string): string | null {
const projectConfig = path.join(directory, ".opencode", "opencode.json")
function findPackageJsonUp(startPath: string): string | null {
try {
const stat = fs.statSync(startPath)
let dir = stat.isDirectory() ? startPath : path.dirname(startPath)
for (let i = 0; i < 10; i++) {
const pkgPath = path.join(dir, "package.json")
if (fs.existsSync(pkgPath)) {
try {
const content = fs.readFileSync(pkgPath, "utf-8")
const pkg = JSON.parse(content) as PackageJson
if (pkg.name === PACKAGE_NAME) return pkgPath
} catch {}
}
const parent = path.dirname(dir)
if (parent === dir) break
dir = parent
}
} catch {}
return null
}
for (const configPath of [projectConfig, USER_OPENCODE_CONFIG]) {
export function getLocalDevVersion(directory: string): string | null {
const localPath = getLocalDevPath(directory)
if (!localPath) return null
try {
const pkgPath = findPackageJsonUp(localPath)
if (!pkgPath) return null
const content = fs.readFileSync(pkgPath, "utf-8")
const pkg = JSON.parse(content) as PackageJson
return pkg.version ?? null
} catch {
return null
}
}
export interface PluginEntryInfo {
entry: string
isPinned: boolean
pinnedVersion: string | null
}
export function findPluginEntry(directory: string): PluginEntryInfo | null {
for (const configPath of getConfigPaths(directory)) {
try {
if (!fs.existsSync(configPath)) continue
const content = fs.readFileSync(configPath, "utf-8")
const config = JSON.parse(content) as OpencodeConfig
const config = JSON.parse(stripJsonComments(content)) as OpencodeConfig
const plugins = config.plugin ?? []
for (const entry of plugins) {
if (entry === PACKAGE_NAME || entry.startsWith(`${PACKAGE_NAME}@`)) {
return entry
if (entry === PACKAGE_NAME) {
return { entry, isPinned: false, pinnedVersion: null }
}
if (entry.startsWith(`${PACKAGE_NAME}@`)) {
const pinnedVersion = entry.slice(PACKAGE_NAME.length + 1)
const isPinned = pinnedVersion !== "latest"
return { entry, isPinned, pinnedVersion: isPinned ? pinnedVersion : null }
}
}
} catch {
@@ -58,13 +127,26 @@ export function findPluginEntry(directory: string): string | null {
export function getCachedVersion(): string | null {
try {
if (!fs.existsSync(INSTALLED_PACKAGE_JSON)) return null
const content = fs.readFileSync(INSTALLED_PACKAGE_JSON, "utf-8")
const pkg = JSON.parse(content) as PackageJson
return pkg.version ?? null
} catch {
return null
if (fs.existsSync(INSTALLED_PACKAGE_JSON)) {
const content = fs.readFileSync(INSTALLED_PACKAGE_JSON, "utf-8")
const pkg = JSON.parse(content) as PackageJson
if (pkg.version) return pkg.version
}
} catch {}
try {
const currentDir = path.dirname(fileURLToPath(import.meta.url))
const pkgPath = findPackageJsonUp(currentDir)
if (pkgPath) {
const content = fs.readFileSync(pkgPath, "utf-8")
const pkg = JSON.parse(content) as PackageJson
if (pkg.version) return pkg.version
}
} catch (err) {
log("[auto-update-checker] Failed to resolve version from current directory:", err)
}
return null
}
export async function getLatestVersion(): Promise<string | null> {
@@ -91,29 +173,33 @@ export async function getLatestVersion(): Promise<string | null> {
export async function checkForUpdate(directory: string): Promise<UpdateCheckResult> {
if (isLocalDevMode(directory)) {
log("[auto-update-checker] Local dev mode detected, skipping update check")
return { needsUpdate: false, currentVersion: null, latestVersion: null, isLocalDev: true }
return { needsUpdate: false, currentVersion: null, latestVersion: null, isLocalDev: true, isPinned: false }
}
const pluginEntry = findPluginEntry(directory)
if (!pluginEntry) {
const pluginInfo = findPluginEntry(directory)
if (!pluginInfo) {
log("[auto-update-checker] Plugin not found in config")
return { needsUpdate: false, currentVersion: null, latestVersion: null, isLocalDev: false }
return { needsUpdate: false, currentVersion: null, latestVersion: null, isLocalDev: false, isPinned: false }
}
if (pluginInfo.isPinned) {
log(`[auto-update-checker] Version pinned to ${pluginInfo.pinnedVersion}, skipping update check`)
return { needsUpdate: false, currentVersion: pluginInfo.pinnedVersion, latestVersion: null, isLocalDev: false, isPinned: true }
}
const currentVersion = getCachedVersion()
if (!currentVersion) {
log("[auto-update-checker] No cached version found")
return { needsUpdate: false, currentVersion: null, latestVersion: null, isLocalDev: false }
return { needsUpdate: false, currentVersion: null, latestVersion: null, isLocalDev: false, isPinned: false }
}
const latestVersion = await getLatestVersion()
if (!latestVersion) {
log("[auto-update-checker] Failed to fetch latest version")
return { needsUpdate: false, currentVersion, latestVersion: null, isLocalDev: false }
return { needsUpdate: false, currentVersion, latestVersion: null, isLocalDev: false, isPinned: false }
}
const needsUpdate = currentVersion !== latestVersion
log(`[auto-update-checker] Current: ${currentVersion}, Latest: ${latestVersion}, NeedsUpdate: ${needsUpdate}`)
return { needsUpdate, currentVersion, latestVersion, isLocalDev: false }
return { needsUpdate, currentVersion, latestVersion, isLocalDev: false, isPinned: false }
}

View File

@@ -38,3 +38,4 @@ function getUserConfigDir(): string {
export const USER_CONFIG_DIR = getUserConfigDir()
export const USER_OPENCODE_CONFIG = path.join(USER_CONFIG_DIR, "opencode", "opencode.json")
export const USER_OPENCODE_CONFIG_JSONC = path.join(USER_CONFIG_DIR, "opencode", "opencode.jsonc")

View File

@@ -1,10 +1,12 @@
import type { PluginInput } from "@opencode-ai/plugin"
import { checkForUpdate } from "./checker"
import { invalidateCache } from "./cache"
import { checkForUpdate, getCachedVersion, getLocalDevVersion } from "./checker"
import { invalidatePackage } from "./cache"
import { PACKAGE_NAME } from "./constants"
import { log } from "../../shared/logger"
import type { AutoUpdateCheckerOptions } from "./types"
export function createAutoUpdateCheckerHook(ctx: PluginInput) {
export function createAutoUpdateCheckerHook(ctx: PluginInput, options: AutoUpdateCheckerOptions = {}) {
const { showStartupToast = true } = options
let hasChecked = false
return {
@@ -22,21 +24,36 @@ export function createAutoUpdateCheckerHook(ctx: PluginInput) {
if (result.isLocalDev) {
log("[auto-update-checker] Skipped: local development mode")
if (showStartupToast) {
const version = getLocalDevVersion(ctx.directory) ?? getCachedVersion()
await showVersionToast(ctx, version)
}
return
}
if (result.isPinned) {
log(`[auto-update-checker] Skipped: version pinned to ${result.currentVersion}`)
if (showStartupToast) {
await showVersionToast(ctx, result.currentVersion)
}
return
}
if (!result.needsUpdate) {
log("[auto-update-checker] No update needed")
if (showStartupToast) {
await showVersionToast(ctx, result.currentVersion)
}
return
}
invalidateCache()
invalidatePackage(PACKAGE_NAME)
await ctx.client.tui
.showToast({
body: {
title: `${PACKAGE_NAME} Update`,
message: `v${result.latestVersion} available (current: v${result.currentVersion}). Restart OpenCode to apply.`,
title: `OhMyOpenCode ${result.latestVersion}`,
message: `OpenCode is now on Steroids. oMoMoMoMo...\nv${result.latestVersion} available. Restart OpenCode to apply.`,
variant: "info" as const,
duration: 8000,
},
@@ -51,6 +68,21 @@ export function createAutoUpdateCheckerHook(ctx: PluginInput) {
}
}
export type { UpdateCheckResult } from "./types"
async function showVersionToast(ctx: PluginInput, version: string | null): Promise<void> {
const displayVersion = version ?? "unknown"
await ctx.client.tui
.showToast({
body: {
title: `OhMyOpenCode ${displayVersion}`,
message: "OpenCode is now on Steroids. oMoMoMoMo...",
variant: "info" as const,
duration: 5000,
},
})
.catch(() => {})
log(`[auto-update-checker] Startup toast shown: v${displayVersion}`)
}
export type { UpdateCheckResult, AutoUpdateCheckerOptions } from "./types"
export { checkForUpdate } from "./checker"
export { invalidateCache } from "./cache"
export { invalidatePackage, invalidateCache } from "./cache"

View File

@@ -19,4 +19,9 @@ export interface UpdateCheckResult {
currentVersion: string | null
latestVersion: string | null
isLocalDev: boolean
isPinned: boolean
}
export interface AutoUpdateCheckerOptions {
showStartupToast?: boolean
}

View File

@@ -17,3 +17,4 @@ export { createAutoUpdateCheckerHook } from "./auto-update-checker";
export { createAgentUsageReminderHook } from "./agent-usage-reminder";
export { createKeywordDetectorHook } from "./keyword-detector";
export { createNonInteractiveEnvHook } from "./non-interactive-env";

View File

@@ -28,7 +28,7 @@ TELL THE USER WHAT AGENTS YOU WILL LEVERAGE NOW TO SATISFY USER'S REQUEST.
## WORKFLOW
1. Analyze the request and identify required capabilities
2. Spawn exploration/librarian agents via background_task in PARALLEL (10+ if needed)
3. Use planning agents to create detailed work breakdown
3. Always Use Plan agent with gathered context to create detailed work breakdown
4. Execute with continuous verification against original requirements
</ultrawork-mode>

View File

@@ -0,0 +1,9 @@
export const HOOK_NAME = "non-interactive-env"
export const NON_INTERACTIVE_ENV: Record<string, string> = {
CI: "true",
DEBIAN_FRONTEND: "noninteractive",
GIT_TERMINAL_PROMPT: "0",
GCM_INTERACTIVE: "never",
HOMEBREW_NO_AUTO_UPDATE: "1",
}

View File

@@ -0,0 +1,34 @@
import type { PluginInput } from "@opencode-ai/plugin"
import { HOOK_NAME, NON_INTERACTIVE_ENV } from "./constants"
import { log } from "../../shared"
export * from "./constants"
export * from "./types"
export function createNonInteractiveEnvHook(_ctx: PluginInput) {
return {
"tool.execute.before": async (
input: { tool: string; sessionID: string; callID: string },
output: { args: Record<string, unknown> }
): Promise<void> => {
if (input.tool.toLowerCase() !== "bash") {
return
}
const command = output.args.command as string | undefined
if (!command) {
return
}
output.args.env = {
...(output.args.env as Record<string, string> | undefined),
...NON_INTERACTIVE_ENV,
}
log(`[${HOOK_NAME}] Set non-interactive environment variables`, {
sessionID: input.sessionID,
env: NON_INTERACTIVE_ENV,
})
},
}
}

View File

@@ -0,0 +1,3 @@
export interface NonInteractiveEnvConfig {
disabled?: boolean
}

View File

@@ -56,7 +56,7 @@ async function sendNotification(
await ctx.$`osascript -e ${"display notification \"" + escapedMessage + "\" with title \"" + escapedTitle + "\""}`
break
case "linux":
await ctx.$`notify-send ${escapedTitle} ${escapedMessage}`
await ctx.$`notify-send ${escapedTitle} ${escapedMessage}`.catch(() => {})
break
case "win32":
await ctx.$`powershell -Command ${"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('" + escapedMessage + "', '" + escapedTitle + "')"}`

View File

@@ -6,6 +6,7 @@ import {
findMessageByIndexNeedingThinking,
findMessagesWithOrphanThinking,
findMessagesWithThinkingBlocks,
findMessagesWithThinkingOnly,
injectTextPart,
prependThinkingPart,
stripThinkingParts,
@@ -177,6 +178,8 @@ async function recoverThinkingDisabledViolation(
return anySuccess
}
const PLACEHOLDER_TEXT = "[user interrupted]"
async function recoverEmptyContentMessage(
_client: Client,
sessionID: string,
@@ -187,23 +190,28 @@ async function recoverEmptyContentMessage(
const targetIndex = extractMessageIndex(error)
const failedID = failedAssistantMsg.info?.id
const thinkingOnlyIDs = findMessagesWithThinkingOnly(sessionID)
for (const messageID of thinkingOnlyIDs) {
injectTextPart(sessionID, messageID, PLACEHOLDER_TEXT)
}
if (targetIndex !== null) {
const targetMessageID = findEmptyMessageByIndex(sessionID, targetIndex)
if (targetMessageID) {
return injectTextPart(sessionID, targetMessageID, "(interrupted)")
return injectTextPart(sessionID, targetMessageID, PLACEHOLDER_TEXT)
}
}
if (failedID) {
if (injectTextPart(sessionID, failedID, "(interrupted)")) {
if (injectTextPart(sessionID, failedID, PLACEHOLDER_TEXT)) {
return true
}
}
const emptyMessageIDs = findEmptyMessages(sessionID)
let anySuccess = false
let anySuccess = thinkingOnlyIDs.length > 0
for (const messageID of emptyMessageIDs) {
if (injectTextPart(sessionID, messageID, "(interrupted)")) {
if (injectTextPart(sessionID, messageID, PLACEHOLDER_TEXT)) {
anySuccess = true
}
}

View File

@@ -133,20 +133,15 @@ export function findEmptyMessages(sessionID: string): string[] {
export function findEmptyMessageByIndex(sessionID: string, targetIndex: number): string | null {
const messages = readMessages(sessionID)
// Try multiple indices to handle system message offset
// API includes system message at index 0, storage may not
const indicesToTry = [targetIndex, targetIndex - 1]
// API index may differ from storage index due to system messages
const indicesToTry = [targetIndex, targetIndex - 1, targetIndex - 2]
for (const idx of indicesToTry) {
if (idx < 0 || idx >= messages.length) continue
const targetMsg = messages[idx]
// NOTE: Do NOT skip last assistant message here
// If API returned an error, this message is NOT the final assistant message
// (the API only allows empty content for the ACTUAL final assistant message)
if (!messageHasContent(targetMsg.id)) {
return targetMsg.id
}
@@ -177,6 +172,28 @@ export function findMessagesWithThinkingBlocks(sessionID: string): string[] {
return result
}
export function findMessagesWithThinkingOnly(sessionID: string): string[] {
const messages = readMessages(sessionID)
const result: string[] = []
for (const msg of messages) {
if (msg.role !== "assistant") continue
const parts = readParts(msg.id)
if (parts.length === 0) continue
const hasThinking = parts.some((p) => THINKING_TYPES.has(p.type))
const hasTextContent = parts.some(hasContent)
// Has thinking but no text content = orphan thinking
if (hasThinking && !hasTextContent) {
result.push(msg.id)
}
}
return result
}
export function findMessagesWithOrphanThinking(sessionID: string): string[] {
const messages = readMessages(sessionID)
const result: string[] = []

View File

@@ -1,5 +1,5 @@
import type { Plugin } from "@opencode-ai/plugin";
import { createBuiltinAgents, BUILD_AGENT_PROMPT_EXTENSION } from "./agents";
import { createBuiltinAgents } from "./agents";
import {
createTodoContinuationEnforcer,
createContextWindowMonitorHook,
@@ -18,6 +18,7 @@ import {
createAutoUpdateCheckerHook,
createKeywordDetectorHook,
createAgentUsageReminderHook,
createNonInteractiveEnvHook,
} from "./hooks";
import { createGoogleAntigravityAuthPlugin } from "./auth/antigravity";
import {
@@ -65,11 +66,36 @@ function getUserConfigDir(): string {
return process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
}
const AGENT_NAME_MAP: Record<string, string> = {
omo: "OmO",
build: "build",
oracle: "oracle",
librarian: "librarian",
explore: "explore",
"frontend-ui-ux-engineer": "frontend-ui-ux-engineer",
"document-writer": "document-writer",
"multimodal-looker": "multimodal-looker",
};
function normalizeAgentNames(agents: Record<string, unknown>): Record<string, unknown> {
const normalized: Record<string, unknown> = {};
for (const [key, value] of Object.entries(agents)) {
const normalizedKey = AGENT_NAME_MAP[key.toLowerCase()] ?? key;
normalized[normalizedKey] = value;
}
return normalized;
}
function loadConfigFromPath(configPath: string): OhMyOpenCodeConfig | null {
try {
if (fs.existsSync(configPath)) {
const content = fs.readFileSync(configPath, "utf-8");
const rawConfig = JSON.parse(content);
if (rawConfig.agents && typeof rawConfig.agents === "object") {
rawConfig.agents = normalizeAgentNames(rawConfig.agents);
}
const result = OhMyOpenCodeConfigSchema.safeParse(rawConfig);
if (!result.success) {
@@ -203,7 +229,9 @@ const OhMyOpenCodePlugin: Plugin = async (ctx) => {
? createRulesInjectorHook(ctx)
: null;
const autoUpdateChecker = isHookEnabled("auto-update-checker")
? createAutoUpdateCheckerHook(ctx)
? createAutoUpdateCheckerHook(ctx, {
showStartupToast: isHookEnabled("startup-toast"),
})
: null;
const keywordDetector = isHookEnabled("keyword-detector")
? createKeywordDetectorHook()
@@ -211,6 +239,9 @@ const OhMyOpenCodePlugin: Plugin = async (ctx) => {
const agentUsageReminder = isHookEnabled("agent-usage-reminder")
? createAgentUsageReminderHook(ctx)
: null;
const nonInteractiveEnv = isHookEnabled("non-interactive-env")
? createNonInteractiveEnvHook(ctx)
: null;
updateTerminalTitle({ sessionId: "main" });
@@ -252,24 +283,40 @@ const OhMyOpenCodePlugin: Plugin = async (ctx) => {
const userAgents = (pluginConfig.claude_code?.agents ?? true) ? loadUserAgents() : {};
const projectAgents = (pluginConfig.claude_code?.agents ?? true) ? loadProjectAgents() : {};
config.agent = {
...builtinAgents,
...userAgents,
...projectAgents,
...config.agent,
};
const isOmoEnabled = pluginConfig.omo_agent?.disabled !== true;
// Inject orchestration prompt to all non-subagent agents
// Subagents are delegated TO, so they don't need orchestration guidance
for (const [agentName, agentConfig] of Object.entries(config.agent ?? {})) {
if (agentConfig && agentConfig.mode !== "subagent") {
const existingPrompt = agentConfig.prompt || "";
const userOverride = pluginConfig.agents?.[agentName as keyof typeof pluginConfig.agents]?.prompt || "";
config.agent[agentName] = {
...agentConfig,
prompt: existingPrompt + BUILD_AGENT_PROMPT_EXTENSION + userOverride,
};
}
if (isOmoEnabled && builtinAgents.OmO) {
// TODO: When OpenCode releases `default_agent` config option (PR #5313),
// use `config.default_agent = "OmO"` instead of demoting build/plan.
// Tracking: https://github.com/sst/opencode/pull/5313
const { name: _planName, ...planConfigWithoutName } = config.agent?.plan ?? {};
const omoPlanOverride = pluginConfig.agents?.["OmO-Plan"];
const omoPlanBase = {
...builtinAgents.OmO,
...planConfigWithoutName,
description: `${config.agent?.plan?.description ?? "Plan agent"} (OhMyOpenCode version)`,
color: config.agent?.plan?.color ?? "#6495ED",
};
const omoPlanConfig = omoPlanOverride ? deepMerge(omoPlanBase, omoPlanOverride) : omoPlanBase;
config.agent = {
OmO: builtinAgents.OmO,
"OmO-Plan": omoPlanConfig,
...Object.fromEntries(Object.entries(builtinAgents).filter(([k]) => k !== "OmO")),
...userAgents,
...projectAgents,
...config.agent,
build: { ...config.agent?.build, mode: "subagent" },
plan: { ...config.agent?.plan, mode: "subagent" },
};
} else {
config.agent = {
...builtinAgents,
...userAgents,
...projectAgents,
...config.agent,
};
}
config.tools = {
@@ -436,6 +483,7 @@ const OhMyOpenCodePlugin: Plugin = async (ctx) => {
"tool.execute.before": async (input, output) => {
await claudeCodeHooks["tool.execute.before"](input, output);
await nonInteractiveEnv?.["tool.execute.before"](input, output);
await commentChecker?.["tool.execute.before"](input, output);
if (input.sessionID === getMainSessionID()) {

View File

@@ -124,8 +124,6 @@ async function executeSync(
task: false,
call_omo_agent: false,
background_task: false,
background_output: false,
background_cancel: false,
},
parts: [{ type: "text", text: args.prompt }],
},

View File

@@ -0,0 +1,103 @@
import { describe, test, expect, beforeEach, afterEach } from "bun:test"
import { mkdirSync, rmSync, writeFileSync, existsSync } from "node:fs"
import { join } from "node:path"
import { tmpdir } from "node:os"
// Import the function we'll create to replace glob
import { findFileRecursive } from "./downloader"
describe("findFileRecursive", () => {
let testDir: string
beforeEach(() => {
// #given - create temp directory for testing
testDir = join(tmpdir(), `downloader-test-${Date.now()}`)
mkdirSync(testDir, { recursive: true })
})
afterEach(() => {
// cleanup
if (existsSync(testDir)) {
rmSync(testDir, { recursive: true, force: true })
}
})
test("should find file in root directory", () => {
// #given
const targetFile = join(testDir, "rg.exe")
writeFileSync(targetFile, "dummy content")
// #when
const result = findFileRecursive(testDir, "rg.exe")
// #then
expect(result).toBe(targetFile)
})
test("should find file in nested directory (ripgrep release structure)", () => {
// #given - simulate ripgrep release zip structure
const nestedDir = join(testDir, "ripgrep-14.1.1-x86_64-pc-windows-msvc")
mkdirSync(nestedDir, { recursive: true })
const targetFile = join(nestedDir, "rg.exe")
writeFileSync(targetFile, "dummy content")
// #when
const result = findFileRecursive(testDir, "rg.exe")
// #then
expect(result).toBe(targetFile)
})
test("should find file in deeply nested directory", () => {
// #given
const deepDir = join(testDir, "level1", "level2", "level3")
mkdirSync(deepDir, { recursive: true })
const targetFile = join(deepDir, "rg")
writeFileSync(targetFile, "dummy content")
// #when
const result = findFileRecursive(testDir, "rg")
// #then
expect(result).toBe(targetFile)
})
test("should return null when file not found", () => {
// #given - empty directory
// #when
const result = findFileRecursive(testDir, "nonexistent.exe")
// #then
expect(result).toBeNull()
})
test("should find first match when multiple files exist", () => {
// #given
const dir1 = join(testDir, "dir1")
const dir2 = join(testDir, "dir2")
mkdirSync(dir1, { recursive: true })
mkdirSync(dir2, { recursive: true })
writeFileSync(join(dir1, "rg"), "first")
writeFileSync(join(dir2, "rg"), "second")
// #when
const result = findFileRecursive(testDir, "rg")
// #then
expect(result).not.toBeNull()
expect(result!.endsWith("rg")).toBe(true)
})
test("should match exact filename, not partial", () => {
// #given
writeFileSync(join(testDir, "rg.exe.bak"), "backup file")
writeFileSync(join(testDir, "not-rg.exe"), "wrong file")
// #when
const result = findFileRecursive(testDir, "rg.exe")
// #then
expect(result).toBeNull()
})
})

View File

@@ -1,7 +1,21 @@
import { existsSync, mkdirSync, chmodSync, unlinkSync } from "node:fs"
import { existsSync, mkdirSync, chmodSync, unlinkSync, readdirSync } from "node:fs"
import { join } from "node:path"
import { spawn } from "bun"
export function findFileRecursive(dir: string, filename: string): string | null {
try {
const entries = readdirSync(dir, { withFileTypes: true, recursive: true })
for (const entry of entries) {
if (entry.isFile() && entry.name === filename) {
return join(entry.parentPath ?? dir, entry.name)
}
}
} catch {
return null
}
return null
}
const RG_VERSION = "14.1.1"
const PLATFORM_CONFIG: Record<string, { platform: string; extension: "tar.gz" | "zip" } | undefined> = {
@@ -70,14 +84,12 @@ async function extractZipWindows(archivePath: string, destDir: string): Promise<
throw new Error("Failed to extract zip with PowerShell")
}
const { globSync } = await import("glob")
const rgFiles = globSync("**/rg.exe", { cwd: destDir })
if (rgFiles.length > 0) {
const srcPath = join(destDir, rgFiles[0])
const foundPath = findFileRecursive(destDir, "rg.exe")
if (foundPath) {
const destPath = join(destDir, "rg.exe")
if (srcPath !== destPath) {
if (foundPath !== destPath) {
const { renameSync } = await import("node:fs")
renameSync(srcPath, destPath)
renameSync(foundPath, destPath)
}
}
}
@@ -92,14 +104,12 @@ async function extractZipUnix(archivePath: string, destDir: string): Promise<voi
throw new Error("Failed to extract zip")
}
const { globSync } = await import("glob")
const rgFiles = globSync("**/rg", { cwd: destDir })
if (rgFiles.length > 0) {
const srcPath = join(destDir, rgFiles[0])
const foundPath = findFileRecursive(destDir, "rg")
if (foundPath) {
const destPath = join(destDir, "rg")
if (srcPath !== destPath) {
if (foundPath !== destPath) {
const { renameSync } = await import("node:fs")
renameSync(srcPath, destPath)
renameSync(foundPath, destPath)
}
}
}