> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Adding a New CLI

> Give an agent your own command-line tools, with parsed flags, generated help and access to workspace files.

A custom CLI gives an agent your own command, with fixed subcommands and
flags: a client for your service, a tool over workspace files, or a script.
For a typed `CLI`, Mirage parses each line, refuses a bad one and generates
`--help` and `man`. A script CLI is a program that reads its own arguments.

A typed CLI declares its grammar with `CommandSpec`, the same parser Mirage's
built-in commands use, so its `--help`, error messages and exit codes work
the same way as theirs.

## Write a typed CLI

A handler gets the same four arguments a shell command's handler gets: the
install's accessor, the path operands, the text operands and a `Context`.
Mirage builds the accessor once per install from the install's validated
config, and closes it when the install goes. The default `NOOPAccessor` only
holds that config, at `accessor.config`. The `@struktoai/mirage-core/...` type
imports need `pnpm add @struktoai/mirage-core`.

```typescript theme={null}
import {
  Argument,
  CLI,
  CLIHandler,
  CommandSpec,
  type Context,
  FlagView,
  IOResult,
  type PathSpec,
  Workspace,
  z,
  type CommandFnResult,
} from '@struktoai/mirage-node'
import type { NOOPAccessor } from '@struktoai/mirage-core/accessor/base'

const PagerConfigSchema = z.strictObject({ account: z.enum(['engineering', 'support']) })
type PagerConfig = z.infer<typeof PagerConfigSchema>

function acknowledge(
  accessor: NOOPAccessor,
  _paths: PathSpec[],
  texts: string[],
  ctx: Context,
): CommandFnResult {
  const { account } = accessor.config as PagerConfig
  const incidentId = texts[0]
  const by = new FlagView(ctx.flags, ctx.spec).asStr('by')
  return [
    new TextEncoder().encode(`[${account}] acknowledged ${incidentId} by ${by}\n`),
    new IOResult(),
  ]
}

const PAGER = new CLI({
  spec: new CommandSpec({
    name: 'pager',
    subcommands: [new CommandSpec({
      name: 'ack',
      arguments: [
        new Argument('INCIDENT_ID'),
        new Argument('--by', { required: true }),
      ],
    })],
  }),
  handlers: { ack: new CLIHandler({ fn: acknowledge, write: true }) },
  configModel: PagerConfigSchema,
})

const ws = new Workspace({})
ws.registerCli('pager-eng', PAGER, { account: 'engineering' })
ws.registerCli('pager-support', PAGER, { account: 'support' })

for (const line of ['pager-eng ack INC-1 --by sam', 'pager-support ack INC-2 --by kim']) {
  const r = await ws.shell(line)
  process.stdout.write(r.stdoutText)
}
```

```text theme={null}
[engineering] acknowledged INC-1 by sam
[support] acknowledged INC-2 by kim
```

One CLI, installed twice, serves two accounts. Without `--by`, Mirage refuses
the line before `acknowledge` runs and exits 2:

```text theme={null}
pager-eng ack: option '--by' is required
Try 'pager-eng ack --help' for more information.
```

The runnable [pager example](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/cli/pager.ts)
adds an incident service the handlers change.

### Command shape

| Node | Declares | Its handler gets |
| - | - | - |
| Leaf | `arguments` and a `CLIHandler` | Path and text operands, and parsed flags on `ctx` |
| Group | `subcommands`, and options its leaves inherit | No handler; Mirage runs the leaf the line names |

* In `arguments`, a dashed name such as `--by` declares an option and a bare
  name such as `INCIDENT_ID` declares a positional. Declare a file operand
  with `type: 'path'`; a service ID stays a text operand.
* `CLI.handlers` maps each leaf's path below the root to its `CLIHandler`:
  `'ack'`, `'incident ack'`, or `''` for a program with no subcommands.
* Names and aliases are single words, and a group's children share one set
  of names. An option can't repeat in a parent and its child.
* `new CLI(...)` refuses a bad tree when you build it, and Mirage refuses a
  bad line before the handler runs, so a handler never re-checks its flags.
* Read flags through `new FlagView(ctx.flags, ctx.spec)`. Reading an option
  the spec doesn't declare throws, instead of looking like an omitted flag.
* `configModel` validates each install's config when you register it.
  Without one, the CLI takes no config and `accessor.config` is `null`.
* Mark a handler that changes the service `write: true`. Policy reads it as
  `CommandContext.write`, so one `preCommand` method can refuse every
  writing subcommand, and Mirage drops cached mount listings after it runs.
  It grants no permission.
* Descriptions on the spec, its options and operands become `--help` and
  `man` at every level.

### Output and status

A handler returns `[stdout, IOResult]`. `stdout` is a `Uint8Array`, an
`AsyncIterable<Uint8Array>` for output that arrives in pieces, or `null`. The
`IOResult` carries the exit status and stderr. Piped input arrives on
`ctx.stdin` as bytes, an async byte source, or `null` when nothing is piped;
`materialize` reads all of it.

```typescript theme={null}
import {
  type CommandFnResult,
  type Context,
  IOResult,
  type PathSpec,
  UsageError,
} from '@struktoai/mirage-node'
import type { NOOPAccessor } from '@struktoai/mirage-core/accessor/base'
import { materialize } from '@struktoai/mirage-core/io/types'

const encode = (text: string): Uint8Array => new TextEncoder().encode(text)

async function count(
  _accessor: NOOPAccessor,
  _paths: PathSpec[],
  _texts: string[],
  ctx: Context,
): Promise<CommandFnResult> {
  if (ctx.stdin === null) throw new UsageError('pipe incident IDs on stdin')
  const text = new TextDecoder().decode(await materialize(ctx.stdin))
  return [encode(`${String(text.split('\n').filter(Boolean).length)}\n`), new IOResult()]
}

function watch(_accessor: NOOPAccessor, _paths: PathSpec[], texts: string[]): CommandFnResult {
  async function* events(): AsyncIterable<Uint8Array> {
    for (const incidentId of texts) yield encode(`${incidentId} open\n`)
  }
  return [events(), new IOResult()]
}

function close(_accessor: NOOPAccessor, _paths: PathSpec[], texts: string[]): CommandFnResult {
  const message = `${String(texts[0])} is already closed\n`
  return [null, new IOResult({ exitCode: 1, stderr: encode(message) })]
}
```

Bound as `pager count`, `pager watch INCIDENT_ID...` and
`pager close INCIDENT_ID`:

| Line | Prints | Exit |
| - | - | - |
| `printf 'INC-1\nINC-2\n' \| pager-eng count` | `2` | 0 |
| `pager-eng count` | `pipe incident IDs on stdin` on stderr | 2 |
| `pager-eng watch INC-1 INC-2` | `INC-1 open` and `INC-2 open` | 0 |
| `pager-eng close INC-9` | `INC-9 is already closed` on stderr | 1 |

`new UsageError(message, exitCode)` (exit code 2 by default) prints its
message to stderr and sets the exit status, and the rest of the line keeps
running.

A CLI that prints paths from its own data, as `git` prints its index, returns
rows instead of bytes. Each row names the path it shows. Mirage drops the rows
the session can't see, then calls your renderer with the rest, so no line,
count or column width gives a hidden path away:

```ts theme={null}
import {
  IOResult,
  PathSpec,
  type CommandFnResult,
  type Context,
} from '@struktoai/mirage-node'
import type { NOOPAccessor } from '@struktoai/mirage-core/accessor/base'
import type { Rows } from '@struktoai/mirage-core/io/types'

interface Entry {
  readonly path: PathSpec
  readonly size: number
}

function tracked(
  _accessor: NOOPAccessor,
  _paths: PathSpec[],
  _texts: string[],
  _ctx: Context,
): CommandFnResult {
  // The CLI's own record of the files it tracks.
  const kept: [string, number][] = [['/data/a.txt', 1], ['/data/b.txt', 3]]
  const rows: Rows<Entry> = {
    items: kept.map(([path, size]) => ({ path: PathSpec.fromStrPath(path), size })),
    render: (shown) => {
      const lines = shown.map((entry) => `${entry.path.virtual} ${String(entry.size)}\n`)
      lines.push(`${String(shown.length)} files\n`)
      return Promise.resolve(new TextEncoder().encode(lines.join('')))
    },
  }
  return [null, new IOResult({ rows })]
}
```

The renderer runs inside the command's timeout. A handler returns rows or
stdout, not both.

### Files and the session

Build the service client in `CLI.accessor`, from the install's config, so
every call on one install shares one client. Don't look for a matching VFS to
borrow its credentials or accessor; share core service functions and accessor
classes between a CLI and a VFS instead.

`ctx.vfs` is the session's files, with workspace policy and mount modes
applied: `read`, `write`, `stat`, `readdir`, `symlink`, `readlink` and the
rest, the same API as `session.vfs`.

* Keep the `PathSpec` a `type: 'path'` operand gives you, and derive paths
  with `join` and `parent`. For a path string from config, use
  `PathSpec.fromStrPath(value, undefined, ctx.cwd)`.
* `ctx.vfs.stat(path, undefined, { nofollow: true })` reports a link itself.
* `ctx.vfs.mountOf(path)` names the mount serving a path,
  `ctx.vfs.isMount(path)` says whether a path is a mount root, and
  `ctx.vfs.submounts(path)` lists the mounts below a folder. A mount the
  session hides shows as the nearest folder above it that the session sees,
  so a CLI that removes a folder can refuse without learning the hidden name.
* `ctx.vfs` is `undefined` when your code calls a handler directly; a
  handler that needs files throws `UsageError` then.

After an install's write, Mirage drops the caches of every mount its accessor
may reach, even when the write failed, since it may still have reached the
service. Implement `reaches(peer)` on your accessor to return `false` for a
mount's accessor your writes can't change; an accessor without it reaches
every mount. A script CLI marked as a write drops them too, since Mirage
can't see what it touched. A CLI with no config that works on files, such as
`git`, needs none of this: Mirage drops the cache of each path it writes.

`ctx.env` is a copy of the environment taken when the command starts.
`ctx.session` reads and writes the live session under the shell's rules, so
writing a readonly or hidden variable fails. Reads are plain calls. Writes
return promises: await them, or a failure goes unseen.

| Call | Does |
| - | - |
| `get(name)` | Returns the variable's value, or `null` |
| `snapshot()` | Returns every variable the session can see, as a record |
| `await set(name, value)` | Sets the variable, as `NAME=value` does |
| `await unset(name)` | Removes the variable |
| `isReadonly(name)` | Whether `readonly` has marked the variable |
| `cwd()` | Returns the session's working directory |
| `sessionId` | The session's ID |

```typescript theme={null}
async function login(
  accessor: NOOPAccessor,
  _paths: PathSpec[],
  _texts: string[],
  ctx: Context,
): Promise<CommandFnResult> {
  if (ctx.session === undefined) throw new UsageError('needs a workspace session')
  await ctx.session.set('PAGER_ACCOUNT', (accessor.config as PagerConfig).account)
  return [null, new IOResult()]
}
```

