@wirecat/cli-base 0.110.0 → 0.112.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,70 @@ 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.112.0 — 17.11.2026
12
+
13
+ ### Added
14
+
15
+ - **`adaptOpenApi` reads an OpenAPI 3.1 field of several types.** `type: [string, number, "null"]`, as Resend's file
16
+ types its contact properties, becomes a union of one schema per type, nullable when the list holds `null`; each
17
+ member keeps the `enum` values and constraints that fit its type. Such a field stopped generation before. The types,
18
+ the Valibot schemas and `fakeApi` check it as any other union.
19
+ - **`adaptOpenApi` reads an upload sent as bytes.** A body with no JSON, multipart or form type whose schema is a binary
20
+ string (or none), as Petstore 3's `application/octet-stream` image upload, keeps its content type and no schema;
21
+ the manifest's `request.contentType` says how it travels. It stopped generation before. cli-core sends it from
22
+ `--body-file`.
23
+ - **`signInRequirements` and `signInPlace` say which sign-in a call needs and where the token goes.** The
24
+ requirements are the operation's own `security`, else the document's; a call whose requirements are absent or only
25
+ `{}` needs none. cli-core's `api` group signs by them and `fakeApi` checks by them, so a CLI's test and its real
26
+ calls follow one rule.
27
+ - **`fakeApi` checks the document's sign-in and each operation's own scheme.** `security` gives it the manifest's
28
+ default requirements, which an operation's own `security` (`[]` included) replaces; with `auth`, a call the
29
+ document leaves open no longer needs the header. `token` with `securitySchemes` checks each call by its own
30
+ schemes: `Bearer <token>`, an `api_key` header, or a key in the query, and none for an open call. A CLI's test
31
+ then drops the copy of the document's `security` onto each operation. An upload's bytes are taken as sent, under
32
+ the operation's content type.
33
+ - **`adaptOpenApi` reads three more shapes found in public specs.** An `allOf` member that holds only a description,
34
+ as Resend writes one beside a reference, now describes the field instead of stopping generation. A schema with only
35
+ `nullable: true`, as GitHub's file has, is a nullable "anything". An integer marked `unix-time` (Stripe) or
36
+ `unixtime` (OpenAI) is a plain integer; any other unknown integer format still stops generation. An `anyOf` or
37
+ `oneOf` whose members only add `required` fields to the object they sit on, as Resend's "give at least one of",
38
+ becomes a union of that whole object, once with each; before, each member was an empty object no body matched.
39
+ - **`adaptDiscovery` carries a Discovery document's OAuth.** A document with `auth.oauth2` gives the model an `oauth2`
40
+ scheme with its scopes, and each of its methods `security: [{ oauth2: <its scopes> }]`. Before, the manifest named
41
+ no sign-in, and cli-core sent the token only because a manifest without schemes got a bearer header.
42
+
43
+ ### Fixed
44
+
45
+ - **`fakeApi` answers a string schema with JSON text.** A sample answer of type string, as Petstore's `loginUser`, was
46
+ sent unquoted, as a file is, so the CLI could not read it. A string an answer in `answers` gives is still sent as it
47
+ is.
48
+ - **`sampleOf` gives a value the generated schemas accept for a simple `pattern` and a binary string.** A pattern of
49
+ literals, classes and counts, as Resend's `^#[0-9A-Fa-f]{6}$`, gets a matching string (`#000000`); a binary
50
+ string gets `attach://xxxxxx`, which the Valibot schema asks for. Before, a CLI's generated test sent a sample its
51
+ own check refused.
52
+
53
+ ## 0.111.0 — 17.11.2026
54
+
55
+ ### Added
56
+
57
+ - **Codegen writes what each operation answers.** `typesGenerator` adds `Responses`, a map from operation id to its
58
+ answer type, so a config-built CLI's paths into an answer are checked in the editor. A new `examplesGenerator` writes
59
+ the spec's own sample answers (each under 8 KB, none from an answer that holds a credential) to their own file, for a
60
+ fake to answer with. A schema named `Responses` now stops generation, since it would collide. After the bump, run
61
+ `pnpm generate`: each generated `types.ts` gains `Responses`, so `--check` calls it stale until then.
62
+ - **A spec that names no operation still generates.** Attio's OpenAPI file has no `operationId` at all, so it gave an
63
+ empty catalog. Now each call gets an id from its method and path (`GET /v2/objects/{object}` →
64
+ `getV2ObjectsByObject`). A spec that names some operations still skips the paths without one, as before.
65
+ - **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)
66
+ now asks for tg-cli's order: what you get and why this tool before the quick start. A
67
+ [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)
68
+ gives libraries and kits their own order: a hero line, a proof, "Built on it", install, the links, and the
69
+ documents table at the end. Both are checked in review, so no CLI fails a check. A README in max-cli's order
70
+ (quick start first) is now out of step and moves at its next rewrite.
71
+ - **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)
72
+ now names its exception for a CLI made outside WireCat with cli-template's `new --preset generic`: its
73
+ `bin/release` needs no recorded live check. WireCat's own CLIs keep the gate.
74
+
11
75
  ## 0.110.0 — 17.11.2026
12
76
 
13
77
  ### 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).
