Skip to content

Instantly share code, notes, and snippets.

@BananaAcid
Last active October 18, 2026 20:37
Show Gist options
  • Select an option

  • Save BananaAcid/5162529fece9e1fdb623a98158b1893c to your computer and use it in GitHub Desktop.

Select an option

Save BananaAcid/5162529fece9e1fdb623a98158b1893c to your computer and use it in GitHub Desktop.
OpenCode v2 - PowerShell completion

OpenCode v2 - PowerShell completion

This is a working OpenCode v2 CLI autocompletion solution, PowerShell native.

Execute the below script or add it to your $PROFILE (notepad $PROFILE)

Using --model <TAB>, TAB completes the available models (from command opencode models).

opencode r<TAB>
opencode run -<TAB>  # tab as often as needed to get to --model
opencode run --model o<TAB>
opencode run --model opencode/big-pickle "..."

Same goes for --agant <TAB> to tab through existing agents (from command opencode debug agents)

Install

  1. Download the script below into into PowerShell profile folder
  2. Let the autocomplete file load on each new terminal
  3. Load it now to make autocompletion available

All as oneliner:

$f="$((Split-Path $PROFILE))\opencode-v2-completion.ps1"; iwr "https://gist.githubusercontent.com/BananaAcid/5162529fece9e1fdb623a98158b1893c/raw/opencode-v2-completion.ps1" -OutFile $f; ac $PROFILE "`n. '$f'; . '$f'"

Build manually

1. collect sub commands

opencode run --model opencode/big-pickle "1. run 'opencode -h'. extract all SUBCOMMANDS: 2. run a subagent (parallel) for each subcommand to get its SUBCOMMANDS ('opencode service -h'). repeat for each found SUBCOMMANDS. 3. finally only return a PowerShell `$cmd array that contains alls subcommands as they are nested ('`"service`", `"service start`"') and save the `$cmd command to opencode_subcommands.ps1"

example output:

> build · big-pickle
Got 17 top-level subcommands. Now spawning a subagent for each to extract their nested subcommands.
✓ opencode uninstall subcommands General Agent
✓ opencode acp subcommands General Agent
✓ opencode upgrade subcommands General Agent
✓ opencode debug subcommands General Agent
✓ opencode api subcommands General Agent
✓ opencode plugin subcommands General Agent
✓ opencode mcp subcommands General Agent
✓ opencode auth subcommands General Agent
> build · big-pickle
Now the remaining nine subcommands.
✓ opencode models subcommands General Agent
✓ opencode run subcommands General Agent
✓ opencode mini subcommands General Agent
✓ opencode reload subcommands General Agent
✓ opencode pair subcommands General Agent
✓ opencode stats subcommands General Agent
✓ opencode session subcommands General Agent
✓ opencode service subcommands General Agent
> build · big-pickle
✓ opencode serve subcommands General Agent
> build · big-pickle
$cmd = @(
...
);

2. generate clean list of help docs

# load $cmds into context
. opencode_subcommands.ps1

# collect all help docs
$cmds |% { echo "--------------------------------------`nCOMMAND: opencode $_ -h" ; Invoke-Expression  "opencode $_ -h" } > opencode_commands_help.txt

3. generate Register-ArgumentCompleter

$prompt = @'
Create a Powershell autocompletion function for OpenCode CLI, with all subcommands and default values.
Make `--agent` and `--model` autocomplete (check output of required commands).
Using `Register-ArgumentCompleter -Native -CommandName "opencode" -ScriptBlock { }`.
Get missing information from: https://opencode.ai/docs/de/cli/ (but do not add additional subcommands or additional flags from there, the documentation might not match the opencode cli version)

Based on the appended commandline help.

If available, update existing opencode-v2-completion.ps1.
Save to opencode-v2-completion.ps1
'@

