---
title: Building a CLI that gives AI agents enough context to act
canonical: "https://xiaofeng.dev/en/writing/ai-friendly-cli/"
pubDate: 2026-10-31
updatedDate: 2026-11-22
author: 唐小锋 Xiaofeng TANG
description: "First, some background: I have a CLI program used to collect and evaluate responses from different AI platforms in batches. It uses a browser-use interface…"
tags: [AI Agents, CLI, Developer Experience]
---

First, some background: I have a CLI program used to collect and evaluate responses from different AI platforms in batches. It uses a browser-use interface to navigate to the target platform, submit a question, wait for a response, and then extract the content. After the sampling results are saved, they can be further processed by the evaluation workflow.

This program provides sampling and evaluation capabilities via CLI from the outset. Initially, it was directly invoked by a human: preparing input and configuration, executing commands, viewing logs and results, and then deciding on the next step. If the browser was not logged in, it was logged in first; if a platform failed, the cause was checked, and a decision was made on whether to retry.

Later, as these operations were gradually delegated to the Agent, various problems arose, such as: commands getting stuck at confirmation prompts, logs being mixed into the JSON, environment configurations not taking effect, and tasks reporting errors but the process failing to exit. The essence of these problems was that the CLI design was not AI-friendly enough, so I made significant modifications to make it more closed-loop and self-contained.

The most direct benefit and effect is that the agent can obtain complete information, locate problems, solve obstacles, and ultimately achieve the sampling goal without needing to understand the CLI source code or additional user manuals.

The project has been anonymized, and the example commands `sampler` and platform usage are consistent ` site-a`. Based on this example, I will share my experience in modifying the AI-Friendly CLI.

Let's first look at the main flow of this program. After preparing the questions and configurations, the outer agent calls the CLI step by step, and the sampling command internally operates the browser through browser-use. If a valid login state already exists, sampling can be performed directly, and the results can be saved and evaluated as needed.

```mermaid
%%{init: {"flowchart": {"padding": 6, "rankSpacing": 14}}}%%
flowchart LR
    A["Prepare signed-in session"] --> B["Collect browser responses"] --> C["Save results"] --> D["Evaluate on demand"]
```

In this article, "sampling" refers to obtaining answers from the platform page; "evaluation" refers to reading the saved answers and combining them with the evaluation configuration to call the model for analysis. The two can be run separately, therefore, the timeout, cost, and recovery issues of browser waiting and model invocation will be discussed separately later.

The main commands below all use the `sampler` CLI.

- `setup`: Generates the basic configuration for the browser runtime environment and control model.
- `auth init site-a`: Initiate the platform login process, whereby the user completes the login and saves the browser login state.
- `auth import site-a state.json` Import an existing browser login state file.
- `auth status site-a` Check if the browser login state for this platform is saved locally.
- `sample run --platform site-a --dataset questions.json` Perform browser sampling based on the question set and save the results.
- `runs inspect runs/run-example` Offline inspection of a sampled file, summary, and failed items.
- `evaluate run runs/run-example --context context.json`: Analyze the saved sampled responses in conjunction with the evaluation configuration.
- `evaluate external request.json`: Read external evaluation requests; `-` when the parameter is changed, read from standard input.
- `config inspect --config sampling.json`: View the final value, source, and conflicts of the sampling configuration.
- `doctor browser`: Check browser configuration; only then `--probe` will actual browser or connection detection be performed.

The files and directories mentioned above are examples. `questions.json` They store the question set, ` context.json` provide the evaluation context, and ` runs/run-example` represent the results directory generated from a single sampling. To require JSON output, add the command that supports this option `--format json`; specific parameters can be ` sampler <command> --help`queried.

## Clearly define configuration priorities and effective sources.

Before sampling, the Agent needs to configure the browser and control model, and then specify the platform and issue to be collected. During the design `setup` phase, it's crucial to distinguish which settings can be reused and which should be passed in each time.

- **By `setup` saving relatively stable configurations**, such as whether to use a local or remote browser, service address, and default control model, subsequent tasks can directly read these settings.
- **The task is described by runtime parameters**, such as sampling platform, problem set, sampling mode, number of repetitions, and output location. Changing to a different batch of problems does not require re-initialization.

