Skip to main content

Overview

Commands are registered with .command(), which accepts a name and a definition object containing schemas, metadata, and a run handler.

Registering Commands

Chain .command() calls to register multiple commands:

Command Definition Structure

A command definition includes schemas for inputs, output, and the handler function.

Required Fields

run
function
required
The command handler. Receives a context object with parsed args, options, env, and helper functions. Can return a value, a Promise, or an AsyncGenerator for streaming.

Input Schemas

args
z.ZodObject<any>
Zod schema for positional arguments. Keys define the order arguments are parsed.
options
z.ZodObject<any>
Zod schema for named options/flags.
env
z.ZodObject<any>
Zod schema for environment variables. Keys are the variable names.
output
z.ZodType
Zod schema for the return value. Validates the data returned from run().

Metadata

description
string
A short description of what the command does. Shown in help output.
alias
Record<string, string>
Map of option names to single-character aliases.
Enables -D as shorthand for --saveDev.
examples
Example[]
Usage examples shown in help output.
hint
string
Plain text hint displayed in help after examples and before global options.

Behavior

format
'toon' | 'json' | 'yaml' | 'md' | 'jsonl'
Default output format for this command. Overrides CLI-level format.
outputPolicy
'all' | 'agent-only'
Controls when output data is displayed. Overrides CLI-level or group-level policy.
middleware
MiddlewareHandler[]
Middleware that runs only for this command, after root and group middleware.

Mounting Sub-CLIs

Mount another CLI instance as a command group by passing it directly to .command():

Run Handler Context

The run function receives a context object with parsed inputs and helpers:

Returning Success

Return a value directly or use c.ok() to attach CTAs:

Returning Errors

Throw an error or use c.error() for structured errors:

Async Handlers

Handlers can be async:

Streaming Handlers

Use async *run to stream chunks incrementally:
With --format jsonl, each chunk becomes {"type":"chunk","data":"..."}. You can also yield objects:
Return c.ok() or c.error() from a streaming handler to attach CTAs:

Command Aliases

Use the alias field to define single-character shortcuts for options:
Short aliases can be stacked (e.g. -fn) when all but the last are boolean flags.

Agent Detection

The c.agent boolean is true when stdout is not a TTY (piped or consumed by an agent). Use it to tailor behavior:

Next Steps

Schemas

Explore Zod schema validation and type inference

Output

Learn about output formats and CTAs