opencode run --model opencode/big-pickle --File opencode_commands_help.txt $prompt
Register-ArgumentCompleter -Native -CommandName "opencode" -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
# 1. Parse tokens
$tokens = @($commandAst.CommandElements | ForEach-Object { $_.Value })
if ($tokens.Count -gt 0 -and $tokens[0] -eq 'opencode') {
$tokens = $tokens[1..($tokens.Count - 1)]
}
# Global flags applicable to all commands
$globalFlags = @{
'--help' = 'Show help information'
'-h' = 'Show help information'
'--version' = 'Show version information'
'-v' = 'Show version information'
'--wizard' = 'Start wizard mode for a command'
'--completions' = 'Print shell completion script (bash, zsh, fish, sh)'
'--log-level' = 'Sets the minimum log level'
'--print-logs' = 'Print logs to stderr (server logs require --standalone)'
}
$topLevelSubcommands = [ordered]@{
'upgrade' = 'Upgrade OpenCode to the latest or a specific version'
'update' = 'Upgrade OpenCode to the latest or a specific version (alias)'
'uninstall' = 'Uninstall OpenCode, keeping session data, configuration, and state'
'acp' = 'Start an Agent Client Protocol server'
'api' = 'Make a request to the running server'
'debug' = 'Debugging and troubleshooting tools'
'auth' = 'Manage integrations and credentials'
'mcp' = 'Manage MCP (Model Context Protocol) servers'
'plugin' = 'Manage plugins'
'models' = 'List all available models'
'stats' = 'Show shareable usage statistics'
'mini' = 'Start the minimal interactive interface'
'run' = 'Run OpenCode with a message'
'session' = 'Manage sessions'
'service' = 'Manage the background server'
'reload' = 'Reload configuration'
'pair' = 'Print one-time links to connect a browser or app'
'serve' = 'Start the v2 API and web server'
}
# Locate the active main subcommand (prevents flag arguments like "--log-level debug" from being mistaken as subcommands)
$mainCmd = $null
$mainCmdIndex = -1
for ($i = 0; $i -lt $tokens.Count; $i++) {
if ($topLevelSubcommands.Contains($tokens[$i]) -and $tokens[$i] -ne $wordToComplete) {
$mainCmd = $tokens[$i]
$mainCmdIndex = $i
break
}
}
# Extract sub-tokens following the main command
$subTokens = @()
if ($mainCmdIndex -ge 0 -and $mainCmdIndex -lt ($tokens.Count - 1)) {
$subTokens = $tokens[($mainCmdIndex + 1)..($tokens.Count - 1)] |
Where-Object { $_ -notlike '-*' -and $_ -ne $wordToComplete }
}
# 2. VALUE COMPLETION (Flag parameters & positional arguments)
if ($tokens.Count -gt 0) {
$prevToken = $null
if ($tokens[-1] -eq $wordToComplete -and $tokens.Count -gt 1) {
$prevToken = $tokens[-2]
} elseif ($tokens[-1] -ne $wordToComplete) {
$prevToken = $tokens[-1]
}
if ($null -ne $prevToken) {
switch ($prevToken) {
# Dynamic agent completion with descriptions as hints
'--agent' {
if ($null -eq $script:OpenCodeAgentsCache) {
try {
$rawJson = opencode debug agents 2>$null | Out-String
if ($rawJson) {
$script:OpenCodeAgentsCache = ($rawJson | ConvertFrom-Json)
}
} catch {
$script:OpenCodeAgentsCache = @()
}
}
return $script:OpenCodeAgentsCache |
Where-Object { -not $_.hidden -and $_.id -like "$wordToComplete*" } |
ForEach-Object {
$hint = if ($_.description) { "$($_.name): $($_.description)" } else { $_.name }
[System.Management.Automation.CompletionResult]::new($_.id, $_.id, 'ParameterValue', $hint)
}
}
# Dynamic model completion for 'run' and 'mini'
{ $_ -eq '--model' -or ($_ -eq '-m' -and $mainCmd -in 'mini', 'run') } {
if ($null -eq $script:OpenCodeModelsCache) {
try {
$script:OpenCodeModelsCache = @(opencode models 2>$null | Where-Object { $_ -match '\S' })
} catch {
$script:OpenCodeModelsCache = @()
}
}
return $script:OpenCodeModelsCache |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
}
}
# Hostname suggestions for 'serve'
'--hostname' {
return @('127.0.0.1', 'localhost', '[::1]') |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', "Host address: $_")
}
}
# Port suggestions for 'serve'
'--port' {
return @('49374') |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', 'Default server port (49374)')
}
}
# Server suggestions for background or remote service
'--server' {
return @('http://localhost:49374', 'http://127.0.0.1:49374') |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', 'Default local service URL')
}
}
# Project filter in stats
'--project' {
if ('.' -like "$wordToComplete*") {
return [System.Management.Automation.CompletionResult]::new('.', '.', 'ParameterValue', 'Current project')
}
}
# File attachment / import completion
{ $_ -in '--file', '-f' -or ($_ -eq 'import' -and $mainCmd -in 'auth', 'session') } {
return Get-ChildItem -File -ErrorAction SilentlyContinue |
Where-Object { $_.Name -like "$wordToComplete*" } |
ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_.Name, $_.Name, 'ProviderItem', $_.FullName)
}
}
# Directory completion for session import or top-level directory argument
'--directory' {
return Get-ChildItem -Directory -ErrorAction SilentlyContinue |
Where-Object { $_.Name -like "$wordToComplete*" } |
ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_.Name, $_.Name, 'ProviderContainer', $_.FullName)
}
}
'--completions' {
return @('bash', 'zsh', 'fish', 'sh') |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
}
'--log-level' {
return @('all', 'trace', 'debug', 'info', 'warn', 'warning', 'error', 'fatal', 'none') |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
}
# Installation method choices for upgrade & update
{ $_ -in '--method', '-m' -and $mainCmd -in 'upgrade', 'update' } {
return @('curl', 'npm', 'pnpm', 'bun', 'yarn', 'vp', 'brew') |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', "Install via $_") }
}
'--format' {
if ($mainCmd -eq 'session') {
return @('table', 'json') |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
} else {
return @('default', 'json') |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
}
}
# Positional argument for "opencode debug paths <name>" (only if not typing a flag)
'paths' {
if ($mainCmd -eq 'debug' -and $wordToComplete -notlike '-*') {
return @('db', 'home', 'data', 'config', 'cache', 'state', 'tmp', 'bin', 'log', 'repos') |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', "Path type: $_") }
}
}
# Positional argument for "opencode service get/set/unset <key>"
{ $_ -in 'get', 'set', 'unset' -and $mainCmd -eq 'service' -and $wordToComplete -notlike '-*' } {
if ('env' -like "$wordToComplete*") {
return [System.Management.Automation.CompletionResult]::new('env', 'env', 'ParameterValue', 'Environment variable')
}
}
}
}
}
# 3. SUBCOMMAND ROUTING
if ($null -ne $mainCmd) {
$cmdFlags = @{}
switch ($mainCmd) {
'debug' {
$subchoices = @{
'agents' = 'List all agents'
'config' = 'List configuration sources'
'paths' = 'Show global paths (data, config, cache, state)'
}
if ($subTokens.Count -eq 0 -and $wordToComplete -notlike '-*') {
return $subchoices.GetEnumerator() |
Where-Object { $_.Key -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_.Key, $_.Key, 'Command', $_.Value) }
}
}
'auth' {
$subchoices = @{
'list' = 'List integrations and credentials'
'login' = 'Connect an integration'
'logout' = 'Log out of a saved account'
'export' = 'Print stored credentials, including secrets, as JSON'
'import' = 'Import credentials exported by auth export'
'switch' = 'Switch the active account for an integration'
}
if ($subTokens.Count -eq 0 -and $wordToComplete -notlike '-*') {
return $subchoices.GetEnumerator() |
Where-Object { $_.Key -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_.Key, $_.Key, 'Command', $_.Value) }
}
if ($subTokens.Count -ge 1) {
switch ($subTokens[0]) {
'list' { $cmdFlags = @{ '--standalone' = 'Run with a private server'; '--server' = 'Server URL'; '--format' = 'Output format (default, json)' } }
'login' { $cmdFlags = @{ '--standalone' = 'Run with a private server'; '--server' = 'Server URL'; '--method' = 'Auth method ID'; '--answer' = 'Provider form answer (key=value)' } }
'logout' { $cmdFlags = @{ '--standalone' = 'Run with a private server'; '--server' = 'Server URL' } }
'export' { $cmdFlags = @{ '--standalone' = 'Run with a private server'; '--server' = 'Server URL' } }
'import' { $cmdFlags = @{ '--standalone' = 'Run with a private server'; '--server' = 'Server URL' } }
'switch' { $cmdFlags = @{ '--standalone' = 'Run with a private server'; '--server' = 'Server URL' } }
}
}
}
'mcp' {
$subchoices = @{
'list' = 'List configured MCP servers and their status'
'add' = 'Add an MCP server to your configuration'
'auth' = 'Authenticate with an OAuth-capable remote MCP server'
'logout' = 'Remove stored OAuth credentials for an MCP server'
}
if ($subTokens.Count -eq 0 -and $wordToComplete -notlike '-*') {
return $subchoices.GetEnumerator() |
Where-Object { $_.Key -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_.Key, $_.Key, 'Command', $_.Value) }
}
if ($subTokens.Count -ge 1 -and $subTokens[0] -eq 'add') {
$cmdFlags = @{
'--url' = 'URL for a remote MCP server'
'--header' = 'HTTP header for remote server (name=value)'
'--env' = 'Environment variable for local server (name=value)'
'--global' = 'Write to global config instead of project config'
}
}
}
'plugin' {
$subchoices = @{
'list' = 'List plugins'
'add' = 'Install a plugin and add it to global configuration'
'check' = 'Check package plugins for updates'
'update' = 'Update package plugins'
'remove' = 'Remove a plugin from global configuration'
}
if ($subTokens.Count -eq 0 -and $wordToComplete -notlike '-*') {
return $subchoices.GetEnumerator() |
Where-Object { $_.Key -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_.Key, $_.Key, 'Command', $_.Value) }
}
if ($subTokens.Count -ge 1 -and $subTokens[0] -eq 'list') {
$cmdFlags = @{ '--builtin' = 'Include built-in server plugins' }
}
}
'session' {
$subchoices = @{
'list' = 'List top-level sessions in current project, newest first'
'delete' = 'Delete a session and its child sessions'
'export' = 'Export session data as JSON'
'import' = 'Import session data from a JSON file or URL'
}
if ($subTokens.Count -eq 0 -and $wordToComplete -notlike '-*') {
return $subchoices.GetEnumerator() |
Where-Object { $_.Key -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_.Key, $_.Key, 'Command', $_.Value) }
}
if ($subTokens.Count -ge 1) {
switch ($subTokens[0]) {
'list' { $cmdFlags = @{ '--standalone' = 'Private server'; '--server' = 'Server URL'; '--max-count' = 'Limit count'; '-n' = 'Limit count'; '--format' = 'Output format (table, json)' } }
'delete' { $cmdFlags = @{ '--standalone' = 'Private server'; '--server' = 'Server URL' } }
'export' { $cmdFlags = @{ '--standalone' = 'Private server'; '--server' = 'Server URL'; '--sanitize' = 'Redact sensitive transcripts and file data' } }
'import' { $cmdFlags = @{ '--standalone' = 'Private server'; '--server' = 'Server URL'; '--directory' = 'Target directory for session import' } }
}
}
}
'service' {
$subchoices = @{
'start' = 'Start the background server'
'restart' = 'Restart the background server'
'status' = 'Show background server status'
'stop' = 'Stop the background server'
'get' = 'Get service configuration'
'set' = 'Set service configuration'
'unset' = 'Unset service configuration'
}
if ($subTokens.Count -eq 0 -and $wordToComplete -notlike '-*') {
return $subchoices.GetEnumerator() |
Where-Object { $_.Key -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_.Key, $_.Key, 'Command', $_.Value) }
}
}
# Single-level commands
'upgrade' { $cmdFlags = @{ '--method' = 'Installation method'; '-m' = 'Installation method' } }
'update' { $cmdFlags = @{ '--method' = 'Installation method'; '-m' = 'Installation method' } }
'uninstall' { $cmdFlags = @{ '--dry-run' = 'Preview files without removing'; '--force' = 'Skip confirmation prompts'; '-f' = 'Skip confirmation prompts' } }
'acp' { $cmdFlags = @{ '--login' = 'Run auth login instead of starting server' } }
'api' { $cmdFlags = @{ '--standalone' = 'Private server'; '--server' = 'Server URL'; '--data' = 'Request body'; '-d' = 'Request body'; '--header' = 'Header (name:value)'; '-H' = 'Header (name:value)'; '--param' = 'OpenAPI parameter (key=value)' } }
'models' { $cmdFlags = @{ '--standalone' = 'Private server'; '--server' = 'Server URL' } }
'reload' { $cmdFlags = @{ '--standalone' = 'Private server'; '--server' = 'Server URL' } }
'pair' { $cmdFlags = @{ '--url' = 'External HTTP(S) server URL'; '--remote' = 'Pair through OpenTunnel remote address' } }
'serve' {
$cmdFlags = @{
'--hostname' = 'Hostname address ([::1], localhost, 127.0.0.1)'
'--port' = 'Port to listen on (defaults to 49374)'
'--cors' = 'Additional allowed CORS origin'
'--service' = 'Only starts the service'
'--stdio' = 'Pipes stdin/stdout and bypasses TUI for editor integrations'
}
}
'stats' {
$cmdFlags = @{
'--standalone' = 'Private server'; '--server' = 'Server URL'; '--days' = 'Show last N days (0 is today)';
'--year' = 'Calendar year'; '--all' = 'Lifetime statistics'; '--project' = 'Filter by project ID or .';
'--models' = 'Show model usage'; '--tools' = 'Show tool reliability'; '--cost' = 'Show cost & token details';
'--full' = 'Show every detailed section'; '--limit' = 'Row limit'; '--json' = 'Output as JSON'
}
}
'mini' {
$cmdFlags = @{
'--standalone' = 'Private server'; '--server' = 'Server URL'; '--continue' = 'Continue last session'; '-c' = 'Continue last session';
'--session' = 'Session ID'; '-s' = 'Session ID'; '--fork' = 'Fork session when continuing';
'--replay' = 'Restore history on resume/resize'; '--no-replay' = 'Disable history restore on resume/resize';
'--replay-limit' = 'Limit replay count'; '--model' = 'Model (provider/model)'; '-m' = 'Model (provider/model)';
'--agent' = 'Agent to use'; '--prompt' = 'Prompt to use'
}
}
'run' {
$cmdFlags = @{
'--standalone' = 'Private server'; '--server' = 'Server URL'; '--continue' = 'Continue last session'; '-c' = 'Continue last session';
'--session' = 'Session ID'; '-s' = 'Session ID'; '--fork' = 'Fork session before continuing';
'--model' = 'Model (provider/model#variant)'; '-m' = 'Model (provider/model#variant)';
'--agent' = 'Agent to use'; '--format' = 'Output format (default, json)'; '--file' = 'Attach file'; '-f' = 'Attach file';
'--title' = 'Session title'; '--thinking' = 'Show thinking blocks'; '--auto' = 'Auto-approve non-denied permissions'
}
}
}
# Merge global flags and command flags
$allFlags = [ordered]@{}
foreach ($k in $cmdFlags.Keys) { $allFlags[$k] = $cmdFlags[$k] }
foreach ($k in $globalFlags.Keys) { $allFlags[$k] = $globalFlags[$k] }
return $allFlags.GetEnumerator() |
Where-Object { $_.Key -like "$wordToComplete*" } |
ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_.Key, $_.Key, 'ParameterName', $_.Value)
}
}
# 4. TOP-LEVEL AUTOCOMPLETE (First token after 'opencode')
$topLevelFlags = [ordered]@{
'--standalone' = 'Run with a private server instead of the background service'
'--server' = 'Connect to a server URL instead of the background service'
'--auto' = 'Auto-approve permissions that are not explicitly denied'
'--continue' = 'Continue the last session'
'-c' = 'Continue the last session'
'--session' = 'Session ID to continue or create'
'-s' = 'Session ID to continue or create'
'--prompt' = 'Prompt to use'
}
foreach ($k in $globalFlags.Keys) { $topLevelFlags[$k] = $globalFlags[$k] }
if ($wordToComplete -like '-*') {
return $topLevelFlags.GetEnumerator() |
Where-Object { $_.Key -like "$wordToComplete*" } |
ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_.Key, $_.Key, 'ParameterName', $_.Value)
}
} else {
# Suggest subcommands
$cmdResults = $topLevelSubcommands.GetEnumerator() |
Where-Object { $_.Key -like "$wordToComplete*" } |
ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_.Key, $_.Key, 'Command', $_.Value)
}
# Also suggest local directories for "opencode [<directory>]"
$dirResults = Get-ChildItem -Directory -ErrorAction SilentlyContinue |
Where-Object { $_.Name -like "$wordToComplete*" } |
ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_.Name, $_.Name, 'ProviderContainer', "Directory: $($_.FullName)")
}
return @($cmdResults) + @($dirResults)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment