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

# Laravel Baton — Investigating a TypeScript Package for CLIs Used by People, CI, and AI Agents

> An initial investigation of laravel/baton. It covers the interactive UI, machine-readable --json output, AI agent detection, and the exit code conventions.

> [!NOTE]
>
> This article is based on the README and package.json of [laravel/baton](https://github.com/laravel/baton). It reflects `@laravel/baton` v0.1.1 (released December 1, 2026). The package is at 0.x, so its API may change.

## What Baton is

[Baton](https://github.com/laravel/baton) is a TypeScript package for building command-line apps that work well whether a person, CI, or an AI agent runs them. From one command definition, you get different behavior depending on who is running it.

```sh theme={null}
my-cli deploy                # A person: prompts, spinners, a timeline down the left
my-cli deploy --json         # A script: one line of JSON on stdout, errors on stderr
CLAUDECODE=1 my-cli deploy   # An agent: JSON automatically, and never a question it cannot answer
```

It is a library for CLIs that run on Node.js, not a feature of Laravel itself. The Laravel Cloud CLI, `@laravel/cloud-cli`, is also built with Baton ([Laravel Cloud CLI overview](https://kawax.biz/en/blog/laravel-cloud-cli.md)).

## The problem it addresses

A CLI has three kinds of users.

* **People**: want clear prompts, tidy output, and suggestions when they mistype a command
* **CI**: wants predictable exit codes and output it can parse
* **AI agents**: want machine-friendly output and never want to stop at a question nobody can answer

Baton serves all three from the same code path. You write each command once, and its behavior adapts to whoever is running it.

```mermaid theme={null}
flowchart LR
    A["my-cli deploy"] --> B{"Who is running it"}
    B -->|Person| C["Timeline<br>Prompts and spinners"]
    B -->|"CI, agent, or --json"| D["JSON<br>One line on stdout"]
    D -->|On failure| E["Error<br>stderr and exit code"]
```

## Installation

Baton requires Node.js 22 or later. To start a new CLI, use the `create-baton` scaffolder.

```shell theme={null}
npm create @laravel/baton my-cli
cd my-cli
npm run dev hello
npm run dev hello --json
```

The scaffolder generates an example command, a test, shell completions, an `AGENTS.md` (working rules for AI agents), and a `CLAUDE.md` for Claude Code.

To add Baton to an existing oclif CLI, install the package and point the `oclif` settings in `package.json` at your command map, help class, and typo handler.

```shell theme={null}
npm install @laravel/baton @oclif/core
```

## Writing a command

Every Baton command extends `BaseCommand`. Here is the `hello` command from the README.

```ts theme={null}
import { BaseCommand } from '@laravel/baton/oclif'
import { Flags } from '@oclif/core'

export default class Hello extends BaseCommand {
  static override description = 'Say hello'

  static override flags = {
    name: Flags.string({ description: 'Who to greet' }),
  }

  async run(): Promise<void> {
    const { flags } = await this.parse(Hello)

    const ui = this.open('Say Hello', flags)

    const form = this.form(ui, { flags })

    const name = await form.submit(() =>
      form.field('name', {
        prompt: (current) =>
          ui.text({
            label: 'Who should we greet?',
            defaultValue: current ?? '',
            required: true,
          }),
        fallback: () => 'world',
      }),
    )

    this.respond({ greeting: `Hello, ${name}!` })

    ui.success(`Said hello to \`${name}\`.`)
  }
}
```

* **`open`**: draws the title and loads `ui` only when someone is watching. On a JSON run, `ui` is a silent stand-in, so you never need to check whether anyone is watching.
* **`form`**: uses the `--name` flag if it was passed, asks a person if one is at the terminal, and otherwise uses the `fallback`.
* **`respond`**: writes the answer as JSON on a JSON run and ends the run. It has no effect on the output for people.

> [!WARNING]
>
> `respond` ends the run by throwing a `CommandExit`. If you wrap it in a `try`, rethrow the `CommandExit`, or the command will keep running past its answer.

Register commands in `src/index.ts`.

```ts theme={null}
import { BaseHelp, commandNotFound, Completions } from '@laravel/baton/oclif'
import Hello from './commands/hello.js'

export const COMMANDS = {
  completions: Completions,
  hello: Hello,
}

export const HELP = BaseHelp

export const COMMAND_NOT_FOUND = commandNotFound
```

## Output and prompts

All output is drawn on a single timeline with a gray rail down the left edge. The main building blocks are:

* **Notes**: one-line messages with `ui.info`, `ui.success`, `ui.warning`, and `ui.error`
* **Callouts**: boxed messages with headings, steps, key-value pairs, and links, using `ui.callout`
* **Details and tables**: `ui.details` for one item and `ui.table` for several
* **Code**: `ui.codeBlock` for code or command output, and `ui.copyable` for text people copy and paste
* **Work in progress**: `ui.spin` for a spinner, and `ui.task` for work that logs progress as it runs

Prompts exist for each kind of answer.

```ts theme={null}
const name = await ui.text({ label: 'Name', placeholder: 'my-app', required: true })
const secret = await ui.password({ label: 'API token' })
const region = await ui.select({ label: 'Region', options: regions, searchable: true })
const sure = await ui.confirm({ label: 'Delete cache `sessions`?', defaultValue: false })
```

Once answered, each prompt collapses into a small box showing its label and answer, so the timeline reads as a record of every decision.

## Forms and validation

When an API rejects an input, the form asks again for only the rejected fields, with the rejected value filled in. You signal a rejection with `CliError`.

```ts theme={null}
throw new CliError('The name is taken.', {
  rejected: true,
  fields: { name: ['has already been taken.'] },
})
```

For a Laravel application, you pass the field errors from the `errors` object of a 422 response. The CLI then asks again only for the rejected `name`.

On a headless run, nobody can answer again, so the form writes a JSON error to stderr that includes the values it sent, and exits with code `5`. Keys that name secrets, such as `password` and `token`, are masked as `*****` by default.

> [!WARNING]
>
> Everything inside `submit` runs again from the top after a rejection. Put the request that may be rejected last in the body, and make sure anything before it is safe to repeat.

## Machine output

### JSON and agent detection

A command answers in JSON when `--json` is passed, or when nobody can answer a question: in CI, with stdin or stdout piped, with `-n` or `--no-interaction`, or when an AI agent runs it. Baton recognizes 16 agents, including Claude Code, Cursor, Codex, Gemini, and Copilot. For others, set the `AI_AGENT` variable.

Because a person's shell may also set these variables, you can treat a person as interactive with a variable named after your CLI's bin, such as `MY_CLI_INTERACTIVE=1`. A piped stdin or stdout, `--json`, and `-n` still take priority over it.

JSON is written to stdout as a single compact line. Use `--fields` to select only the values you need.

```sh theme={null}
my-cli environment:list --json --fields=name,database.name
```

### Masking

By default, any value whose key names a secret (password, token, credential, private key, API key, authorization, cookie, session id, DSN, and so on) is replaced with `*****`. Pass `--show-sensitive` to reveal it. Keys such as `db_password` and `apiKey` are masked, while `bypass_cache` is not.

### Errors and exit codes

Throw a `CliError` for anything a person should read. It is drawn on the timeline for people and written as JSON to stderr for machines.

```ts theme={null}
throw new CliError(`No region named \`${name}\`.`, { code: 'not_found' })
```

```json theme={null}
{ "error": true, "message": "No region named nope.", "code": "not_found" }
```

Scripts should branch on `code`, not on `message`.

| Code | Meaning |
| - | - |
| `0` | Success |
| `1` | Failure |
| `2` | A flag or argument the parser refused |
| `4` | Authentication is required |
| `5` | An input was rejected |
| `127` | No such command |
| `130` | Interrupted with Ctrl-C |

## Testing

Tests can check both what a script receives and what a person sees, without a terminal.

* **`runCommand`**: runs the command as a script or agent would, and returns the exit code, JSON, and error
* **`renderCommand`**: runs the command as a person would, answers each prompt by its label, and returns the drawn timeline as text

```ts theme={null}
import { runCommand } from '@laravel/baton/testing'

const run = await runCommand(CacheGet, ['sessions'])

run.exitCode // 0
run.json // { id: 'cache-1', name: 'sessions', … }
```

> [!NOTE]
>
> Write output through `ui` and `respond`, not `console.log`. Output that bypasses Baton's rendering cannot be checked by these tests.

## Observations

* Baton is a Node.js library, not part of Laravel. For interactive prompts in Artisan commands, use [Laravel Prompts](https://kawax.biz/en/prompts.md).
* It is used by `@laravel/cloud-cli`, and it is designed so that AI agents can run the same CLI.
* It is at 0.x, so the API may change. If you adopt it, consider pinning the version.
* It is licensed under MIT.

## Related pages

> [card] [Laravel Cloud CLI](https://kawax.biz/en/blog/laravel-cloud-cli.md)
>
> An overview of `@laravel/cloud-cli`, which uses Baton.

> [card] [Laravel Prompts](https://kawax.biz/en/prompts.md)
>
> The interactive UI for PHP Artisan commands.

## Primary sources

* [`laravel/baton`](https://github.com/laravel/baton) (default branch `main`)
* [README](https://github.com/laravel/baton/blob/main/README.md)
* [`package.json`](https://github.com/laravel/baton/blob/main/package.json) (`@laravel/baton` v0.1.1, MIT)
* [`docs/AGENTS.md`](https://github.com/laravel/baton/blob/main/docs/AGENTS.md)


## Related topics

- [Introducing Laravel Wayfinder](https://kawax.biz/en/blog/wayfinder-introduction.md)
- [Laravel Agent Detector — AI agent detection package](https://kawax.biz/en/blog/agent-detector-introduction.md)
- [Laravel Cloud CLI — operate Laravel Cloud from your terminal](https://kawax.biz/en/blog/laravel-cloud-cli.md)
- [Laravel AI SDK](https://kawax.biz/en/ai-sdk.md)
- [Blog](https://kawax.biz/en/blog/index.md)


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