<!-- Markdown twin of https://eugene1g.github.io/effect-handbook/tooling/cli-framework · The Effect 4 Handbook (effect@4.1.4, audited 2026-11-19) · Index: https://eugene1g.github.io/effect-handbook/llms.txt · Modules: https://eugene1g.github.io/effect-handbook/effect-4-modules.md · Agent guide: https://eugene1g.github.io/effect-handbook/reference/agent-guide.md -->

# CLI Framework

**Contents:** [CliConfig](#cliconfig) · [Command](#command) · [Flag](#flag) · [Argument](#argument) · [Param](#param) · [Primitive](#primitive) · [Prompt](#prompt) · [HelpDoc](#helpdoc) · [Completions](#completions) · [CommandSpec](#commandspec) · [GlobalFlag](#globalflag) · [CliError](#clierror) · [CliOutput](#clioutput) · [TerminalCapabilities](#terminalcapabilities)

The CLI modules define parsers, help, completions, prompts, and command handlers as typed values that compose with ordinary Effects and Layers. Import the barrel with `import { Argument, Command, Flag, Prompt } from "effect/cli"`, or use the module paths shown in each section.

> **Warning:** The framework lives under `effect/cli`; pin the Effect version because this surface can change between minor releases. The release-matched [`ai-docs` CLI example](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/70_cli) provides a compact runnable companion.

## CliConfig

`effect/cli/CliConfig` — unstable

A fiber-scoped `Context.Reference` controlling runner-wide CLI behavior. Its service contains the ordered list of built-in global flags installed by `Command.run`; the default is `GlobalFlag.BuiltIns`. Earlier action flags have precedence.

```ts
import { Effect } from "effect"
import { CliConfig, Command, GlobalFlag } from "effect/cli"

const app = Command.make("comp", {}, () => Effect.void)

// Keep help, version, and completions, but do not accept --log-level.
const withoutLogLevel = CliConfig.layer({
  builtIns: GlobalFlag.BuiltIns.filter((flag) => flag !== GlobalFlag.LogLevel)
})

const program = Command.run(app, { version: "1.0.0" }).pipe(
  Effect.provide(withoutLogLevel)
)
```

`CliConfig.make(options)` returns a value merged over the defaults; `CliConfig.layer(options)` provides it for parsing, help generation, and command execution. This only controls built-ins — application-specific global flags still attach with `Command.withGlobalFlags`.

**Reach for it when** embedding a CLI, constraining its global surface, or removing a built-in flag that conflicts with your application.

## Command

`effect/cli/Command` — unstable

A `Command<Name, Input, ContextInput, E, R>` is both a typed description of how to parse a command's flags and arguments and an Effect that yields its parsed input when run. Subcommands can `yield* parentCommand` inside their handlers to read the parent's typed config without prop-drilling.

Mental model: a command declares what it needs from the CLI (config shape), what it returns (handler Effect), and how it composes with siblings (subcommands) and ancestors (shared flags). `Command.make(name, config, handler)` is the constructor; all other methods decorate it.

Flags declared with `Command.withSharedFlags` are visible to every subcommand handler; a subcommand reads them via `const root = yield* comp`.

```ts
import { NodeRuntime, NodeServices } from "@effect/platform-node"
import { Console, Effect } from "effect"
import { Argument, Command, Flag } from "effect/cli"

// Reusable flag — share it across commands
const outputFormat = Flag.Literals("format", ["table", "json", "csv"]).pipe(
  Flag.withAlias("f"),
  Flag.withDescription("Output format for results"),
  Flag.withDefault("table" as const)
)

// Root command: declares shared flags visible to all subcommands
const comp = Command.make("comp").pipe(
  Command.withSharedFlags({
    format: outputFormat,
    verbose: Flag.Boolean("verbose").pipe(
      Flag.withAlias("v"),
      Flag.withDescription("Print diagnostic output"),
      Flag.withDefault(false) // an omitted boolean flag is otherwise a MissingOption error
    )
  }),
  Command.withDescription("Compensation administration CLI")
)

// Subcommand: grant equity to an employee
const grant = Command.make(
  "grant",
  {
    employee: Flag.String("employee").pipe(
      Flag.withAlias("e"),
      Flag.withDescription("Employee ID (e.g. e-42)")
    ),
    shares: Flag.Int("shares").pipe(
      Flag.withDescription("Number of RSU shares to grant")
    ),
    cliff: Flag.String("cliff").pipe(
      Flag.withDescription("Cliff period, e.g. 12mo"),
      Flag.withDefault("12mo")
    )
  },
  Effect.fn(function*({ employee, shares, cliff }) {
    // Access parent's shared flags by yielding the parent command
    const root = yield* comp
    if (root.verbose) {
      yield* Console.log(`format=${root.format} action=grant`)
    }
    yield* Console.log(
      `Granted ${shares} RSUs to ${employee} with ${cliff} cliff`
    )
  })
).pipe(
  Command.withDescription("Grant equity (RSUs) to an employee"),
  Command.withExamples([
    {
      command: "comp grant --employee e-42 --shares 1000 --cliff 12mo",
      description: "Grant 1 000 RSUs to employee e-42 with a 12-month cliff"
    }
  ])
)

// Subcommand: start a merit review cycle
const reviewStart = Command.make(
  "start",
  {
    cycle: Flag.String("cycle").pipe(
      Flag.withDescription("Merit cycle ID, e.g. 2025-Q1"),
      Flag.withDefault("current")
    ),
    budget: Flag.Int("budget").pipe(
      Flag.withDescription("Approved merit budget in USD")
    )
  },
  Effect.fn(function*({ cycle, budget }) {
    const root = yield* comp
    if (root.verbose) {
      yield* Console.log(`format=${root.format} action=review/start`)
    }
    yield* Console.log(`Merit review cycle "${cycle}" started — budget $${budget}`)
  })
).pipe(
  Command.withDescription("Start a new merit review cycle"),
  Command.withAlias("s")   // comp review s --budget 500000
)

// Group review actions under a "review" parent subcommand
const review = Command.make("review").pipe(
  Command.withDescription("Manage merit review cycles"),
  Command.withSubcommands([reviewStart])
)

// Wire subcommands and run
comp.pipe(
  Command.withSubcommands([grant, review]),
  Command.run({ version: "1.0.0" }),
  Effect.provide(NodeServices.layer),
  NodeRuntime.runMain
)
```

> **Tip:** Use `Command.withSharedFlags` for typed values that child handlers read by yielding their parent command. Use `Command.withGlobalFlags` for runner-wide actions or settings rather than ordinary parsed command input.

### Key combinators

| Combinator | Purpose |
| --- | --- |
| `Command.make(name, config, handler)` | Constructor — name + typed config + optional inline handler |
| `Command.withHandler(fn)` | Attach or replace the handler after construction; the command keeps its existing error type, so validation errors and a replaced handler's errors stay in `E` |
| `Command.withSubcommands([...])` | Register child commands (union of their errors/requirements flows up) |
| `Command.withSharedFlags({...})` | Parent flags visible inside all subcommand handlers |
| `Command.withGlobalFlags([...])` | Attach `GlobalFlag` instances (settings, not shared input) |
| `Command.withDescription(s)` | Long description shown in `--help` |
| `Command.withShortDescription(s)` | One-liner shown in parent's subcommand list |
| `Command.withAlias(s)` | Alternate invocation name (`review start` → `review s`) |
| `Command.unlisted` | Keep a command invocable but omit it from normal listings/help |
| `Command.withExamples([...])` | Curated examples shown at the bottom of `--help`; pass `({ commandPath }) => [...]` to derive them from where the command is mounted |
| `Command.validate(f)` | Check the parsed input before the handler runs (for example mutually exclusive flags). A `CliError` such as `CliError.ValidationError` is shown with help like a parse error; any other error is reported like a handler failure and added to the command's error type (see [below](#validating-input-across-flags)) |
| `Command.provide(layer)` | Provide a Layer to the handler (static or derived from parsed input) |
| `Command.provideEffect(effect)` | Run an effect before the handler and provide its result as a service |
| `Command.run({ version })` | Convert to a runnable `Effect` (reads argv from `Stdio`) |
| `Command.runWith(cmd, cfg)(args)` | Run with an explicit `string[]` — great for testing |

> **Testing:** `Command.runWith(rootCmd, { version: "1.0.0" })(["grant", "--employee", "e-42", "--shares", "1000"])` runs against explicit `argv`. Its requirements always include `Command.Environment`, so provide `NodeServices.layer` or the in-memory environment shown below.

### Validating input across flags

`Command.validate(f)` receives the same input as the handler, with defaults, prompts, and wizard answers already applied. Validations run in the order they were added, stop at the first failure, and survive a later `withHandler`. Added after `withSharedFlags`, a validation sees the shared flags; added after `withSubcommands`, it also runs when a subcommand is selected. The error decides how the failure is reported:

| Validation fails with | Reported as |
| --- | --- |
| a `CliError`, usually `CliError.ValidationError({ message })` | a usage mistake: `Command.run` prints the help and the message, then fails with `ShowHelp` |
| any other error | a handler failure: no help, the original error reaches the caller, its `CliError.userMessage` (if any) is rendered unless `renderErrors` is `false`, and its type is added to the command's `E` |

```ts
import { Effect, Option, Schema } from "effect"
import { CliError, Command, Flag } from "effect/cli"

class ConflictingSources extends Schema.TaggedError<ConflictingSources>()("ConflictingSources", {}) {
  override get [CliError.userMessage]() {
    return "--plan-file and --plan-url cannot be used together"
  }
}

export const importPlan = Command.make(
  "import",
  {
    planFile: Flag.String("plan-file").pipe(Flag.optional),
    planUrl: Flag.String("plan-url").pipe(Flag.optional)
  },
  ({ planFile, planUrl }) => Effect.log("importing", Option.orElse(planFile, () => planUrl))
).pipe(
  // A usage mistake: shown with the command help.
  Command.validate(({ planFile, planUrl }) =>
    Option.isNone(planFile) && Option.isNone(planUrl)
      ? Effect.fail(new CliError.ValidationError({ message: "pass --plan-file or --plan-url" }))
      : Effect.void
  ),
  // A domain error: no help, and the command's error type becomes ConflictingSources.
  Command.validate(({ planFile, planUrl }) =>
    Option.isSome(planFile) && Option.isSome(planUrl) ? Effect.fail(new ConflictingSources()) : Effect.void
  )
)
```

Use your own tagged errors when the caller must tell failures apart, for example to map them to exit codes or JSON output. To tell an omitted flag from one passed with its default value (`--force=false`), declare it with `Flag.optional` and apply the default in the handler; once `withDefault` or a config fallback has filled the value in, presence is lost.

> **Migration:** `Command.withHandler` keeps the command's existing error type instead of replacing it with the new handler's. Code that annotates such a command with a narrower error type must widen the annotation, or pass the final handler to `Command.make` instead.

### Testing a command

`Command.runWith` is the seam: it takes explicit arguments, requires the same `Command.Environment` services as production (`FileSystem`, `Path`, `Terminal`, `Stdio`, `ChildProcessSpawner` — all supplied by `NodeServices.layer`), and writes help, version, and rendered errors through Effect's `Console` service. Inside `it.effect` that output lands in `TestConsole`, so a CLI test needs no process spawn and no stdout scraping.

```ts
import { NodeServices } from "@effect/platform-node"
import { assert, it } from "@effect/vitest"
import { Console, Effect, Result } from "effect"
import { Command, Flag } from "effect/cli"
import { TestConsole } from "effect/testing"

const grant = Command.make(
  "grant",
  { employee: Flag.String("employee"), shares: Flag.Int("shares") },
  ({ employee, shares }) => Console.log(`Granted ${shares} RSUs to ${employee}`)
)

const run = Command.runWith(grant, { version: "1.0.0" })

it.effect("runs the handler with parsed input", () =>
  Effect.gen(function*() {
    yield* run(["--employee", "e-42", "--shares", "1000"])
    assert.deepStrictEqual(yield* TestConsole.logLines, ["Granted 1000 RSUs to e-42"])
  }).pipe(Effect.provide(NodeServices.layer)))

it.effect("a bad value fails with ShowHelp carrying the structured cause", () =>
  Effect.gen(function*() {
    const result = yield* Effect.result(run(["--employee", "e-42", "--shares", "many"]))

    assert.isTrue(Result.isFailure(result))
    if (Result.isFailure(result) && result.failure._tag === "ShowHelp") {
      const [first] = result.failure.errors
      assert.strictEqual(first?._tag, "InvalidValue")
      assert.strictEqual(first?._tag === "InvalidValue" ? first.option : undefined, "shares")
    } else {
      assert.fail("expected a ShowHelp failure")
    }
    // Usage went to Console.log, the rendered error to Console.error.
    assert.strictEqual((yield* TestConsole.errorLines).length, 1)
  }).pipe(Effect.provide(NodeServices.layer)))
```

`NodeServices.layer` gives the command the real filesystem and terminal. When a test must be hermetic — no disk, no TTY, no child processes — assemble the environment from the in-memory pieces instead; the stubs below turn an unexpected terminal read or process spawn into a defect. A custom `Terminal.make` must supply every member, including `size` (a scoped queue of `{ columns, rows }` that starts with the current dimensions and receives each resize):

```ts
import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from "effect"
import { ChildProcessSpawner } from "effect/process"

export const CliTestEnvironment = Layer.mergeAll(
  FileSystem.layerNoop({}), // operations you do not supply fail as NotFound (or die); `exists` answers false
  Path.layer,
  Stdio.layerTest({}),
  Layer.succeed(Terminal.Terminal, Terminal.make({
    columns: Effect.succeed(80),
    rows: Effect.succeed(24),
    size: Effect.die("this command must not watch the terminal size"),
    readInput: Effect.die("this command must not read keys"),
    readLine: Effect.die("this command must not prompt"),
    display: () => Effect.void
  })),
  Layer.succeed(
    ChildProcessSpawner.ChildProcessSpawner,
    ChildProcessSpawner.make(() => Effect.die("this command must not spawn processes"))
  )
)
```

| What this proves | What it does not prove |
| --- | --- |
| parsing, defaults, fallbacks, handler wiring, and the typed failure for bad input | that the packaged binary starts, reads real `argv`, and exits with the right status — launch the built artifact once for that (see [Testing an Effect Application](../deep-dives/testing-an-effect-application.md#the-built-artifact-lane)) |

Assert on the structured error, not on the rendered help text: help tables are aligned by terminal display width (wide, emoji, combining, and zero-width graphemes), so exact column spacing is a formatter detail. Pass `{ renderErrors: false }` when the embedding host owns error rendering; help documents are still printed. To suppress or redirect the built-in help, version, and invalid-invocation output itself, provide a [`CliOutput.Presenter`](#clioutput).

Use when you need a type-safe CLI application with subcommands, help generation, and shell completions.

## Flag

`effect/cli/Flag` — unstable

A `Flag<A>` is a typed parser for named CLI options (`--verbose`, `--shares 1000`). Flags are composable: chain `Flag.withDefault` to make optional, `Flag.optional` to get `Option<A>`, `Flag.withFallbackConfig` to satisfy from an environment variable when absent. Boolean flags: `--dry-run` alone means `true`; `--no-dry-run` negates it — rename that form with `Flag.withNegation("skip-dry-run")` or remove it with `Flag.withoutNegation` (both also change shell completions). An **omitted** boolean flag is not an implicit `false`: like every other flag it fails with `CliError.MissingOption` unless you add `Flag.withDefault(false)`, `Flag.optional`, or a config/prompt fallback. That makes absence uniform across flag types and lets a fallback chain decide it. The built-in global flags add their own `false` default.

```ts
import { Config } from "effect"
import { Flag, Prompt } from "effect/cli"

// Boolean: --dry-run / --no-dry-run
const dryRun = Flag.Boolean("dry-run").pipe(
  Flag.withAlias("n"),
  Flag.withDescription("Simulate without writing changes"),
  Flag.withDefault(false) // required when omitted unless given a default, optional, or fallback
)

// Integer: number of RSU shares
const shares = Flag.Int("shares").pipe(
  Flag.withAlias("s"),
  Flag.withDescription("Number of RSU shares"),
  Flag.withDefault(500)
)

// Constrained enum: target merit cycle
const cycleKind = Flag.Literals("kind", ["rsu", "option", "bonus"]).pipe(
  Flag.withDescription("Grant type"),
  Flag.withDefault("rsu" as const)
)

// Fall back to an env-var when the flag is absent
const hrisToken = Flag.String("hris-token").pipe(
  Flag.withFallbackConfig(Config.String("HRIS_API_TOKEN"))
)

// Redacted string — value is masked in help and logs
const apiSecret = Flag.Redacted("api-secret")

// Optional — yields Option<string>, None when omitted
const note = Flag.String("note").pipe(Flag.optional)

// Key-value map: --label team=eng --label region=us -> Record<string, string>
const labels = Flag.KeyValuePair("label").pipe(
  Flag.withDescription("Attach metadata labels to the grant")
)

// Fall back to an interactive prompt when the flag is absent and the terminal can prompt.
// Pass the Prompt directly — no callback wrapper needed.
const employeeId = Flag.String("employee").pipe(
  Flag.withFallbackPrompt(
    Prompt.String({ message: "Employee ID: " })
  )
)
```

### Flag constructors at a glance

Key APIs: Flag.String, Flag.Boolean, Flag.Int, Flag.Finite, Flag.Date, Flag.Literals, Flag.ChoiceWithValue, Flag.Path, Flag.File, Flag.Directory, Flag.Redacted, Flag.FileText, Flag.FileParse, Flag.FileSchema, Flag.KeyValuePair

### Validation, alternatives, and awkward values

```ts
import { Schema } from "effect"
import { Flag } from "effect/cli"

// Validate or transform the parsed string with any Schema: bad input is a parse error,
// so the handler only ever sees a valid value.
const Email = Schema.String.check(
  Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, { message: "Expected an email address" })
)
const approver = Flag.String("approver").pipe(Flag.withSchema(Email))

// Alternatives: try --plan-file, then --plan-url. The result is a union...
const planSource = Flag.File("plan-file").pipe(
  Flag.orElse(() => Flag.String("plan-url"))
)

// ...or a Result that records WHICH flag supplied the value.
const planSourceTagged = Flag.File("plan-file").pipe(
  Flag.orElseResult(() => Flag.String("plan-url"))
)

// An alternative chain can be optional as a whole: None when neither flag is present.
const optionalPlanSource = Flag.File("plan-file").pipe(
  Flag.orElse(() => Flag.String("plan-url")),
  Flag.optional
)

const _ = [approver, planSource, planSourceTagged, optionalPlanSource]
```

| Situation | Behavior |
| --- | --- |
| Neither flag of an `orElse` chain is given | the chain fails with `MissingOption` naming the *last* alternative; wrap it in `Flag.optional` or `Flag.withDefault` to make absence legal |
| A `KeyValuePair` value contains `=` | only the first `=` splits: `--label note=a=b` yields `{ note: "a=b" }` |
| A value begins with `-` and parses as a number (`-3`, `-3.70`, `-2e5`) | parses as a value either way: `--delta -5` and `--delta=-5` both set `delta` to `-5` |
| A value begins with `-` but is not numeric, such as a string flag value of `-x` | write it inline: `--label=-x`. The spaced form `--label -x` reads `-x` as another flag and fails with `UnrecognizedOption` |
| A boolean flag is omitted | `MissingOption`, unless the flag has a default, is optional, or has a fallback |
| A single-valued flag is given twice (`--shares 1 --shares 2`) | rejected with `InvalidValue` (expected "at most 1 value") instead of keeping the first; use `Flag.atLeast`, `Flag.atMost`, or `Flag.between` to accept repeats. `KeyValuePair` flags still merge their occurrences |
| A short cluster with an inline value (`-vn=3`) | split into `-v -n=3`; a single dash before a multi-character name (`-num=3`) is split the same way, so write `--num=3` |
| `--=value` | passed through as a plain value, not an empty-named flag |

### GNU-style optional flag values

`Flag.withOptionalValue(rawValue)` lets a **present** flag omit its value. The raw string is parsed and validated by the original flag. It does not make the flag itself optional; add `Flag.optional` or `withDefault` for absence.

```ts
import { Flag } from "effect/cli"

const color = Flag.Literals("color", ["auto", "always", "never"]).pipe(
  Flag.withOptionalValue("auto"),
  Flag.optional
)
// --color        -> Some("auto")
// --color=never  -> Some("never")
// absent         -> None
```

Explicit values **must use `=`**, including a short alias (`-c=never`). `--color never` leaves `never` for positional/subcommand parsing; the flag never consumes the next token. Help renders an optional-value form such as `--color [=choice]`.

**Metadata for documentation tools.** `Flag.annotate(key, value)` (and `Argument.annotate`) attaches a value under a `Context.Key`, for facts the parser cannot know, such as the environment variable behind a `withFallbackConfig` or a deprecation note. Annotations never affect parsing, help, or completions, and survive combinators applied before or after them; [`CommandSpec`](#commandspec) reports them.

Use when you need named `--` options for type-safe command configuration.

## Argument

`effect/cli/Argument` — unstable

Positional command-line arguments — values without a `--name` prefix. `Argument<A>` is structurally identical to `Flag<A>` with nearly the same constructor surface; the distinction is named vs positional.

Arguments resolve in declaration order. `Argument.variadic` collects all remaining positionals into an array. Only one variadic argument is allowed per command, and it must be last.

```ts
import { Argument } from "effect/cli"

// Required positional: the employee ID to look up
const employeeArg = Argument.String("employee-id").pipe(
  Argument.withDescription("Employee ID (e.g. e-42)")
)

// Optional positional: an output file path
const outFile = Argument.String("output-file").pipe(
  Argument.optional   // yields Option<string>
)

// Variadic — collect zero or more employee IDs for a bulk operation
const employeeIds = Argument.String("employee-ids").pipe(
  Argument.variadic,
  Argument.withDescription("Employee IDs to process")
)

// Read a comp-plan JSON file directly from a positional path
const planFile = Argument.FileText("plan-path").pipe(
  Argument.withDescription("Path to the comp plan JSON file")
)

// Parse positional as a chosen enum value
const reviewAction = Argument.Literals("action", ["start", "close", "reopen"])
```

> **Tip:** Options can appear before or after positional arguments: both `comp grant e-42 --shares 1000` and `comp grant --shares 1000 e-42` are accepted.

Variadic bounds and defaults interact. `Argument.variadic` accepts zero or more values, so omission already parses — to `[]` — and a `withDefault` placed after it never applies. Require at least one value, and the default becomes reachable:

```ts
import { Argument } from "effect/cli"

// Omitted -> [] (the default below is dead code)
const anyIds = Argument.String("employee-id").pipe(
  Argument.variadic,
  Argument.withDefault(["all"])
)

// Omitted -> ["all"]; given -> one or more ids
const idsOrAll = Argument.String("employee-id").pipe(
  Argument.atLeast(1),
  Argument.withDefault(["all"])
)

// Bounded: between one and five ids, no default
const fewIds = Argument.String("employee-id").pipe(Argument.between(1, 5))

const _ = [anyIds, idsOrAll, fewIds]
```

Use when the natural invocation uses positional subjects (file paths, resource IDs) rather than `--name <value>` flags.

## Param

`effect/cli/Param` — unstable

The shared machinery powering both `Flag` and `Argument`. A `Param<Kind, A>` carries a `Kind` type tag (`"flag"` or `"argument"`) determining tokenisation. All combinators (`withDefault`, `optional`, `map`, `mapEffect`, `filter`, `withFallbackConfig`, `withFallbackPrompt`, `withSchema`) are implemented once in `Param` and re-exported by both `Flag` and `Argument` (`variadic` is on `Argument` only).

Rarely imported directly in application code — use `Flag` and `Argument` instead. Relevant when building custom param combinators or reading the parsing internals.

- **Param.Single** — Leaf param backed by one `Primitive` value parser. Has a name, optional aliases, optional metavar for help text.

- **Param.Map / Transform** — Wraps a param with a pure or effectful transformation; implements `Flag.map`, `Flag.mapEffect`, `Flag.filter`.

- **Param.Optional** — Wraps a param, changing its result from `A` to `Option<A>`. Succeeds with `None` when the token is absent.

- **Param.Variadic** — Allows a param to appear 0–N (or min–max) times, collecting results into `ReadonlyArray<A>`.

`Param.annotate(key, value)` is the shared implementation of `Flag.annotate` and `Argument.annotate`; the values live on each `Single` node's `annotations`. `withDefault`, `withFallbackConfig`, and `withFallbackPrompt` record a structural `Param.Fallback` on their `Transform` node without evaluating it: `{ _tag: "Default", value }` for a literal default, and only the kind (`"DefaultEffect"`, `"Config"`, `"Prompt"`) for fallbacks that would have to run to be inspected. [`CommandSpec`](#commandspec) reads both.

Use when building abstractions over the CLI library — custom combinators that work for both flags and arguments, or inspecting param structure for documentation generation.

## Primitive

`effect/cli/Primitive` — unstable

Leaf-level value parsers converting raw CLI strings into typed TypeScript values. Each `Flag.*` and `Argument.*` constructor wraps a `Primitive`. A `Primitive<A>` is essentially `(rawString: string) => Effect<A>` with a display name; the framework derives shell completion types from `_tag`.

- **Primitive.String** — Identity: accepts any string.

- **Primitive.Boolean** — Accepts `true/false/yes/no/on/off/1/0`. Recognises `--no-<flag>` canonical negation.

- **Primitive.Int / Primitive.Finite** — Schema-validated numeric parsers. Produces a structured `InvalidValue` error on bad input.

- **Primitive.Date** — Parses ISO-8601 date strings into `Date`.

- **Primitive.Choice** — Restricts value to a fixed string set; drives completion script's value list.

- **Primitive.Path** — `Primitive.Path(pathType, mustExist?)` validates existence and type (`file | directory | either`) against the real filesystem at parse time.

- **Primitive.Redacted** — Returns `Redacted<string>`; masked in help output and Effect logging.

- **Primitive.FileText / FileParse / FileSchema** — Reads a file at the given path and returns its text, parsed INI/JSON/TOML/YAML, or Schema-decoded value. `FileParse()` infers from `.ini`, `.json`, `.toml`, `.yaml`, or `.yml`; `{ format }` overrides detection.

- **Primitive.KeyValuePair** — Parses `KEY=VALUE` pairs; multiple appearances merge into `Record<string, string>`. Only the first `=` separates key from value, so values may themselves contain `=`.

Use when inspecting what type a flag or argument represents (e.g. documentation generation or custom completion logic) — `_tag` is the canonical discriminant.

## Prompt

`effect/cli/Prompt` — unstable

Interactive terminal prompts. A `Prompt<A>` is an Effect that runs a TUI render loop and yields a typed value on confirmation. Prompts compose with `Effect.gen`, chain with `Prompt.flatMap`, and collect with `Prompt.all`.

Each prompt has three phases: render (write ANSI), process (receive keypress, return next state or final value), clear (erase frame). The CLI connection is `Flag.withFallbackPrompt` (and `Argument.withFallbackPrompt`): when a required flag is absent, the prompt runs automatically — but only when [`TerminalCapabilities`](#terminalcapabilities) reports `canPrompt`. Otherwise the prompt is not built or shown and the parse fails with the original `MissingOption` / `MissingArgument`, so a CI job or piped invocation fails instead of hanging. Pass the `Prompt` or an `Effect` yielding one directly.

Prompts and the command wizard respect `NO_COLOR`, suppressing color/style escapes but retaining cursor and redraw controls: this is not a plain non-interactive transcript mode. Terminal input is acquired only when a prompt needs user input, so constant fallback prompts leave piped stdin untouched.

```ts
import { Effect } from "effect"
import { Flag, Prompt } from "effect/cli"

// Text input — for capturing an employee's new title on promotion
const titlePrompt = Prompt.String({ message: "New job title: " })

// Password — masked input for the HRIS API token
const hrisTokenPrompt = Prompt.Password({ message: "HRIS API token: " })

// Yes/No confirm — guard a raise that exceeds the pay band
const confirmAboveBand = Prompt.Confirm({
  message: "Salary exceeds band midpoint by > 20%. Proceed anyway?",
  initial: false
})

// Select from a list — choose a performance rating
const ratingPrompt = Prompt.Select({
  message: "Performance rating",
  choices: [
    { title: "Exceeds expectations", value: "exceeds" },
    { title: "Meets expectations",   value: "meets" },
    { title: "Below expectations",   value: "below" }
  ]
})

// Toggle — approve or reject a raise recommendation
const approvalToggle = Prompt.Toggle({
  message: "Approve raise recommendation?",
  active: "approve",
  inactive: "reject",
  initial: true
})

// Multi-select — pick which comp components to adjust
const componentsPrompt = Prompt.MultiSelect({
  message: "Adjust compensation components",
  choices: [
    { title: "Base salary",  value: "base" },
    { title: "Bonus target", value: "bonus" },
    { title: "RSU grant",    value: "equity" }
  ]
})

// Chain prompts: an interactive raise-approval wizard
const raiseWizard = Effect.gen(function*() {
  const rating   = yield* ratingPrompt
  const approved = yield* approvalToggle
  if (approved) {
    const aboveBand = yield* confirmAboveBand
    return { rating, approved, aboveBand }
  }
  return { rating, approved, aboveBand: false }
})

// Fallback prompt on a flag: if --employee is omitted, the prompt fires.
// Pass the Prompt directly — no callback wrapper.
const employeeFlag = Flag.String("employee").pipe(
  Flag.withFallbackPrompt(Prompt.String({ message: "Employee ID: " }))
)
```

### Built-in prompt types

Key APIs: Prompt.String, Prompt.Password, Prompt.Hidden, Prompt.Confirm, Prompt.Select, Prompt.AutoComplete, Prompt.MultiSelect, Prompt.Toggle, Prompt.Int, Prompt.Number, Prompt.Date, Prompt.List, Prompt.File, Prompt.Custom

> **Example:** The `employeeFlag` above accepts `--employee e-42`; when the flag is omitted, it asks for the employee id interactively.

### Theming prompts

Prompt symbols and colors come from one `Prompt.Theme` — a `Context.Reference` whose default is built by `Prompt.makeTheme()` from platform-appropriate glyphs (Windows-specific fallbacks, not exclusively ASCII). Provide it once to restyle every prompt in the application; pass a partial `theme` to a single prompt to override it there. The per-prompt option wins over the context value.

```ts
import { Effect } from "effect"
import { Prompt } from "effect/cli"

// A message-less Select shows only the choices. AutoComplete still requires one.
const cyclePrompt = Prompt.Select({
  choices: [
    { title: "FY27 merit cycle", value: "fy27" },
    { title: "FY27 mid-year adjustment", value: "fy27-mid" }
  ]
})

// One prompt with a local override: a different mask character for this secret only.
const tokenPrompt = Prompt.Password({
  message: "HRIS API token",
  theme: { passwordMask: "•" }
})

const wizard = Effect.gen(function*() {
  const cycle = yield* cyclePrompt
  const token = yield* tokenPrompt
  return { cycle, token }
})

// Application-wide theme: plain ASCII markers for a terminal without Unicode glyphs.
const asciiTheme = Prompt.makeTheme({
  prefix: ">",
  pointer: ">",
  tick: "ok",
  checkboxOn: "[x]",
  checkboxOff: "[ ]"
})

const themedWizard = wizard.pipe(Effect.provideService(Prompt.Theme, asciiTheme))
```

Theme fields: `prefix`, `pointer`, `pointerSmall`, `ellipsis`, `tick`, `arrowUp`, `arrowDown`, `checkboxOn`, `checkboxOff`, `descriptionSeparator`, `passwordMask`, `toggleSeparator`, and the colors `primaryColor`, `mutedColor`, `successColor`, `errorColor`, `submittedColor`. Setting a symbol to the empty string removes both the symbol and its adjacent spacing.

Notable current prompt behavior: `Prompt.Select` and `Prompt.MultiSelect` without a `message` show only the choices and, on submit, a tick followed by the selected titles; `Prompt.Date` does not carry typed digits into the next field on Tab, including when navigation wraps; and `Prompt.AutoComplete` and `Prompt.File` do not swallow `j` and `k` while a filter query is being typed.

Use when you want wizard-style interactive CLIs or need to prompt for a required value absent from the environment.

## HelpDoc

`effect/cli/HelpDoc` — unstable

The intermediate data structure for a command's help page. Captures description, usage line, flag/argument docs, inherited and global flag docs, subcommand listing, and examples — before any string formatting. Shared flags declared on ancestor commands arrive in `inheritedFlags` (rendered as an `INHERITED FLAGS` section), not in `flags`; `commandPath` and `globalFlagsScope` record where the command and its global flags are declared. Rendering is delegated to `CliOutput.Formatter`.

`HelpDoc` is to `--help` output what `Schema` is to JSON serialization: a structured description renderable multiple ways (plain text, ANSI, Markdown, JSON). The CLI framework builds it automatically from the command tree; inspect or transform it for custom tooling.

```ts
import { Context, Option as O } from "effect"
import type { HelpDoc } from "effect/cli"

// HelpDoc is plain data — construct it manually for testing or tooling.
// Note: subcommands is ReadonlyArray<HelpDoc.SubcommandGroupDoc>, not a flat list.
const grantCommandHelp: HelpDoc.HelpDoc = {
  description: "Grant RSUs or options to an employee",
  usage: "comp grant [options]",
  annotations: Context.empty(),
  flags: [
    {
      name: "employee",
      aliases: ["-e"],
      type: "string",
      description: O.some("Employee ID (e.g. e-42)"),
      required: true
    },
    {
      name: "shares",
      aliases: ["-s"],
      type: "integer",
      description: O.some("Number of RSU shares to grant"),
      required: true
    },
    {
      name: "cliff",
      aliases: [],
      type: "string",
      description: O.some("Cliff period, e.g. 12mo"),
      required: false
    }
  ],
  args: [],
  globalFlags: [],
  subcommands: [],   // ReadonlyArray<SubcommandGroupDoc>
  examples: [
    {
      command: "comp grant --employee e-42 --shares 1000 --cliff 12mo",
      description: "Grant 1 000 RSUs with a 12-month cliff"
    }
  ]
}
```

The default formatter aligns the flag, argument, and subcommand tables by terminal *display* width rather than string length, so wide characters, emoji, combining marks, and zero-width graphemes in names or descriptions do not skew the columns. A custom formatter that pads with `String.prototype.padEnd` does not get that for free; test on the `HelpDoc` data rather than on padded output.

> **Migration:** a custom formatter that read ancestor shared flags from `HelpDoc.flags` must read them from `HelpDoc.inheritedFlags`.

Use when implementing a custom `CliOutput.Formatter`, generating Markdown documentation from the CLI tree, or building tooling requiring structured access to the help model.

## Completions

`effect/cli/Completions` — unstable

Shell completion script generator. Given a `CommandDescriptor`, `Completions.generate` returns a static completion script string for Bash, Zsh, Fish, or PowerShell (`"powershell"`). The built-in `--completions` flag also accepts `pwsh` as an alias for `powershell`; use the canonical name for programmatic generation.

Rarely called directly. `GlobalFlag.Completions` wires it automatically: `comp --completions bash` prints a script users can source. Completion-aware types (`choice`, `path`, `file`, `directory`) produce richer tab-completion suggestions automatically.

```bash
# Install completions for the comp-admin CLI (once)
comp --completions bash >> ~/.bash_completion
comp --completions zsh  >> ~/.zshrc
comp --completions fish > ~/.config/fish/completions/comp.fish
```

For PowerShell, save `comp --completions powershell > comp-completion.ps1` and dot-source the script from your profile (`. ./comp-completion.ps1`). Regenerate scripts after changing the command tree.

To generate completions programmatically (e.g. in a build script or test), `Completions.fromCommand(command)` converts an existing `Command` tree into a `CommandDescriptor` — the same one `--completions` uses, with shared flags, aliases, and negations, and without hidden flags or unlisted subcommands:

```ts
import { Completions } from "effect/cli"

// Usually derive the descriptor from the command tree itself — handlers never run:
//   Completions.generate("comp", "zsh", Completions.fromCommand(compCommand))
// A hand-written descriptor works too:
const descriptor: Completions.CommandDescriptor = {
  name: "comp",
  description: "Compensation administration CLI",
  flags: [
    {
      name: "format",
      aliases: ["-f"],
      description: "Output format",
      type: { _tag: "Choice", values: ["table", "json", "csv"] }
    }
  ],
  arguments: [],
  subcommands: [
    {
      name: "grant",
      description: "Grant equity to an employee",
      flags: [
        {
          name: "employee",
          aliases: ["-e"],
          description: "Employee ID",
          type: { _tag: "String" }
        },
        {
          name: "shares",
          aliases: ["-s"],
          description: "Number of RSU shares",
          type: { _tag: "Int" }
        },
        {
          name: "cliff",
          aliases: [],
          description: "Cliff period",
          type: { _tag: "String" }
        }
      ],
      arguments: [],
      subcommands: []
    },
    {
      name: "review",
      description: "Manage merit review cycles",
      flags: [],
      arguments: [],
      subcommands: [
        {
          name: "start",
          description: "Start a new merit review cycle",
          flags: [
            {
              name: "budget",
              aliases: [],
              description: "Approved merit budget in USD",
              type: { _tag: "Int" }
            }
          ],
          arguments: [],
          subcommands: []
        }
      ]
    }
  ]
}

const bashScript = Completions.generate("comp", "bash", descriptor)
const zshScript  = Completions.generate("comp", "zsh",  descriptor)
const fishScript = Completions.generate("comp", "fish", descriptor)
```

What the built-in `--completions` flag and `Completions.fromCommand` derive for you — and what a hand-written `CommandDescriptor` must therefore reproduce:

| Behavior | Detail |
| --- | --- |
| Subcommand aliases complete like the canonical name | the generated descriptor lists an aliased subcommand a second time under its alias, with the same flags and nested commands |
| Shared flags reach every descendant | flags declared with `Command.withSharedFlags` are included in each descendant's flag list |
| Choice values survive supported quoting contexts | values containing quotes, spaces, word-break characters, Unicode, or shell metacharacters are escaped for Bash (including Bash 3.2, without associative arrays), Zsh, and Fish; Bash still has partial-quote limitations for `!` inside an already-open double quote and apostrophes inside a mid-word single quote |
| Positional arguments and subcommands coexist in Zsh | a command that has both completes correctly |
| Repeatable flags keep completing | a flag under `Flag.atLeast`, `Flag.between` with a maximum above 1, or a `KeyValuePair` flag is still offered after its first use; the descriptor marks it `repeatable: true`, which a hand-written descriptor must set itself |
| Subcommand names may contain `:` | names such as `test:unit` complete in Bash and Zsh |
| Optional positionals are not required | an argument that is optional, or variadic without a positive minimum (`Argument.variadic`, `Argument.atLeast(0)`), is described as not required |
| `--completions sh` | accepted as an alias for `bash` |

Regenerate installed completion scripts after upgrading Effect; a script generated against an older command tree does not reflect flags or subcommands added since.

Use when you need programmatic completion script access. For normal CLIs, `GlobalFlag.Completions` handles it automatically. For a complete description of a command, including hidden flags and unlisted subcommands, use [`CommandSpec`](#commandspec).

## CommandSpec

`effect/cli/CommandSpec` — unstable

A projection of one command path of a `Command` tree into plain data, for documentation tooling: reference pages, man pages, JSON schemas, or a check that every config fallback is documented. Where [`Completions.fromCommand`](#completions) deliberately drops what a shell should not offer, `CommandSpec` keeps everything: hidden flags and unlisted subcommands are included and marked, primitive types are not collapsed, and each flag says where it is declared.

`CommandSpec.resolve(command, path, { builtIns? })` returns `Option<Spec>`. It is pure and synchronous: it runs no handler, prompt, `Config` lookup, or effectful default. `path` names commands from the root down, root first, exactly like `HelpDoc.commandPath`; only canonical names match, so an alias, an unknown segment, a different root name, or an empty path gives `Option.none()` rather than the nearest ancestor. `builtIns` defaults to `GlobalFlag.BuiltIns`; pass the list from your `CliConfig` when it differs, or `[]` to omit built-ins.

| `Spec` field | Contents |
| --- | --- |
| `path`, `name`, `alias`, `description`, `shortDescription`, `unlisted`, `annotations` | the resolved command; `examples` are resolved for this path |
| `flags` | local flags, then flags inherited through `withSharedFlags` from the root down, then global flags (built-ins first), in help order. A nearer flag hides an inherited one of the same name; a global flag is always listed |
| `arguments` | positional arguments in declaration order |
| `subcommands` | direct children with `name`, `alias`, `group`, `unlisted`, and descriptions; an alias is a field, not an extra entry |

Each flag carries `name`, `aliases` (without dashes), `description`, `hidden`, `type` (one variant per `Primitive`, such as `{ _tag: "Choice", values }` or `{ _tag: "Path", pathType }`), `typeName`, `metavar`, `required`, `fallbacks`, `variadic` (`{ min, max }` or `undefined`), `optionalValue`, `negation` (the effective `no-<name>` form of a boolean flag), `scope` (`Local`, `Inherited` with `declaredBy`, or `Global` with `declaredBy` and `kind`), and the `annotations` set with [`Flag.annotate`](#flag). Arguments carry the same facts except aliases, hidden, optional value, negation, and scope.

- **`required` ignores `Config` and `Prompt` fallbacks.** It says whether parsing fails when the entry is absent and nothing on its own path supplies a value, so a flag with `withFallbackConfig` is still `required`; render it from `fallbacks` as "required unless `$DB_URL` is set". `withDefault` and `optional` clear it, a bare boolean flag is required like any other, and a global action flag is never required.
- **`fallbacks` are structural.** They are `Param.Fallback` values in the order the parser consults them (innermost first): `{ _tag: "Default", value }` for a literal default, and only the kind for `DefaultEffect`, `Config`, and `Prompt`. The config key is not recoverable, which is what `annotate` is for.
- **Transformations are transparent and alternatives are split.** `map`, `withSchema`, and `filter` do not show up; a parameter built with `orElse` yields one entry per alternative, each with its own branch-local `required` and `fallbacks`.

```ts
import { Config, Context, Option } from "effect"
import { Command, CommandSpec, Flag } from "effect/cli"

const EnvVar = Context.Service<never, string>("docs/EnvVar")

const push = Command.make("push", {
  dbUrl: Flag.String("db-url").pipe(
    Flag.withFallbackConfig(Config.String("DB_URL")),
    Flag.annotate(EnvVar, "DB_URL")
  ),
  dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false))
})
const cli = Command.make("app").pipe(Command.withSubcommands([push]))

// One reference-table row per flag of `app push`, without running anything.
export const rows = Option.map(CommandSpec.resolve(cli, ["app", "push"], { builtIns: [] }), (spec) =>
  spec.flags.map((flag) => ({
    flag: `--${flag.name}`,
    type: flag.typeName,
    required: flag.required,
    env: Option.getOrUndefined(Context.getOption(flag.annotations, EnvVar)),
    default: flag.fallbacks.find((fallback) => fallback._tag === "Default")?.value
  }))
)
// Some([{ flag: "--db-url", type: "string", required: true, env: "DB_URL", default: undefined },
//       { flag: "--dry-run", type: "boolean", required: false, env: undefined, default: false }])
```

**Reach for it when** generating documentation or a machine-readable description of a CLI in a build step. For shell scripts use `Completions`, and for rendering `--help` use `HelpDoc`.

## GlobalFlag

`effect/cli/GlobalFlag` — unstable

Built-in and user-defined flags that intercept parsing before the normal handler runs. A global flag is either an `Action` (runs a side-effect and exits) or a `Setting` (provides a context service to the handler). Built-ins: `Help`, `Version`, `Wizard`, `Completions`, `LogLevel`.

Global flags have higher precedence than all other parsing. `Action` globals exit; `Setting` globals inject a context value (e.g. `LogLevel` sets the minimum log level for the handler's Effect runtime).

Constructors: `GlobalFlag.Action({ flag, run })` for action flags; curried `GlobalFlag.Setting(id)({ flag })` for setting flags. A setting is a `Context.Service` the handler can `yield*` to read the parsed value.

```ts
import { Effect } from "effect"
import { Command, Flag, GlobalFlag } from "effect/cli"

// --- Custom action flag: print the license and exit ---
const licenseFlag = GlobalFlag.Action({
  flag: Flag.Boolean("license").pipe(
    Flag.withDescription("Print license information"),
    Flag.withDefault(false)
  ),
  run: (_value, _ctx) => Effect.log("MIT License — Copyright 2025 CompAdmin Authors")
})

// --- Custom setting flag: dry-run mode as a context service ---
// GlobalFlag.Setting is curried: setting(id)({ flag })
const dryRunSetting = GlobalFlag.Setting("dry-run")({
  flag: Flag.Boolean("dry-run").pipe(
    Flag.withDescription("Simulate writes without committing changes"),
    Flag.withDefault(false)
  )
})

// Access a setting value inside a handler by yielding the setting object:
const grantCmd = Command.make(
  "grant",
  { shares: Flag.Int("shares") },
  Effect.fn(function*({ shares }) {
    // dryRunSetting is a Context.Service — yield it to get the boolean
    const isDryRun = yield* dryRunSetting
    if (isDryRun) {
      yield* Effect.log(`[dry-run] Would grant ${shares} shares`)
    } else {
      yield* Effect.log(`Granting ${shares} shares`)
    }
  })
)

// Attach the custom globals to the command
const grantWithGlobals = grantCmd.pipe(
  Command.withGlobalFlags([licenseFlag, dryRunSetting])
)
```

### Built-in globals

| Flag | Type | Effect |
| --- | --- | --- |
| `--help / -h` | Action | Renders help doc and exits |
| `--version / -v` | Action | Prints `name version` and exits |
| `--wizard` | Action | Runs the interactive wizard for the selected command |
| `--completions <bash\|zsh\|fish\|powershell\|sh\|pwsh>` | Action | Prints completion script and exits (`sh` aliases `bash`; `pwsh` aliases `powershell`) |
| `--log-level <level>` | Setting | Sets runtime minimum log level |

> **Note:** `GlobalFlag.BuiltIns` is ordered `Help`, `Version`, `Wizard`, `Completions`, `LogLevel`; the first present action wins. `Command.withGlobalFlags` attaches application-specific actions or settings to a command and its descendants.

`--wizard` prompts for each parameter of the selected command, prints the equivalent command line, and asks whether to run it. Two details matter for what it prints:

- **Secrets are masked in the rendered command.** A `Flag.Redacted` parameter is collected with `Prompt.Password`, and the printed command shows `<redacted>` in place of the value while the real value is passed to the run.
- **Values that look like flags are written inline.** A collected value beginning with `-` is emitted as `--delta=-5` rather than `--delta -5`, so the lexer cannot mistake it for a flag or for the `--` delimiter.
- **Already typed input is replaced, not repeated.** Flags and arguments typed for the selected command before `--wizard` are dropped from the printed command and asked for again; parent shared flags and subcommand names are kept. For a command without subcommands, positional answers follow a `--` separator, so they cannot be read as the value of a preceding boolean flag.

Invalid values for a global flag show the command help like any other parse error. `--help` and `--version` print through `CliOutput.Presenter` (by default the `Console` service) and **succeed**; they are not failures. A parent command invoked without a subcommand fails with `ShowHelp` and an empty `errors` list, which maps to exit code `0`.

Use when you need a flag that short-circuits command dispatch or provides context-level configuration to every handler in the tree.

## CliError

`effect/cli/CliError` — unstable

The typed error union for the CLI parser. `CliError.CliError` is what `Command.run` may fail with — a discriminated union covering every parser and runner failure mode. `NodeRuntime.runMain` handles these automatically (the runner has already printed them; the exit code comes from the error); match on `_tag` when embedding a CLI in a larger Effect application or writing integration tests.

**Parse and validation failures arrive wrapped.** The runner collects them, prints the help page plus the rendered errors, and fails with a single `ShowHelp` whose `errors` array holds the structured causes (`InvalidValue`, `MissingOption`, `UnknownSubcommand`, …). A `catchTag("InvalidValue", …)` placed on `Command.run` therefore never fires for bad input; inspect `ShowHelp.errors` instead. `UserError` and any error type of your own handlers, or of your own [`Command.validate`](#validating-input-across-flags) rules, reach the caller directly.

**Give a domain error a user-facing message without wrapping it.** When a handler or validation fails with an object carrying a string `[CliError.userMessage]` — `UserError` does, and a tagged error can define the getter — `Command.run` renders that message with the installed formatter and rethrows the *original* error, so `catchTag` on your own tag still works and `runMain` does not log it twice. `CliError.getUserMessage(error)` reads it.

```ts
import { Effect, Schema } from "effect"
import { CliError, Command } from "effect/cli"

class GrantExists extends Schema.TaggedError<GrantExists>()("GrantExists", { employee: Schema.String }) {
  override get [CliError.userMessage]() {
    return `${this.employee} already has a grant this cycle`
  }
}

// `comp grant` prints "ERROR  e-42 already has a grant this cycle" and fails with GrantExists.
const grant = Command.make("grant", {}, () => Effect.fail(new GrantExists({ employee: "e-42" })))

const _ = grant
```

| Error class | When it fires |
| --- | --- |
| `UnrecognizedOption` | A `--flag` was passed that no command recognises. Includes Levenshtein suggestions. |
| `DuplicateOption` | A subcommand declares a flag whose name its parent already declares (a command-definition error, not a user-input error). |
| `ValidationError` | A `Command.validate`, `Flag.mapEffect`, or `Argument.mapEffect` rule rejected the parsed input; carries `message`. A validation that fails with your own error instead is not wrapped in `ShowHelp`. |
| `MissingOption` | A required flag was absent and had no default or fallback. |
| `MissingArgument` | A required positional argument was absent. |
| `UnexpectedArgument` | Extra positional arguments remained after parsing. |
| `InvalidValue` | A value failed Primitive parsing (e.g. "abc" for an integer flag), or a single-valued flag was repeated. |
| `UnknownSubcommand` | The first token didn't match any known subcommand. Includes suggestions. |
| `UserError` | A handler or parameter transform explicitly wrapped a failure for safe CLI rendering; carries `cause` and an optional `userMessage`. Prefer the `CliError.userMessage` annotation on your own error. |
| `ShowHelp` | The runner's failure for "help was shown": with `errors` attached for parse/validation failures (exit code 1), or with an empty `errors` list when a parent command is invoked without a subcommand (exit code 0). An explicit `--help` is not an error at all — it prints and succeeds. |

```ts
import { Effect } from "effect"
import { Command, Flag } from "effect/cli"
import { NodeServices } from "@effect/platform-node"

const grant = Command.make(
  "grant",
  {
    employee: Flag.String("employee"),
    shares: Flag.Int("shares")
  },
  ({ employee, shares }) => Effect.log(`Granted ${shares} shares to ${employee}`)
)

const program = grant.pipe(
  Command.run({ version: "1.0.0" }),
  // Bad input surfaces as ONE ShowHelp; the structured causes are in `errors`.
  // Command.run has already printed the help page and the rendered errors.
  Effect.catchTag("ShowHelp", (help) =>
    Effect.forEach(help.errors, (error) => {
      switch (error._tag) {
        case "InvalidValue":
          return Effect.logWarning(`bad value for ${error.kind} "${error.option}"`, {
            value: error.value,
            expected: error.expected
          })
        case "MissingOption":
          return Effect.logWarning(`required flag missing: --${error.option}`)
        default:
          return Effect.logWarning(`cli parse failure: ${error._tag}`)
      }
    }, { discard: true })),
  // Catch ShowHelp only when this embedding must recover; otherwise let
  // NodeRuntime.runMain take the exit code from the error.
  Effect.provide(NodeServices.layer)
)
```

Use when embedding a CLI runner in a larger Effect program and needing to distinguish parse errors, user errors, and help requests, or when asserting on specific error conditions in tests.

## CliOutput

`effect/cli/CliOutput` — unstable

Two services decide what built-in CLI output looks like and where it goes. `CliOutput.Formatter` is the renderer: it turns help documents, errors, and version strings into text; override it with `CliOutput.layer(myFormatter)`. `CliOutput.Presenter` is the sink: `Command.run` / `runWith` hand it an event (`Help` with reason `"Requested"` or `"Implicit"`, `InvalidInvocation` with the help document and errors, or `Version`) instead of writing to the console itself; override it with `CliOutput.layerPresenter(presenter)`.

`HelpDoc` is the data; the Formatter renders it; the Presenter decides whether and where to print it. Swap the formatter for colourless output, Markdown, or JSON; swap the presenter to keep stdout clean for machine-readable results, send usage errors to stderr, or silence help in an embedding host. Presenting never changes the result: implicit help and invalid invocations still fail with `CliError.ShowHelp`. `--completions` scripts, wizard output, and `CliError.userMessage` renderings bypass the presenter.

`CliOutput.defaultPresenter` writes help and version to `Console.log`, and on an invalid invocation the help to `Console.log` and the errors to `Console.error`. Without an installed `Formatter`, it uses the default formatter colored according to [`TerminalCapabilities`](#terminalcapabilities)`.canColor`, so `NO_COLOR`, `FORCE_COLOR`, and `TERM=dumb` are honored.

`CliOutput.defaultFormatter({ colors?, inheritedFlags?, globalFlags? })` takes `"full"` (default), `"summary"`, or `"none"` for the `INHERITED FLAGS` and `GLOBAL FLAGS` sections of subcommand help. `"summary"` replaces the section with a pointer such as `Run 'comp --help' for inherited flags`; a command that declares global flags always lists them in full.

`CliOutput.displayWidth(text)` exposes the built-in help/table terminal-cell measurement for custom formatters. It ignores ANSI escapes, handles combining/zero-width characters, and accounts for wide graphemes: use it rather than `text.length` or `padEnd` when aligning terminal columns.

```ts
import { Console, Effect } from "effect"
import { CliOutput } from "effect/cli"

// Plain text, and subcommand help that points at the parent instead of repeating its flags.
const plainFormatter = CliOutput.defaultFormatter({
  colors: false,
  inheritedFlags: "summary",
  globalFlags: "summary"
})

const program = Effect.gen(function*() {
  const fmt = yield* CliOutput.Formatter
  // Manually format a version string
  console.log(fmt.formatVersion("comp", "1.0.0"))
}).pipe(
  Effect.provide(CliOutput.layer(plainFormatter))
)

// Keep stdout for results: usage errors go entirely to stderr; everything else is unchanged.
const StderrPresenter = CliOutput.layerPresenter({
  present: (event) =>
    event._tag === "InvalidInvocation"
      ? Effect.gen(function*() {
        const formatter = yield* CliOutput.Formatter
        yield* Console.error(formatter.formatHelpDoc(event.helpDoc))
        yield* Console.error(formatter.formatErrors(event.errors))
      })
      : CliOutput.defaultPresenter.present(event)
})

// Custom formatter — emit JSON for machine-readable help tooling
const jsonFormatter: CliOutput.Formatter = {
  formatHelpDoc:  (doc)           => JSON.stringify(doc, null, 2),
  formatCliError: (err)           => JSON.stringify({ error: err._tag, message: err.message }),
  formatError:    (err)           => JSON.stringify({ error: err._tag, message: err.message }),
  formatVersion:  (name, version) => JSON.stringify({ name, version }),
  formatErrors:   (errs)          => JSON.stringify(errs.map((e) => ({ tag: e._tag, message: e.message })))
}

const _ = [program, StderrPresenter, jsonFormatter]
```

Use when you need colourless CI output, machine-readable help (JSON/Markdown), or control over where built-in help and errors are written — override the formatter or presenter rather than post-processing printed strings.

## TerminalCapabilities

`effect/cli/TerminalCapabilities` — unstable

A `Context.Reference` of `{ canColor, canAnimate, canPrompt }` for the current process. Built-in `Command` help, version, and error output follows `canColor` (unless you install a `CliOutput.Formatter`), and fallback prompts from `Flag.withFallbackPrompt` / `Argument.withFallbackPrompt` run only when `canPrompt` is `true`. `canAnimate` is for your own output: it says whether stdout is being watched.

**Detection.** `TERM=dumb` clears all three. Otherwise a non-empty `NO_COLOR` disables color and wins over `FORCE_COLOR`; `FORCE_COLOR` forces color even off a TTY, except `0` and `false`; empty variables count as unset. `canAnimate` needs stdout to be a terminal, and `canPrompt` needs both stdin and stdout to be terminals. The default value is detected from `process` the first time it is read (all `false` without a `process` global); `TerminalCapabilities.layer` detects through the current `ConfigProvider` and the `Stdio` service instead, and never fails.

```ts
import { Effect } from "effect"
import { Command, Flag, Prompt, TerminalCapabilities } from "effect/cli"

const grant = Command.make(
  "grant",
  { employee: Flag.String("employee").pipe(Flag.withFallbackPrompt(Prompt.String({ message: "Employee ID: " }))) },
  ({ employee }) => Effect.log(`granting to ${employee}`)
)

// Force non-interactive behavior: no colors, and a missing --employee fails with MissingOption.
const nonInteractive = Command.run(grant, { version: "1.0.0" }).pipe(
  Effect.provideService(TerminalCapabilities.TerminalCapabilities, {
    canColor: false,
    canAnimate: false,
    canPrompt: false
  })
)

// Application output can share the same answer.
const banner = Effect.gen(function*() {
  const { canColor } = yield* TerminalCapabilities.TerminalCapabilities
  return canColor ? "\u001b[1mcomp\u001b[0m" : "comp"
})

const _ = [nonInteractive, banner]
```

**Reach for it when** a CLI must behave correctly in CI, pipes, and dumb terminals, or when your own output should color and animate under the same rules as the built-in help.