@@ -66,6 +66,9 @@ export const adaptDiscovery = (documents, options = {}) => {
66
66
  const operations = [];
67
67
  const metadata = { scopes: {}, omissions: [] };
68
68
  const services = {};
69
+ // A document's `auth.oauth2` is Google's OAuth 2.0, the one sign-in its methods take.
70
+ const scopes = {};
71
+ let signsIn = false;
69
72
  const fail = (problem) => {
70
73
  throw new CodegenError([problem]);
71
74
  };
@@ -153,6 +156,11 @@ export const adaptDiscovery = (documents, options = {}) => {
153
156
  if (typeof document.rootUrl !== "string" || typeof document.servicePath !== "string")
154
157
  fail(`invalid Discovery document: ${service} has no rootUrl or servicePath`);
155
158
  services[service] = { rootUrl: String(document.rootUrl), servicePath: String(document.servicePath) };
159
+ const oauth2 = object(document.auth) && object(document.auth.oauth2) ? document.auth.oauth2 : undefined;
160
+ if (oauth2)
161
+ signsIn = true;
162
+ for (const [scope, value] of Object.entries(oauth2 && object(oauth2.scopes) ? oauth2.scopes : {}))
163
+ scopes[scope] = object(value) && typeof value.description === "string" ? value.description : "";
156
164
  for (const [id, value] of Object.entries(document.schemas))
157
165
  schemas.push({ id: `${service}_${id}`, schema: node(value, service, `/schemas/${id}`) });
158
166
  const walk = (resources, path) => {
@@ -198,6 +206,7 @@ export const adaptDiscovery = (documents, options = {}) => {
198
206
  };
199
207
  }),
200
208
  source: { location: `${service}${location}/methods/${name}` },
209
+ ...(oauth2 ? { security: [{ oauth2: metadata.scopes[raw.id] ?? [] }] } : {}),
201
210
  ...(raw.deprecated === true ? { deprecated: true } : {}),
202
211
  };
203
212
  if (object(raw.request))
@@ -234,6 +243,7 @@ export const adaptDiscovery = (documents, options = {}) => {
234
243
  },
235
244
  operations: operations.sort((a, b) => a.id.localeCompare(b.id)),
236
245
  schemas,
246
+ ...(signsIn ? { securitySchemes: { oauth2: { type: "oauth2", flows: { authorizationCode: { scopes } } } } } : {}),
237
247
  },
238
248
  metadata,
239
249
  services,
@@ -5,7 +5,7 @@
5
5
  * A name typed from memory then fails a test instead of reaching a real account.
6
6
  */
7
7
  import type { ManifestOperation } from "./manifest.js";
