Provides AST-aware code search and replace capabilities via the ast-grep CLI. This tooling layer enables OpenCode agents to perform precise, language-aware code transformations and queries across the repository using structured AST patterns rather than fragile regex-based matching.
The implementation follows a layered architecture:
Tool Definitions (tools.ts):
ast_grep_search: Exposes a tool for AST pattern matching with meta-variable support ($VAR, $$$)ast_grep_replace: Exposes a tool for AST-aware code rewriting with dry-run capabilityCLI Integration (cli.ts):
runSg(): Core function that spawns the ast-grep CLI with proper argument construction, timeout handling, and output parsinggetAstGrepPath(), startBackgroundInit())crossSpawn for cross-platform process spawningType System (types.ts):
CliLanguage (25 supported languages) and CliMatch/SgResult interfacesUtilities (utils.ts):
formatSearchResult(): Formats search results grouped by file with line numbers and truncation awarenessformatReplaceResult(): Formats replacement results with dry-run indicators and before/after snippetsgetEmptyResultHint(): Provides user guidance when patterns yield no matches (e.g., missing colons in Python)Binary Management (downloader.ts):
ensureAstGrepBinary(): Downloads platform-specific ast-grep binary on-demand to ~/.cache/oh-my-opencode-slim/bin/Environment & Constants (constants.ts):
checkEnvironment(): Validates CLI availability at startup for early feedbackformatEnvironmentCheck(): User-friendly status reportingPublic API (index.ts):
ast_grep_search tool with pattern, language, optional paths/globs/contextrunSg() with appropriate argumentsrunSg() ensures CLI availability (downloads if needed), constructs CLI args:
-p <pattern> --lang <lang> --json=compact-r <rewrite> (for replace), -C <context>, --globs <glob>, pathsrunSg() parses output, handles truncation (max bytes/max matches), and returns SgResultformatSearchResult() and surfaces to user via metadatagetEmptyResultHint() may provide user guidanceast_grep_replace with pattern, rewrite, language, dry-run flagrunSg() with updateAll: !dryRun to enable actual file writesreplacement field[DRY RUN] or [APPLIED] indicators and before/after snippetsgetAstGrepPath() triggers background initialization via startBackgroundInit()ensureAstGrepBinary()resolvedCliPath to avoid repeated lookups@opencode-ai/plugin tool registration@ast-grep/cli (for fallback binary resolution)crossSpawn utility for cross-platform process handlingextractZip utility for binary extractionast_grep_search tool for pattern matchingast_grep_replace tool for code transformations// Search for all console.log calls in TypeScript files
@fixer search for console.log calls in TypeScript files
// Replace arrow functions with regular functions
@fixer replace arrow functions with regular functions
See tool definitions in tools.ts for full argument schemas and examples.