After `pager-eng login`, `echo $PAGER_ACCOUNT` prints `engineering`. If
`PAGER_ACCOUNT` is readonly, the command exits 1 with
`pager-eng login: PAGER_ACCOUNT: readonly variable`. To run another command
from a handler, use `await ctx.shell(line)`; see [`Context`](#context).

### On a mount

A typed CLI registered on a mount runs its subcommands there, with the
mount's accessor, so it declares no `configModel`, `accessor` or `script`:

```typescript theme={null}
import { MountMode, RAMVFS } from '@struktoai/mirage-node'
import type { RAMAccessor } from '@struktoai/mirage-core/accessor/ram'

function tag(accessor: RAMAccessor, paths: PathSpec[], texts: string[]): CommandFnResult {
  const [note] = paths
  if (note === undefined) return [null, new IOResult({ exitCode: 1 })]
  accessor.store.files.set(`/${note.vfsPath}`, new TextEncoder().encode(texts.join(' ')))
  return [null, new IOResult()]
}

const NOTES = new CLI({
  spec: new CommandSpec({
    name: 'notes',
    subcommands: [new CommandSpec({
      name: 'tag',
      arguments: [new Argument('note', { type: 'path' }), new Argument('tags', { nargs: '+' })],
    })],
  }),
  handlers: { tag: new CLIHandler({ fn: tag, write: true }) },
})

const ws = new Workspace({ '/notes/': new RAMVFS() }, { mode: MountMode.WRITE })
ws.mount('/notes/').registerCommands([NOTES])
```

`notes tag /notes/a.md draft` parses, shows help and refuses bad flags the
same way an installed CLI does.

* It runs on the working directory's mount when that mount has `notes`.
* Otherwise a writing subcommand runs on the only writable mount that has
  it. With two, Mirage refuses the line and names both; `cd` into one.
* A read-only subcommand runs on the first mount that has it.
* `--help` works from anywhere.
* A VFS gives the same tree to every mount of it through its `commands`
  option.
* Its handlers reach the backend directly, without Mirage's file layer. A
  writing one must declare `write: true`; it runs only on a writable mount,
  and Mirage drops cached listings after it.

## Script CLIs

A script CLI is a program file that reads its own arguments and needs no
Mirage imports:

```yaml theme={null}
machines:
  monty:
    provider: in_process
    runtime: monty
clis:
  pager:
    script: ./cli/pager.py
    machine: in_process
    config:
      width: 80
```

It runs on the [machine](https://docs.mirage.strukto.ai/home/setup/machine/overview.md) its entry names, as
[Script CLIs](https://docs.mirage.strukto.ai/home/setup/runtime/overview.md#script-clis) describes; without a
`machines` entry for its language it exits 127. Mirage embeds the file when
the workspace loads.

* Words after the command name arrive as argv. On Pyodide, Monty and
  QuickJS, `argv[0]` is the installed name, so two installs can tell
  themselves apart; the Node-only `host` machine runs CPython with `-c`,
  which owns `sys.argv[0]`. Arguments start at index 1 everywhere.
* A script declares no Mirage grammar, so every option reaches it unchanged,
  `--help` included. A script CLI built in code can add a `CommandSpec` to
  get Mirage's parsing and help.
* Piped input arrives on stdin.
* Config arrives as JSON in `MIRAGE_CLI_CONFIG`, alongside the session's
  environment. Changes the program makes to its environment stay with it.
* Its stdout, stderr and exit status become the command's.
* A script CLI takes no `configModel`, subcommands or handlers.

| Runs on | Arguments | Standard input |
| - | - | - |
| Pyodide | `sys.argv` | `sys.stdin` |
| Monty | `argv` global | `stdin` global |
| QuickJS | `scriptArgs` | `std.in` |

Pyodide, Monty and QuickJS read and write workspace files but have no network
and no Node builtins. Use the Node-only `machine: host` to run the host's own
interpreter when the script needs more.

## Install it

`ws.registerCli(name, cli, config)` installs a typed or script CLI under
`name`. The agent types that name, `pager-eng`, not the spec's name, `pager`.

To install a typed CLI from workspace YAML, register its spec first, then
load the workspace:

```typescript theme={null}
import { registerCliSpec } from '@struktoai/mirage-node'

registerCliSpec(PAGER)
```

```yaml theme={null}
clis:
  pager-eng:
    cli: pager
    machine: in_process
    config:
      account: engineering
```

A script CLI needs no registration: its entry names the file with `script:`,
as in [Script CLIs](#script-clis).

`cli:` can also point at `./file.mjs:ATTR` or a package reference such as
`my-clis/specs:PAGER`; a relative file resolves next to the YAML file.

* A `.js` file follows its nearest `package.json` `type`; `.mjs` is always a
  module.
* A `.ts` file runs through Node's type stripping, not compilation, so build
  first if it uses syntax that needs transforming.
* TypeScript has no entry points like Python's. Use a package reference, or
  call `registerCliSpec` from your code.

Registration follows these rules:

* A registered name or a builtin wins over a file or package reference.
* Registering a name another registration or a builtin already holds fails.
* Only your code can install or remove a CLI. The shell has no `install`
  command, so an agent can't remove one. A shell function can still shadow
  a CLI, as in bash; refuse that with a `preCommand` policy.

See [CLI entries](https://docs.mirage.strukto.ai/home/configuration/workspace.md#cli-entries) for every
`clis` key.

## Snapshots and credentials

A snapshot saves a typed CLI install by its spec name. A Zod object
`configModel` also says what to redact; mark each string credential with
`secretStr()`:

```typescript theme={null}
import { secretStr, z } from '@struktoai/mirage-node'

const ConfigSchema = z.object({ token: secretStr(), account: z.string() })
```

* Loading the snapshot needs fresh config for that install through `clis`;
  Mirage refuses to restore a redacted credential as if it were real.
* The loading process must also resolve the spec name, or pass
  `[cli, config]` as that install's `clis` entry.
* A normalizer function also works as `configModel`, but Mirage can't see
  inside its result, so the snapshot saves it as it is. Use a Zod object
  for config that holds credentials.
* `Workspace.copy()` carries a CLI installed in code, with its real config.

A script CLI's snapshot embeds the script, and saves its config as it is,
since there is no config model to mark secrets. Keep credentials in the
environment, or pass fresh config through `clis` when loading.

## Reference

The constructors document exact types and defaults:
[`CLI` and `CLIHandler`](https://github.com/strukto-ai/mirage/blob/main/typescript/packages/core/src/commands/cli/types.ts),
and [`CommandSpec` and `Argument`](https://github.com/strukto-ai/mirage/blob/main/typescript/packages/core/src/commands/spec/types.ts).

### `CLI` and `CLIHandler`

| Field | Meaning |
| - | - |
| `CLI.spec` | The root `CommandSpec`. |
| `CLI.handlers` | Each leaf's path mapped to its `CLIHandler`. |
| `CLI.configModel` | The Zod schema, or a normalizer function, each install's config must pass. |
| `CLI.accessor` | Builds the install's accessor from its config, once per install; Mirage closes it when the install goes. Default `NOOPAccessor`. |
| `CLI.script`, `CLI.machine`, `CLI.runtime` | The embedded script, the machine type that runs it (`in_process`, the default in code, or `host`) and the runtime there, if named. A CLI without a script runs on `in_process` only. |
| `CLIHandler.fn` | The handler, called as `fn(accessor, paths, texts, ctx)`. |
| `CLIHandler.write`, `CLIHandler.limit` | Whether the handler changes the service, and its execution limit. |
| `CLIHandler.writeWhen` | Options that make an otherwise read-only leaf a write on the line that passes them, as `himalaya message read --seen` marks mail read. |

### `CommandSpec`

| Field | Meaning |
| - | - |
| `name`, `aliases` | The command word, and other words for a subcommand. |
| `subcommands` | A group's children. |
| `arguments` | Options and positionals; a group's options pass to its leaves. |
| `description`, `epilog` | Help text, and text after it. |
| `usageStyle` | How help and refusals read: argparse, Git, clap, Cobra or poppler. Cobra leaves a missing positional to the handler. poppler answers an option error with the help page and exit 99. |
| `allowAbbrev` | Whether a unique prefix of a long option counts as the option. |

### `Argument`

| Field | Meaning |
| - | - |
| Names | One positional name, or one or more dashed option spellings. |
| `type` | `str` (default), `int`, `float`, or `path` for a workspace path. |
| `action` | `store` (default), `store_true`, `count`, `append`, or `extend`. |
| `nargs` | One value by default; `?` for optional or an integer for a fixed count. Positionals also take `*`, `+` or `REMAINDER`; only one positional may take a variable count, and it must come last. |
| `choices` | The allowed values. |
| `required` | Whether an option must be given; a positional's count comes from `nargs`. |
| `default`, `env` | An option's fallbacks; a value from the environment counts as given. |
| `help`, `metavar` | Help text, and the value's name in help. |

The names follow argparse, which Mirage supports in part. Positionals take no
`default`, and options take no variable count. `append` collects one value per
use; `extend` flattens fixed groups. The other fields of `CommandSpec` and
`Argument` describe shell builtins' grammars, such as `tar`'s old-style
options; a CLI doesn't need them.

### `Context`

| Argument or field | Holds |
| - | - |
| `accessor` | The install's accessor. The default `NOOPAccessor` holds the validated config at `accessor.config` (`null` without a config model). |
| `paths` | The path operands, resolved against the working directory. |
| `texts` | The text and number operands, in declaration order. |
| `ctx.argv` | The words after the command name as typed, subcommands included. |
| `ctx.flags` | Group and leaf flags keyed by option name, `--dry-run` as `dry_run`. |
| `ctx.spec` | The leaf's `CommandSpec`. |
| `ctx.stdin` | Piped bytes, an async byte source, or `null`. |
| `ctx.cwd` | The session's working directory. |
| `ctx.env` | A copy of the environment taken when the command starts. |
| `ctx.vfs`, `ctx.session` | The session's files and live session; absent outside a workspace. |
| `ctx.shell` | `await ctx.shell(line)` runs another line in the calling session and returns its `IOResult`. Calling it after the command returns raises an error. |
| `ctx.processes` | The session's processes, as `ps` and `jobs` see them. |
| `ctx.ids` | The workspace's source of generated names and random values, so a seeded workspace replays them. |
| `ctx.signal` | Aborts when the line is cancelled or times out. |
| `ctx.runtime`, `ctx.diff`, `ctx.find` | Not set for a CLI; they serve interpreter commands, `diff` and `find`. Run code through `ctx.shell` instead. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.