8
- import type { SchemaNode } from "./model.js";
8
+ import type { SchemaNode, SecurityRequirement, SecurityScheme } from "./model.js";
9
9
  export interface FakeCall {
10
10
  method: string;
11
11
  url: URL;
@@ -32,11 +32,24 @@ export interface FakeApiOptions {
32
32
  definitions: Readonly<Record<string, SchemaNode>>;
33
33
  /** The server the CLI calls: `https://cloud-api.yandex.net`. */
34
34
  baseUrl: string;
35
- /** The header and value every call to `baseUrl` must carry; omit for a service without sign-in. */
35
+ /**
36
+ * The header and value every call to `baseUrl` must carry, unless its `security` (its own, else the document's) is
37
+ * empty; omit for a service without sign-in. `token` instead checks each call by its schemes.
38
+ */
36
39
  auth?: {
37
40
  header: string;
38
41
  value: string;
39
42
  };
43
+ /**
44
+ * The token a call must carry where one of its security schemes puts it (`securitySchemes`): `Bearer <token>`, an
45
+ * `api_key` header, a key in the query. A call whose security, its own or else the document's, is absent or empty
46
+ * needs none, as cli-core's `api` group then sends none.
47
+ */
48
+ token?: string;
49
+ /** The document's default requirements, the manifest's `security`; an operation's own `security` replaces them. */
50
+ security?: readonly SecurityRequirement[];
51
+ /** The manifest's `securitySchemes`, which `token` is checked by. */
52
+ securitySchemes?: Readonly<Record<string, SecurityScheme>>;
40
53
  /** Answers by operation id. One without an answer gets a sample built from its response schema, with status 200. */
41
54
  answers?: Readonly<Record<string, Answering>>;
42
55
  /**
@@ -1,4 +1,5 @@
1
1
  import { identifier } from "./names.js";
2
+ import { signInPlace, signInRequirements } from "./sign-in.js";
2
3
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
4
  const resolved = (node, definitions) => {
4
5
  let at = node;
@@ -129,6 +130,46 @@ export const schemaProblems = (value, node, definitions, where = "body", loose =
129
130
  }
130
131
  }
131
132
  };
133
+ /**
134
+ * A string a simple pattern accepts: anchors, literals, `[...]` classes, `\d`, `\w` and `{n}`, `{n,m}`, `+`, `*`, `?`.
135
+ * `undefined` for anything else, and for a sample the pattern still refuses.
136
+ */
137
+ const patternSample = (pattern) => {
138
+ const atoms = [];
139
+ let at = pattern.startsWith("^") ? 1 : 0;
140
+ const end = pattern.endsWith("$") && !pattern.endsWith("\\$") ? pattern.length - 1 : pattern.length;
141
+ while (at < end) {
142
+ const char = pattern[at];
143
+ let atom;
144
+ if (char === "[") {
145
+ const close = pattern.indexOf("]", at + 1);
146
+ if (close < 0 || pattern[at + 1] === "^")
147
+ return undefined;
148
+ atom = pattern[at + 1] === "\\" ? (pattern[at + 2] === "d" ? "0" : "x") : pattern[at + 1];
149
+ at = close + 1;
150
+ }
151
+ else if (char === "\\") {
152
+ const next = pattern[at + 1] ?? "";
153
+ atom = next === "d" ? "0" : next === "w" ? "x" : /[^a-zA-Z0-9]/.test(next) ? next : "";
154
+ if (!atom)
155
+ return undefined;
156
+ at += 2;
157
+ }
158
+ else if ("()|.".includes(char))
159
+ return undefined;
160
+ else {
161
+ atom = char;
162
+ at += 1;
163
+ }
164
+ const quantifier = /^(\{(\d+)(,\d*)?\}|\+|\*|\?)/.exec(pattern.slice(at, end));
165
+ const times = quantifier ? (quantifier[2] !== undefined ? Number(quantifier[2]) : quantifier[0] === "+" ? 1 : 0) : 1;
166
+ if (quantifier)
167
+ at += quantifier[0].length;
168
+ atoms.push(atom.repeat(times));
169
+ }
170
+ const sample = atoms.join("");
171
+ return regexOf(pattern)?.test(sample) ? sample : undefined;
172
+ };
132
173
  /** A value the schema accepts: the first enum value, the minimum, one array item, every object field. */
133
174
  export const sampleOf = (node, definitions, seen = new Set()) => {
134
175
  switch (node.type) {
@@ -143,8 +184,14 @@ export const sampleOf = (node, definitions, seen = new Set()) => {
143
184
  const parts = objectParts(node, definitions);
144
185
  return parts ? sampleOf({ type: "object", ...parts }, definitions, seen) : null;
145
186
  }
146
- case "string":
147
- return node.enum?.[0] ?? "x".repeat(Math.max(node.minLength ?? 6, 1)).slice(0, node.maxLength ?? 64);
187
+ case "string": {
188
+ if (node.enum?.[0] !== undefined)
189
+ return node.enum[0];
190
+ if (node.format === "binary")
191
+ return "attach://xxxxxx";
192
+ const plain = "x".repeat(Math.max(node.minLength ?? 6, 1)).slice(0, node.maxLength ?? 64);
193
+ return node.pattern === undefined ? plain : (patternSample(node.pattern) ?? plain);
194
+ }
148
195
  case "integer":
149
196
  case "number":
150
197
  return (node.type === "integer" ? node.enum?.[0] : undefined) ?? node.minimum ?? Math.min(1, node.maximum ?? 1);
@@ -199,6 +246,9 @@ const specificity = (template) => [
199
246
  -template.replace(/\{[^}]+\}/g, "").length,
200
247
  ];
201
248
  const JSON_BODY = /[/+]json\s*(;|$)/i;
249
+ const JSON_TYPE = { "content-type": "application/json" };
250
+ const FORM_BODY = /^(multipart\/form-data|application\/x-www-form-urlencoded)\s*(;|$)/i;
251
+ const mediaType = (type) => type?.split(";")[0]?.trim().toLowerCase();
202
252
  const hostAnswer = (hosts, host) => hosts?.[host] ??
203
253
  Object.entries(hosts ?? {}).find(([pattern]) => pattern.startsWith("*.") && host.endsWith(pattern.slice(1)) && host.length > pattern.length - 1)?.[1];
204
254
  const scalar = (raw, node) => {
@@ -221,6 +271,21 @@ export const fakeApi = (options) => {
221
271
  };
222
272
  const definitions = options.definitions;
223
273
  const problemsOf = (value, node, where) => schemaProblems(value, node, definitions, where, options.looseObjects);
274
+ const placesOf = (requirements) => {
275
+ const names = [...new Set(requirements.flatMap((one) => Object.keys(one)))];
276
+ const places = names.flatMap((name) => {
277
+ const scheme = options.securitySchemes?.[name];
278
+ const place = scheme && signInPlace(scheme);
279
+ return place ? [place] : [];
280
+ });
281
+ return { names, places };
282
+ };
283
+ const keyParameters = new Set(Object.values(options.securitySchemes ?? {}).flatMap((scheme) => {
284
+ const place = signInPlace(scheme);
285
+ return place?.in === "query" ? [place.name] : [];
286
+ }));
287
+ const carries = (request, url, place, token) => (place.in === "header" ? request.headers.get(place.name) : url.searchParams.get(place.name)) === place.value(token);
288
+ const leaks = (request, url, token) => [...request.headers.values()].some((value) => value.includes(token)) || url.search.includes(token);
224
289
  const fetch = async (input, init) => {
225
290
  const request = new Request(input, init);
226
291
  const url = new URL(request.url);
@@ -246,6 +311,8 @@ export const fakeApi = (options) => {
246
311
  return refuse(400, `${url.host} was called over ${url.protocol}`);
247
312
  if (options.auth && request.headers.has(options.auth.header))
248
313
  return refuse(400, `the ${options.auth.header} header was sent to ${url.host}, which is not the service`);
314
+ if (options.token !== undefined && leaks(request, url, options.token))
315
+ return refuse(400, `the token was sent to ${url.host}, which is not the service`);
249
316
  const { status = 200, body, headers } = await answer(call);
250
317
  return json(status, body, headers);
251
318
  }
@@ -264,13 +331,21 @@ export const fakeApi = (options) => {
264
331
  call.operation = operation.id;
265
332
  call.path = matchPath(operation.binding.path, path) ?? {};
266
333
  const where = `${operation.id}`;
267
- const open = operation.security?.length === 0;
334
+ const declaredSecurity = operation.security ?? options.security;
335
+ const open = declaredSecurity?.every((one) => Object.keys(one).length === 0) === true;
268
336
  if (options.auth && !open && request.headers.get(options.auth.header) !== options.auth.value)
269
337
  return refuse(401, `${where}: no ${options.auth.header} header with the expected sign-in`);
338
+ const requirements = signInRequirements(operation, options.security);
339
+ if (options.token !== undefined && requirements) {
340
+ const { names, places } = placesOf(requirements);
341
+ const token = options.token;
342
+ if (!places.some((place) => carries(request, url, place, token)))
343
+ return refuse(401, `${where}: no sign-in where its security names it (${names.join(" or ")})`);
344
+ }
270
345
  const problems = [];
271
346
  const declared = (location) => operation.parameters.filter((one) => one.in === location);
272
347
  for (const name of url.searchParams.keys())
273
- if (!declared("query").some((one) => one.name === name))
348
+ if (!declared("query").some((one) => one.name === name) && !keyParameters.has(name))
274
349
  problems.push(`${where}: no query parameter "${name}"`);
275
350
  for (const parameter of [...declared("query"), ...declared("path")]) {
276
351
  const values = parameter.in === "query" ? url.searchParams.getAll(parameter.name) : [call.path[parameter.name]];
@@ -292,6 +367,11 @@ export const fakeApi = (options) => {
292
367
  if (text !== "") {
293
368
  if (!operation.request)
294
369
  problems.push(`${where}: takes no body`);
370
+ else if (contentType && !JSON_BODY.test(contentType) && !FORM_BODY.test(contentType)) {
371
+ const sent = mediaType(request.headers.get("content-type"));
372
+ if (sent !== mediaType(contentType))
373
+ problems.push(`${where}: the body is sent as ${sent ?? "no content type"}, not ${contentType}`);
374
+ }
295
375
  else if (contentType && !JSON_BODY.test(contentType)) {
296
376
  try {
297
377
  const form = await new Response(bytes, { headers: request.headers }).formData();
@@ -326,8 +406,9 @@ export const fakeApi = (options) => {
326
406
  }
327
407
  const response = operation.response?.schema ? definitions[operation.response.schema] : undefined;
328
408
  const answering = options.answers?.[operation.id];
409
+ // A sample of a string answer is JSON text, never the bytes of a download.
329
410
  if (!answering)
330
- return json(200, response ? sampleOf(response, definitions) : undefined);
411
+ return json(200, response ? JSON.stringify(sampleOf(response, definitions)) : undefined, JSON_TYPE);
331
412
  const { status = 200, body, headers } = await answering(call);
332
413
  // A scenario that answers off the schema tests a service that does not exist.
333
414
  if (status >= 200 && status < 300 && response && body !== undefined) {
@@ -4,13 +4,14 @@
4
4
  * files with (`identifier`, `requestSchema`), and format-neutral: it parses no file format and
5
5
  * adds no runtime dependency. `adaptOpenApi` reads an OpenAPI document and `adaptDiscovery` Google Discovery
6
6
  * documents the consumer has parsed; `upgradeToOpenApi3` brings Swagger 1.2 and 2.0 to OpenAPI 3 through two optional
7
- * peer dependencies. `fakeApi` serves the generated manifest as a strict fake for a CLI's tests. An adapter from
7
+ * peer dependencies. `fakeApi` serves the generated manifest as a strict fake for a CLI's tests, and `signInRequirements` with
8
+ * `signInPlace` say which sign-in a call needs and where its token goes. An adapter from
8
9
  * Postman or anything else lives in the consumer.
9
10
  */
10
11
  export { adaptDiscovery, type DiscoveryMetadata, type DiscoveryOptions, type DiscoveryProvenance, type DiscoveryResult, type DiscoveryService, readDiscovery, type SyncDiscoveryOptions, syncDiscovery, } from "./discovery.js";
11
12
  export { type FakeAnswer, type FakeApi, type FakeApiOptions, type FakeCall, fakeApi, sampleOf, schemaProblems, } from "./fake.js";
12
13
  export { requestSchema } from "./json-schema.js";
13
- export { type CoverageOptions, coverageGenerator, definitionsGenerator, type ManifestOperation, manifestGenerator, } from "./manifest.js";
14
+ export { type CoverageOptions, coverageGenerator, definitionsGenerator, examplesGenerator, type ManifestOperation, manifestGenerator, } from "./manifest.js";
14
15
  export { type MergedSource, type MergeOptions, type MergeReport, mergeOpenApi, type SpecSource } from "./merge.js";
15
16
  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
17
  export { identifier, kebab } from "./names.js";
@@ -18,6 +19,7 @@ export { adaptOpenApi, OpenApiError } from "./openapi.js";
18
19
  export { detectPagination } from "./pagination.js";
19
20
  export { type PatchedSpec, type PatchSpecOptions, patchSpec, type SpecPatch } from "./patch.js";
20
21
  export { type AuthOverride, applyNames, applyOverrides, applyPagination, applyPermissionRule, CodegenError, type CommandNames, type GenerateOptions, generate, type PermissionRule, READING_POST_REASON, validateModel, type WriteOptions, writeArtifacts, } from "./pipeline.js";
22
+ export { type SignInPlace, signInPlace, signInRequirements } from "./sign-in.js";
21
23
  export { API_SKILL_GROUPS, API_SKILL_INDEX, type ApiSkillOptions, apiSkillFiles } from "./skill.js";
22
24
  export { upgradeToOpenApi3 } from "./swagger.js";
23
25
  export { typesGenerator } from "./typescript.js";
@@ -4,19 +4,21 @@
4
4
  * files with (`identifier`, `requestSchema`), and format-neutral: it parses no file format and
5
5
  * adds no runtime dependency. `adaptOpenApi` reads an OpenAPI document and `adaptDiscovery` Google Discovery
6
6
  * documents the consumer has parsed; `upgradeToOpenApi3` brings Swagger 1.2 and 2.0 to OpenAPI 3 through two optional
7
- * peer dependencies. `fakeApi` serves the generated manifest as a strict fake for a CLI's tests. An adapter from
7
+ * peer dependencies. `fakeApi` serves the generated manifest as a strict fake for a CLI's tests, and `signInRequirements` with
8
+ * `signInPlace` say which sign-in a call needs and where its token goes. An adapter from
8
9
  * Postman or anything else lives in the consumer.
9
10
  */
10
11
  export { adaptDiscovery, readDiscovery, syncDiscovery, } from "./discovery.js";
11
12
  export { fakeApi, sampleOf, schemaProblems, } from "./fake.js";
12
13
  export { requestSchema } from "./json-schema.js";
13
- export { coverageGenerator, definitionsGenerator, manifestGenerator, } from "./manifest.js";
14
+ export { coverageGenerator, definitionsGenerator, examplesGenerator, manifestGenerator, } from "./manifest.js";
14
15
  export { mergeOpenApi } from "./merge.js";
15
16
  export { identifier, kebab } from "./names.js";
16
17
  export { adaptOpenApi, OpenApiError } from "./openapi.js";
17
18
  export { detectPagination } from "./pagination.js";
18
19
  export { patchSpec } from "./patch.js";
19
20
  export { applyNames, applyOverrides, applyPagination, applyPermissionRule, CodegenError, generate, READING_POST_REASON, validateModel, writeArtifacts, } from "./pipeline.js";
21
+ export { signInPlace, signInRequirements } from "./sign-in.js";
20
22
  export { API_SKILL_GROUPS, API_SKILL_INDEX, apiSkillFiles } from "./skill.js";
21
23
  export { upgradeToOpenApi3 } from "./swagger.js";
22
24
  export { typesGenerator } from "./typescript.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) => {
@@ -32,6 +32,10 @@ const KNOWN = new Set([
32
32
  "$ref",
33
33
  "discriminator",
34
34
  ]);
35
+ /** Seconds since 1970 as Stripe (`unix-time`) and OpenAI (`unixtime`) mark them: a plain integer. */
36
+ const SECONDS = new Set(["unix-time", "unixtime"]);
37
+ /** What a type list's union keeps for itself instead of repeating it on each member. */
38
+ const TYPE_LIST_OWN = new Set(["description", "default", "deprecated", "nullable", "const", "enum", "title"]);
35
39
  const PRIMITIVE_CONSTRAINTS = ["pattern", "minLength", "maxLength", "minimum", "maximum", "enum"];
36
40
  /** What the HTTP client sets itself; as flags they would only invite a second, wrong value. */
37
41
  const TRANSPORT_HEADERS = new Set(["authorization", "user-agent", "content-type", "accept"]);
@@ -75,11 +79,42 @@ const JSON_VARIANT = /^application\/([\w.-]+\+)?json\s*(;|$)/i;
75
79
  const jsonContent = (content) => content[JSON_TYPE] ?? Object.entries(content).find(([type]) => JSON_VARIANT.test(type))?.[1];
76
80
  const SCHEME_TYPES = new Set(["apiKey", "http", "oauth2", "openIdConnect", "mutualTLS"]);
77
81
  const FLOWS = ["implicit", "password", "clientCredentials", "authorizationCode"];
82
+ /** A spec without a single operationId (Attio's) still has calls: `get /v2/objects/{object}` → `getV2ObjectsByObject`. */
83
+ const derivedId = (method, path) => method +
84
+ path
85
+ .split("/")
86
+ .filter(Boolean)
87
+ .map((segment) => {
88
+ const words = segment
89
+ .replace(/^\{|\}$/g, "")
90
+ .split(/[^A-Za-z0-9]+/)
91
+ .filter(Boolean);
92
+ const pascal = words.map((word) => (word[0] ?? "").toUpperCase() + word.slice(1)).join("");
93
+ return segment.startsWith("{") ? `By${pascal}` : pascal;
94
+ })
95
+ .join("");
96
+ /** A sample answer bigger than this stays in the spec: the manifest ships inside every CLI. */
97
+ const LARGEST_EXAMPLE = 8 * 1024;
98
+ const exampleOf = (media) => {
99
+ const examples = isObject(media.examples) ? Object.values(media.examples) : [];
100
+ const first = examples.find((one) => isObject(one) && one.value !== undefined);
101
+ const example = "example" in media ? media.example : first?.value;
102
+ if (example === undefined)
103
+ return undefined;
104
+ return JSON.stringify(example).length <= LARGEST_EXAMPLE ? example : undefined;
105
+ };
78
106
  const strings = (source, keys) => Object.fromEntries(keys.flatMap((key) => (typeof source[key] === "string" ? [[key, source[key]]] : [])));
79
107
  /** `{type: "null"}` or `type: ["null"]`: JSON Schema 2020-12's own way to say "only null". */
80
108
  const isNullOnly = (source) => isObject(source) &&
81
109
  (source.type === "null" ||
82
110
  (Array.isArray(source.type) && source.type.length > 0 && source.type.every((t) => t === "null")));
111
+ const fits = (value, type) => type === "integer"
112
+ ? Number.isInteger(value)
113
+ : type === "array"
114
+ ? Array.isArray(value)
115
+ : type === "object"
116
+ ? isObject(value)
117
+ : typeof value === type;
83
118
  const pick = (source, keys) => Object.fromEntries(keys.map((key) => [key, source[key]]));
84
119
  const typeOfConst = (value) => typeof value === "string"
85
120
  ? "string"
@@ -106,6 +141,13 @@ const typedFromExample = (schema) => {
106
141
  };
107
142
  return isObject(schema) && !marked(schema);
108
143
  };
144
+ const isRequiredOnly = (member) => isObject(member) && Array.isArray(member.required) && Object.keys(member).every((key) => key === "required");
145
+ const isNote = (member) => isObject(member) && Object.keys(member).every((keyword) => IGNORED.has(keyword) || keyword === "description");
146
+ /** A body schema that says "any bytes": none, `{}`, or a binary string, as 3.0 writes it or 3.1 does. */
147
+ const isBytes = (schema) => schema === undefined ||
148
+ (isObject(schema) &&
149
+ (Object.keys(schema).length === 0 ||
150
+ (schema.type === "string" && (schema.format === "binary" || schema.contentMediaType !== undefined))));
109
151
  class Adapter {
110
152
  problems = [];
111
153
  document;
@@ -149,15 +191,12 @@ class Adapter {
149
191
  return common;
150
192
  }
151
193
  /** OpenAPI 3.1 writes `nullable` as `type: [T, "null"]`. */
152
- #type(source, common, where) {
194
+ #type(source, common) {
153
195
  if (Array.isArray(source.type)) {
154
196
  const types = source.type.filter((type) => type !== "null");
155
197
  if (types.length !== source.type.length)
156
198
  common.nullable = true;
157
- if (types.length === 1)
158
- return types[0];
159
- this.problems.push(`${where}: a schema of several types ${JSON.stringify(source.type)}`);
160
- return null;
199
+ return types[0];
161
200
  }
162
201
  if (source.type !== undefined)
163
202
  return source.type;
@@ -201,9 +240,23 @@ class Adapter {
201
240
  if (keyword) {
202
241
  if (Array.isArray(source.type) && source.type.includes("null"))
203
242
  common.nullable = true;
204
- return this.#union(source[keyword], keyword, common, where);
243
+ const members = source[keyword];
244
+ // Resend's "give at least one of": members that only add required fields to the object they sit on.
245
+ if (isObject(source.properties) && members.every(isRequiredOnly)) {
246
+ const { [keyword]: _, ...object } = source;
247
+ const required = Array.isArray(source.required) ? source.required : [];
248
+ const whole = members.map((member) => ({
249
+ ...object,
250
+ required: [...required, ...member.required],
251
+ }));
252
+ return this.#union(whole, keyword, common, where);
253
+ }
254
+ return this.#union(members, keyword, common, where);
205
255
  }
206
- const type = this.#type(source, common, where);
256
+ const types = Array.isArray(source.type) ? source.type.filter((type) => type !== "null") : [];
257
+ if (types.length > 1)
258
+ return this.#typeList(source, types, common, where);
259
+ const type = this.#type(source, common);
207
260
  const values = source.const !== undefined ? [source.const] : Array.isArray(source.enum) ? source.enum : undefined;
208
261
  switch (type) {
209
262
  case "string": {
@@ -224,7 +277,7 @@ class Adapter {
224
277
  const node = { ...common, type: "integer" };
225
278
  if (source.format === "int32" || source.format === "int64")
226
279
  node.format = source.format;
227
- else if (source.format !== undefined)
280
+ else if (source.format !== undefined && !SECONDS.has(String(source.format)))
228
281
  this.problems.push(`${where}: unsupported integer format "${source.format}"`);
229
282
  if (typeof source.minimum === "number")
230
283
  node.minimum = source.minimum;
@@ -265,7 +318,7 @@ class Adapter {
265
318
  case null:
266
319
  return { type: "unknown" };
267
320
  case undefined:
268
- if (Object.keys(source).every((keyword) => IGNORED.has(keyword) || keyword === "description")) {
321
+ if (Object.keys(source).every((keyword) => IGNORED.has(keyword) || keyword === "description" || keyword === "nullable")) {
269
322
  return { ...common, type: "unknown" };
270
323
  }
271
324
  this.problems.push(`${where}: a schema with no type`);
@@ -275,6 +328,23 @@ class Adapter {
275
328
  return { type: "unknown" };
276
329
  }
277
330
  }
331
+ /**
332
+ * OpenAPI 3.1's `type: [string, number, "null"]`: a union of one schema per type, each keeping the constraints and
333
+ * enum values that fit it; a type no enum value fits is left out.
334
+ */
335
+ #typeList(source, types, common, where) {
336
+ if (source.type.includes("null"))
337
+ common.nullable = true;
338
+ const values = source.const !== undefined ? [source.const] : Array.isArray(source.enum) ? source.enum : undefined;
339
+ const rest = Object.fromEntries(Object.entries(source).filter(([key]) => !TYPE_LIST_OWN.has(key)));
340
+ const of = types.flatMap((type) => {
341
+ const fitting = values?.filter((value) => fits(value, type));
342
+ if (fitting?.length === 0)
343
+ return [];
344
+ return [this.schema({ ...rest, type, ...(fitting ? { enum: fitting } : {}) }, where)];
345
+ });
346
+ return { ...common, type: "union", of };
347
+ }
278
348
  #object(source, common, where) {
279
349
  const properties = {};
280
350
  for (const [name, property] of Object.entries(isObject(source.properties) ? source.properties : {})) {
@@ -356,6 +426,14 @@ class Adapter {
356
426
  }
357
427
  }
358
428
  #allOf(source, members, common, where) {
429
+ // A member with only a description, as Resend writes one beside a reference, describes the field and adds nothing.
430
+ const notes = members.filter(isNote);
431
+ if (notes.length > 0 && notes.length < members.length) {
432
+ const [note] = notes.flatMap((one) => typeof one.description === "string" && one.description.trim() ? [one] : []);
433
+ if (note && !common.description)
434
+ common.description = note.description;
435
+ return this.#allOf(source, members.filter((one) => !isNote(one)), common, where);
436
+ }
359
437
  const distributed = this.#distribute(members, common, where);
360
438
  if (distributed)
361
439
  return distributed;
@@ -424,7 +502,7 @@ class Adapter {
424
502
  }
425
503
  /**
426
504
  * JSON when offered, unless a multipart body carries a file, which JSON cannot; then multipart,
427
- * then a form. A content type outside these three refuses the operation.
505
+ * then a form, then bytes (a type whose schema is a binary string). Anything else refuses the operation.
428
506
  */
429
507
  #requestBody(source, where) {
430
508
  const content = isObject(source.content) ? source.content : {};
@@ -436,8 +514,12 @@ class Adapter {
436
514
  const body = { confidence: "contract", required: source.required === true };
437
515
  if (offered.length === 0)
438
516
  return body;
517
+ // An upload sent as the bytes themselves: `application/octet-stream`, an image type.
518
+ const raw = type ? undefined : offered.find((candidate) => isBytes(schemaOf(candidate)));
519
+ if (raw)
520
+ return { ...body, contentType: raw };
439
521
  if (!type) {
440
- this.problems.push(`${where}: a body must be JSON, multipart or a form, found ${offered.join(", ")}`);
522
+ this.problems.push(`${where}: a body must be JSON, multipart, a form or bytes, found ${offered.join(", ")}`);
441
523
  return body;
442
524
  }
443
525
  // Only a charset may be dropped: `application/merge-patch+json` must travel as itself.
@@ -463,8 +545,15 @@ class Adapter {
463
545
  .sort()) {
464
546
  const answer = responses[code];
465
547
  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}`);
548
+ if (!isObject(json) || json.schema === undefined)
549
+ continue;
550
+ const example = exampleOf(json);
551
+ return {
552
+ confidence: "contract",
553
+ required: true,
554
+ schema: this.schema(json.schema, `${where}.responses.${code}`),
555
+ ...(example === undefined ? {} : { example }),
556
+ };
468
557
  }
469
558
  return undefined;
470
559
  }
@@ -539,6 +628,11 @@ class Adapter {
539
628
  operations() {
540
629
  const operations = [];
541
630
  const paths = isObject(this.document.paths) ? this.document.paths : {};
631
+ const named = Object.values(paths).some((item) => isObject(item) &&
632
+ METHODS.some((method) => {
633
+ const operation = item[method];
634
+ return isObject(operation) && typeof operation.operationId === "string";
635
+ }));
542
636
  for (const [path, item] of Object.entries(paths)) {
543
637
  if (!isObject(item))
544
638
  continue;
@@ -549,8 +643,9 @@ class Adapter {
549
643
  continue;
550
644
  const pointer = `#/paths/${path.replaceAll("~", "~0").replaceAll("/", "~1")}/${method}`;
551
645
  // A path without an id is a description, not a call: Meta models its webhook payload this way.
552
- if (typeof source.operationId !== "string")
646
+ if (named && typeof source.operationId !== "string")
553
647
  continue;
648
+ const id = typeof source.operationId === "string" ? source.operationId : derivedId(method, path);
554
649
  const verb = method.toUpperCase();
555
650
  const own = (Array.isArray(source.parameters) ? source.parameters : [])
556
651
  .map((parameter, index) => this.#parameter(parameter, `${pointer}.parameters[${index}]`))
@@ -564,7 +659,7 @@ class Adapter {
564
659
  this.problems.push(`${pointer}: path parameter "${name}" is not declared`);
565
660
  }
566
661
  const operation = {
567
- id: source.operationId,
662
+ id,
568
663
  binding: { kind: "http", method: verb, path },
569
664
  tags: Array.isArray(source.tags) ? source.tags.map(String) : [],
570
665
  parameters,
@@ -584,7 +679,7 @@ class Adapter {
584
679
  operation.requestBody = this.#requestBody(source.requestBody, pointer);
585
680
  const response = this.#response(source, pointer);
586
681
  if (response)
587
- operation.response = { confidence: "contract", required: true, schema: response };
682
+ operation.response = response;
588
683
  operations.push(operation);
589
684
  }
590
685
  }
@@ -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";
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Which sign-in one call of a generated manifest needs and where its token goes. cli-core's `api` group signs requests
3
+ * by this and `fakeApi` checks them by it, so a CLI's test and its real calls cannot disagree.
4
+ */
5
+ import type { SecurityRequirement, SecurityScheme } from "./model.js";
6
+ /** Where one scheme carries a token, and what the header or query parameter then holds. */
7
+ export interface SignInPlace {
8
+ in: "header" | "query";
9
+ /** A header name in lower case, or a query parameter as the spec spells it. */
10
+ name: string;
11
+ value: (token: string) => string;
12
+ }
13
+ /** `undefined` for a scheme a token cannot be sent by: basic, digest, a key in a cookie, mutual TLS. */
14
+ export declare const signInPlace: (scheme: SecurityScheme) => SignInPlace | undefined;
15
+ /**
16
+ * The requirements one call signs in by: the operation's own `security`, else the document's. `undefined` when it needs
17
+ * no sign-in: neither says anything, as in a spec without security, or every requirement is `{}` (`security: []`
18
+ * included). An optional sign-in (`[{}, { oauth: [] }]`) still signs in.
19
+ */
20
+ export declare const signInRequirements: (operation: {
21
+ security?: readonly SecurityRequirement[];
22
+ }, document: readonly SecurityRequirement[] | undefined) => readonly SecurityRequirement[] | undefined;
@@ -0,0 +1,30 @@
1
+ const BEARER = { in: "header", name: "authorization", value: (token) => `Bearer ${token}` };
2
+ /** `undefined` for a scheme a token cannot be sent by: basic, digest, a key in a cookie, mutual TLS. */
3
+ export const signInPlace = (scheme) => {
4
+ if (scheme.type === "apiKey") {
5
+ if (!scheme.name || (scheme.in !== "header" && scheme.in !== "query"))
6
+ return undefined;
7
+ return {
8
+ in: scheme.in,
9
+ name: scheme.in === "header" ? scheme.name.toLowerCase() : scheme.name,
10
+ value: (token) => token,
11
+ };
12
+ }
13
+ if (scheme.type === "http") {
14
+ if (!scheme.scheme || /^bearer$/i.test(scheme.scheme))
15
+ return BEARER;
16
+ if (/^(basic|digest)$/i.test(scheme.scheme))
17
+ return undefined;
18
+ return { in: "header", name: "authorization", value: (token) => `${scheme.scheme} ${token}` };
19
+ }
20
+ return scheme.type === "oauth2" || scheme.type === "openIdConnect" ? BEARER : undefined;
21
+ };
22
+ /**
23
+ * The requirements one call signs in by: the operation's own `security`, else the document's. `undefined` when it needs
24
+ * no sign-in: neither says anything, as in a spec without security, or every requirement is `{}` (`security: []`
25
+ * included). An optional sign-in (`[{}, { oauth: [] }]`) still signs in.
26
+ */
27
+ export const signInRequirements = (operation, document) => {
28
+ const requirements = operation.security ?? document;
29
+ return requirements?.some((one) => Object.keys(one).length > 0) ? requirements : undefined;
30
+ };
@@ -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
@@ -81,7 +81,7 @@ it changed, for the CLI's provenance.
81
81
 
82
82
  From the source the generator reads:
83
83
 
84
- - **Operations**: method and path, parameters, the request body (JSON, multipart or a form), and the first 2xx answer
84
+ - **Operations**: method and path, parameters, the request body (JSON, multipart, a form, or bytes for an upload), and the first 2xx answer
85
85
  with a JSON body (`200`, `201` as HubSpot creates, `202`, `207`, or `2XX`). `application/hal+json`,
86
86
  `application/json; charset=utf-8` and other JSON types count as JSON.
87
87
  - **Effect**: GET and HEAD read, POST, PUT and PATCH write, DELETE is destructive.
@@ -130,14 +130,17 @@ From the source the generator reads:
130
130
 
131
131
  ### A strict fake for tests
132
132
 
133
- `fakeApi({ operations, definitions, baseUrl, auth, answers, hosts })` serves the generated manifest and definitions as
134
- a `fetch` for a CLI's tests. It refuses, with a 4xx and a line in `refusals`, an unknown path or method, an unknown or
135
- mistyped query parameter (a repeated one is a list), a missing required one, a body field the schema lacks (JSON, a
136
- form or multipart), and a call without the `auth` header, unless the operation's `security` is `[]`. An operation
137
- answers a sample built from its response schema, or what `answers` gives for it, checked against that schema: an
138
- answer off the schema throws. A string, bytes or a stream is sent as it is, for a file. `hosts` answers the other
139
- hosts a link points at (`downloader.disk.yandex.ru`, `*.disk.yandex.net`), and refuses a call there over another
140
- scheme or with the `auth` header. A CLI writes only its scenarios. `looseObjects` lets unknown fields through, for a
133
+ `fakeApi({ operations, definitions, baseUrl, security, securitySchemes, token, answers, hosts })` serves the generated
134
+ manifest and definitions as a `fetch` for a CLI's tests. It refuses, with a 4xx and a line in `refusals`, an unknown
135
+ path or method, an unknown or mistyped query parameter (a repeated one is a list), a missing required one, a body field
136
+ the schema lacks (JSON, a form or multipart), an upload under another content type, and a call without its sign-in.
137
+ `token` is checked where the call's schemes put it (`Bearer <token>`, an `api_key` header, a key in the query), by
138
+ `signInRequirements`: the operation's own `security`, else the document's `security`, and none when neither names
139
+ one, as cli-core then sends none. The older `auth: { header, value }` is one header every call needs, unless its
140
+ `security` is empty. An operation answers a sample built from its response schema, as JSON, or what `answers` gives
141
+ for it, checked against that schema: an answer off the schema throws. A string, bytes or a stream an answer gives is
142
+ sent as it is, for a file. `hosts` answers the other hosts a link points at (`downloader.disk.yandex.ru`,
143
+ `*.disk.yandex.net`), and refuses a call there over another scheme or with the token. A CLI writes only its scenarios. `looseObjects` lets unknown fields through, for a
141
144
  source whose subtypes the definitions cannot tell apart.
142
145
 
143
146
  ### The API part of the agent skill
@@ -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.112.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"