Concurrency levels, model selection, and other settings can have long-term default values, while also allowing for parameter overriding during the current run. Temporary overriding only affects the current task; the configuration should only be explicitly updated when long-term changes are needed. This aligns with [the CLI Guidelines' configuration recommendations](https://clig.dev/#configuration): select parameters or configuration files based on their frequency of change, and prioritize explicit parameters.

However, simply specifying priorities is insufficient. The evaluation command previously assigned default values ​​to batch size and concurrency directly at the CLI parameter layer. Even when the user didn't pass parameters, these values ​​still entered subsequent processing, obscuring the environment configuration for batch tasks.

After modification, the CLI first retains the "parameter not provided" status, and then determines the value:

- If no parameters are passed, the configuration or default value of the corresponding running mode will be read.
- Explicitly pass in parameters and use the values ​​provided by the caller.

The program can thus distinguish between "no concurrency specified" and "an explicit concurrency level that is exactly equal to the default value". The sampling configuration also specifies the merging order: CLI parameters take precedence over environment files, environment files take precedence over JSON configurations, and the model's default value is used last.

If a configuration fails to take effect, the Agent needs to know where the value comes from. The newly added information `config inspect` will list valid configurations, field sources, conflicts, missing items, and ignored configurations to help it determine which layer should be modified.

## Remove manual confirmation before execution

Once the configuration and task parameters are ready, the program will prompt for confirmation early on. Humans can confirm and continue; the agent, however, needs to recognize the prompts, maintain the process connection, and send input. If the calling tool does not support interaction, the command will stop here.

During the modification, the confirmation prompt was removed from the main execution path, allowing the caller to express their choices via parameters before execution. The initialization setup wizard is still retained, allowing both types of callers to complete the same configuration in different ways.

- When a user uses the app for the first time, `setup` they can learn and fill in the information step by step through the wizard, without having to memorize seven or eight options at the beginning.
- Once the agent has obtained the necessary configuration, all parameters are passed at once `setup`. If a non-interactive call lacks a required value, the program will report an error explaining what is missing.

[The CLI Guidelines](https://clig.dev/#interactivity) also recommend providing invocation methods that do not rely on prompts and answers, and explicitly reporting errors when input is missing in non-interactive mode. These practices are beneficial for script automation and are equally applicable to agents.

The platform login process requires users to complete QR code scanning and verification. `auth init` Provide a login portal; the Agent should instruct users to complete this step before proceeding with sampling.

## Explicitly specify the output format, stream output runtime events

Once execution begins, the Agent needs to read two types of information: the result when the task ends, and the real-time progress during execution. These address the questions of "what has been accomplished" and "where are we now?", respectively.

### Explicitly select human-readable or machine-readable format

When humans use the CLI directly, tables and prompts are easier to read. The agent, however, needs to read the number of successes, failures, and file locations. Therefore, the program provides two result formats:

- `--format human` Outputs human-readable content, which is also the default format.
- `--format json` Output structured results for the Agent or script to parse.

```bash
sampler sample run --config sampling.json --format human
sampler sample run --config sampling.json --format json
```

Early implementations would detect pipeline or CI environments and automatically switch to JSON. Later, this was changed to explicit selection to avoid the same command returning different formats depending on the calling environment.

JSON mode also needs to isolate regular logs. The final JSON itself might be error-free, but if even a single print statement from a third-party library gets mixed in, the entire stdout cannot be directly `json.loads()` parsed. Therefore, the program redirects the underlying runtime's regular output to stderr, allowing stdout to retain the final JSON.

### Output runtime events line by line using NDJSON

Browser sampling requires submitting a question, waiting for a response, and then extracting the content. Only the final JSON is returned, and the Agent cannot see the running status during this waiting period.

The program provides an NDJSON event stream for this purpose, writing information such as sampling start and waiting for heartbeats into independent JSON objects, each object occupying one line. The caller can parse it as soon as it receives a complete line, without waiting for the entire JSON array to close. This line-by-line organization method comes from [the NDJSON specification](https://github.com/ndjson/ndjson-spec); to ensure timely event delivery, the program also actively flushes the output buffer after each write.

Below is an example after omitting fields such as timestamps:

```jsonl
{"sequence":1,"event":"sample_item_started","platform":"site-a","query_id":"q1"}
{"sequence":2,"event":"sample_item_heartbeat","platform":"site-a","query_id":"q1","elapsed_seconds":30}
```

The sampling command enables `--events ndjson` event output:

```bash
sampler sample run --config sampling.json --events ndjson
```

The sampling command writes NDJSON to stdout and ordinary logs to stderr. The `--events ndjson` and `--format json` options are mutually exclusive. An agent can then read one event per line without mixing in logs or a different output format.

## Add heartbeat feedback and set timeout limits.

While the browser waits for a response, the page may remain blank for an extended period. The program periodically reports the current sampled item and the elapsed waiting time via heartbeats, letting the Agent know that the process is still running and which response it is waiting for.

The waiting process must also have a termination condition. The program handles several timeout types:

- **Single sampling timeout**: Record the failure and continue with subsequent tasks.
- **Browser closed or background cleanup timed out**: End the cleanup wait to prevent CLI from failing to exit even when the task has already reported an error.
- **User login timeout**: End the current wait and report login failure.

When evaluating the call to the model service, automatic retries may also be initiated. `Retry-After` Upon receiving a server response, the program will wait for that specified time; otherwise, a capped random backoff will be used. Retry events are logged with the failure type and waiting time, allowing the agent to see that the program is automatically retries, thus preventing the repeated initiation of the same task.

## Return to structured errors and fix suggestions

If you are not logged in, sampling will be blocked before submitting the issue. Simply rerunning the sampling will not solve the problem; you need to log in first.

If only "Login status error" is returned, the agent still needs to guess the reason and find the handling command. The program later added error categories, specific reasons, and remedial suggestions. Below is a simplified anonymization example:

```json
{
  "schema_version": "cli-json/v1",
  "status": "failed",
  "error": "auth_precheck_failed",
  "error_category": "auth_required",
  "reason": "Missing auth state for site-a.",
  "remediation": "Run sampler auth init site-a."
}
```

These fields provide the information needed for the next step:

- `error_category` The authentication issue needs to be addressed; simply retrying sampling won't help.
- `reason` The missing ` site-a` login status can pinpoint the specific platform.
- `remediation`: Which command to run first; if scanning is required, ask the user to complete it before continuing sampling.

This is a concrete example of Agent-Friendly's user experience: when an error occurs, it explains the cause and provides actionable next steps, reducing the need to consult manuals, guess parameters, and engage in repeated trial and error. [Anthropic's tool design experience](https://www.anthropic.com/research/writing-tools-for-agents) also suggests that error responses should provide specific and actionable improvement information to help the Agent correct subsequent calls.

When standardizing error output, the parameter parsing phase should also be covered. Unknown options may be rejected by the CLI framework before entering the business function; handling JSON errors only within the business function cannot cover these types of errors.

## Returns an execution summary; the complete results are saved to a file.

After a batch of tasks is completed, the Agent first needs to determine whether the results are usable. Assuming that eight out of ten samples are successful and two fail, simply checking whether the process exited normally is not enough.

The program retains the number of successes, failures, and task status in the summary: \_ for all successes `completed`, \_ for partial failures ` completed_with_errors`, and \_ for failure status ` failed`. `--allow-errors` It allows exiting with a success exit code even in the event of sampling errors, but will not change the failure status in the result to success. Subsequent processes can continue to run, and the Agent can also identify tasks that are not yet completed.

The response text can be quite long, so the CLI returns a summary, product path, and subsequent actions, saving the complete input, response, dosage, and summary to the runtime directory. The Agent first determines whether to handle failures, then reads the response or proceeds to evaluation as needed.

- `runs inspect` Offline check to ensure file integrity and that the number of summaries matches the number of outputs.
- `evaluate run`: Evaluate existing sampling results without having to open the browser again.
- `evaluate external`: Receives files or standard input and processes data processed by other programs.

This aligns with [Anthropic's context engineering approach](https://www.anthropic.com/research/effective-context-engineering-for-ai-agents) of retrieving information on demand: first, retain file paths and other references, then read the detailed content when needed. For this sampling program, this also means that existing responses can be reused after modifying the evaluation method, reducing redundant sampling.

After the output is written, the program generates `DONE` a flag; the specific number of samples completed and which entries failed are described in the summary and task status. The agent can then decide whether to proceed directly to the evaluation or handle the failed items first.

## Clearly define breakpoint recovery capabilities and retry scope.

After identifying which tasks have failed, the agent needs to determine what will happen if it restarts: whether it can continue from where it left off, or whether it will resample or incur model costs again.

The way samples and evaluations are saved directly affects the cost of retrying.

- **The sampling process accumulates results in memory and writes them to a file upon completion.** If the process is forcibly terminated midway, completed responses may be lost. Rerunning the original input on a failed platform will also repeat entries that were already successful on that platform; therefore, the scope of the rerun needs to be specified to the Agent.
- **The evaluation process saves checkpoints item by item and records retry budgets.** Saved progress can be reused during re-execution, reducing repeated calls to the billing model. For records where the budget is exhausted, the agent can `--retry-failed` explicitly initiate a new round of attempts.

Retry suggestions should also include necessary input. For example, if the output does not echo the original query, explicitly prompt for additional original input so that the agent can formulate an executable retry command.

## Desensitize sensitive output

When providing information to the Agent, you also need to handle the keys, cookies, and remote browser connection addresses that the program accesses. Command results enter the Agent context and may also be saved or transferred to other tools.

The program centralizes the desensitization process in the public JSON output, replacing sensitive fields in the returned results and setting access permissions for the authentication file. The agent can obtain diagnostic results without simultaneously receiving authentication credentials.

Remote login `viewer_url` is used for handover operations. The program retains a complete link in the login handover output, allowing the Agent to hand over the entry point to the user, who can then open a browser to complete the login. Data anonymization must hide authentication credentials while retaining the information necessary to complete the current operation.

## Allow the agent to make informed decisions about the next step.

The biggest change in this upgrade is that information that previously required manual input has been transformed into content that the agent can directly read and query. Previously, humans would check logins, trace configuration sources, and decide which failed tasks were worth rerunning; now, even with the agent, these judgments still require a basis.

Non-interactive calls, structured output, and clear error messages are standard practice for excellent CLIs. When dealing with agents, I focus more on whether this information can support their continued task completion: what is currently happening, what work has been completed, what obstacles have been encountered, and what operations are still available. The CLI executes specific operations and reports the facts, while the agent analyzes this information in conjunction with the task objectives and selects the next command.

**Exposing sufficient information to enable agents to make informed decisions is the most important feature of the AI-Friendly CLI.** It provides summaries of results, progress reports on events, handling suggestions for errors, and retains access to the full content. Ensuring agents have access to relevant information when needed allows them to better leverage their analytical and reasoning capabilities, enabling the CLI's core tasks to be completed more smoothly.
