@wirecat/cli-base 0.110.0 → 0.111.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,28 @@ Versions before 0.8.0 are in the [git tags](https://github.com/WireCatLabs/cli-b
8
8
  Every entry says what changed as a caller sees it, why, and what to watch for — the rules are
9
9
  [`docs/dev/CONVENTIONS.md`](docs/dev/CONVENTIONS.md#the-changelog).
10
10
 
11
+ ## 0.111.0 — 17.11.2026
12
+
13
+ ### Added
14
+
15
+ - **Codegen writes what each operation answers.** `typesGenerator` adds `Responses`, a map from operation id to its
16
+ answer type, so a config-built CLI's paths into an answer are checked in the editor. A new `examplesGenerator` writes
17
+ the spec's own sample answers (each under 8 KB, none from an answer that holds a credential) to their own file, for a
18
+ fake to answer with. A schema named `Responses` now stops generation, since it would collide. After the bump, run
19
+ `pnpm generate`: each generated `types.ts` gains `Responses`, so `--check` calls it stale until then.
20
+ - **A spec that names no operation still generates.** Attio's OpenAPI file has no `operationId` at all, so it gave an
21
+ empty catalog. Now each call gets an id from its method and path (`GET /v2/objects/{object}` →
22
+ `getV2ObjectsByObject`). A spec that names some operations still skips the paths without one, as before.
23
+ - **README rules that put the reader's gain first.** [The README rule](docs/standards/docs.md#wc-doc-7--readmemd-is-the-full-introduction-to-the-tool)
24
+ now asks for tg-cli's order: what you get and why this tool before the quick start. A
25
+ [new rule](docs/standards/docs.md#wc-doc-23--a-librarys-or-a-kits-readme-opens-with-what-you-build-a-proof-and-who-builds-on-it)
26
+ gives libraries and kits their own order: a hero line, a proof, "Built on it", install, the links, and the
27
+ documents table at the end. Both are checked in review, so no CLI fails a check. A README in max-cli's order
28
+ (quick start first) is now out of step and moves at its next rewrite.
29
+ - **The live check before a release is WireCat's own.** [WC-REL-17](docs/standards/releases.md#wc-rel-17--a-release-pull-request-says-what-was-checked-and-the-release-needs-a-recorded-live-check)
30
+ now names its exception for a CLI made outside WireCat with cli-template's `new --preset generic`: its
31
+ `bin/release` needs no recorded live check. WireCat's own CLIs keep the gate.
32
+
11
33
  ## 0.110.0 — 17.11.2026
12
34
 
13
35
  ### Added
package/README.md CHANGED
@@ -1,208 +1,107 @@
1
- <img src="https://raw.githubusercontent.com/WireCatLabs/cli-base/main/docs/images/social-preview.png" alt="The foundation for agent-ready CLIs: output for people and machines, stable exit codes, keyring, testable clocks" width="100%">
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/WireCatLabs/cli-base/main/docs/images/social-preview.png" alt="cli-base: CLIs that scripts and AI agents can trust" width="100%">
3
+ </p>
2
4
 
3
5
  # @wirecat/cli-base
4
6
 
5
- The foundation for command-line tools that people and AI agents both use. Output for a person and for a program,
6
- a closed error model with stable exit codes, secrets in the OS keyring, injectable clocks, one query language,
7
- the command tree as data — the parts every CLI needs and nobody should write twice.
7
+ Build a command-line tool that a script and an AI agent can trust, in TypeScript on Node or Bun. cli-base keeps data
8
+ on stdout and everything else on stderr, and turns every failure into one JSON error with a stable exit code.
8
9
 
9
- [Architecture](docs/dev/ARCHITECTURE.md) · [API reference](docs/REFERENCE.md) · [Shared tooling](docs/TOOLING.md) ·
10
- [Testing](docs/dev/TESTING.md) · [Changelog](CHANGELOG.md) · [wirecat.dev](https://wirecat.dev)
10
+ ```ts
11
+ import { CliError, captureStreams, createRenderer, errorObjectOf, exitCodeOfError, renderError } from "@wirecat/cli-base"
11
12
 
12
- [![npm](https://img.shields.io/npm/v/@wirecat/cli-base)](https://www.npmjs.com/package/@wirecat/cli-base)
13
- [![CI](https://github.com/WireCatLabs/cli-base/actions/workflows/ci.yml/badge.svg)](https://github.com/WireCatLabs/cli-base/actions/workflows/ci.yml)
14
- [![Node](https://img.shields.io/node/v/@wirecat/cli-base)](https://nodejs.org/)
15
- [![Bun](https://img.shields.io/badge/bun-tested-f9f1e1)](https://bun.sh/)
16
- [![License: Apache 2.0](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
13
+ const streams = captureStreams()
14
+ createRenderer({ format: "json", color: false, streams }).result({ chats: 2 })
17
15
 
18
- ## Key documents
16
+ const error = errorObjectOf(new CliError("not_found", "No chat named Alice"))
17
+ streams.diagnostic(renderError(error, { cli: "acme", interactive: false }))
19
18
 
20
- | Document | What it answers |
21
- |---|---|
22
- | [Architecture](docs/dev/ARCHITECTURE.md) | The entry points, the lines this package does not cross, who consumes what |
23
- | [API reference](docs/REFERENCE.md) | What each entry point holds, with examples |
24
- | [Shared tooling](docs/TOOLING.md) | The TypeScript, Biome, lefthook, docs and CI setup a CLI takes from here, and `cli-dev` |
25
- | [Publishing](docs/PUBLISHING.md) | Where a CLI is published beyond npm, how to prove it, and what has gone wrong |
26
- | [Testing](docs/dev/TESTING.md) | The checks, and what each one is for |
27
- | [Conventions](docs/dev/CONVENTIONS.md) | How code here is written |
28
- | [Standards handbook](docs/standards/README.md) | The rules every WireCat CLI follows, one page per area and a new-CLI checklist |
29
- | [CLI standard](https://github.com/WireCatLabs/cli-core/blob/main/docs/dev/STANDARD.md) | The messenger-specific rules for tg, max and wa |
30
- | [Roadmap](docs/roadmap.md) | What is being built next for developers on this package |
31
- | [Changelog](CHANGELOG.md) | What each version changed, and what may break callers |
19
+ streams.stdout // ['{"chats":2}']
20
+ streams.stderr // ['{"error":{"code":"not_found","reason":"item.not-found","message":"No chat named Alice","retry":{"safe":false}}}']
21
+ exitCodeOfError(error) // 6
22
+ ```
32
23
 
33
- ## What it is
24
+ No spinner, no `✓` and no warning ever reaches stdout in a machine mode, so `acme chats --json | jq` always gets clean
25
+ JSON. `captureStreams` lets a test prove it.
34
26
 
35
- Every WireCat tool is built on it: [tg-cli](https://github.com/WireCatLabs/tg-cli),
36
- [max-cli](https://github.com/WireCatLabs/max-cli), and [cli-core](https://github.com/WireCatLabs/cli-core) — the shared
37
- messaging engine — and through it the mail, notes, Zoom and Drive tools.
27
+ **Built on it:** [cli-core](https://github.com/WireCatLabs/cli-core) and 15 WireCat CLIs on top of it, among them
28
+ [tg-cli](https://github.com/WireCatLabs/tg-cli), [max-cli](https://github.com/WireCatLabs/max-cli) and
29
+ [gcal-cli](https://github.com/WireCatLabs/gcal-cli). [cli-testing](https://github.com/WireCatLabs/cli-testing) uses
30
+ it alone.
38
31
 
39
- Up to version 0.20.0 (October 2026) this package was `@wirecat/cli-core`. That name now belongs to the shared
40
- messaging engine: in older changelogs, plans and issues, "cli-core" means this package. Those old
41
- `@wirecat/cli-core` versions (0.18–0.20) are deprecated on npm.
32
+ ## Install
42
33
 
43
34
  ```sh
44
35
  npm install @wirecat/cli-base
45
36
  ```
46
37
 
47
- It is ESM only, for Node 22 and later: `import` it (`require()` works from Node 22.12). Add `commander` if you use
48
- `/skill`, and `vitest` if you use `/testing/setup`.
38
+ It is ESM only, for Node 22 and later, and runs on Bun. `import` it (`require()` works from Node 22.12). Add
39
+ `commander` if you use `/skill`, and `vitest` if you use `/testing/setup`.
49
40
 
50
- **One rule shapes everything here: in a machine mode, stdout carries data and nothing else.** No spinner, no `✓`, no
51
- warning, no ANSI. Diagnostics go to stderr, in every mode including the pretty one. That is the contract a script or
52
- an agent depends on, and `captureStreams` exists so a test can prove nothing leaked across.
41
+ [API reference](docs/REFERENCE.md) · [Architecture](docs/dev/ARCHITECTURE.md) · [Shared tooling](docs/TOOLING.md) ·
42
+ [Standards handbook](docs/standards/README.md) · [Changelog](CHANGELOG.md) · [wirecat.dev](https://wirecat.dev)
53
43
 
54
- ```ts
55
- import { captureStreams, createRenderer } from "@wirecat/cli-base"
44
+ [![npm](https://img.shields.io/npm/v/@wirecat/cli-base)](https://www.npmjs.com/package/@wirecat/cli-base)
45
+ [![CI](https://github.com/WireCatLabs/cli-base/actions/workflows/ci.yml/badge.svg)](https://github.com/WireCatLabs/cli-base/actions/workflows/ci.yml)
46
+ [![Node](https://img.shields.io/node/v/@wirecat/cli-base)](https://nodejs.org/)
47
+ [![Bun](https://img.shields.io/badge/bun-tested-f9f1e1)](https://bun.sh/)
48
+ [![License: Apache 2.0](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
56
49
 
57
- const streams = captureStreams()
58
- createRenderer({ format: "json", color: false, streams }).result({ chats: 2 })
50
+ ## Which package to install
59
51
 
60
- streams.stdout // ['{"chats":2}']
61
- streams.stderr // []
52
+ ```mermaid
53
+ flowchart LR
54
+ cli["Your CLI"] -->|"keeps messages, mail or files to search"| core["@wirecat/cli-core"]
55
+ cli -->|"any other CLI"| base["@wirecat/cli-base"]
56
+ core --> base
57
+ base --> runtime["Node or Bun"]
62
58
  ```
63
59
 
64
- ## Architecture
65
-
66
- The package is split by **when** a piece runs, so a tool loads only what it calls:
67
-
68
- | When | Entry points |
69
- |---|---|
70
- | Every command | root: streams, renderer, errors and exit codes, keyring, credentials, paths, config, time, retry, logging, field selection, output buffer, deadlines |
71
- | Only if the tool speaks HTTP | `/http` |
72
- | Every command that answers | `/standards`: effects, errors, output envelopes, log record, next steps |
73
- | Commands that describe the tool | `/commands`, `/completion`, `/query`, `/skill`, `/mcp`, `/update`, `/standards/tables` |
74
- | Build time | `/codegen`, with a small `/codegen/runtime` for the generated schemas |
75
- | Release time | `/release` |
76
- | Tests | `/testing`: captured streams, memory and broken keyrings, a fake clock |
77
- | Configuration | `biome`, `tsconfig.*.json`, `lefthook.yml`, `cspell` presets |
78
-
79
- Three lines this package does not cross:
80
-
81
- - **Nothing in the root export is HTTP.** Status classification, `Retry-After` and the fetch seam live in `/http`, so a
82
- CLI that speaks a WebSocket never carries an HTTP stack.
83
- - **The environment is an argument.** The clock, the sleep, the keyring, `env`, `fetch` and the streams are all
84
- parameters; the real ones are only defaults. A timeout test finishes instantly, and a keyring test cannot reach a
85
- real keychain.
86
- - **It logs nothing and prints nothing by itself.** It hands the host a `Logger` interface, a Pino adapter and a
87
- renderer; what is written, and where, is the host's call.
88
-
89
- Four runtime dependencies: valibot and its JSON Schema converter, cli-table3 and cross-spawn; colour is `node:util`. Commander is
90
- an optional peer: `/commands` and `/completion` use only its types, and `/skill` needs it installed at run time.
60
+ Install [cli-core](https://github.com/WireCatLabs/cli-core) when your tool keeps what it reads in a local store and
61
+ searches it. It brings cli-base along as a peer. For any other CLI, cli-base alone is enough.
91
62
 
92
63
  ## Features
93
64
 
94
- ### Output for people and machines
95
-
96
- - **Three formats from one renderer:** `pretty` for a person — tables for lists, labelled lines for objects — and
97
- `json` or `jsonl` for a program. `quiet` keeps only failures.
98
- - **Field selection** (`--json=id,speaker.id`) that keeps the list envelope and the operation ids, and refuses unsafe
99
- paths.
100
- - **A bounded output buffer.** Output waits until the command succeeds and has closed what it holds; past the limit
101
- (4 MiB by default) it fails visibly instead of truncating.
102
-
103
- ### Errors a script can branch on
104
-
105
- Fourteen closed error codes, one exit number each: validation, configuration, authentication, permission, not found,
106
- rate limited, timeout, network, provider, outcome unknown and the rest. A script branches on `$?`, an agent on the
107
- `code` and `reason` in one JSON object on stderr. Errors are recognised by a brand, so two installed copies of the
108
- package still understand each other's errors.
109
-
110
- ### The standard, as data a machine checks
111
-
112
- The rules every WireCat CLI follows — the verb vocabulary, the output envelope, the error reasons, next steps, the log
113
- record — live in `/standards` as Valibot schemas that also emit JSON Schema 2020-12.
114
-
115
- - **The whole command tree as data.** `describeProgram` walks the live Commander tree, like `rails routes`: every
116
- command, option, default, conflict and whether it writes. `commands --json` gives it to an agent instead of `--help`.
117
- - **A linter for command trees.** `cli-dev lint` checks a CLI's tree against 19 rules — unknown verbs, filter flags
118
- that should be query fields, examples that do not run, key casing and more. Known violations live in a baseline
119
- that may only shrink.
120
- - **An audit across CLIs.** `cli-dev audit` reads several CLIs' command trees and checks them against each other:
121
- the commands every CLI must have, the same options and output where two CLIs share a path, the same meaning for the
122
- same flag. Entity-schema and error-reason comparisons require additional inputs; the weekly published-CLI
123
- run does not supply them and reports `n/a` for those checks.
124
-
125
- ### One query language for every list
126
-
127
- `tasks list state:open priority>1`: a port of the Lucene 9.12.3 parser, with the fields read from the entity's own
128
- schema — strings, choices, numbers, times, booleans, references. A list filters where its data lives, in its store or
129
- at the provider, never in memory; `evaluate` exists only as a test oracle for those compilers. An unknown field fails
130
- with the list of fields that exist.
65
+ - **A script branches on `$?`, an agent on one JSON object.** 15 closed error codes, each with its own exit number:
66
+ 2 for a bad argument, 4 for a failed sign-in, 6 for not found. Errors are recognised by a brand, not a class, so two
67
+ installed copies of the package still understand each other's errors.
68
+ - **Output that never stops halfway.** `pretty` for a person, `json` or `jsonl` for a program, and `--json=id,name`
69
+ for only those fields. Output waits until the command succeeds, and past 4 MiB it fails with an error instead of
70
+ cutting the answer.
71
+ - **Tests that never wait.** The clock, the sleep, the keyring, `env`, `fetch` and the streams are arguments. A
72
+ timeout test finishes at once, a retry test needs no real backoff, and a keyring test cannot reach a real keychain.
73
+ `/testing` has the fakes.
74
+ - **Retries that never send twice.** Backoff with full jitter, and "no answer came" is never read as "safe to repeat".
75
+ A write whose outcome is unknown stays unknown and is not retried.
76
+ - **The command tree as data for an agent.** `commands --json` gives every command, option and default instead of
77
+ `--help`. `cli-dev lint` checks the tree against the shared vocabulary, and `cli-dev audit` compares several CLIs.
78
+ - **One query language for every list.** `tasks list state:open priority>1` is parsed by a port of the Lucene
79
+ 9.12.3 parser, with the fields read from the entity's own schema. An unknown field fails with the list of fields
80
+ that exist.
81
+ - **API clients that never guess.** `/codegen` turns an OpenAPI 3.0 or 3.1 document into types, Valibot schemas and an
82
+ operation manifest. It stops on an operation it cannot classify as a read, a write or a delete, and never falls back
83
+ to `any`.
84
+ - **Installs that stay current, and never update unasked.** The CLI knows which package manager installed it and
85
+ prints the command that updates it. `wcat tg …` runs `wcat-tg …`, so every WireCat tool is one command away.
131
86
 
132
87
  ### Secrets in the OS keyring, on every platform
133
88
 
134
- Credentials resolve environment → keyring → file, warning once and falling through when the keyring refuses.
89
+ Credentials resolve environment, then keyring, then file. When the keyring refuses, it warns once and falls through.
135
90
 
136
91
  | Platform | Backing store | Needs installing |
137
92
  |---|---|---|
138
- | macOS | Keychain, via the Security framework | nothing — part of the OS |
139
- | Windows | Credential Manager | nothing — part of the OS |
140
- | Linux desktop (GNOME, KDE) | Secret Service over D-Bus — `gnome-keyring`, `kwallet` | nothing on a normal desktop; the keyring must be **unlocked** |
141
- | Linux headless, container, WSL, CI | usually **nothing** — no session bus, no secrets daemon | falls back to a `0600` file, with one warning on stderr |
93
+ | macOS | Keychain, via the Security framework | nothing, part of the OS |
94
+ | Windows | Credential Manager | nothing, part of the OS |
95
+ | Linux desktop (GNOME, KDE) | Secret Service over D-Bus: `gnome-keyring`, `kwallet` | nothing on a normal desktop, the keyring must be **unlocked** |
96
+ | Linux headless, container, WSL, CI | usually **nothing**: no session bus, no secrets daemon | falls back to a `0600` file, with one warning on stderr |
142
97
  | FreeBSD | Secret Service, same as Linux | same |
143
98
 
144
- **No compiler is involved.** Prebuilt binaries cover twelve platform triples, and the Linux one speaks D-Bus itself,
145
- so libsecret is not a requirement. Checked against `@napi-rs/keyring` 2.1.0 on 2026-09-19.
146
-
147
- This repository's CI runs the tests on Linux only. macOS runs the path tests when they change, and that run does not
148
- block a merge (`macos.yml`); nothing runs on Windows here. A CLI built on this library can run its own unit suite
149
- on macOS and Windows through `node-ci.yml` with `platforms: true`; here, Full validation started by hand with
150
- `platforms` does the same. On 2026-10-18 that run passed on macOS and failed 14 tests on Windows (file modes,
151
- spawning `npm` and `tsc`). In every test the keyring is a fake, so no test reaches a real Keychain or Credential
152
- Manager.
153
-
154
- Two traps worth designing for: the keyring is global, so a throwaway config directory shares the owner's entry (pass
155
- `isolated: isMovedRun(…)` so it never deletes it); and a locked Linux keyring can block on a prompt rather than fail.
156
-
157
- ### Time, retries and deadlines
158
-
159
- - **Monotonic and wall clocks, and one sleep** that both timeouts and backoff use, so a fake clock controls both.
160
- - **Retries with full-jitter backoff**, and a distinction most retry helpers miss: "no answer came" is not "safe to
161
- repeat". A write whose outcome is unknown stays unknown.
162
- - **Cooperative deadlines.** A timeout waits for the command to settle before it rejects, so resources close in order.
163
-
164
- ### Files on disk
165
-
166
- - **Paths:** the XDG layout on Linux and macOS (`~/.config`, `~/.local/share`, `~/.cache`), `AppData` on Windows,
167
- each overridable by environment variable.
168
- - **Config** that names the bad field, and an atomic write with the file's own mode. A directory it creates gets
169
- `0700`; a directory that already exists keeps its mode.
170
- - **Logs** as one JSON record per line with OpenTelemetry field names. A top-level key outside the allow-list is
171
- written as `[not allowed]`. At any depth, a field named exactly as in `REDACTED_FIELDS` or the program's `redact`
172
- list (case-sensitive) and a field whose name marks message content are written as `[redacted]`.
173
-
174
- ### Generated API clients that never guess
175
-
176
- `/codegen` turns an API description into TypeScript types, Valibot schemas, an operation manifest and a coverage page.
177
- `adaptOpenApi` reads an OpenAPI 3.0 or 3.1 document, and `upgradeToOpenApi3` brings Swagger 1.2 and 2.0 to it;
178
- another format needs an adapter in the caller.
179
- Every operation is classified as a read, a write or destructive, with how far the source can be trusted. Generation
180
- stops, naming the problem, on a collision, an unclassified operation or a dangling reference — it never drops an
181
- operation and never falls back to `any`. 64-bit integers stay exact.
182
-
183
- ### Built for agents and for keeping installs current
184
-
185
- - **`skill show` and `skill install`** give a coding agent the CLI's own guide, versioned with the CLI; `skill status`
186
- says whether each installed copy matches it.
187
- - **MCP setup** for Codex and Claude Code, with a read-only handshake probe.
188
- - **Shell completion** from the command tree, answered from local data only — a shell asks on every Tab.
189
- - **Update checks that never update unasked.** Which package manager installed the CLI, the command that updates it,
190
- and a daily notice only when a person is at a terminal. A tool holding someone's credentials does not change itself.
191
- - **Release checks** every CLI shares: changelog shape, dead links, package contents, versions in step.
192
- - **`wcat`, one command for every tool.** `wcat tg …` runs `wcat-tg …`, like `git foo` runs `git-foo`, and any
193
- `wcat-<name>` program on PATH joins. `wcat --help` lists what is installed with each tool's description;
194
- `wcat shortcuts add` gives a tool its short name only where no other program has it. Each tool keeps the `wcat`
195
- launcher working on start, at the cost of a few `stat` calls.
196
-
197
- ## Engineering
198
-
199
- - **Both runtimes, executed.** Node 22+ and Bun; `pnpm smoke:bun` runs the same exports under Bun rather than
200
- assuming they work.
201
- - **One shared toolchain.** TypeScript, Biome, lefthook, CSpell, a Markdown linter and a reusable CI workflow — install, lint,
202
- typecheck, test with coverage, build, Bun and a gitleaks scan of the whole history. A CLI takes each piece on its
203
- own: [Shared tooling](docs/TOOLING.md).
204
- - **`cli-dev`** replaces the scripts every CLI used to copy: version sync, docs checks, slow-test reports, the test
205
- matrix and the command-tree lint.
99
+ No compiler is involved. Prebuilt binaries cover twelve platform triples, and the Linux one speaks D-Bus itself, so
100
+ libsecret is not needed. Checked against `@napi-rs/keyring` 2.1.0 on 2026-09-19. Two traps to design for, a shared
101
+ entry in a throwaway config folder and a locked Linux keyring, are in the
102
+ [API reference](docs/REFERENCE.md#where-secrets-actually-go-per-platform).
103
+
104
+ ## Development
206
105
 
207
106
  ```sh
208
107
  pnpm test # vitest, Node
@@ -212,13 +111,40 @@ pnpm typecheck
212
111
  pnpm build
213
112
  ```
214
113
 
114
+ Four runtime dependencies: valibot and its JSON Schema converter, cli-table3 and cross-spawn. A CLI takes its
115
+ TypeScript, Biome, lefthook, CSpell and CI setup from here, one piece at a time ([Shared tooling](docs/TOOLING.md)),
116
+ and `cli-dev` replaces the scripts every CLI used to copy. Which checks run on which platform is in
117
+ [Testing](docs/dev/TESTING.md#platforms).
118
+
215
119
  ## Releasing
216
120
 
217
121
  `bin/release` on `main` starts [`release.yml`](.github/workflows/release.yml), which runs every check and publishes
218
- through npm's [trusted publishing](https://docs.npmjs.com/trusted-publishers/) with provenance — no npm token in
219
- GitHub. It tags `v<version>` once npm shows the new version. The steps are in [RELEASING.md](docs/dev/RELEASING.md); how a release reaches the tools is in the
122
+ through npm's [trusted publishing](https://docs.npmjs.com/trusted-publishers/) with provenance, with no npm token in
123
+ GitHub. It tags `v<version>` once npm shows the new version. The steps are in [RELEASING.md](docs/dev/RELEASING.md),
124
+ and how a release reaches the tools is in the
220
125
  [architecture](docs/dev/ARCHITECTURE.md#how-a-change-is-published-and-picked-up).
221
126
 
127
+ ## Key documents
128
+
129
+ | Document | What it answers |
130
+ |---|---|
131
+ | [Architecture](docs/dev/ARCHITECTURE.md) | The entry points, the lines this package does not cross, who consumes what |
132
+ | [API reference](docs/REFERENCE.md) | What each entry point holds, with examples |
133
+ | [Shared tooling](docs/TOOLING.md) | The TypeScript, Biome, lefthook, docs and CI setup a CLI takes from here, and `cli-dev` |
134
+ | [Publishing](docs/PUBLISHING.md) | Where a CLI is published beyond npm, how to prove it, and what has gone wrong |
135
+ | [Testing](docs/dev/TESTING.md) | The checks, and what each one is for |
136
+ | [Conventions](docs/dev/CONVENTIONS.md) | How code here is written |
137
+ | [Standards handbook](docs/standards/README.md) | The rules every WireCat CLI follows, one page per area and a new-CLI checklist |
138
+ | [CLI standard](https://github.com/WireCatLabs/cli-core/blob/main/docs/dev/STANDARD.md) | The messenger rules for tg, max and wa |
139
+ | [Roadmap](docs/roadmap.md) | What is being built next for developers on this package |
140
+ | [Changelog](CHANGELOG.md) | What each version changed, and what may break callers |
141
+
142
+ ## History
143
+
144
+ Up to version 0.20.0 (October 2026) this package was `@wirecat/cli-core`. That name now belongs to the shared
145
+ messaging engine, so in older changelogs, plans and issues "cli-core" means this package. Those old `@wirecat/cli-core`
146
+ versions (0.18 to 0.20) are deprecated on npm.
147
+
222
148
  ## Licence
223
149
 
224
150
  [Apache License 2.0](LICENSE).
@@ -10,7 +10,7 @@
10
10
  export { adaptDiscovery, type DiscoveryMetadata, type DiscoveryOptions, type DiscoveryProvenance, type DiscoveryResult, type DiscoveryService, readDiscovery, type SyncDiscoveryOptions, syncDiscovery, } from "./discovery.js";
11
11
  export { type FakeAnswer, type FakeApi, type FakeApiOptions, type FakeCall, fakeApi, sampleOf, schemaProblems, } from "./fake.js";
12
12
  export { requestSchema } from "./json-schema.js";
13
- export { type CoverageOptions, coverageGenerator, definitionsGenerator, type ManifestOperation, manifestGenerator, } from "./manifest.js";
13
+ export { type CoverageOptions, coverageGenerator, definitionsGenerator, examplesGenerator, type ManifestOperation, manifestGenerator, } from "./manifest.js";
14
14
  export { type MergedSource, type MergeOptions, type MergeReport, mergeOpenApi, type SpecSource } from "./merge.js";
15
15
  export type { ApiBody, ApiModel, ApiOperation, ApiParameter, ApiSchema, ApiServer, Binding, CodeGenerator, Confidence, Discriminator, Effect, GeneratedArtifact, HttpBinding, HttpMethod, OAuthFlow, OperationPermission, Override, PageParameter, Pagination, RpcBinding, SchemaNode, SecurityRequirement, SecurityScheme, SourceInfo, SourceReference, } from "./model.js";
16
16
  export { identifier, kebab } from "./names.js";
@@ -10,7 +10,7 @@
10
10
  export { adaptDiscovery, readDiscovery, syncDiscovery, } from "./discovery.js";
11
11
  export { fakeApi, sampleOf, schemaProblems, } from "./fake.js";
12
12
  export { requestSchema } from "./json-schema.js";
13
- export { coverageGenerator, definitionsGenerator, manifestGenerator, } from "./manifest.js";
13
+ export { coverageGenerator, definitionsGenerator, examplesGenerator, manifestGenerator, } from "./manifest.js";
14
14
  export { mergeOpenApi } from "./merge.js";
15
15
  export { identifier, kebab } from "./names.js";
16
16
  export { adaptOpenApi, OpenApiError } from "./openapi.js";
@@ -40,6 +40,13 @@ export declare const definitionsGenerator: (options: {
40
40
  path: string;
41
41
  coreImport?: string;
42
42
  }) => CodeGenerator;
43
+ /**
44
+ * The spec's own sample answer of each operation that has one, for a fake to answer with. Its own file, so the manifest
45
+ * every CLI loads at start stays small; an answer that holds a credential keeps its sample in the spec.
46
+ */
47
+ export declare const examplesGenerator: (options: {
48
+ path: string;
49
+ }) => CodeGenerator;
43
50
  export interface CoverageOptions {
44
51
  path: string;
45
52
  title: string;
@@ -1,4 +1,5 @@
1
1
  import { kebab } from "./names.js";
2
+ import { isLossless } from "./runtime.js";
2
3
  import { SchemaTree } from "./tree.js";
3
4
  const withoutUndefined = (value) => Object.fromEntries(Object.entries(value).filter(([, field]) => field !== undefined));
4
5
  const toManifest = (operation, tree) => withoutUndefined({
@@ -62,6 +63,56 @@ export const definitionsGenerator = (options) => (model) => {
62
63
  },
63
64
  ];
64
65
  };
66
+ /** A lossless parser's number → a plain one; an integer a double would round stays its exact text. */
67
+ const plain = (value) => {
68
+ if (isLossless(value))
69
+ return /^-?\d+$/.test(value.value) && !Number.isSafeInteger(Number(value.value)) ? value.value : Number(value.value);
70
+ if (Array.isArray(value))
71
+ return value.map(plain);
72
+ if (value === null || typeof value !== "object")
73
+ return value;
74
+ return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, plain(inner)]));
75
+ };
76
+ /** Whether a credential sits anywhere in the answer, behind references too. */
77
+ const holdsSecret = (node, tree, seen = new Set()) => {
78
+ if (!node)
79
+ return false;
80
+ if (node.sensitive)
81
+ return true;
82
+ switch (node.type) {
83
+ case "ref": {
84
+ if (seen.has(node.ref))
85
+ return false;
86
+ seen.add(node.ref);
87
+ return holdsSecret(tree.schema(node.ref).schema, tree, seen);
88
+ }
89
+ case "array":
90
+ return holdsSecret(node.items, tree, seen);
91
+ case "object":
92
+ return [...Object.values(node.properties), node.additionalProperties].some((inner) => holdsSecret(inner, tree, seen));
93
+ case "union":
94
+ case "allOf":
95
+ return node.of.some((inner) => holdsSecret(inner, tree, seen));
96
+ default:
97
+ return false;
98
+ }
99
+ };
100
+ /**
101
+ * The spec's own sample answer of each operation that has one, for a fake to answer with. Its own file, so the manifest
102
+ * every CLI loads at start stays small; an answer that holds a credential keeps its sample in the spec.
103
+ */
104
+ export const examplesGenerator = (options) => (model) => {
105
+ const tree = new SchemaTree(model);
106
+ const examples = Object.fromEntries(model.operations.flatMap((operation) => operation.response?.example === undefined || holdsSecret(operation.response.schema, tree)
107
+ ? []
108
+ : [[operation.id, plain(operation.response.example)]]));
109
+ return [
110
+ {
111
+ path: options.path,
112
+ content: `export const examples: Readonly<Record<string, unknown>> = ${JSON.stringify(examples, null, 2)}\n`,
113
+ },
114
+ ];
115
+ };
65
116
  const cell = (text) => (text ?? "").replace(/\s+/g, " ").replace(/\|/g, "\\|").trim();
66
117
  /** Every operation the source has, and how it is reached — the page a reviewer diffs after a sync. */
67
118
  export const coverageGenerator = (options) => (model) => {
@@ -75,6 +75,30 @@ const JSON_VARIANT = /^application\/([\w.-]+\+)?json\s*(;|$)/i;
75
75
  const jsonContent = (content) => content[JSON_TYPE] ?? Object.entries(content).find(([type]) => JSON_VARIANT.test(type))?.[1];
76
76
  const SCHEME_TYPES = new Set(["apiKey", "http", "oauth2", "openIdConnect", "mutualTLS"]);
77
77
  const FLOWS = ["implicit", "password", "clientCredentials", "authorizationCode"];
78
+ /** A spec without a single operationId (Attio's) still has calls: `get /v2/objects/{object}` → `getV2ObjectsByObject`. */
79
+ const derivedId = (method, path) => method +
80
+ path
81
+ .split("/")
82
+ .filter(Boolean)
83
+ .map((segment) => {
84
+ const words = segment
85
+ .replace(/^\{|\}$/g, "")
86
+ .split(/[^A-Za-z0-9]+/)
87
+ .filter(Boolean);
88
+ const pascal = words.map((word) => (word[0] ?? "").toUpperCase() + word.slice(1)).join("");
89
+ return segment.startsWith("{") ? `By${pascal}` : pascal;
90
+ })
91
+ .join("");
92
+ /** A sample answer bigger than this stays in the spec: the manifest ships inside every CLI. */
93
+ const LARGEST_EXAMPLE = 8 * 1024;
94
+ const exampleOf = (media) => {
95
+ const examples = isObject(media.examples) ? Object.values(media.examples) : [];
96
+ const first = examples.find((one) => isObject(one) && one.value !== undefined);
97
+ const example = "example" in media ? media.example : first?.value;
98
+ if (example === undefined)
99
+ return undefined;
100
+ return JSON.stringify(example).length <= LARGEST_EXAMPLE ? example : undefined;
101
+ };
78
102
  const strings = (source, keys) => Object.fromEntries(keys.flatMap((key) => (typeof source[key] === "string" ? [[key, source[key]]] : [])));
79
103
  /** `{type: "null"}` or `type: ["null"]`: JSON Schema 2020-12's own way to say "only null". */
80
104
  const isNullOnly = (source) => isObject(source) &&
@@ -463,8 +487,15 @@ class Adapter {
463
487
  .sort()) {
464
488
  const answer = responses[code];
465
489
  const json = isObject(answer) && isObject(answer.content) ? jsonContent(answer.content) : undefined;
466
- if (isObject(json) && json.schema !== undefined)
467
- return this.schema(json.schema, `${where}.responses.${code}`);
490
+ if (!isObject(json) || json.schema === undefined)
491
+ continue;
492
+ const example = exampleOf(json);
493
+ return {
494
+ confidence: "contract",
495
+ required: true,
496
+ schema: this.schema(json.schema, `${where}.responses.${code}`),
497
+ ...(example === undefined ? {} : { example }),
498
+ };
468
499
  }
469
500
  return undefined;
470
501
  }
@@ -539,6 +570,11 @@ class Adapter {
539
570
  operations() {
540
571
  const operations = [];
541
572
  const paths = isObject(this.document.paths) ? this.document.paths : {};
573
+ const named = Object.values(paths).some((item) => isObject(item) &&
574
+ METHODS.some((method) => {
575
+ const operation = item[method];
576
+ return isObject(operation) && typeof operation.operationId === "string";
577
+ }));
542
578
  for (const [path, item] of Object.entries(paths)) {
543
579
  if (!isObject(item))
544
580
  continue;
@@ -549,8 +585,9 @@ class Adapter {
549
585
  continue;
550
586
  const pointer = `#/paths/${path.replaceAll("~", "~0").replaceAll("/", "~1")}/${method}`;
551
587
  // A path without an id is a description, not a call: Meta models its webhook payload this way.
552
- if (typeof source.operationId !== "string")
588
+ if (named && typeof source.operationId !== "string")
553
589
  continue;
590
+ const id = typeof source.operationId === "string" ? source.operationId : derivedId(method, path);
554
591
  const verb = method.toUpperCase();
555
592
  const own = (Array.isArray(source.parameters) ? source.parameters : [])
556
593
  .map((parameter, index) => this.#parameter(parameter, `${pointer}.parameters[${index}]`))
@@ -564,7 +601,7 @@ class Adapter {
564
601
  this.problems.push(`${pointer}: path parameter "${name}" is not declared`);
565
602
  }
566
603
  const operation = {
567
- id: source.operationId,
604
+ id,
568
605
  binding: { kind: "http", method: verb, path },
569
606
  tags: Array.isArray(source.tags) ? source.tags.map(String) : [],
570
607
  parameters,
@@ -584,7 +621,7 @@ class Adapter {
584
621
  operation.requestBody = this.#requestBody(source.requestBody, pointer);
585
622
  const response = this.#response(source, pointer);
586
623
  if (response)
587
- operation.response = { confidence: "contract", required: true, schema: response };
624
+ operation.response = response;
588
625
  operations.push(operation);
589
626
  }
590
627
  }
@@ -10,6 +10,7 @@ interface LosslessLike {
10
10
  isLosslessNumber: true;
11
11
  value: string;
12
12
  }
13
+ export declare const isLossless: (input: unknown) => input is LosslessLike;
13
14
  interface Range {
14
15
  minimum?: number;
15
16
  maximum?: number;
@@ -6,7 +6,7 @@
6
6
  * `LosslessNumber`), because a 64-bit id read as a JS number is silently a different id.
7
7
  */
8
8
  import * as v from "valibot";
9
- const isLossless = (input) => typeof input === "object" &&
9
+ export const isLossless = (input) => typeof input === "object" &&
10
10
  input !== null &&
11
11
  input.isLosslessNumber === true &&
12
12
  typeof input.value === "string";
@@ -1,4 +1,5 @@
1
1
  import { identifier } from "./names.js";
2
+ import { CodegenError } from "./pipeline.js";
2
3
  import { SchemaTree } from "./tree.js";
3
4
  const doc = (text, indent) => {
4
5
  const line = text?.replace(/\s+/g, " ").replace(/\*\//g, "*\\/").trim();
@@ -76,5 +77,10 @@ export const typesGenerator = (options) => (model) => {
76
77
  const type = union ?? writer.node(schema.schema, schema.id, tree.literalFor(schema.id));
77
78
  return `${doc(schema.schema.description, "")}export type ${name} = ${type}\n`;
78
79
  });
80
+ // The answer of each operation by its id, so a config's paths into an answer are checked in the editor.
81
+ const responses = model.operations.map((operation) => ` ${key(operation.id)}: ${tree.responseName(operation.id) ?? "unknown"}`);
82
+ if (tree.named.some(({ name }) => name === "Responses"))
83
+ throw new CodegenError(["a schema named Responses collides with the generated map of answers"]);
84
+ declarations.push(`/** What each operation answers, by its id. */\nexport interface Responses {\n${responses.join("\n")}\n}\n`);
79
85
  return [{ path: options.path, content: declarations.join("\n") }];
80
86
  };
@@ -40,7 +40,7 @@ the four steps that need a person. A new CLI is ready for its first release when
40
40
  | [Data model](data-model.md) | `DATA` | 9 | Core entities, entities and source records, `external_id`, field names, links and duplicates, files, calendar entries |
41
41
  | [Testing](testing.md) | `TEST` | 19 | Sandbox, no network, no real waits, one test time limit, leak tests, coverage, contracts, test matrix, parity, fakes as strict as the service |
42
42
  | [Security](security.md) | `SECR` | 24 | Secrets, logs, keyring, argv, error text, untrusted text, scanners, workflow hardening, reporting, OAuth sign-in and which app it uses, meeting secrets, keyring in moved-folder runs |
43
- | [Documents](docs.md) | `DOC` | 22 | User pages and developer pages, generated pages, current facts, changelog, repository page |
43
+ | [Documents](docs.md) | `DOC` | 23 | User pages and developer pages, generated pages, current facts, changelog, repository page |
44
44
  | [Comparisons](comparisons.md) | `CMP` | 11 | Which tools a comparison page lists, rows as user tasks, agents and safety, where others are better, proof of marks |
45
45
  | [Releases](releases.md) | `REL` | 16 | `bin/release`, the release lock, versions, the owner's yes, trusted publishing |
46
46
  | [CI](ci.md) | `CI` | 13 | Hooks, the pull request budget, full validation, monthly runs, conflict markers |
@@ -72,12 +72,14 @@ Rule ids on this page are `WC-DOC-<n>`. How to read a rule, how ids work and whi
72
72
 
73
73
  ### WC-DOC-7 · `README.md` is the full introduction to the tool
74
74
 
75
- - **Why:** most readers open only the README; it must take them from "what is this" to a first result.
75
+ - **Why:** most readers open only the README, and it must take them from "what is this" to a first result. A reader
76
+ decides whether to install from what the tool does for them, so the gains and the "why" come before the steps.
76
77
  - **Enforced by:** review only.
77
- - **Example:** follow max-cli's README order: quick start, what you can do, for AI agents, why this tool, the main
78
- features, sign-in and profiles, settings and permissions, limits, security, when it does not work, documentation,
79
- development.
80
- - **Exceptions:** none.
78
+ - **Example:** follow tg-cli's README order: the hero line with what the reader gets, three bold gains, what you get
79
+ (with an invented conversation), why this tool and a one-line link to the comparison, quick start, use it with your
80
+ agent, what it can do, how it works, settings and permissions, security, when something goes wrong,
81
+ documentation, development. The install command stays within the first two screens.
82
+ - **Exceptions:** a library or a kit follows WC-DOC-23 instead.
81
83
  - **Applies to:** all CLIs. **Since:** cli-base 0.41.0. **Rulings:** NEED-500.
82
84
 
83
85
  ### WC-DOC-8 · A user guide follows the portal's authoring and terminology rules
@@ -235,7 +237,8 @@ Rule ids on this page are `WC-DOC-<n>`. How to read a rule, how ids work and whi
235
237
  unfinished next to the others, and one without topics is not found in GitHub search.
236
238
  - **Enforced by:** review only.
237
239
  - **Example:** `docs/images/social-preview.png` is 1280×640 in the shared style: the command name in the
238
- cyan-violet-magenta gradient, a one-line tagline and the "part of WireCat · wirecat.dev" footer. `README.md` opens
240
+ cyan-violet-magenta gradient, a one-line tagline and the "part of WireCat · wirecat.dev" footer. Copy cli-base's
241
+ `docs/images/src/banner.html`, change its text, and render it with `pnpm docs:images`. `README.md` opens
239
242
  with it through an absolute `raw.githubusercontent.com` URL, so it also renders on npmjs.com, with the tagline as
240
243
  its alt text. The same file is the repository's social preview (Settings → Social preview; GitHub has no API for
241
244
  it). The homepage is the tool's wirecat.dev docs page, and the topics name the service, `cli`, `ai-agents`, `mcp`
@@ -263,6 +266,19 @@ An agent that opens the skill carries SKILL.md in every later turn of its sessio
263
266
  - **Exceptions:** a SKILL.md under the limit needs no references.
264
267
  - **Applies to:** every CLI that ships an agent skill. **Since:** cli-base 0.106.0. **Rulings:** none.
265
268
 
269
+ ### WC-DOC-23 · A library's or a kit's README opens with what you build, a proof and who builds on it
270
+
271
+ - **Why:** a developer decides in one screen whether a library fits their stack. A table of documents or a rename
272
+ history in that screen tells them nothing about what they would build.
273
+ - **Enforced by:** review only.
274
+ - **Example:** cli-base's README, in this order: the banner, one sentence that names what you build with it and on
275
+ which stack, one proof right below it (a short code sample with its real output in comments, or a GIF), "Built on
276
+ it" with two or three linked consumers and a count, install, the links row and badges, then the features as gains
277
+ with one checked number each. The "Key documents" table and the rename history go at the end.
278
+ - **Exceptions:** none.
279
+ - **Applies to:** cli-base, cli-core, cli-template and every other WireCat library or kit. **Since:** cli-base
280
+ 0.111.0. **Rulings:** none.
281
+
266
282
  ## Sources
267
283
 
268
284
  These documents explain the rules on this page in more detail. Where one of them disagrees with this page, this page
@@ -236,7 +236,9 @@ still compared with every file; a line from before cli-base 0.80.8 has no `<tree
236
236
  `chore(release): 0.4.0` without `## Conformance` fails `release-pr.yml`. `bin/release` writes the section into
237
237
  the pull request it opens to raise a taken number, since only the number changes.
238
238
  - **Exceptions:** cli-template's own release has no service to check; its `bin/release` skips the live check where
239
- `kit/` exists, a folder `new` never copies.
239
+ `kit/` exists, a folder `new` never copies. A CLI made outside WireCat with `new --preset generic` has
240
+ `"preset": "generic"` in its `template.json`, and its `bin/release` and `release-start.yml` skip the live check: its
241
+ owner decides how to check the real service. A CLI under `@wirecat` cannot be made with that preset.
240
242
  - **Applies to:** every CLI made from cli-template 0.17.0 or later. **Since:** cli-base 0.80.3. **Rulings:** none.
241
243
 
242
244
  ## Sources
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-base",
3
- "version": "0.110.0",
3
+ "version": "0.111.0",
4
4
  "description": "The parts every command line tool needs: output modes, terminal rendering, error model, exit codes, credentials, clocks",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",
@@ -125,6 +125,7 @@
125
125
  "secrets:scan": "gitleaks git --no-banner --redact .",
126
126
  "prepublishOnly": "pnpm build",
127
127
  "standards:check": "node config/wirecat/check.mjs",
128
+ "docs:images": "node docs/images/src/render.ts",
128
129
  "docs:lint": "markdownlint-cli2",
129
130
  "docs:spell": "cspell lint --config cspell.json --no-progress README.md \"docs/standards/**/*.md\"",
130
131
  "ci:quick": "pnpm typecheck"