# API

readerly has one main entry point and eleven subpaths. Most commands need only `createOut`. The subpaths export the parts it is built from, for tools that keep their own output code.

## Entry points

| Import | Exports |
| --- | --- |
| `readerly` | Everything below, plus `processIo`, `countsText`, `verdictWord`, `withFlag` and every type |
| `readerly/out` | `createOut`, `OutOptions`, `Out`, `Verdict`, `DiagnosticInput`, `ConfirmQuestion`, `AskQuestion` |
| `readerly/detect` | `detect`, `DetectInput`, `ciName`, `harnesses`, `HarnessRow`, `Marker` |
| `readerly/profile` | `resolveProfile`, `ProfileInput`, `formatEnvName`, `readerFlags` |
| `readerly/color` | `colorDecision`, `colorEnabled`, `createStyle`, `ColorInput` |
| `readerly/budget` | `DEFAULT_REPORT_BUDGET`, `planBudget`, `shownGroups`, `hiddenCounts`, `hasHidden` and their types |
| `readerly/github` | `githubAnnotations` |
| `readerly/progress` | `createProgress`, `ProgressOptions` |
| `readerly/prompt` | `canPrompt`, `ask`, `confirm`, `readInput`, `PromptSpec`, `AskSpec`, `ConfirmSpec` |
| `readerly/envelope` | `failure`, `actionRequired`, `FailureError`, `toFailure`, `exitCodes`, `FailureExtra` |
| `readerly/tree` | `tree` |
| `readerly/nostics` | `fromNostics`, `nosticsReporter`, `DiagnosticLike`, `NosticsMethod` |

The shared types, such as `Profile`, `Detection` and `DiagnosticRecord`, come from `readerly`. The built-in renderers are not exported. Reach them through `createOut`.

## readerly/out

### createOut

```ts
function createOut<Result extends object = object>(options: OutOptions<Result>): Out<Result>
```

Resolves the profile from `argv`, `io` and detection, then collects entries and renders them once through the renderer for the picked format. `Result` types `out.set()` and `run.result`. Throws `No renderer for format <name>.` when the format has no renderer. A bad `--format` or `--max-chars` doesn't throw. It becomes a usage failure that `end()` and `fail()` print with exit code 2. See [Failures and exit codes](https://readerly.loadsheet.dev/guide/failures#bad-reader-flags).

### OutOptions

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `tool` | `string` | required | The tool's name, as in the verdict, the rerun command, the schema and `<TOOL>_FORMAT`. |
| `command` | `string` | | The subcommand, such as `check`. |
| `version` | `string` | | Goes in jsonl's `version` record as `tool@version`. |
| `schema` | `string` | `` `${tool}.${command ?? "run"}/v1` `` | The json and jsonl schema name. |
| `argv` | `readonly string[]` | | The arguments after the command. readerly reads the [reader flags](https://readerly.loadsheet.dev/guide/flags) and keeps the rest for `rerun`. |
| `formats` | `readonly string[]` | | Formats the tool accepts beyond the built-in four. |
| `renderers` | `Partial<Record<string, Renderer<Result>>>` | | Replaces the renderer of each format named. |
| `render` | `Renderer<Result>["render"]` | | Replaces every format's rendering. Wins over `renderers`. |
| `summary` | `(result: Partial<Result>, counts: Counts) => string \| undefined` | | Words after the counts on the verdict line, such as `in 212 files (0.8s)`. |
| `maxRows` | `number` | `50` | Rows `text` shows at a terminal before it hides the rest. |
| `io` | `Partial<Io>` | `processIo()` | The env, streams, stdin and clock. Missing fields come from the process. |
| `detection` | `Detection` | `detect()` | Detection to use instead of detecting from `io`. |

### Out

| Method | What it does |
| --- | --- |
| `readonly profile: Profile` | The resolved profile. |
| `log(text: string): void` | A line for people. `text` streams it to stdout, `jsonl` writes a `log` record, `agent` budgets it, `json` drops it, `--quiet` hides it in `text`. |
| `debug(text: string): void` | A line on stderr, only with `--verbose`. |
| `error(d: string \| DiagnosticInput): void` | Adds an error. |
| `warn(d: string \| DiagnosticInput): void` | Adds a warning. |
| `info(d: string \| DiagnosticInput): void` | Adds an info. |
| `diagnostic(d: DiagnosticRecord): void` | Adds a record with its own `severity`. |
| `set(fields: Partial<Result>): void` | Merges `fields` into the result with `Object.assign`. |
| `next(command: string, reason?: string): void` | Suggests a command to run next. |
| `progress(label: string): Progress` | Progress on stderr in `text`, unless `--quiet`. A no-op in other formats. |
| `confirm(question: ConfirmQuestion): Promise<boolean>` | Resolves a yes or no. See [Prompts and input](https://readerly.loadsheet.dev/guide/prompts). |
| `ask(question: AskQuestion): Promise<string>` | Resolves a string value. |
| `write(answer: string): void` | Sets an answer the tool rendered itself. |
| `fail(error: unknown): number` | Renders the failure and returns its exit code. |
| `end(verdict?: Verdict): number` | Renders the run and returns its exit code: 0 ok, 1 failed, 2 action_required. |

Call `end` or `fail` once. A second call throws `out.end or out.fail was already called.` With `--verbose`, the first output also writes the profile's choices to stderr, one per line, such as `format: text (detected terminal (stdout.isTTY))`.

### Related types

```ts
type DiagnosticInput = Omit<DiagnosticRecord, "severity">;
type ConfirmQuestion = Omit<ConfirmSpec, "profile" | "input" | "flush" | "onDefault" | "io">;
type AskQuestion = Omit<AskSpec, "profile" | "input" | "flush" | "onDefault" | "io">;

interface Verdict {
  status?: Status;
  /** Replaces `OutOptions.summary` for this run. */
  summary?: string;
}
```

## readerly/detect

```ts
function detect(input?: DetectInput): Detection

interface DetectInput {
  env?: Env;
  stdout?: { isTTY?: boolean; columns?: number };
  stderr?: { isTTY?: boolean };
  stdin?: { isTTY?: boolean };
  /** Skips detection: `true` makes the reader an agent, `false` rules one out. */
  agent?: boolean;
}
```

Works out the reader and why. Synchronous, and writes nothing. Each missing field comes from the real process. `detect({ env: { AI_AGENT: "claude-code" } })` with no TTYs returns reader `agent`, reason `AI_AGENT` and agent `{ id: "claude-code", raw: "claude-code", strength: "declared" }`. See [Readers](https://readerly.loadsheet.dev/guide/readers).

```ts
function ciName(env: Env): string | undefined
```

The CI provider the env names, such as `github-actions`, `generic` for a bare `CI`, or `undefined` outside CI and when `CI` is `0`, `false`, `no` or `off`.

```ts
const harnesses: readonly HarnessRow[]
type Marker = string | readonly [name: string, value: string];
interface HarnessRow {
  id: string;
  prefix?: string | readonly string[];
  strong?: readonly Marker[];
  weak?: readonly Marker[];
  session?: string;
  effort?: string;
  version?: string;
  verified?: boolean;
}
```

The harness registry `detect` reads. A bare `Marker` means the variable is set and not falsy, and a tuple means it equals the value. Strong markers are set only while a model runs the command. Weak ones count only off a TTY and outside CI. See [Coding agents](https://readerly.loadsheet.dev/guide/agents).

## readerly/profile

```ts
function resolveProfile(input: ProfileInput): Profile

interface ProfileInput {
  tool: string;
  flags?: ReaderFlags;
  argv?: readonly string[];
  detection?: Detection;
  env?: Env;
  formats?: readonly string[];
}
```

Turns flags, env and detection into a `Profile`. Throws a usage `FailureError` on a bad `--format` or `--max-chars`. `createOut` calls it for you.

```ts
function formatEnvName(tool: string): string
```

The variable that sets a tool's format: `formatEnvName("vite-doctor")` is `VITE_DOCTOR_FORMAT`.

```ts
function readerFlags(argv: readonly string[]): ReaderFlags
```

Scans `argv` for the reader flags without throwing. It stops at `--` and leaves everything else in `rest` for your parser. `readerFlags(["src", "--json", "--max-chars=600", "-y", "--", "--full"])` returns `json: true`, `yes: true`, `maxChars: "600"` and `rest: ["src", "--", "--full"]`. See [Shared flags](https://readerly.loadsheet.dev/guide/flags).

## readerly/color

```ts
function colorDecision(input: ColorInput): { enabled: boolean; why: string }
function colorEnabled(input: ColorInput): boolean
function createStyle(enabled: boolean): Style

interface ColorInput {
  flag?: boolean;
  env: Env;
  isTTY: boolean;
}
```

`colorDecision` applies `--color`/`--no-color`, then `FORCE_COLOR`, then `NO_COLOR`, then a TTY whose `TERM` isn't `dumb`, and names the signal that decided. `colorEnabled` returns only the boolean. `createStyle(true)` wraps `styleText` from `node:util` and always emits escapes. `createStyle(false)` returns text unchanged. See [Color and glyphs](https://readerly.loadsheet.dev/guide/color).

## readerly/budget

```ts
const DEFAULT_REPORT_BUDGET = 8000;
function planBudget(fixed: number, groups: readonly BudgetGroup[], maxChars: number): BudgetUnit[]
function shownGroups(groups: readonly BudgetGroup[], units: readonly BudgetUnit[]): GroupShown[]
function hiddenCounts(groups: readonly BudgetGroup[], shown: readonly GroupShown[]): BudgetHidden
function hasHidden(hidden: BudgetHidden): boolean

interface BudgetGroup { tier: number; header: number; rows: number[]; detail: number }
type BudgetUnit =
  | { kind: "header"; group: number }
  | { kind: "row"; group: number }
  | { kind: "detail"; group: number };
interface GroupShown { header: boolean; rows: number; detail: boolean }
interface BudgetHidden { groups: number; rows: number; detail: number }
```

`planBudget` returns the units that fit in `maxChars` after `fixed`. `shownGroups` turns them into what each group shows, `hiddenCounts` counts what is left out, and `hasHidden` says whether anything is. See [Budget](https://readerly.loadsheet.dev/guide/budget#using-planbudget-on-its-own).

## readerly/github

```ts
function githubAnnotations(list: readonly DiagnosticRecord[], cap?: number): string
```

GitHub Actions workflow commands for the errors and warnings that have a `file`, at most `cap` of each kind, 10 by default, one per line. It returns the string and prints nothing. An error at `src/app.ts:14:3` with code `ACME001` becomes:

```text
::error title=ACME001,file=src/app.ts,line=14,col=3::Route handler reads process.env
```

See [GitHub Actions](https://readerly.loadsheet.dev/integrations/github-actions).

## readerly/progress

```ts
function createProgress(label: string, options?: ProgressOptions): Progress

interface ProgressOptions {
  stderr?: Writer;
  now?: () => number;
  shortLabel?: string;
  intro?: string;
  unit?: string;
}
```

Progress on stderr for a step that takes over 2 seconds. On a terminal it draws one line with a bar, the share done and the time left, rewrites it in place and clears it on `stop()`. Elsewhere it prints a line every 5 seconds. `shortLabel` replaces `label` on a narrow terminal, `intro` prints once before the first line off a terminal, and `unit` names what `done` and `total` count, `files` by default. See [Progress](https://readerly.loadsheet.dev/integrations/progress).

## readerly/prompt

```ts
function canPrompt(profile: Profile): boolean
function ask(spec: AskSpec): Promise<string>
function confirm(spec: ConfirmSpec): Promise<boolean>
function readInput<T = Record<string, unknown>>(source: string | undefined, io?: Partial<Io>): Promise<T | undefined>
```

`canPrompt` is true for a terminal reader on `text` with stdin and stderr TTYs and no `--no-input`. `ask` and `confirm` resolve a value from the flag, `--input`, the env, a prompt, the default, or throw `action_required`. `readInput` parses an `--input` value: inline JSON, `@file`, or `@-` for stdin. It returns `undefined` when `source` is.

```ts
interface PromptSpec {
  name: string;
  message: string;
  profile: Profile;
  flag?: string;
  env?: string;
  input?: Readonly<Record<string, unknown>>;
  rerun?: string;
  code?: string;
  required?: string;
  flush?: () => void;
  onDefault?: (flag: string | undefined) => void;
  io?: Partial<Io>;
}
interface AskSpec extends PromptSpec {
  value?: string;
  default?: string;
  choices?: readonly string[];
}
interface ConfirmSpec extends PromptSpec {
  value?: boolean | string;
  default?: boolean;
  requireExact?: string;
  reason?: string;
}
```

`createOut` fills in `profile`, `input`, `flush`, `onDefault` and `io`. Called directly, `flush` runs before a prompt writes anything and `onDefault` runs when the default answers without asking.

## readerly/envelope

```ts
function failure(kind: FailureKind, message: string, extra?: FailureExtra): Failure
function actionRequired(message: string, missing: Missing[], extra?: Omit<FailureExtra, "missing" | "status" | "exitCode">): FailureError
function toFailure(error: unknown): Failure
class FailureError extends Error {
  readonly failure: Failure;
  constructor(failure: Failure);
}
const exitCodes: { readonly ok: 0; readonly failed: 1; readonly usage: 2 };

interface FailureExtra extends Omit<Failure["error"], "message"> {
  schema?: string;
  status?: Status;
  exitCode?: number;
  missing?: Missing[];
  rerun?: string;
}
```

`failure` gives `usage` and `action_required` exit code 2 and the others 1, unless `extra.exitCode` says otherwise. `toFailure` keeps a `FailureError`'s failure and turns anything else into `runtime`. See [Failures and exit codes](https://readerly.loadsheet.dev/guide/failures).

## readerly/tree

```ts
function tree(headline: string, branches: ReadonlyArray<readonly [label: string, text: string]>, style?: Style): string
```

A headline and its `├▶ label: text` branches, the last one `╰▶`, with no trailing newline. With a style, the headline and labels are bold and the glyphs dim. See [Diagnostics](https://readerly.loadsheet.dev/guide/diagnostics#using-tree-on-its-own).

## readerly/nostics

```ts
function fromNostics(d: DiagnosticLike, severity?: Severity): DiagnosticRecord
function nosticsReporter(sink: DiagnosticSink): (d: DiagnosticLike, options?: { method?: NosticsMethod }) => void
type NosticsMethod = "log" | "warn" | "error";
```

`fromNostics` maps a nostics diagnostic, matched by shape, to a record: `code` from `code` or `name`, `message` from `message` or `why`, and the first source as the location. The severity defaults to `warn`. `nosticsReporter` hands each diagnostic to a sink such as `out`, with `error` mapped to error, `warn` to warn and `log` to info. See [nostics](https://readerly.loadsheet.dev/integrations/nostics).

## Root-only exports

```ts
function processIo(): Io
function countsText(counts: Counts): string
function verdictWord(status: Status): string
function withFlag(rerun: string, flags: string): string
```

`processIo` reads `process.env`, the process streams and `Date.now()` each time a field is read. `countsText` gives `2 errors, 1 warning`, or `no problems`. `verdictWord` gives `ok`, `failed` or `action required`. `withFlag` adds flags before a `--`: `withFlag("acme check src -- extra", "--fix")` is `acme check src --fix -- extra`.

## Types

All from [`src/types.ts`](https://github.com/loadsheet/readerly/blob/main/src/types.ts), exported from `readerly`.

```ts
type Env = Readonly<Record<string, string | undefined>>;
type Reader = "agent" | "ci" | "terminal" | "pipe";
type Format = "text" | "agent" | "json" | "jsonl" | (string & {});
type Verbosity = "quiet" | "normal" | "verbose";
type Severity = "error" | "warn" | "info";
type Status = "ok" | "failed" | "action_required";
type FailureKind = "usage" | "config" | "runtime" | "action_required";
type Style = (format: StyleFormat | readonly StyleFormat[], text: string) => string;

interface AgentInfo {
  id: string;
  raw?: string;
  version?: string;
  mode?: "agent" | "harness";
  strength: "declared" | "strong" | "weak";
  sessionId?: string;
  effort?: string;
  wrapper?: { id: string; threadId?: string };
}

interface Detection {
  reader: Reader;
  reason: string;
  agent?: AgentInfo;
  ci?: { name: string };
  stdout: { isTTY: boolean; columns?: number };
  stderr: { isTTY: boolean };
  stdin: { isTTY: boolean };
}

interface ReaderFlags {
  format?: string;
  json: boolean;
  full: boolean;
  maxChars?: string;
  color?: boolean;
  noInput: boolean;
  yes: boolean;
  verbose: boolean;
  quiet: boolean;
  input?: string;
  rest: string[];
}

interface Profile {
  format: Format;
  color: boolean;
  interactive: boolean;
  budget: number;
  full: boolean;
  yes: boolean;
  verbosity: Verbosity;
  annotations?: "github";
  detection: Detection;
  why: Record<"format" | "color" | "interactive" | "budget", string>;
}

interface DiagnosticRecord {
  severity: Severity;
  code?: string;
  message: string;
  why?: string;
  fix?: string;
  docs?: string;
  file?: string;
  line?: number;
  column?: number;
  endLine?: number;
  endColumn?: number;
  sources?: string[];
  data?: unknown;
}

interface Missing { field: string; flag?: string; env?: string; choices?: readonly string[] }

interface Failure {
  schema?: string;
  kind: FailureKind;
  status: Status;
  exitCode: number;
  error: { code?: string; message: string; why?: string; fix?: string; docs?: string; file?: string };
  missing?: Missing[];
  rerun?: string;
}

interface Writer { write(chunk: string): unknown; isTTY?: boolean; columns?: number }
interface StdinLike { isTTY?: boolean; [Symbol.asyncIterator]?(): AsyncIterator<unknown> }
interface Io { env: Env; stdout: Writer; stderr: Writer; stdin: StdinLike; now(): number }

interface DiagnosticSink { diagnostic(d: DiagnosticRecord): void }
interface ProgressUpdate { done: number; total: number; doneBytes?: number; totalBytes?: number }
interface Progress { update(progress: ProgressUpdate): void; stop(): void }

type Entry =
  | { type: "diagnostic"; diagnostic: DiagnosticRecord }
  | { type: "log"; message: string }
  | { type: "next"; command: string; reason?: string };
interface Counts { error: number; warn: number; info: number }
```

`StyleFormat` is a single format name accepted by `styleText` from `node:util`, such as `"red"` or `"bold"`. `RunState`, `RenderContext`, `Chunk` and `Renderer` are on [Custom renderers](https://readerly.loadsheet.dev/guide/renderers).

<!-- vitehub-docs:section-links -->
## In this section

- [Introduction](https://readerly.loadsheet.dev/raw/guide.md)
- [Installation](https://readerly.loadsheet.dev/raw/guide/installation.md)
- [Readers](https://readerly.loadsheet.dev/raw/guide/readers.md)
- [Coding agents](https://readerly.loadsheet.dev/raw/guide/agents.md)
- [Formats](https://readerly.loadsheet.dev/raw/guide/formats.md)
- [Shared flags](https://readerly.loadsheet.dev/raw/guide/flags.md)
- [Color and glyphs](https://readerly.loadsheet.dev/raw/guide/color.md)
- [Diagnostics](https://readerly.loadsheet.dev/raw/guide/diagnostics.md)
- [Budget](https://readerly.loadsheet.dev/raw/guide/budget.md)
- [Prompts and input](https://readerly.loadsheet.dev/raw/guide/prompts.md)
- [Failures and exit codes](https://readerly.loadsheet.dev/raw/guide/failures.md)
- [JSON and JSONL](https://readerly.loadsheet.dev/raw/guide/json.md)
- [Custom renderers](https://readerly.loadsheet.dev/raw/guide/renderers.md)
- [API](https://readerly.loadsheet.dev/raw/guide/api.md) (this page)

All pages: [llms.txt](https://readerly.loadsheet.dev/llms.txt)
